March 24, 2017 | Author: Muhammad Zulhilmi Wak Jong | Category: N/A
Download Programming the PIC microcontroller in c.pdf...
Programmingthe PICMicrocontrollerwithMBasic
Programmingthe PICMicrocontrollerwithMBasic byJackR.Smith
AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO Newnes is an imprint of Elsevier
NewnesisanimprintofElsevier 30CorporateDrive,Suite400,Burlington,MA01803,USA 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
Contents 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
v
Contents 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 vi
Contents 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
vii
Contents 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
viii
Contents 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
ix
Preface MyintroductiontocomputerswasinthedaysofIBM’sModel29cardpunch.Youfirstcarefullyprinted yourFORTRANcodeonacodingsheet,thenpunchedacarddeckandfinallywalkedyourcardsoverto thecampuscomputercenter.There,oneofthehighacolytesoftheIBM360—inrealityagradstudent—acceptedthedeckwithafaintlookofdisdain.Youmightevencatchaglimpseofthecomputeritselfthrough theglasswallofthecomputercenter.Thefollowingday,ifyouwerefortunate,yourcarddeckwasreadyfor pick-up,wrappedinthegreenbarpaperoutputyourjobelicited.Ifyouwerereallylucky,theoutputmade senseandyoucouldgoontoyournexttask.Ifyouwerelessfortunate,theprintoutidentifiedyourerrors. And,ifyouwerereallyhavingabadday,yourcarddeckwashiddeninsideaninch-thickcoredumpprintout,densewithhexadecimalregisterandmemoryvalues. Today,wehaveasmuchcomputingpoweronourdesktopsaswasbehindtheglasswallwhenIwaspunchingcarddecks.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,electronicsquestionsaresprinkledliberallythroughouttheseforaaswell.
x
Preface I’vetriedtoaddressboththesoftwareandhardwareaspectsofworkingwithPICs,withmyimaginedreader havinganinterestinbothprogrammingandelectronics,butwithoutspecializedtraining.AlthoughI’vetried toerronthesideofinclusionoverbrevity,thisbookcan’treplaceabasicunderstandingofelectronics,nor anelementarygraspofhowonegoesaboutwritingBASICprograms.Itrustthatreadersexperiencedin electronicswillforgivethesimplificationsnecessitatedinthisendeavor,andthatexperiencedprogrammers understandthattheywillnotnecessarilyfindelegantalgorithmsorcodeineverycase.But,thisworkisnot intendedtoreplicateKnuth’sTheArtofComputerProgramming,norHorowitzandHill’sTheArtofElectronics.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.Somearetheunavoidablebyproductofsimplifyingcomplexsubjectsforanintroductorylevelpresentationandothersarejustplaindumbmistakes.Regardlessofthecategory,Iacceptfull responsibility.Imaybecontactedbye-mailat
[email protected]toreporterrorsoromissions.
JackSmith June2005,Clifton,VA
xi
Acknowledgments AcknowledgmentsareduetomywifeJanet,whohastoleratedwithgoodgracetheinnumerablehoursI’ve spentinthebasementworkshoporinfrontofthecomputerscreen.IalsowishtothankthepeopleatBasic Micro,includingNathanScherdin,andDaleKubin,fortheirassistanceinwritingthisbook.Ialsowishto thankLarryandJanetPhippsforthehospitalityshowntome.
xii
What’sontheCD-ROM? ThecontentoftheCD-ROMwasdevelopedwithWindows®XP,andhasbeenverifiedasreadablewith Windows®2000.Ithasnotbeentestedwithotheroperatingsystems. Itscontentsareorganizedinaseriesofdirectories:
MBasic876 BasicMicroInc.hasprovidedafreeMBasiccompiler,MBasic876,withallfeaturesofMBasicProfessional,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-featuredgeneral-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.
xiii
What’sontheCD-ROM? DataSheetsandApplicationNotes Datasheetsformanyofthetransistors,diodesandintegratedcircuitsusedinthisbook’scircuitsareprovidedinthedirectorydatasheetsandapplicationnotes.Inaddition,Ihaveincludedaselectionofrelevant applicationnotesandothermaterialfromkeysemiconductormanufacturers. Eachmanufacturer’sdatasheetsarecontainedinadirectorynamedafterthemanufacturer.
xiv
1
CHAPTER
PICs“101” WhatisaPIC®? PICsareinexpensiveone-chipcomputersdesignedandmanufacturedbyMicrochipTechnology,Inc. TheacronymoriginallystoodforProgrammableIntelligentComputer,butMicrochip’sofficialnamefor thesedevicesisnowPICmicro®microcontrollers.WewillcallthemPICs.In1977,GeneralInstruments, Microchip’spredecessor,developedtheoriginalPIC,thePIC1650.ThePIC1650canbethoughofasthe grandfatheroftoday’sPICs,anditsarchitecture,programmingapproachandotherfeaturesdirectlycorrespondtothosefoundinmodernPICs.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 thelogicalandarithmeticfunctionsofthePICfollowinginstructionsitreadsfromtheprogrammemory.It readsfromandwritestodatamemoryandtheinput/ outputmodule. • Programmemory:HoldsinstructionsfortheCPU.The CPUreadsprogrammemorybutisphysicallyprevented inmostmodelPICsfromwritingtoprogrammemory. • Datamemory:Holdsmemorythattheprogrammer mayuseforvariables.TheCPUreadsfromandwrites todatamemory. • Input/output:HowthePICcommunicateswiththe worldoutsidethechip;forexample,pinsthatgobetweenlogical0andlogical1. Figure1-1:MainelementsofaPIC. 1
Chapter1 •
Peripherals:SpecialpurposefunctionsbuiltintothePIC,suchastimers,analog-to-digitalconverters andpulsewidthmodulators. IfyouarefamiliarwiththeIntelmicroprocessorsusedinIBM-compatiblepersonalcomputers,youmaynoticeonestrikingdifferenceinFigure1-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: 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 Microchip’sGeneralPurposePICLineName(InstructionWordLength)andMBasicSupport ProgramMemoryType Base-Line(12-bit) Mid-Range(14-bit) High-End(16-bit) 12C,12CE,16Cand16CE17C-seriesand18C-series. EPROM/EEPROM seriesEPROMandEEPROM NotsupportedbyMBasic 16CR-series.Notsupported Notproducedby Read-onlyMemory(ROM) NonesupportedbyMBasic byMBasic Microchip Flash(electronicallyerasable) 18F-series.Notpresently Some12F-seriesand supportedbyMBasic 16F-series (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.
2
PICs“101” 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;thememoryisconfiguredatthetimeofmanufacturingtocontaintheprogramcodeandmaynotbesubsequentlyaltered,somethingeconomicallyfeasible onlyinhighvolumeproducts.MBasicdoesnotsupportPICswithread-onlymemory. • EPROMandEEPROM:EPROM(erasableprogrammableread-onlymemory)andEEPROM(electricallyerasableprogrammableread-onlymemory)memorymaybewrittentoelectronicallythroughthe applicationofaprogrammingvoltagetothePIC.Oncewritten,EPROMmemorymaynotbere-written, andisthusbecomesread-onlyafterwards.Microchipreferstothesedevicesas“onetimeprogrammable”orOTPproducts.EEPROMdevices,however,maybeerasedthroughseveralminutes’exposure toultravioletlight.Electrically,Microchip’sEPROMandEEPROMchipsusethesametechnology, withEPROMchipsbeingencapsulatedinopaqueepoxy.EEPROMchipshaveaquartzwindowthrough whichUVlightmayreachthechipsurface.(Afterprogramming,youcoverthewindowwithanopaque labeltopreventerasurethroughambientsunlightorfluorescentlightexposure.)EPROMPICsmaybe usefulinsmalltomediumvolumeproduction,butbothEPROMandEEPROMdevicesarerapidlybeingsupplantedbyflashmemoryPICs. • Flash:FlashmemorymaybewrittentoanderasedelectronicallythroughtheapplicationofaprogrammingvoltagetothePIC.Flashmemorymaybewrittentohundredsofthousandsoftimeswithouterror and,atroomtemperature,basedonextrapolatedlifetesting,willretaindatafor100years.Flashisideal fordevelopingprogramsandlearningMBasic,asrevisingcodeandwritingtherevisedprogramtoflash requireswellunderaminuteforallbutthelongestprograms. LookingatthepriceofchipsofsimilarperformanceandcapacitywithEPROM,EEPROMandflash memorytypes,it’seasytoseewhyflashdevicesaretakinganincreasingshareofthemarket. MemoryType EEPROM(UVerasable) EPROM(one-timeprogramming) Flash
PartNumber 16CE625/JW 16CE625/P 16F628A
Packaging Ceramicwindowed18-pinDIP(CDIP)Type“JW” Plastic18-pinDIP(PDIP)Type“P” Plastic18-pinDIP(PDIP)Type“P”
UnitCost $10.64 $4.38 $3.05
Finally,withineachcategory,Microchipoffersstandardvoltage(5voltnominal)andextendedvoltage (minimumvoltagedependentuponmemorytype;compatiblewith5voltsupply;somewithbuilt-inregulatorforoperationfromhighervoltages.)PIC’salsohaveawidevarietyofmemorysize,internalperipheral options,temperatureranges,maximumoperatingfrequencyandpackaging.Thesevariantsareidentified throughassociatedalphanumericdesignators.
3
Chapter1 MemoryandVoltageDesignators Memory/Voltage Memory/VoltageType Letter C EPROM CR ROM One-timeprogrammable(EPROM)and CE EEPROM(erasable) F Flash HV HighVoltage(15V) LF LowVoltageFlash LC LowVoltageOne-timeprogrammable LCR LowVoltageROM
TemperatureRangeDesignators Temperature TemperatureRange Letter 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.
Device PIC12CE673 PIC12CE674 PIC12F629 PIC12F675 PIC16C554
Data RAM 128 128 64 64 80
ADC 4 4 4 -
PICSSupportedbyMBasic Program Memory SerialI/O Speed 1024 – 10 2048 – 10 1024 – 20 1024 – 20 512 – 20
4
Timers 1+WDT 1+WDT 2+WDT 2+WDT 1+WDT
LowVoltage Device PIC12LCE673 PIC12LCE674 PIC12F629 PIC12F675 PIC16LC554 (continued)
PICs“101”
Device PIC16C558 PIC16C620 PIC16C620A PIC16C621 PIC16C621A PIC16C622 PIC16C622A PIC16C62A PIC16C62B PIC16C63 PIC16C63A PIC16C642 PIC16C64A PIC16C65A PIC16C65B PIC16C66 PIC16C662 PIC16C67 PIC16C71 PIC16C710 PIC16C711 PIC16C712 PIC16C715 PIC16C716 PIC16C717 PIC16C72 PIC16C72A PIC16C73A PIC16C73B PIC16C745 PIC16C74A PIC16C74B PIC16C76 PIC16C765 PIC16C77 PIC16C770 PIC16C771 PIC16C773 PIC16C774 PIC16C923 PIC16C924 PIC16CE623 PIC16CE624 PIC16CE625
Data RAM
ADC
128 80 96 80 96 128 128 128 128 192 192 176 128 192 192 368 176 368 36 36 68 128 128 128 256 128 128 192 192 256 192 192 368 256 368 256 256 256 256 176 176 96 96 128
– – – – – – – – – – – – – – – – – – 4 4 4 4 4 4 6 5 5 5 5 5 8 8 5 8 8 6 6 6 10 – 5 – – –
PICSSupportedbyMBasic Program Memory SerialI/O Speed 2048 512 512 1024 1024 2048 2048 2048 2048 4096 4096 4096 2048 4096 4096 8192 4096 8192 1024 512 1024 1024 2048 2048 2048 2048 2048 4096 4096 8192 4096 4096 8192 8192 8192 2048 4096 4096 4096 4096 4096 512 1024 2048
– – – – – – – I²C,SPI I²C,SPI USART,I²C,SPI USART,I²C,SPI – I²C,SPI USART,I²C,SPI USART,I²C,SPI USART,I²C,SPI – USART,I²C,SPI – – – – – – I²C,SPI I²C™,SPI™ I²C,SPI USART,I²C,SPI USART,I²C,SPI USB,USART USART,I²C,SPI USART,I²C,SPI USART,I²C,SPI USB,USART USART,I²C,SPI I²C,SPI I²C,SPI USART,I²C,SPI USART,I²C,SPI I²C,SPI I²C,SPI – – –
5
20 20 40 20 40 20 40 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 24 20 20 20 24 20 20 20 20 20 8 8 30 30 30
Timers 1+WDT 1+WDT 1+WDT 1+WDT 1+WDT 1+WDT 1+WDT 3+WDT 3+WDT 3+WDT 3+WDT 1+WDT 3+WDT 3+WDT 3+WDT 3+WDT 1+WDT 3+WDT 1+WDT 1+WDT 1+WDT 3+WDT 1+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 1+WDT 1+WDT 1+WDT
LowVoltage Device PIC16LC558 PIC16LC620 PIC16LC620A PIC16LC621 PIC16LC621A PIC16C622 PIC16LC622A PIC16LC62A PIC16LC62B PIC16LC63 PIC16LC63A PIC16LC642 PIC16LC64A PIC16LC65A PIC16LC65B PIC16LC66 PIC16LC662 PIC16LC67 PIC16LC71 PIC16LC710 PIC16LC711 PIC16LC712 PIC16LC715 PIC16LC716 PIC16LC717 PIC16LC72 PIC16LC72A PIC16LC73A PIC16LC73B – PIC16LC74A PIC16LC74B PIC16LC76 – PIC16LC77 PIC16LC770 PIC16LC771 PIC16LC773 PIC16LC774 PIC16LC923 PIC16LC924 PIC16LCE623 PIC16LCE624 PIC16LCE625 (continued)
Chapter1
Device PIC16F627 PIC16F628 PIC16F73 PIC16F74 PIC16F76 PIC16F83 PIC16F84 PIC16F84A PIC16F870 PIC16F871 PIC16F872 PIC16F873 PIC16F873A PIC16F874 PIC16F874A PIC16F876 PIC16F876A PIC16F877 PIC16F877A
Data RAM
ADC
224 224 192 192 368 36 68 68 128 128 128 192 192 192 192 368 368 368 368
– – 5 8 5 – – – 5 8 5 5 5 8 8 8 5 8 8
PICSSupportedbyMBasic Program Memory SerialI/O Speed 1024 2048 4096 4096 8192 512 1024 1024 2048 2048 2048 4096 4096 4096 4096 8192 8192 8192 8192
USART USART I²C,SPI,USART I²C,SPI,USART I²C,SPI,USART – – – USART USART I²C,SPI USART,I²C,SPI USART,I²C,SPI USART,I²C,SPI USART,I²C,SPI USART,I²C,SPI USART,I²C,SPI USART,I²C,SPI USART,I²C,SPI
20 20 20 20 20 10 10 20 20 20 20 20 20 20 20 20 20 20 20
Timers
LowVoltage Device
3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 1+WDT 1+WDT 1+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT 3+WDT
PIC16LF627 PIC16LF628 PIC16LF73 PIC16LF74 PIC16LF76 PIC16LF83 PIC16LF84 PIC16LF84A PIC16LF870 PIC16LF871 PIC16LF872 PIC16LF873 PIC16LF873A PIC16LF874 PIC16LF874A PIC16LF876 PIC16LF876A PIC16LF877 PIC16LF877A
Thislistmayseembewilderingatfirst,solet’sgothroughthetable’sparameters: Device—Thisissimplyashortformofthedevicepartnumber. DataRAM—DataRAMspecifiestheamount(inbytes)ofrandomaccessmemoryavailabletoholdvariablesinyourMBasicprogram.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 analogvoltageandconvertittoanumericalvalue.Dependinguponthemodel,the ADCmayhave8-bit,10-bitor12-bit resolution.Chapter11showshowtouse theADCtobuildadigitalvoltmeter.
Figure1-2:UnderstandingMBasic’smemoryusagereport.
6
PICs“101” SerialI/O—CertainPICshavespecializedhardwaresupportofuptothreeserialstandardprotocols:The USART(universalsynchronousasynchronousreceivertransmitter)supportsthecommonRS-232typeasynchronousprotocol,aswellasothers;I²C(inter-integratedcircuit)andSPI(serialperipheral interface)arebothprimarilyusedtocommunicatebetweenthePICandotherintegratedcircuits,suchas add-onmemory,temperaturesensors,serialnumbergeneratorsandthelike.MBasichowever,implementsRS-232-typeserialcommunications(theSerInandSerOutprocedures),aswellasI2C(the I2CinandI2Coutprocedures)andSPI(viatheShiftInandShiftOutprocedures)insoftware, soallthreeprotocolsareavailablewhetherornotthePIChastheassociatedspecializedhardware. Indeed,insomerespectsMBasic’ssoftwaresolutionissuperior,asitpermitsuser-definedpinassignments,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.Fortunately,Microchip’slowvoltagePICsalsofunctionwiththetraditional5Vsupplysotheymaybeused withBasicMicro’sICPanddevelopmentboards.
HowDoIPickOne? Thefirststepistoidentifyyourrequirementsandthenfindthematchingdevices. • HowmanyI/Opinsdoyouneed? • HowmuchRAMisrequired?EachbytevariabledeclaredinMBasicconsumesonebyteofRAM,each wordvariabletwobytesandeachlong,fourbytes. • Howmuchprogrammemoryisrequired?AsacrudeestimateoftheMBasicprogramsizethatfitsintoa particularprogrammemorycapacity,youmayassume400−1300wordsforlibraryfunctionsand8−20 wordsperlineofexecutablecode,dependinguponthecompileroptimizationchoice(minimumsizeor maximumspeed),themixofinstructionsusedandthelengthoftheprogram.Themoredifferentproceduresandfunctionsused,thelargerthelibraryrequirement. • Howfastadevicemeetsyourspeedrequirements? • Doyouneedspecialpurposefunctions,suchasanA/Dconverter,aUSART,specifictimersoraninternalclockoscillator? • Howdoesthecostfitintotheprojectbudget? • Doyouwantaone-time-programmableoraflashmemorydevice? • Aretherephysicalpackagepreferences? • Islow-voltageoperationnecessary?
7
Chapter1 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.MBasic876isacomplete,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.
8
PICs“101”
References [1-1]
MicrochipprovidesawealthofPICinformation,availableforfreedownloading,onitsInternetwebsite, http://www.microchip.com.Allareworthreading,butofparticularinteresttobeginnersaretheintroductorytutorialsfoundathttp://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”familyandtheassociatedPICmicro™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.
9
2
CHAPTER
MBasicCompilerand DevelopmentBoards TheCompilerPackage ANoteonCompilerVersions Bythetimethisbookispublished,BasicMicrowillhavereleasedanupdatedMBasiccompiler(version 5.3.0.0)andrationalizeditscompilerfamily,droppingits“standard”versioncompiler,makingtheformer “professional”versionitsflagshipPICcompiler.(Ifyouarestillusingversion5.2.,checkwithBasicMicro forupgradeinformation.OwnersofMBasicProfessionalversion5.2qualifyforafreeupgrade,whileMBasicStandardownersqualifyforareducedpriceupgradetoMBasic-Professional.)Inaddition,BasicMicro hasamadeavailableafreeversionofitsMBasicProfessionalcompiler,MBasic876ontheCD-ROMassociatedwiththisbook.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.Chapter29summarizesthedifferencesbetweenversion5.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,BasicMicrooffersoneversionofitsMBasiccompiler,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,theISPPRO,wellintegratedwiththeMBasiccompilerthatautomaticallyloadsHEXcodefile.Amajorplus ofBasicMicro’sISP-PROisreal-timedebuggingthroughits“in-circuitdebugging”orICDcapability.Althoughitwouldbepossibletosubstituteathird-partyprogrammerfortheISP-PRO,losingboth seamlessintegrationwiththecompilerandICDabilitymorethanoffsetsanycostsavings.TheISP-
10
MBasicCompilerandDevelopmentBoards 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-PROcommunicationslinkoperates.Inthosecases,BasicMicrosuggestsusinganinexpensiveadd-onUSB-to-serialadapter tosubstituteforthebuilt-inserialportandrecommendsBafoTechnologies’BF-180USB-to-serialadapter. AslightlymoreexpensivealternativethatIhavehadreliableresultswithisBelkin’sF5U109,soldasa “USBPDAAdapter,”butwhichis,infact,astraightUSB-toserialadapter.ManyotherUSB-to-serialadapterslikelywill providereliableresults. Inadditiontothedevelopmentandprototypeboards,theISPPROiscompatiblewithBasicMicro’sUniversalAdapter.The UniversalAdapter,however,doesnotcontainanoscillatoror theothercircuitryneededtoactuallyrunaPICprogram,and isintendedforprogrammingonly. Figure2-1:ISP-PROandRJ-11jumpercable.
BASICandItsEssentials
ThisbookisnotintendedtoteachBASICprogrammingfromthegroundup.Therearemanygood“BASICprogrammingforthebeginner”booksandweassumethereaderhasatleastpassingfamiliaritywith programcontrolstatements,mathematicproceduresandvariableassignmentandstructure.Italsoassumes thereaderhasinstalledtheMBasiccompiler(eitherthefullversionorMBasic876,version5.3.0.0asof thedateofwriting)andhasfamiliarizedhimselfwiththefirst80pagesorsointheMBasicUser’sGuide. Incidentally,becauseMBasicis,insomerespects,areturntotheearlydaysofmicrocomputerlanguage implementation,I’vefound20-yearoldreferencedocumentsforIBM’sPersonalComputerBASICbeneficialinrefreshingmymemoryonsomeofthefinerpointsofBASICsyntaxorprocedureandofconsiderably morehelpthanmodernbooksdetailing,forexample,VisualBasic.Avisittoyourlocalusedbookstoremay turnupusefulreferencematerial.I’veprovidedthenamesofafewofmyfavoritelong-out-of-printBASIC referencesinthischapter’sreferencesection. Asaguidetofindingtheappropriateprocedure,Table2-1groupsMBasic’scommandsintoalogical classification. Table2-1:TaxonomyofMBasicfunctionsandprocedures. Group ProgramFlow
Procedure
Group HardwareRelated
Repeat/Until While/WEND Do/While For/Next If/Then/Else/EndIf GoTo GoSub/Return Branch
11
Procedure ADIN ADIN16 Count HPWM SetCapture GetCapture SetCompare
Chapter2 Table2-1:TaxonomyofMBasicfunctionsandprocedures. Group PinRelated
EEPROM
Procedure
Group Miscellaneous
Button Low PulsIn PulsOut RCTime Reverse Toggle SetPullups INxx Outxx Dirxx
Variables
Data Read ReadDM Write WriteDM
Procedure DeBug End Let Nap Sleep Stop
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 RandomGenerator
Pause PauseUs PauseClk
MemoryRelated
Peek Poke
Random
ProgramMemory
ReadPM WritePM
ExplicitExternal DeviceSupport
Servo SPMotor Xin Xout
OnReset
OnPOR OnBOR OnMOR
Interrupts
Enable Disable OnInterrupt SetExtInt SetTmr0 SetTmr1 SetTmr2 IsrASM GetTimer1
Assembler
12
ASM{} ISRASM
MBasicCompilerandDevelopmentBoards Table2-1:TaxonomyofMBasicfunctionsandprocedures. Group CommandModifiers
Procedure
Group MathOperators and Functions
Dec Hex Bin Str Sdec Shex Sbin Ihex Ibin ISHex ISBin REP Real WaitStr Wait Skip
BitwiseOperators
! & | ^ >> = 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.
13
Chapter2
Figure 2-5: Basic Micro’s 28/40 prototype board.
Figure 2-4: Basic Micro’s 08/18 prototype board.
Allfourboardspermitin-circuitprogramming—thatis,the PICmaybeprogrammedwithoutremovingitfromyour board,ordisconnectingitspinsfromwhateveryoumayhave connectedtothem.Figure2-6,asimplifiedblockdiagramof the28/40prototypeboard,showshowthisispossible.Three ofthepinsrequiredforprogramming,RB4,RB6andRB7, areswitchedthrougha74HC4053analogmultiplexer/demultiplexerbetweentheirnormalconnectiontothePICpin headerandtheRJ11socketthatconnectstotheISP-PRO programmer.Forourpurpose,the74HC4053canberegarded asanelectronicthree-poledoublethrowswitch,controlledby theISP-PRO.TheMCLR(masterclear)pinisthefourthconnectionrequiredforprogrammingandisdirectlyconnected totheRJ11programmingsocket. The0818and08/18boardsfollowasimilardesign,butwith extraconfigurationjumpersnecessitatedbythemultiplefunctionsMicrochipassignedtocertainpinsofPICsproducedin8 and18-pinpackages.The0818and08/18datasheetsshould Figure 2-6: Simplified block diagram of 28/40 beconsultedbeforeprogrammingthesesmallPICs. prototypeboard. AllfourboardsbringthevariousPICpinstologically labeledheaders;forexample,A0,A1,soyoudon’thavetocontinuallycross-referencephysicalpinnumbers withtheirlogicalassignments. InworkingwithBasicMicro’sdevelopmentboardsandISP-PROprogrammerwatchoutforthefollowing: • Thesearesoldasbareboards,withunprotectedtracesonthebottom.Don’tputthemdownonconductive surfacesortheboardmaybedamagedandwatchforstraywiresorcomponentleadsaswell.(Iwatched myISP-PROboardbedraggedbyitsserialcableacrossthemetaledgeonthetableandlookedonhelplesslyassparksflew.Needlesstosay,theISP-PROdidn’tworkafterthat.)Ithelpstoaddsmallstick-on rubberfeettothebottomofallboards. • Itispossibletodamagethe74HC4053electronicswitch,asisratedatamaximumswitchedcurrentof25 mA.ThemostlikelydamagescenariocomesfromforcingthePICtosinkexcessivecurrent.Additionally, unlikeamechanicalrelay,the74HC4053introducesapproximately80to100ohmsofseriesresistance. AnotherdifficultybeginnersoftenhaveisconfusingVDDandVSSwhenwiringcircuits.VSSisgroundinBasic Micro’sdevelopmentboards.VDDisthesupplyvoltageandis+5voltsinthedevelopmentboards.Thusa schematicreferenceto+5VisthesameasVDDandareferencetogroundcorrespondstoVSS.(ThisterminologycomesfromVDDasthe“drain”voltageandVSSasthe“source”voltageforafieldeffecttransistor,the basicbuildingblockofPICs.) 14
MBasicCompilerandDevelopmentBoards
ProgrammingStyle EveryprogramprintedinthetextisalsoprovidedasafileintheaccompanyingCD-ROMwithtwoversions supplied—theoriginallydevelopedprogramscompatiblewithMBasicversion5.2.1.1.andarevisedversioncompatiblewith5.3.0.0.TheremaybedifferencesbetweentheprintedprogramandtheCD-ROMfor severalreasons: • TheCD-ROMisquickertoupdateandmayhavealaterorcorrectedversionofthetextprogram. • Pagewidthandoveralllengthrestrictionsmakeitnecessarytolimitthecommentsandblankspaces usedontheprintedpage.Thedatafileshavenosimilarrestrictionandhencemayhaveadditionalcommentsandmaybeformattedforgreaterreadability.(AlthoughnotdocumentedintheUser’sGuide, MBasicusestheverticalbar“|”asacontinuationsymbol,thusallowingonelogicallineofBASIC codetobesplitovertwoormorephysicallines.)
StandardProgramLayout Asanaidinreadabilityandmaintainability,Iliketofollowastandardlayoutwhenprogramming,asexemplifiedinthefollowingtemplate: ;ProgramSample.Bas–Filename ;Version1.00 ;14September2003–originalversion ; ;Constants ;----------------Defineconstantshere ;Variables ;----------------Declarevariableshere ;Initialization ;-------------Initializationcodehere–thiscodeisexecutedonlyonce Main ;--------Maincodesegmenthere IfsomethingGoSubSub1 IfsomethingelseGoSubSub2 IfsomethingtotallydifferenthappensGoSubSub3 GoToMain;ifappropriatetohaveacontinuousloop Sub1 ;---- Subroutinecodehere Return Sub2 ;---- Subroutinecodehere Return Sub3 ;---- Subroutinecodehere IncludesGoSubSubSub1 Return SubSub1 ;----- Subroutinecodegoeshere Return End
15
Chapter2 Thestructureislogical;firstdefineconstantsandvariablesandconductanynecessaryinitialization,then writethemainprogramsegment.Iusesubroutinesasnecessary,withthegoalofkeepingthemainsegment shortandtothepoint.MBasichasnorestrictiononthenumberofsubroutinesthatmaybenestedsoone subroutinemaycallanother. Withversion5.3.0.0,MBasicintroduceduser-definedfunctions,albeitwithglobal,notlocal,variables.This featurewasaddedtoolatetobeusedintheprogrammingexamples,exceptforChapter29.
Constants,VariableandSubroutineNames Intelligentlyselectingconstant,variableandnamesaidsprogramreadability.MBasicpermitsvariables andconstantstohavenamesupto1024characterslong,shouldyousowish.(MBasichasseveralhundred reservedwordsandyoushouldn’tusethesenames.Inmostcasesyouwillreceiveawarningorerrormessageifyoutrytoredefineareservedword.)Allnamesarecaseinsensitive,sowecanusecapitalizationto improvereadabilitywithoutworryingaboutconsistency.ThenamingconventionsI’vedevelopedinclude: • Indexorcountingvariables,forexample,controlvariablesusedinFor/Nextloops,startwithlettersin therangei…n.(Yes,thisisaholdoverfromtheearlydaysofFORTRANwhenintegervariablenames hadtostartwithoneoftheseletters.)Keepthesenamesshort,particularlyiftheywillbeusedfrequently.Inmanycases,thesinglelettersi,j…nareperfectlysuitable. • Namesshouldreflectcontentsoractivities,withoutbeingoverlylong.SupposeweusetheA/Dconvertertoreadavoltagefollowedbyasubroutinecalltoaveragethisreadingwiththelast15readings—that is,amovingaverageof16readingsandthattheindividualreadingisn’telsewhereused.Sincethevoltagevaluebeingreadwillbediscardedaftertheaveragingprocess,wemayuseTempVolt,sotheA/D readstatementwouldbe:ADINAN0,CLK,ADSETUP,TempVolt.Iliketonamevariablesthathave limitedscopewithatwo-partname,startingwithTemp.Tomakethenamemorereadable,useupper andlowercase,thusTempVoltiseasiertoreadthantempvoltorTEMPVOLT.Or,insertanunderscoreasaseparator;Temp_Volt.(Permissibleseparatorcharactersare_,@,$,%,?and`.)Subroutines shouldbenamedaccordingtotheactivityperformed,inthisexample,TakeAverageisanappropriate name,orevenTakeAverageVolt.IwouldreservethenameAvgVoltforthevariableholdingthe averageofthelast16readings,thuskeepingthesuffixnameVoltandchangingtheprefixtodescribe thetypeofvoltageparameterinthevariable.Short,conciseandinformativevariablenamescanoften beconstructedoftheform“adjective–noun”whilesubroutinenamesareoftenoftheform“verb-noun” wheretheverbdescribestheactionandthenoundescribesthesubjectoftheaction. • Althoughverylongnames,suchasAverageTheLast16VoltageReadingsmayseemdescriptiveat first,theyactuallyhinder,ratherthanassistcomprehensioniftheyareusedwithabandon. Theseareguidelines,nothardandfastrules,andevenmyobservanceisn’t100%,butfollowingalogicalconsistentnamingapproachwillpaydividendsinthelongrunintermsoffewererrorsandimprovedreadability.
BuildingtheCircuitsandStandardAssumptions InadditiontotheMBasiccompiler(eitherthefullorMBasic876freeversions),anISP-PROprogrammeranda 2840developmentboard,andanyassociatedpartsrequiredforspecificprojects,youshouldhaveaccessto: • Asecondlargerplugboardtoholdoverflowcircuitry. • Assortedjumperwires.Youcanpurchaseakitofjumperwires,ormakeyourownfromashortlength ofscrap25-pairor50-pairtelephonecable. • Asecondadjustableregulatedpowersupply,preferablyonethathastwoindependentoutputssothat positiveandnegativevoltagesmaybeprovided. • Adigitalmultimeter. • Yourabilitytotroubleshoot,experimentandverifyoperationofcircuitswillbegreatlyenhancedifyou haveatriggeredoscilloscope. 16
MBasicCompilerandDevelopmentBoards Insteadofbuyingresistorsandcapacitorsoneortwoatatime,considerbuyingassortmentkits.Possible suppliersareidentifiedinAppendixA.AlmostallresistorsusedwithaPICwillbe10Korlessinvalueand are¼wattdissipationrating,soevenalimitedassortmentofvalueswillbequitebeneficial. Sinceweuseprebuilddevelopmentboards,certainthingsareomittedintheschematicsprovidedinthisbook. • BasicMicro’sprototypeanddevelopmentboardsincludebypasscapacitorsontheVDDsupplyheaders. Hence,theywillnotnormallybeillustratedinschematicdiagrams.However,ifpartsofthetestcircuitryisbuildonansecondplugboard,orifyouaredesigningaprintedcircuitboardtoholdyourdesign, gooddesignpracticesaysyoushouldliberallybypassVDD. • Thedevelopmentboardsaredesignedforceramicresonatorfrequencydeterminingelementsandare shippedbyBasicMicrowitha10MHzresonator.Thecircuitsandsoftwareinthisbookusea20MHz resonator.Inmanycases,therewillbenodifferenceinperformance,butformaximumcompatibility withtheprogramsinthisbook,usea20MHzresonator.Resonatorscostunder$1andareavailable fromsuppliersidentifiedatAppendixA.
ChoiceofPIC I’veuseda16F877Atodevelopthecircuitinthisbook,butnoneoftheprogramsdependuponthe“A”version’saddedfeatures,soa16F877willworkequallywell.Exceptforthosefewcircuitsthatareinput/output pinconstrained,youmaysubstitutea16F876or‘876AinanydesignanduseBasicMicro’sfreeMBasic876 compilerforalmosteveryprogramwedevelop.
Pins,PortsandInput/Output SinceeveryusefulprogrammustreadfromorwritetoaPIC’sinput/outputpins,let’ssummarizehow MBasichandlespinsandports.Itcanbeconfusingbecausesomepinshavetripleorquadrupleorevenmore dutiesandbecauseMBasicprovidesseveralwaystoaddressanygivenpin.And,thewordpinitselfhasdual usage,asitreferstothephysicalpackaging(an8-pinDIPpackageforexample)andtothosephysicalpins thatmaybeusedforvariouspurposes.TosimplifyourdiscussionwewilllimitourselvestoPICsthatare supportedbyMBasicandplugintoeitherthe0818or2840developmentboards. PICscommunicatewithexternalcircuitrythroughintermediary“ports.”Portsaretreatedinternallybythe PIC’sCPU,andbyMBasic,asbyte(8-bit)variableswitheachbitcorrespondingtoaparticularpin.For example,themostsignificantbitinPortB’sbytevaluecorrespondstopinRB7,whiletheleastsignificantbit correspondstoRB0.(InsomePICs,notallbitsofeachportvariablehavephysicalpinassignments.) LettersfromA…Eidentifyports,exceptinDIP8packagedPICswhichhaveonlyoneport,calledGPIO (generalpurposeinput/output).Thus,wehaveGPIO,PortA,PortB…PortEaspredeclaredvariablesin MBasic.(Portidentifiersarewrittenwithoutaspace,forexample,PortA,notPortA.)Ofcourse,notall PICsphysicallysupportalloftheseports,andinsomecasesnot alleightbitsofaporthaveassociatedpins.Forexample,the PIC16F876hasPortA(butonlybits0…5aremappedtopins), PortBandPortC.MBasic’sconfigurationfiles,fortunately,ensure thatonlylegitimateportvariablesarepredeclaredfortheparticular PICbeingprogrammed. Figure2-7illustrates,asanexample,PortBanditspinassignments.Eachgeneral-purposeI/Opinisidentifiedwithaconsistent namingconvention.Forexample,RB0isPortB,bit0.The“R” inRBstandsfor“register,”whichissynonymouswith“file”or “variable.”MBasicalsopre-definesconstantsassociatedwitheach Figure2-7:PortBtopinassignments. 17
Chapter2 ofthesepins,sowehaveconstantsB0,B1…B7availabletous.MBasicgivesusasecondwaytoreference pinsthroughasequentialnumberingsystem,forexample,A0=0,A1=1upthroughE7=39.Finally,to providebackwardscompatibilitywiththeBasicStamp™,MBasicincludesthededicatedfunctionsINxx, OUTxxandDIRxxwherexxisthebit,nibble,byteorwordidentifierasreflectedinTable2-2. Table2-2:PortandbitI/Ovariables,constantsanddedicatedfunctions. Variables
Constants
DedicatedFunctions
Portata Time
Nibbleat aTime
Bitata Time
Nibble
Port.Bit
Pin Constant
Pin Value
Bit
PortA. Nib0 or PortA. LowNib
PortA.Bit0
RA0
0
IN0/OUT0/DIR0
PortA.Bit1
RA1
1
IN1/OUT1/DIR1
PortA.Bit2
RA2
2
IN2/OUT2/DIR2
PortA.Bit3
RA3
3
IN3/OUT3/DIR3
PortA. Nib1 or PortA. HighNib
PortA.Bit4
RA4
4
IN4/OUT4/DIR4
PortA.Bit5
RA5
5
IN5/OUT5/DIR5
PortA.Bit6
RA6
6
IN6/OUT6/DIR6
PortA.Bit7
RA7
7
IN7/OUT7/DIR7
PortB.Bit0
RB0
8
IN8/OUT8/DIR8
PortB.Bit1
RB1
9
IN9/OUT9/DIR9 IN10/OUT10/ DIR10 IN11/OUT11/ DIR11 IN12/OUT12/ DIR12 IN13/OUT13/ DIR13 IN14/OUT14/ DIR14 IN15/OUT15/ DIR15
Port Variable
PortA
PortB.Nib0 or PortB. LowNib PortB PortB.Nib1 or PortB. HighNib
PortC. Nib0 or PortC. LowNib PortC
PortC. Nib1 or PortC. HighNib
INS/OUTS/DIRS Nibble
Byte
Word
INA/OUTA/ DIRA INL/OUTL/ DIRL INB/OUTB/ DIRB
INS/ OUTS/ DIRS
INC/OUTC/ DIRC
PortB.Bit2
RB2
10
PortB.Bit3
RB3
11
PortB.Bit4
RB4
12
PortB.Bit5
RB5
13
PortB.Bit6
RB6
14
PortB.Bit7
RB7
15
PortC.Bit0
RC0
16
PortC.Bit1
RC1
17
PortC.Bit2
RC2
18
PortC.Bit3
RC3
19
INHOUTH/ DIRH IND/OUTD/ DIRD
PortC.Bit4
RC4
20
INxx:Readstatus,whetherininputor outputmode
PortC.Bit5
RC5
21
OUTxx:Writevalue
DIRxx:Setdirection 1=input,0=output
PortC.Bit6
RC6
22
PortC.Bit7
RC7
23
(continued)
18
MBasicCompilerandDevelopmentBoards Table2-2:PortandbitI/Ovariables,constantsanddedicatedfunctions. Variables
Constants
DedicatedFunctions
Portata Time
Nibbleat aTime
Bitata Time
Port.Bit
Pin Constant
Pin Value
PortD.Bit0
RD0
24
PortD.Bit1
RD1
25
26
Note:DIRxxcommandisreversed fromBasicStamp
Port Variable
PortD
Nibble PortD. Nib0 or PortD. LowNib PortD. Nib1 or PortD. HighNib PortE.Nib0 or PortE. LowNib
PortE PortE.Nib1 or PortE. HighNib
PortD.Bit2
RD2
INS/OUTS/DIRS Bit
Nibble
Byte
Word
xxasappropriateforbit,nibble,byte orword
PortD.Bit3
RD3
27
PortD.Bit4
RD4
28
PortD.Bit5
RD5
29
PortD.Bit6
RD6
30
PortD.Bit7
RD7
31
PortE.Bit0
RE0
32
PortE.Bit1
RE1
33
PortE.Bit2
RE2
34
PortE.Bit3
RE3
35
PortE.Bit4
RE4
36
PortE.Bit5
RE5
37
PortE.Bit6
RE6
38
PortE.Bit7
RE7
39
MBasicpermitsustoreferenceaportorapinasanaddressorasavariable.Asanaddress,theportorpin isanargumenttocertainfunctions.Asavariable,thevalueoftheport(eitherinreadingorwriting)canbe usedlikeanyothervariable.TherearealsothededicatedfunctionsidentifiedinTable2-2thatoperateon specificportsorpinswithoutanexplicitportorpinreference,suchasIN0.WemustrememberthatMBasic automaticallyinitializesallI/Opinsasinputsandthatbeforereadingfromorwritingtoaportorapinwe mustfollowsomesimplerules: First,setthedirectionoftheportorpintobeeitheraninputoroutput; Second,readtheportorpinifaninput,orwritetotheportorpinifanoutput; or, Readfromorwritetoaportorpinwithaprocedurethatautomaticallysetsthedirection.
OutputMode Let’sseehowmanydifferentwayswecanassignapintoanoutputandtomakeitsvalue0.We’llusepin RB0asourexample. ;DirectPinAddressing ;--------------------OutputB0 ;Firstmakeitanoutput.B0isaconstant PortB.Bit0=0 ;PortB.Bit0isavariable Dir8=0 Out8=0
;Specialpurposefunction,DIR8isforpinB0 ;LikewiseforOut8
19
Chapter2 LowB0
;Lowfunctionautomaticallymakesitanoutput ;noneedtoseparatelymakeitintoanoutput
Output8 PortB.Bit0=0
;B0isanaliasfor8socanuse8directly ;Makethevariableassignment
Low8
;B0isanaliasfor8socanuse8directly ;LOWswitchestooutputmodeandoutputs0
TRISB.Bit0=0 PortB.Bit0=0
;TRISBvariablecontrolsPortBI/Odirection, ;0=output&1=input. ;PortB.Bit0isavariable
;Byteatatimeaddressingtodealwithmultiplepins ;inoneinstruction ;---------------------------------------------------TRISB=%00000000 ;Setsall8pinsto0,i.e.,output PortB=%00000000 ;Assignall8bits(pins)to0. DIRH=%00000000 OUTH=%00000000
;Makeall8PinsinPortBoutput ;Setall8bits(pins)to0
InputMode TomakeRB0aninputandreaditsvalue,wehavethechoiceofasimilarsetofoptions: ;DirectPinAddressing ;Assumewehavealreadydeclared: ; BitVarVar Bit ; ByteVarVar Byte ;toholdthevaluebeingread ;--------------------InputB0 ;Firstmakeitaninput.B0isaconstant BitVar=PortB.Bit0 ;PortB.Bit0isavariable Dir8=1 BitVar=In8
;Specialpurposefunction,DIR8isforpinB0 ;LikewiseforIN8
Input8 ;B0isanaliasfor8socanuse8directly BitVar=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.,input ByteVar=PortB ;Readall8bits(pins)intoByteVar. DIRH=%11111111 ByteVar=INH
;Makeall8PinsinPortBinput ;Readall8bits(pins)intoByteVar
PinVariablesvs.Addresses Onecommonerrorbybeginnersisconfusingpinvariableswithpinaddresses.ThefunctionsOutput,Low andInputrequireapinaddressastheirargument.ThepinaddressmaybeoneofMBasic’spre-defined constants,forexample,B0,oritsequivalentnumericalvalue,8.Thepinaddressmayalsobethevalueofa variable,suchas: ForI=B0toB7 LowI Next
;Igoesfrom8(B0)to15(B7) ;MakesB0low,thenB1throughB7sequentially
IntheLowIstatement,LowoperatesonthevalueofI,whichitinterpretsastheaddressofapin.When Iis8,forexample,LowoperatesonpinRB0.Thus,theabovecodefragmentisidenticalwith:
20
MBasicCompilerandDevelopmentBoards ForI=8to15 LowI Next
Pinvariablesareusedtoreadthevalueofapinorofaportandtowritetoapinorportviaanassignment (the“=”sign).ThuswehaveByteVar=PortB,orPortB=$FF.WealsomayusePortBlikeanyother bytevariable,suchasx=2*PortB. IfwetrytoreadthevalueofpinB0asaninputwiththestatementBitVar=B0,thecompilerwillproduce noerror,butBitVarwillnotholdthedesiredresult.Rather,thisstatementisidenticalwithBitVar=8.If testingforapinvalueconditioninaloopstatement,it’simportantthatthevariableconstructbeused. ;TotestPinB0 ;-------------IfPortB.Bit0=1Then ;executecodegoeshere EndIf ;Thefollowingcodewillcompilebutwon’twork ;sinceit’sthesameaswritingIf(8=1),whichisalwaysfalse IfB0=1Then ;executecodegoeshere EndIf
Finallyit’spossibletoreadfromapinorportthatissetforoutputinwholeorinpart,andtowritetoapin orportthatissetforinputinwholeorinpart.Noerrormessagewillbegenerated.Ifyouareexperiencing strangeorunstableresultsreadingorwritingtopinsorports,checktoensurethecorrectdirectionissetand thatyouarecorrectlyusingpinvariablesandpinconstants. PICsequippedwithanalog-to-digitalconvertersapplythedesignatorsAN0,AN1…topinsthatalsohavean analogfunction.Thus,a16F876pinnameRA0/AN0indicatesthatthepinhasthreepossibleuses:digital output,digitalinput(RA0)andanalog(AN0)input.Theprocessofassigningapintobeananaloginputis discussedindetailinChapter11.
RunTimevs.ProgramTimePinAssignments Allthepinassignmentswehavediscussedtothispointareruntimealterable,i.e.,theirstatusmaybealtered bytheprogramonthefly.Inonepartofyourprogramapinmaybeaninputandlaterintheprogramthe samepinmaybeanoutput.However,insomePICs—mostoftenthoseinthe8and18-pinpackages—certainpinconfigurationsmayonlybeestablishedatprogramtime,ataskusuallyaccomplishedviaanoption dialogboxinMBasicbeforecompilingyourcode.(ThispermitsMicrochiptomaketheirsmallerpackage devicesmoreflexible,butatthecostofconfusiontobeginningprogrammers.)Then,dependinguponthe programtimeconfiguration,furtherruntimechangesmaybepossible.Programtimepinsetupishighly devicespecificandreferencetothedatasheetforyourspecificPICwillbebeneficial. We’llexplorethedifferencebetweenruntimeandprogramtimealterablepinsinthecontextofthe12F629, whichhas3pinsthatmustbeconfiguredatprogramtime: 12F629ExampleofPinsConfiguredatProgramTime ProgramTimeConfiguration RunTimeConfiguration GP3:Input GP3(general-purposeI/O) GP3:Output GP3/MCLR/Vpp MCLR/Vpp(masterclear/Vprogram) None GP4:Input GP4(general-purposeI/O) GP4:Output T1G(timer1gate) GP4/T1G/OSC2/CLKOUT OSC2(secondresonatorconnection) None CLKOUT(clockout) None PinName
21
Chapter2 PinName
GP5/T1CKI/OSC1/CLKIN
12F629ExampleofPinsConfiguredatProgramTime ProgramTimeConfiguration RunTimeConfiguration GP5:Input GP5(general-purposeI/O) GP5:Output T1CKI(Timer1clockin) CLKIN(externalclockinput) None OSC1(firstresonatorconnection) None
IftheGP3/MCLR/Vpppinisdefinedatprogramtimetobeageneral-purposeI/Opin,itmaybeusedforinputoroutputexactlyaswe haveearlierdiscussed,andchangedfrominputtooutputunderprogramcontrol.However,ifatprogramtimeitisdefinedasMCLR,it isunavailableforanyotherpurpose.Thisselectionisaccomplished withtheMCLRcheckboxfoundinMBasic’sConfigurationdialog box,asshowninFigure2-8. Thetwooscillatorpinsalsomustbedefinedatprogramtime,but arelinked.Ifyouplantouseanexternalresonatororcrystal,the OSC1andOSC2pinconfigurationmustbeactive.Ifyouplanto useanexternalclocksource,thentheCLKINoptionmustbeactive. IfyouwishtousetheinternalRCoscillator,thentheCLKOUTpin mayeitherbeGP5orOSCOUT.IfanexternalRCoscillatorisused, theRCnetworkmustconnecttotheOSC1pin.Table2-3shows howtheseoptionsinteractandhowtheyareselectedintheMBasic configurationboxofFigure2-8.(TheMBasicconfigurationoptions Figure 2-8: Program time pin options for12F629. correspondtothefirstcolumninTable2-3.) Table2-3:ConfigurationDialogfor12F629–OscillatorConfiguration. Configuration DialogBox LowPower External HighSpeed ExternalClk IntRConGP4 IntRConClkOut ExtRConGP4 ExtRConClkOut
Oscillator Configuration LP XT HS EC INTOSC INTOSC RC RC
GP4/T1G/OSC2/CLKOUTFunction OSC2—crystalconnection OSC2—crystalconnection OSC2—crystalconnection GP4(general-purposeI/O) GP4(general-purposeI/O) CLKOUT(clockwaveformoutput) GP4(general-purposeI/O) CLKOUT(clockwaveformoutput)
GP5/T1CKI/OSC1/CLKINFunction OSC1—crystalconnection OSC1—crystalconnection OSC2—crystalconnection CLKIN(externalclockinput) GP5(general-purposeI/O) GP5(general-purposeI/O) CLKIN-RCcircuitonpin CLKIN-RCcircuitonpin
Furthercomplicatinganalreadycomplexmatter,anexternalclocksourcemaybeusedintheLP,XTand HSmodesbyfeedingitintoOSC1,inwhichcase,OSC2isunused.TheLP,XTandHSmodessetinternal parametersintheoscillatorsectionofthe12F629andestablishthemaximumresonatororcrystalfrequency andassociatedcapacitorvalues.Section9ofMicrochip’sPIC12F629/675DataSheetshouldbeconsulted forspecifics.
LVPProgrammingPinSelection Onecompiletimefeaturesharedby16F876/877chips(includingthe“A”versions),alongwithmanyother flashprogrammemoryPICs,isthelowvoltageprogramming(LVP)option.Historically,flashmemory hasrequiredapplicationofaprogrammingvoltagetwoorthreetimesthatofthenormaloperatingvoltage,
22
MBasicCompilerandDevelopmentBoards typically12VforaPICoperatingwithVDDof5V,knownashighvoltageprogramming(HVP).NewerPICs, suchasthe16F876/877/876A/877AmaybeoptionallyprogrammedinLVPmode,usingonly+5V.Whether aPICthatsupportsLVPactuallyhasLVPenabledisdeterminedbyaconfigurationbit,thevalueofwhichis keyedtotheLVPcheckboxinMBasic’sconfigurationsetupdialogboxseeninFigure2-8.Ifthechipdoes notsupportLVP,asistrueinFigure2-8,theLVPcheckboxisgrayedout. ToensuremaximumflexibilitywhenprogrammingbotholderandnewermodelPICs,BasicMicro’sISPPROandits0818and2840DevelopmentBoardsusehighvoltageprogrammingandfortheprogramsinthis bookyoushouldnotselectLVPmodeinMBasic’sprogrammingoptions.MicrochipenablesLVPaspartof themanufacturingprocess,sowhenprogramminganewPICforthefirsttimeyouwillfinditnecessaryto cleartheLVPselectionboxinMBasic’sconfigurationmenu,ifthatmodelPIChasLVPfunctionality. BasicMicro’sISP-PROdoesnotsupportLVPandprogramsonlyusingHVPmode.But,sinceaPICwith LVPenabledisstillprogrammableviaHVP,youcan,nonetheless,selectLVPandprogram16F876/877/ 876A/877AchipswithMBasicandtheISP-PRO.However,ifyoudoso,pinRB3becomestheLVPcontrol pinandisnolongeravailableasageneral-purposeI/Opin.(ThespecificpinusedforLVPcontrolvaries;for example,a16F628usesRB4.)NoteveryLVP-capablemodelPICbehavessonicelyandyoumayfindsome modeldevicesrefusetoprogramifyouinadvertentlyleavetheLVPoptionselected.I’veevenseendifferent samplesofthesamemodelPICbehavedifferentlywiththeLVPoptionselected.Inthiscase,clearingthe LVPcheckbox,followedbyseveralcyclesofMBasic’s“erase”functionusuallyrestoresprogrammability.
WeakPull-Up Onelastremarkandwemayleavethisoverlylongdiscussionofpins.ManyPICshavebuilt-in“weak”pull-up resistorsforPortB,usablewhensettobeaninput.We’lldealwithfloatinginputgatesandtheneedforpullupresistorsinChapter4,butMBasic’sprocedureforcontrollingPortB’sinternalpullupsisSetPullUps wheremodeisoneoftwopre-definedconstants,Pu_OfforPu_Onforde-activatingoractivating, respectively,internalpull-upresistors.Pull-upresistorsforalleightpinsofPortBareactivatedordeactivated bythiscommand,notindividualpins.ForPortBpinsthataresettobeoutputs,SetPullUpshasnoeffect.
Pseudo-CodeandPlanningtheProgram Indescribinganalgorithmorevenacompleteprogram,wewilloftenuseamixtureofEnglishandMBasic statementscalled“pseudo-code.”Pseudo-codeisausefultoolwhendevelopinganideabeforewritingaline oftruecodeorwhenexplaininghowaparticularprocedureorfunctionorevenanentireprogramworks.To distinguishitfromMBasicorassembler,pseudo-codewillappearinbold,italicCouriertypeface. Let’sillustratethebenefitofpseudo-codewithasimpleexample.SupposewewishtoilluminateanLEDfor 1secondwheneverabuttonispushed.We’llassumethatthebuttonisconnectedtotheRB0pinonaPIC, thatpressingthebuttontakesRB0lowandthattheLEDisilluminatedbytakingpinRB1high.Afterany buttonpush,theprogramrepeatsandwaitsforthenextpush.(We’llignorebuttondebounce,multiplebutton pressesandafewotherreal-worldconcerns.)Apseudo-codeversionofourprogramis: InitializationRoutine Initializebuttonpintobeaninput InitializeLEDpintobeanoutput SetLEDpintonotilluminateLED MainProgramLoopStart Readbuttonpinanddeterminestate Ifbuttonnotpresseddonothing Ifbuttonpinispressed,setLEDpintoilluminate Ifbuttonhasbeenpressedwait1second TurnLEDOffafter1second GobacktoMainProgramLoopandtestfornextpress
23
Chapter2 Thispseudo-codeexampleoffersaeasytounderstandstatementoftheprogramstructureandonceweare satisfiedthatitslogicmatchesourdesiredoperation,wecaneasilytransformitintoanMBasicprogram, witheachlineofpseudo-codeexpandingintooneortwolinesofrealcode: ;Initialization ;-------------InputB0 ;Initializebuttonpintobeaninput OutputB1 ;InitializeLEDpintobeanoutput LowB1 ;SetLEDpintonotilluminateLED Main ;---- IfPortB.Bit0=0Then;Readpinanddeterminestate HighB1 ;Ifpressed,LEDilluminated Pause1000 ;Ifbuttonpressedwait1second LowB1 ;TurnLEDOffafter1second EndIf ;Ifbuttonnotpresseddonothing ;GobacktoMainProgramLoopand GoToMain ;testfornextpress End
Forallbutthesimplestprograms,Istartwithahighlevelpseudo-codedefinitionofoverallprogram flow—perhapsaidedbyasimpleflowchart—butatahighlevelofabstraction.Thefirstpseudo-codedraft concentratesonthehighlevelprogramflowandlogic,withsubroutines,initialization,input/outputconcerns beingalineortwoofpseudo-code.Itshowsthedesiredinputandoutputdata,evenifitissomethingas simpleas“readuser’skeypadpress.”ImayevenwriteanddebugMBasiccodeimplementingthehighlevel design,substitutingdummysub-routinesforthedetailedones,andhard-codinguserinputs. Oncethehigh-levelprogramflowisfunctioning,Iwritepseudo-codeforeachmainsubroutine,followed byanMBasicrealization.Eachsubroutineiswrittenanddebuggedbeforestartingonthenext,totheextent permittedbytheprogramlogic.Whereonesubroutinedependsonthenext,followatopdownapproach. Ifyouhavetoboildownwritinggoodcodeintoonerule,itwouldbe:
☞Thinkfirst,codelater.
Ifwearepermittedafewmorerules,theywouldbe: • Definetheproblem,includingthe“goesintos”and“comesoutofs,”thatis,theinformationtogointothe program,suchasswitchreadings,sensorreadingsandtheconditionsthatcausethosereadingstobegenerated,andthedesiredoutput,suchaslogiclevelpinchanges,analogoutputsthroughadigital-to-analog converter,andtheactionstheseoutputscause,suchasturningonamotororactivatingasolenoid. • Documenttheproblemandthesolutionandkeepthedocumentationuptodateasyoudevelopanswers, evenifyouareprogrammingforpersonalsatisfaction,oreducationandnotwiththethoughofdevelopingacommercialproduct. • Thinkfirst,codelater—thesinglemostimportantthingforaprogrammertodoistoresistthesirencall ofwritingcodeandinsteadstudy,understandandplanwhattodo.Codingisoftenthesimplesttaskand canbealmostmechanical,iftheproblemisfirstproperlyunderstoodanddefined. • Programmodularly,proceedingfromthetopdown,anessentialphilosophyifyouaretoefficiently producereadable,stablecode.It’spossibletoprogramfromthebottomup,startingwithdetailsand workingtowardsageneralstructurethatfitstogetherthedetails,butit’snevertherightwaytoproceed.Andifyoudomanagetomakeitwork,achangeindetailscanupsetthegeneralstructureyou’ve cobbledtogether.Top-downprogrammingismuchmoretoleranttotheinevitablechangesthatoccuras aprojectprogresses.And,writecodeinmodularsubroutines,notasonelargeomnibusprogram.Code development,maintainabilityanddebuggingareallimmenselyaidedbycodinginsubroutines.Asseen
24
MBasicCompilerandDevelopmentBoards inmanyexamplesinthisbook,ourmodularprogrammingtakestheformofsimpleprogramstotest concepts,hardwareandcode,butwhicharethencombinedintomorecomplexconstructions.
InsidetheCompiler TheprocessofcompilinganMBasicprogramandhavingtheresultantcodeprogrammedintothePICis illustratedinFigures2-9and2-10.Theprocessistransparenttousers,asBasicMicro’sintegrateddevelopmentenvironmentautomaticallyinvokestheassembler,thelinkerandtheloaderprogramanddeletesany unnecessaryintermediatefiles.Wewillfindreason,however,toexaminetheintermediateassembler(.ASM) filewhenweexaminehowassemblerprogrammingmesheswithMBasic.
Figures2-9:Flowduringprogramcompilation.
Figure2-10:PICtocompilerflow.
Compilervs.Interpreter We’vereferredtotheMBasicsoftwareasa“compiler.”SincethesoftwarerunsunderWindowsonan Intel-compatiblePC,andthetargetisaPICitshouldbecalleda“cross-compiler,”astheterm“compiler”is usuallyunderstoodtomeanthatthetargetprocessoristhesameastheprocessoruponwhichthecompiler executes. Amorefundamentalquestion,though,isMBasicacompiledlanguageoraninterpretedlanguage?Inthe purestcase,acompilertakesthehighlevellanguagesourcecodeandtranslatesallofitatoncetomachine code.Apureinterpreter,incontrast,translatesthehighlevellanguagestatementsoneatatime.Allelse beingequal,apureinterpreterrunsthesamesourcecodesignificantlyslowerthanapurecompiler.However,theinterpreteryieldsamuchmorecompactresult,occupyingafractionofthecodespaceinthetarget machinerequiredforitscompiledequivalent.Thereare,intherealworld,fewpurecompilersandfew pureinterpreters,andMBasicfallsonthecontinuumbetweenthetwoextremes,albeitclosertotheinterpreterendthanthecompilerend,adecisionnecessitatedbythesmallcodeandvariablesizeinPICs.Ifyou examinetheintermediateassemblerfileoutputfromasimpleprogram,youwillfindtheMBasicstatements areconvertedtotokensandorderedaccordingtoReversePolishNotation,whichwillbefamiliartothose havingusedanolderHewlett-Packardhandheldcalculator. 25
Chapter2 Let’slookataverysimpleexampletoillustratehowMBasicconvertsastatementintoRPNtokens.Here’sa simplemathematicalexpressioninMBasic: Ax Bx Cx Dx Ex Fx Gx
var var var var var var var
byte byte byte byte byte byte byte
Gx=Ax+(Bx-Cx/Dx)-Ex*Fx
Theresultingassembleroutput,extractedfromtheASMfile,aftercompilingunderMBasicversion5.2.1.1 (removingnonessentiallines)fromtheMBasicis: retlw_VARP32 retlwHIGH0848h;AX retlwLOW0848h;AX retlw_VARP32 retlwHIGH0849h;BX retlwLOW0849h;BX retlw_VARP32 retlwHIGH084ah;CX retlwLOW084ah;CX retlw_VAR retlwHIGH084bh;DX retlwLOW084bh;DX retlw_DIV retlw_SUB retlw_ADD retlw_PUSH32 retlw_VARP32 retlwHIGH084ch;EX retlwLOW084ch;EX retlw_VAR retlwHIGH084dh;FX retlwLOW084dh;FX retlw_MULL retlw_SUB retlw_PUSH32 retlw_ADDRESS retlwHIGH084eh;GX retlwLOW084eh;Gx retlw_LET
Wewon’tspendalotoftimeonthistopicandwillsaveforlaterdiscussionseveralimportantconcerns,but let’sgothroughitquickly.Retlwstatements(returnliteralinthewregister)returnaliteralvaluetothe callingfunction;forexample,retlw1returnsthevalue1whenitiscalled.(Ifyoucompilethisstatement underversion5.3.0.0,theretlwstatementsarereplacedbychip-specificmacrocalls,butthecodestructure remainsthesame.) Thestatementgroup:
retlw_VARP32 retlwHIGH0848h;AX retlwLOW0848h;AX
canbeunderstoodtoaccomplishplacingthevalueoftheMBasicvariableAxintoaformusablebyMBasic’smathematicallibrary. Thestatementretlw_DIVinstructsMBasic’smathematicallibrarytoexecutethedivisionoperatoronthe twovaluesimmediatelyprecedingit. Basedonthisunderstanding,wecansimplifythemeaningoftheassemblercode: AX BX
26
MBasicCompilerandDevelopmentBoards
CX DX DIVIDE SUBTRACT ADD EX FX MULTIPLY SUBTRACT Gx LET(=)
Parenthesesmayhelpshowhowthisisevaluated,anditwillbeimmediatelyclearifyouhaveusedanHP calculatorwithRPN: AXADD(BXSubtract(CXDXDivide))Subtract((EXFXMultiply))(GX=) Or,Gx=Ax+(Bx-Cx/Dx)-Ex*Fx
References Thefollowingtworeferencesarelongoutofprint,butmayturnupfromtimetotimeinusedbookstores. [2-1] BASICReference,PersonalComputerHardwareReferenceLibrary,ThirdEd.,(May1984).Anyof IBM’sBASIChandbooksfromthelate1970’stomid‘80sareworthacquiringastheydocument,in IBM’sexceedinglythoroughfashion,thenutsandboltsofBASICprogramming.Obviouslysomeofthe informationishighlyspecifictoPCsoftheera,butasurprisinglyhighamountofinformationisdirectly applicabletoMBasic. [2-2] Nagin,PaulandLedgard,Henry,BasicWithStyle—ProgrammingProverbs,HaydenBookCompany, RochellePark,NJ(1978).Thisthinvolumeispackedwithmoregoodadviceonprogrammingthan mostbooksthreetimesitssize.Itisn’tasmucha“howtocode”bookasitisa“howtothinkaboutcoding”book,andisthusthatmuchmorevaluable,as“howtocode”booksareplentiful. [2-3] Brown,P.J.,WritingInteractiveCompilersandInterpreters,JohnWiley&Sons,NewYork,NY(1979). [2-4] Aho,A.V.,etal,CompilersPrinciples,TechniquesandTools,Addison-WesleyPublishingCo.,Reading, MA(1986). [2-5] PIC12629/675DataSheet,MicrochipTechnology,Inc.,DocumentNo.DS41190C(2003). [2-6] PIC16F87XDataSheet,MicrochipTechnology,Inc.,DocumentNo.DS30292C(2001).
27
3
CHAPTER
TheBasics–Output AgreatdealofyourworkwithPICswillinvolveturningthingsonandoff.Theactionmaybeassimple asilluminatinganLEDtoshowprogramstatus,orascomplexassequencingmultiplemotors.Youmay accomplishtheseactionswiththePIC’sinput/outputpins,unaided,orwithexternalelectronicorelectromechanicaldevices.Theactionmayrequire“sourcing”or“sinking”currentorvoltage.Ahighstatepinsources Current I currentintoanexternalload,whilealowstateoutputpinreceivesorsinkscurrent fromanexternalload.Inthischapter,wewillreviewafewelementaryelectronics principlesandlearnhowtousethemtoallowPICstocontrolexternaldevices. ThischapterdealswiththeelectroniccharacteristicsofPICpinsasoutputdevices. R
Diagramsanddiscussionsinthisbookassumepositiveorclassicalcurrentflow,in V whichcurrentflowfrompositivetonegative,asshowninFigure3-1.Traditional circuitequations,aswellasthearrowsymbolfordiodesandtransistorsfollowthis conventionaswell. Figure3-1:Conventional Beforebuildinganyofthesamplecircuitspleasedownloadandreadtherelevant CurrentFlow datasheetsfromthedevicemanufacturer’sInternetwebsite.(TheCD-ROMsuppliedwiththisbookalsocontainssomedatasheets.)Tokeepthischapteratamanageablelength,I’vehadto glossovermanysubtletiesinthespecificationsandapplicationofthesedevices,hittingonlythehighlights. Carefuladvancestudyofdatasheetsandanyassociatedapplicationnoteswillreducethetimespentdesigninganddebuggingyourdesigns.
PinArchitectures Atfirstglance,Microchip’ssimplifiedschematicoftheI/Opinsmayseemconfusing.Chapter3ofthe 16F87xReference,forexample,requirestenfigurestoillustratetheinternalsofI/Opinconstruction.Atthe beginningandintermediatestagesofprogrammingwithMBasicandconcentratingonlyontheoutputmode, though,wecansimplifythingsfurther,reducingtheessentialstothoseofFigure3-2.Inthe16F87xseries, andinothermid-rangePICs,wheninoutputmode,pinsareconnectedtoaclassicalcomplementarymetal oxidesemiconductor(CMOS)configuration.Insomecases,suchasforRA0…RA3,Microchip’sdocuments showtheCMOStransistorsdirectly;inothers,suchasRB0…RB3,theyarenotshownbutareimbeddedin alogicgatesymbol. Formanypurposes,wecanregardthePMOSandNMOStransistorsofFigure3-2assimplyswitched resistors;theyareeitherveryhighresistances,amountingtoalmostopencircuits,oralowvalueresistor,as illustratedinFigure3-3.Whentheoutputislow,thepinappearstobealowvalueresistor,approximately25 ohms.Whentheoutputishigh,thepinappearstobetheVDDsourceconnectedthroughresistorofabout85 ohms,aslongasthesourcedcurrentdoesn’texceed15mAorso.
28
TheBasics–Output Vdd Simplified PIC Output
Figure3-2:Simplified outputpin.
Simplified PIC Output Pin RA4-T0CKI Pin Only
Vdd
External Pull Up
PMOS PIC Internal Driver Circuitry
I/O_Pin
PIC Internal Driver Circuitry
I/O_Pin
NMOS
NMOS
External Pull-up Resistor Required if Logic High to be Outputted
WhenusingBasicMicro’sdevelopmentorprototypeboards,the74HC4053 multiplexerneededtopermitin-circuitprogrammingaddsapproximately 50–100ohmsseriesresistancetopinsRB4,RB6andRB7.Inmanycases thisadditionalresistancecanbeignored. Onepin,RA4,isdifferent;itisconfiguredasanopendrainMOSFET. Whensettolow,itperformsidenticallywiththeotherpinarchitectures. However,whensettohigh,thereisnointernalconnectionwithVDDand henceitwillnotdirectlysourcevoltage.Ifit’snecessarytouseRA4asa sourcingoutputpin,youcanaddanexternal“pull-up”resistor,typicallyin therangeof470ohms–4.7Kohms.Thesourcedcurrentthencomesfrom thepull-upresistor.UnlikeallotherpinsthatcannotexceedVDD,RA4’s opendrainisratedto12volts.
Vdd
85
When Pin=High
PIN
When Pin=Low 25
Simple Model of PIC's I/O Pins When Set to Output
Wheneithersourcingorsinkingcurrent,thesafeoperatinglimitsofthePIC Figure3-3:Formanyanalyses, theoutputpinsappeartobe mustbeobserved.Thefollowingmaximumsafeparametersapplytothe simpleresistors. 16F87xseries,andtheElectricalCharacteristicssectionofMicrochip’sdata sheetforyourtargetPICshouldbeconsulted.Exceedingtheselimitsmay causedamagetothedevice,orreduceitsreliability. Symbol VOD
IOK
AbsoluteMaximumRatingsfor16F87XPICs Characteristic MaximumValue Units Conditions Opendrainhighvoltage 14 V AppliestopinRA4only Voltageonanypinwithrespect -0.3Vto V toVss VDD+0.3V TotalchipsupplycurrentintoVDD 250 mA supplypin TotalchipcurrentoutofVSSpin 300 mA Outputclampcurrent(VfVDD) Maximumoutputcurrentsunkby 25 mA anyI/Opin
29
Chapter3 Symbol
AbsoluteMaximumRatingsfor16F87XPICs Characteristic MaximumValue Units Conditions Maximumoutputcurrentsourced 25 mA byanyI/Opin MaximumcurrentsunkbyPortA, 200 mA PortDandPortEarenot PortBandPortE,combined implementedon16F873/876 devices Maximumcurrentsourcedby 200 mA PortDandPortEarenot PortA,PortBandPortE,combined implementedon16F873/876 devices MaximumcurrentsunkbyPortC 200 mA PortDandPortEarenot andPortD,combined implementedon16F873/876 devices MaximumcurrentsourcedbyPortC 200 mA PortDandPortEarenot andPortD,combined implementedon16F873/876 devices
Beforestartingourcircuitdiscussion,let’sreviewthesemaximumratings. Opendrainhighvoltage—RA4isuniqueandomitstheinternalPMOStransistorconnectiontoVDD.VODis maximumsafevoltagethatmaybeappliedtoRA4. VoltageonanypinwithrespecttoVss—Inthenormalcircuit,VSSwillbeatgroundpotential.Yourcircuit shouldbedesignedsothatwheninoutputmode,pinswillnotbetakenmorethan0.3Vnegativewith respecttogroundnormorethan0.3VabovethePIC’spositivesupplyvoltage,VDD.Shouldthesevoltages besignificantlyexceeded,theprotectivediodesshowninFigure3-2willstarttoconduct,potentiallycausingthepinorchipmaximumcurrentlimittobeexceeded,unlessotherwisecurrentlimited. TotalchipsupplycurrentintoVDDsupplypin—Inadditiontosourcingcurrentlimitsonindividualpins,this parameterestablishesaglobalmaximumavailablecurrentfortheentirePIC.Itis,withnegligibleerror, thesumofallpinsourcingcurrents. TotalchipcurrentoutofVSSpin—Inadditiontosinkingcurrentlimitsonindividualpins,thisparameter establishesaglobalmaximumfortheentirePIC.Itis,withnegligibleerror,thesumofallpinsinking currents. Outputclampcurrent(VfVDD)—IfapinistakenaboveVDDorbelowground,itmustbecurrent limited,commonlywithaseriesresistor,sothattheoutputclampcurrentisnotexceeded. MaximumoutputcurrentsunkbyanyI/Opin—Themaximumsafesinkingcurrentwhenapinislow. Sinkingcurrentisnotinternallylimitedandisgovernedbytheexternalcircuitparameters. MaximumoutputcurrentsourcedbyanyI/Opin—Themaximumcurrentthatmaybesafelysourcedbya highpin.Internalcircuitrylimitssourcingcurrenttoapproximately25-30mAsoitissafe,butnotgood designpractice,tooperateanoutputpinintoashortcircuit. MaximumcurrentsunkbyPortA,PortBandPortE,combined—Anothercompositelimit,applyingtosinkingcurrentbyallPortsA,BandEpinscombined. MaximumcurrentsourcedbyPortA,PortBandPortE,combined—Anothercompositelimit,applyingto sourcingcurrentbyallPortsA,BandEpinscombined. MaximumcurrentsunkbyPortCandPortD,combined—Anothercompositelimit,applyingtosinking currentbyallPortsCandDpinscombined. MaximumcurrentsourcedbyPortCandPortD,combined—Anothercompositelimit,applyingtosourcingcurrentbyallPortsCandDpinscombined. Ahighoutputwillsourcebetween25and30mAintoashortcircuitindefinitely,butwhensinkingcurrent,themaximumsafecurrentratingmustbeobserved.Figures3-4and3-5illustratethetypicalvoltage
30
TheBasics–Output 1000
Typical E vs. I PIC Sourcing Current
5
800
Voltage Available at PIC Pin (V)
Voltage Developed on Pin (mV)
Typical E vs. I PIC Sinking Current
600
400
200
0
4
3
2
1
0
0
5
10
15
20
25
30
0
Current into PIC Pin (mA)
5
10
15
20
25
30
Current out of PIC pin (mA)
Figures3-5:TypicalEvs.Iforsourcingcurrent.
Figures3-4:TypicalEvs.Iforsinkingcurrent.
versuscurrentrelationshipfor bothsourcingandsinkingcurrent. Alsorememberthatwhenusing BasicMicro’s2840Development Board,pinsRB4,RB6andRB7are switchedthroughthe74HC4053 multiplexerwhichhasa25mA maximumcurrentlimit. Onefinalbitofterminologyand we’llbeontocircuitry.Figure3-6 showsthreepossibleswitchingconfigurations.Forclarity,thedrawing Figure3-6:Possibleswitchingconfigurations. showsamechanicalswitch.We,of course,willuseavarietyofelectronicsubstitutes. Lowsideswitching—Theswitchisbetweentheloadandground.Whenclosed,bothsidesoftheswitchare atgroundpotential. Highsideswitching—Theswitchisbetweenthevoltagebeingswitchedandtheload.Whenclosed,both sidesoftheswitchareattheswitchingvoltage. Isolatedswitching—Thereisnocommonconnectionbetweenthecircuitbeingswitchedandthecontrolling PIC.Manydevicessuitableforisolatedswitchingalso workforlowsideorhighsideswitching.
LEDIndicators InlearninghowtoprogrammingaPCinahighlevellanguage,thetraditionalfirstprogramwrites“HelloWorld”to thescreen.SincePICsdon’thaveascreen,thefirstMBasic programtraditionallyblinksanLED.We’lldothatideaone better,buildinguptofourstateswithoneLEDandonePIC pin.But,firstwe’llstartwithtwoLEDsandtwopinsas showninFigure3-7. 31
Figure3-7:LEDconnections.
Chapter3 Program3-1 i
var
byte
Fori=B0toB1 ;LEDsareonB0…B1 OutputI ;sowemakethemoutputs Next Main Fori=B0toB1 Lowi Next Pause1000 Fori=B0toB1 Highi Next Pause1000 GoToMain
;somewillilluminatewithalow
;somewillilluminatewithahigh
End
Thecodeisstraightforward;Afterdeclaringourindexvariablei,wesetpinsRB0…RB1tobeoutputswith theOutputprocedureinsideaFor…Nextloop.TheOutput(i)proceduretakesthepinaddressasitsargument,withirangingfromB0toB1,pre-definedinMBasicasthenumericaladdressesofpinsRB0…RB1. Wethensetthesepinstoalternatebetweenlowandhigh,with1second(1,000milliseconds)ineachstate usingMBasic’sHighandLowproceduresinsidetwoFor…Nextloops,eachfollowedbyaPause(1000) procedure.Anendlessloop(Main…GoToMain)causesthealternatinghigh/ lowstepstoberepeated. D1illuminatedwhenRB0low—WhenRB0goeslow,currentfromthe+5V supplygoesthroughseriescombinationofLEDD1,resistorR3andthe internalresistanceofRB0.LEDsmayberegardedasadevicethathave approximatelyaconstantvoltagedropfortypicaloperatingcurrentsinthe rangefrom1mAtotensofmA.Figure3-8illustrates,forcurrentlevels between1and50mA,theLED’svoltagedropisbetween1.7and2.2V. Withonlyasmallerror,wemayregardtheLEDasaconstantvoltagedevice,withabouta2Vdrop.(There’saslightdifferenceinvoltagedropfor differentoutputcolors,butforalmostallred,greenandyellowLEDs,we Figure3-8:E/Icurvetraceof maycalculatethecurrentlimitingresistorsassuminga2voltsdrop.) redLED.Horiz:0.5V/divVert: 5mA/div. WemaynowsolvethecurrentloopequationforthecircuitinvolvingD1,rememberingthatalowpinisfunctionallyequivalenttoa25ohmresistor:
5V=2V+250I+25I
rearranging
or
5V–2V+250I+25Iso3V=275I I=
3 = 10.9 mA 275
WhereIisthecurrentthroughtheLEDandseriesresistor. Moreoften,wewishtocalculatetheseriescurrentlimitingresistorneededforaparticularLEDcurrentI(in mA)wheretheLEDisonwhenthePICdrivingpinislow:
R3 =
3000 − 25 I mA
32
TheBasics–Output WefudgedabitbyassumingthevoltagedropacrossD1isconstantregardlessofcurrent,butthesesimple equationswillbewithin10%ofamoredetailedcalculation,morethanaccurateenoughfordeterminingthe currentthroughanLEDindicator. D2IlluminatedwhenRB1high—WhenRB1goeshigh,currentfromtheVDD(the+5VsupplyinBasic Micro’sdevelopmentboards)goesthroughseriescombinationofLEDD2,resistorR4andtheinternal resistanceofRB1.ThisisonlyaslightrearrangementofourearlieranalysisofD1,withtheinternal equivalentresistanceofthehighpinbeing85ohms.Hence, 5V=2V+220I+85I
rearranging
or
5V–2V+220I+85Iso3V=305I
I=
3 = 9.8 mA 305
WhereIisthecurrentthroughtheLEDandseriesresistor. Or,tocalculatetheseriescurrentlimitingresistorwheretheLEDisonwhenthePICdrivingpinishigh(inmA):
R4 =
3000 − 85 I mA
Inadditiontotheconstantvoltagedropfudge,thisanalysis assumesahighpinismodeledaccuratelybyasan85ohm resistorinserieswithVDD.AsFigure3-5shows,thisassumptionstartstofailasthesourcedcurrentexceeds15mAand theplotofIversusEdivergesfromastraightline. TwoLED’sononepin—WecanconnecttwoLEDstoone pinusingthecircuitswejustdevelopedasshowninFigure3-9.ThecurrentforeachLEDiscalculatedusingthe sameequationsforindividualpinconnections. Figure3-9:TwoLEDsononepin. Fourstatesfromonepin—UsingtheconnectionofFigure 3-10,it’spossibleforonepintoproducefourstatesin a2-pindualLED.(MostdualLEDshavetwopins,but somedualLEDshavethreepinspermittingthecircuitof Figure3-9tobeused.)Fairchild’sMV5491Atwo-pindual LEDisconfiguredasaredandgreenLEDinanti-parallel wherebycurrentflowinonedirectionprovidesredlight whiletheoppositedirectionprovidesgreenlight. InthecircuitofFigure3-10whenRB2ishigh,currentflows fromRB2throughD1andR2.WhenRB2islow,current flowsfromthe+5VsupplythroughR1,D2andissunkat RB2.Thesuggestedresistorsyield6.9mAcurrentforthe greenLED(D1)and8.6mAfortheredLED(D2). Figure3-10:Onepin,fourstates. It’spossibletogetathirdcoloroutofthisdesignaswell.By rapidlyswitchingbetweentheredandgreenLEDs,theeyeperceivesorange.Thefollowingcodefragment willaccomplishthis,switchingatapproximately100Hz. 33
Chapter3
Main HighB2 Pause5 LowB2 Pause5 GoToMain
Finallyifafourthcondition,LEDoff,isdesired,switchRB2toinput.Asaninput,RB2isessentiallyan opencircuit,andneitherD1norD2willbeilluminated.Thistrickwillnotworkwiththeconfigurationof Figure3-9,asbothdiodeswillilluminateinthatstate. Program3-2exercisesallfourstatesofFigure3-10’sdualLED. Program3-2 ;FourstatesfromonedualcolorLEDandonePICPin ;Assumesbi-colorLEDonRB2 ;Withvoltagedividercircuit i
Var
Byte
Main HighB2 Pause1000 LowB2 Pause1000 Fori=0to255 HighB2 Pause5 LowB2 Pause5 Next InputB2 Pause1000 GoToMain
;Green
;Red
;Orange
;noillumination
End
Program3-2firstilluminatesthegreenLEDfor1secondfollowedbyredfor1second,followedby2.5 secondsoforangewhenboththeredandgreendiodesaresequentiallyactivefor5ms.Finally,thediodeis darkfor1second.
SwitchingInductiveLoads Steppermotorsandrelaysarecommoninductiveloads switchedbyPICs.ConsiderthecircuitshowninFigure3-11 thatcontrolsasmallOmronG2RL-24relay. Fromintroductorycircuittheory,weknowthatwhencurrent flowsthroughaninductor,energyisstoredinitsmagnetic field.Whenthecircuitisswitchedoff,thestoredenergymust go“somewhere.”Whathappens,ofcourse,isthecollapsing magneticfieldcausesavoltagespike—hundredsofvolts eveninathesmallG2RL-24relay—atthecollectorofQ1. Intheabsenceofprotectivecircuitry,Q1willtemporarily Figure3-11:Switchinganinductiveload. breakdownwhenthespikeexceedsitsVCEOrating(40V fora2N4401)andthestoredenergyisdissipatedinQ1.EvenifQ1isn’tdamagedbytherepeatedover-voltage breakdown,gooddesignpracticesaysthatweshouldlimittheovervoltagetosafelimits.Fortunately,asshown 34
TheBasics–Output inFigure3-12it’seasytoaddaprotectivediode.D1iscalled a“clampingdiode”becauseitclampsthevoltagespike.You mayalsoseeitreferredtoasa“snubbingdiode”or“snubber.” WhenthemagneticfieldcollapsesasQ1isswitchedoff,the inducedvoltagecausesdiodeD1toconduct,andthestored energyisdissipatedintheinternalresistanceoftheinductor, R1inFigure3-12,andanoptionalexternalresistor,R3. Aswithmanythingsinelectronics,thereisatradeoffhere. Thecurrentresultingfromthemagneticfielddecaydoesn’t droptozeroinstantaneously,butratherasafunctionofthe totalresistanceintheD1-R3-R1circuit.Thefasterwemake thecurrentdroptozero(smallertheseriesresistance)the Figure 3-12: D1 and R3 are added protective higherthevoltagespike.Conversely,ifwelimitthevoltage components. spiketoitsminimumlevelbysettingR3atzeroohms, wefindthelongesttimefortheinducedcurrentto decay.Figure3-13illustrateshowthepeakvoltage spikeandcurrentdecaytimesinteractforthecircuit ofFigure3-12.Ifyouarefamiliarwithelementary calculus,thisrelationshipisobvioussincethevoltage EacrossaninductorofvalueLHenriesisproportional tothetimerateofchangeoftheinstantaneouscurrenti throughtheinductor: E=L
di dt
Afasterdecay(greaterdi/dt)meansmoreinduced voltageandviceversa. Ifweareconcernedwiththerelayreleasetime,we wantthecurrenttodecaybelowthereleasecurrent asquicklyaspossible.Thissuggestsahigherseries resistor,perhapswithaQ1possessingahigherVCEO Figure3-13:“Shutdownat15ms,currentandvoltage toaccepttheresultinghighervoltagespike.Perhaps vs.clampingcircuitresistance. moreofaconcernexistswithwhendrivingastepper motor.Wewishthemagneticfieldtocollapseasquicklyaspossiblewhencurrentisremovedfromawinding,particularlyifweareinterestedinrunningthemotornearitsmaximumstepspersecondrating. Forcriticalapplications,andparticularlyforsteppermotors,theclampingdiodeshouldbeafastswitching device,suchasaSchottkydiode.Alternatively,itispossibletouseaZenerdiode,settoavalancheuponturn off.BydelayingtheonsetofcurrentflowuntiltheZenerdiodeavalanches,significantlyfasterdecayispossible.(TheZenerisinserieswithD1,polarizedsothatD1preventsforwardcurrentflowthroughtheZener.) We’lllookatsteppermotordrivingcircuitsindetailinalaterchapter. Itispossibletocalculatetheinductivespikelevelanddecaytimeanalytically,butit’smucheasiertousea SPICEcircuitsimulationprogramsuchasLinearTechnology’sLTSpice.[Ref3-4] Theremainderofthischapterwon’tmentioninductivespikeprotection,unlessitisappropriatebecauseof devicecharacteristics. 35
Chapter3
LowSideSwitching SmallNPNSwitch Figure3-14depictsasimplelowsideswitch.WhenRB0ishigh, Q1isforwardbiasedintoconductionandcurrentflowsthroughthe load.Let’sworkthroughafewdesignconcernswiththissimple circuit.Wewillassumetheloadisa100ohmresistorandVis12 volts.Hence,thecurrentbeingswitchedis120mA.We’lltreatthe currentthroughthiscircuitasaconstantandignorethevoltagedrop acrosstheswitchingdevicetosimplifyourcalculations.Sinceour switchcircuitswilloperatewithavoltagedropofwellunder0.5V, oursimplificationswillnotintroduceappreciableerror. Figure 3-14: 2N4401 NPN low side switch. Voltagerating—WhenRB0islow,Q1appearsasanopencircuitandthushasthefullloadsupplyvoltageVacrossit.Ina transistordatasheet,themaximumvoltagethatmaysafelybeappliedinthismodeisVCEOormaximum collectortoemittervoltage,baseopen.Ourparticulardevice,a2N4401isratedfor40VVCEO.Itshould besafetouseituptoabout25volts,applyingareasonablesafetymargintotheratedvalue.Our12V switchingexamplewillbewellwithinQ1’sratings. Leakagecurrent—Whenthe2N4401iscutoff—thatis,thebasevoltageislessthanabout0.4V,someleakagecurrent,ICEX,willstillflowthroughthedevice’scollector.ICEXisratednottoexceed0.1µAinthe 2N4401,anegligiblevalueinthecontextofourcircuits. Saturationvoltage—Whenthebasedriveissufficienttosaturateabipolartransistor,thevoltagedropbetweenthecollectorandemitterisapproximatelyaconstant,referredtoindatasheetsasVCE(SAT),0.4V fora2N4401atcurrentlevelsnear100mA. Collectorcurrentanddevicepowerdissipation—The2N4401hasamaximumcontinuouscollectorcurrent ratingof600mA,andamaximumpowerdissipationratingof625mWatroomtemperature(25°C).The saturatedcollectorvoltage,VCE(SAT)is400mVat150mAand750mVat500mA.Thethermalresistance junctiontoambientRθJAis200°C/wattandthemaximumjunctionoperatingtemperatureis+150°C. We’llassumeadequatebasedrivetosaturateQ1,henceweexpectthecollectorvoltageat120mAtobe400 mVorless.We’llalsoassumeQ1istobeoncontinuously—continuouslyinthiscontextmeanslongenough forthermalequilibriumtobereached,amatterofafewsecondsfora2N4401sizedevice.Hence:
Thedevicedissipationwillbe120mA×400mV,or48mW. Thejunctiontemperatureriseoverambientwillthusbe200°C/watt×0.048watts,or9.6°C.Assumingtheambientairtemperatureis120°F(49°C),themaximumjunctiontemperaturewillthus be48°+9.6°=57.6°C.
Todeterminecasetemperature,weusethethermalresistancejunctiontocaseRθJCspecification,83.3°C/ watt.Thecasewillthusbeat83.3°C/watt×0.048watts,or4°Caboveambienttemperature.Ourdesignthus iswellwithinthesafeoperatingparametersofthe2N4401. Ifthe2N4401isbeingcycledoffandonatarapidrate,thedutycyclewillenterintocertainoftheseratings. Forexample,supposethe2N4401isdrivingamultiplexedLEDdisplay,onfor2msandofffor8ms,fora dutycycleof0.20.TheaveragepowerdissipationofQ1willthusbe20%ofthepeakpowerandthepermissiblepeakpowerdissipationlimitmaybeasmuchasfivetimesthecontinuousvalue.Ofcourse,forthis averagingeffecttowork,theontimemustbeshortcomparedwiththetimeittakesforthedevicetoreach thermalequilibrium.
36
TheBasics–Output Basecurrentdrive—Asaroughapproximation,wemayregardQ1asacurrentoperatedswitch—thatis,for everymilliampereofcurrentwewishtobesunkbyQ1’scollector,wemustinjectintothebaseacertain currentlevel.(Thisisahighlysimplifiedapproximationofsemiconductoroperation,butadequatefor ourpurpose.)TheratioofcollectorcurrenttobasecurrentisknownashFEor“DCcurrentgain.”The DCcurrentgainvariesfromdevicetypetodevicetype,isnotwellcontrolledfromexampletoexample ofthesamedevicetypeand,finally,varieswithcurrentevenforaparticulartransistor.2N4401devices, forexample,haveanhFEthatvariesfrom20to300,dependingonthecollectorcurrent. Ifwearenotconcernedwithswitchingtime,orpowerminimization,thesimplestdesignapproachistoassumetheworstcasehFEanddesignaccordingly.Tosink120mA,forexample,sincetheminimumspecified hFEat100mAis100,thetargetbasecurrentshouldbe1.2mA.However,wenotethatatboth500mAand 10mAcollectorcurrents,theminimumhFEdropsto40.Hence,asamatterofperhapsexcessivecaution,and toensureQ1isdrivenwellintosaturation,wewilldesignforhFEof40,representing3mAbasecurrent. Thebasetoemitterjunctionvoltage,VBE,fora2N4401isspecifiedat750mVforabasecurrentof15mAand collectorcurrentof150mA,sowewillusethisvalueincalculatingthebaseresistor,R2.(Sincethebaseto emitterjunctionismodeledasaforwardbiasedsilicondiode,700mVisacommonlyusedroughestimatefor thebasetoemittervoltageoverawiderangeofbasecurrentsforallsiliconbipolarjunctiontransistors.)R2’s value(neglectingthePIC’sapproximately85ohmseriesresistancewhensourcingcurrent)isthus: 5V − 0.750V R2 = = 1.4 kohm 0.003 A SwitchingSpeed—We’vealludedtoQ1’sswitchingspeed concernsseveraltimesinourdesign.Ifweareswitching anLED,orrelayorsteppermotor,theseproblemsare unlikelytoconcernus.However,therearetimeswhereit iscriticaltoswitchaloadasfastaspossible.Figure3-15 showswhathappenswhenveryshortswitchingintervals areusedinthecircuitofFigure3-14.RB0emitsafastrise andfall200nswidepulseandQ1turnsonwithlessthan 20nsdelay.However,whenRB0goeslow,Q1exhibits nearly500nsturnoffdelay.Theturn-offdelayresults fromthe“storedcharge”effect,whereexcessminority carrierchargeisstoredinthebaseregionofthetransistor Figure3-15:2N4401switchingtimeIbase=6 junctionstructureandmustberemovedbeforethetransis- mA,Ic=40mA;Ch1:PICpintobasedrive;Ch2: torturnsoffandcollectorcurrentceases.Weassumethat 2N4401collector. anyonedesirousofswitchingspeedsinthesub-microsecondrangeknowsaboutstoredchargesandthemitigatingtechniquestodealwiththeproblem. OnefinalpointshouldbenotedwiththebipolartransistordesignofFigure3-14—thevoltageVbeing switchedisimmaterial.Ofcourse,Q1mustberatedtowithstandthevoltage,butwithasuitabletransistor,thecircuitofFigure3-14couldswitch500voltsaseasilyasitswitches5volts.Thecurrentrequiredto saturateorcutoffQ1isnotaffectedbythevoltageitswitches.
SmallN-ChannelMOSFETSwitch Attheriskofconsiderableoversimplification,Q1inFigure3-14maybethoughtofasacurrentcontrolled switch;currentinjectedintothebasecausesthecollectortobepulledclosetogroundpotential.Thereis asimilarvoltagecontrolledswitch,theMOSFET,wherebyvoltageappliedtothedevice’sgatecausesthe drainvoltagetobepulledclosetothesource,orgroundpotentialinalowsideswitch. 37
Chapter3 Figure3-16istheMOSFETcounterpartofFigure3-14.A2N7000MOSFETcomparesfavorablywiththe2N4401inthemaximumpermissiblevoltage,witha60V rating.However,the2N7000isratedat200mAmaximumcontinuouscurrentand500 mAmaximumpulsedcurrentwithatotaldevicemaximumdissipationof400mW. Let’slookattheareasofdifferencebetweentheMOSFETand NPNbipolartransistor. Whensaturated,aMOSFETactslikealowvalueresistor betweenthedrainandsource,referredtoRDS(ON),withthecorrespondingvoltagebetweenthedrainandsourcedetermined bytheproductofthedraincurrentIDandRDS(ON).Recallthat inthe2N4401,thecorrespondingvoltageVCE(SAT)isapproximatelyaconstantvalueoverawidecurrentrange.
Figure3-16:2N7000NPNLowSideSwitch.
TherelationshipbetweenRDS(ON)andthegatevoltageis,asillustratedinFigure3-17,complex.Thepointtobetakenaway fromFigure3-17isthatsincewecandriveQ1’sgateonlyto +5voltswithahighonanoutputpin,weexitthesaturation regionwithonlymodestdraincurrent. Let’srunthroughthesame120mAsinkdesignwedidforthe 2N4401.We’vealreadydeterminedthatthe2N7000meets ouropencircuitvoltagerequirementsandthat120mAis lessthanthemaximumpermissiblecontinuousdraincurrent. Withagatedriveof+5Vand120mAdraincurrent,Figure 3-17showsRDS(ON)willbeabout3.2ohms.SinceVDSisthe IRdropacrossRDS(ON),wemaycalculateitas0.120A×3.2 ohms,or0.38volts,verysimilartoour2N4401NPNbipolar Figure3-17:2N7000predictedon-resistance transistordesign. ThepowerdissipatedinQ1equalsID×VDS,or0.38volts× 0.120mAor46mW,almostidenticalinvaluewiththe48 mWwefoundforthe2N4401bipolarswitchandwellwithin thedeviceratings.The2N7000’sthermalresistancejunction toambientRθJAis312.5°C/wattandthemaximumjunction operatingtemperatureis+150°C.Thetemperatureriseat thecasewillthusbe312.5°C/watt×0.046watt,or14.4°C. Assumingtheambientairtemperatureis120ºF(49°C),the maximumjunctiontemperaturewillthusbe48°C+14.4°C= 62.4°C,allquiteacceptablevalues.
variationwithgatevoltageanddraincurrent.
Ifweweretorepeatthisseriesofcalculationsfor,saya 400mAload,wewillfindRDS(ON)is3.6ohms,VDSis1.44 VandQ1’sdissipationis576mW,welloverthemaximum Figure 3-18: 2N7000 driven by PIC turn-on/ permissiblevaluefora2N7000.Theproblemisthat5Vis inadequategatevoltagetofullyturntheMOSFETat400mA. turn-offspeedCh1:PICoutput;Ch2:2N7000 drain.
Whenlookingatnanosecondswitchingwitha2N4401,we foundsignificantturn-offproblemsduetostoredcharge.AsFigure3-18shows,boththeturnonandturn offtimesfora2N7000arequiterespectable.But,acloseexaminationoftheleadingedgeofthePICoutput
38
TheBasics–Output foreshadowsthemaindifficultyofdrivingMOSFETs,gatecharge.Thesmallplateauorkinkintherisetime ofthePICoutputreflectsthefactthatthegateofaMOSFETbehaveslikeanonlinearcapacitiveloadtoits drivingcircuitry.Accordingly,theswitchingtimeperformanceisdefinedbytheabilityofthedrivingPIC tochangethegatevoltage.The2N7000’sgate,assuminga5Vgatedriveand120mAload,looksapproximatelylikea200pFcapacitor.WewillexamineMOSFETgatedrivingproblemswhenwelookatahigher powerdevice,theIRF510.Fornow,wesimplynotethataPICiscapableofdirectlydrivinga2N7000to quiterespectableswitchingspeeds.
HighPowerBipolarLowSideSwitching Boththe2N4401and2N7000arelowpowerdevices,goodforcontinuouscurrentsofafewtenthsofanampereatmost.Supposewe wishtoswitchanampereortwowithabipolartransistor. Inmostinstances,wewillnotbeabletobuildahighpowerswitch bysimplyreplacingthe2N4401withahighpowerdevice,asthe25 mAorsomaximumcurrentoutputofahighPICpinisn’tenough basedrivetoreliablysaturateasimplebipolarpowertransistor. ConsiderFigure3-19.TheTIP31’smaximumcurrentratingis3.0 A,butatthisleveltheminimumguaranteedhFEisonly10,so300 Figure3-19:Highcurrentswitchingwith mAbasedrivewouldberequiredforsaturation.Evenat1.5amperes TIP31. collectorcurrentthePICisshortofachievingfullsaturationwiththemaximumpossiblePICoutputcurrentasits basedrive(This,ofcourse,wouldrequirehFEtobeatleast 60.).Figure3-20showstheVCEis920mV,insteadofthe expected300mVshownintheTIP31’sdatasheetfor1.5A collectorcurrent. ADarlingtontransistorsolvesourbasedriveproblem.As reflectedinFigure3-21,aDarlingtontransistorusesone transistorasaemitterfollowercurrentboostertodrivethe baseofthesecondtransistor.TheDarlingtonconfigurationmayusetwoseparatedevicesor,asinthecaseofthe TIP120,thedrivertransistormaybeintegratedontothe samedieasthepowertransistor.ThecompositehFEofthe Figure 3-20: TIP31 at 1.5A IC Ch1: Base Ch2: DarlingtonpairisapproximatelytheproductofthehFE collector. ofthetwotransistors.Sincethedrivertransistordoesn’t handlehighcurrents,itshFEmaybeverylarge,thusensuringa compositehFEinthethousands.Foracollectorcurrentof1A,the TIP120’shFEisapproximately3300,permittingcollectorsaturation withabasecurrentofaslittleas300µA. Sofar,sogood.TheTIP120isratedat60VVCE,5Amaximum collectorcurrentICand65wattsdissipation,withanappropriate heatsink.ThepricetobepaidfortheextrahFE,though,isfound inthesaturationvoltage,VCE(SAT).ForanICof3A,VCE(SAT)is2.0V whileat5A,VCE(SAT)is4.0V.AquickglanceinFigure3-21reveals whyVCE(SAT)issopoor.ThedrivertransistorreliesuponVCE(SAT)as Figure 3-21: Switching with TIP120 itssourceofcurrenttosupplybasedrivetotheoutputtransistor. Darlington.
39
Chapter3 Recallthatthebaseoftheoutputtransistor’sbasemustbe atabout0.7Vaboveitsemitterbeforebasecurrentflows. And,thedrivertransistoritselfintroducesanother0.4Vor sominimumvoltagedropevenifitissaturated.Hence,if VCE(SAT)dropsbelow1.1V,thedrivertransistornolonger cansupplybasecurrenttotheoutputstage. Anotherareaweexpecttoseeaperformanceproblemwith theDarlingtonisturnofftimeaspowertransistorsare slowerthanthesmallswitchingdeviceswehavelookedat sofar.Figure3-22confirmsourpessimism,astheTIP120’s turnofftimeisnearlytwomicroseconds.However,we shouldrememberthatformanyapplications,2µsturnoff Figure3-22:TIP120turnofftimeCh1:PICoutput; timeismorethanadequate. Ch2:TIP120collector.
CalculatingthebaseseriesresistorRbase,andtheother parametersfollowtheapproachusedforthe2N4401andwon’tberepeated.However,attentionmustbe paidtoproperheatsinkselectionforpowerdevices.AlthoughtheTIP120isratedat65wattsdissipation, thatvaluepresumesanadequateheatsink.Absentaheatsink,itsratingisonly2watts.Operatingwithouta heatsink,incontinuousoperation,aTIP120shouldnotsinkmorethan1Aorso—andeventhatispushingit.
HighPowerMOSFETLowSideSwitching IRF510Switch Justastherearehighpowerrelativesofthe2N4401,the2N7000hasmanybigbrothersaswell.We’ll quicklyexamineoneoftheoriginalpowerMOSFETsbutthenturnourattentiontoanewpowerMOSFET devicethatsolvesmanyoftheshortfallsofearlierdevices. TheIRF510isoneoftheearliestinexpensivepowerMOSFETsandisstillinproduction.It’sratedat100V VDS,maximumIDof5.6Aandapowerdissipationof43watts,assumingproperheatsinking.Itissupplied inaTO220package.RDS(ON)isunder1ohmatroomtemperature.(Moderndevicesareinthetensofmilliohmrange,butwe’llstickwiththeIRF510toillustratethepointongatevoltageconcerns.) WhenwesubstitutetheIRF510forthe2N7000,asshowninFigure3-23againwearelimitedto5Vgate drive.IfweconsulttheRDS(ON)versusgatevoltageandcurrentplotofFigure3-24,weseethatfor5VVGSand
Figure 3-24: IRF510 predicted on-resistance variationwithgatevoltageanddraincurrent.
Figure3-23:LowsideswitchingwithIRF510.
40
TheBasics–Output 1AID,weexpectRDS(ON)tobeabout0.5ohm.But,supposewewishtosink3.0Aofcurrentrepresenting,saya 12voltsupplyanda4ohmload,wellwithintheIRF510’sratings.AsFigure3-24shows,theminimumVGSto obtainsaturationat3Aexceeds5V.Ifallwehavetodrive thegateisthe+5VhighfromourPIC,RDS(ON)willbemany ohmsindicatingtheIRF510isoutofsaturationandoperatinginthelinearregion.Infact,undertheseconditionswith VGS=5VwewillfindVDSapproximately6.2VandID1.4A. TheIRF510willdissipate8.6wattsanditsRDSis4.4ohms. IfweexpectedtheIRF510toactasasaturatedswitch,with anRDS(ON)ofafewtenthsofanohm,wewillbeinfora surprise.And,ifourdesigndidn’tuseaheatsinkbecauseit wasn’tnecessarywithalowRDS(ON),we’llhaveanevengreater surpriseastheIRF510destroysitselffromoverheating. Finally,roundingoutthedifficultiesindrivinganIRF510 directlyfromaPIC,weseetheexpectedturnonproblem. Figure3-25showsnearly750µsturnondelay.
Figure3-25:PICOutput;Ch2:IRF510Drain.
IPS021Switch ManysuppliershaveaddressedtheshortcomingsseenwhenweexaminedtheIRF510.We’lllookatone particulardevice,InternationalRectifier’sIPS021intelligentpowerMOSFETswitchwhichisratedat50V VDSandhasseveralinterestingfeatures: • Logiclevelinputwithbuilt-involtagemultiplierandlevel convertertoensuresaturationoftheswitchingMOSFET; • RDS(ON)0.125ohmsorlessatroomtemperatureand5V input; • Over-temperatureprotectedwithautomaticshutdown; • Over-currentprotected,at5.5Anominal; • Built-insnubbingprotectionforinductiveloads. TheIPS021issuppliedinaTO-220packageandhasthesame pinconnectionastheIRF510.Inalmostallcasesitcanbe Figure3-26:LowsideswitchingwithIPS021 intelligentpowerswitch. directlysubstitutedforanIRF510withlittleornochangein circuitdesignorphysicallayout.AsshowninFigure3-26, isconnectedinthesamefashion.InternationalRectifier recommendsaseriesresistorof500ohmsto5Kohms betweenthedrivingpinandtheinputpinoftheIPS021, althoughitmaynotbenecessaryinallcases. What’snottolikeabouttheIPS021?Themainissueis switchingspeed,withturn-onandturn-offspeedsinthe severalmicrosecondrange.Formanypurposes,wherea fewmicrosecondsofturn-onorturn-offtimeisimmaterial, theIPS021isagoodchoice.Figure3-27showsexcellent performanceinswitching1.5AinthecircuitofFigure3-26. Theseriesresistanceof240milliohmscomputedfrom Figure3-27includeswiringandplugboardcomponentsas Figure 3-27: IPS021 Switching 1.5A Ch1: PIC wellastheIPS021’sRDS(ON). Output;Ch2:IPS021Drain.
41
Chapter3 HighSideSwitching SmallPNPSwitch Figure3-28depictsasimplehighsideswitch.WhenRB0is low,Q1isforwardbiasedintoconductionandcurrentflows throughtheload.Let’sworkthroughafewdesignconcerns withthissimplecircuit.Wewillassumetheloadisa47ohm resistorandVis2volts.Hence,thecurrentbeingswitchedis approximately45mA. Wecalculatethebaseresistorandpowerdissipationexactlyas foralowsideswitch,butwemustbecarefultoselectthecorrect voltagesources.The2N4403hFEat–2VVCEand–150mAICis specifiedataminimumof100.Wewillwishthebiascurrentto Figure3-28:2N4403PNPhighsideswitch. beatleast450µA.(InaPNPtransistor,thecollectorisnegativewithrespecttotheemitter;hencethesignofthevoltages andcurrentsarereversedfromtheNPNcase.)When conducting,thebasebiassource(RB0)isat0voltsandthe emitterisatVvolts(2.0Vinourdesignexample)positive. Henceinourexamplethevoltagetodrivethebasecurrentis 2.0V.Wewillusethestandard700mVassumptionforQ1’s base-emitterjunctionvoltagedropandwe’llignoreRB0’s 26ohmequivalentoutputresistancewhenlow.Hence,the netvoltageacrossRbaseis–2.0V+0.7Vor–1.3V.To obtain450µAcurrentflow,Rbaseshouldbe1.3V/450×10–6 or2.9Kohm.Ifwewishtoensuresaturationundervarying temperaturesandcomponenttolerances,wewillincreasethe basecurrentto,say750µA(Rbasecalculatedas1.7Kohm) Figure3-29:2N4403PNPhighsideswitchCh1: andusetheneareststandard5%resistorvalue,1.8Kohm. PICOutput;Ch2:2N4403collector. Figure3-29showsourdesigninoperation. Inlow-sideNPNtransistorswitchingdesign,thevoltagebeingswitchedwasimmaterial,aslongasthetransistorwaswithinitsratings.WhenRB0isatground,theNPNtransistorisreversedbiasedandhencecutoff; boththeemitterandcollectorareatthesamepotential,groundsothereisnovoltagedifferencebetweenthe baseandemitter.LookingatthePNPhighsidecircuitwhenRB0ishighandwewishQ1tobecutoffshows adifferentstory,however.Supposewewishtohighsideswitch 12VandRB0ishigh,at5V.TheendofRbaseconnectedto Q1’sbaseisonebase-emitterdiodedroplowerat+11.3Vwhile theendconnectedtoRB0isat+5V.Hencecurrentwillflow outQ1’sbase-emitterjunction;Q1becomesforwardbiasedand willconduct.Thisisthecentralprobleminhighsideswitching withaPNPtransistororapositiveMOSFET(PMOS);wemust haveavailablecontrolvoltagesatleastequaltothevoltageto beswitchedinordertoturnoffthedevice. TocontrolahighsideswitchexceedingthePIC’sVDD,wemay modifythecircuitofFigure3-28byaddingan2N4401NPN Figure3-30:UsebothPNPandNPNtransistors transistortocontrolthebaseofQ1,asshowninFigure3-30. toimplementhighsideswitch.
42
TheBasics–Output WhenRB0ishigh,Q2isforwardbiasedanditscollectorisessentiallyatground(VCE(SAT)isaround400 mV).Q1isthenbiasedintoconductionbycurrentflowingthroughR2andQ2.WhenRB0islow,Q2iscut offandmayberegardedasanopencircuit.Hence,Q1’sbaseispulledto12VbyR1,makingVCEzero,cuttingQ1off.ThevaluesgiveninFigure3-30provide–0.9mAbasedrive,morethanadequatetosaturateQ1 fortheloadcurrent.Notethataddingthe2N4401driverinvertsthecontrolsensecomparedwiththecircuit ofFigure3-28.
HighPowerHighSideSwitching RatherthanduplicatethelowsideswitchingdiscussionbutwithahighpowerPNPtransistors,orPMOS devices,wewillimmediatelyjumptoanintegratedhighsideMOSFETswitch,InternationalRectifier’s IPS511.TheIPS511isamemberofIR’sintelligentpowerswitchfamily,butwithsomefeaturesnotincludedintheIPS021weearlierexamined.(Ifyouwishtoexperimentwithahighsideversionoftheearlierlow sideswitchingdesigns,aTIP125isthePNPcomplementoftheTIP120DarlingtonandaTIP32isthePNP complementoftheTIP31.Finally,aBS250Pisagoodp-channelanalogofthe2N7000andanIRF9510is thep-channelcomplementoftheIRF510.) Ifyouconstructhighsideswitcheswithp-channeldevices,youwillsoondiscovertheyexhibitlimited operatingrangewhenthegatevoltageswingislimitedtothe0…5Vavailablefromadirectconnection toaPIC’soutputpin.ToreliablyturnoffanIRF9510with a5Vgateswing,forexample,requiresittobeswitching lessthanapproximately8volts,whiletoensurethedevice issaturatedrequiresittobeswitchingatleast4.5volts.In thehighsideswitchingconfiguration,VGSequalsthevoltage beingswitchedminuseither0V(PICatlow)or5V(PICat high).SinceVGSmustbeatleast–4.5VtotobringRDS(ON)to reasonablelevels(turn-on;PICoutputislowsoVGis0V)the minimumvoltagetobeswitched(VS)mustbe4.5V.Conversely,toensureturnoff,VGSmustbeatleast–3Vwhenthe Figure 3-31: Suggested 2N7000/IRF9510 high PICoutputishigh.Whenhigh,VGis+5V,soVScan’texceed sideswitch. +8V.Hence,anIRF9510highsideswitchwithitsgatedriven directlybyaPIC’soutputpinisoflimitedpracticaluse.Anauxiliaryn-channelgatecontroldevicewillbe necessaryinmostcases,suchasthe2N7000showninFigure3-31.ToavoidexceedingtheIRF9510’sVGS limit,themaximumvoltagebeingswitchedmustnotexceed20V. TheIPS511isamuchcleaneralternativeandoffersmanyusefulfeatures,including: • Logiclevelinputwithbuilt-involtagemultiplierandlevelconvertertoensuresaturationoftheswitchingMOSFET; • RDS(ON)0.135ohmsorlessatroomtemperatureand5Vinput; • Over-temperatureprotectedwithautomaticshutdown; • Over-currentprotected,at5.0Anominal; • Built-insnubbingprotectionforinductiveloads. • Statusfeedbackreportingofnormaloperation,openload,overcurrentandovertemperature. TheIPS511isavailableina5-pinTO220packageandisratedat50VVDS.Figure3-32showsatypicalconnection.AswithIR’sIPS021lowsideintelligentswitch,theIPS511providescrisp,lowdropswitchingas seeninFigure3-33.RiseandfalltimesfortheIPS511arewellunder100µs. UnliketheIPS021,theIPS511hasastatuspinwhich,whenreadinconjunctionwiththeInandOutpins ontheIPS511,providesusefulinformation.InFigure3-32,theoutputvoltageissensedthroughavoltage 43
Chapter3
Figure 3-33: IPS511 switching 50mA Ch1: PIC output;Ch2:IPS511drain.
Figure 3-32: High side switching with IPS511 intelligentpowerswitch.
dividerconsistingofR3andR4,assuming,asislikelythecase,theIPS511isswitchinggreaterthan5V.ApplyingOhm’slawandsummingthevoltagedrops,ifwewishthevoltageatRB2tobe5V,wecanstatethe relationshipbetweenR3,R4andVOUTas: V R R3 = OUT 4 − R4 5 SincenosignificantcurrentflowsintoaPICinputpin,wemayselectR4assomeconvenientvalue,say10K. VOUTwillbeonlyafewtenthsofavoltdifferentfromV1,sowemayuseV1insteadofVOUTinourcalculation.AssumeV1is12V.WecalculateR3as: 12 × 10, 000 − 10, 000 = 14, 000 5 Theneareststandard5%valueis15K.
R3 =
Ifwewishtodetectanopenloadcondition,wemustalsoinstallthepull-upresistorR5.R5’svaluedepends, inpart,upontheloadresistanceandtheacceptabilityoftheresultingparasiticcurrentthroughtheloadwhen theIPS511isoffaswellasthevaluesofR3andR4.Let’sassumeRloadis12ohms.IfwesetR5to1200 ohms,100timesRload,theparasiticcurrentwillbenotmorethan1%ofthenormaloncurrentandthe voltageacrosstheloadwillbelessthan1%ofV1.Formanypurposes,thiswillbemorethanacceptable.If theloadshouldbecomeanopencircuit,thenwhentheIPS511isoffthevoltageatRB2willthenbederived throughavoltagedividerwherethetopresistorconsistsofR3inserieswithR5.IfwecankeepR5toapproximately10%ofR3,wewillstillmaintainagoodhighconditiononRB2.R3is15K,soaslongasR5is atleast1500ohms,wehavemetthisobjective.Hence,wemaypickR5as1300ohms,astandard5%value betweenourminimumdesiredvalueof1200ohmsandourupperobjectiveof1500ohms.Wecanquickly checkthevoltageatRB2underthefourpossibleconditions: InState H H L L
VoltageatRB2UnderConditionsofLoadStatus Load RB2Voltage RB2Status Normal 4.8 H Open 4.8 H Normal 0.1 L Open 4.6 H
44
TheBasics–Output Aswewilllearnlater,whenaninput,themaximumvoltagelevelaPICisguaranteedtobereadasalowis0.8V, whiletheminimumvoltagethatwillbereadasahighis2.0VonaPortBpin,assumingVDDisintherange4.5 V…VDD…5.5V.Hence,RB2willbereadaslowonlyundertheconditionatthethirdlineinthetable. TodeterminethestatusoftheIPS511wewouldimplementthefollowingpseudo-code: ;PossibleroutinetoreadstatusofIPS511 ;AssumesconnectiontoPICasatFig3-32 ; Status var PortB.Bit1 Load var PortB.Bit2 InputB1 InputB2 ; Main HighRB0 Pause2
;turnontheIPS511andapplypowertoload ;DelaytoensureIPS511isfullyon
;nowcheckthestatuswhentheIPS511shouldbeon If(Status=1)AND(Load=1)ThenGoSubNormalOn If(Status=0)AND(Load=0)ThenGoSubOverload
LowRB0 ;turntheIPS511off Pause2 ;nowcheckthestatuswhenoff If(Status=0)AND(Load=0)ThenGoSubNormalOff If(Status=1)AND(Load=1)ThenGoSubOpenLoad
NormalOn;SubroutineifallisOKattheloadwhenon ;------ CodetobeexecutedifresultisOK Return NormalOff;SubroutineifallisOKatloadwhenoff ;------- CodetobeexecutedifresultisOK Return OpenLoad;Subroutinetobeexecutedifloadisopen ;------ Codetobeexecutediftheloadisopen Return OverLoad;Subroutinetobeexecutedifexcessivecurrent ;---------- orovertemperature Codetobeexecutedforovercurrentcondition Orovertemperaturecondition.Determinethedifference Betweenthetwobycheckingforcyclingorsteadystate LowonLoad IfLoadiscycling—problemisovertemperature Return
Separatingcertainfaults,suchasovertemperatureandovercurrentmayrequirerepeatedpollingofthestatusandoutputpinstodeterminewhetherthefaultperiodicallyclearsitself(asthedevicecoolsdownandthe thermaltripresets)orremainsstatic.Additionally,iftheonsetofcurrentlimitingmustbedetecteditmaybe necessarytoalterR3,R4andR5tocauseabnormallylow,butnotzero,voltageacrosstheloadtoreadasa lowonRB2.
IsolatedSwitching Althoughwewilldiscussavarietyofdevicesundertheisolatedswitchingcategory,ofcoursethesemay alsobeusedforlowsideorhighsideswitching.
45
Chapter3 RelaySwitching Relayspre-dateelectronics,astheyweredevelopedtoextendtherangeofmanualMorsetelegraphsystemsin themid1800s.Nonetheless,weshouldnotquicklydiscardtherelaysolutiontoswitching.Relaysareavailable inarichvarietyofcontactconfigurations,contactmaterial,powerrating,voltageratingandcoilrating.
• • • •
Goodthingsaboutrelays Resistanttodamagefromoverloadsandpolarity reversal Excellentisolationbetweenswitchedloadand controllingcircuitry Widerangeofratings CanswitchAC,DC,video,RF,lowlevelaudio,etc. byproperselectionofdevice.
• • • • • •
Notsogoodthingsaboutrelays Limitedlife,althoughmanyrelaysareratedfor tensofmillionsofoperations Noise Speedofoperationandrelease,usuallyinthe millisecondrange. Sizemaybeanissue Contactbounce Requirespowertoholdrelayoperated,unlessitis alatchingrelay.
We’lllookatthreerelays: Make/Model StandexJG102-12-1 OmronG5V-2-H1
CoilRating 12V/24mA 12V/12.5mA
Contact Configuration SPST(1A) DPDT(2C)
OmronG2RL-24
12V/33.3mA
DPDT(2C)
ContactRating 48V/1A 125VAC/0.5A 30VDC/2A 250VAC/8A 30VDC/8A
Comments Veryhighspeedreedrelay Lowsignalrelaywithbifurcated contacts;ultrasensitive General-purposepowerrelay
Totestthecontactclosureandoperate/releasetime,we’ll usethecircuitofFigure3-34.Figure3-34shouldbe familiar;a2N7000lowsideswitchdrivestherelaycoil. Asweearlierdetermined,thecurrentandvoltagerequired tooperatetherelaysundertestiswellwithinthelimits fora2N7000.Tosensecontactclosureandbounce,we usea5Vsourceinserieswitha56ohmresistortopass approximately90mAthroughthecontacts.Inorderto makemeasurements,V2’snegativeterminalisconnected toground;butinordertoemphasizetheabilityofrelays toswitchisolatedcircuits,Figure3-34showstheloadin Figure3-34:Relaytestcircuit. itsmostgeneral“floating”form. Sincearelaycoilisaninductiveload,wemustuseasnubbingdiodetoavoiddamagingthe2N7000.To illustratethevoltagespikeevenasmallinductiveloadgenerates,compareFigures3-35and3-36.Withoutasnubbingdiode,theinductivespikeexceeds76V,atwhichpointthe2N7000breaksdown.Addinga 1N4001snubbingdiodereducesthespiketo12.7V—thatis,0.7Vabovethe12Vrelaysupplyvoltage. Finally,althoughtheoperatingandreleasetimesfortheserelaysislongcomparedwithpureelectronic switches,formanyapplicationsafewmillisecondsdelaybetweenPICoutputandrelaypull-inisoflittle consequence.
46
TheBasics–Output
Figure3-35:JG102-12-1RelayWithoutSnubber Ch1:PICOutput;Ch2:2N7000Drain.
Figure3-36:JG102-12-1RelaywithSnubberCh1: PICOutput;Ch2:2N7000Drain.
StandexJG102-12-1 Reedrelaysarewellknownforhighspeedoperation, andtheJG102-12-1(sincereplacedbymodelJG10012-1)meetsourexpectations.Figures3-37,3-38and 3-39showoperatingtimesforthisdevice.TheJG10212-1relayturnsonin250µs,butanadditional150µs isnecessaryforcontactbouncetocease.Turnofftime isalsoapproximately250µs.Sincetheturn-onand turn-offtimesareapproximatelyequal,theoverall relayhightimeisveryclosetothePICcontrolpinhigh time,althoughdelayedbyapproximately400µs.(The terms“operatetime”or“pull-intime”and“release time”areusuallyusedwhendiscussingrelayspeeds, insteadofturn-onandturn-off.However,toillustrate Figure 3-37: JG102-12-1 Reed relay Ch1: PIC thecommonalitywithtransistorswitching,we’lluse output;Ch2:relaycontact. theturn-onandturn-offterminologyaswell.)
Figure3-38:JG102-12-1Reedrelayturn-ondelay andcontactbounceCh1:PICoutput;Ch2:relay contact.
Figure3-39:JG102-12-1Reedrelayturn-offdelay Ch1:PICoutput;Ch2:relaycontact.
47
Chapter3 Reedrelaysarecommonlyusedintelecommunicationsequipmenttoswitchvoice,dataandhighfrequency signalsandarenotoftenemployedforswitchingpowercircuits. OmronG5V-2-H1 TheG5V-2-H1isamemberofOmron’stelecommunicationsfamily,optimizedforlowlevelsignalsandisusedfor purposessimilartothoseofreedrelaysaswellasforlow levelpowerswitching.TheG2Visofconventionalrelay construction,butwithbifurcatedcross-pointgoldplated silvercontacts.Eventhoughthecontactsareofprecious metal,Omronquotesaminimumcontactloadof10µAand 10mVDC.Atlowerlevels,oxidesandcontaminantsmay preventreliableoperation. Althoughconstructedwithbifurcatedcross-pointcontacts, contactbounceisstillapparentwiththeG5V-2-H1,as reflectedinFigure3-40.Operateandreleasetimesareapproximately4ms.
Figure3-40:G5V-2-H1relayCh1:PICoutput;Ch2: relaycontact.
OmronG2RL-24 TheG2RL-24isapowerrelay,suitableforswitchingAC andDCupto8amperes.Asmightbeexpected,relays designedtoswitchhighercurrentsaremoresubstantially constructedandhencetakemoretimetooperateandrelease.Figure3-41showstheG2RL-24requiresnearly 8mStooperateanddampencontactbounce.Releasetime isshorter,only4ms.Sincereleaseisshorterthanoperate, theoriginal10msPICoutputonlyresultsin6msofuseful relayclosure.
4N25OpticalIsolatedNPNSwitch Opticalcouplersor“optoisolators”consistofanLED Figure3-41:G2RL-24relayCh1:PICoutput;Ch2: packagedwithaphoto-diodeoraphototransistor.When relaycontact. illuminated,lightfromtheLEDsaturatesthereceptorand itconducts.ThereisnoelectricalconnectionbetweentheLEDinputandphotodeviceoutput,sothetwo circuithalvesareindependentandmaybeatapotentialdifferenceofhundredsoreventhousandsofvolts. Optoisolatorsareavailableinawiderangeofoperatingspeedsandconfigurations.We’ll firstlookatalowpoweroptoisolator,thevenerable4N25device,followedbyamodern highpoweropticallycoupledMOSFET,thePS710A-1A-1. Figure3-42showshowsimpleitistoconnectan optoisolatortoaPIC.R1isselectedtoachievethe desiredLEDon-currentusingthemethodology developedearlierinthischapter.The220ohmresistorisintendedtoprovideapproximately10mALED on-current.The4N25’soutputtransistorisconfigured asalowsideswitchintheexample.
48
Figure3-42:4N25Optoisolatorconnection.
TheBasics–Output Withamaximumcurrentratingofonly150mA, the4N25isnotintendedtoswitchlargecurrentssoitwilloftenbeusedasthefirststagein amultistageswitchingarrangement,suchasthat showninFigure3-43.Inthisdesign,the4N25 operatesasanemitterfollower.WhentheLED isilluminatedviaRB0goinghigh,currentflows throughthe4N25’soutputtransistorandR3,takingthegateofQ1intoconduction.Currentthen Figure3-43:4N25withIRF510. flowsthroughtheloadandQ1.WhentheLEDis dark,the4N25’soutputtransistoriscutoffandQ1’sVGSisclosetozeroandQ1iscutoff.Ofcourse,anyof themoremodernIPSproductsmaybesubstitutedfortheIRF510. LowpoweroptoisolatorsarealsooftenusedtoisolatedataorsignalcircuitsfromthePIC,andanoptical coupledRS-232circuitpermitsisolatingaPICfromtheassociatedcomputerorcontrolleddevices.
PS710A-1AAC/DCOpticallyIsolatedMOSFET NEC’sPS710A-1AisahighpowerMOSFEToptoisolator.Unlikethe4N25,thePS710Aisapowerdevice, capableofswitchingloadsupto1.8Aat60V,anditsseriesMOSFETdesignwillswitchbothACandDC. EachMOSFEThasanRDS(ON)of0.1ohmand,forDCswitching,maybeparalleledhandle3.6A. ThePS701A-1AisconnectedasillustratedinFigure3-44 forACorDCswitching.Otherconfigurationsarepossible forDCswitchingandyoushouldconsultthedatasheetfor additionalinformation. Figure3-45showstheresultsforthecircuitofFigure3-44, Figure3-44:AC/DCisolatedswitchingwithNEC’s switching1Aat5V.Figure3-45confirmsthedatasheet’s PS710A-1A. 1mstypicalturn-ontimeand50µstypicalturn-offtime. Inswitchinghighcurrentsinmicrosecondtimes,undesiredtransientsandoscillationsareoftenseen,particularlywhenusingaplug-inboardandlabpowersupplieswithlongleads.Whenthedesignistransferredto aprintedcircuitboardwithwidepowertracesandintegratedpowerdistributionfilteringtheproblemisoften solved.Insomecasesadditionalfilteringandbypassingwillbenecessary.Figure3-46showsanexpanded
Figure3-46:Undesiredoscillationinplugboard layoutofPS107A-1ACh1:PICoutput;Ch2:load.
Figure 3-45: Switching with a PS107A-1A Ch1: PICoutput;Ch2:load.
49
Chapter3 viewofthePS710A-1A’sturn-offintervalillustratesthetypeofextraneoustransientssometimesseenina plugboardlayout.Don’tbesurprisedtoseesimilarunwantedoscillationsinsomeofyourlayouts.Evenina breadboardlayout,youcanusuallystoporatleastreducetheseextraneoussignalsbybetterattentiontolead dressandgroundingjumperlocations,combinedwithadditionalpowerleadbypasscapacitors
SpecialPurposeSwitching We’veonlytouchedthesurfaceofwaystoswitchDCandACpowerwithaPIC.Inlaterchapters,wewill address: • H-bridgemotordrivers • IntegratedDarlingtontransistorarrays • TriacswitchingandcontrollingACpowerloads And,therearespecialpurposeintegratedcircuitssuitableforlowlevelsignal,audioandvideoswitching, suchasthe74HC4053,whatwe’llsaveforafuturebook.
FastSwitching—SoundfromaPIC Sofarinthischapter,ouremphasishasbeenonrelativelyslowswitching.But,ifweswitchaloudspeaker offandonatanaudiorate,wecanproducesound,perhapstobeusedasanalerttone,orabeeptoconfirm anactionorstatus.(WewillneedfastswitchingtocontrolaDCmotor’sspeedthroughpulsewidthmodulation,andtocontrolsteppermotors,bothtopicsdealtwithinlaterchapters.) Wecangenerateasoundeitherthroughaself-containedsounder,suchastheSonalert®productsintroduced byMallory,orthroughthePICproducingtheaudiosignalitself.ASonalertmaybedrivenbyaPICusing anyofthetechniquesyoulearnedearlierinthischapter.Laterchaptersexploreinsomedetailtheadvantages anddisadvantagesofvariouswaystogenerateaudiosignalsusingMBasic.Here,however,wewilljustlook attwosimpleinterfacesandoneofthemanyaudiooutputproceduresavailableinMBasic. We’llassumeyoudon’tintendtoproduceearsplitting,highfidelityoutputfromaPIC.Rather,youareinterestedinbeepsandotheralertingtones.Insomecases,itmaybepossible toobtainadequatevolumelevelsbydrivingthespeakerdirectlyfroma PIC,asillustratedinFigure3-47.Whenthinkingofaspeaker,lowimpedancedesignsmostoftencometomind,with3.2,4and8ohmdevicesbeing common.I’vegenerallybeendisappointedwiththevolumelevelswhen alowimpedancespeakerisdirectlyconnectedtoaPIC.Indeed,aseries resistor,R1inFigure3-47,of50ohmsorsoisnecessarytoproduceuseful Figure 3-47: Driving a speaker directlyfromaPIC. soundoutput. Remember,however,thatahighoutputpinmaybethoughtofasa5Vsourceinserieswithapproximately 85ohms.Workinginto,forexample,a3.2ohmspeakerwitha50ohmseriesresistor,approximately99.8% ofthetheoreticalmaximumoutputpowerofthepinwillbelostandnottransferredtothespeaker.Thisstill mayproduceanacceptablevolumelevel.Ifthespeakerhashigherimpedance,sayatleast32ohms,amuch greaterproportionoftheavailablepowerwillproduceusefulsound.Ifnecessary,asimpleseriesresistor, shownasR1inFigure3-47,canserveasavolumecontrol. Ifyou’veexaminedaloudspeakeryouknowthetypicalconstructionconsistsofapaperconethatmovesin oroutinresponsetocurrentthroughthevoicecoil.OursimpleconnectionofFigure3-47movesthecone onlyinonedirection,eitherinorout,dependingonwhichspeakerconnectionyougroundandwhichyou connecttothePIC’spin.Theunidirectionalmotionthrowsawayonehalfthepotentialsoundlevel.Dependingonyourdesiredsoundlevelandspeakerrating,thismayormaynotbeimportant.Figure3-48shows
50
TheBasics–Output weareabletodevelopapeakcurrentof27mAthrougha 3.2ohmspeaker.Thisparticularspeakeryieldedaweak soundwith27mAcurrent.Wemaycalculatethepower deliveredtothespeakerbyrecallingthattheRMSpowera squarewaveisequaltotheone-halfthepeakpower.(The RMSoftheonperiodisequaltothepeak;butsincehalf thecycleisoff,theRMSreducesbyonehalf.)Hence, theRMSpowerdeliveredtothespeakerisapproximately 1.2mW.(Thisisbaseduponthespeaker’snominal3.2 ohmimpedance.MeasurementsoftheparticularspeakerI testedshoweditstrueimpedanceat1000Hzis3.09ohms, representing2.95ohmsresistanceinserieswith149µH inductance.) Figure 3-48: Direct drive of 3.2 ohm speaker withPICand56ohmseriesresistorCh2:Speaker Let’slookatahigherpowerdriverforalowimpedance current(mA). speaker.Sincewearenotoverlyconcernedwiththesound quality—thePICsoundprocedureweuseoutputsasquare wave,afterall—wewillusea2N4401emitterfollower todrivethe3.2ohmspeaker,usingthecircuitshownin Figure3-49.And,topermitthespeaker’svoicecoiltohave bothinandoutexcursions,weuseC1toblocktheDC component.
Figure3-50showstheresultingcurrentthoroughthespeaker. TheRMSpowerdeliveredtothespeakerisnowapproximately45mW,yieldingnearly16dBmoresoundoutput,avery Figure3-49:2N4401emitterfollowerspeakerdriver. noticeableimprovementoverthedirectdriveconnection. Program3-3usesMBasic’ssoundproceduretooutputa 1000Hzsquarewavefor1,000millisecondsonRB0.The toneoutputisrepeatedendlesslythroughtheGoToMain loop. Program3-3 ;Program3-03 Main ;burstof1000Hzfor1second w/endlessloop SoundB0,[1000000\1000] GoToMain End
References [3-1]
Horowitz,PaulandHill,Winfield,TheArtofElecFigure3-50:2N4401FollowerDriveof3.2Ohm tronics,2nd.Ed.,(1989).Ifyouhaveonlyonebookon SpeakerwithPICand56OhmSeriesResistorCh2: SpeakerCurrent(mA). electronicsinyourlibrary,thisshouldbeit.Alongawaited3rdeditionisrumoredtobeintheworks,but thatshouldn’tdiscourageyoufrompurchasingthe2ndedition. [3-2] AmericanRadioRelayLeague,TheARRLHandbookforRadioCommunications2003ed.,American RadioRelayLeague(2003).Althoughaimedatradioamateurs,theARRLHandbookprovidesgood
51
Chapter3 entry-levelcoverageofbasicanaloganddigitalelectronics,testequipmentandconstructionpractices. TheARRLupdatesitshandbookeveryyear,sopurchasethemostrecentversionavailable. [3-3] Ludeman,RobertR.,IntroductiontoElectronicDevicesandCircuits,SaundersCollegePublishing (1990).Writtenasanintroductorytextforcommunitycollegeelectronictechnicianstudents,it’sagood summaryofbasicsolid-stateelectronicswithoutrequiringadvancedmathematics. [3-4] LinearTechnologyCorp.makesavailableafreeMicrosoftWindows-basedSPICEsimulatorandschematiccapturesoftware,“LTSpice/SwitcherCADIII.”AlthoughaimedasadesigntoolsupportingLTC’s products,thesoftwareisnotlimitedtoLTCdevices.Itmaybedownloadedathttp://www.linear-tech. com/software/.Inaddition,add-ondevicelibrariesandexplanatorymaterialforLTSpiceareavailable intheassociatedYahoousergrouphttp://groups.yahoo.com/group/LTspice/inthefilesfolder.The schematicsandsimulationsinthisbookuseLTSpice. [3-5] Barkhordarian,Vrej,PowerMOSFETBasics,InternationalRectifierCorp.TechnicalNote(undated). [3-6] InternationalRectifierCorp.,TheDo’sandDon’tsofUsingMOS-GatedTransistors,AN-936(v.Int). (Undated) [3-7] InternationalRectifierCorp.,CurrentRatingsofPowerSemiconductors,AN-949(v.Int),(Undated). [3-8] InternationalRectifierCorp.,SelectingandDesigninginTheRightSchottky,AN-968,(Undated) [3-9] OmronElectronics,Inc.,RelayUser’sGuide(1990).AvailableforfreedownloadatOmron’sreference centerhttp://oeiwcsnts1.omron.com/pdfcatal.nsf.Fromthispage,selectRelays.Fromtherelayspage selectManual. [3-10] DatasheetsforthedevicesusedinthischapterareavailablefordownloadingatthefollowingURLaddresses: 2N4401:http://www.fairchildsemi.com/ds/2N/2N4401.pdf 2N4403:http://www.fairchildsemi.com/ds/2N/2N4403.pdf PS710A-1A:http://www.csd-nec.com/opto/english/pdf/PN10268EJ01V0DS.pdf 2N7000:http://www.fairchildsemi.com/ds/2N/2N7000.pdf 4N25:http://www.fairchildsemi.com/ds/4N/4N25.pdf TIP31:http://www.fairchildsemi.com/ds/TI/TIP31.pdf TIP120:http://www.fairchildsemi.com/ds/TI/TIP120.pdf MV5491ADualLED:http://www.fairchildsemi.com/ds/MV/MV5094A.pdf IRF510:GotoInternationalRectifier’shomepagehttp://www.irf.com/andenterIRF510inthesearchbox. IRF9510:GotoInternationalRectifier’shomepagehttp://www.irf.com/andenterIRF9510inthe searchbox. IPS021:GotoInternationalRectifier’shomepagehttp://www.irf.com/andenterIPS021inthesearchbox. IPS511:GotoInternationalRectifier’shomepagehttp://www.irf.com/andenterIPS511inthesearchbox. G5VRelay:GotoOmron’shomepageforUSrelayproductshttp://oeiweb.omron.com/andenter G5V-2-H1inthesearchbox. G2RL-24Relay:GotoOmron’shomepageforUSrelayproductshttp://oeiweb.omron.com/andenter G2RL-24inthesearchbox. StandexJG100Relay:http://www.standexelectronics.com/serjg.htm
52
4
CHAPTER
TheBasics– DigitalInput AfterChapter3’sexaminationoftheoutputmode,we’llnowturntoPICpinsusedasdigitalinputdevices. ManyPICsincludeanalog-to-digitalconvertersandwe’llcoveranaloginputsinChapter11. Digitalsignallevelsareeitheralogicallow(0)oralogicalhigh(1)—whatcouldbesimpler?Aswiththe restofthisbook,weassumeVDDis5voltsandVSSis0volts.InPIClogic,a0voltinputcorrespondstoa logicallow.Likewise,a5Vinputisalogicalhigh.But,supposeourinputis1.7V.Isitalogicalloworisita logicalhigh?Doestheanswertothisquestiondependonourchoiceofaninputpin?And,doesitdependon thevoltageattheinputpinearlierintime?We’llfindoutinthischapter.
Introduction First,let’sdefineafewterms,asillustratedinFigure4-1: VIL—Themaximumvoltageonaninputpinthatwillbereadasa logicallow. VIH—Theminimumvoltageonaninputpinthatwillbereadasa logicalhigh. Undefinedregion—Theundefinedregionthevoltagelevel betweenVILandVIH.Inputvoltagesintheundefinedregion maybereadasaloworasahigh,asthePIC’sinputcircuitrymayproduceoneresultortheother.(Obviouslythe voltagewillbereadaseitheraloworahigh;it’sjustthatwe Figure4-1:Inputlevelrelationships. havenoassurancewhichoneitwillbe.) Thresholdvoltage—Theinputvoltagethatseparatesalowfromahigh;thethresholdvoltage,VT,minusa smallincrementisreadasalowwhilethethresholdvoltageplusasmallincrementisreadasahigh. Thethresholdvoltagediffersfromlogicfamilytologicfamilyandsomewhatbetweendifferentchipsof thesametype.ThedifferencesbetweenVTandVILandVIHaredesignmarginsaccountingfordevice-todeviceprocesstolerances,temperatureeffectsandthelike. Inanideallogicdevice,VILequalsVIHandthereisnoundefinedregion. MicrochiphaschosentobuildPICswithvaryinginputdesignsandassociatedvaryingVILandVIHvalues. Wewillnotconsiderafewspecialpurposepins,suchasthoseassociatedwiththeoscillator,inthischapter. Evenso,the16F87xseriesPICshavethreeinputpinvariations: TTLlevel—Ofthemanylogicfamiliesintroducedintheearlydaysofdigitalintegratedcircuits,transistor-transistorlogic(TTL)wasbyfarthemostsuccessfulwithTTLanditsdescendantsstillusedtoday. PortAandPortBinputpinsmimicTTLlogicinputlevels,exceptforRA4,whichhasaSchmitttrigger input.(Ofcourse,TTLstyleSchmitttriggerinputsexist;butsincetheyarenotfoundinthePICswe consider,wewon’tfurtherconsiderthem.)
53
Chapter4 6
Low to High Transition
Output Voltage
4 High to Low Transition
Schmitttriggerinputs—Almostallotherinputpinsareof Schmitttriggerdesign.ASchmitttriggerhasdifferent transitionvoltages,dependingonwhethertheinputsignal ischangingfromhightoloworlowtohigh,asillustrated inFigure4-2. SpecialSchmitttriggerinputs—PinsRC3andRC4aresoftwareselectableSchmitttriggerorSMBusconfiguration. (SMBusisaprotocoldevelopedbyIntelfordataexchange betweenintegratedcircuits.Wewillnotfurtherdiscuss SMBuscommunicationsinthisbook.)WhenRC3and RC4areusedasnormal,generalpurpose,inputpins,their parametersdifferslightlyfromthoseoftheotherSchmitt triggerinputpins.
2
0 0
2
4
6
Input Voltage
Figure4-2:Schmitttriggerinput.
InputLogicLevelSpecifications:16F87xwith4.5V0ThenGoSubLED_On;buttonpushed Next;Row GoToLoop;checkformorekeypresses
ThesubroutineLED_OnisadummyroutinethatsimplyflashesanLEDtoshowtherowandcolumnnumbersofthebuttonbeingpressed.Youmaywishtousethiskeypadroutineasonebuildingblockinamore complexandusefulprogram.
References [4-1]
Mancini,Ron,“ExaminingSwitch-DebounceCircuits,”EDN,p.22,Feb.21,2002.
66
5
CHAPTER
LCDModules BlinkinganLEDisfine,asfarasitgoes,butitlimitsourcommunicationsopportunitywiththeoutside world.IfusersarenottolearnMorsecode,atext-basedmessagedisplayexpandsourcommunications horizongreatly.LiquidCrystalDisplayshavebecomethedisplayofchoiceforPICoutputforgoodreasons; theyarerelativelyinexpensive,havebuilt-insupportinMBasicandareavailableinavarietyofsizes. We’lldealexclusivelywithLCDmodulessupportedbyMBasic. AnLCDmoduleincludesboththedisplayandacontroller board,asshowninFigure5-1.Don’tbuyinexpensiveLCD displayssoldbysomesurplusstoreswithoutthecontroller board—theyarenotcompatiblewithMBasic’sLCDfunctions. Almostuniversally,LCDmodulesuseanHitachiHD44780 controller/driverchip,oraderivativechipcompatiblewiththe HD44780commandset,suchasSamsung’sKS0066orEpson/ Seiko’sSED1278.(AnHD44780onlysupportsa16-character display,butwithauxiliarychipswillcontroluptoan80-charac- Figure5-1:MainLCDmoduleelements. terdisplay.) Theparticulardisplaywe’lluseinourexperimentsisaTianma TM162YBC6,2-line,16charactersperlinedisplay,supertwisted nematictechnologywithLEDbacklighting,availablefromBasic Micro,asshowninFigure5-2.However,almostanyLCDmodule maybesubstitutedforthisdisplaywithlittleornomodificationsto thehardwareorsoftwaredevelopedinthischapter. TheTM162YBC6’scontrollerchipisaKS0066,U1inFigure5-3. Inthisproduct,theKS0066issuppliedasanun-mounteddieand Figure5-2:TM162YBC6LCDdisplay. the“blackblob”isthechip’sencapsulatedhousing.(Asecond similarlypackagedchipisunderneaththequalitycontrolsticker.)
SelectingaDisplay We’lllookatthreeaspectsofselectinganLCDmodule;size,technologyandbacklighting.
DisplaySizes Therearethreeelementstodisplaysizing: 1. Numbersofcharacters—Displaysarestandardizedin1,2and 4lineconfigurations,with8,16,20and40charactersperline, Figure 5-3: KS0066 controller chip on with40charactersperlineavailable1,2or4linesizes.Afew LCDboard. 67
Chapter5 10and12charactersperlinedisplaysarealsoavailable.(The4×40displayisconfiguredastwo2×40 displayswithcommondataandcontrollines,butindependentE,orclock,lines.) 2. Charactersize—Sizesofindividualcharactersrangefromthealmostinvisible(0.072”)uptoapproximately0.25"wide. 3. Dotmatrixsize—Mostdisplaysusea5×7pixelmatrix,usually withan8thlinefortheunderscore,butafewpremiumpricedisplays offera5×8matrix,witha9thlinereservedforunderscore.Figure 5-4showshowcharactersareformedfromtheTM162YBC6’s5×7 pixeldisplay,withan8thline,notactiveinFigure5-4,reservedfor Figure 5-4: Characters are formed fromsmallsquarepixels. theunderscore.
CrystalTechnology LCDmanufacturershave,overtime,improvedthequalityofdisplaysthrough,amongotherthings,new liquidcrystalchemistry.Whenselectingadisplay,youmayfind Twistednematic(TN)—isanoldertechnology,stillusedtoday,withatwistangleof90°orless.Thegreater thetwistangle,thegreaterthecontrastbetween“on”and“off”pixels.Charactersareblackwithagray background. Supertwistednematic(STN)—isanewertechnologywithatwistanglebetween180°and270°,offering animprovedviewinganglecomparedwithTNdevices.STNdevicesfunctionusingadifferentphysical principle,birefringence.Unlesscorrected,however,birefringenceshiftsthebackgroundcolortoyellowgreenandthecharactercolortoblue.However,thebackgroundcolorcanbechangedtoagraywitha specialfilter.STNdisplaysareavailableintwocolors,blackcharactersonagreenbackgroundorblack charactersonasilverbackground. Filmsupertwistednematic(FSTN)—isthemostrecentadvance,addingaretardationfilmtotheSTNdisplay tocompensateforthecoloraddedbythebirefringenceeffect.Thisallowsablackandwhitedisplayto beproduced.FSTNdisplaysareonlyavailableinblackcharactersonawhitebackground.Itisthemost expensivetechnology,butimprovesbothviewinganglesandcontrastcomparedwithSTNdevices.
Backlighting LCDsarepassivedevices;theydonotemitlightbutratherareonlyvisiblethroughlightfromanother source.ThreelightingoptionsarecommonlyavailableforsmallLCDmodules: Reflective—ReflectiveLCDshavenobacklightingandareviewedonlythroughambientlightreflectedfrom thedisplay.Reflectivemodulesareabitcheaperandforlowpowerapplicationsmaybedesirable. Electroluminescent—Electroluminescentilluminateddisplayshaveaverypleasingappearance,buthave severalmajordrawbacks.First,theelectroluminescentpanelrequiresseveralhundredvoltsACoperatingpower,usuallysuppliedthroughaninverterpowersupplyoperatingat400Hz.Manyinexpensive surpluselectroluminescentilluminatedLCDsaresoldwithouttheassociatedinverter.Second,electroluminescentpanelshavealimitedlife,typicallyafewthousandhours,whiletheLCDdisplayitselfmay last20yearsincontinuousoperation.Itmaybenecessary,therefore,toreplacetheelectroluminescent sourcemanytimesduringthedisplay’slifetime.Electroluminescentlifetimescontinuetoimprove,but olderdeviceslikelytobefoundinthesurplusmarketaregenerallynotgoodbetsforlongevity. LED—ThemostpopularbacklightingilluminationsourceisanLEDarray.AnarrayofLEDsedge-illuminatesathindiffusersheetunderlyingtheLCDglassandprovidesuniformbackgroundlighting.LED backlightingisavailableinred,green,yellow,blueandothercolorsandmaybedimmedorturned offbyvaryingtheLEDdrivecurrent.LEDbacklightinghastwomajordisadvantages—highpower consumptionandreducedLCDlifeathightemperaturesduetotheextraheataddedbytheLEDs.LED
68
LCDModules backlightingis,however,muchlongerlivedthanelectroluminescentdevices,withtypicalexpected lifetimeswellover50,000hours. Itisn’tgenerallypossibletoinstallyourownbacklightinginareflectivedisplay,astheirbacksurfacesare opaquetolightcomingfromtherear.Transmissivedisplayintendedforbacklightedoperationhavearear neutraldensitypolarizerpermittinglighttopassthrough. LargeLCDdisplays,suchasfoundinlaptopcomputers,arebackilluminatedwithcoldcathodefluorescent lamps,butthistechnologyisseldom,ifever,foundinsmallalphanumericdisplays.
LCDEnvironmentalConsiderations Wesometimesforgetthatthe“L”inLCDstandsforliquid.Whenitgetscoldenough,theliquidcrystalsare frozeninplaceandthedisplaystopsworking.Fortunatelyfreezingseldomdamagesthedisplay.Ifyou’re planningonoutdooroperation,astandardLCD,ratedtoonly0°C,maypresentproblems.ExtendedtemperatureLCDsareavailablepermittingoperationdownto–20°C,butoftenrequireaseparate–7Vdisplay biaspowersupply.Checkthedatasheettodetermineyourdisplay’srequirements.
VFDDisplays We’veconcentratedonLCDdisplays,butanothertechnology,thevacuumfluorescentdisplay,orVFD, shouldbementioned.VFDsareactiveemittingdisplays,generatingasoftblueglowwhenapixelisactive. Eachpixelisaminiaturecathoderayvacuumtube,activewhenelectronsstrikeaphosphor.VFDsoffer highbrightnessandawideviewingangle—typically140°—andoperateoverawidetemperaturerange. Theirprimarydrawbacksareexpense—betweentwoandfourtimesthepriceofasimilarbacklightedLCD module—andrelativelyhighpowerconsumption.AtypicallifetimespecificationforaVFDis50,000hours tohalfbrightness. VFDmodulesareavailableinthesameconfigurationsasLCDmodulesandtheirdisplaycontrollersare HD44780compatible.Indeed,manyVFDmodulesarepin-for-pindrop-inreplacementsforLCDmodules. Accordingly,wewon’tfurthermentionVFDs,asourLCDdiscussiondirectlyapplies.
ConnectiontoPIC Figure5-5showstheconnectionwe’lluseforourtestprograms.Let’srunthroughthefunctionandconnectionofeachpin.ThePICpinassignmentsareforourtestcircuitandmaybeadjustedasneededforyour projects.TheLCDpinnumberassignmentsapplytothevastmajorityofLCDmodules,but,ofcourse,you shouldcheckyourparticulardisplaytoverifytheassignments.
Figure5-5:LCDmoduleconnectiontoPIC.
69
Chapter5 LCDPinName VSS VCC
LCDPinNumber 1 2
PICPin None None
VEE
3
None
RS
4
B0
R/W
5
B2
E
6
B1
DB0
7
None
DB1 DB2 DB3 DB4 DB5 DB6 DB7
8 9 10 11 12 13 14
None None None B4 B5 B6 B7
LED+
15
None
LED–
16
None
Comments Ground. Toregulated+5Vsource. Forcontrastadjustment;connectto20Kpotentiometeror inmanycasescanbedirectlygrounded.Notethatextended temperaturerangedisplaysmayrequireVEEtobeconnected toanegativesupply. Register(control/display)selectbit: R/S=0—Dataiswritten/readto/fromcontrolregister. R/S=1—Dataiswritten/readto/fromdisplayRAM. Read/Writeselectbit: R/W=0—WritedatatoRAM. R/W=1—ReaddatafromRAM. IfyoudonotintendtoreadfromtheLEDmemory(very oftenthecase)youmayomitthisconnectionfromthePIC anddirectlygroundtheLCD’sR/Spin. Enable—theclockpinforreadingandwritingdata. Databit0(LSB).8-bitdatatransfertoLCDisnotsupported byMBasic’sLCDReadandLCDWriteproceduressoDB0…DB3 arenotused. Databit1—notusedin4-bittransfer. Databit2—notusedin4-bittransfer. Databit3—notusedin4-bittransfer. DB4…DB7aregroupedtogetherintoanibbleforLCDRead andLCDWriteprocedures.We’llusePortB.HighNib(B4…B7). ConnecttoLEDsupply;neednotberegulated,butdoes requireseriescurrentlimitingresistor. Connecttoground.
Afewoftheseconnectionsdeservefurtherdiscussion. Power,groundandbias—VSSandVCC(labeledVDDinsomeLCDmodules)arestraightforward;VSSis ground,whileVCCisconnectedto+5V.(Somelowervoltagedisplaymodulesarenowavailable;of coursecheckyourmodule’sdatasheettoverifythatitrequiresa+5Vsupply.)TheLCD’slogicchips arepoweredfromthisvoltage.However,thevoltageappliedtothecrystalstocausethemtorotateis obtainedfromVCC(positive)andVEE(negative).BysettingVEEafewtenthsofavoltaboveground, VDDbecomesnegativewithrespecttoVEEandthusthenegativevoltagerequiredforcrystalrotationis obtained.VEEdeterminesthedisplay’scontrast,soit’scommontoderiveVEEthrougha10Kohmto20 kohmpotentiometerresistivevoltagedivider,asshowninFigure5-5.Thedesireddisplaycontrastcan beobtainedbyvaryingthepotentiometersetting.(VEErequiresonlyafewhundredmicroamperescurrent,soarelativelyhighvaluepotentiometercanbeused.)I’vefoundthatalmostalldisplaysworkwell atroomtemperatureifVEEisjustconnectedtoground,soforcasualexperimentingI’lloftenomitthe contrastadjustmentpotentiometerandsimplygroundVEE. ExtendedtemperaturerangeLCDmodules(andevenafewstandardtemperaturemodules)requireaseparate –7VsupplytodriveVEEandmayneedanautomaticcompensationcircuittoadjustVEEastheambienttemperaturechanges.The–7VsupplyisappliedtotheVEEpinthroughapotentiometerforcontrastadjustment. RS—TheRegisterSelectpindetermineswhetherdataisroutedtotheLCDmodule’scontrolregisterordisplayRAM.Forexample,iftheRSpinishigh,sendingthedatavalue(hex)$28totheLCDmodulecan
70
LCDModules causetheleftparenthesischaracter“(“tobedisplayed;iftheRSpinislow,thesame$28charactersets thedisplaytotwolinemode.Sincewemustbothwritenormaldisplaydataandcommandinstructions, theRSpinmustbeconnectedtoaPICoutputpin.LCDWriteautomaticallysetsorclearstheRSpin, basedonthevaluebeingwrittentothedisplay. R/W—Datatobedisplayedisheldinread/writerandomaccessmemoryintheLCDmodule.MBasicallows ustoreadfrom(LCDRead)iswellaswriteto(LCDWrite)theLCDmodule’sRAM.Theread/write (R/W)pindetermineswhetherwearewritingdatatothemodule(R/Wislow)orreadingdatafromthe module(R/Wishigh).QuiteoftenweneednotreaddatafromtheLCDmoduleandwemaysimply connecttheLCDmodule’sR/Wpintoground.Forgenerality,thischapter’ssampleprogramsconnect theR/WpintoaPICoutputpinsobothLCDReadandLCDWriteoperate. E—DataisexchangedbetweenthePICandtheLCDmoduleisparallelformat—thatis,eithereightorfour bitsofabytearesentsimultaneously.Theenable(E)pin,bychangingstatefromhightolow,informs thereceivingdevice(theLCDmoduleifdataisbeingsenttofordisplay)thatthedatapinsshouldbe read.WecanconsidertheEpinasadataclock. Data—NormalLCDmodulesareparalleltransferdevices;theycanexchangedataaseitherone8-bitbyte ortwo4-bitnibbles.MBasic’sLCDReadandLCDWritefunctionssupportonly4-bit(nibble)transfer mode,sowe’llconcentrateonthat.In4-bitmode,onlythedatalinesDB4…DB7areactive.Totransfer abytethehighnibbleistransferredfirstfollowedbythelownibble.Fortunately,LCDReadandLCDWritetakecareofthesedetailsforus.Ifyou’vebeenkeepingtrackofhowmanypinswe’veusedto communicatewiththeLCDmodule,youunderstandwhyBasicMicrochosetoimplementthe4-bit mode.Evenso,sevenpinsmustbedevotedtoLCDcommunicationsinthegeneralcase,droppingtosix ifwewishtoonlywritetothemoduleandaccordinglygroundtheLCD’sR/Wpin. TheonlythingleftistocalculatetheLEDcurrentlimitingresistor’svalue.Figure5-6showsthestandard LEDconfiguration.ThebacklightconsistsofadozenormoreLEDpairs,seriesconnected,withaforward voltageoftypically4.1Vwhenoperatingatratedcurrent. OurTM162YBC6backlightarrayisspecifiedat4.7Vat therated93mAcurrent,ahighervoltagethantypically seen.AssumingtheLEDsupplyisconnectedtoa+5V regulatedoutput,wemayquicklycalculatetherequired currentlimitingresistor: 5V − 4.7V = 3.2 Ω 0.093 A Wewillusethecloseststandardvalue,3.3ohms.
R1 =
Thepowerdissipatedbythelimitingresistoris:
P = I 2 R1 = ( 0.093) × 3.2 = 0.027 watts 2
Figure5-6:LEDcurrentlimitingresistor.
Aone-quarterwattresistorisadequate. IfthebacklightLEDarrayisratedat4.2or4.3V,wemayusea1Asiliconpowerdiodeinserieswiththe LEDarrayinsteadofaresistortolimitthecurrent. Weshouldbecautiousinconnectingdevicestothe+5VregulatedsupplyinBasicMicro’sdevelopment boards.The5Vregulatorhasnoheatsinkanditsmeasuredinputvoltageis13V(nominal12V“wallwart” powersupply).The7805’sthermalresistance(junctiontoair)RθJAis65°C/Wandthemaximumoperating junctiontemperatureis+125°C.Iftheambientairtemperatureis25°C,wecanpermitnomorethana100°C junctiontemperatureriseoverambient.A100°Criseinjunctiontemperatureiscausedby100°C/65°C/W,or 71
Chapter5 1.5Wdissipation.Sincethevoltagedropacrosstheregulatoris13V–5V,or8V,1.5Wdevicedissipationis reachedwithatotal192mAcurrentdraw.Wellbeforethiscurrentlevelthe7805willbecomehotenoughto burnyourfinger,soit’snotdesirabletopushittothelimit.But,ifyoudo,7805’sarewellprotectedbyinternalcircuitry,includingover-temperatureshutdown,sothechancesofdamagingtheregulatorareminimal.
HelloWorld Nowthatwe’vewiredtheLCDmoduleaccordingtoFigure 5-5,let’slookatsomecode.Thecanonicalfirstprogram displays“HelloWorld,”sohere’sourLCDversionasseen inFigure5-7.Program5-1writes“HelloWorld”onthe LCDmodule,waits1.5seconds,clearsthescreenandwrites “HelloWorld”againinanendlessloop.
Figure5-7:HelloWorld.
Program5-1 ;Program5-01--HelloWorld ;Varibles ;-------LCDNib
VarPortB.Nib1
;Constants ;--------- RegSel Con Clk RdWrPin
B0 Con Con
B1 B2
;Initialization ;-------------Pause500 ;AllowstheLCDtoinitialize LCDINITRegSel\Clk\RdWrPin,LCDNib Main LCDWriteRegSel\Clk\RdWrPin,LCDNib,[“HelloWorld”] Pause1500 LCDWriteRegSel\Clk\RdWrPin,LCDNib,[CLEAR] Pause1500 GotoMain End
Let’slookatsomekeyelementsoftheprogram. ;Varibles ;-------LCDNib
VarPortB.Nib1
;Constants ;--------- RegSel Con B0 Clk Con RdWrPin Con ;Initialization ;-------------Pause500
B1 B2
;AllowstheLCDtoinitialize
ThePause500statementgivestheLCDmodule500mstogothroughanyinternalpower-onstartupsequenceithasbeforereceivingcommandsanddatafromourMBasicprogram. LCDINITRegSel\Clk\RdWrPin,LCDNib
72
LCDModules TheLCDINITcommand,newinversion5.3.0.0,initializestheLCDmodulewiththemostcommonsetupparameters,clearsthedisplaymemory,andpositionsthecursoratthetopline,leftmostposition.Ifyourinitialization requirementsarenotmetbyLCDINIT,youcancustominitializethemoduleusingtheLCDWritefunction. RatherthanseparatelydiscussLCDINIT’sarguments,wewillconsidertheminconjunctionwithLCDWrite. AllthreeLCDfunction,LCDInit,LCDWriteandLCDReadusethefirstfourargumentstomapthephysicalconnectionsbetweenthePICandtheLCDmodule.Tounderstandthephysicalconnectiontosoftware mapping,we’lllookatLCDWriteindetail.(TheRdWrPinisoptional;ifomitted,onlythreeargumentsare requiredforthesethreeLCDfunctions.) LCDWriteRegSel\Clk\RdWrPin,LCDNib,[{mods}Exp]
ThefirstthreeargumentsforLCDWrite—RegSel,ClkandRdWrPin—identifythepinstowhichtheLCD module’sRS(RegSel),E(Clk)andR/W(RdWrPin)connectionsareattached.FollowingFigure5-5,we’ve connectedRStoRB0,EtoRB1andR/WtoRB2.Hence,wedefinethreenewconstants,RegSel,Clkand RdWrPinandsetthemequaltoB0,B1andB2,respectively.(IfyouhardwiretheLCDmodule’sR/Wpinto ground,youmayomittheRdWrPinfromtheLCDWriteargumentlist.) Ofcourse,wecouldhavesimplywrittenLCDWriteB0\B1\B2…everytimeweinvokeLCDWrite.Suppose,though,wewishtocopyourcodetoanotherproject,butonewheretheLCDisconnectedtoC0, C1andC2,insteadofB0,B1andB2.Insteadoftryingtofindperhapsdozensofplacesinourcodewhere LCDWriteisusedandchangeeveryone,insteadallweneedtoischangethethreeconstantdeclaration statements,amucheasiertask. LCDWrite’sfourthargument,LCDNib,definesthePortnibbletowhichtheLCDmodule’sDB4…DB7
pinsareconnected.Sincewe’veusedthreepinsfromPortBforcontrol,we’llstickwithPortBforthedata nibble.We’veconnectedRB4toDB4,RB5toDB5,etc.sothedatanibbleisPortB.HighNib(equivalent toPortB.Nib1).AlthoughtheMBasicUser’sGuidesuggeststhatLCDNibmaybeeitheravariableora constant,Ifoundthatanythingotherthanavariablegeneratesacompilererror. Now,let’slookatthefinalpartofLCDWrite;the“stuff”withinthesquarebrackets.Thefirstfourarguments informLCDWritewheretosendthedata;theinformationwithinthesquarebracketsisthedatatobesent. TounderstandwhatLCDInitdoes,we’lldetourbyexamininghowtoinitializeanLCDusingtheolder method,sendinganinitializationmessagewithLCDWrite. ToduplicatethefunctionalityofLCDInit,wesendtheinitializationsequence[INITLCD1,INITLCD2, TWOLINE,CLEAR,HOME,SCR]. ReferringtotheMBasicUser’sGuide,wefindtheseinitializationcommandscausethefollowingactionin theLCDmodule: HexValue $103(note) $102(note) $128 $101
Name INITLCD1 INITLCD2 TWOLINE CLEAR
$102
HOME
$10C
SCR
ActionCausedinLCDDisplay Firstinitializationcommand. Secondinitializationcommand. Setdisplayfortwo-linemode. Writesaspace($20)characterintoalldisplayRAMmemory.Itreturns thedisplayaddresscounterto0.Theincrement/decrementmodeisset toincrement.Theresultistoclearthedisplayofalltextandposition thecursorattheleftedgeofthedisplayinthefirstlineandcausethe nexttextcharactertobedisplayedtotherightofthelastcharacter. Setsthedisplayaddresscounterto0andremovesanydisplayshift thatmighthavebeeninplace.DisplayRAMcontentsarenotaltered. Displayon,underscoreandblockcursorsdisabled.
73
Chapter5 TheMBasicUser’sGuidesaysthevalueassociatedwithInitLCD1is$133,whilethatofInitLCD2is$132. However,examinationoftheresultingassemblercodeshowstheUser’sGuideisinerror.(Thepre-definedLCD initializationconstantHomeisalso$102.)Inanyevent,thesequenceestablishedbyInitLCD1,InitLCD2must beusedtosettheLCDmoduleto4-bitoperationandproperlyinitializeitsoperation. Thenextfourinitializationconstants,TWOLINE,CLEAR,HOME,SCR,setthedisplaytooperateintwo-line mode;erasesthedisplaymemory;setsthestartoftexttothetopline,leftposition;andturnsthedisplayon, withnocursor.Ifwewishtousethisolderinitializationmethodology,thecorrespondingfunctionis: LCDWRITERegSel\Clk\RdWrPin,LCDNib,[INITLCD1,INITLCD2,TWOLINE,CLEAR, HOME,SCR]
ThisinitializationsequenceprovidesthesamefunctionalityastheLCDInitcommandaddedinversion5.3.0.0. Main LCDWriteRegSel\Clk\RdWrPin,LCDNib,[“HelloWorld”] Pause1500 LCDWriteRegSel\Clk\RdWrPin,LCDNib,[CLEAR] Pause1500 GotoMain
HavinginitializedtheLCDmodule—eitherwiththeLCDInitcommandorLCDWriteandaninitialization string—wenowwriteour“HelloWorld”stringtothedisplay.(RegardlessofhowweinitializetheLCD,we needtoinitializeitbutonce.)NotethatweusethesameLCDWriteprocedureasmightwedoforsending commandsequences;ifthevaluesinsidethebracketsare255orless,LCDWriterecognizesthemascharacters,notcommands,andappropriatelyclearstheRSline.RememberthatMBasictreatsastringsequence asaseriesofindividualcharacters,eachwithabytevaluebetween0…255.Afterwriting“HelloWorld,”the programwaits1.5secondsandclearsthedisplaywiththeLCDWrite[CLEAR]command.Afteranother1.5 secondpause,“HelloWorld”iswrittenagaintothedisplay.
LCDModuleMemory,ShiftsandLines BeforewebecomemoreadventuresomewithLCDWrite,wemustunderstandhowdisplaymemoryisorganizedinLCDmodules. TheHD44780andcompatiblecontrollerchipshave80bytesofdisplaydataRAM(DDRAM)—thememory thatholdsthemessageyouwantdisplayed—regardlessofwhethertheyareconnectedtoa16×1,a16×2, a20×2orsomeothersizeLCDdisplay.It’spossibletowritetoall80bytesofdisplaymemory,butonly thatpartofthememorythatfitsintothedisplaywindowwillbeseen.Aswewillsee,however,it’spossible tooffsetthedisplaywindowtoshowdifferentsegmentsofthetotalmemory. SomeLCDmodulesmayaddexternalDDRAMmemory;socheckthedatasheetforyourparticulardisplay. Others,suchasa40×4display,fittwoHD44780controlchips,withseparateE(E1andE2)connections butwithallotherconnectionsparalleled.ThesedisplayscanbewrittentowithLCDWritebytreatingthem astwoindependent40×2displays,withcommonpins,exceptfordifferentE1andE2connections. Memorylayoutfor16×2and20×2displaysseemsreasonablystandardized.Here’sthe16×2display layoutforthedefaultscreenwindowposition: Characters Line1 Line2
0 $00 $40
1 $01 $41
2 $02 $42
3 $03 $43
4 $04 $44
5 $05 $45
6 $06 $46
7 $07 $47
8 $08 $48
9 $09 $49
10 $0A $4A
11 $0B $4B
12 $0C $4C
13 $0D $4D
14 $0E $4E
15 $0F $4F
ThevaluesinthetablearetheLCDmodule’smemoryaddressthatcorrespondtothedefaultscreenwindow position—thatis,acharacterwrittenintomemoryposition$41willappearasthesecondcharacterfromthe
74
LCDModules leftinthesecondlineofthedisplay.Memoryforline1andline2continues;line1tomemorylocation$3F andline2tomemoryposition$7F,buttheseareoutsidethedisplaywindowwidth. A20×2displayhasthesamestartingpointsforLines1and2,butthevisiblecharacterdisplay,ofcourse, extendsforfouradditionalcharacters.Eventhefirsttwolinesofa20×4displaymapto$00and$40.Nonetheless,youshouldverifythememoryarrangementforyourdisplay,assomevariationsexist.Incidentally, althoughnotdocumentedintheUser’sGuide,LCDWriteworksfor20×4displays,asweshallseeinChapter6. ScrLeftandScrRight Tounderstandhowthescrollingthedisplaywindowworks,supposewehavean8×1display,with8charactersavailableononeline.Afterinitialization,wesenda16-characterstringtothedisplay(forclarityomitting thepinandnibbleaddressdetailsfromLCDWrite;we’llindicatethisomissionbyaddingaellipse“…”): LCDWrite…[“HELLOWORLD!!!!!]
Theresultistoloadthefirst16DDRAMpositionsinthedisplaywiththismessage. Characters Memory Message
0 $00 H
1 $01 E
2 $02 L
3 $03 L
4 $04 O
5 $05
6 $06 W
7 $07 O
8 $08 R
9 $09 L
10 $0A D
11 $0B !
12 $0C !
13 $0D !
14 $0E !
15 $0F !
Sincewehavean8-characterwindow,we’llindicatewhichcharactersaredisplayedbyboxingthemwith aheavyoutline.We’llalsoassumethedisplayhasbeeninitializedwiththesameconstantsinProgram5-1, exceptthatitisaone-linedisplay.Hencethedisplaywindowshows: Message
H
E
L
L
O
W
O
R
L
D
!
!
!
!
!
WewillseeHELLOWOonthedisplay. However,wecanscrollthememoryleftorrightunderneaththedisplaywindowbysendingaScrLeftor aScrRightcommandtothedisplaywithLCDWrite.SupposeweexecuteLCDWrite…[ScrLeft]four timesinimmediatesequence.Theresultis: Message
H
E
L
L
O
W
O
R
L
D
!
!
!
!
OurdisplaynowshowsOWORLD!,asthetexthasscrolledfourpositionstotheleft. We’lldemonstratescrollingwithProgram5-2.Program5-2assumesweusea16×2displayandimplementstwosuccessivefullscreenwidthscrollstodisplayall40charactersinline1’sDDRAM. Program5-2 ;Varibles ;-------LCDNib i
Var Var
PortB.Nib1 Byte
;Constants ;--------- RegSel Clk RdWrPin
Con Con Con
B0 B1 B2
;Initialization ;-------------Pause500
;AllowstheLCDtoinitialize
LCDInitRegSel\Clk\RdWrPin,LCDNib
75
!
Chapter5 Main LCDWriteRegSel\Clk\RdWrPin,LCDNib,[Clear,ScrRAM] LCDWriteRegSel\Clk\RdWrPin,| LCDNib,[“ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”] Pause15000 Fori=0to15 LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrLeft] Next Pause15000 Fori=0to15 LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrLeft] Next Pause15000 GotoMain
AfterthesameinitializationroutinedevelopedinProgram5-1,wewrite36charactersA…9intotheLCDmodule’sDDRAM,atpositions$00…$23withLCDWrite…”ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”]. (TheinitializationcommandssettheDDRAMwritepositionto$00andenableautomaticincrementfor eachcharacteraddedtoDDRAM.)Sincewe’reusinga16×2display,weexpecttoseeA…Ponthetopline ofthescreen,andFigure5-8confirmsourexpectation. Afterpausing15seconds,wescrollleft16times: Fori=0to15 LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrLeft] Next
AsFigure5-9confirms,thenext16characters—Q…5—arenowvisible.After15moreseconds,wescroll left16moretimes. Fori=0to15 LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrLeft] Next
Figure5-8:First16characters.
Figure5-9:Scrollleft16positions.
So,whatdoweseenow?Weexpectthedisplaytostartwith6,and atrunthrough9.Figure5-10shows,however,anadditionalfour spacesandA…H.Tounderstandwhyweseewhatwedo,rememberthattheHD44780has80bytesofDDRAM,splitequally betweenline1(positions0…39)andline2(positions64…104). (We’rebouncingbackandforthbetweendecimalandhexadecimal representationsofmemoryaddresses,sodon’tgetlostorconfused. Hexvaluesareprecededwitha$symbol.)Wefirstclearedthe memory,whichwritesspacecharacters($20)intoall80DDRAM positions.Startingatposition0(line1)wethenwrote the36charactersA…9into DDRAM,sothefourspacesat theendareleftoverfromthe initializationspacecharacters.WhatabouttheA…H though?Theansweristhat theDDRAMcounterwraps around,sothatDDRAM Figure 5-10: Scroll left 16 positions a address40istreatedbythe HD44780asposition00,41 secondtime. 76
LCDModules as01,etc.Hence,theA…Harethecharacterswewroteatpositions0…7,wrappedaroundwhenwetriedto displaypositions40…47. We’veillustratedScrLeft,butScrRightworksthesameway,butwithoppositemovement. Whywouldyouwanttoscroll?Ifyourmessageistoolongtofullydisplay,scrollitacrossthedisplay,one stepeveryhalf-second.Or,perhapsyouwantyourmessagetoreceiveattention.Scrollitleftandthenright severaltimesasaneyecatcher.And,supposeyouwishtodisplayastreamofcontinuouscharacters,perhaps frommonitoringanRS-232line,ormaybefromanamateurradioMorsecodedecoder.It’saloteaserto readcontinuoustextiftheoldtextscrollsonepositionleftwitheachnewcharactersaddedattheright. WritingataDefinedLocation We’velookedatscrollingthedisplay,butsupposewewishtokeepthedisplaytextfixedandwritenewinformationataspecificlocation.Forexample,supposeourdisplayisreportingtheoutdoortemperature.Wemight likethedisplaytoreadOutdoor72Fwhenit’s72degreesoutsideandOutdoor73Fwhenit’s73degrees. Wehaveacoupleofwaystodisplaythismessage.OnewouldbetowriteitdirectlyusingtheLCDWrite procedure,forexample.,LCDWrite…[“Outdoor“,DECOTemp,”F”]everytimewereadourtemperaturesensor(withtheresultingvalueheldinOTemp)andupdatethedisplay.Beforewritingthisstring,we mightclearthedisplay.Inpseudo-codethisapproachis: Initializethingsthatneedinitialization Main ReadthetemperaturesensorandputvalueintoOTemp ClearLCD Write“Outdoor”+String(OTemp)+“F”toLCD GoToMain
However,therearesomeadvantagesinwritingthefixedtextparts“Outdoor”and“F”justonceandwriting onlythetemperaturevaluewhenread.Ifnothingelse,wecansaveabitofexecutiontime,andourcodemay wellbeeasiertoreadaswecanseparatefixedinitializationtypeactivities(writingthe“Outdoor”and“F”) fromrepetitiveactions,suchasreadingthetemperaturesensorandwritingitsvalue. Usingour16×2displayandlookingatline1,thefixedpartofourmessageisthus: Characters Memory Message
0 $00 O
1 $01 u
2 $02 t
3 $03 d
4 $04 o
5 $05 o
6 $06 r
7 $07
8 $08
9 $09
10 $0A
11 $0B F
12 $0C
13 $0D
14 $0E
15 $0F
Whatweneed,therefore,isawaytowritethetemperaturestartingatDDRAMaddress$08.Fortunately,we mayaccomplishthateasilythroughLCDWrite…[ScrRAM+Offset]command.ThecommandLCDWrite… [ScrRAM+Offset]movestheDDRAMaddresscountertothememorypositionOffset.Hence,towrite thetemperaturebeginningatDDRAMposition$8,wefirstexecuteLCDWrite…[ScrRAM+$8].Program5-3 showsthecompletecodetoexecutethistask.(IfwewantedtopositiontheDDRAMaddresscountertoline 1’sstart(0),wewouldsimplyuseLCDWrite…[ScrRAM]withnooffset.) Program5-3 ;Varibles ;-------LCDNib OTemp
VarPortB.Nib1 Var Byte
;Constants ;--------- RegSel Con Clk RdWrPinCon
B0 Con B2
B1
77
Chapter5 ;Initialization ;-------------Pause500
;AllowstheLCDtoinitialize
LCDInitRegSel\Clk\RdWrPin,LCDNib OTemp=RandomOTemp LCDWriteRegSel\Clk\RdWrPin,LCDNib,[Clear,ScrRAM] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[“OutdoorF”] Pause1000 Main LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrRAM+$7] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[““] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrRAM+$8] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[DECOTemp] Pause10000 GotoMain End
Wedon’thavearealtemperaturereadingroutine,sowesubstitutearandomnumber.Wealsodon’tworry aboutminussigns(weshoulduseasignedvariableforOTemp)andwewon’tconcernourselveswithsome otherpresentationniceties,asourfocusisuponhowtowriteataspecificDDRAMaddress. LCDWriteRegSel\Clk\RdWrPin,LCDNib,[Clear,ScrRAM] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[“OutdoorF”]
Herewewritethefixedpartofthedisplay.Weallowfourspacesforthetemperaturereading;threeforthe digitsandoneblanktoseparatetheword“Outdoor”fromthefirsttemperaturedigit. Main LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrRAM+$7] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[““] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrRAM+$8] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[DECOTemp] Pause10000 GotoMain
Nowwewritethetemperaturereading.First,becausewedon’tknow howmanydigitstheprecedingreadingmighthaveoccupied,weclear theoldreadingbywritingfourspacesstartingat$7.First,weposition theDDRAMmemorypointerat$7andthenwritefourblanks.Now wearereadytowritetheactualtemperaturereading.(Ifthiswerea realthermometerprogramwewouldfirstgetatemperaturereading,of course.)WepositiontheDDRAMmemorypointerwherewewishthe firstdigitofthetemperaturereadingtobegin($8)withtheLCDWrite… [ScrRAM+$8]procedure.Finally,wewritetheactualtemperature valuewithLCDWrite…[DECOTemp].Figure5-11showstheresult.
Figure 5-11: Simulated temperature display.
BlinkingandCursorSelection Anotherattentiongetteristoflashingthetextoffandon.Whilewecoulddothisbyclearingthedisplay andre-writingtheinformation,it’seasiertosendoff/oncommandstotheLCDmodule.Thefollowingcode fragmentendlesslyflashesthecurrenttextonforonesecondandoffforonesecond. FlashText LCDWriteRegSel\Clk\RdWrPin,LCDNib,[Off] Pause1000 LCDWriteRegSel\Clk\RdWrPin,LCDNib,[Scr] Pause1000 GoToFlashText
78
LCDModules TheOffcommanddoesexactlywhatitsnamesuggests;itturnsthedisplayimageoff.Wethenwait1,000 millisecondsandturnthedisplayimagebackon.Thereisno“on”command;ratheryoumustchoosefrom fourcommandsthatturnthedisplayimageonandsimultaneouslycontrolthecursor. HexValue $10C $10D $10E $10F
Name SCR SCRBLK SCRCUR SCRCURBLK
ActionCausedinLCDDisplay Displayon,nocursordisplayed, Displayon,nounderscorecursor,blinkingsolidblockshowsnextcharacterposition Displayon,steadyunderscorecursorshowsnextcharacterposition Displayon,steadyunderscorecursorandblinkingsolidblockshownextcharacter position.
Thesecommands,ofcourse,canalsobeusedatinitialization.Ifso,itwillbenecessarytouseanappropriate initializationstring,sentviaLCDWrite,insteadoftheLCDInitfunction. Figures5-12and5-13showtheresultsofSCR(line1inbothfigures),ScrCur(line2,Figure5-12)and SCRBLK(line2,Figure5-13).Thefourthoption,ScrCurBlkhasbothasteadyunderscoreandaflashing blockatthenextcharacterposition.
Figure5-12:Underscorecursor.
Figure5-13:Blockcursor.
Ifyourapplicationisdisplay-only—usersdonotenterinformation—acursorisn’tnecessaryandtheSCR initializationconstantisappropriate.Iftheuserinteractswithyourprogram,however,acursorisavaluablecuetoshowwherethedataistobeenteredorchanged.We’llseeexamplesofuserinteractioninlater chapters.
FontSelection InadditiontothenormalupperandlowercaseEnglishalphabet,numbersandpunctuationsymbols, HD44780-compatiblecontrollershaveanextendedfontset.UsuallytheextensionisKatakana(Japanese)or, lessoften,genericWesternEuropeanaccentedcharacters.Otherfontextensions,suchasCyrillic,Greekand Hangul(Korean)arealsoavailablefromsomemanufacturers.(Ifyouarewillingtopurchasealargeenough quantity,semiconductorhouseswillmanufactureanLCDcontrollerchipwithyourowncustomdesigned characters.) Theextendedcharactersetisn’tatruesecondfontset,where,for example,theEnglishcharacter“A”appearsasadifferentsymbol followingafontselectioncommand.Rather,thesearecharacters withavalueof$80to$FF,abovethestandardcharacterbyterange ofspace($20)todelete($7F).Towritetheextendedcharactercorrespondingwithavalueof$9B,yousimplyuseLCDWrite…[$9B]. Multiplecharactersareseparatedwithcommas,e.g.,LCDWrite… [$9B,$9C,$8F].Program5-4displaysextendedcharacters,together Figure 5-14: Extended character set withtheirvalue,withtheresultsinFigure5-14. display. 79
Chapter5 Program5-4 ;Varibles ;-------LCDNib i
VarPortB.Nib1 Var Byte
;Constants ;--------- RegSel Clk RdWrPinCon
Con Con B2
;Initialization ;-------------Pause500
B0 B1
;AllowstheLCDtoinitialize
LCDInitRegSel\Clk\RdWrPin,LCDNib Main Fori=$80TO$FF LCDWriteRegSel\Clk\RdWrPin,LCDNib,[Clear,Home,”Value:“,DECi,”“,ISHEXi] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrRAM+$40,”Char“,i] Pause2000 Next GotoMain End
Bynow,thisprogramshouldrequirelittleexplanation,aswe’veseenallofitearlierinthischapter.The keylineswritethenumericalvalue(indecimalandhex)onthetopline,whilethecorrespondingcharacterappearsonbottomline.ThenormalEnglishcharactersetstopsat$7F,sowestartat$80andgotothe maximumpossiblebytevalue,$FF.Ifyouchangethestartingpointto$20,insteadof$7F,youcanseethe normalEnglishcharactersetaswell.
CustomCharacters Ifthenormalandextendedcharactersaren’tenough,youcandefineuptoeightcustomcharacters.Oncedefined,thesecharactersarefullyaccessiblejustasanypre-definedcharacter.Customcharactersarecontained incharactergeneratormemory,orCGRAM.SinceCGRAMisvolatile,yourprogrammustrewritethecustomcharacterstoCGRAMifpowerisremovedfromtheLCDmodule.Wewillloadourcustomcharacters atinitialization. We’lldemonstratecustomcharactersinthecontextofabargraphdisplay.Ifwe’remeasuringaparameter, suchasananalogvoltagewithaPIC’sbuilt-inanalog-to-digitalconverter,canshowtheresultingvalue asadigitstringonourdisplay—12.56volts,forexample,updatedseveraltimesasecond.But,ifyouare adjustingavariablevoltagecontrol,youwillfinddigitaldisplaysaren’twellsuitedtoshowingtrendsor short-termchanges.Indeed,seeingatrendorspottingamomentaryfluctuationareareaswhereanold-fashionedmovingneedlemeterisoftenbetterthanadigitaldisplay.Manydigitalmetermanufacturershave addedaquickrespondingbargraphmimickingananalogmeterscale.Ourbargraphexampleduplicatesthis feature. Let’sstartwithacloseupofacharacter,“T”asifitwereaddedtoCGRAM:
80
LCDModules 16 8 4 3
4 2
2 1
1 0
Row
Value
0
31
1
4
2
4
3
4
4
4
5
4
6
4
7
0
Thecharacter“T”isformedfroma5x8matrix,withthebottom rowreservedfortheunderscorecursor.We’venumberedtherows 0…7,toptobottomandcolumns0…4,righttoleft.Tostorethis characterinformation,the44780controllermapseachrowintoa memorybyte,withthebottomfivebitsmappedintothedisplay cells—1foranopaquepixeland0foratransparentpixel.We cancalculatethevalueofthecorrespondingbytebysumming theopaquepixels.Forexample,thecapofthe“T”hasthebinary value00011111,whichwemayconverttodecimalas16+8+4+ 2+1,or31.(Thethreemostsignificantbitsmaybeanything,as theyarenotusedincharactermapping.We’llmakethem000for convenience.)
Theeightcustomcharactersareassignedvalues0…7.Towritealleightcustomcharacterstothedisplay, therefore,thesyntaxisLCDWrite…[0,1,2,3,4,5,6,7]. Tocreatecustomcharacters,wemustwritetheirrowbytevaluestoCGRAM.We’llaccomplishthisthrough MBasic’sall-purposeLCDWriteprocedure,LCDWrite…[CGRAM+Offset,Value].CGRAMistheaddress ofthefirstbyteofCGRAMmemory,andvalueisthebytevalueassociatedwiththeparticularaddress. Eachbytefollowsinroworder,andeachcharacterfollowsincharacterorder.Thefollowingtableprovides theoffsetforeachrow,foreachcharacter.Fortunately,werarelymustkeeptrackofindividualCGRAM values,astheHD44780controllerchipdoesitforus. Ifwewishcharacternumber0to containournew“T,”wewould Row 0 simplyexecuteLCDWrite… 0 0 [CGRAM,31,4,4,4,4,4,4,0]. 1 1 Thisprocedurefirstsetsthewriting 2 2 tooccuratCGRAMposition0.(We 3 3 couldhavewrittenthisCGRAM+0.) 4 4 Thenexteightargumentsarethebyte 5 5 valuesofthecharacterrows,inorder 6 6 row0…row7.Ifwehaveusedthe 7 7 normalinitializationstringforthe LCDmodule,theLCDmoduleisinauto-increment modeandeachbytewrittenisautomaticallyplacedin thenextmemorylocationbytheHD44780.Ifwehave asecondcustomcharactertodefine,wewouldstartit atCGRAM+8,andthethirdatCGRAM+16.(Ifitimmediatelyfollowedthefirstdefinition,wecouldskip theCGRAM+8andallowtheinternalauto-increment featuretodefinetheaddress.) OurbardisplayisbasedonworkbyLarryPhipps, afriendoftheauthor,whodevelopedaquickacting displayreferenceusedinadjustinghisamateurradio equipment.Westartbydefiningfourcustomcharacters:
81
CharacterNumber 1
2
3
4
5
6
7
8
16
24
32
40
48
56
9
17
25
33
41
49
57
10
18
26
34
42
50
58
11
19
27
35
43
51
59
12
20
28
36
44
52
60
13
21
29
37
45
53
61
14
22
30
38
46
54
62
15
23
31
39
47
55
63
Character0 16 8
4
2
1
0
16
1
16
2
16
3
21
4
16
5
16
6
16
7
0
Chapter5 Character1
Character2
0
20
0
21
1
20
1
21
2
20
2
21
3
21
3
21
4
20
4
21
5
20
5
21
6
20
6
21
7
0
7
0
0
0
1
0
2
0
3
21
4
0
5
0
6
0
7
0
Character3
Customcharacter3isavisualplaceholder;itfillsthedisplaywithdots.Theotherthreecharactersshowactivity,withone,twoorthreeverticalbars.Here’showwemightwritethesecustomcharactersintoCGRAM: LCDWRITERegSel\Clk\RdWrPin,LCDNib,[CGRAM,16,16,16,21,16,16,16,0] LCDWRITERegSel\Clk\RdWrPin,LCDNib,[CGRAM+820,20,20,21,20,20,20,0] LCDWRITERegSel\Clk\RdWrPin,LCDNib,[CGRAM+1621,21,21,21,21,21,21,0] LCDWRITERegSel\Clk\RdWrPin,LCDNib,[CGRAM+240,0,0,21,0,0,0,0]
A16characterdisplay,usedtotallyforbars,permitsdisplaying0…48.Larry’sadjacentbarshaveaspace sincetheLCDmodulehasaone-pixelgapbetweenadjacentcharacters.Theresultisuniformlyspacedverticalbarsacrossthefulldisplaywidth. We’llassumethatthebargraphistodisplayavalueheldinabytevariableTempandthatTempisscaled 0…48.Ourstrategyfordisplayingbarsisthus: GetnewvalueofTemp Determinewhichcharacterswillbeallbars(Char(2)) Writethosecharactersasallbars Determinehowmanybarswillbedisplayedtotherightofthelastallbars character Displaythataseither0(Char(3),1(Char(0)or2(Char(1)bars Fillanyremainingspacewithalldots(Char(3))
Ourdemonstrationprogramcyclesthrough0…48bars,withonesecondbetweensuccessivebardisplays.If weremovetheintentionalonesecondpause,wecanupdatethebarapproximately100times/secondassumingourPIChasa20MHzclockandtherearenolengthycalculationsinvolvedtodetermineTemp. Program5-5 ;ProgramBarGraphSample ;Varibles
82
LCDModules ;-------LCDNib i j x y Temp
Var Var Var Var Var Var
PortB.Nib1 Byte Byte Byte Byte(3) Byte
;Constants ;--------- RegSel Con Clk RdWrPin
B0 Con Con
B1 B2
;Initialization ;-------------Pause500 y(0)=3 y(1)=0 y(2)=1
;AllowstheLCDtoinitialize
LCDInitRegSel\Clk\RdWrPin,LCDNib GoSubLoadBar Main End
Fori=0to48 ;executiontime10.08mSec Temp=i x=Temp/3 ;div LCDWriteRegSel\Clk\RdWrPin,LCDNib,[SCRRAM] j=0 Whilej1023)moveinstepsthatareamultipleofthe oscillatorclockperiod. We’llwrapupHPWMwithtwofinalpoints: Howtoturnitoff—OnceinvokedwithaHPWMcommand,MBasicprovidesnowaytoturnthePWMmodule off.ThePWMmodulemaybeturnedoffandtheC1orC2pinsreturnedtonormalinput/outputuseby clearingtheassociatedcontrolregisterwiththefollowingcommand. CCP1Con=$0 ;turnsoffthePWMgenerator1(PinC2) CCP2Con=$0;turnsoffthePWMgenerator2(PinC1)
Criticalperiod/dutyvalues—InworkingwithHPWM,Ifoundafewcriticalcombinationsofperiodandpulse thatcausedtheoutputtoceasefunctioningandstayfrozenatlogical0.Youshouldavoidthesecombinations.BasicMicroisawareofthisproblemanditisscheduledtobefixedinversion5.3.0.0. AvoidTheseBadValuesofPeriod&Pulse Period Pulse 1023 512and513 4095 2048through2055 16383 8192through8223
AfterthisdetourtoexamineHPWM,let’sreturntoProgram24-2. PWMC2 PWMPrd Con
Con 2048
0
Wefirstdefinetwoconstants.PWMC2isanaliasthatweusetosettheCCPxargumentinHPWMtoactivate thePWMmoduleattachedtopinC2.PWMPrdistheperiodargumentinHPWM.I’vepickedthevalue2048, whichcorrespondstoaperiodof102µs,orafrequencyofabout10KHz,andwhichisfreeofcriticalvalues thatcauseHPWMtofail.Why102µsandnotsomeothervalue?Aswithmostthingsinengineering,there isatradeoff.Toavoidacousticalnoise,wemustkeepthefrequencyabovetheaudiblerange.But,aswe increasefrequencystraycapacitanceandinductancestarttobeaproblem,andswitchinglossesincrease.I selected10KHzasareasonablecompromisebetweenthesecompetingobjectives. Main ForDutyCyc=0toPWMPrdStep25 HPWMPWMC2,PWMPrd,DutyCyc Pause1000 Next GoToMain
Themainprogramlooprampsupthemotorfromstoptofullspeedbyslowlyvaryingduty.Aswelearned inChapter16,andsummarizedearlierinthischapter,byvaryingtheon/offtimeofthePWMwaveform,it, ineffect,appliesavariablevoltageacrossthemotor. RunProgram24-2andseewhathappens.Verylowvaluesofdutylikelywon’tresultinenoughvoltageto startrotatingthemotorshaft,sotheremaybeafewsecondswherenothingseemstobehappening.Then, themotorwillslowlystarttorotate,graduallyincreasingspeedtomaximum.Then,itwillstopandthe processwillbeginagain. Ifyouputanaveragereadingmeter,suchasananalogvoltmeter,acrossthemotorconnections,youshould seetheaveragevoltageslowlyrampup.Figure24-8showsthevoltageandcurrentwaveformsacrossthe motorforadutycycleof18.1%,correspondingtoanaveragevoltageofabout2.2V.Sincetheoscilloscope’schannel1isconnectedtoQ1’sdrain,alowvoltagecorrespondstocurrentflowthroughthemotor. Figure24-9showsthesameparameters,butwithadutycycleof92.7%,correspondingtoanaveragevoltage of11.1voltsacrossthemotor. 578
DCMotorControl
Figure24-8:Program24-2OutputCh1:Q1Drain Voltage;Ch2:MotorCurrent(50mA/div).
Figure24-9:Program24-2OutputCh1:Q1Drain Voltage;Ch2:MotorCurrent(50mA/div)].
Program24-3 Now,let’swireupthetachometercircuitasshowninFigure24-10. Program24-3rampsupthemotor,stillinanuncontrolled,openloopmode,andreadsthetachometerpulse width.We’lluseProgram24-3toverifythatourtachometercircuitisfunctioningandseehowitbehaves, particularlyatlowspeeds.We’lloutputseveralmeasuredandcomputedvaluestotheserialportforlater analysis.
Figure24-10:Motorcontrollerandtachometerconnection.
579
Chapter24 ;Program24-3 ;MotorPWMversusTachFrequency ;Constants ;------------PWMC2 PWMPrd TachPin Low2Hi Hi2Low HTab MinPeriod MaxPeriod DCStep AvgNumber MinDutyCyc
Con Con Con Con Con Con Con Con Con Con Con
0 2048 C5 1 0 9 200 8000 8 200 368
;Variables ;------------DutyCycVar TachWid j k Avg Freq PctGood RealDC RPM
Word Var Var Var Var Var Var Var Var
;usedinHPWMforduty Long ;measuredtachometerpulsewidthus Byte ;counter Byte ;counter Long ;averagepulsewidth Float ;floatingpointtachfrequency Float ;floatingpoint%ofgoodtachdata Float ;floatingpointdutycycle% Float ;computedmotorRPM
;constanttoactivatePWMonC2 ;for102usperiod ;tachometerinputpin ;constantforPulsIn ;constantforPulsIn ;thetabcharacterforoutput ;minimumvalidpulsewidthunits ;maximumvalidpulsewidthunits ;stepsizefordutycycleramp ;howmanytachometerreads ;startingpointtogetmotormoving
;Initialize ;------------EnableHSerial SetHSerial H115200 Main
ForDutyCyc=MinDutyCycto(PWMPrd-DCStep)StepDCStep HPWMPWMC2,PWMPrd,DutyCyc Avg=0 k=0 Forj=1toAvgNumber PulsInTachPin,Hi2Low,TachWid If(TachWid>MinPeriod)AND| (TachWidMinPeriod)AND| (TachWidMinPeriod)AND(TachWidTargetthemotorisrunningtooslowly ;soweturnthedriveonbytakingoutputpinhigh ;Otherwisewearetoofast,soweturnitofftoslowdown IfTachWid>TargetThen HighMotorPin Else LowMotorPin EndIf GoToMain ;Initialize ;------------Target=2678600/RPM
Westartbycomputingthepulsewidththatcorrespondstoourtargetspeed.(RPMisdefinedasaconstant.) Howdowearriveatthisformula? 10 6 ≈ 2.6786 × 10 6 Tunits = RPM × 8 × 2 × 1.4 60
583
Chapter24 RPMx8x2yieldsthenumberoftachometerhalf-pulsesperminute.Thereciprocalofthisquantityisthedura-
tionofeachhalf-pulseinseconds.Multiplyingby106resultsinmicrosecondsanddividingby1.4converts microsecondstounitintervals,asreturnedbyMBasic’sPulsInfunctionwitha20MHzclock.Combining allthenumericalconstants,theresultis2678600/RPM.Foratargetspeedof1750RPM,thetargetpulse lengthis2678600/1750,or1531unitsteps. Wethenspinthemotorforabriefperiodsothatthetachometerwillprovideaccurateresults.(Sincethemotorisdriventhrougha2N7000lowsideswitch,ahighontheoutputpinturnsthemotoron.) OutputMotorPin HighMotorPin Pause100
Themainprogramloopimplementsoursimplecontrolstrategy;ifthemotorisrunningslowerthanthe target,applyfullpower.Ifit’stoofast,turnthepoweroff. Main
Repeat PulsInTachPin,Hi2Low,TachWid Until(TachWid>MinPeriod)AND(TachWidTargetThen HighMotorPin Else LowMotorPin EndIf GoToMain
Implementingourbang-bangalgorithmissimple:Iftooslow(TachWid>Targer)thentakeMotorPin high,therebyapplyingfullpowertothemotor.Ifnot,themotormustberunningtoofast,soweremove powertoitbydroppingMotorPinlow. Prettysimple,isn’tit?Let’sseehowwellitworks.Figures24-14and24-15showthevoltageacrossthemotor operatingat2000RPMundertwoconditions;noloadandloadedwithfrictioncreatedbypressingafinger lightlyagainstthesideofthespinningmotorshaft.Atnoload,themotormaintainsitsspeedwithavoltage dutycycleofabout12.8%.Whenloadedwithfingertipfriction,thedutycycleincreasesto76.3%.(Sincethe off/onpulsesaresolong—nearly10ms—theunloadedspeedversusdutycyclegraphofFigure24-13can’tbe directlyapplied.)ImonitoredthemotorspeedwithaGeneralRadioStrobotacwhileapplyingtheload,verifyingthemotorstayedinspeedregulation.(Remember;lookingatQ1’sdrain,lowcorrespondstomotoron.)
Figures 24-14: Unloaded Motor Voltage BangBang Controller Ch1: 2N7000 Drain; Ch2: unused.
584
Figure24-15:LoadedMotorVoltageBang-Bang ControllerCh1:2N7000Drain;Ch2:unused.
DCMotorControl Figure24-16:SpeedError—Bang-BangControl] showsmotorspeederrorversustargetmotorspeed. Atspeedsbelow1500RPM,theerrorclimbsquite rapidly,aproductofourneedtowaitforavalid speedmeasurementbeforemakinganoff/ondecision.Attheseslowspeeds,wemayhavetomake10 or20ormoremeasurementsbeforefindingagood one.Wecantakeameasurementonlyonceevery halftachometercycle,soevenonebadmeasurementatslowRPMcostsusseveralmilliseconds. Thus,thecontrolloopreactiontimebecomesslower thandesirableandspeedregulationsuffers.(We suggestanalternativeapproachintheIdeasfor modificationstocircuitsandprogramssectionof thischapter.) Figure24-16:Speederror—bang-bangcontrol.
Program24-5
Althoughoursimplebang-bangalgorithmdeliversadequatestaticspeedcontrolovertherange2000-4000 RPM,wedidnottestitforresponsetodynamicchanges,suchasquicklyappliedorquicklydisengaged loads,orinstantaneousspeedchangecommands.We’lltakealookathowproportionalcontrolreactsto speedchangecommandsinconnectionwithProgram24-5. ;Program24-5 ;MotorPWMwithproportionalcontrol ;Constants ;------------PWMC2 Con 0 ;SetkoutputforPinC2 PWMPrd Con 2048 ;For20MHz,PRF=102.5usec MinDutyCyc Con 368 TachPin Con C5 ;PulsInpin Low2Hi Con 1 ;ConstantforPulsIndirection Hi2Low Con 0 ;ConstantforPulsIndirection MinPeriod Con 200 ;Minimumperiodtobevalidunitsteps MaxPeriod Con 8000 ;Maxperiodtobevalidunitsteps ;aboveassumes20MHzPICclock RPM Con 1750 ;TargetRPM ;TheACtachometerproduces8Hzperrevolution ;ToconvertRPMtoperiod,usethefollowing ;formula ;Variables ;------------DutyCycVar TachWid ErrorVal K Gain
Word Var Var Var Var
;DutycycleforHPWM Word ;Measuredtachometerwidthinunitsteps SWord ;Errorbetweendesiredandmeasured Word Byte
;Initialize ;------------;TheACtachometerproduces8Hzperrevolution ;ToconvertRPMtoperiod,usethefollowing ;formula Clear Target=2678600/RPM DutyCyc=MinDutyCyc ;getmotorspinning Pause500 ;timetospinup EnableHSerial SetHSerialH115200
585
Chapter24 k=0 ;ApproximationtovarygainwithRPM Gain=100000/RPM Main HPWMPWMC2,PWMPrd,DutyCyc ;Wehavetokeepthisloopasfastaspossible ;Measureuntilwegetagooddatapoint Repeat PulsInTachPin,Hi2Low,TachWid Until(TachWid>MinPeriod)AND(TachWidPWMPrdThen DutyCyc=PWMPrd-10 EndIf IfDutyCyc0Then k=k-1;k=k+1forlastscan,sosubtract1 ELSE k=79 EndIf
First,weinitializetherunningsumvariablesumandcorrectforthelastkincrement.Ifwescanalength79 barcode(*123456*forexample)kbecomes0.Wecheckforthatconditionandresetittothepropervalue, 79.(Yes,itwouldbebettertofixthisproblemintheinterruptserviceroutine.)
Fori=0tok PEEKAStart+i,Temp Sum=Sum+Temp Next;i ;HserOut[“Sum:“,DecSum,13]
Wecalculatethesumofthemeasuredwidths.Ifyouwishtoseetheresultofthiscalculation,uncomment theHSerOutstatement.
Modulus=16*(k/ElLen)-1 Modulus=Sum/Modulus
Thetwostatementsabovereplicateourearliermanualcalculation.ElLenistheelementlength,9.Weset ElLenat9,not10,becauseweuseintegerdivisionand9forcesthecorrectresult,aslongasthetotalnumberofelementsreadis79orless.Wethencalculatethemodulusintermsofcounterticks,exactlyasinour earliermanualexample.
Thsld=2*Modulus
Wemustdeterminethewidththresholdtodistinguishwidefromnarrowelements.Intheory,thedivision pointshouldbetwicethewidthofthenarrowestelement,sowesetthethresholddecisionpointThsldas twicethemodulus.
IfDataDebug=1Then HSerOut[“TotalBars/Spaces:“,Deck,13] HSerOut[“Modulus:“,DecModulus,”Threshold:“,| DecThsld,13] EndIf
BysettingtheconstantDataDebugto1,wecanenableprintingofmoreintermediateresults.
If(kThsldThen WorkArray(k)=1 Else
618
BarCodeReader EndIf Next;k Return
WorkArray(k)=0
SubroutineFillWorkArrayreadsthenineelementwidthscomprisingacompletecharacterfromthe reservedmemoryblockandevaluateseachwidthaseithernormalorwide.Thenormal/widecomparison isbaseduponwhetherthemoduluswidthisgreaterorlessthanthedecisionpointTshld.Iftheelement evaluatesasnarrow,a0isplacedintoWorkArray,anine-elementbytearray.Ifitevaluatesaswide,a1is enteredinstead.ThebytevariablejholdsthecharacternumberandisevaluatedbeforecallingFillWorkArray.Therelationshipbetweenmemoryaddresses,elementsandcharactersisillustratedbelow. FileAddress(Bank1) $A0 $A1 $A2 $A3 $A4 $A5 $A6 $A7 $A8 $A9 $AA $AB … $B2 $B3 $B4 … $EE $EF
FictitiousArrayEquivalent Data(0) Data(1) Data(2) Data(3) Data(4) Data(5) Data(6) Data(7) Data(8) Data(9) Data(10) Data(11) … Data(18) Data(19) Data(20) … Data(78) Data(79)
Elements 1 2 3 4 5 6 7 8 9
CharacterNo.
0
Inter-CharSpace 1 2 … 9 1 … 8 9
1
Inter-CharSpace 2 … 7
Thememoryaddressassociatedwithelementk(0…8)ofcharacterj(0…7)iscalculatedas AStart+10*j+k. NowthatWorkArrayisfilledwiththelogicalvaluesforeachelement,subroutineCalculateValues numericallyevaluatesthebarandspacevalues. CalculateValues
;assumesWorkArrayisfilled; ;CalcultesspaceVandbarV
;------------ SpaceV=WorkArray(1)*8+WorkArray(3)*4+WorkArray(5)*2| +WorkArray(7) ;HSerOut[“Char:“,Decj,HTab,”Space:“,DecSpaceV,13] BarV=WorkArray(0)*16+WorkArray(2)*8+WorkArray(4)*4| +WorkArray(6)*2+WorkArray(8) ;Wecouldaddlimitshere,SpaceVmustbe1 Next;n Return
We’veexpandedsubroutineBadScantowriteanerrormessage.Theerrormessagesarecontainedina48elementbytearray,witheachmessageoflength16.Thisletsuscompactlystoreandwritemultipleerror messages,basedonthelowerthreebitsofScanStatus.Eachbitisexaminedoneatatimethroughashift rightsequence. GoodScan ;doublebeepandmessage ;---------- IfDataDebug=1Then HSerOut[“GoodScan”,13] EndIf SoundSpkrPin,[BeepLen\BeepHz] Return
SubroutineGoodScanisthesameasinProgram25-4. ;ReversesdigitsinDigits() ;Assumesi&temparefree ReverseArray ;------------- ;startandleftandreversedigits Fori=0to((MaxDigits/2)-1) Temp=Digits(i) Digits(i)=Digits(MaxDigits-1-i) Digits(MaxDigits-1-i)=Temp Next;i Return End
Lastly,it’snecessarytoreversethedigitorderwhereascanismaderight-to-left.Wedothisbyswappingthe firstandlastvaluesinthearrayDigits(),thenswappingthesecondandnexttolastvalues,etc.moving inwardtothecenterofthearray.Wecould,ofcourse,useMBasic’sswapfunctioninsteadoftheintermediatevariabletemp. Let’sseehowitworksinpractice.Here’ssomesampleoutputwithDataDebug=0. 031901927370 081262224533 081262224533 639785321774
628
BarCodeReader 939785321774 BadBarNumber ChecksumError 914014?????? BadBarNumber DigitReadError ChecksumError 057163170074 BadBarNumber ChecksumError
AsforProgram25-4,ifwesetDataDebug=1,weseeintermediatedatavalues.Again,I’vereformattedthe outputintothreecolumnstosavespace. i:0 i:1 i:2 i:3 i:4 i:5 i:6 i:7 i:8 i:9 i:10 i:11 i:12 i:13 i:14 i:15 i:16 i:17 i:18 i:19 i:20 i:21 i:22 i:23 i:24 i:25 i:26 i:27 i:28 i:29 i:30 i:31 i:32 i:33 i:34 i:35 i:36 i:37 i:38 i:39 i:40
Width:32 Width:18 Width:25 Width:64 Width:45 Width:22 Width:20 Width:21 Width:41 Width:21 Width:56 Width:39 Width:35 Width:34 Width:18 Width:30 Width:18 Width:29 Width:31 Width:16 Width:14 Width:16 Width:58 Width:32 Width:17 Width:29 Width:32 Width:16 Width:14 Width:16 Width:15 Width:15 Width:30 Width:14 Width:27 Width:27 Width:30 Width:14 Width:28 Width:27 Width:16
i:66 i:67 i:68 i:69 i:70 i:71 i:72 i:73 i:74 i:75 i:76 i:77 i:78 i:79 0 0 1 2
Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 0 32 18 25
75 1 1 1
25
3 13 3 4 5 6
1 %1101 64 45 22 20
151 Digit:0 3 2 1 1
7 55 7 8 9 10
32 19 32 33 34 35
8 %10011 30 14 27 27
98 Digit:2 2 1 2 2
14
36 19 36 37 38 39
9 %10011 30 14 28 27
99 Digit:2 2 1 2 2
14
10 100 %100011Digit:4 16 1 13 1 42 3 29 2
14
21
40 35 40 41 42 43
19
11 107 %110001Digit:5 17 1 27 2 46 3 17 1
15
2 139 %110111Digit:8 21 1 41 2 21 1 56 3
44 49 44 45 46 47
3 %11001 39 35 34 18
126 Digit:1 2 2 2 1
18
12 110 %111101Digit:3 14 1 61 4 20 1 15 1
15
11 25 11 12 13 14
48 61 48 49 50 51
4
108
15
13 118 %111101Digit:3 16 1 65 4 21 1 16 1
16
15
52 61 52 53 54 55
(Continued)
629
Chapter25 i:41 i:42 i:43 i:44 i:45 i:46 i:47 i:48 i:49 i:50 i:51 i:52 i:53 i:54 i:55 i:56 i:57 i:58 i:59 i:60 i:61 i:62 i:63 i:64 i:65
Width:13 Width:42 Width:29 Width:17 Width:27 Width:46 Width:17 Width:14 Width:61 Width:20 Width:15 Width:16 Width:65 Width:21 Width:16 Width:17 Width:17 Width:16 Width:25 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0
19 15 16 17 18
%10011 30 18 29 31
Digit:2 2 1 2 2
19 47 19 20 21 22
5 104 %101111Digit:6 16 1 14 1 16 1 58 4
14
23 19 23 24 25 26
6 %10011 32 17 29 32
110 Digit:2 2 1 2 2
15
27 27 28 29 30 31 1
7 16 14 16 15 15
76 1 1 1 1
15
56 56 57 58
14 17 17 16
50 1 1 1
16
081262224533 0 0 1 8 2 11 3 13 4 31 5 33 6 39 7 41 8 53 9 58 10 67 Sum:67 CheckDigit:3 GoodScan
EAN-13 Onefinalnoteandwe’llbringthecurtaindownonanotherlongchapter.Beginningin2005,forincreased internationalcompatibility,UPC-AwillbesupplementedbytheEAN-13code.ThegoodnewsisthatEAN13isalmostidenticalwithUPC-A,exceptitaddsanadditionaldigittothenumbersystemplace,foratotal of13.Itsstructureis: NumberofDigits 2 5 5 1
Content NumberSystem(CountryCode) ManufacturerCode ProductCode CheckDigit
Thenotsogoodnewsishowtheadditionaldigitisadded.EAN-13maintainsthesame59-elementstructure ofUPC-A(agoodthingindeed)andthesamebasicdigitencoding(alsoagoodthing).Theextranumbersystemdigitisderivedfromparitycomputationsonthefiveleft-of-centermanufacturercodedigits, wherebytheleft-of-centerdigitsareencodedeitherwithoddorevenparityschemes.ThecurrentUPC-A left-of-centerdigitencodingisthe“oddparity,”encodingscheme,thatis,allcharactersareencodedwithan oddnumberof1s.The“evenparity”schemeistheright-of-centerscheme,butreversed.Dependingupon whichdigitstotheleftofcenterareevenparityencodedandwhichareoddparityencoded,the13thdigit maybederived.Thismaybethoughofasasuperimposedfive-bitbinarysystem:OOOOO,OEOEE,etc. whereOOOOOindicatesallfivemanufacturerdigitsareencodedwithoddparity,OEOEEindicatestheyare encodedinthesequenceodd-even-odd-even-evenparityencoding.Thefive-bitbinaryvaluesderivedfrom theodd/evenencodingtechniquethenaremappedintothe13thdigit.Forexample,ifthefivemanufacturer digitsareencodedOOOOO,the13thdigitis0.(This,bytheway,yieldsUPC-A.And,thecountrycodefor theUnitedStatesis0,soEAN-13reducestoUPC-Ainthiscase.)Ifthefivemanufacturercodedigitsare encodedwiththeOEOEEpattern,the13thdigitis1. 630
BarCodeReader Thecheckdigitcomputationalsochanges,withthenew13thdigit(whichisthefirstdigitsequentially,asthe lastdigitremainsthecheckdigit)beingconsideredanevendigitforthepurposeofcheckdigitcomputation. Reference[25-12]providesanexcellentoverviewofthechangesbetweenUPC-AandEAN-13andshould providesufficientinformationforyoutomodifyProgram25-5toreadbothUPC-AandEAN-13barcodes andidentifywhichtypeofcodehasbeenread.
IdeasforModificationstoProgramsandCircuits •
• • • •
ModifyProgram25-5toreadbothUPC-AandEAN-13codes.Hint:ComparetheDValueforthefive manufacturerdigitsagainstanodd/eventable.Considerthedigit0forexample.Ifitisencodedwith oddparity,itis%0001101,or13.Ifitisencodedwithevenparityitis%0100111or39,assumingwe scanleft-to-right.Ifwescanthebarcoderight-to-left,thecorrespondingvalueswouldbe(evenparity) %1011000(88)and(oddparity)%1110010(114).IfDValue=13or114,theparityisodd.IfDValue =88or39,parityiseven.Or,theodd/evenstatuscanbecomputedbysimplysummingthenumberof 1sinDValue.Usetheparitystatustosetbits0…4ofanewvariableDigit13,andthenuseabyte tabletodeterminethecorresponding13thdigitvalue.(The13thdigitisn’tthedirectbinaryvalueofthe odd/evensuperencoding.) HowwouldyoumodifythecircuitryandprogramtoaddcodestoragetoexternalEEPROM?How shouldbedatabestoredandretrievedforlaterdownloadingtoaPC? AddanLCDdisplaytoshowthedecodeddigits,andinformtheuserofanerrorinscanning. Many3of9barcodesarelongerthanthemaximumvalueourprogramaccepts.Howwouldyouexpandthedecodinglength? Ourprogramstructuremaybecategorizedas“postprocessing”inthatwescanbarwidthdatainto memoryanddecodeitsvalueafterthescaniscomplete.Analternativeapproachdecodesthebarcode asthescanisinprogress.IsthisfeasiblewithMBasicandappropriateassemblercodewherenecessary fortime-criticalmatters?Howwouldyoustructuresuchaprogram?Whatadvantagesanddisadvantagesmightithavecomparedwithourpost-processingapproach?
References [25-1]
AgilentTechnologies,ElementsofaBarCodeSystem,ApplicationNote1013,(1999).Availableat http://www.semiconductor.agilent.com. [25-2] Dennon,Jack,LinuxReadsBarCodes,ELJonline,March2001.Availableathttp://www.linuxdevices.com. [25-3] HewlettPackard(nowAgilentTechnologies),LowCurrentBarCodeDigitizerIC,TechnicalData HBCC-0500,DocumentNo.5964-1563E,(October1995).Containsasuggestedcircuitthatisthebasis forHP’sA000serieswands. [25-4] AgilentTechnologies,LowCurrentDigitalBarCodeWandTechnicalDataHBCS-A000Series,DocumentNo.5964-6664E(November,1999).Coversthetypeofwandusedinthischapter.However,the pinconnectiondataisnotnecessarilyaccurate. [25-5] Baker,JohnandBauer,Wayne,TheMathematicsofBarcodes,AUnitforTechPrepMathematics Courses,MathematicsEducationDevelopmentCenter,IndianaUniversity(1999). Availableathttp://www.indiana.edu/~atmat/units/barcodes/barunit.htm. [25-6] Laurer,George,QuestionsPertainingtotheCodeandSymbolTechnology,(undated).Availableat http://members.aol.com/productupc/techques.html.Mr.LaurerinventedtheUPCbarcodeintheearly 1970’swhileatIBM. [25-7] WorthData,Inc.,BarCodePrimer(May2003).Availableathttp://www.barcodehq.com. [25-8] Code39BarcodeSpecification(undated).Availableathttp://www.barcodeman.com/info/c39_1.php3 [25-9] Thomas,Roger,BarCodesDemystified,ElectronicsWorld(September2001),reprintedathttp://www. blackmarket-press.net/info/plastic/list_1.htm. 631
Chapter25 [25-10]
IfyouwishtolookupinformationonaproductbasedonitsUPC-Acode,tryhttp://www.upcdatabase.com/. ByfarthebestofthefreewareorsharewareCode3of9fontsthatIlookedatisfromIDAutomation. com,whichmakesavailablefreeforpersonalusealimitedversionofitsCode39fontpackage(restrictedtonumbers0…9andthestart/stopsymbol).Thedownloadislinkedathttp://idautomation.com/. [25-11] AusefuldemoUPC-AgeneratorprogramforWindows,barcodemaker.exe,isavailableathttp://www. winbarcode.com/index.php.Thebarcodesgeneratedarecomplete,excepttheword“Eval”obscures halfthelead-inguardelements.Theresultingbarcodeisperfectlyreadable,however. [25-12] AnexcellentexplanationofEAN-13maybefoundisathttp://www.barcodeisland.com/ean13.phtml. [25-10]
PrintingYourOwnBarCode Figures25-12and25-13providesampleCode3of9andUPC-Abarcodesforyoutodevelopandtestthe programsinthischapter.YoumayeasilyprintyourownCode3of9andUPC-Abarcodes,however. 3of9BarCodes Code3of9barcodesaretheeasiesttoprint.First,youmustdownloadandinstallaCode3of9barcode font.Onesourceoffree3of9TrueTypeformatbarcodefontsisBarcodes,Inc.,http://idautomation.com/. Downloadthedemonstrationpackage,whichisfullyfunctionalforthedigits0…9.Morecomprehensive, butnotfree,barcodefontpackagesareavailableforpurchasefromthissupplier. UseanyWindowswordprocessingprogram,suchasMicrosoftWordorNotepad,totypetheinformation youwishtoconverttoabarcode.Thefirstandlastcharactermustbeanasterisk“*”symbol.Ifyouuse MicrosoftWord,thedefaultsettingscauseleadingandtrailingasteriskstobeinterpretedasboldfont commandsandanytextbetweenthetwoasteriskstobolded.Youmaydisablethisautomaticboldingfrom Word’sTools|AutoCorrectmenu.Selectthetab“AutoformatasYouType”anduncheckthebox“*bold* and_italc_withrealformatting”under“ReplaceasyouType.”Afteryouhavetypedtheinformationto beconvertedtoabarcode,suchas*1234*andthenselectthetext(includingtheleadingandtrailing asterisks)andchangethefonttothebarcodefontyouearlierdownloaded.
Figure25-12:SampleCode3-of-9barcodes.
Figure25-13:SampleUPC-Abarcode.
UPC-ABarCodes Fornoncommercialexperimentation,theeasiestwaytoprintaUPC-AbarcodeisthroughtheWindows programbarcodemaker.exeavailableforfreedownloadathttp://www.winbarcode.com/index.php.The downloadedprogramisfullyfunctional,butaddstheword“eval”totheleadingandtrailingbars,andprints thosebarshalf-height.Theresultingbarcodesproperlydecode. 632
CHAPTER
26
SendingMorseCode Althoughhand-sentMorsecodemaybearchaic,it’sstillaninterestingandimportantpartofthehobbyof AmateurRadio.We’regoingtobuildanelectronickeyertosimplifythetaskofsendingMorsecode.Even ifyouhavenointerestinMorsecode,don’tskipthischapter,aswe’lldelveintodecodingvariablelength codesusingabinaryweightedtreeandlearnafewotherusefultechniquesaswell. Akeyertranslatescontactclosuresfromapaddleintoperfectlyformedandspaceddots,dashesandspaces. Spaces?Yes,spaces.Spaces—theidletimebetweendotsanddashesandbetweenlettersandwords—are asimportantasthedotanddashelementsinsendingandreceiving Morse. Apaddle,asillustratedinFigure26-1isnothingmorethanapairof single-pole,singlethrowswitches,operatedbypressingonelever ortheother.And,sincetheswitchesoftheFigure26-1paddleare independent,bothmaybeclosedatonce.Pressingoneleversends dots,pressingtheothersendsdashesandpressingbothsendsalternatingdotsanddashes.(Thefirstlevercloseddetermineswhetherthe firstelementsentisadotoradash.)Theabilitytoautomaticallysend alternatingdotsanddashesbysqueezingbothpaddleleversisknown Figure26-1:AMorsecodepaddle. inhamradioterminologyasiambickeyingandthepaddleofFigure 26-1isaniambicpaddle.Thetermiambiccomesfromthewordiambusedtodescribealternatingshortand longsyllablesinpoetry.FromeighthgradeEnglishclassyoumayrecallthatiambicpentametermeanseach lineofthepoemhasfivealternatingshort/longsyllables,suchasShakespeare’sSonnet49: Toleavepoormethouhastthestrengthoflaws, SincewhytoloveIcanallegenocause.
Basedonthestatusofthedotanddashlevers,ourkeyerautomaticallycompletesthecorrectlengthdotor dash,sendsalternatingdots/dashes,addsthecorrectend-of-elementspaceanddisplaysthesentletters(includingwordspaces)onanLCDdisplay.Itusestworotaryencoderstoselectandsetimportantparameters, suchassendingspeedandthedot/dashratio.
MorseCode101 WefirstranintoMr.MorseandhiscodeinChapter17torespondinatelephoneremotecontrolsystem. Let’ssummarizewhatMorsecodeisandhowitworks.Morsecodeiscomprisednotonlyof“dots”and “dashes”but,equallyimportantly,spaces.Thedurationofdots,dashesandspacesaredefinedwithrespect tothedurationofasingledot.Therelationshipis:
633
Chapter26 Element Dot Dash Inter-ElementSpace Inter-letterSpace Inter-WordSpace
RelativeLength 1 3 1 3 7
Morseisavariablelengthcode,wherethemostcommonlettersarerepresentedbytheshortestcombinationof elements.E,forexample,isthemostcommonletterintheEnglishalphabetandisassignedtheshortestpossibleMorsecharacter,asingledot,andcanbetransmittedintheintervaloftwodotlengths—oneforthedot, oneforthespacefollowingthedot.Q,incontrast,infrequentlyoccursinEnglishandisassignedalongsymbol,dash-dash-dot-dash,andrequires14dotlengthstosend—threedashesatfourdotlengthseach(threefor thedashplusoneforthefollowingspace)andonedotoftwodotlengths(oneforthedot,oneforthespace). HerearethemostcommonMorsecharacters,alongwiththreespecial“prosigns”orproceduresignals,AR, SKandSN.Aprosignissentasoneletter,thatis,forARthereisonlyonedotspacebetweentheAandthe R,notthreedotspacesfortheseparateletters“A”followedbyan“R.”Thethreeprosignsmeanendofmessage(AR),endofcommunications(SK)andreadytoproceed(SN)andarewidelyusedinamateurradio Morsecommunications. 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L
_ . . . . . _ _ _ _ . _ _ _ . . _ . . . _ .
_ _ . . . . . _ _ _ _ . . . . _ . . _ . _
_ _ _ . . . . . _ _
_ _ _ _ . . . . . _
. _ .
. .
_ . . _ _ .
. . _ .
_ _ _ _ _ . . . . .
M N O P Q R S T U V W X Y Z ? “/” . , = SK AR SN
_ _ _ . _ . . _ . . . _ _ _ . _ . _ _ . . .
_ . _ _ _ _ .
_ _ . . .
. . _ . . _ . . _ _ . . _ .
_ . _ . _ . _ . . . . . . .
. _
_ _ _ . _ _ _ . . _ _ _
. . . _ _ . . .
. _ _ _
Let’sgetafewmoreconceptsoutoftheway.AmateurradiooperatorstransmitMorsebyoff/onkeyingof atransmitter,atechniqueusuallycalled“CW”orcontinuouswavetransmission.Dotsanddashesrepresent “keydown”output;spacesaretransmittedasnosignalor“keyup.”Thistechniqueisbetterdescribedas ICW,orinterruptedcontinuouswavetransmission,butthat’snotwhathamscallit.Moderntransmittersor transceivershaveacontrolvoltageof12Vorlessthat,byconvention,ispulledtogroundtoputthetrans634
SendingMorseCode mitterinthe“keydown”ortransmitstate.Foroperatorconvenience,keyersusuallyprovideanaudiosignal, orsidetone,thattracksthetransmitterkeying,asit’salmostimpossibletoaccuratelysendevenmoderate speedMorsewithoutacousticalfeedback.Finally,althoughthetheoreticallyperfectdot/dashratiois1:3, someoperatorspreferlighter(shorterdots)orheavier(longerdots)characteristics.(Itmayalsobenecessary toadjusttheweighttocompensatefortheturnon/turnofftimeoftheparticulartransmitterwithwhichthe keyeristobeused.)Thedot/dashratioiscalledweighting,orweight,andwe’llmakeitadjustableinour finaldesigns.(Thetermweightitselfcomesfromthedaysofmechanicalsemiautomatickeysthatuseda vibratinglevertocreatedots;thespeedofthedotswaschangedbymovingaweightcloserorfurtherfrom thespringpivot;whilethedotdurationwaschangedbyincreasingordecreasingtheweight.)
Programs Figure26-2showsthecircuitarrangementfor Program26-1.Thepull-upresistors,R1andR2are 1K,sothat5mAcurrentflowsthroughthepaddle contacts.Wewishtokeepthecurrentthroughthe paddlecontactssufficientlyhightoensurereliable contact,and5mAisareasonablevalue,butmaynot beenoughforsomecontactmaterials.Additionally, apaddleisusuallyconnectedtothekeyerthrough Figure26-2:CircuitconfigurationforProgram26-1. aconnectingcableseveralfeetlongandhenceis subjecttostray60HzACpickup.Bykeepingthe pull-upresistorvaluesinthe1Kandlessrange,wereducestrayvoltagesthatotherwisemightbereadas falsepaddleclosures.(Inauseableversion,wemustalsobeconcernedabouttransmittedradiofrequency energybeingcoupledintothekeyer,andwemayfinditnecessarytoaddradiofrequencychokesandbypass capacitorstoallI/Oleads.) Thebuzzerisapiezo-electricsounder,RadioShackpartno.273-054thatoperateson6V.Itputsoutmore thanadequatevolumeforourbrieftest.(WeonlyusethebuzzerinProgram26-1;ifyoudon’twanttospend themoneytobuyone,skiptoProgram26-2.)Akey-downconditiondropsA0low,therebysoundingthe buzzerandilluminatingLEDD1. Program26-1 ;Program26-01 ;minimalistkeyer ;Constants ;---------------WPM Con TonePin Con DashPin Con DotPin Con
25 A0 B4 B5
;Variables ;---------ELtime DashCon DotCon
Word ;Elementlengthinmilliseconds PortB.Bit4 PortB.Bit5
Var Var Var
;speedinWPM ;Pinforbeep/Morseoutput ;frompaddle ;frompaddle
;Initialization ;-------------InputDotPin InputDashPin OutputTonePin ELtime=1200/WPM;FromPARIS=50Elements=1Word
635
Chapter26 LowTonePin Pause250 HighTonePin Main IfDashCon=%0Then GoSubDashOut EndIf IfDotCon=%0Then GoSubDotOut EndIf GoToMain DotOut ;----- Return
LowTonePin PauseElTime HighTonePin PauseElTime
DashOut ;----- Return End
LowTonePin Pause3*ElTime HighTonePin PauseElTime
Tokeepthefocusonconcepts,wedefinethecodespeedasaconstant. WPM
Con
25
;speedinWPM
Morsecodespeedisuniversallydefinedin“wordsperminute”andthe“standardword”“PARIS”iscomprisedof50elements,includinginter-character,inter-letterandinter-wordspaces,whereanelementisequal toonedotlength.I’vesettheconstantWPMat25,for25wordsperminute.Nextwecalculatethedotlength, ourbaselengthoftime,inmilliseconds. ELtime=1200/WPM;FromPARIS=50Elements=1Word
Thedivisor,1200,isderivedfromthestandard50elements=1wordreference.Thus,theelementspersecond(EPS)isrelatedtothespeedinwordsperminute(WPM)by: WPM × 50el / word 60 sec/ min Or,restatinginmillisecondsandinvertingtheresulttoyieldmillisecondsperelement:
EPS =
t=
where:
60 × 1000 1200 = WPM × 50 WPM
tisthedurationofanelement,inmilliseconds
WPMisthecodespeedinwordsperminute.
ElTimeis,therefore,thedurationinmilliseconds,ofthebasicelementofMorse,oneElTimeisadot(and inter-elementspace)lengthand3*ElTimeisadashlength. Main IfDashCon=%0Then GoSubDashOut EndIf IfDotCon=%0Then GoSubDotOut EndIf GoToMain
636
SendingMorseCode Themainprogramloopscansthetwopaddlecontactsandifeitherisclosed,branchestoa“sendadot”or a“sendadash”subroutine.Supposeboththedashanddotcontactsareclosed.Howdoestheiambicaction function?It’ssimple;themainprogramloopcyclesthroughdash/dotsequences.Whicheverpaddleleveris closedfirstdeterminesthefirstelementsent;andtheloopstructureaboveautomaticallyaddsiambicfunctionality. DotOut ;----- Return
LowTonePin PauseElTime HighTonePin PauseElTime
DashOut ;----- Return
LowTonePin Pause3*ElTime HighTonePin PauseElTime
Thetwooutputsubroutinestaketheoutputpinlow,therebysoundingthebuzzer,keepingitlowforone elementlength(dot)orthreeelementlengths(dash).ThePauseELTimestatementaddsoneinter-element spaceattheendofeachdotordash.It’suptotheoperator,ofcourse,toinsertanappropriateinter-wordor inter-letterspace. Program26-2 Let’simproveProgram26-1intwoways.First,we replacethebuzzerwithasmallspeakerandletthe PICgeneratethesidetone.Second,weimprovethe paddlesensingtobetterfitwithhumanphysiology. Figure26-3showstherevisedschematic. Save,perhapsfordiodeD1,Figure26-3isself-explanatory.PinC1isoneofthe16F87x/Afamily’s PWMhardwaremoduleoutputsandtogglesbetween Figure26-3:CircuitconfigurationforProgram26-1. highandlowat1600Hz.WeletthePWMruncontinuously,andtakepinA0lowtogatethespeakeron.Sinceaspeakerproducessoundforeitherpolarityof currentflow,thisschemewillnotworkwithoutD1.D1servesasecondpurposeofavisualindicatorthatA0 istakenlow. ;Program26-02 ;secondstagekeyer ;Addmemoryandsidetonegenerator ;Constants ;---------------WPM Con OutPin Con DashPin Con DotPin Con SideTonePer Con DutyCycle Con Opened Con Closed Con
30 ;speedinWPM A0 ;Pinforsidetone B4 ;frompaddle B5 ;frompaddle 12500 ;for1600Hzbasedon20MHzclock SideTonePer/2 %1 ;forkeyingpinstatus %0
;Variables ;---------ELtime DashCon
Word ;Elementlengthinmilliseconds PortB.Bit4
Var Var
637
Chapter26 DotCon Mode LastEle HalfDot HalfDash DotStat DashStat i
Var Var Var Var Var Var Var Var
PortB.Bit5 Byte Byte ;holdslastelementdotordash Word ;durationofonehalfdotinms Word ;durationofhalfdashinms Bit ;statusofdotlever Bit ;statusofdashlever Word ;loopvar
Initialization ;------------- ;SetupIO.Dot&Dashhavepullups InputDotPin InputDashPin OutputOutPin ;setupelementtimings. ELtime=1200/WPM;FromPARIS=50Elements=1Word HalfDot=ElTime/2 HalfDash=3*HalfDot HighOutPin ;setsidetonefrequency HPWM0,SideTonePer,DutyCycle
DotStat=Opened DashStat=Opened
Main DashStat=DashCon DotStat=DotCon ;Dashcontactclosed IfDashStat=ClosedThen GoSubTurnOn DotStat=Opened Fori=1to(ElTime*3);HalfDash Pauseus140 Next Fori=1to(ElTime*3);HalfDash IfDotCon=ClosedThen DotStat=Closed EndIf Pauseus60 Next ;PauseHalfDash GoSubTurnOff EndIf ;Dotcontactclosed IfDotStat=ClosedThen GoSubTurnOn DashStat=Opened Fori=1toElTime ;IfDashCon=ClosedThen ;DashStat=Closed ;EndIf Pauseus300 Next Fori=1toElTime IfDashCon=ClosedThen DashStat=Closed EndIf Pauseus200 Next GoSubTurnOff EndIf GoToMain
638
SendingMorseCode TurnOn ;----- LowOutPin Return TurnOff ;------- HighOutPin PauseElTime Return End
Let’sstartwithsomethingsimple;thesidetonegenerator.We’lluseoneofthe16F87x/APWMhardware modulestooutputasquarewave(dutycycle50%).IfyouneedarefresheronMBasic’sHPWMfunction, pleasereviewChapter24.RememberthatoncewestartthehardwarePWMrunning,itcontinuestofunction independentlyofwhateversoftwarefunctionwemayhavethePICperform.This“setandforget”featureis animportantpartofourstrategyinthesidetonefunction.Weestablishtwoconstants,SideTonePerfor thePWMperiodandDutyCycleforthedutycycleperiod. SideTonePer Con SideTonePer/2
12500 ;for1600Hzbasedon20MHzclockDutyCycleCon
ThemaximumpossibleperiodanddutycyclevaluesforMBasic’sHPWMfunctionare16838,withboththe periodanddutycyclevariablesdefinedintermsofclockperiods.Iusea20MHzresonatorinmydevelopmentboards,sotheclockperiodis50ns.ThismeansthemaximumperiodthePWMmodulecanoutputis 16383x50ns,or819µs.Sincefrequencyis1/period,thecorrespondingfrequencyis1.22KHz.Iuseda2” diameterspeakerinmylayout,andIfoundityieldedsatisfactoryvolumewhenthefrequencywasbetween 1.5and2KHz.Isettledupon1600Hzasthesidetonefrequency.Thedutycycledeterminesthedurationof thepositivePWMoutput;forasquarewaveitisone-halftheperiod. HPWM0,SideTonePer,DutyCycle
Oncetheperiodanddutycyclevaluesaredetermined,weturnonthehardwarePWMmoduleconnectedto pinC2withtheHPWMfunction,withthemoduleselectionbytesetto0.Thespeakerisgatedoffandonby pinA0,asdiscussedearlier. We’rebuildinganiambickeyer,thatalternatesdotsanddashesautomaticallywhenbothpaddlecontacts areclosed.But,youcan’tsqueezebothpaddleleversforever—atsomepointthealternatingsequencemust endandeitherrepetitivedotsordashesaresent,oranend-of-characterspaceissent.AverygoodMorse operatorcanworkat50WPMorfaster,whereanelementlengthis24msorless.TocorrectlysendMorse atthisspeed,goodhandcoordinationisnecessaryandit’scriticalthatthekeyerreadthepaddlecontactsat thecorrecttime.ThesecondimprovementinProgram26-2iswhenthepaddlecontactstatusisread.Reference[26-2]containsadetailedexplanationoftheimportanceofreadingthestatusofthepaddlecontactsat preciselythecorrecttime.Asreference[26-2]reads: Ifatthemidpointofanelementtheoppositepaddleisstilldepressed,thenthealternatingelementwillbe sentafterthespace.Ifyoucanletgooftheoppositepaddlebeforethiscriticaltime(themidpoint),thenyou won’tgetanythingfromthatpaddle,unlessyoure-closeitbeforethefinishofthespace. Let’sseehowtoimplementthismidpointsampling. Main
DashStat=DashCon DotStat=DotCon
Atthetopofthemainprogramloopwereadbothpaddlecontactsandstoretheirstatusinthevariables DashStatandDotStat.(We’vealreadyaliasedPortB.Bit4andPortB.Bit5toDashConandDotCon, respectively.)
639
Chapter26 WecouldhavereadbothcontactssimultaneouslybyreadingallPortBbitsinonestatement,alongthelines ofthefollowingpseudo-code: PortStatus=PortB DashStat=PortStatus.Bit4 DotStat=PortStatus.Bit5
Sinceareadonlytakes50µs,however,readingthetwocontactsinsequenceinpracticeworksjustaswell asreadingthemsimultaneously. Toimplementmidpointsampling,webreakthedotanddashelementsintohalves.Inpseudo-codeouralgorithmis: IfDashcontactisclosed,takethesidetonecontrollow Waitforonehalfadashlength Duringthesecondhalfofthedashlength,readthedot Contact.Ifthedotcontactisclosedatanytime duringthesecondhalfofthedash,storethestatusasdotclosed Afterthesecondhalfofthedash,takethesidetonehigh Waitoneelementlengthforinter-elementspacing
Thefollowingcodeimplementsthispseudo-codealgorithm.
;Dashcontactclosed IfDashStat=ClosedThen GoSubTurnOn DotStat=Opened Fori=1to(ElTime*3);HalfDash Pauseus140 Next Fori=1to(ElTime*3);HalfDash IfDotCon=ClosedThen DotStat=Closed EndIf Pauseus60 Next ;PauseHalfDash GoSubTurnOff EndIf
Tobreakthedashintotwohalves,we’vechosentousetwoFor…Nextloops.SinceElTimeiscalculatedin milliseconds,itmakessensetosetthedurationofeachhalf-periodloopat0.5msor500µs.I’veadjusted thetwoPauseusargumentstomakeeachFor…Nextloopexecuteinexactly500µs.Sincethesecondhalf For…NextloophasextrastatementsreadingDotConandperformingtheIf…Thentest,itrequireslessidle timeinitsPauseusstatement. Tocalibratethelooptime,anddeterminetheproperargumentsforthePauseusstatements,addtiming statementstotheeachloophalf,alongthefollowinglines:
IfDashStat=ClosedThen GoSubTurnOn DotStat=Opened bsf PortB,0 Fori=1to(ElTime*3);HalfDash Pauseus140 Next Bcf PortB,0
ThetwoaddedassemblerstatementssetB0highforthedurationoftheFor…Nextloop,thuspermittingthe lengthoftimeittakestoexecutetobemeasuredwithanoscilloscope.We’vediscussedthistechniqueelsewhereandalsodescribedanalternativemeasuringtechniqueusingthePIC’sinternalcountertoprofilecode duration.EithermethodcanbeusedtoadjusttheFor…Nextlooptoexecuteinexactly500µs. DuringthesecondhalfFor…Nextloop,wereadthedotcontacteveryloopcycle.Ifwefindthedotcontact closedatanytimeduringthesecondFor…Nextloop,wesetthestatusvariableDotStattoclosed.Contact closuresduringthefirsthalfFor…Nextlooparenotread,inkeepingwithourdesiredalgorithm. 640
SendingMorseCode Weimplementthesamestrategyfordashes,sampling,ofcourse,thestatusofthedashcontactafteronehalf dotdurationhaspassed.
IfDotStat=ClosedThen GoSubTurnOn DashStat=Opened Fori=1toElTime ;IfDashCon=ClosedThen ;DashStat=Closed ;EndIf Pauseus300 Next Fori=1toElTime IfDashCon=ClosedThen DashStat=Closed EndIf Pauseus200 Next GoSubTurnOff EndIf
It’sinterestingtoseethedifferenceintimedelaysrequired.Theonlydifferencebetweenthedotanddash For…NextstatementsisthatthedashForstatementincludesthecomputation3*ElTime.Thissinglecomputationconsumesabout160µsoverhead. TheremainderofProgram26-2holdsthespeakergatingsubroutines. TurnOn ;----- LowOutPin Return TurnOff ;------- HighOutPin PauseElTime Return
Notethatweaddtheinter-elementoffperiodof oneelementlengthtosubroutineTurnOff. Program26-3 Program26-2workswell,andallowssending highqualityMorse.But,withboththespeed andweightsetbyconstants,it’susableonly forexperimentation.Let’snowaddtworotary encodersthatallowustochangespeedand weight. We’llusetheinterrupt-drivenencoderreading schemeintroducedinProgram6-3and6-4.If youhaven’treadChapter6yet,andinparticulartheanalysisofthesetwoprograms,youmay wishtodosonow.Sincetherotaryencoders mustbeconnectedtointerrupt-enabledpins, wemustrearrangeourcircuitryabit,including movingthetwopaddleconnectionsandthegatingpinforthespeaker.Figure26-4showsthe Figure26-4:CircuitconfigurationforProgram26-3. revisedschematic. 641
Chapter26 Inadditiontothetworotaryencoders,we’veaddeda2N7000MOSFETtokeyatransmitter.Wheninkeydowncondition,the2N7000’sgateistakenhighbypinB0,therebydrivingthe2N7000intoconductionand turningonthetransmitter. TherotaryencoderconnectionisidenticalwiththatdevelopedinChapter6,Figure6-13andwillnotbe furtherdiscussedinthischapter. Althoughweonlyadjusttwoparameters—speedandweight—ratherthandedicateoneencodertoeach variable,we’llsetthemupasafunctionselectionandvalueselectionpair.We’llfindthishelpfulwhenwe considermakingmoreparametersuser-adjustableinProgram26-4.Rotatingthefunctionselectortoggles betweenspeedandweight,whilerotatingthevalueencoderchangesthevalueoftheselectedparameter, speedorweight. ;Program26-03 ;secondstagekeyerwithvariablespeedandweight ;Constants ;---------------OutPin Con DashPin Con DotPin Con SideTonePer Con DutyCycle Con Opened Con Closed Con MinWPM Con MaxWPM Con MinWeight Con MaxWeight Con MinSel Con MaxSel Con FcnEnc Con ValEnc Con
A0 ;Pinforsidetone B1 ;frompaddle B2 ;frompaddle 12500 ;for1600Hzbasedon20MHzclock SideTonePer/2 %1 ;forkeyingpinstatus %0 ;keyleverclosed 5 ;minimumspeed 75 ;maximumspeed 0 ;weightis%change 100;maxweight 0 ;Selectionrange 1 ;maxselectionrange 1 ;Functionencodere 0 ;Valueencoder
;Variables ;---------ELtime DotTime DashCon DotCon DotStat DashStat i CurVal OldVal
Var Var Var Var Var Var Var Var Var
Word ;Elementlengthinmilliseconds Word ;dotlength(allowforweight) PortB.Bit1 PortB.Bit2 Bit ;statusofdotlever Bit ;statusofdashlever Word ;loopvar Byte(2);forallselections Byte(2);forallselections
Counter WPM Weight Selector EncID
Var Var Var Var Var
SByte SByte SByte SByte Byte
;+1or-1 ;SpeedinWPM ;Weightadjustment ;whichselection ;whichrotaryencoder
Initialization ;------------- ;SetupIO.Dot&DashhaveEXTERNALpullups InputDotPin InputDashPin OutputOutPin ;Defaultpositions WPM=20 Weight=50 Selector=0 ;setupelementtimings.
642
SendingMorseCode
ELtime=1200/WPM;FromPARIS=50Elements=1Word DotTime=(ElTime*Weight)/50
DotStat=Opened DashStat=Opened
CurVal(FcnEnc)=(PortB&%11000000)/64 OldVal(FcnEnc)=CurVal(FcnEnc)
Main
HighOutPin ;setsidetonefrequency HPWM0,SideTonePer,DutyCycle
;Sincewehavetwoencoders,needtokeeptrackofboth CurVal(ValEnc)=(PortB&%00110000)/16 OldVal(ValEnc)=CurVal(ValEnc)
;Interruptsonchangeofeitherencoder OnInterruptRBINT,ReadEncoder EnableRBINT ;2N7000isonB0.Initializeinkeyup OutputB0 bcf PortB,0 ;Readthepaddle DashStat=DashCon DotStat=DotCon ;Dashcontactclosed ;Breakkeydownintofirstandsecondhalf.Infirsthalf ;ignoreoppositelever.Sampleoppositeonlyinlasthalf ;RememberElTimeisinmilliseconds. IfDashStat=ClosedThen GoSubTurnOn ;keydown DotStat=Opened ;assumeoppositenotactivated ;Theilooptakes500ustoexecute Fori=1to(ElTime*3);HalfDash Pauseus115 ;adjustedforclockspeed ;andexecutiontime Next ;sototaltime=500us ;startthesecondhalf.500ustoexecute
Fori=1to(ElTime*3);HalfDash IfDotCon=ClosedThen DotStat=Closed EndIf Pauseus45 ;adjustedforclock ;andexecutiontime Next ;sototaltime=500us GoSubTurnOff
EndIf
;Dotcontactclosed ;Dashcontactclosed ;Breakkeydownintofirstandsecondhalf.Infirsthalf ;ignoreoppositelever.Sampleoppositeonlyinlasthalf ;RememberElTimeisinmilliseconds. ;Differenceintimingisdueto3*factorindashloop IfDotStat=ClosedThen GoSubTurnOn ;keydown DashStat=Opened ;assumenotactivated ;Likewise,eachpassthroughtheilooptakes500us ;Dottimeisadjustedbyweight Fori=1toDotTime Pauseus280 ;neededtomake500us
643
Chapter26 Next ;Startsecondhalfandlookatoppositelever Fori=1toDotTime IfDashCon=ClosedThen DashStat=Closed EndIf Pauseus190 ;neededtomake500us Next GoSubTurnOff EndIf GoToMain ;startsidetoneandkeydown TurnOn ;----- LowOutPin ;sidetone Bsf PortB,0;takegateof2N7000high;keydown Return ;turnsidetoneoffandkeyup TurnOff ;------- HighOutPin ;sidetoneoff bcf PortB,0;2N7000gatelow;keyup PauseElTime ;waitinter-elementspace Return Disable ;ReadEncoderiscalledwheneverB4...B7changesasoneofthetwo ;rotaryencodersisrotated ReadEncoder ;--------- Pause10 ;debounce CurVal(ValEnc)=(PortB&%00110000)/16 ;valueencoder CurVal(FcnEnc)=(PortB&%11000000)/64 ;functionencoder ;Whichencoderhasbeenchanged?Encodersareidentifedas ;0and1.0isvalueencoder,1isfunctionselection IfCurVal(ValEnc)OldVal(ValEnc)Then EncID=ValEnc EndIf IfCurVal(FcnEnc)OldVal(FcnEnc)Then EncID=FcnEnc EndIf ;Basedonlastvalueofencoder,determinedirection IfCurVal(EncID)OldVal(EncID)Then BranchCurVal(EncID),[S0,S1,S2,S3] AfterBranch ;Iffunctionselectencoder,updatetheselectorvalue IfEncID=FcnEncThen GoSubUpDateSelector EndIf ;Ifthevalueencoder,updatespeedorweight IfEncID=ValEncThen BranchSelector,[UpDateWPM,UpDateWeight] AfterSelector EndIf EndIf Resume ;Thefollowingfourroutinesdecodetheencodervalueand ;basedontheoldandnewvaluedeterminethedirectionof ;shaftrotation. S0 ;--------- IfOldVal(EncID)=2Then GoSubClockWise ELSE
644
SendingMorseCode GoSubCounterClockWise EndIf GoToAfterBranch S1 ;---------- IfOldVal(EncID)=0Then GoSubClockWise ELSE GoSubCounterClockWise EndIf GoToAfterBranch S2 ;---------- IfOldVal(EncID)=3Then GoSubClockWise ELSE GoSubCounterClockWise EndIf GoToAfterBranch S3 ;---------- IfOldVal(EncID)=1Then GoSubClockWise ELSE GoSubCounterClockWise EndIf GoToAfterBranch ;Ifclockwiserotation,increasevalue ;willuseCountertoupdatevalueslater ClockWise ;------------- OldVal(EncID)=CurVal(EncID) Counter=1 Return ;Ifcounterclockwisedecrease ;UseCountertoupdatevalueslater CounterClockWise ;------------- OldVal(EncID)=CurVal(EncID) Counter=-1 Return ;Iffunction=WPM,wecanupdateWPMbyaddingthecurrent ;countervaluetothecurrentWPM.Alsocheckforbadvalues ;ofWPM UpDateWPM ;--------- WPM=WPM+Counter IfWPMMaxWPMThen WPM=MaxWPM EndIf ELtime=1200/WPM;FromPARIS=50Elements=1Word DotTime=(ElTime*Weight)/50 GoToAfterSelector ;Selectordetermineswhichvariableisupdatedby ;thevalueencoder. UpDateSelector ;------------ Selector=Selector+Counter IfSelectorMaxSelThen Selector=MaxSel EndIf
;Weightdeterminesthedotlength.Keepdashlengthdetermined ;byWPM,butallowdotlengthtovaryiftheoperatorwantsto ;changeit. UpDateWeight ;----------- Weight=Weight+Counter IfWeightMaxWeightThen Weight=MaxWeight EndIf DotTime=(ElTime*Weight)/50 GoToAfterSelector End
Sinceweallowusersettableparameters,wemustsetmaximumandminimumpermittedvalues.Wedefinea seriesofappropriateconstants.Wealsoassociateamaximumandminimumvaluefortheselectionencoder. MinWPM MaxWPM MinWeight MaxWeight MinSel MaxSel
Con Con Con Con Con Con
5 ;minimumspeed 75 ;maximumspeed 0 ;weightis%change 100;maxweight 0 ;Selectionrange 1 ;maxselectionrange
Forconvenience,wealsodefineafewotherconstants.(I’veomitteddiscussingconstantswe’veseenin Program26-2.) ;Constants ;---------------Opened Con Closed Con FcnEnc Con ValEnc Con
%1 %0 1 0
;forkeyingpinstatus ;keyleverclosed ;Functionencodere ;Valueencoder
Thefunctionandvalueencodersareidentifiedbynumbers,0and1,sowecreatemoremeaningfulaliases forthesenumbers.Likewise,wedefineOpenedandClosedtorepresentthestatusofthepaddlelevers. InasmallchangefromProgram6-4,we’llkeepthecurrentandpriorencodervaluesinatwotwo-element arrays,suchthat,forexample,thelastvalueofthefunctionencoderisheldinOldVal(FcnEnc). CurVal OldVal
Var Var
Byte(2);forallselections Byte(2);forallselections
Counter WPM Weight Selector EncID
Var Var Var Var Var
SByte SByte SByte SByte Byte
;+1or-1 ;SpeedinWPM ;Weightadjustment ;whichselection ;whichrotaryencoder
And,sincewecanbothincrementanddecrementthespeed,weightandselectorvariables,we’llmakethese signedbytetype.ThevariableCounterholdstheresultofachangeinencodershaftangle,+1forclockwise rotation,and–1forcounterclockwiserotation. Initialization ;------------- ;SetupIO.Dot&DashhaveEXTERNALpullups InputDotPin InputDashPin OutputOutPin
646
SendingMorseCode
;Defaultpositions WPM=20 Weight=50 Selector=0
Weestablishthepaddleconnectionsasinputs,thesidetonegateasanoutputanddefinedefaultvaluesfor speedandweight.
;setupelementtimings. ELtime=1200/WPM;FromPARIS=50Elements=1Word DotTime=(ElTime*Weight)/50
Wehaveaddedanewtimingvariable,DotTime,andanewparameter,Weight.Weightdeterminesthe durationofadot,withrespecttoatheoreticallyidealdotlength.Weightrangesfrom0…100,with50correspondingtotheidealdotlength.IfWeight=25,thedotlengthisone-halfnormal;ifWeight=100,thedot lengthistwicenormal.
HighOutPin ;setsidetonefrequency HPWM0,SideTonePer,DutyCycle
DotStat=Opened DashStat=Opened
ThepreviousinitializationfollowsProgram26-2.
;Sincewehavetwoencoders,needtokeeptrackofboth CurVal(ValEnc)=(PortB&%00110000)/16 OldVal(ValEnc)=CurVal(ValEnc)
CurVal(FcnEnc)=(PortB&%11000000)/64 OldVal(FcnEnc)=CurVal(FcnEnc) ;Interruptsonchangeofeitherencoder OnInterruptRBINT,ReadEncoder EnableRBINT
TheabovecodetracksProgram6-4andreadsbothencoderstoestablishtheirpositionatstart-up.Bysetting boththeoldandcurrentvaluesequalaspartofInitialization,weavoidafalseupdateatstart-up.After readingthecurrentencoderpositionweenablethechangeonPortBinterrupt,RBINT,sothatshouldeither rotaryencoderberotated,programexecutionwillgototheinterruptserviceroutineReadEncoder.
;2N7000isonB0.Initializeinkeyup OutputB0 bcf PortB,0
Finally,weinitializethepinusedfortransmitterkeying,B0.Notethatwe’veusedanassemblerstatementto setthispinto0.WecouldhaveaccomplishedthisinMBasicbyviaaLowB0statement,butasavariation, we’llusethemuchfasterassemblercall. We’llskipalloftheMain…GoToMainportionofProgram26-3,exceptfortheDotTimerelatedportion,as we’vealreadyanalyzedthiscodeforProgram26-2.
Fori=1toDotTime Pauseus280 Next
;neededtomake500us
Sincewewishtosetthedotdurationindependentlyfromthedashduration,we’vemodifiedthedotrelated For…NextloopsbysubstitutingDotTimeforElTime. TheReadEncoderinterruptroutineisexecutedwheneitherrotaryencoderismovedtoanewposition.We’ve analyzedthisroutineinChapter6andwon’trepeatithere,saveforthepartsspecifictoourapplication. ;rotaryencodersisrotated ReadEncoder ;--------- Pause10 ;debounce CurVal(ValEnc)=(PortB&%00110000)/16
647
;valueencoder
Chapter26
CurVal(FcnEnc)=(PortB&%11000000)/64
;functionencoder
Wedon’tknowwhichencoderischanged,sowereadboth.
;Whichencoderhasbeenchanged?Encodersareidentifedas ;0and1.0isvalueencoder,1isfunctionselection IfCurVal(ValEnc)OldVal(ValEnc)Then EncID=ValEnc EndIf IfCurVal(FcnEnc)OldVal(FcnEnc)Then EncID=FcnEnc EndIf
Toidentifywhichhaschanged,wecomparethecurrentvaluewiththelastvalue.WesettheencoderIDvariableEncIdtoValEncorFcnEnc,dependingonwhichencoderhaschangedvalue.
;Basedonlastvalueofencoder,determinedirection IfCurVal(EncID)OldVal(EncID)Then BranchCurVal(EncID),[S0,S1,S2,S3]
Thefourpossiblevaluesofanencoderare0,1,2and3.WebranchtoroutinesS0…S3baseduponthecurrentvalueoftheencodertodeterminethedirectiontheshaftwasrotatedtoarriveatthecurrentvalue.S0 correspondstoacurrentvalueof0,andsoon.
AfterBranch ;Iffunctionselectencoder,updatetheselectorvalue IfEncID=FcnEncThen GoSubUpDateSelector EndIf
Ifthechangedencoderisthefunctionencoder,weupdateSelector.Selectordetermineswhetherthe valueencoderchangesspeed(Selector=0)orweight(Selector=1) ;Ifthevalueencoder,updatespeedorweight IfEncID=ValEncThen BranchSelector,[UpDateWPM,UpDateWeight] AfterSelector EndIf EndIf Resume
BasedonthevalueofSelector,webranchtoeitherUpDateRPMorUpDateWeight. ThefourroutinesS0…S3aresimilar,sowe’llonlylookatone,S0. S0 ;--------- IfOldVal(EncID)=2Then GoSubClockWise ELSE GoSubCounterClockWise EndIf GoToAfterBranch
Ifthecurrentencodervalueis0,anditslastvaluewas2,thentheshaftrotationmusthavebeenclockwise.If not,therotationwascounterclockwise.Wegotoanappropriatesubroutine. ClockWise ;------------- OldVal(EncID)=CurVal(EncID) Counter=1 Return ;Ifcounterclockwisedecrease ;UseCountertoupdatevalueslater CounterClockWise ;------------- OldVal(EncID)=CurVal(EncID) Counter=-1 Return
648
SendingMorseCode ClockwiserotationsetsCounterto1;counterclockwisesetsitto–1. Whenachangedpositionisfoundoneitherencoder,executiongoestoanupdateroutine,UpDateSelector,UpDateWPMandUpDateWeight.UpDateSelectorisatruesubroutine,whileUpdateWPMand UpDateWeightarepseudo-subroutines,calledwithaBranchstatementandreturningtothelineafterthe BranchviaaGoTo.Sinceallthreeupdatefunctionsaresimilar,we’llexamineonlyone,UpdateWPM. ;Iffunction=WPM,wecanupdateWPMbyaddingthecurrent ;countervaluetothecurrentWPM.Alsocheckforbadvalues ;ofWPM UpDateWPM ;--------- WPM=WPM+Counter IfWPMMaxWPMThen WPM=MaxWPM EndIf ELtime=1200/WPM;FromPARIS=50Elements=1Word DotTime=(ElTime*Weight)/50 GoToAfterSelector
ToupdatethevariableWPM,weaddCountertoit.WethenchecktoseeiftheupdatedWPMexceedsthe maximumpermittedWPM,orisbelowtheminimumWPM.Iftheselimitsarebreached,wesetWPMtoeither themaximumorminimumvalues,asappropriate.IfwechangeWPM,wealsomustcalculateanewElTime, andanewDotTime,usingthesameapproachwedidatinitialization. Finally,wehavemodifiedthesubroutinesTurnOnandTurnOfftoincludesettingandclearingthetransmitterkeyingpinB0connectedtothe2N7000gate.WeuseanassembleropcodetosetandclearB0toexecute thecommandasquicklyaspossible.Inreality,theextra50µsorsothatitwouldtakeifwereplacedbsf PortB,0byitsequivalentMBasicstatementHighB0willnotproduceanappreciabledelay. TurnOn ;----- LowOutPin ;sidetone Bsf PortB,0;takegateof2N7000high;keydown Return ;turnsidetoneoffandkeyup TurnOff ;------- HighOutPin ;sidetoneoff bcf PortB,0;2N7000gatelow;keyup PauseElTime ;waitinter-elementspace Return
Program26-4 AlthoughProgram26-3isfunctionalenoughtouseontheair,wecandomuchbetter.Whatimprovements willwemake? • AddanLCDdisplayshowingthespeedandweight. • Addauser-selectableleft/righthandoptionanddisplay. • DecodethesentMorseanddisplayitontheLCD. • Savethespeed,weightandhandselectionwhenpowereddown. Figure26-5showstheconfigurationforourimprovedfunctionalitykeyer.ItfollowsFigure26-3,butwith newpinassignmentsnecessitatedbytheLCD.TheLCDconnectionissimilartotheoneweexaminedin Chapter5sowewon’trepeattheanalysis.IusedaDisplaytech204ALCD,a20×4display.AlthoughProgram26-4usesonlylines1and4,we’llseesomepossibleusesfortheextratwolinesinthischapter’sIdeas forModificationstoProgramsandCircuitssection. 649
Chapter26
Figure26-5:Circuitconfiguration forProgram26-4.
Program26-4isverylong.Ratherthanfollowournormalstructureoflistingtheprograminfull,followed byasection-by-sectionanalysis,we’llskipthefulllisting.Program26-4,likeallotherprogramsinthis book,isavailableinanelectroniccopyintheassociatedCD-ROM.Ifyouneedalistingtofollowwhile readingtheanalysis,youmayprintonefromtheprogramfile. We’veseenalmosteverylineofcodeinProgram26-4before,eitherinProgram26-3,orinotherchapters. Hence,we’llconcentrateonnewconcepts. Datastructure—InProgram26-3,wekeptthespeedandweightvaluesinseparatevariables,WPMand Weight.TomakeProgram26-4moreextensibleandalloweasyintroductionofmoreuser-settableparameters,we’lldefineanarray,Param,toholdalluserparameters,andthemaximumandminimumpermissible valuesforeachparameter.Paramisstructuredas: Param(x)holdsthecurrentvalue,suchasspeed,weight,etc. Param(x+1)holdsthemaximumallowedvalueforParam(x) Param(x+2)holdstheminimumallowedvalueforParam(x)
Theindexxhasvalues0,3and6inourapplication.Thus,thespeedinWPMisatParam(0),themaximum allowedspeedsettingisatParam(1)andtheminimumallowedspeedisatParam(2).Tomakeiteasierto writeandunderstandthecode,wealsodefineseveralassociatedconstants:
650
SendingMorseCode WPM MinWPM MaxWPM
Con Con Con
0 5 75
;WPMselectorinParam() ;minimumspeed ;maximumspeed
Wt MinWeight MaxWeight
Con Con Con
3 0 100
;WeightselectorinParam() ;weightis%change ;maxweight
Hand Normal Reversed
Con Con Con
6 0 1
;HandselectorinParam() ;leftorrighthandpaddleconfig ;reverseleft/right
MinOff MaxOff
Con Con
2 1
;offsetofminvalueinParam() ;offsetofmaxvalueinParam()
Toseehowdefiningtheseconstantsmaketheresultingcodeeasiertofollow,let’slookatinitializingthe speed,weightandhand.(Handdetermineswhetherthepressingtheleftpaddleleversendsdotsordashes. Left-handedoperators,suchastheauthor,generallyprefertheleftlevertosenddashesandtherightdots, thereverseofsettingsusedbyright-handedoperators.) Param(WPM)=0:Param(WPM+MaxOff)=MaxWPM:Param(wpm+MinOff)=MinWPM Param(Wt)=0:Param(Wt+MaxOff)=MaxWeight:Param(Wt+MinOff)=MinWeight Param(Hand)=0:Param(Hand+MaxOff)=Reversed:Param(Hand+MinOff)=Normal
We’vesetthethreeparametersto0becausethenextstepistoretrievetheirstoredvaluesfromEEPROM. Youshouldsee,however,thatthemeaningofParam(WPM)iseasiertounderstandthanParam(0).
ImplementingLeft/RightReversalandIdentifyingSpaces Let’slookatasimplifiedversionofourmainprogramloop. Main NormalSense ;========== DashStat=DashCon ←dashtodash DotStat=DotCon ←dottodot IfDashStat=ClosedThen … EndIf IfDotStat=ClosedThen … EndIf GoToEndMain ReversedSense ;============= DashStat=DotCon ←dashtodotreversal DotStat=DashCon ←dottodashreversal IfDashStat=ClosedThen … EndIf IfDotStat=ClosedThen … EndIf EndMain IdleCount=IdleCount+1 IfIdleCount=LetterSpaceThen GoSubSpacing EndIf BranchParam(Hand),[NormalSense,ReversedSense]
Howwehandleleft/rightreversalisstraightforward.Wehaveidenticalkeydowntimingloops,exceptthat onesetreversesthedot/dashsense.WhichloopwebranchtodependsuponthevalueofParam(Hand).In
651
Chapter26 additiontoreversingthedot/dashsenseatthetopofeachtimingloop,wealsoreversethevariableswhen readingtheoppositeleverinsidethesecondhalfloops,ascanbeseenincomparingtwocorresponding samplecodesections: Normal IfDashStat=ClosedThen GoSubTurnOn
Morse(j)=Dash DotStat=Opened Fori=1to(ElTime*3)
Reversed IfDashStat=ClosedThen Morse(j)=Dash GoSubTurnOn DotStat=Opened
Pauseus115 Next
Fori=1to(ElTime*3) Pauseus115
Next
Fori=1to(ElTime*3) IfDotCon=ClosedThen← DotStat=Closed EndIf Pauseus45 Next EndIf
GoSubTurnOff
Fori=1to(ElTime*3) IfDashCon=ClosedThen←
Next
EndIf
GoSubTurnOff
DotStat=Closed EndIf Pauseus45
AsimilarreversalisintheDotStat=Closedloopsofboththenormalandreversedsections. Closeexaminationofthesamplecodeshowsanewstatement,Morse(j)=Dash,aswellassomecode addedatthebottomoftheMainprogramloop.AllarerelatedtodisplayingthesentMorseontheLCD. Let’sseehowweaccomplishthis. First,wedefineanarray,Morse,andfourassociatedconstants: Dot Dash Nil MorseLen
Con Con Con Con
-1 1 0 8
;forArrayMorse ;inarrayofsendelements ;isclassedasdot/dashornothing ;lengthofarrayholdingdots/dash/nil
Morse
Var
SByte(MorseLen);holdselements
Assume,forthemoment,thatwestartwithMorsefilledwithNil(0)values.Wehaveadded Morse(j)=DashandMorse(j)=Dotstatementstoeachdashanddotloop,sothatMorse(j)willbefilled withthedot/dashvaluesastheoperatorsendsthem.(WeincrementtheelementcounterjaspartofsubroutineTurnOff.) Thisleavestwoimportantquestionsopen: • SinceMorseisavariablelengthcode,howdoweknowwhenonecharacterhasbeensentandthenextstarts? • HowdowetranslatethearrayMorse()intocharacterstodisplayontheLCD? Let’streatthesequestionsinorder.Thefirstquestionisabitmisleading.WhileMorseisavariablelength code,itdoeshaveauniqueend-of-charactersignal—anintervalequaltothreeelementlengthswhereneither adotnoradashhasbeensent.Remember,tothinkofMorseasonlycomprisingdotsanddashesisn’tcorrect;aswesaidearlier,spacesareanintegralcomponent. Sothen,howdoweknowwhenneitheradotnoradashhasbeensentforthreeelementlengths,andhowdo wedistinguishthatfromthewordspace,whichisnodotordashsentforsevenelementlengths?Let’stakea lookatthebottomofMainprogramloopagain. 652
SendingMorseCode
IdleCount=IdleCount+1 IfIdleCount=LetterSpaceThen GoSubSpacing EndIf
ThevariableIdleCountincrementseverypassthroughthemainprogramloop.IfweresetIdleCountto0 everytimewesendadotoradash,andifweknowhowlongittakestopassthroughacompleteloopwhen neitherthedotordashleversarepressed,i.e.,theloopisidling,wecancalculatehowmanyIdleCounts correspondtoanend-of-characterspace.I’vemeasuredthetimeittakesforexecuteProgram26-4’sloop whenneitherpaddleleverispressed,basedona20MHzclock,as586microseconds.We’vedefinedanew constantIdleTimetoholdthisvalue. IdleTime
Con
586
;microsecondsforidleloopexecution
Wenowcalculatehowmanyidlepassesittakestoidentifyanend-of-characterspaceandstorethisvaluein awordvariableLetterSpace.Inordertogivetheoperatorabitofmarginforsendingnon-perfectcode (remember—thisspacingisnotautomaticallydetermined),we’llsettheend-of-characterthresholdat2.5 elementlengths,not3.
LetterSpace=(ELTime*1500)/IdleTime
Thefactor1500comesfrom(a)ElTimeisinmilliseconds,whileIdleTimeisinmicroseconds,sowemust multiplyElTimeby1000toconverttomicrosecondsand(b)oneinter-elementspace,equaltoElTime,is automaticallyinsertedaspartofthesubroutineTurnOffattheendofeachdotordash.Themainloopisnot idlewhileTurnOffisexecuting,sowemustsubtractoneelementlengthfromourcalculation,thusmaking ourthreshold1.5elementlengths,not2.5. Let’sturnourattentiontothesubroutineSpacing,whichiscalledwhenIdleCount=LetterSpace, thatis,when2.5elementlengthshavepassedwithoutadotordashbeingsent. Spacing ;-------- ;FollowingavoidsjunkatstartofLCDreadout IfFirst=FirstYesThen Return EndIf
Inordertopreventstraycharactersfromappearingwhentheprograminitializes,weavoidcallingsubroutine Spacinguntilthefirstdotordashhasbeensent.ThevariableFirstaccomplishesthistrap,asweinitializeitasFirstYesintheinitializationsectionandsetittoFirstNoeverytimeadotordashissent.Hence, beforethefirstdotordashissent,acalltoSpacingresultsinanimmediateReturn.
IdleCount=0
WemustresetIdleCountto0tobereadyforthenextspacemeasurement.
WordSpace=WordSpace+1 ;Ispauselongenoughtobeawordspace? ;Ifso,triggerawordspaceoutandresetcounter IfWordSpace=WordRatioThen WordSpace=0 IfEndWord=EndYesThen EndWord=EndNo TempStr=““ GoSubShowChar;putitonLCD EndIf EndIf
Recallthatawordspaceissevenelementslong,nominally.Hence,wecandeterminewhetherwehavea wordspaceorsimplytheend-of-characterspacebyusingasupplementalcounter,WordSpacetoseehow manyconsecutiveend-of-characterspaceshaveoccurred.HowmanytimesisSpacingcalledbeforewe decidealetterspacehasbeensent?Herewehavetodealwithanotherboundarycondition:
653
Chapter26 0
Dotor Dash
1
2
3
4
2.5ElLen 1CharSpace
4.0
5.5
7.0
Totalelapsedtimesinceendofdotor dashinelementlengths
1.5
1.5
1.5
Element/spacelength
1.0
1.5
WordSpace=WordSpace+1
Spacingiscalledfirst2.5elementlengthsaftertheendoftheprecedingdotordash.Thenexttimeitis
calledis4.0elementlengthsaftertheendoftheprecedingdotordash,andthetimeafterthat5.5element lengths.Sincewewishtogiveourselvesabitofamarginforoperatorerror,we’llsaythatanyidletimeover 5.5elementlengthsisawordspaceandaccordinglydefinetheconstantWordRatioat3.SinceweincrementWordSpacebeforetheequalitytest,settingWordRatioat3meansthatthetestsucceedsonthethird calltoSpacing. SupposeSpacinghasbeencalled,butinsufficientidletimehasoccurredtoconstituteawordspace.Hence, wehaveanend-of-characterspaceandthusarereadytoconvertthevaluesinMorse()toacharacterand displayitontheLCD.Atthispoint,wehavethecharacter’sdot/dash/nilsequenceloadedintothearray Morse,andwehavedeterminedthatavalidend-of-characterspacehasbeenreceived. Let’ssupposetheletteris“C,”ordash/dot/dash/dot.Morse()holds: 0 Dash 1
1 Dot –1
2 Dash 1
3 Dot –1
4 Nil 0
5 Nil 0
6 Nil 0
7 Nil 0
Element Character Morse()Value
IfwediagramthelettersA…ZinMorse,asshownin Figure26-6weseeaninterestingrelationship. Figure26-6’sstructureisknownasa“binary tree”incomputerscienceterms.(Thetreeis upsidedown,withthestemintheairand thebranchesdownward.)Ateachnode (element),wemakeadecisionbased uponthenextelement;goalongthedot branchorthedashbranchuntilthe nextelementhasanilvalue.Wehave thendecodedtheletter. Wemightimplementabinarytree throughaseriesofIf…Thenstatements.Let’sseehowthatmightwork Figure26-6:Morsecodebinarytree. todecode“C.” IfMorse(0)=DashThen IfMorse(1)=DotThen IfMorse(2)=DashThen IfMorse(3)=DotThen IfMorse(4)=NilThen Character=“C” EndIf EndIf Endif EndIf EndIf
654
SendingMorseCode Forsimplification,I’veomittedalltheotherconditionalbranchesinthisnestedIf…Thenstatementthat allowustodecodeT,N,M,D,K,G,O,B,X,Y,ZandQaswellasCstartingwithadashatMorse(0),butit shouldbeclearthatnestedIf…Thenstatementsare,atbest,asingularlyinelegantmethodtodecodeMorse code,nottomentionbeingslowinexecution. Somecomputerlanguagesfacilitatetreestructures,suchassupportforlinkedlists,butMBasicdoesn’t. That’snotsurprising,consideringPICsarenotintendedforheavy-dutydataprocessing.And,wecandevise aquickandefficientwaytodecodeMorsewithoutrecoursetoesotericdatastructures.Westartbynoting thesimilarityofabinarytreetoabinarynumber.Ifwesaythestartingpoint(root)valueis128;thatevery layerdownrepresentsonebinaryshifttotherightandthatadotrepresentssubtractionandadashrepresents addition,wecanmapeachMorsecharacterintoauniquenumberbetween0…255. Let’sseehowthisworksfor“C.” 0 Dash 1 64 +64
+128
1 Dot –1 32 –32
2 Dash 1 16 +16
3 Dot –1 8 –8
4 Nil 0 4 0
5 Nil 0 2 0
6 Nil 0 1 0
7 Nil 0 0 0
Element Character Morse()Value BinaryWeight Sum
Theletter“C”thuscorrespondsto128+64–32+16–8,or168.Wethencanindexintoabytetablethat hastheletter“C”atits168thpositionandquicklyretrievethecorrectdecodedcharacter. ThisweightedbinarytreeconversionforA…Z,0…9andcommonpunctuationmarksandprosignsisas follows: FirstElementisaDot 1 2 3 4 5 64 32 16 8 4
6 2
5
7 1
FirstElementisaDash 1 2 3 4 5 64 32 16 8 4
Ch Wt 4
H
6
8 4
SN
V
D
3
22
X
160 C
32 F
184
T
192
50
7
60
196
Z
64 L
176 Y
48 ?
168
K
40
U
152
N
28
I
E
144 148
24
2
140
20 SK
Ch Wt
136 =
16
7 1
132
B
12
S
6 2
200 ,
72
G
655
206 208
Chapter26 R
80 AR
Q
84 .
A
M
W J
224
86
8
96 P
216
O
228 240
104
9
244
112
0
252
120 1
124
Ifthenextelementisadot,moveupwardonelevel;ifitisadash,movedownwardonelevel
Basedonthisapproach,calculatingthebinarytreevalueforMorse()issimple;wemultiplyeachelement valuebythatlevel’sweightandsumthetotal:
IfEndLetter=EndYesThen ;wehaveanendoftheletter Temp=128 Forj=0to(MorseLen-1) Temp=Temp+Morse(j)*TreeW(j) Morse(j)=Nil;clearfornextletter Next
NotethatweearlierdefinedthelevelweightingsinthebytearrayTreeW: TreeW ByteTable$40,$20,$10,$8,$4,$2,$1
ThevaluesinTreeWarestatedinhex,where$40correspondstodecimal64,etc.Youshouldalsonoteour earlierchoiceof1,-1and0fordash,dotandnilvalueswasnotaccidental. Return
;nowgetcorrespondingcharacter TempStr=DeCode(Temp) ;PutitontotheLCD GoSubShowChar ;Getreadyfornextletter j=0 EndLetter=EndNo EndWord=EndYes EndIf
Wehavedefinedanotherbytetable,DeCode,toholdthecorrespondingletterforeachbinaryweighted Morsecharactervalue.CharactersthatareunassignedinMorsearegiventheunderscore“_”character. DeCode
ByteTable
“____5___H___4___S___^_%_V___3___”,| “I_______F_______U_?_________2___”,| “E_______L_______R___+_.___*_____”,| “A_______P_______W_______J___1___”,| “____6___B___=___D___/___X_______”,| “N_______C_______K_______Y_______”,| “T___7___Z_____,_G_______Q_______”,| “M___8___________O___9_______0___”
ThefinalstepistodisplaythedecodedcharacteratthetoplineoftheLCDdisplay.Wedothisthrough subroutineShowChar. ShowChar ;-------- ;Holdthedecodedcharactersinalength20array ;InsertnextcharacteratMindexposition BarrelAry(Mindex)=TempStr LineNo=1 ;displayonline1
656
SendingMorseCode OurLCDhas20characters/lineandfourlines.We’lluseline1,thetopline,todisplaythesentcharacter. And,foramoreelegantdisplay,we’llwritethetextlefttoright,butassoonasthelineisfilledwiththefirst 20characters,we’llinsertnewcharactersintherightmostpositionandscrolltheothercharactersonepositiontotheleft.Toaccomplishthescrolling,we’llholdtheincomingcharactersinthe20-elementbytearray BarrelAry.(Thisstructureisnotquiteaclassicalbarrelarray,sinceweintroduceanewcharacteratthe end.However,itsstructureanduseissimilartoabarrelarray;henceitsvariablename.)ThevariableMindexholdsthenextopenpositioninBarrelAryandthenewcharacterisinsertedatBarrelAry(Mindex). ;PositionLCDcursor&writethecharacterarray LCDWriteRegSel\Clk,LCDNib,[ScrRAM+LineOff(LineNo)] Fork=0to(BarrelSize-1) LCDWriteRegSel\Clk,LCDNib,[StrBarrelAry(k)\1] Next
Nowthatthenewcharacterhasbeenstoredatthedesiredposition,wemovethecursortothestartofLine1 andwewritethecontentsofBarrelArytotheLCD,onecharacteratatime.Wehavepreviouslydefined thebytearrayLineOfftoholdthelineoffsetmemoryindex.We’veextensivelycoveredtherelationship betweenLCDmemoryaddressanddisplaypositioninChapter5andwewon’trepeatithere. ;Westartatleftsideofscreen,writecharstoright. ;Whenreachthelastposition,wekeepaddingcharsat ;rightandshiftallprior ;charsonepositiontotheleft. ;HenceweonlyincreaseMindexifitislessthan19. ;Onceithits19wekeepitthere. IfMIndex=(BarrelSize-1)Then Fork=0to(BarrelSize-2) BarrelAry(k)=BarrelAry(k+1) Next EndIf
Theabovecodemoveseverycharacteronepositiontotheleft,overwritingBarrelAry(0). LineNo=4 LCDWriteRegSel\Clk,LCDNib,| [ScrRAM+LineOFf(LineNo)+CursorPsn(Selector)] Return
Finally,wereturntheLCDcursortothestatusline,Line4,andpositionitoverthecurrentlyselectedparameter. Let’sseehowwedisplaythespeed,weightandhandvariablesinLine4.SubroutineLCD_UpDateStatusis calledwheneveranyofthethreeuser-adjustableparametersarealtered.SincetheprocessforreadingtherotaryencodersislargelyunchangedfromProgram26-3,wewillconcentrateonlyontheLCDdisplayaspect. LCD_UpDateStatus ;---------------- LineNo=4 LCDWriteRegSel\Clk,LCDNib,[ScrRAM+LineOFf(LineNo)] LCDWriteRegSel\Clk,LCDNib,[DECParam(WPM)\2,”WPM“,| DECParam(Wt)\3,”Wt“]
657
Chapter26 Return
IfParam(Hand)=NormalThen LCDWriteRegSel\Clk,LCDNib,[“Normal”] EndIf IfParam(Hand)=ReversedThen LCDWriteRegSel\Clk,LCDNib,[“Revs’d”] EndIf LCDWriteRegSel\Clk,LCDNib,[ScrRAM+LineOFf(LineNo)+CursorPsn(Selector)]
SubroutineLCD_UpDateStatusappliestheprincipleswelearnedinChapter5;itmovesthecursortoLine 4andwritesthecurrentvalueofspeedandweight.Dependinguponthehandsetting,thelasttextmessage writtenistheword“normal”or“reversed.” Figure26-7showstheLCDdisplay.Thesquarecursorshowsthecurrentlyselectedparameterthatmaybe changedthroughthevalueencoder.Figure26-8showsthe 2N7000’sgatevoltagewhilesendingtheletter“K”at20WPM. OnelastadditiontoProgram 26-4isthatthe currentvaluesof speed,weightand handaresavedto EEPROMandare readatprogram launch,thereby preserving changesduring Figure 26-7: LCD display showing decodedtextandstatusdisplay, poweroff.
Figure26-8:Outputwhilesendingletter“K”.
Threesubroutines,GetParams,SaveParamsandFirstPassprovideEEPROMfunctionality. ;SaveparameterstoEEPROM SaveParams ;---------- Forn=0to2 Writen,Param(n*3) Next Return
SaveParamswritesthethreevalues,onebyteatatime,tothefirstthreeEEPROMpositions.Notethat sincetheparametervaluesareheldinParam(0),Param(3)andParam(6),weindexwithn*3.Sincewe
definetheassociatedmaximumandminimumvaluesasconstants,weneednotsaveanyotherelementsof Param(). ;ReadparamsfromEEPROM GetParams ;--------- ;GetparametersfromEEPROM Forn=0to2 Readn,Param(n*3) Next
Wereadthesavedparametersinaprocessthattracksthesaveroutine.
;Wenowtakeadvantageoffactthatatprogramtime ;MBasiczerosouttheEEPROM.Hencewetestforthis ;conditionasWPMwillbe