www.dbebooks.com - Free Books & magazines
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
! & | ^ >> <<
LogicalOperators
And Or Xor NotAnd NotOr NotXor
ComparisonOperators
FloatingPointConversion
Procedure + * LowMult HighMult FractionalMult / // ABS SIN COS DCD SQR BIN2BCD BCD2BIN Max Min Dig Rev = <> < > <= >= 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 <mode>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(Vf<0or mA ±20 Vf>VDD) 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(Vf<0orVf>VDD)—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.5V<VDD<5.5V InputType VIL(max) VIH(min) TTL 0.8V 2.0V Schmitt 0.2VDD 0.8VDD RC3/RC4Schmitt 0.3VDD 0.7VDD 6
Input Logic Levels 16F87x PIC 5
Input Voltage (V)
High 4
3
2
Undefined 1
Low 0 TTL
Schmitt
RC3/4 Schmitt
Input Pin Type
Figure4-3:Inputlogiclevelcomparison.
Figure 4-4: SN7400 TTL logic levels Ch1: X-axis (gateinput);Ch2:Y-axis(gateoutput).
Figure4-3illustratesthedifferencesbetweenthethreeinputtypes.Toseehowtheseinputdesignsdifferin practice,wecanapplyatimevarying0…5Vsignaltoaninputpinandplottheinputvoltageagainsttheoutput valueusinganoscilloscope.Ifwehaveastand-alonelogicgate,thisisastraightforwardexercise.Figure4-4, forexample,showstheinputversusoutputresultforaSN7400TTLquadNANDgate.(Toobtainanoninvertingoutput,thetestconfigurationplacestwoNANDgatesinseries,andtoyieldthefull5Vlogichigh,a2.2K ohmpull-upresistorwasaddedtotheoutputgate.)Weseeaclear,narrowtransition,withVTRANSITIONaround 1.6V,fullyconsistentwithMicrochip’sVILandVIHparametersforTTLmimickinginputpins. Ifwewishtoobtainasimilarplotwitha16F877,however,wemustsomehowdeterminethelogicalstate— highorlow—oftheinputpincorrespondingtotheinputvoltageto.Theeasiestwaytodothisissimplyecho theinputpin’svaluetoanoutputpin.Inpseudo-codethealgorithmis: 54
TheBasics:DigitalInput ReadPin: ReadInputPin-IfInputPin<>1MakeOutputPin=0 ReadInputPin-IfInputPin<>0MakeOutputPin=1 GotoReadPin
Itturnsoutthattobeuseful,theprocessofreadingtheinputpinandmakingtheoutputpinmustbedonemore quicklythanpossibleusingMBasic,we’lladdsomehighspeedassemblerintothemix.Thereasonforthe unusualpseudo-codestructure(thenotequaloperator)willbecomeclearwhenwelookattherealcode. Program4-1 ;Program4-01 InputB0 OutputB1 Main ASM { ReadIn }
btfss bcf btfsc bsf GoTo
PortB,0 PortB,1 PortB,0 PortB,1 ReadIn
;IfRB0=1thenskipsettingitto0 ;makeRB1=0 ;IfRB0=0thenskipsettingitto1 ;makeRb1=1 ;Repeattheloop
GoToMain End
Don’tworryifyoudon’tunderstandtheassemblerportionsofProgram4-1,aswewilllearnmoreabout mixingassemblerandMBasiclater.However,theactualprogramtracksthepseudo-code.Wefirstmake RB0aninputandRB1anoutputusingMBasic.Then,themainprogramisanendlessloop. ThebtfssPortB,0statementreadsthe0’thbitofPortB(RB0)andifitis“set,”i.e.,ifitreadshigh,the immediatelyfollowingstatementisskipped.Ifitislow,thestatementimmediatelyfollowingisexecuted. (ThemnemonicisBitTestFile,SkipifSet,orbtfss).
btfss PortB,0 bcf PortB,1
;IfRB0=1thenskipsettingitto0 ;makeRB1=0
TheabovecodereadsRB0andbranches,dependingonitsvalue.IfRB0isset—thatis,RB0=1,thenthe nextstatement(bcfPortB,1)isskipped.Conversely,ifRB0=0,thenbcfPortB,1isexecuted.The bcf—orbitclearfile—operatorclearsorsetstozeroabit,inthiscase,RB1.Thesetwostatements,therefore,readRB0andsetRB1tozeroifRB1iszero.
btfsc PortB,0 bsf PortB,1
;IfRB0=0thenskipsettingitto1 ;makeRb1=1
Thenexttwostatementsperformtheinverseoperation.RB0isreadasecondtimeandtested—butthistime fortheclearstate—usingthebtfscoperation.(Thebtfscoperatorworksjustlikebtfss,exceptthenext instructionisskippedifthetestedbitisclear.)IfRB0ishigh,thentheoperationbsfPortB,1isperformed,therebysettingRB1. ExecutioncontinueswiththeGoToReadIn,whichloopsbacktoreadingRB0. Toterminatethisprogram,powermustberemovedfromthePIC,oranotherprogramwrittenintoits memory. Program4-1isn’tthefastestwaytotransferaninputpinleveltoanoutputpin,butwe’lllookatmoreefficienttechniqueslater.Italsousesmultiplereadactions,therebycreatingthepossibilityofmishandlingif theinputchangesvaluebetweenthetworeadoperations.
55
Chapter4 Witha20MHzclock,thisprogramhasa1.2µsoperatingcycle.(TheSN7400gate,performingthesetasksin hardware,requireslessthan10ns,120timesfasterthanthe PIC’ssoftware.)Hence,whenweexaminetheinput/output relationshipwiththesamesetupweusedfortheSN7400 gate,wewillexpecttoseehorizontalsmearing,wherethe outputlagstheinputbythisdelay.SeeFigure4-5.Wesee VTHRESHOLDisapproximately1.5V,quiteclosetothevalue measuredfortheSN7400trueTTLgate. ModifyingProgram4-1toacceptRC0astheinputand runningthesameinput/outputsweep,weseeinFigure 4-6thehysteresisoftheSchmitttrigger.Thelow-to-high transitionoccursatapproximately3.1V,whilethehigh-to- Figure 4-5: 16F876 TTL logic levels Ch1: X-axis (RB0input);Ch2:Y-axis(RB1output). lowtransitionoccursatapproximately1.8V.Thebeauty ofseparatehigh-lowandlow-hightransitionlevelsisnoise rejection.Supposetheinputsignalhasnoiseridingonit, perhapsinducedfromhigh-speedlogicchipsonthesame board.Onceatransitionfromonestatetotheotherhas occurred,ittakesa1.3Vnoiseexcursiontocauseareverse transition.Asweshallseelater,thishysteresisaddsgreatly tonoiserejection. WeunderstandMicrochip’sdecisiontouseTTLmimickinginputsastheproductofbackwardcompatibilitywith earlierPICsandaccesstothehugebaseofTTLdevices. But,whyhasMicrochipdesignedtherestofitsPICinputs withSchmitttriggerinputsinsteadofnormalCMOSinputs,suchasthatseeninFigure4-7foraCD4001BEquad NORgate?Afterall,PICsareCMOSdevicessoitmakes Figure4-6:16F876SchmitttriggerlogiclevelsCh1: X-axis(RC0input);Ch2:Y-axis(RB1output) sensetogivethemstandardCMOScharacteristics,right?
Figure4-7:CD4001BEquad2-inputNORCMOS logic levels Ch1: X-axis (input); Ch2: Y-axis (output).
Figure 4-8: Noisy input read differently by standardCMOSandSchmittinputs.
56
TheBasics:DigitalInput IfMicrochipthoughitsPICswouldcommunicateonlywithotherintegratedcircuitsinstalledonthesame board,itlikelywouldhaveadoptedstandardCMOSinputlevels.But,PICsoftenmustcommunicatewith therealworld,throughsensorsandswitches,operatinginamuchlessbenignenvironmentwherethenoise rejectingpropertiesoftheSchmitttriggercometothefore.Figure4-8illustratestheabilityofaSchmitt triggerinputtocorrectlyreadaninputsignalinthepresenceoflargenoisevoltages. Inordertoensurethatlevelsarecorrectlyread,regardlessoftheinputtype,weshouldaimforlogic 0inputlevelsnotexceeding0.8Vandlogichighlevelsofatleast4.0V.Ifwemeettheseobjectives, allinputporttypeswillcorrectlyreadtheinputlevels.Iftheselevelscannotbeachieved,itwillbe necessarytofurtherinvestigatethedesigntoensurereliabledatatransfer. Regardlessoftheirtype,PIC inputpinsrepresentahighinput impedancetotheoutsideworld. AsreflectedinFigure4-9,the onlycurrentthatflowsinorout ofaninputpinisduetoleakage anddoesnotexceed1µA.(Inthe 16F876family,pinRA4’sleakage currentmaybeupto5µA.)For lowimpedancecircuitswemay safelyconsideraninputpinasan opencircuit,withzerocurrentflow inoroutofthepin.Ahighimped- Figure4-9:Simplifiedmodelofinputpins. anceinputpincarrieswithitthe possibilityofstaticdamage,asevenasmallstaticchargeproduceshighvoltagesintoahighimpedancepin. AlthoughtheclampingdiodestoVDDandVSShelppreventdamage,it’sstillagoodideatofollowanti-static precautionswhenhandlingPICs.Italsomeansthatinputpinsshouldbeprotectedwhenexposedtooutside worldvoltageandcurrents.Wewillbrieflycoversomeoftheserealworldissuesinthisandlaterchapters. Theexceptiontothisassumptionrelatestothesoftwareenabledinternalpull-upresistorsonpinsRB0… RB7.Iftheweakpull-upfeatureonPortBisenabledviaMBasic’sprocedureSetPullUps,theinputpins areconnectedtoVDDthroughaninternal20Kohmresistor.IfenabledthroughtheSetPullUpsPU_On ordisabledthroughSetPullUpsPU_Offprocedure,theactionappliestoallPortBpins.Inthiscase,the inputpinsources250µA. We’vereferredtopull-upresistorswithoutexplainingwhyandwheretheyareused.Supposewewishto readaswitchanddetermineifitisopenorclosed.Ifwesimplyconnecttheswitchtoaninputpin,asin Figure4-10a,wecannotbeassuredof RB0’sstatuswhentheswitchisopen. Certainly,iftheswitchisclosed,RB0 willbeatgroundpotentialandwill bereadasalogicallow.Whenopen, however,thevoltageatRB0results fromthePIC’sinternalrandomleakagecurrent,pluswhateverstraysignal thatoutsidecircuitrymayinduceinthe connectionsbetweentheswitchand Figures4-10a,b,c:Pull-uprequiredtoreadswitch.
57
Chapter4 RB0.Theresultmaybealogicalhigh,orlow,andwearewithoutanyassurancethattheswitch’sposition willbecorrectlyorconsistentlyread. Ifinstead,weconnectRB0toVDD,eitherthroughtheinternalpull-upsource(Figure4-10c)orthroughan externalpull-upresistor(Figure4-10b),whentheswitchisopenRB0willbe“pulledup”toVDDandthe switchpositionwillcorrectlybereadasalogicalhigh.
SwitchBounceandSealingCurrent Beyondassuringthatanopenswitchiscorrectlyread,apull-upresistorprovidestheswitchwithenough currenttoreliablyoperate.Inadditiontothemechanicalwipingactionofswitchcontacts,asmallDCcurrentgreatlyassistsinmaintainingreliableconductionbetweenmovingswitchcontacts.And,iftheswitch isconnectedthroughwiringwithmechanicalsplicesandcrimporscrewpressureterminals,thecurrent helpscleanoxidizingfilmfromthematingconductors.Fromtelephoneterminology,weoftenrefertothis asa“sealing”currentora“wetting”current.Henceswitchcircuitsareoftenreferredtoaswet—carryinga currentwellinexcessofthatnecessarytopullaninputpinhighorlow—ordry—carryingonlyaminimal signalcurrent.Formostmechanicalswitches,unlesswearetryingtosavepowersuchasinabatterypoweredsystem,selectthepull-upresistortosupply5to20mAcurrentflowthroughtheswitchwhenclosed. For5Vsystems,useapull-upresistorof1Kohmto250ohms.Finally,thesmallerthepull-upresistor value,thelessstrayvoltagewillbeinducedintothewiringconnectingthePICwiththeswitch. Whenamechanicalswitchoperates,thesame“contact bounce”phenomenaweobservedinChapter3withrelay contactsisseen.Inmostswitches,thecontactseparation operation(“break”)isrelativelyclean,butthecontactclosure (“make”)exhibitsmultiplebounceevents.Figure4-11shows nearly1.5msisrequiredtoreachasteadystateclosedconditioninthemicroswitchSPDTswitchbeingtested. Whyshouldwebeworriedaboutswitchbounce?The answeristhatinmanycases,wedon’tcare.Bounceisn’t aconcern,forexample,whereabaudrateswitchisread onlyatstart-up,orwherealimitswitchsensestheposition ofapartandactivatesasoftwarestopsequence.Inthefirst case,theswitchisn’toperatedwhiletheprogramexecutes Figure 4-11: Contact bounce upon closure of andinthesecondmultipleactivationsofstopsequence microswitch. isn’taconcern.Suppose,however,theswitchcountsthe numberoftimesanactionisperformed.Clearlywewant oneswitchoperationtoincrementthecountonce,not onceforeachofadozenorsobounces.Toprevent switchbouncefromrepeatedlytriggeringanoperation, wemustdebouncetheswitch. Wecandebounceaswitcheitherwithexternalelectronics,orinsoftware.
HardwareDebouncing Althoughspecializedintegratedcircuit“debouncers,”such asFairchild’sFM809microprocessorsupervisordevices, existwe’lllookatasimplecircuitdescribedinarecentisFigure4-12:Hardwaredebounce. sueofEDNMagazine,asshowninFigure4-12.[4-1] 58
TheBasics:DigitalInput Whentheswitchisopen,C1chargestoVDDandRC0isreadashigh.Whentheswitchmakes,C1isdischargedthroughR2(D1isreversedbiasedandmaybeneglected)andwillbereadaslowwhenthevoltage acrossC1dropsbelowhigh-to-lowtransitionvoltage,approximately1.8V.IfthetimeconstantofR2-C1 islongcomparedwiththeindividualbounceintervals,thedecaywillbesmoothandonlyonetransition throughVTHRESHOLDwilloccur.But,evenifspikesofseveralhundredmillivoltsoccuratRC0theoutputwill staylow,asinordertochangeitsreadstate,RC0mustseethelow-to-hightransitionvoltageofapproximately3.1V. Whentheswitchisclosed,theinputpinisconnectedtogroundthroughR2.Theleakagecurrentfromthe PICinputpinisratednottoexceed1µA,sointheworstcasewithR2at15Kohm,theinputpinwillbeat 0.015V,wellwithinthelogicallowrange. Whentheswitchisopenedafterclosure,C1chargesthroughR1andR2inparallelwithD1.UntilthevoltageacrossC1reaches0.7VfromVDD,C1chargesmostlythroughR1andD1.Hence,thechargecycleis significantlyshorterthanthedischargecycle.Thisdesignassumesthattheswitchhasbounceproblemsonly onmakeandthereforelittleornoanti-bounceeffectisrequiredonbreak. TherelationshipbetweenC1,R2andthedesireddebouncetimeTBisgivenby: R2C1 = −
TB VTHRESHOLD Ln VDD
IfwedesignforaSchmittinputwhereVTHRESHOLDfora hightolowtransitionisapproximately1.8V,andifwe makeC10.1µF,aconvenientvalue,wemaysimplifythis equationandsolveforR2intermsofTB:
R2 ≈ 10TB
R2isinKohm,andTBisinmilliseconds.Ifthedesired debouncetimeis1.5ms,R2shouldbe15Kohm.Figure 4-13showshowwellthissimplecircuitremovesthe bouncefromthesameswitchshowninFigure4-11. Tostudytheeffectofthedebouncecircuit,wesimplymake RB0equaltoRC0andrepeatthetestinanendlessloop.
Figure4-13:Externaldebouncecircuitoperation Ch1:RC0PICinput;Ch2:RB0PICoutput.
Program4-2 ;Program04-02 ;ProgramtoechoreadofC0toB0 ;Variables Temp Var Byte InputC0 OutputB0 Main PortB.Bit0=PortC.Bit0 GoToMain End
ThekeystatementintheprogramisPortB.Bit0=PortC.Bit0wheretheassignmentoperatorforcesa readofRC0andasubsequentwriteoftheresultingvaluetoRB0.Thisread/writesequenceisrepeatedevery timetheloopexecutes.Program4-2runsquiteabitslowerthanProgram4-1,withtheswitchpinRB0being readonceevery68µs,comparedwiththeonceevery1.2µsintheassemblercode. 59
Chapter4 SoftwareDebouncing Wemayalsodebouncetheswitchinsoftware.Inthesimplestcase,wesimplypauseprogramexecutionto allowtheswitchcontactstostabilize. Program4-3 ;Program04-03 ;Variables Temp Var
Byte
InputB0 OutputB1 Main PortB.Bit1=PortB.Bit0 Pause2 GoToMain End
Figure4-14showstheeffectofpausing2mafterreading theinputpin.TheactualreadingofRB0inthestatement PortB.Bit1=PortB.Bit0stilloccursveryquickly;in 0.2µsfora20MHzclockedPIC,eventhoughtheentire statementrequiresapproximately14µstoexecute.However,thesequickreadsarenowspacedapproximatelyevery 2msapart.Hence,ifthereadhappenstodetectahighduringthebounceperiod,theoutputstayshighuntilatleast thenextreadperiod.Bythattime,theswitchwillhavehad timetostabilizeandthenextreadwillcorrectlybealow. If,ontheotherhand,RB0readsalowduringabounce, theoutputdropstolowimmediately.Thenextread,2ms later,willalsoreadalow,sincetheswitchwillhaveby Figure4-14:DebounceviaPause2Ch1:RB0PIC thenstabilized.Ineithercasetheswitchissuccessfully input;Ch2:RB1PICoutput. debounced. MBasicalsoprovidesabuilt-inswitchdebounceprocedureButton,invokedas: Buttonpin,downstate,delay,rate,bytevariable,targetstate,address
Pin—istheaddressofthepintobereadandmaybeeitherapre-definedconstant,suchasB0,oravariable settothepin’saddress. Downstate—Buttontestsforaspecificinput,eitherhighorlow.Downstateisaconstantorvariable (either0or1)thatdefineswhichconditionrepresentstheswitchbeingoperated.Iftheswitchoperation causesalowtobeappliedtopin,Downstateshouldbe0;ifoperationcausesahigh,Downstate shouldbe1. Delay—aconstantorvariable(0…255)thatcontrolshowlongButtonwaitsbeforestartingauto-repeat. Auto-repeatmeansthatButtonactsasiftheswitchisrepeatedlycycled,similartotherepeatedletters obtainedwhenyouholdakeydownonyourcomputerkeyboard.IfDelayissetto0,debounceand auto-repeataredisabled;ifDelayissetto255,debounceisenabled,auto-repeatisdisabled.Delayis inunitsofthetimebuttoniscalled.Forexample,ifbuttonisusedinaloopthatrequires2msto execute,andifDelayissetto10,thenetdelayis20ms. Rate—isaconstantorvariable(0…255)thatdeterminesthetimebetweenauto-repeats.Rateisalsoinunits oftimebuttoniscalled.
60
TheBasics:DigitalInput ByteVariable—isabytevariableusedbyButtonforworkspace.Youmustdeclarethisvariable. TargetState—isaconstantorvariable(0or1)thatspecifieswhichstatepinmustbeintocauseprogram executiontobranchtoAddress. Address—Alabeltowhichexecutionwilljumpuponpin=TargetState. Program4-4illustrateshowButtonmaybeused. Program4-4 ;Program04-04 ;Variables Temp Var
Byte
InputB0 OutputB1 Main HighB1 ButtonB0,0,255,100,Temp,1,UpButton GoToMain UpButton: LowB1 Pause10 GoToMain End
Program4-4readsthestatusofaswitchconnectedas showninFigure4-15.Program4-4makesanoutput pin,B1,trackthedebouncedinputpinB0.Wefirstset B1highandtesttoseeifB0islowviatheButton debounceprocedure.Iftheswitchisopen,B0remains high,andprogramexecutionresumesafterButton withtheGoToMainstatementwhichloopsbacktosettingB1highandreadingB0.If,however,theswitchis closedandButtonreadsalowonB0,programexecutionbranchestoUpButton.UpButtonisadummy Figure4-15:Switchconnection. procedurethatsimplymakesB1lowfor10ms,after whichexecutionresumeswithsettingB1highandreadingB0throughtheGoToMainstatement.Ifyouwishthe buttonpresstodosomethinguseful,theappropriatecode wouldbeattheprocedureUpButton. Figure4-16showstheoutputofProgram4-4whereButtonissetforautomaticrepeatoperationwithDelay250 andRate250.SincetheprogramloopreadingButton takes140µstoexecute,itwillstartrepeatingafter250× 140µs,or35ms.Itwillcontinuetorepeatevery250×140 µsor35ms.Uponactivation(eitherinitiallyorfollowing eachauto-repeat)programexecutionbranchestoasimple routinethatdropstheoutputlowfor10ms. Figure 4-16: Button with Delay=250,Rate=250 Ch1:RB0PICInput;Ch2:RB1PICOutput.
61
Chapter4
Figure 4-17: Button with delay=255, rate=100 Ch1:RB0PICinput;Ch2:RB1PICoutput
F i g u r e 4 - 1 8 : A l t e r n a t i v e S w i t c h i n g Connections.
Inmanycases,weneeddebounceonly,withoneoperationforeverybuttonpush.Figure4-17showstheeffectivenessofButtonatdebouncing. Figure4-18showsthreepossibleswitchconnections.SW1andSW2correspondtoState0andState1 designsinMBasic’sUser’sGuidebuttondiscussion.WhenSW1isclosed,RB0goeslowwhilewhenSW2 isclosed,RB1goeshigh.IfSW2isinstalledonthesameprintedcircuitboardasthePIC,theconnection showninFigure4-18isacceptable.However,iftheswitchisremotefromthePIC,perhapsevenconnected byalengthycable,thedesignassociatedwithSW2requiresunprotected+5VtoberuntoSW2,thusexposingittopossibleproblems.Ifanormallyclosedswitchisavailable—perhapstheNCcontactsofaSPDT switch—thealternateconfigurationofSW3isbetter.IntheworstcaseshouldeithersideofSW3beinadvertentlygroundednodamagewilloccur.
IsolatedSwitching Justaswithswitchingisolatedloads,thereareoccasionswhenyoumaywishtoreadaswitchclosurethat cannothaveacommongroundwithyourPICcircuit.Or,youmayhavealongrunofcablebetweenthe switchandthePICandwishtoensureagainststrayinducedvoltagesorgroundcurrents. WecanapplyseveraltechniquesdevelopedinChapter3isolatingPICinputsfromswitches.Figure4-19 implementstwosimpleapproaches.RB0isswitchedthrougharelay,whileRB1isswitchedthroughan opticalcoupler.BothRB0andRB1 needdebouncingtreatment. SW1makesorbreakscurrent throughrelayK1,therebyoperating thecontactsconnectedtoRB0.When SW1isopen,RB0ishigh;when SW1isclosed,RB0islow.R1isselectedtopermitareasonablewetting current,5mAintheexample,toflow throughK1’scontacts.D1isasnubbingdiodetoreducearcingwhen SW1isopened.Forsmallrelays operatedfromlowvoltagesources, Figure4-19:IsolatingremoteswitchesfromaPIC. D1maybesafelyomitted. 62
TheBasics:DigitalInput SW2makesorbreakscurrentthroughtheLEDhalfofoptoisolatorU1.Whenilluminated,U1’sLEDsaturatesthephototransistorandpullsitscollector—andRB1—low.Whennotilluminated,U1’sphototransistor isoffandRB1istakenhighR2.R3shouldbeselectedtoensurethephototransistorisfullysaturatedwhen theLEDisilluminated,with15to20mAbeingatypicalcurrentvaluefora4N25optoisolator.R2should beselectedtoensurethephototransistor’scollectorvoltageisunder0.5VwhentheLEDisilluminated.For a4N25,wecanaccomplishthisbyacollectorcurrentof1mAorso.ThecomponentvaluesinFigure4-19 resultinanLED-onvoltageof0.15Vatthephototransistor’scollector.
ReadingaKeypad Sofar,we’velookedatisolatedswitches,withonepinforeachswitch.We’lllookatonetypeofmultiple switchassembly—calledarotaryencoder—inChapter7,andadifferenttype—thekeypad—inthischapter. Keypads,suchasthosefoundontelephonesandcalculators,arealmostalwaysmatrixswitches,asillustratedinFigure4-20.Pressingabuttonestablishesaconnectionbetweenitscolumnandrowterminals.For example,pressingthe“5”buttoninFigure4-20connectscolumn2withrow2.Manyinexpensivekeypads, includingtheVelleman16KEYmodelwe’lluseinourexperiments,areconstructedwithaconductiveelastomerdesignratherthanphysicalmake/breakswitches.Theseswitchestypicallyhaveanonresistanceof 100–200ohms,comparedwiththemilliohmrangeresistancefoundinmechanicalswitches.
1
2
Col_4
Col_3
Col_2
Col_1
Let’sseehowwemightgoaboutreadingthekeyboard.SupposeweconnectitasshowninFigure4-21. Then,wesequentiallymakepinsB4…B7outputahighandaftereachhigh,wereadpinsB0…B3toseeif anyarehigh.Ifso,wecandeterminetherownumberandcolumnnumberandfromthatidentifywhichbuttonhasbeenpressed.ThisprocessisillustratedinFigure4-22.
3
A Row_1
4
5
6
B Row_2
7
8
9
C Row_3
*
0
#
D Row_4
Figure4-20:Typical16-positionkeypad switch.
Figure4-21:KeyboardconnectiontoPIC.
R1…R4are“pull-down”resistorsandensurethatinputpinsRB0…RB3donotdriftupwardstowardsa logicalhighfrominternalleakagecurrentsorpossibleleakageacrossthekeypad’sopencontacts.R5limits thecurrentthroughLEDD1toapproximately10mAwhenRA0ishigh.
63
Chapter4
Figure4-22:Readingthekeypad.
Inpseudo-code,wewould: ScanKeyboard ForRow=B4toB7 HighRow Pause10 Column=PortB.Nib0 IfColumn<>0thenkeymusthavebeenpressed Sogotoasubroutinetodealwiththepress Ifnot,thenkeepscanningtherow NextRow GoToScanKeyboard
WecandeterminetherownumberdirectlysinceRowNumber=Row-B4+1.Column,ontheotherhand, isreadas1,2,4or8.WehaveseveralwaystocalculatetheColumnNumberfromColumn,butwe’lluse asimpleonenow.Wedefineanauxiliaryarray,TempArrayandassignTempArray(1)=1,TempArray(2)=2,TempArray(4)=3andTempArray(8)=4.Then,ColumnNumber=TempArray(Column). Program4-5readsthekeypadandthenflashesanLEDconnectedtoRA0inthesequence<flashrownumber>pause<flashcolumnnumber>. Program4-5 ;Programtotestkeypadreading ; ;thekeypadoutputpulsesaLEDwiththerow/columnvalue.LEDis ;poweredbytheportandgoestoground.Forexamplepressingthe;”8”keypulses theLEDina3-pause-2pattern. Column Row
Var Var
Byte Byte
;CounterforFor/Nextloops ;CounterforFor/Nextloops
64
TheBasics:DigitalInput Temp LED RIndex CIndex i TempArray
Var Con Var Var Var Var
Byte ;holdsthecolumnbinaryvalue A0 ;HaveanLEDhangingoffA0 Byte ;HoldstheRowValue1..4 Byte ;HoldstheColumnvalue1..4 Byte ;CounterforvariousFor/Nextloops Nib(9) ;Useforconversion
; ; ;Initialize ;========== Column=0 Row=0 Temp=0 OutputLED LowLED
;setuptheLEDpin ;wewanttheLEDoff
ForColumn=B0toB3 InputColumn Next;NextColumn ForRow=B4toB7 OutputRow LowRow Next;NextRow
;Settheseforinput
;Settheseforoutput ;wewillpulseahigh,startthemoutaslows
;holdstheactualcolumnnumber.1,2,4&8areonlylegalvalues ;sootherelementsofthearraycanhaverandomvalues TempArray(1)=1 TempArray(2)=2 TempArray(4)=3 TempArray(8)=4 ; ; ;MainHerewereadthekeypad.Puta1sequentiallyontherows ;==== andseewhichcolumnhasthehigh. ;Sincethecalledsubroutinetakesalongtimetorunandisonly ;triggeredonce,noadditionaldebounceisrequired.Thismaynot ;bethecaseforothercalledsubroutines. Loop: ForRow=B4toB7 ;Scantherows HighRow ;pulsea1acrosseachrow Pause10 ;waitabit Temp=PortB.Nib0 ;readall4columnsatonce LowRow ;restorethelow IfTemp>0ThenGoSubLED_On ;buttonpushed Next;Row GoToLoop;checkformorekeypresses
;Executeuponkeypress--atthemomentitjustflashesanLED ;---------------------------------------------------------------LED_On: ;pulseLEDnumberofrowtimes Rindex=Row-B4+1;therownumber,from1..4 Fori=1toRIndex;nowflashtheLED HighLED Pause150 LowLED Pause150 Next ;Nexti
65
Chapter4 ;nowweconvertcolumnvalue(heldinTemp)tocolumnnumber ;Columnvalueis1,2,4,8correspondingtoColumn1,2,3or4. CIndex=TempArray(Temp);conversionviaarrayindexing Pause500 ;pausetopermittheusertodistinguishrows ;fromcolumnswhenwatchingtheLED ;sameapproachtoflashthecolumnnumberusingtheLED Fori=1toCIndex HighLED Pause150 LowLED Pause150 Next;Nexti Return;LED_On End
Thecentralportionoftheprogramisthekeyscanloop,whichimplementsthepseudo-codealmostdirectly: Loop: ForRow=B4toB7 ;Scantherows HighRow ;pulsea1acrosseachrow Pause10 ;waitabit Temp=PortB.Nib0 ;readall4columnsatonce LowRow ;restorethelow IfTemp>0ThenGoSubLED_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 Whilej<x LCDWriteRegSel\Clk\RdWrPin,LCDNib,[2] j=j+1 WEND LCDWriteRegSel\Clk\RdWrPin,LCDNib,[y(Temp//3)];mod Forj=x+1to15 LCDWriteRegSel\Clk\RdWrPin,LCDNib,[3] Next LCDWriteRegSel\Clk\RdWrPin,LCDNib,[SCRRAM+$40,”“] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[SCRRAM+$40,DecTemp] Pause1000 Next GoToMain
LoadBar ;loadthebarcharactersintocharacterRAM ;------------- LCDWRITERegSel\Clk\RdWrPin,LCDNib,[CGRAM,16,16,16,21,16,16,16,0] LCDWRITERegSel\Clk\RdWrPin,LCDNib,[20,20,20,21,20,20,20,0] LCDWRITERegSel\Clk\RdWrPin,LCDNib,[21,21,21,21,21,21,21,0] LCDWRITERegSel\Clk\RdWrPin,LCDNib,[0,0,0,21,0,0,0,0] Return
83
Chapter5 Asbefore,we’veseenmuchofProgram5-5,sowe’llconcentrateonthenewelements. LoadBar;loadthebarcharactersintocharacterRAM ;------------- LCDWRITERegSel\Clk\RdWrPin,LCDNib,[CGRAM,16,16,16,21,16,16,16,0] LCDWRITERegSel\Clk\RdWrPin,LCDNib,[20,20,20,21,20,20,20,0] LCDWRITERegSel\Clk\RdWrPin,LCDNib,[21,21,21,21,21,21,21,0] LCDWRITERegSel\Clk\RdWrPin,LCDNib,[0,0,0,21,0,0,0,0] Return
SubroutineLoadBariscalledduringtheinitializationprocessandloadsourfourcustomcharactersinto CGRAM.Sinceweloadthesecharactersintheircharacternumberorder,withoutanyotherinterveningdata beingsenttotheLCDmodule,weneedonlysettheCGRAMaddressonce,andpermittheHD44780’sautoincrementfeaturetotakecareoftherest. Main
Fori=0to48 Temp=i x=Temp/3
;executiontime10.08mSec ;div
TheForiloopcyclesusthroughallpossiblevaluesofbarlength.Forthisdemonstrationprogram,welet thebarlengthvariable,Temp,equali.Thevariablexdeterminesthebreakpointbetweenallthreebarsand allthreedots.SupposeTemp=11.Thecorrespondbargraphwillhavethree“|||”charactersfollowedbyone “||.”character.Theremainingcharacterswillbetheblankidentifiers“...”.Sinceeach“|||”corresponds toavalueof3bars,wecandeterminehowmany3-barsarecontainedinTempbysimpleintegerdivision.In thiscase11/3=3.Ratherthanrepeatthisdivision,we’lldoitonceandusethevariablextoholdtheresult viax=Temp/3.So,wecannowwritex“|||”characterstothedisplay,afterfirstresettingthedisplayaddresstothetopline,character0:
LCDWriteRegSel\Clk\RdWrPin,LCDNib,[SCRRAM] j=0 Whilej<x LCDWriteRegSel\Clk\RdWrPin,LCDNib,[2] j=j+1 WEND
WeusetheWhile/WENDconstructionhere,becauseit’spossiblethatthereshouldno“|||”characters displayed,asisthecasewhereTemphasthevalue0,1or2.Sincetheconditionaltestismadeattheoutset inaWhile/WENDloop,wehaveproperlydealtwiththecasewhereno“|||”istobedisplayed.Wesimply executeLCDWrite…[2]xtimestoputupthecorrectleading“|||”characters. LCDWriteRegSel\Clk\RdWrPin,LCDNib,[y(Temp//3)];mod
Nowwedealwiththevariablenumberofbarsinthenextcharacter.There’salotpackedintothisonelineof code,sopayattention.Todeterminehowmanybarsareinthenextcharacter,welookattheremainderafter integerdivisionby3,thenumberofbarspercharacter.(InMBasic,theremainderor“modulus”operator usesthe//symbol.)Theresultis0,1or2.Iftheremainderis0,wedisplaycharacter3.Iftheremainderis1, wedisplaycharacter0.Iftheremainderis2,wedisplaycharacter2.WecouldindexintoaseriesofLCDWritestatements,basedonthevalueoftheremainder,butthat’sslow.Instead,weuseathree-elementbyte arraywedefinedandinitializedearlier:
y(0)=3 y(1)=0 y(2)=1
Thus,ifweusetheremainderastheindex,theyarraygivesusthecorrectcharactertowritetothescreen. Hence,wehaveLCDWrite…[y(Temp//3)]. Wemayhaveavoidedarrayindexmappingbyabetterselectionofcharacterorder,butthisexampleisa fragmentofalargerprogramanddisplaythatcalledfortheorderweused.Besides,arraymappingisausefultrickthatwillbehandyinotherinstances. 84
LCDModules
Forj=x+1to15 LCDWriteRegSel\Clk\RdWrPin,LCDNib,[3] Next
Now,wefinishupbyfillingwhateverisleftofthedisplaywithourblankplaceholder,character3.Wedo thiswithaFor/Nextloop,startingonepositionpastthevariablebarcharacter.
LCDWriteRegSel\Clk\RdWrPin,LCDNib,[SCRRAM+$40,”“] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[SCRRAM+$40,DecTemp] Pause1000 Next GoToMain
Finally,wewritethedecimalvalueofTemponthebottomline,pause1secondtoallowyoutoseethebar versusdigitalcountandthengotothenexttestloop.Figure5-15showstheresultsofProgram5-5.Ina programdoingusefulwork,wewoulddeletethePause1000statement.Figure5-16showstheapplication resultingfromLarry’swork.
Figure5-16:Usingabargraphdisplay.
Figure5-15:Bargraphdisplay.
References [5-1]
Hitachi,HD44780(DotMatrixLiquidCrystalDisplayController/Driver),(undated).IfyouareinterestedinthenutsandboltsofLCDwork,youwillneedtheHD44780datasheet.Hitachirecentlyspun itssemiconductoroperationsintoRenesasTechnologyandtheHD44780datasheetisavailablefor downloadathttp://america.renesas.com/products/supportdocs/hd44780.pdf.AlthoughRenesasdoesnot recommendtheHD44780fornewdesigns,newerLCDcontrollersaredownwardcompatiblewiththe HD44780commandset. [5-2] TianmaMicroelectronicsCo.,Ltd.,SpecificationforLCDModule,ModuleNo.TM162YBC6, (undated).Thisdatasheetisavailablefordownloadathttp://www.tianma.com/spec_sheets/ TM162YBC6%20SPEC.pdf. [5-3] EpsonElectronics,SED1278LCDController/DriversTechnicalManual,(undated). [5-4] SamsungElectronics,KS0066U16COM/40SEGDriver&ControllerforDotMatrixLCD,(undated).
85
6
CHAPTER
ReadingComplex InputSwitches Chapter4lookedatreadingindividualswitchesandamatrixkeypad.We’llextendourswitchreadingto lookatadditionalpinsavingtechniques.We’llalsoseehowrotaryencoders—bothinternallydecodedand incrementalversions—canbereadwithaPIC.
PinSavingTechniques It’sacommonrequirementtoreadaconfigurationswitchduringstart-up.Perhapstheswitchdefinesthe baudrateforaserialoutput,oritmaysetsomeotherparameter.Regardless,todedicateseveralpinstosense astart-upconfigurationisawasteofscarcepinresourcesandmayforceustousealarger,moreexpensive PICthanotherwisedesired.
SimpleApproach Howmightwereada16-stateswitch?We’llimmediatelydiscardhooking16individualswitchesto16input pins.Werecallthat4-bitsgiveus16uniquecombinations,sowecanusefourswitchcontactstogenerate16 states.Thismightbeeithera4-sectionDIPswitchwithindividualswitchselections,oritmightbearotaryDIP switchwithpositions0…Finternallycodedintoonecommonconnectionandfourswitchedpoles,suchasthe simpleconnectionisshowninFigure6-1.Aclosedswitchplacesahighonthecorrespondinginputpin,andan openswitchplacesalowonthecorrespondingpin.ReadingRB7…RB4asPortB. HighNib,theswitchsectionscorrespondto the4bitsinthenibble. Todeterminetheswitchclosurepatterncorrespondingtoanyparticularvalue,welook atthebinarycombinations.Forexample,if PortB.HighNibistoreturnthevalue13, wesimplynotethat13inbinaryis1101. Hence,B7,B6andB4mustbehighand B5mustbelow.So,theswitchesassociated withB7,B6andB4willbeclosedandB5’s switchwillbeopen.Anotherwaytolookat thisistoseethatB7hasthevalueofeither 8(closed)or0(open),B6iseither4or0, B5iseither2or0andB4iseither1or0.To sumto13requires8+4+1,againcorrespondingtoswitchclosuresonB7,B6and B4.Figure6-1’svaluelabelscorrespondto Figure6-1:Readinga4-sectionswitch. thisweighting. 86
ReadingComplexInputSwitches Let’sseehowwemightreadthearrangementofFigure6-1andusetheconfigurationswitchreadingtoset theserialoutputbaudrate. Program6-1 ;Showreadingbaudrate ;fromswitchesonB4...B7 ;8 4 2 1 ;B7 B6 B5 B4 TRISB=$F0 EnableHSerial ;InitializeBaudRate BranchPortB.HighNib,[S0,S1,S2,S3,S4,S5,S6,S7,| S8,S9,S10,S11,S12,S13,S14,S15] S0: SetHSerialH1200 :GoToSendMessage S1: SetHSerialH2400 :GoToSendMessage S2: SetHSerialH4800 :GoToSendMessage S3: SetHSerialH7200 :GoToSendMessage S4: SetHSerialH9600 :GoToSendMessage S5: SetHSerialH14400 :GoToSendMessage S6: SetHSerialH19200 :GoToSendMessage S7: SetHSerialH24000 :GoToSendMessage
S8: S9: S10: S11:
SetHSerialH26400 SetHSerialH28800 SetHSerialH31200 SetHSerialH33600
:GoToSendMessage :GoToSendMessage :GoToSendMessage :GoToSendMessage
S12: S13: S14: S15:
SetHSerialH36000 SetHSerialH38400 SetHSerialH57600 SetHSerialH115200
:GoToSendMessage :GoToSendMessage :GoToSendMessage :GoToSendMessage
Main SendMessage HSerOut[“SwitchValue:“,DECPortB.HighNib,13] Pause100 GoToMain End
We’resavingserialoutputforalaterChapter,sowe’llsimplynotethatcertainPICs,includingthe 16F876/877seriesweuseinourexperiments,havebuilt-inhardwaresupportforserialoutput,andthatthese devicesthetransmitoutputappearsonRC6.So,it’snecessarytoconnectajumperfromC6tothe“TX”pin oftheserialsocketinBasicMicro’s2840developmentboard.TheDB9serialoutputportconnectorshould thenbehookedtoasecondcomputerrunningaserialterminalprogram,suchasHyperTerminalincluded withWindows,or,evenbetter,theexcellentfreewareprogramTerminal[6-9]. Beforeusingthehardwareserialoutput,it’snecessarytoinitializeitwiththeEnableHSerialcommand, whichinstructsthecompilertoloadthehardwareserialinput/outputcodemodule.Don’tforgetthatbefore actuallysendingorreceivingserialdata,youmustspecifythedataspeedwiththeSetHSerialfunction, whichtakesasitsargumentapre-definedparameterthatdefinesthedesiredbaudrate.Theseconstantsare oftheformHnnnnwherennnnisthedataspeed.Afterinitializationandspeedsetting,textmaybesentover theserialportthroughtheHserOutprocedure.(We’llcoverserialdatainmuchmoredetailinChapter9,so ifyoumaywishtoskipaheadformoreinformation.) TRISB=$F0 ;InitializeBaudRate BranchPortB.HighNib,[S0,S1,S2,S3,S4,S5,S6,S7,| S8,S9,S10,S11,S12,S13,S14,S15]
87
Chapter6 WeinitializepinsB4…B7tobeinputsthroughtheTRISB=$F0assignment.(SeeChapter2forareviewof theTRISstatement.) WethenreadthefourswitchpolessimultaneouslybyreadingPortB.HighNibble.PortB.HighNibble hasavalueof0…15correspondingtothebinaryweightedvaluesoftheswitchpositions.TheBranch PortB.HighNib[…]proceduretransfersprogramexecutiontoS0ifPortB.HighNib=0,toS1if PortB.HighNib=1throughS15ifPortB.HighNib=15. Eachjumplabelissimilarinstructure,sowe’lllookatS0: S0: SetHSerialH1200
:GoToSendMessage
First,wesetthehardwareserialportbaudrateandthenexecutionbranchestoSendMessage. Main SendMessage HSerOut[“SwitchValue:“,DECPortB.HighNib,13] Pause100 GoToMain
ThecodefollowingSendMessagesendstheswitchvalueontheserialoutputport.Iftheswitchissetfor 13,correspondingtoabaudrateof38400,thefollowingmessagewillbedisplayedontheconnectedterminal:“SwitchValue13.”Thismessagerepeatsevery100ms. Ofcourse,yourterminalprogrammustbesettomatchthebaudratesetbytheswitches.Thecharacter“13”at theendofthemessagestringisacarriagereturn.Ifyouwantthesemessagestoeachstartonanewline,make sureyourterminalprogramisconfiguredforthisaction.(Someterminalprogramsrequirealinefeedcharacter tostartanewlineandthiscannotbechanged.Ifyoureceiveallthemessagesononeline,changetheoutput datato[SwitchValue:",DECPortB.HighNib,13,10],as10isthecharactervalueforlinefeed.) Ifyouseeonlygibberishontheterminalscreen,tryresettingthePICwiththeresetbuttononthedevelopmentboardtoforcetheswitchestobefreshlyread.Or,brieflyremovepowerfromthedevelopmentboardto forceapower-onreset. Ourdiscussionandprogramstructureassumestheswitchhasbinarycodedcontacts,asisbyfarthemost frequentarrangementforinexpensiveDIP-packagedconfigurationswitches.
Doubled-UpLCD/Configuration Switch Program6-1readstheconfigurationswitch once,atstart-uponly,butthefourpins connectedtotheswitchpolesareunavailableforotheruses.Insomecases,wecan reusethosepinsforotherpurposes. Figure6-2showshowwemayusethe samepinstoreadfourswitchcontacts andoutputdatatoanLCDmodule.(The diodesareordinarysiliconsignaldiodes, suchas1N4148s.)Thiscircuitoperatesin twomodesasshowninthefollowingtable.
Figure6-2:DuplexingswitchandLCDdatapins.
88
ReadingComplexInputSwitches Mode ReadSwitches OutputtoLCD
PinsRB4…RB7 Input Output
PinRA5 Output–High Output-Low
Toreadthefourswitchcontacts,makeRB4…RB7inputsandtakeRA5high.Anyswitchthatisclosed causesahighonitsconnectedpinjustasinthecircuitofFigure6-1.Pinsconnectedtoopenswitchesare pulledlowbythepull-downresistors.TheLCDmoduleinitializesininputmode,soitsdatainputpins DB4…DB7areeffectivelyopencircuitsandmaybedisregarded. Afterreadingtheswitchcontacts,wetakeRA5lowandmakeRB4…RB7outputs.(Thepull-downresistors donotsignificantlyburdenthePIC’soutputpinsandmaybedisregarded.)EachoftheoutputpinsRB4… RB7maybeeitherhigh(approximatelyatVDD)orlow(approximatelyatVSS)andtheassociatedswitchmay beeitheropenorclosed.Thus,wehavefourpossiblecombinations: PinsRB4…RB7
AssociatedSwitchOpen
High
Switchisolatesextraneouscircuitry fromtheconnection.
Low
Switchisolatesextraneouscircuitry fromtheconnection.
AssociatedSwitchClosed Diodeisreversedbiasedsoitpresentsa highimpedancecircuitandisolatesthe extraneouscircuitry. Boththeanodeandcathodeofthe diodeareatapproximatelysame voltage,sonosignificantcurrentflows andtheextraneouscircuitrymaybe disregarded.
UnderallpossiblecombinationsofRB4…RB7outputsandswitchopen/closed,theconnectionbetweenthe PICandLCDmoduleactsasiftheswitchwerenotthere. Program6-2demonstratesduplexingtheswitchandLCD.TheLCDconnectionsarethesameasweusedin Chapter5. Program6-2 ;Showreadingbaudrate ;fromswitchesonB4...B7 ;8 4 2 1 ;B7 B6 B5 B4 ;Varibles ;-------LCDNibVarPortB.Nib1 SWValueVar Byte ;Constants ;--------- RegSel Con Clk RdWrPin
B0 Con Con
B1 B2
Initialize ;---------TRISB=$F0 EnableHSerial OutputA5 ;InitializeBaudRate HighA5 Pause5 SWValue=PortB.HighNib BranchSWValue,[S0,S1,S2,S3,S4,S5,S6,S7,| S8,S9,S10,S11,S12,S13,S14,S15]
89
Chapter6
S0: S1: S2: S3:
SetHSerialH1200 SetHSerialH2400 SetHSerialH4800 SetHSerialH7200
:GoToInitLCD :GoToInitLCD :GoToInitLCD :GoToInitLCD
S4: S5: S6: S7:
SetHSerialH9600 SetHSerialH14400 SetHSerialH19200 SetHSerialH24000
:GoToInitLCD :GoToInitLCD :GoToInitLCD :GoToInitLCD
S8: S9: S10: S11:
SetHSerialH26400 SetHSerialH28800 SetHSerialH31200 SetHSerialH33600
:GoToInitLCD :GoToInitLCD :GoToInitLCD :GoToInitLCD
S12: S13: S14: S15:
SetHSerialH36000 SetHSerialH38400 SetHSerialH57600 SetHSerialH115200
:GoToInitLCD :GoToInitLCD :GoToInitLCD :GoToInitLCD
InitLCD LowA5 LCDInitRegSel\Clk\RdWrPin,LCDNib Pause500 ;AllowstheLCDtoinitialize SendMessage HSerOut[“SwitchValue:“,DECSWValue,13] LCDWRITERegSel\Clk\RdWrPin,LCDNib,["SwitchValue:",DECSWValue] Pause5000 LCDWRITERegSel\Clk\RdWrPin,LCDNib,[Clear,Home] Pause500 GoToSendMessage End
We’veseenlargepartsofthisprogramearlierinthischapterandinChapter5,sowe’llconcentrateonthe differences. Becausewecanonlyreadtheswitchunderspecificconditions,thatis,RA5beinghighandRB4…RB7 beinginputs,ifwewishtousetheswitchvalueelsewhereintheprogramit’snecessarytostoreitafterreading.HencewedeclareanewvariableSWValuetoholdthevalue.WealsomakeRA5anoutputpinwiththe OutputA5function. HighA5 Pause5 SWValue=PortB.HighNib BranchSWValue,[S0,S1,S2,S3,S4,S5,S6,S7,S8,| S9,S10,S11,S12,S13,S14,S15]
Theactualreadandbranchprocedureisstraightforward;takeA5high,pausefor5mstostabilization(the pausestatementcanberemovediftimeisanissue;it’saddedasinsuranceandisn’tstrictlynecessary)and thenreadPortB.HighNibthroughtheassignmentoperatorSWValue=PortB.HighNib.Wethenbranch totheappropriatebaudrateselectionjustasinProgram6-1,butusingSWValueastheindex.(Remember, the|isacontinuationcharacterallowingasinglelogicallineofMBasiccodetobebrokenovertwoormore physicallines.) S0: SetHSerialH1200
:GoToInitLCD
Note,however,thataftersettingthebaudratewejumptoInitLCD. InitLCD LowA5 LCDWRITERegSel\Clk\RdWrPin,LCDNib,[InitLCD1,InitLCD2,TwoLine,CLEAR,HOME,SCR] Pause500 ;AllowstheLCDtoinitialize
TheroutineInitLCDduplicatesthecodeweexploredinChapter5.AfterinitializingtheLCD,execution thenpassestoSendMessage.
90
ReadingComplexInputSwitches SendMessage HSerOut[“SwitchValue:“,DECSWValue,13] LCDWRITERegSel\Clk\RdWrPin,LCDNib,[“SwitchValue:“,DECSWValue] Pause5000 LCDWRITERegSel\Clk\RdWrPin,LCDNib,[Clear,Home] Pause500 GoToSendMessage
WehaveexpandedSendMessagetoalsowritetheswitchvaluetothe LCD.Afterdisplayingtheswitchvaluefor500ms,weerasetheLCD, pauseforanother500msandrepeattheSendMessageroutine.Figure 6-3showstheresult. TomakethiscircuitworktheLCDmodulepinsmustbeinputs.Ifyour programrequiresreadingdatafromtheLCDmodule,youmustreadthe switchonlyduringtimeswhentheLCDmoduleisininputmode. AlthoughwehavecastduplexingtheLCDandswitchinthecontextof Figure6-3:LCDmoduledisplaysthe aone-timeinitializationread,thecircuitryandprogramlogicisnotso switchvalue. limited.ThereisnothingstoppingusfromduplexingtheLCDandswitch withmultiplereads,suchaswheretheswitchescontroluser-adjustablefunctionsthatarepolledperiodically aslongastheprogramisoperating,perhapsalongthefollowinglines: InitializationRoutines InitializeLCD MainLoop Readswitches MakeB4…B7inputs TakeRA5high ReadB4…B7andstorevalueinSWValue TakeRA5low MakeB4…B7Outputs DostuffbasedonSWValue WritemessagestoLCD GoToMainLoop
RotaryEncoders Theterm“rotaryencoder”isafancynameforaspecializedswitch.Aswitch,afterall,convertsmechanical motionintosomething—contactoperations—thatmaybesensedelectronically.Arotaryencoderconverts motion—shaftrotation—intocontactoperation.We’lllookatrotaryencoders,butlinearencodersalsoexistwhereastraight-linemotion,suchasarodmovingbackandforth,isconvertedintocontactoperations. We’llusetheword“encoder”asshorthandfor“rotaryencoder,”butrememberlinearencodersalsoexist. Rotaryencoders,alsoknownas“shaftencoders”and“positionencoders,”havemanyuses.Forexample, thepositionofamachinetoolspindlemaybelocatedthrougharotaryencoderandleadscrewmechanism. (Moreoften,thisisdonewithlinearencoders,however.)Arotaryencoderonitsshaftmaymeasurethe RPMspeedofamotor.Or,itmaymeasuretheangleofaroboticarmjoint,ortheazimuthofarotatingradar antenna.We’lllookatamoremundanerotaryencoderapplication,allowingausertoscrollthroughanLCD menuandselectoptions.Thesearelow-endapplications,buttheconceptswelearncarryoverintoprecision andhighspeedencoders. Encodersmaybegroupedintotwomaincategories,absoluteandrelative. Absolute—Absoluteencodersprovideanoutputthatuniquelyidentifiestheshaftangle.Anabsoluteencoder canbethoughtofasamultipositionrotaryswitch;asyourotatetheswitchonesetofcontactsbreaks andanewsetofcontactsmake.Hence,thereisadirectrelationshipbetweenangleandcontacts;ifwe knowwhichcontactsareclosedweknowtheshaftposition.Thepriorpositionoftheshaftisimmaterial;touniquelydeterminethecurrentshaftangleallweneedtoknowiswhichcontactisclosed.(We’ll seehowrealencodersaremadelater.) 91
Chapter6 Relative—Relativeencoders(sometimescalled“incrementalencoders”)provideinformationonthedirectionofshaftrotation,forexample,didtheshaftmoveclockwiseorcounterclockwiseand,withmany devices,howmanydegreesdidtheshaftrotate?Inordertoknowtheangletheshaftisatforthisinstant, wemustknowitspositionatsomestartingtimeandrememberallthechangesreportedbytherelative encodersincethestartingtime. Ananalogytoabsoluteandrelativeencodersisfoundinhouseaddresses.Supposeyouaretryingtofind aparticularhouse.Theabsoluteaddressofthehouseis123MainStreet.Therelativeaddressofthehouse is:“fromwhereyouarenow,gotwoblocksnorth,threeblockswestandit’sthefourthhouseontheright.” Bothaddresseswillgetyoutothesameplace,buttherelativeaddressisusefulonlyfromadefinedstartingpointandrequiresyoutokeeptrackofallturnsandthedistancetraveled.Worseyet,shouldyoumake amistakeandtakeevenasinglewrongturntheabsoluteaddressdoesn’tchange;buttherelativeaddressing informationbecomesworthless. Thesameistruewithrotaryencoders;ifwemakeamistakeandmissoneoftherelativereports,allfuture positioninformationwillbeinerror.And,duringpower-upandinitialization,wemustindextherelative shaftrotationtoaknownreference.Theabsoluteencoder,incontrast,actslikeanonvolatilememory;it reportsitspositionatstart-upjustasitdidwhenlastrunning. Foroursimpleprogramswheretheuserrotatesanencodershafttoselectitemsfromamenu,wecanoften assumearelativeencoderstartsatadefaultmenu.Ifweinsteadwishtracktheazimuthofarotatingradar antennaorifwewishourdevicetohaveafrontpanelwithlabeledswitchpositions,wewillalmostcertainly decidetouseanabsoluteencoder.Ifweuseanincrementalencoder,wewillfinditnecessarytoprovideasynchronizationmechanism,suchasacontactclosureeverytimethedevicepassesacertainazimuthposition.
EncoderConstruction Inexpensiveencodersarealmostalwaysmechanical,similartorotary switches.Figure6-4showstypicalrelativeandabsolutemechanical encoders.TheCTSSeries288devicesshowncostlessthan$5.00in singlelotpurchasesandofferatypicaloperatinglifetimeofa15,000 actuations,quiteadequateformanualmenuselectionanddataentry inmostapplications.Absolutemechanicalencodersarerarelyfound withmorethan32steps/revolutionandarelimitedtomoderaterotationspeed.Theyareavailablewithandwithoutdetents.(Detentsforce Figure6-4:CTSSeries288mechanical theshafttopreferredpositionswhileencoderswithoutdetentsare rotaryencoders. stableatanyangle.) Higherendencodersarepredominantlyoptical,withpricesrangingfrom$25upintothethousandsofdollarrange.TheirlifetimeismeasuredinthetensofmillionsofrotationsandsomeareratedforhighRPM operation.Resolutionisavailableinhundredsoreventhousandsofpositionsperrevolution.Multiturnrotary encodersarealsoavailable,similartomultiturnpotentiometers.Sinceopticalencodershavenomechanicallymovingswitchcontacts,theyhaveasmooth,almostsilky,feelwhenrotatedbyhand.Consequentlythey areusedforcontrolsthatmusthaveasmoothfeelorseektomimicananalogcontrol,suchasthetuning knobonashortwavereceiver.Opticalencodersare,ofcourse,theproductofchoiceformotorRPMsensors andwhenusedforthispurposeareoftencalled“opticaltachometers.” AbsoluteopticalencodersusemultipleLED/photodiodepairstoreadaglassorplasticdiscwithaprinted scale.Relativeopticalencodersusethesametechnology,butwithamuchsimplerinternalstructure.(We’ll skipoverthedetailsofabsoluteopticalencodersatourlevelofdiscussion.)
92
ReadingComplexInputSwitches Figures6-5,6-6and6-7showtheconstructionofaspecialpurposeopticalrelativeencoderdevelopedby SherlineProducts,Inc.aspartofitsdigitalreadoutoptionforitslineoftabletopmillingmachinesand lathes.Thisparticulardevicereadstherotationofacalibratedhandwheelonasmallinexpensivemilling machinemanufacturedbySherlinetodetermineX,YandZmovement.(Theleadscrewstowhichthehandwheelsareattachedare20threads/inch,andtheencoderoutputs100pulsesperrevolution,sotheposition resolutionis0.0005.”Todeterminetheresultinglinearaccuracyrequiresanalysisofbacklashanderrorsin leadscrewrollingandsimilarmechanicalissues.)Thedesignerofthisparticularreadoutsystemoptedfor relativeencoders,sinceanintegralpartofthemachiningprocessisassigninga0,0,0referencelocationto thepartbeingmachinedandtherewouldbelittlegainedwithavastlymoreexpensiverotaryabsoluteencoder.Professionaldigitalreadoutsformillingmachinesuselinearencoders,oftenwithglassscales,sothat positioninformationisindependentfromtheleadscrews.Thesereadoutsoftencostseveraltimesasmuchas thepriceofacompleteSherlinemillingmachine,includingthedigitalreadout. Let’sgothroughhowSherline’sdesignworks.Figure6-5showsthehandwheelwiththeinterrupterdisk attached,aswellasanun-mountedinterrupterdisk.TheinterrupterdiskfitsintothesensorholderofFigure 6-6.ThesensorholderhastwoLED/photoreceptorpairs,spacedacarefullycontrolleddistanceapart.Figure6-7showstheinterrupterdisklooselyinsertedintothesensorholder.Theleadscrewandshaftassembly, ofcourse,arenotshowninthesefigures.
F i g u r e 6 - 5 : H a n d w h e e l a n d interrupterwheel.
Figure 6-6: LED and photo sensor housing.
Figure6-7:Interrupterwheelshown inhousing.
SupposewehaveoneLED/photo-sensorpair,asshowninFigure6-8.Since theinterrupterwheelhas25spokes and25slots,wehave50uniquepositionsforeachrevolution.But,wecan’t determineiftherotationdirectionis clockwiseorcounter-clockwise.To bothimproveresolutionandprovide directioninformation,wecanadda secondLED/photo-sensorpair,spaced Figure6-8:EncoderwithoneLED/photo-sensor. anintegernumberofinterrupterteeth apart,plusone-quartertooth.This arrangementisoftencalledaquadraturesensororquadratureencoder,sincetheextraone-quarterspacingrepresents a90-degreephaseshiftofonecompleteopaque/clearcycle. Figure6-9showshowthistechniquebothdoublesangular Figure6-9:Quadrature resolutionandprovidesrotationdirectioninformation.One sensingofrotation.
93
Chapter6 cycle,i.e.,rotationthroughonesolidspoke,givesfouroutputs,androtationdirectioncanbederivedfrom theorderinwhichtheoutputsoccur.Sincewehave25spokes,eachrevolutionyields100uniqueoutputs. Direction
↑
Output 00 10 11 01
Direction
↓
Althoughwe’velookedatSherline’srelativeencoder,thesameprinciplesapplytooff-the-shelfrotaryencodersyoupurchasefromanelectronicspartshouse,includingtheonesinFigure6-4.
CodeOutput Absoluteencodersareavailablewithaselectionofoutputcoding,withthetwomostcommonlyavailable beingGraycodeandstraighthexadecimalbinarycode.Graycoding(namedafterFrankGray,itsinventor) changesbyonlyonebitforeverystatechange.Hexadecimalcodecanchangewithmorethanonebit(think abouttherolloverina4-bitcodefrom$F(1111)to0(0000);allfourbitssimultaneouslychangestate). Gray-codedencoderspermitnoimproperintermediateoutputstates.Forexample,ifouralgorithmreadsa 4-bithexadecimal-codedencoderstartingattheinstantanybitchangesvalue,wemaygetanerroneousresultunlessallbitschangesimultaneously,orweadequatelydebouncetheoutput.Sinceonlyonebitchanges foreachstatetransitioninaGray-codeddevice,readingstriggeredbyasinglebitchangeautomaticallyproducethecorrectresult.Ifourencoderisturnedbyhand,theremaybelittleadvantagetoaGray-codedoutput, butifwearereadingamotorshaftspinningat3600RPM,aGray-codeoutputispreferable. ThedifferencebetweenhexadecimalandGraycodecanbeseenforaCTSSeries288mechanical4-bit(16 positionsperrevolution)encoder. Position 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
4-BitGrayCode ContactClosuretoCommon A(LSB) B E F(MSB) 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 0 1 1 0 0 1 1 0 1 1 1 0 1 0 1 0 0 0 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 0
Value 0 4 12 8 10 14 15 11 9 13 5 1 3 7 6 2
94
4-BitHexadecimalCode ContactClosuretoCommon A(LSB) B E F(MSB) 0 0 0 0 1 0 0 0 0 1 0 0 1 1 0 0 0 0 1 0 1 0 1 0 0 1 1 0 1 1 1 0 0 0 0 1 1 0 0 1 0 1 0 1 1 1 0 1 0 0 1 1 1 0 1 1 0 1 1 1 1 1 1 1
Value 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
ReadingComplexInputSwitches
ReadingaRelative Encoder Afterallthistheory,let’slook atsomecode.Program6-3 willreada16position,twobitrelativeshaftencoder(CTS model288T232R161A2)and illuminateanLEDindicating whethertheshaftisrotated clockwiseorcounter-clockwise.We’llalsoincrementa counterforclockwiserotation anddecrementitforcounterclockwiserotationandoutput thecountervalueoverthe RS-232port.ThecircuitassociatedwithProgram6-3is showninFigure6-10. Figure6-10:Schematicforincrementalencoderreadprogram. Program6-3 ;Variables ;----------CurVal OldVal Counter
Var Var Var
;Initialize ;----------Clear OutputA0 OutputA1
;clockwiseLED ;counter-clockwiseLED
LowA0 LowA1 EnableHSerial SetHSerialH115200
Byte ;currentencoder Byte ;oldencoder Sbyte ;countsstatechanges
;initializebothLEDsoff ;changeiflowerspeedneeded
CurVal=(PortB&%00110000)>>4 OldVal=CurVal HSerOut[“Ctr“,SDECCounter,13]
;getcurrentreading ;initializeforfuturechange ;outputthecounter
Main ;-------------CurVal=(PortB&%00110000)>>4 ;returns0…3 IfCurVal<>OldValThen BranchCurVal,[S0,S1,S2,S3] ;ifchanged,lookatold EndIf AfterBranch GoToMain S0 ;readingis0,checkifcamefrom2or1 ;--------- IfOldVal=2Then GoSubClockWise ELSE GoSubCounterClockWise EndIf
95
Chapter6 GoToAfterBranch
S1 ;readingis1,checkifcamefrom0or3 ;---------- IfOldVal=0Then GoSubClockWise ELSE GoSubCounterClockWise EndIf GoToAfterBranch S2 ;readingis2,checkifcamefrom3or0 ;---------- IfOldVal=3Then GoSubClockWise ELSE GoSubCounterClockWise EndIf GoToAfterBranch S3 ;readingis3,checkifcamefrom1or2 ;---------- IfOldVal=1Then GoSubClockWise ELSE GoSubCounterClockWise EndIf GoToAfterBranch ClockWise ;------------- HighA0 ;turnCWLEDon LowA1 ;turnCCWLEDoff OldVal=CurVal ;readytocheckfornextinput Counter=Counter+1 ;bumpupcounter HSerOut[“Ctr“,SDECCounter,13] ;outputthecounter Return CounterClockWise ;------------- LowA0 ;turnCWLEDoff HighA1 ;turnCCWLEDon OldVal=CurVal ;readyfornextinput Counter=Counter–1 ;decrementcounter HSerOut[“Ctr“,SDECCounter,13] ;outputthecounter Return End
Let’sgothroughtheinterestingportionsofthecode. ;Variables ;----------CurVal OldVal Counter
Var Var Var
Byte Byte SByte
We’llreadandholdtheencodervalueinCurVal.OldValholdsthepreviousencodervalue,andwewill incrementordecrementCounterdependingonthedirectionofshaftrotation.Counterisasignedbyte,
96
ReadingComplexInputSwitches withpermittedvaluesfrom–128to+127,thusallowingustoincrementordecrementCounterfromits initializedvalueof0. CurVal=(PortB&%00110000)>>4 OldVal=CurVal
Weinitializebyreadingthecurrentencodervalueandsettheoldvalueequaltothecurrentvalue.This permitsustodetectthefirstrotationbycheckingforCurVal<>OldVal.First,weperformabitwise AND(“&”)ofthereadvaluewith%00110000.TheANDfunctionmasksoffallbitsreadonPortBexcept forthosecorrespondingto1’sinthemaskoperator%00110000,B5andB4.MaskingallexceptB5andB4 permitsustoignorethevaluesreturnedbytheremainderofPortB’spins.Sincetheencoderisconnectedto B4andB5,thereadvalueisshiftedtotheleftbyfourbits,whichweremovebyshiftingthereturnedvalue fourbitstotheright.(ThereasonweconnectedtheencodertoB4andB5insteadofB0andB1willbeseen whenwelookattheinterruptversionofProgram6-3.)Toforcethecorrectorderofoperation,weenclose thelogicalANDoperationwithparentheses.Intheabsenceoftheparentheses,MBasic5.3.0.0wouldfirst divide%00110000by16andthenlogicallyANDtheresultwiththevaluereadonPortB.Thisrepresentsa changefromearlierversionsofMBasic,wheretheorderofprecedencewasdifferent. CTS’sdatasheetshowstheoutputsequence(assumingclockwiserotation)forthefirsteightpositionsas: ContactClosure ToCommon
B A
PositionNo.
0 0 0
0 1 1
1 1 2
1 0 3
0 0 4
0 1 5
1 1 6
1 0 7
Inourcircuitacontactclosure(datasheet1)resultsinalogicallowatthePIC’sinputpin,andanopen(data sheet0)isalogicalhigh.Hence,ourcircuitinvertsthe0’sand1’sfromtheCTS’sdatasheet’sprospective. AsshowninFigure6-10,pinAisconnectedtoB4,whilepinBisconnectedtoB5.Consequently,ourPIC inputpinsequencelookslike: PICPin
B5 B4
PositionNo. PortB&b00110000 PortB&b00110000/16
1 1 0 48 3
1 0 1 32 2
0 0 2 0 0
0 1 3 16 1
1 1 4 48 3
1 0 5 32 2
0 0 6 0 0
0 1 7 16 1
Wenowrewrite(PortB&b00110000)>>4intworows,representingclockwiseandcounter-clockwise rotation,startingwith0forconvenience: Clockwise Counter-Clockwise
0 0
1 2
3 3
2 1
0 0
1 2
3 3
2 1
Tounderstandhowwedifferentiateclockwiseandcounter-clockwiserotation,supposetheencoder’scurrent valueisreadas0.Ifthepreviousvaluewas0,theencodershafthasnotmovedsinceitslastread.Ifthepreviousvaluewas2,therotationisclockwise;ifthepreviousvaluewas1,therotationiscounter-clockwise. Main ;-------------CurVal=(PortB&%00110000)>>4 IfCurVal<>OldValThen BranchCurVal,[S0,S1,S2,S3] EndIf AfterBranch GoToMain
Withthisunderstanding,themainprogramshouldbeclearer.Wehavetwosequentialcomparisonstomake. First,hastheencodermoved,whichwetestforwiththeIfCurVal<>OldValThen…test.Iftheencodershafthasrotatedsinceitslastread,theconditionalistrueandwebranchtooneoffourprogramlabels basedonthecurrentencodervalue,S0ifthevalueis0,andsoon. 97
Chapter6 S0 ;readingis0,checkifcamefrom2or1 ;--------- IfOldVal=2Then GoSubClockWise ELSE GoSubCounterClockWise EndIf GoToAfterBranch
ProgramexecutionreachesS0onlyifCurVal=0.Hence,todeterminetherotationdirection,weonly needtestthepriorvalue,whichwedowiththeIfOldVal=2test.Iftrue,thedirectionisclockwiseand weexecutetheClockWisesubroutine;iffalse,thedirectionmustbecounter-clockwise,soweexecutethe CounterClockWisesubroutine. ClockWise ;------------- HighA0 ;turnCWLEDon LowA1 ;turnCCWLEDoff OldVal=CurVal ;readytocheckfornextinput Counter=Counter+1 ;bumpupcounter HSerOut[“Ctr“,SDECCounter,13] ;outputthecounter Return CounterClockWise ;------------- LowA0 ;turnCWLEDoff HighA1 ;turnCCWLEDon OldVal=CurVal ;readyfornextinput Counter=Counter–1 ;decrementcounter HSerOut[“Ctr“,SDECCounter,13] ;outputthecounter Return
TheClockWiseandCounterClockWisesubroutinesaremirrorimagesofeachother;theysetandclear thedirectionLEDsandbumpupordecrementthecounterandwritetheupdatedvalueofthepositioncountertothehardwareserialport. AfterreadingChapter4,youmaywonderwherethedebounceroutineis.Afterall,wearesensingamechanicalswitchwhosedatasheetquotesa5msmaximumbounceperiod.Theansweristhattheexecutiontime oftheprogram,includingtheserialoutputstatement,providessufficientdelaytoprovidetroublefreereading.Inmostcases,arealprogramwouldbranchintoenoughcodethatconsumedenoughtimetoprovide debounceasanincidentalbenefit.Ifnot,wecouldaddaPause5statementaftereachswitchread.Or,we mightadddebouncecircuitrytoourdesign. Asitstandsnow,witha20MHzclock,Program6-3’smainprogramloopexecutesin400µswherethe encoderhasnotchangedvalue,andin750µswhereithaschangedvalue.Thus,itaccuratelyreadswellover 1,000steps/second,or3700RPM,farfasterthansomeonetwistingaknobattachedtotheshaftwilloperate theencoder. Figures6-11and6-12showtheinputwaveformsasIturnedtheshaftquicklybyhand.Incidentally,you mayreadreferencestoquadratureencoderoutputsbeingreadbycomparingthephaseofthetwooutputsfor clockwiseandcounter-clockwiserotation.Figure6-11showsChannel2(B5)leadingChannel1(B4)during clockwiserotation,whileFigure6-12showsChannel1(B4)leadsChannel2(B5)duringcounter-clockwise rotation.And,infact,thewaveformsatB4andB5are90°outofphase.Iviewthisphasecomparisonanalysisfarmoreconfusingthanbeneficial,particularlyinabeginningleveldiscussion.Hencewehaveinstead focusedonreadingtheencodervalueandcomparingitwiththepriorvalue.
98
ReadingComplexInputSwitches
Figure6-12:Counter-clockwisemanualrotation Ch1:B4Ch2:B5.
Figure 6-11: Clockwise manual rotation Ch1: B4Ch2:B5.
Program6-3spendsagreatdealoftimepotentiallydoingnothing;inatypicalprogramthatusesarotary encodertoselectmenuitems,operatorinteractionisinfrequent.Howmanytimesdoyouchangethethermostatsettinginyourhouse?Certainlynothundredsoftimesasecond.Wouldn’titbeniceifweourmain programcouldspenditstimemakingimportantcomputationsandbranchtodealwithachangeduserinput onlywhentheencoderischanged,withoutcheckingtheencoder’svalueeverytimewegothroughourmain loop?Theanswer,ofcourse,isthatnotonlywouldthisbenice,thefolksatMicrochipandBasicMicrohave comeupwithawaytodoexactlythatthroughthemechanismofinterrupts.We’regoingtosaveinterrupts untilChapter10,buthere’sasneakpreview. WheneverthestateofinputpinsRB4…RB7change,wecancausethePICtostopwhatevercodeitisrunningandinsteadrunnewcode.Thisprocessiscalledan“interrupt”incomputer-speakanditdoesexactly that;itinterruptsthecurrentcodeandswitchesexecutiontoan“interrupthandler.” DeletetheCodeBelowfromProgram6-3
ReplaceitwiththeFollowingInterruptVersion
CurVal=(PortB&%00110000)>>4 OldVal=CurVal
CurVal=(PortB&%00110000)>>4 OldVal=CurVal
Main ;-------------CurVal=(PortB&%00110000)>>4 ;returns0…3 IfCurVal<>OldValThen BranchCurVal,[S0,S1,S2,S3] ;ifchanged,lookatold EndIf AfterBranch GoToMain
OnInterruptRBINT,ReadEncoder EnableRBINT Main ;-------------GoToMain Disable ReadEncoder CurVal=(PortB&%00110000)>>4 IfCurVal<>OldValThen BranchCurVal,[S0,S1,S2,S3] EndIf AfterBranch Resume
99
Chapter6 WheneveranypinofRB4…RB7changesstate(from0to1orviceversa),ifenabled,anRBINTtypeinterruptisissued.TouseaninterruptinMBasic,wefirstassociatetheinterrupttypewiththeprogramlabel oftheinterrupthandlerwiththeOnInterruptRBINT,ReadEncoderprocedure.Thissimplysaysthat wheneveranRBINTistriggered,weexecutecodefollowingthelabelReadEncoder.Next,weturnonor “enable”theRBINTinterruptwiththeprocedureEnableRBINT.Now,wheneverweturntheencoder shaft,eitherB4orB5willchangevalueandprogramexecutionwilljumptoReadEncoder. Disable ReadEncoder CurVal=(PortB&%00110000)>>4 IfCurVal<>OldValThen BranchCurVal,[S0,S1,S2,S3] EndIf AfterBranch Resume
Inordertoavoidinterruptsofinterrupts,wemustturnoffadditionalinterruptsbeforetheinterrupthandler viatheDisablefunction.TheinterruptprocedureitselfduplicatesthecodewedevelopedinProgram6-3. Attheendoftheinterruptprocedure,wereturntonormalprogramflowthroughaResumestatement. ThecodeexecutedintheMain…GoToMainloopinourinterruptprogramissimplyaserialoutput.But, itcouldhavebeenanything,suchaslengthymathematicalcalculations,LCDwrites,oranythingelseyou candoinMBasic.Whentheinterruptoccurs,MBasicwillseamlesslyexecutetheinterrupthandlerand returnflowtoyourmainprogram.Hence,itisuptoyourcodetorecognizeandaccommodatechangesto Counter—asaresultofuserinputcommands—betweenprogramstatements. There’sanothersubtletyhereaswell.MBasicwillnotbreakexecutionofastatementtoserviceaninterrupt. Suppose,forexample,yourmaincodehasaoneseconddelayinitthroughaPause1000procedure.If youtwisttheshaftontheencoderjustasthePause1000procedurestartsexecution,theinterrupthandler willnotbeinvokeduntilafterthe Pause1000completes.So,ifthis happensyoumaytwisttheshaft encoderknobthroughadozenpositions,buttheinterruptprocedure won’trecognizethem.(Inalater chapterwe’lllaterseethatanassemblerlanguageinterruptdoesn’t sharethisproblem.)
DualEncodersandLCD Let’sseehowwemightmeldour LCDandrotaryencoderwork. Supposewewishtomakeacustom thermostatwithadifferentsetting foreachroominourhouse.We’ll seehowyoumightmakeadisplay thatshowstheroomnameonone lineofanLCDandthetemperature setpointonthesecondline.One rotaryencoderselectstheroomand asecondrotaryencodersetsthede- Figure6-13:TwoencodersandLCD. 100
ReadingComplexInputSwitches siredtemperature.We’llbuildonlyaskeletonprogram,omitting manyusefulelements,suchasstoringsetpointsinEEPROMto preservesettingsafterpoweroutages. OurwiringdiagramisshowninFigure6-13.TheLCDwewill useisa20×4model,butsincetheprogramusesonlythetop twolinesasmallertwo-linedisplaymaybesubstitutedwithout change.TheresultingdisplaycanbeseeninFigure6-14.Tooperate,oneencoderselectstheroom.Turningitclockwiseadvances throughtheroomnamesandcounter-clockwisereversesthrough thenamelist.Asecondencodervariestheroom’stemperatureset Figure6-14:SampleoutputofProgram6-4. point;clockwisetoincreaseandcounter-clockwisetodecrease thesetpointtemperature. Program6-4 Tosavespace,wehaveomittedaprintedlistingofProgram6-4.Itsfullcontentisavailableonthe CD-ROM. Let’slookatthepartsofProgram6-4wehaven’tseenbefore: CurVal OldVal Counter
Var Var Var
Byte ;currentroomencodervalue Byte ;oldroomencodervalue SByte ;up/downroomcounter
TempCtr CurTempEnc OldTempEnc
Var Var Var
SByte ;up/downtemperaturecounter Byte ;currenttemperatureencoderreading Byte ;oldtempertureencoderreading
EncFlag TempOld
Var Var
Byte Byte
;isinterruptfromtempertureorroom ;temporaryS0...S3index
TheroomselectionvariableshavethesamenameandsamefunctiondevelopedinProgram6-3.Wealsoset upaparallelvariablestructuretoholdthetemperatureencodervalues.Thesethreevariableshavetheword Tempinthem.Wealsodeclareasentinelorflagvariable,EncFlag,toidentifywhethertheencoderbeing readistheroomselectionortemperatureadjustencoder.Finally,sincewewishtoreusethebranchandthe priorencodertestroutines,wedeclareanewvariableTempOld(temporaryold)thatreplacesOldValin theseroutines. WriteDM0,[11,”LivingRoom”] StrIndex(0)=0
Sincewewishtoselectanddisplayroomnamesusinganup/downcounter,asimpledatastructurewould beanarrayofstrings,accessedthroughthecounterastheindexvariable.Indeed,inPascalterminology, wemightprefertodefineanarrayofrecordstoholdnotjusttheroomname,butalsothesetpointtemperatureandotherrelatedinformation.Alas,MBasicdoesn’tpermitarraysofstrings,or,forthatmatter,other two-dimensionalarrays,letalonearraysofrecords.And,ifitdid,wewouldquicklyconsumeRAMfor staticmessages,unnecessarilywastingprecioussystemresources.So,weneedanalternativewaytodisplay String(0),String(2)… We’vebrieflymentionedEEPROMmemoryinChapter2.Torecap,EEPROMisnonvolatilememoryavailableinmany,butnotall,PICs.RatherthanconsumeRAMwithaseriesofbytearrayscontainingroom names,we’llinsteadwritethestringstoEEPROMandretrievethemasnecessary.MBasicprovidesseveral mechanismsforwritingtoEEPROM,andwe’llusetheWriteDMprocedure. WriteDMAddress[{mod}Expression,{mod}Expression…]
101
Chapter6 WeareresponsibleforkeepingtrackofhowmuchmemorywhenwewritetoEEPROM,andwemustdefine thestartingmemoryaddress,Address.The16F876/877PICfamilywe’reusinghas256bytesofEEPROM andAddressaccordinglyrangesfrom0…255.WriteDMautomaticallywritesthecontentswithinthebracketstoconsecutiveEEPROMaddresses,startingwithAddress.WewriteapackagetoEEPROMcontaining thelengthofthestring(excludingthislengthbyte)followedbythestringcontents,sothatwemaysimplify theprocessofwritingeachstringtotheLCD.(We’reborrowingthisideafromearlyversionsofBorland’s Pascalcompiler.Iviewitasabetterapproachforshortstringsandlimitedstoragespacethanthe“terminate thestringwitha0”approachusedinCcompilersandlaterversionsofPascal.)Westorethestartingaddress ofeachpackagedstringinanarrayStrIndexsothatwemayaccesseachstringwithanindexnumber. AllofthisworkgivesusthefunctionalequivalentofRoomName(i),whereRoomName(0)=“Living Room,”RoomName(1)=“DiningRoom,”andsoon.Weusetheroomselectionencodertovaryifrom0to 7therebypermittingustoselectandwritetheselectedroomnametotheLCD.We’vealsodeclaredthearrayCurValue()toholdthedesiredsetpointtemperatureforeachroom. ;Initialreadofbothencoders CurVal=(PortB&%00110000)>>4 OldVal=CurVal CurTempEnc=(PortB&11000000)>>6 OldTempEnc=CurTempEnc
WefollowtheconceptintroducedinProgram6-3toreadthetemperatureencoder.Sincethetemperature encoderisconnectedtopinsB7andB6,themaskanddivisorchange,asseeninthepreviouscodefragment. Main ;KeepCountertolegalroomnumbers IfCounter>MaxRoomNoThen Counter=MaxRoomNo EndIf IfCounter<0Then Counter=0 EndIf MsgID=Counter
Themainprogramloopfirstensuresthattheroomencodercounterdoesnotreturnavalueoutsidethe permittedindexrange.Wehaveeightrooms,indexedfrom0…7,sowecorrespondinglylimitCounterto 0…7.WesetMsgID=Counter,sinceweMsgIDisadummyindexvariableusedtodisplaystringsinthe subroutineWritelnMSG. ;ChangedRoomEncoder? IfMsgID<>OldMsgIDThen LineNo=1 GoSubWritelnMsg OldMsgID=MsgID TempCtr=CurSetting(MsgID) LineNo=2 GoSubWritelnTemp EndIF
;Writenewroom ;Displaytemp
AsinProgram6-3,iftheroomselectionencoderhaschanged,thenMsgID,haschangedandweexecutethe statementsfollowingtheIF…Thenstatement.Let’stakeaquicklookatthesubroutineWritelnMsg. WritelnMsg;WritesEEPROMstringtoLCD.StartingadrisAdr ;----------;LineisLineNo ReadDMStrIndex(MsgID),[StrLen] ReadDMStrIndex(MsgID)+1,[StrTempStr\StrLen] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrRAM+LineOff(LineNo)] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[““] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[ScrRAM+LineOff(LineNo)] LCDWriteRegSel\Clk\RdWrPin,LCDNib,[StrTempStr\StrLen] Return
102
ReadingComplexInputSwitches Sincewecan’twritecustomproceduresandfunctionswithlocalvariablesinMBasic,we’lluseglobal variablesandsubroutines.WritelnMsgdisplaysthemessagepointedtoinStrIndex(MsgID)ontheLCD lineidentifiedinLineNo.First,wereadthelengthofthestringtobedisplayedandstoreitinStrLenvia thestatementReadDMStrIndex(MsgID),[StrLen].Next,weretrievethestringitself(startingonebyte pastthestartingaddress)andstoreitinTempStrviathestatementReadDMStrIndex(MsgID)+1,[Str TempStr\StrLen].NotethatweusethestringlengthtoreadthecorrectnumberofbytesfromEEPROM. TheremainderofthissubroutineshouldbefamiliarafterthrashingthroughLCDworkingsinChapter5.To keepthesubroutineflexibleenoughtowriteonanyofthefourlinesinourdisplay,weindexthestarting memorytothelinenumberviathearrayLineOff(LineNo).(ThevaluesofLineOff(1)…LineOff(4) aretakenfromthedisplay’sdatasheetandareestablishedintheinitializationsectionofProgram6-4.)We thenclearthelinebywriting20spacecharacters,followedbyresettingtheLCDwriteaddresstothestartof thelineandwritethedesiredroomname. Goingbacktothemainroutine,afterwritingtheroomnameonline1,wesetthetemperatureencoder countertothecurrentvalueofthesetpointforthedisplayedroomwiththeassignmentstatementTempCtr =CurSetting(MsgID). Finally,wewritethesetpointtemperatureonline2withacalltoGoSubWritelnTemp.Subroutine WritelnTempfollowstheformatofWritelnMsg,butinsteadofwritingastring,itwritesthesetpoint temperaturefortheselectedroomwithLCDWriteRegSel\Clk\RdWrPin,LCDNib,[“Setting“,DEC CurSetting(Counter),”F”].ThisstatementwritethesetpointtemperatureheldinCurSetting()to thelinedefinedbythevalueofLineNo. ;Changedtempsetting? IfTempCtr<>CurSetting(MsgID)Then CurSetting(MsgID)=TempCtr LineNo=2 GoSubWritelnTemp EndIf GotoMain
Themainroutinenowcheckstoseeifthetemperatureencoderhasbeenchanged.(Rememberwesetthe temperaturecountertothecurrentsetpointwheneverwedisplayanewroom)Thetemperaturecounteriscomparedwiththesetpointoftheselectedroom,andifitdiffers,weupdatethesetpointthrough CurSetting(MsgID)=TempCtranddisplaythenewvaluewithacalltoWritelnTemp. Theremainderoftheworkisdonethroughtheinterrupthandler,ReadEncoder. ReadEncoder ;InvokedonchangeinB4...B7 CurVal=PortB&%00110000/16 ;Roomencoder IfCurVal<>OldValThen ;Ifchanged,checkitout EncFlag=RoomEnc ;IDsourceasRoomEncoder TempOld=OldVal BranchCurVal,[S0,S1,S2,S3] EndIf CurTempEnc=PortB&%11000000/64 ;Temperatureencoder IfCurTempEnc<>OldTempEncThen ;Ifchanged EncFlag=TempEnc ;IDasTemperatureEncoder TempOld=OldTempEnc HighA2 BranchCurTempEnc,[S0,S1,S2,S3] EndIf AfterBranch Resume
ReadEncoderisinvokedwheneverB4…B7changestate,causedbyrotatingeithertheroomselectionor temperatureselectionencoders.Wedistinguishwhichencoderhaschangedbycomparingtheirrespective 103
Chapter6 currentvalueswiththeirlastreadvalues.TheinterrupthandlerthensetstheencoderflagtoeitherRoomEnc orTempEncandsetsthevariableTempOldtoeitherOldValorOldTempEnc.Executionthenjumpsto S0…S3viatheBranchinstruction,justasinProgram6-3. S0 ;--------- IfTempOld=2Then GoSubClockWise ELSE GoSubCounterClockWise EndIf GoToAfterBranch
S0…S3areidenticalwiththeircorrespondingcomponentsinProgram6-3,excepttheoldvaluebeingtested isheldinTempOld.UsingTempOldpermitsustousethesamecodetohandleeitherencoder.Otherwise, wewouldhavetoconstructparallelandvirtuallyidenticalcode,toanalyzeeachencoder’sstate. ClockWise ;------------- ;Checkwhichencoderischanged IfEncFlag=RoomEncThen ;RoomEncoder OldVal=CurVal Counter=Counter+1 EndIf IfEncFlag=TempEncThen ;Temperatureencoder TempCtr=TempCtr+1 IfTempCtr>MaxTempThen TempCtr=MaxTemp EndIf IfTempCtr<MinTempThen TempCtr=MinTemp EndIf OldTempEnc=CurTempEnc EndIf Return
ThesubroutinesClockWiseandCounterClockWisearebaseduponthesubroutinesinProgram6-3,butexpandedtodifferentiatebetweenthetwoencodersources.BasedupontheencodersourceflagvariableEncFlag, thesetwosubroutinesincrement(clockwise)ordecrement(counterclockwise)thecorrectcounter(Counterfor theroomselectionencoder;TempCtrforthetemperaturesetencoder).Thesesubroutinesalsolimitthepossible valuesofTempCtrtothepre-establishedmaximum(MaxTemp)andminimum(MinTemp)temperaturevalues.
IdeasforModificationstoProgramsandCircuits • • • • •
ModifyProgram6-4towritethetemperaturesetpointstoEEPROMandtoreadthesetpointsfrom EEPROMuponstart-up. ExpandWritelnMsgandWritelnTemptoaddathirdparameter,startingcharacternumber.Makean appropriatechangetotheerasefunctionsofthesesubroutines. RewriteProgram6-4touseup/downleft/rightpushbuttonswitchesinsteadofrotaryencoders.After abuttonisheldinforacertaintime,theactionshouldrepeat.Addafifthbutton“Enter”toaccepta changedtemperaturesetpointvalue. ExpandProgram6-4toincludeothertypicalthermostatfunctions,suchasMode:Heat/Cool/Off/ManualFan.Addacurrentroomtemperaturereadingtothedisplay. It’soccasionallynecessarytoreadseveralBCDswitches,suchaswherethePICistheinterfacebetweenusersettableswitchesandaserial-programmedfrequencysynthesizerchip.Figures6-15and 6-16showhowmanyswitchesmaybemultiplexedtoreducethenumberofpinsthatmustbededicated toswitchreading.Apseudo-codealgorithmtoreadtheconfigurationofFigure6-15is:
104
ReadingComplexInputSwitches MakeRB0…RB3Outputs MakeRB4…RB7Inputs Forswitch=0to3 MakeRB0+switchhigh AllotherofRB0…RB3makelow ReadswitchvalueonRB4…RB7 DisplayswitchvalueonLCD Nextswitch
BreadboardupthecircuitsanddevelopcodetoreadtheswitchesandwritetheresultsonanLCDdisplay drivenfromPortCasinProgram6-4.
Figure6-15:Multiplexingaswitch.
Figure6-16:Multiplexingabankofswitches.
105
Chapter6
References [6-1]
Julicher,Joseph,HardwareTechniquesforPICmicroMicrocontrollers,MicrochipTechnologies,Inc. ApplicationNoteAN234(Documentno.DS00234A)(2003). [6-2] D’Souza,Stan,FourChannelDigitalVoltmeterwithDisplayandKeyboard,MicrochipTechnologies, Inc.ApplicationNoteAN557(Documentno.DS00557C)(1997). [6-3] MicrochipTechnologies,Inc.,Tips‘nTricks,(Documentno.DSS40040B)(2003). [6-4] MoreinformationonSherline’stabletopmachineryproductscanbefoundatitswebsite, http://www.sherline.com. [6-5] Miller,Brian,UsingRotaryEncodersasInputDevices,CircuitCellarNo.152,(March2003). [6-6] TechToolsReadingRotaryEncoders,ApplicationNoteHWT4,(undated).Availablefordownloading fromtheInternetatTechTools’swebsitehttp://www.tech-tools.com/catapps.htm. [6-7] CTSCorporation,Series288EncoderTechnicalData,TechnicalDataSheet5288,(undated). [6-8] DisplaytechLtd.,LCDModule204ASeriesv.1.1productSpecifications,(undated). [6-9] ThefreewareprogramTerminalisavailableathttp://bray.velenje.cx/avr/terminal/.
106
7
CHAPTER
Seven-Segment LEDDisplays Inmanyrespects,anLCDmoduleisanidealdisplay;easytouse,availableinawidechoiceofsizesand capacityandsupportedinMBasicwithoneeasy-to-usefunction,LCDWrite.But,asgoodasLCDmodules are,therearetimeswhentheyjustwon’tdo.Chapter7looksatanearlier—butstillcommon—technology, seven-segmentLEDdisplays.(Indeed,muchofwhatwelearninthischaptermaybedirectlyappliedtoan evenoldertechnology,theNixietube.)Seven-segmentdisplayshavebeenbuiltwithothertechnologies, includingincandescentfilamentandvacuumfluorescent,butthesearerarelyusedtoday. LEDdisplaysareavailableinseveralformats,includingdotmatrix(5x7,8x8andotherpixelarrangements) andalphanumericmultisegment(16-segment,forexample).We’regoingtoworkwithasimplerdevice, though,thehumble7-segmentnumericdisplay,intendedtodisplaythedigits0…9.(It’spossible,aftera fashion,todisplaytheletters“a”,”b”,”c”,”d”,”E”and“F”onaseven-segmentdisplay,shouldyoudesire.) TheparticulardeviceusedinthischapterisanAgilentTechnologiesHDSP-5721,twodigit,commonanode yellowLEDdisplay,witha0.56”characterheight.Anycommonanodedisplaymaybesubstitutedforthe HDSP-5721with,atmost,minorchangestothecircuitry.(Themaindifferencewillbethevalueofcurrent limitingresistors.)We’llalsouseavariantseven-segmentdisplayinChapter11.
LEDDisplaySelection DigiKey’scatalogshowsnearly500differentseven-segmentLEDdisplays,withawiderangeofsize,color, packagesandconfiguration.We’llassumethatyoucansortoutthesizeandcolordisplaynecessaryforyour application.Severalselectionparametersareworthyoffurtherconsideration,however. Mountingstyle—Theoverwhelmingmajorityofseven-segmentdisplaysaremadewithconnectionpins exitingatthebackofthehousing.Inmostcases,however,yourmainPCBwillbehorizontal,thus requiringeitheraseparateverticallymountedPCBtoholdthedisplays,orexpensiverightangledisplay sockets.Afewdisplays,however,areavailablewithbottompinsforrightanglemounting.(We’lluse theseinChapter11’sdigitalvoltmeter.) Seven-segmentdisplaysarealsomanufacturedasindividualdigits,paireddigits,tripledigitsandquad digits.Forexperimentationandeducationpurposes,there’slittletobegainedfromanythingotherthanindividualdigits.IusedHDSP-5721dualdigitdisplaysbecauseIhappenedtohaveaquantityonhand. Specialcharacters—Sometimesthedisplaymustincludeaspecialcharacter,suchas“+”and“–”signs.The “–”canbesimplythecentersegmentofanormalseven-segmentdisplay,butifa“+”signisnecessary aspecialdisplayconfigurationisrequired,or“three-quarters”ofa“+”canbemadefromastandard display.Youcanalsofindpartialdigitdisplays,witha“+”,“–”andthedigit“1”.Othercommondisplay arrangementsincludeclockstyledisplays,withcolonsseparatingthehourandminutedigits.Decimal pointsareanotheroption,withtheirplacementbeingeitherleftorrightofthedigit(ornodecimalpoint atall).
107
Chapter7 Commonanodeorcommoncathode—Figure7-1showsatypicalseven-segment display,withthesegmentsidentifiedA…Gandthedecimalpoint.EachsegmentcontainsoneormoreLEDs. Itisn’tnecessarytoconnecttoboththecathodeandanodeofeachindividualdiode, sotosavepins,individualsegmentLEDsareconstructedwitheithertheiranodes orcathodesincommon,asshowninFigure7-2.Commoncathodedisplaysrequire individuallycontrolledhighsidesegmentdriversandacommonlowsidedigitselector.Commonanodedisplaysuseahighsidedigitselectionswitchandindividual lowsidedigitselectors.Eitherconfiguration,ofcourse,requiresacurrentlimiting resistorforeachsegment.We’lluseacommonanodedisplay,buttheprogramlogic andhardwarecanbeeasilyrevisedtoworkwithacommoncathodedisplay. There’sonereasontoprefercommonanodedisplays.Ourdesignusesseparatedigit F i g u r e 7 - 1 : S e v e n s e g m e n t d i s p l a y andsegmentdrivertransistorspermittinghighsegmentdrivecurrentforimproved brightness.Ifyourdisplayprovidesadequatebrightnesswith25mAorlesssegment segmentidentification. current,youmaydirectlyconnectthesegmentsofacommonanodedisplaytothePIC’soutputpins,asthey willsafelysink25mA.Inacommoncathodedisplay,however,thePICwouldberequiredtosourcecurrent toeachsegmentand,aswefoundearlier,PICsarebetteratsinkingcurrentthansourcingcurrent.
Figure7-2:Commonanodeandcommoncathodeconfigurations.
CircuitDesign Figure7-3showsourtestcircuit.It’safamiliarmixofhigh-sideandlow-sidedriversasdiscussedinChapter3.Let’slookatitindetail.
108
Seven-SegmentLEDDisplays Figure7-3:Four-digitLED displaysetup.
PinsA0…A3areconnectedto2N4403PNPtransistorssetupashigh-sidedigitswitches.WhenA0…A3go low,Q1…Q4areforwardbiased,and+5V,lessVSAT,appearsonthecommonanodesofDigits3…0.We’ve selectedR8…R11(2.2Kohm)tolimitthebasecurrentdrivetoaround2.5mA. EachdigithasitscathodesegmentsA…Gconnectedinparallel,witheachsegmentgoingtoanoutputpin ofaULN2003ANPNDarlingtonarray.ThecorrespondinginputsoftheULN2003Aareconnectedtopins B0…B6.(Thedecimalpointisn’tconnected,asitisn’tneededinourapplication.But,don’tworry;we’llsee aseven-segmentdisplaywithautomaticdecimalpointsettinginChapter11.) WhenanypinB0…B6goeshigh,theattachedDarlingtonissaturatedandthuscompletesthecircuit. Thus,toturnonSegment(i)ofDigit(j),theassociatedB0…B6pinmustbehighandtheassociateddigit selectionpinA0…A3mustbelow.Thispermitsustoindividuallycontroleachsegmentofeachdigit.To givetheappearanceofsimultaneousoperation,wecyclethroughallfourdigitsquickerthanourpersistence ofvisionrecognizesflicker. EachsegmentofaHDSP-5721isratedfor60mApeakcurrent,and20mAcontinuouscurrent.Sincewe aremultiplexingfourdigits,we’llbelimitedbythepeakcurrentrating.TheHDSP-5721’sforwardvoltage isspecifiedas2.1Vtypical.Aswe’llseebelow,wemayexpectaround1.0VdropacrosstheULN2003A driver.FromChapter3,weknowthe2N4403’sVSATisaround0.4V.Hence,thevoltageacrossthelimiting
109
Chapter7 resistoris(5.0–2.1–1.0–0.4)Vor1.5V.Toachieve60mA,thecurrentlimitingresistorwouldbe(1.5 V/0.060A),or25ohms.Ifound60mAresultedinabrighterdisplaythanIwanted,sobyexperimentationI foundthedesiredbrightnessrequired68ohms.Theresultantpeakcurrentisapproximately25mA. TheULN2003Aisaninterestingandusefuldevice;solet’stake aquicklookatwhat’sinside.ItconsistsofsevenidenticalNPN Darlingtontransistordrivers,andassociatedsnubbingdiodes ina16-pinDIPpackage.EachDarlingtonisratedat500mA current,and50Voutputvoltage.(Youcan’trunallsevendrivers eachsinking500mAwithoutgrossly exceedingtheULN2003A’spower ratings,ofcourse.)AtypicaldriverappearsinFigure7-4.Again,thisshould befamiliarfromChapter3.Thedriver transistorhasabuilt-inbaseresistor, sowemaydirectlyconnectittoaPIC outputpin.LikeallDarlingtons,it suffersinVSATcomparedwithasingle transistor,beingratedataround1.0V for100mAcollectorcurrent,comFigure7-4:TypicalULN2003Adriver. paredwiththe0.4Vorsowefindfora 2N4401.Eachdriverhasanassociatedclampdiodetopreventdamagewhendrivinginductiveloads.We’ve connectedittoVDD,althoughthisconnectioncouldbeomitted,ifdesired,sincethere’snoinductivespike whendrivinganLED.We’llusethischipforlaterprojects,suchasdrivingsmallsteppermotors,whereit’s importanttoconnecttheclamptoVDD. We’reusingaULN2003Ainsteadofsevenseparate2N4401sor2N7000spurelyasamatterofwiring convenience.So,ifyoudon’thaveaULN2003A,wireupthecircuitwithseven2N7000s,or2N4401swith 2.2Kbaseresistors.Itisn’tnecessarytouseaDarlingtonconfigurationatthecurrentlevelsnecessaryto drivesmallLEDdisplays.IfyourLEDdisplayprovidesadequatebrightnesswith25mAorlesscurrent, omitanyexternalsegmentdriverandconnectthecurrentlimitingresistordirectlytopinsB0…B6.Inthis case,youwillneedtorecalculatethedroppingresistor,andinvertthesenseoftheB0…B6pins.(Withan externaldriver,ahighonB0…B6activatesasegment,butwithadirectconnectionalowonB0…B6is required.Thecurrentlimitingresistorshouldbearound100ohms.) IdevelopedthecircuitofFigure7-3aspartofalargerproject, andFigure7-5showstheresultingprototypePCB.Thedevice thatlookslikeanintegratedcircuitabovethedisplaysare68-ohm currentlimitingresistorsintheformofaBournes4116R-1-680 resistornetwork.Separateresistorswouldworkjustaswell.Of course,youdon’tneedtodesignandbuildaPCBtoexperiment withthiscircuit;asolderlessplugboardworksperfectlywell.You can’tsqueezeallthepartsontothesmall2840developmentboard’s plugboard,however,soasecond,larger,plugboardisrequired. Figure7-5:Completed4-digitLEDdisplay.
TestProgram Nowthatyou’vewiredupthecircuitofFigure7-3,let’stestit.
110
Seven-SegmentLEDDisplays Program7-1 ;Programtodemonstrate4digit7-segmentLEDdisplay ;Sequentiallyshoweachsegmentandeachdigit i j
Var Var
Byte Byte
Fori=B0toB6 Outputi Lowi Next Fori=A0toA3 Outputi Highi Next Main Fori=A0toA3 Lowi Forj=B0toB6 Highj Pause250 Lowj Next Highi Next GoToMain
Program7-1exerciseseachsegmentandeachdigit.Thesegmentsilluminate,oneatatimeinorderA…G for250mseach,startingwithDigit0(rightmost)andmovingleft. Thecodeitselfrequireslittleanalysis;aftersettingB0…B6andA0…A3foroutput,wesequentiallyscanthe digitsandsegments.Theouterloop,i,stepsthroughthedigits.Foreachdigit,theinnerjloopscansthe segments.Recallthatinordertobeilluminated,asegmentrequiresitsdigitline(A0…A3)tobelow(applies +5Vtothedisplaycommon)anditssegmentpin(B0…B6)tobehigh(saturatestheULN2003Darlington). Hence,theiloopsetsoneofA0…A3lowandthejloopsetsoneofB0…B6high.Toturnoffunwanteddigits, allotherA0…A3pinsaresethighandtoturnoffunwantedsegments,allotherB0…B6pinsaresetlow. Now,let’slookatdisplayingactualdigits,0…9.Program7-2continuouslycyclestherightmostdigitfrom 0…9,displayingeachdigitforonesecond. Program7-2 ;Showsdigits0...9inlastplace ;LEDdisplayiscommmonanode ;cathodesthroughULN2003Aarray ;Variables ;-------------i Var Byte Decode Var Byte(11) ;Digitvalues[D3][D2][D1][D0]
;holdssegmentpattern
;Initialization ;------------- Clear
DeCode(0)=%00111111holdssegments DeCode(1)=%00000110 +---A---+ DeCode(2)=%01011011 || DeCode(3)=%01001111 FB DeCode(4)=%01100110 ||
111
Chapter7
DeCode(5)=%01101101 +---G---+ DeCode(6)=%01111100 || DeCode(7)=%00000111 EC DeCode(8)=%01111111 || DeCode(9)=%01100111 +---D---+ DeCode(10)=%00000000;allblank XGFEDCBAisbitorder TRISB=$00 TRISA=$F0 PortA.LowNib=%1111
Main LowA0 Fori=0to9 PortB=DeCode(i) Pause1000 Next GoToMain End
ThemajoradditiontothisprogramisthearrayDeCodetomapthedesireddigitstothesegmentsthatmust beilluminatedtodisplaythatparticulardigit. We’veconnectedthesegmentsintheorderofsegmentAtoB0…segmentGtoB6.Hence,toilluminatesegmentA,wemustwrite%00000001toPortB.ToilluminatesegmentB,wewrite%00000010toPortB,and soforth.Ifwewishtodisplaythecharacter“0”,forexample,wemustwrite%00111111toPortB,thereby illuminatingallsegmentsexceptG.(IfwedirectlyconnectthedisplaycathodestopinsB0…B6,wemust invertthismapping,forexample,todisplaythecharacter“0”wewouldwrite%11000000toPortB.) Anotherchangewe’vemadeistoinitializePortAandPortBthroughTRISAandTRISBstatements,as outlinedinChapter2.ThischangeillustratesthatMBasicoftengivesusseveralwaysofaccomplishing thesametask.(WecouldomittheTRISAstatement,astheLowandHighstatementsautomaticallychange thepintooutput,butit’scleanertoinitializeourinputandoutputpinsdirectly.)Wealsosetalldigitstooff throughPortA.LowNib=%1111. Main LowA0 Fori=0to9 PortB=DeCode(i) Pause1000 Next GoToMain
ThemainloopfirstactivatesDigit0bydroppingA0low.Then,we loopthroughthedigits0…9.Eachdigitisdisplayedthroughthe assignmentPortB=DeCode(i). Nowthatwe’veverifiedthatallsegmentsilluminateandthatthe digits0…9canbedisplayed,let’sdosomethingmoreusefulwith ourdisplay.Program7-3readsthreemomentarycontactswitches; oneincrementsthecount,onedecrementsthecountandonewill clearthecounttozero.Makingitabitfancier,we’llblankleading zeros.We’lldebouncetheswitchesandsetupthereadloopsothat thecounteronlyincrementsonceforeachclosure. First,asshowninFigure7-6addthreemomentarycontact,normalFigure7-6:Addedswitches. lyopenswitchesandpull-upresistorstothecircuitofFigure7-3.
112
Seven-SegmentLEDDisplays Program7-3 ;Programtodemonstrate4digit7-segmentLEDdisplay ;Countsup/downon4-digitLEDDisplay ;LEDdisplayiscommmonanode ;cathodesthroughULN2003Aarray ;Constants DelayCount
Con
3
;Variables ;-------------i Var Byte j Var Byte Decode Var Byte(11) Digit Var Nib(4) Counter Var Word TempWord Var Word ArmUp Var Nib ArmDown Var Nib ;Digitvalues[D3][D2][D1][D0]
;holdssegmentpattern ;holdsdigitvalues ;valuetodisply
;Initialization ;------------- Clear
DeCode(0)=%00111111holdssegments DeCode(1)=%00000110 +---A---+ DeCode(2)=%01011011 || DeCode(3)=%01001111 FB DeCode(4)=%01100110 || DeCode(5)=%01101101 +---G---+ DeCode(6)=%01111100 || DeCode(7)=%00000111 EC DeCode(8)=%01111111 || DeCode(9)=%01100111 +---D---+ DeCode(10)=%00000000 ;allblank TRISB=$00 TRISA=$F0 TRISC=%00000111
XGFEDCBAisbitorder
;segmentsonPortB ;DigitdriveonPortA ;SwitchesonPortC
PortA.LowNib=0 PortB=DeCode(8) Pause1000 PortB=DeCode(10) Pause250 ;blankleading0s Digit(3)=10 Digit(2)=10 Digit(1)=10
Main ;multiplexrighttoleft Fori=A0toA3 ;orderisimportanttovoidghosting PortB=DeCode(Digit(i-A0)) Lowi ;GetDigitsispartofthedelay GoSubGetDigits Pause1 Highi Next GoToMain GetDigits
113
Chapter7 ;Checktheupcountswitch If(PortC.Bit0=0)AND(ArmUp=0)Then Counter=Counter+1 ArmUp=1 EndIf ;Isitoff?Ifsodelay If(ArmUp>0)AND(PortC.Bit0=1)Then ArmUp=ArmUp+1 IfArmUp=DelayCountThen ArmUp=0 EndIf EndIf ;Checkthedowncountswitch If(PortC.Bit1=0)AND(ArmDown=0)Then Counter=Counter-1 ArmDown=1 EndIf ;Ifswitchoff?Ifsodelay If(ArmDown>0)AND(PortC.Bit1=1)Then ArmDown=ArmDown+1 IfArmDown=DelayCountThen ArmDown=0 EndIf EndIf IfPortC.Bit2=0Then Counter=0 EndIf ;Avoidrollover IfCounter>9999Then Counter=0 EndIf Return
;DigitsareindividualBCD TempWord=Bin2BCDCounter Digit(0)=TempWord.Nib0 Digit(1)=TempWord.Nib1 Digit(2)=TempWord.Nib2 Digit(3)=TempWord.Nib3 ;Followingisforblankingleading0s IfCounter<1000Then Digit(3)=10 EndIf IfCounter<100Then Digit(2)=10 EndIf IfCounter<10Then Digit(1)=10 EndIf
End
We’vedeclaredseveralnewvariables,including: Digit Counter
Var Var
Nib(4) Word
Counteristhevaluethatweincrement,decrementorzerowiththeaddedswitches.Sincewehavefourdisplay digits,Countermayrunfrom0…9999.Weaccordinglystoreitinawordlengthvariable.ThearrayDigitholds thevalueoftheindividualdigitstobedisplayed.IfCounteris1234,forexample,Digit(0)=4,Digit(1) =3,Digit(2)=2andDigit(3)=1.(Thedigitsarenumberedwith0attherightmostposition.)
114
Seven-SegmentLEDDisplays
PortA.LowNib=0 PortB=DeCode(8) Pause1000 PortB=DeCode(10) Pause250 ;blankleading0s Digit(3)=10 Digit(2)=10 Digit(1)=10
Aspartofinitialization,weilluminateallsegmentsbydisplaying“8888”for250ms,followedbyblanking theleftmostthreedigits.(DeCode(10)isablank.)Brieflyilluminatingallsegmentsisacommoninitializationfeature,asitpermitstheusertodetectfailedsegments.Wedon’thavetoworryaboutoperatingall segmentssimultaneouslyasweuserobustdrivers.IfyoursegmentsaredirectlyconnectedtopinsB0…B6, simultaneouslyoperatingallsegmentsandalldigitsmayoverstressthePIC’sabilitytosinkcurrent,in whichcasemodifyyourcodetosequencethedigits. Main ;multiplexrighttoleft Fori=A0toA3 ;orderisimportanttovoidghosting PortB=DeCode(Digit(i-A0)) Lowi ;GetDigitsispartofthedelay GoSubGetDigits Pause1 Highi Next GoToMain
Themainloopsequentiallystepsthroughthedigits,fromrighttoleft,withtheFori…NextloopandilluminatesthesegmentsrequiredtodisplaytheassociatedvalueheldinDigit(i).We’llassumeforthe momentthatDigit(i)holdsthecorrectvalue(0…9)foreachofthefourdisplayeddigits.AfterPortB issettotheproperbitsequencetodisplaythecorrectdigit,executionbranchestosubroutineGetDigits, followingwhichanextra1mspauseisexecuted.(Aswe’llseeshortly,subroutineGetDigitsfillsDigit() withthecorrectvalues.) Severalpointsareworthmentioningifyoumodifythiscodeforotherprograms.First,inordertoavoid flicker,theloopmustexecuterelativelyfast.Aswritten,eachdigitisilluminatedforabout4ms,soallfour digitsareupdatedabout60timespersecond.Ifthisupdateratesignificantlyslows,duetoaddedcode,the displaywillstarttoflicker.Differentpeopleperceiveflickerdifferently,butIfindflickerobjectionableifthe updateratefallsbelow40persecond.Second,it’simportanttoswitchbetweendigitsasfastaspossibleto avoid“ghosting”wherefalsesegmentsarebrieflyilluminated.Toavoidghostingwefirstwritethesegment informationtoPortBandthentaketheassociatedApinlowtoactivatethedigit.Reversingthisordercauses objectionableghosting.Finally,there’satrade-offbetweenthedigit-ontimeandperceivedbrightness,of course,sosometinkeringwiththecurrentlimitingresistormaybenecessaryafteryourcodeisfinished. Let’slookatGetDigits.Thissubroutineiscalledevery4msorso. If(PortC.Bit0=0)AND(ArmUp=0)Then Counter=Counter+1 ArmUp=1 EndIf ;Isitoff?Ifsodelay If(ArmUp>0)AND(PortC.Bit0=1)Then ArmUp=ArmUp+1 IfArmUp=DelayCountThen ArmUp=0 EndIf EndIf
115
Chapter7 Allswitchesarewiredwiththenormal(unpressed)positionopen,sothata0representsswitchpressedand1 isswitchun-activated.Wehavetwoalmostidenticalroutinestohandletheupanddownswitchinputs.We’ll onlylookatthe“up”switchcode. AssumeforthemomentthatArmUp=0(it’sinitializedthatway)andthatthe“up”switchispressed.The conditionalIf(PortC.Bit0=0)AND(ArmUp=0)thusevaluatesastrue,Counterisincremented andArmUpisassignedas1. Aslongasthe“up”switchcontinuestobepressedthesecondconditionalIf(ArmUp>0)AND (PortC.Bit0=1)fails,asPortC.Bit0=0.ArmUpthuscontinuestoequal1andtheearlierconditionalwillfail,thuspreventingCounterfrombeingupdatedduetocontinuedswitchactivation. Whenthe“up”switchisreleased,thesecondconditionalIf(ArmUp>0)AND(PortC.Bit0=1) evaluatestrue,soArmUpisincremented.Iftheswitchbounces,it’spossiblethatthefirstconditionalmay evaluatePortC.Bit0=0astrue.However,ArmUpcontinuestobegreaterthan0,sotheArmUp=0part ofthefirstconditionalfailsandCounterisnotincremented.Eventually,however,assumingthe“up”switch isnotpressed,ArmUpreachesDelayCountatwhichtimeitisresetto0andwearereadyforanotherpress ofthe“up”switch.DelayCountisaconstantthatI’vesetat3,thusrepresentingtwopassesofGetDigits, orabout8ms.YoumayneedtovaryDelayCount,dependingonthebounceperformanceofyourswitches, but3isagoodstartingpoint. IfPortC.Bit2=0Then Counter=0 EndIf
WeneednotcomplicatereadingtheresetswitchconnectedtopinC2;itdoesn’tmatterifbouncecausestwo orthreeconsecutiveresets. ;Avoidrollover IfCounter>9999Then Counter=0 EndIf
Sinceourfour-digitdisplayonlyshows0…9999,werestrictCountertothosevaluesthatarecapableof beingdisplayed. TempWord=Bin2BCDCounter Digit(0)=TempWord.Nib0 Digit(1)=TempWord.Nib1 Digit(2)=TempWord.Nib2 Digit(3)=TempWord.Nib3
Let’slookathowwegettheindividualdigitvaluesoutofCounterandintotheDigitarray.Itturnsout thatthisisarathercommonactivityandMBasicincludesafunction,Bin2BCDtoperformitforus.(There’s anerrorinsomeeditionsoftheUser’sGuidewherethisfunctionisincorrectlyidentifiedasDec2BCD.)Let’s lookat“binarycodeddecimal”abitmoreclosely. SupposeCounterholds1234.Thevalue1234(decimal)isheldinMBasicashex$4D2.Ifwewantedour displaytoshowhexadecimal(assumingwedefinedDeCode($A)…DeCode($F)),wecouldveryeasilyfind ourdigits.We’vedeclaredCounterasawordlengthvariable,soithasfournibbles: WordValue $4D2
Nibble3 $0
Nibble2 $4
Nibble1 $D
Nibble0 $2
Hence,Digit(0)=Counter.Nib0,etc.But,yousay,wewantadecimaldisplay,notahexadecimalone. Fairenough.First,however,whatis1234?It’s1×1000+2×100+3×10+4.Withthisunderstanding,we candeviseanalgorithmtofillDigit(): Digit(3)=Counter/1000 Remainder=Counter//1000
116
Seven-SegmentLEDDisplays Digit(2)=Remainder/100 Remainder=Counter//100 Digit(1)=Remainder/10 Digit(0)=Remainder//10
InMBasic“/”isintegerdivisionand“//”istheremainder,ormodulus,function.Let’sseehowthisalgorithmworksifCounteris1234. 1234/1000=1 1234//1000=234
->Digit(3)
234/100=2 234//100=34
->Digit(2)
34/10=3
->Digit(1)
34//10=4
->Digit(0)
But,there’safasterwaytoaccomplishthisconversionthaninvokingsixintegerdivisionandremainderoperationsinMBasic.First,adefinition:binarycodeddecimal,orBCD,usesfourbits(onenibble)torepresent eachdecimaldigit.Sinceawordis16bitslong,wecan“pack”fourBCDdigits,eachfourbitslong,into eachword.Thisarrangement,oftencalled“packedBCD,”isshownbelow,supposing,somehow,weareable togeteachnibbletoholdthedesireddigits. WordValue 4660 $1234
Nibble3
Nibble2
Nibble1
Nibble0
1
2
3
4
Thedecimalvalueof$1234is4660,butlookingateachnibbleindividuallyweimmediatelyseewhatweare lookingfor,[1][2][3][4]. MBasic’sBin2BCDfunctionconvertsabinaryvariabletopackedBCD.Hence,fillingDigit()issimplya matterofassigningeachnibbletoitsDigit()counterpartthefollowingtheBCDconversion.Weaccomplishthiswiththefollowingcodesnippet: TempWord=Bin2BCDCounter Digit(0)=TempWord.Nib0 Digit(1)=TempWord.Nib1 Digit(2)=TempWord.Nib2 Digit(3)=TempWord.Nib3
Finally,foraestheticreasonsweblankleadingzeros. ;Followingisforblankingleading0s IfCounter<1000Then Digit(3)=10 EndIf IfCounter<100Then Digit(2)=10 EndIf IfCounter<10Then Digit(1)=10 EndIf
We’vedefinedDeCode(10)asablankdigit(allsegmentsoff),sotoblankadigitwesetDigit()as10. ThistaskiseasilyaccomplishedbycheckingthevalueofCounter.IfCounterisunder1000,weknow thatatleasttheleftmostdigitmustbe0,andaccordingassignDigit(3)asablank.Werepeatthistestand assignmentprocesswith100and10forDigit(2)andDigit(1). Afterblankingleadingzeros,thesubroutineisfinishedandprogramexecutionreturnstoMain.
117
Chapter7 Wecannowtesttheprogram.Everytimethe“up”buttonisoperated,thedisplayedcountwillincreaseby one.Everytimethe“down”buttonisoperated,thedisplayedcountwilldecreasebyone,withaminimumof zero.Pressingthe“clear”buttonresetsthedisplaytozero. Program7-3callsthesubroutineonceevery3.8msaswritten.Theanti-bouncedelaylimitsthespeedwith whichthecounterwillincrementanddecrementtoabout20to30operationspersecond,morethanfast enoughforhand-operatedswitches.
IdeasforModificationstoProgramandCircuits • •
•
•
•
Addsegmentdefinitionsfor“a”,”b”,”c”,“d”,“E”and“F”toDeCode().RemovetheTempWord= Bin2BCDCounterstatementanddisplaythecountinhexadecimal. HowdoesflickerchangeasyoumodifythePause1statement?(IfoundthatifIchangedthepause timeto5,flickerisquiteobjectionable,andwith4,flickerisbarelynoticeable.Icouldnotdetectany flickerforapausetimeof3orbelow.Ifyouwishtodisablethepause,commentitoutordeletethe statement.Pause0actuallyexecutesPause255.) Howdoesperceivedbrightnesschangeasyoumodify thePause1statement?Whatistheratioofdigit-onto digit-offtime?Iftheoverheadiszero,eachdigitshould beon25%ofthetime.(AsFigure7-7shows,withthe Pause1statementoperational,eachdigitisilluminated 22.1%ofthetime.Theoverheadisthus11.6%.) Insteadoftriggeringup/downcountswithmechanical switches,substituteafunctiongenerator’ssquarewave output.Howfastcanyouupdatethecounterbefore itmissesinputpulses?Itispossibletoincreasethe responsespeed?(Youdon’tneedtodebounceafunction generator’sinput,sotheinputsoftwarecanbesimpliFigure7-7:Program7-3digitontime,Pause1; fied.)IsitpossibletoreplacethePause1statement Ch1:PinA0;Ch2:PinA1. withrepeatedsubroutinecallstoGetDigits? AnalternativetousingBin2BCDtofillthearrayDigitwiththefourindividualdigitsofCounteristo useMBasic’sDECmodifier:
Digit=DEC4Counter\4
TheDECoperatorfillsDigitwiththeASCIIvaluesofCounter.IfCounter=1234,Digitwill holdthefollowingvalues:
Digit(0)=“1” Digit(1)=“2” Digit(2)=“3” Digit(3)=“4”
ToconverttheASCIIvaluesheldinDigittonumericalvalues,simplysubtractthevalueofASCII“0” usingaFor…NextlooptocyclethroughallfourelementsofDigit.Sinceweareworkingwithfour digitvalues,wemodifytheDECoperatortospecifyamaximumoffourcharactersbyappendingthe digit4totheoperator.(SeeChapter9formoreonusingtheDECoperator.)
ReviseProgram7-3tousethisapproach.Howdoestheprogramspeedcomparewiththeoriginal Bin2BCDapproach?
118
Seven-SegmentLEDDisplays
References [7-1]
AgilentTechnologies,14.2mm(0.56inch)SevenSegmentDisplays,Documentno.5968-9410E(2000). AllegroMicroSystems,Inc.,2003thru2024High-Voltage,High-CurrentDarlingtonArrays,(undated).
[7-2]
119
8
CHAPTER
Introductory StepperMotors Steppermotors,asthenameimplies,rotateindiscretesteps.Mostconventionalmotorsarecontinuous;if wemakeamarkontheshaftofaconventionalmotorandifwewereabletopreciselycontrolthemotor’s excitation,wecouldmaketheshaftmovetoanyangle.123.456degreesfromthestartingmarkisjustas achievableas321.765degrees.Ofcourse,practicalconsiderationsmakethisdegreeofprecisionunlikelyin arealmotor.Asteppermotor’sshaft,incontrast,ismoveabletoonlycertain,pre-definedangles.A48-step steppermotor,forexample,maybepositionedonlyinincrementsof7.5degrees(360°/48).Hence,wemay commandtheshafttogoto7.5°(onestep)or15°(twosteps)butnotto8.432°.(Laterinthischapter,andin Chapter19,we’llseewaystosteptheshaftrotationone-halforasmallerfractionofthemotor’snormalstep size,sothedifferencebetweenconventionalandsteppermotorsblurs.) Whywouldwewantamotorthatonlymovesinsteps?Supposewewishtomoveaninkjetprinter’sprint headacrossthepaper,andthatwemustpositiontheprintheadwithanaccuracyof0.001".We’llassumethe printheadisattachedtoanonslip,nostretchtoothedbeltandthatthebeltisdriventhroughatoothedpulley systemattachedtoapositioningmotor.Let’sattacha200-stepsteppermotortothepulley,through5:1step downgears,andpickthepulleysizesothat1,000stepsofthemotormovestheprintinghead1.000inch. Eachmotorstepthereforecorrespondsto0.001"andwemaypositiontheprintheadto4.567"byinitializing theprintheadatthestartpositionandthenadvancingthemotorby4,567steps.This“openloop”solution ismuchcheaperthana“closedloop”designthatcontinuouslymonitorsthepositionoftheprintheadand stopstheadvancewhenthetargetpositionisreached. We’llconcentrateonsteppermotorfundamentalsinthischapterandadvancedapplicationsinChapter19.
StepperMotorBasics Introduction Let’sstartbyconsideringtheplusesandminusesofsteppermotors: StepperAdvantages
StepperDisadvantages
•Precisecontrolofposition-onepulseadvancesonestep, permittingopenloopcontrol.
•FulltorquefromzeroRPM. •Stepaccuracytypically5%ofstepsize,buterrorsarenon-
cumulative. •Nobrushesorothercurrentcarryingmovingparts;lifetime isthereforelimitedonlybythebearinglife. •Easytointerfacewithmicrocontrollers. •Themotorisself-lockingifthewindingsarepowered whilenotrotating;evenifunpowered,mostdesignshave appreciableresidualtorque.
120
•Limitedspeed. •Certainstepratesmaymechanicallyresonatewiththe
motorcausinglossoftorqueandundesiredvibration.
•Largesteppersarenotreadilyavailable.Moststeppers areinthe0.0001HPto0.05HPrange. •Torquedecreasesasrotationalspeedincreases;ifthe motorstalls,positionlocationislost.
IntroductoryStepperMotors Operation Let’sseehowasteppermotorworks.We’llconsiderahighlysimplified motorthatdoesn’tmatchrealmotordesignsbutprovidesausefulmental modelofhowastepperfunctions.Figure8-1illustratesoursimplemotor model.Atthecenterisabarmagnet,freetorotate,surroundedbyfour electromagnets,spaced90degreestoeachother.Theelectromagnetsare woundoversoftironpoles.Inmotorterminology,thebarmagnetisthe rotorandthesurroundingelectromagnetsformthestator.InFigure8-1, themotorisun-poweredandtherotorhasautomaticallyrotatedtothe positionofminimummagneticenergy;thatis,thepermanentmagnetrotorpositionsitselfsothatitsfluxhastheshortestairpathandthelongest ironpath.Ifyoutrytorotatetherotorbytwistingtheshaft,youwillnote Figure 8-1: Simple stepper model: resistance;youhavetosupplytheenergyrequiredtobreakthemagnetic unpowered. attractionbetweenthestatorandthenearestpole.Youshouldfeelthesame A resistance,followedbythemotorsnappingintoanewstableposition,if + youtwisttheshaftofarealsteppermotor.(Oneuncommontypeofstepper,thevariablereluctancemotor,doesn’texhibitthisbehavior,aswe’ll − S notelater.)Inanunpoweredmotorthetorquerequiredtobreaktherotor freefromitsrestpositioniscalledthedetenttorque. N D
A
B S
– S N C
B
Figure8-2:WindingAenergized.
S
D
A
C
N
S
D
S
B
+
–
A
C S
B
D N
S
Figure8-3:Sequentialcurrentflow inA,BandCcausesrotation.
– +
C
121
Now,let’senergizewindingA,asshown inFigure8-2.We’llsetthepolarityof thecurrentthroughAsothattheinward facingpoleisamagneticsouthpole, whichattractstherotor’snorthpole.As longaswindingAisenergized,therotor isheldinplace.Theexternaltorquenecessarytooverridethemagneticattraction andmovetherotorisknownasthe holdingtorqueorstatictorque.Formost motorstheholdingtorquewhenoperated atratedcurrentisabout10timesthe detenttorque. Whathappensifweenergizethewindingsinsequence?Supposeweapply currenttowindingsA,BandC,inthat order,withthepolaritysothattheinside ofeachwindingisamagneticsouth
Chapter8 pole.Figure8-3showstheresult;therotorrotatesclockwise,asitsnorthpoleissequentiallyattractedby thesouthpolestemporarilycreatedbyenergizingA,BandC.Ofcourse,wemaykeepthisupandenergize D,thenA,B,C,D…solongaswedesiretherotortocontinuesteppingclockwise.Shouldwewishtostop themotor,wemayeitherde-energizeallwindingsor,ifweneedadditionalresttorque,wemaykeepone windingenergized.Ifwewishtorotatetherotorcounter-clockwise,weenergizethewindingsinthereverse order:D,C,B,A. Aswe’llseelater,thereareseveralvariationsontheorderofenergizingwindings,includingenergizing morethanonewindingatonce.
UnipolarandBipolar Thewindingsinoursteppermaybeinternallyconnectedinseveralconfigurations.Two,however,twoareof interest,theunipolarandbipolarconnection.We’llstartwiththebipolarmotor,sometimescalledatwophasesteppermotor. Figure8-4showsoursimplemodelmotorconnectedinthe bipolarconfiguration.Themotorhasfourterminalsaccessibletotheuser,1through4.Theupperdiagramshows ourmotorinthestartingposition,withcurrentflowing throughbothwindingsAandC.NotethatwindingsAand Carewoundsoastoproduceoppositefieldpolarity;when currentflowsinthedirectionofthearrows,windingA presentsasouthpoletotherotorwhilewindingCpresentsanorthpole.Thispolarityisrepresentedbyterminal 1beingpositivewithrespecttoterminal3.Unlikeour earlierexamination,therotoristhusheldinplacebytwo energizedwindings,notone.Supposewethende-energize windingsAandC,energizewindingsBandDtorotate therotor90degreesclockwise,de-energizeBandDand thenre-energizewindingsAandC.Wenowdesirethe magneticpolaritytomatchthatofthelowerillustrationin Figure8-4;themagneticpolarityofwindingsAandCare reversedfromtheupperillustration.Weaccomplishthis magneticpolarityreversalbyreversingthedirectionof currentflowthroughwindingsAandC;wemaketerminal 3positivewithrespecttoterminal1.Let’sseehowthepolaritychangesforonecompleteclockwiserotationcycle. Step 1 2 3 4
Terminal1 + None – None
Terminal3 – None + None
Terminal2 None + None –
Terminal4 None – None +
Figure8-4:Bipolarconfigurationofsimplestepper.
Thereasonwetermthisconnection“bipolar”isthatthe currentpolarityinthewindingsreverses—thatis,ithastwopossiblepolarities,dependingonthestep.We’ll considerhowtoaccomplishreversingthewindingcurrentflowwhenexaminingdrivecircuits.
122
IntroductoryStepperMotors Figure8-5showsoursimplestepperconnectedasa unipolarmotor.(Unipolarmotorsarealsoknownasfour phasesteppermotors.)ThewindingsA-CandB-Dremain inseries,butthecentertaps,XandY,respectivelyarealso available,thusgivingussixconnectionstothewindings. (Insomeunipolarmotors,bothcentertapsareconnected togetherandonlyfivewiresarebroughtout,asshownby thedashedconnectionlinebetweenterminalsXandYin Figure8-5.)Inthenormalmodeofoperation,thecenter tapisalwaysconnectedtothepositivesupplyandwecause currenttoflowinthewindingsbyconnectingtheirfree endstothenegativereturn,groundinmostdesigns. IntheupperillustrationinFigure8-5,windingAis energizedbyplacingpositivevoltageonterminalXand groundingterminal1.Fromthisisthestartingpointwe’ll assumethatwindingAisthenbeende-energized,winding Benergizedtopulltherotor90degreesclockwiseandthen windingBisde-energizedandnowwindingCisenergizedbyconnectingterminal3toground,asshowninthe lowerillustrationinFigure8-5.Currentflowthroughthe windingsisalwaysinthesamedirection;hencethename “unipolar”forthisconnection.NotethatsincewindingsACandB-Dareinseriesjustasinourbipolarconfiguration, wemaytakethisunipolarmotorandconnectittoabipolar drivecircuit(makingnoconnectionstothecentertapsX andY)anditwillwork.(Thisistrueforrealunipolarmotors,notjustforoursimplemodel.) Figure8-5:Unipolarconfigurationofsimplestepper.
Wecansummarizethebenefitsanddrawbacksofunipolarandbipolarconnectionsas: Configuration Unipolar Bipolar
Advantages
Disadvantages
•Simplestdrivecircuit. •Efficientuseofmotorwindings. •Greatertorquethanforsamesizeunipolar
•Lessefficientuseofmotorwindings. •Requiresspecialdrivecircuitry;most commonlyanH-bridgearrangement.
motor.
TypesofStepperMotors Figure8-6showsfourtypicalsteppermotors.Thesmallertwo motorsattheleftofthefigureareknownastincanorcan stackorpermanentmagnetmotors,whilethetwolargermotorsarehybridconstructed. Tincanmotorsareinexpensive,constructedfromapressed orstampedcaseandwithasmoothpermanentmagnetrotor magnetizedwithalternatingnorthandsouthpoles.Usuallytin Figure8-6:Typicalsteppermotors. canmotorshaverelativelycoarsestepsizes,with24and48
123
Chapter8 steps/rev(15and7.5degrees/step)beingtypicalvalues.Tincanmotorsusesleevebearingsandaretypically foundininexpensiveelectronicproducts,suchasinkjetprintersandfaxmachines.Mostmanufacturersuse thecasediameter(inmillimeters)andnumberofstepsaspartofthemodelnumber.Forexample,thesmallestmotorinFigure8-6isaNipponPulseMotormodelPF35-48L4stepper.Thecasediameteris35mm (about1-3/8")andithas48stepsperrevolution.TheL4suffixindicatesthecoilvoltage(nonstandard)and rotormagnettype(Neodymium).Othermanufacturersusedifferentidentifiers,ofcourse,butcasediameter andnumberofsteps/revolutionarecommonlyincorporatedintothemodelidentification. ThetwolargermotorsinFigure8-6areofhybridconstruction.Figures8-7through8-9showapartially disassembledhybridmotor.(Idon’trecommenddisassemblingasteppermotorunlessabsolutelyessential, assomehighperformancerotorswillbepartiallydemagnetizediftherotorisremovedfromthemotorcase.) Figure8-8showsthetoothedpermanentmagnetrotor.Therotorisconstructedoftwotoothedsegments, withonesegmentoffsetbyone-halftoothwidthfromtheother,therebyeffectivelyhalvingthestepsize. (TheobjectsattheendoftherotorshaftareaballbearingandaBellevillewasher.)Figure8-9showsthe stator,whichhasseveralnoteworthyfeatures.First,thefourwindingsareclearlyvisible,justlikeourmental motormodel.However,thepolesaresegmented,witheachpolehavingfourprojectingpieces.(Inmotor terminology,thesearesalientpoles.)Itisn’tnecessary—orevendesirable—forthepolestobecontinuous aroundtheinnerperipheryofthemotor;therotoriscontinuous,whichissufficient.
Figure8-7:Hybridmotordisassembly.
Figure8-8:Hybridmotor toothedrotor.
Figure 8-9: Hybrid motor interruptedtoothedstator.
Hybridmotorsareoftenmanufacturedinindustry-standardcasesizes,asdefinedbytheNationalElectrical ManufacturersAssociation(NEMA).AmotormanufacturedbyCompanyXinNEMAstyle34ismechanicallyinterchangeablewithanotherNEMA34casesizemotormanufacturedbyCompanyY.Thelargest motorinFigure8-6isaNEMA34motor,whiletheonenexttoitisaNEMA23motor.Ofcourse,the electricalandperformancespecificationsoftwomotorswithidenticalNEMAcasesizesarenotnecessarily (orevenusually)thesame. Hybridmotorsaremoreexpensivethantincanmotorsandfeaturehigherqualityconstruction,suchasball bearingsinsteadofsleevebearings,andcastormachinedcasesinsteadofpressedcase.Additionally,the toothedconstructionpermitsmuchfinersteps,with180and200step/revbeingcommonvalues. Athirdtypeofmotoristhevariablereluctance,resemblingthehybridinconstruction,butwithanonpermanent magnettoothedrotor.Variablereluctancemotorsarerelativelyuncommonandwillnotbefurtherdiscussed. Thereareothermuchlesscommonsteppermotortypes,suchasthree-phaseunipolar.Theserequirespecializeddrivingcircuitsandarebeyondthescopeofthistext.
IdentifyingStepperMotors Toidentifyasteppermotorthathasnonameplateorforwhichadatasheetisnotavailable,wemayusethe followingsteps. 124
IntroductoryStepperMotors 1. Turnthemotorshaftbyhand.Youshouldfeelthedetents;ifyoufeelnodetentsthemotorisnotastepperofthetypeconsideredinthischapter.Turnthemotorshaftonecompleterevolutionandcountthe numberofdetentsyouencounter.Thisgivesthesteps/revvalueforthemotor.Commonstep/revvalues are24,48,72,100,180,200,400and800,althoughthelatertwovaluesarerelativelyunusual.Your countshouldbeclosetoamultipleof10or12.Ifyoucount197,italmostcertainlymeansyoumisseda counthereorthereandhavea200step/revmotor. 2. Howmanywiresoraconnectiondoesthemotorhave? a. Four—youlikelyhaveabipolarmotor. b. Fiveorsix—youlikelyhaveaunipolarmotor. 3. Withanohmmeter,identifythewirecolorsorterminal numberscorrespondingtoyourwindingsandlabelthem asinFigure8-10(bipolar)orFigure8-11(unipolar).Make anoteofyourresistancemeasurements.Theresistanceof windingsAandBshouldmeasure within5%orsoofeachother. Likewise,inaunipolarmotor, theresistancefromthecommon centertaptoeachwindingend shouldbeapproximatelyequal andtheresistanceacrosseach completewinding(A1toA2and B1toB2)shouldbeapproximate- Figure 8-10: Winding Figure 8-11: Winding labels for unipolar lyequalandtwicethevaluefrom labelsforbipolarstepper steppermotor. motor. thecommontoeachend. 4. Ifyouhaveaccesstoaninductancebridge,measuretheinductanceofthewindings.Ifyoudon’thaveabridge,youmaysafelyskip thisstep. 5. Nowwewillattemptto“guestimate”themotor’svoltageandcurrentratings.Thisstepisnecessary onlyifyourmotordoesn’thaveanameplateorpartnumberprovidingthisinformationorifyoucan’t findadatasheetforthemotor.Thereisnomagicwaytoaccomplishreverseengineeringthemotor’s ratingwithcompleteaccuracy,butwecancomecloseenoughforexperimentationpurposes.Measure thephysicalsizeoftheunknownmotoranddeterminetheconstructiontype.Isitatincanorahybrid motor?Next,searchthemanufacturer’scatalogs,eitherpapercopiesorontheinternet,untilyoufinda motorwiththesamephysicalsize,constructiontypeconnectiontype(bipolarorunipolar)andnumberofsteps.Seeifyoucanfindamotorwithsimilarcoilresistanceand(ifyouhavemeasuredit,coil inductance).Ifyoucan’tfindamatch,thencalculatethepowerdissipation(inwatts)forseveralmotors ofthesamecasesizeasyourmotorusingtheformulaP=I2R,wherePisthepowerinwatts,Iisthe motor’scurrentratinginamperesandRisthemotor’swindingresistanceinohms,withbothIandR fromthecatalogvalues.YourcalculatedPwilllikelydifferamongthematchingmotors,socalculate anaveragevalue.Then,usingtheaveragepowerdissipationforthephysicallysimilarmotorsandyour measuredresistancevalue,calculatetheresultingIforyourmotor,usingtheformula I = P . R 6. Nowthatwehavedeterminedthemotor’sratedcurrent,I,andthemeasuredR,calculatethemotor’s nominaloperatingvoltageVfromOhm’slaw,V=IR. 7. Noteanyotherimportantparametersfromtheclosestmatchingdatasheet,suchasthemaximumspeed insteps/secondorthemaximumtorque.
125
Chapter8 ReadingaStepperSpecificationSheet Let’slookatatypicalspecificationsheetforaninexpensivetincanmotor,aNipponPulseMotormodel PF35-48.I’vereproducedthedatasheetparametersbelow. Parameters DriveMode ExcitationMode StepAngle StepAngleTolerance StepsperRevolution Voltage WindingResistance WindingInductance HoldingTorque RotorInertia StartingPulseRate,Max SlewingPulseRate,Max AmbientTemp.Range,Operating Temperaturerise Mass
Units ° % V ohm/Ø mH/Ø mN•m kg•m² pps pps °C K g
PF35-48 Unipolar Bipolar Full-step(2-2ex) 7.5 ±5 48 12 5 12 5 90 16 100 17 48 8.9 124 19 20 20 25 25 4.5x10–7 500 530 –10~+50 55 80
Whatdoeseachlinemean? Drivemode—ThePF35-48isavailableineitherabipolaroraunipolarconfiguration. Excitationmode—Aswewillseelater,asteppermaybeoperatedinseveralmodes,andcertainparameters, suchastorqueandstepangle,aredifferentfordifferentmodes.Thedatasheet’sstatement“full-step (2-2ex)”meansthattheperformancedataisbaseduponfullstepoperation,withbothcoilsenergized. Ifthissentencedoesn’tmeanmuchtoyourightnow,putastarinthemarginandcomebacktoitafter readingtherestofthischapter. Stepangle—theangleindegreesthroughwhichtheshaftrotateswhenitadvancesonestepwhileinfullstep mode.Thevalue7.5°correspondsto48steps/rev. Stepangletolerance—thetolerance,asappliedtothestepangle,thatis,theanglethemotorshaftadvances inonefullstepis7.5°±5%.It’simportanttorememberthistoleranceappliesonastep-by-stepbasis andisnotcumulative.After48steps,themotorwillreturntoitsoriginalstartingpointwithanaccuracy of±5%×7.5°or±0.375°.After48000steps(1000completerevolutions),themotorwillbeatitsoriginalstartingangle±0.375degrees.Thenoncumulativeerrorperformanceofastepperisthekeytoits abilitytoperformprecisionoperations.Iftheerrorwerecumulative,afterbeingcommandedtoperform 48000steps,or1,000revolutions,theshaftanglewouldbeunknownwithin±50revolutions,quiteadifferencefromtheactual±0.375degrees! Stepsperrevolution—thenumberoffullstepsrequiredtoreturnthemotorshafttoitsstartingangle.Since thereare360°inonerevolution,thestepangleandstepsperrevolutionarerelatedbytheformula: 360 θ= whereθisthestepangleandNisthenumberofstepsperrevolution. N Voltageandwindingresistance—We’llconsiderthesetwoparametersatthesametime.Youmayrecall fromhighschoolphysicsthatthemagneticfieldofanelectromagnetisproportionaltothecurrentin thewindingsmultipliedbythenumberofturns(ampere-turns)andthattheattractiveforcebetweentwo magnetsisproportionaltotheirmagneticfields.Hence,forafixednumberofturns,theshafttorque inthesteppermotorisproportionaltothecurrentthroughthewindings.Ifwedoublethecurrent,we
126
IntroductoryStepperMotors doublethetorque.And,weknowfromelementarycircuittheorythatresistivepowerdissipationis proportionaltothesquareofthecurrent;P=I2R.Ifwedoublethecurrent,thepowerdissipatedinthe motorgoesupfourfold. Themotordesignermustbalancethesetwoeffectsagainsteachother;tomakethemotormorepowerfulfor itssize,thedesignerwishestomaximizethecurrent.However,morecurrentcausesmoreinternalheating andifthemotortemperatureexceedsacertainlevelthewindinginsulationmaybreakdownandthemotorwillfail.Alternatively,toincreasethestator’smagneticfield,thedesignermaydecidetousesmaller diameterwire,whichallowsmoreturnsinagivenspace(increasingampereturns),butthesmallerdiameter wirehasgreaterresistancewhichmeanswemustapplyhighervoltagetothestatorcoiltoobtainthedesired current.Thetrendistolowervoltagepowersupplies,andthemotormanufacturerstrytomeettheircustomers’needswithlowervoltagemotordesigns. Themotor’sratedvoltageandresistanceallowustocalculatethenominalwindingcurrentusingOhm’slaw: I=V/R.Aswewillseewhenwelookatdrivercircuits,usuallywedrivethemotorthroughaquasi-constant currentarrangement. Inthiscase,thePF35-48motorhastwowindingoptions;a12Vwindingwith100ohmsresistanceanda 5Vwindingwith17ohmsresistance.Wecancalculatethecorrespondingcurrentsas120mAand294mA, respectively.Sincethetorquespecificationsareidenticalforbothwindingoptions,wemaysafelyassume thatthe12Vwindinghascloseto2.45moreturnsthanthe5Vversion,therebykeepingtheampereturns— andtorque—identical.AquickcheckconfirmsthatthePF35-48isdesignedforidenticalpowerdissipation forboth12Vand5Vwindings.The12Vcoildissipates1.44wattsattheratedvoltage,whilethe5Vcoil dissipates1.47watts. ThePF35-48motorIusedinthischapterhasan“L4”suffix,meaningitisa“special”voltagerating.Since weknowthemotordissipationis1.4watts,andsinceImeasuredthecoilresistanceas20ohms,wemay determinethemotor’sratedvoltageis: P=
E2 ; E = PR R
E = 1.4 × 20 = 5.3V Likewise,wecalculatedtheratedcurrent: P = EI ; I =
I=
P E
1.4 = 265 mA 5.3
Where:
Pisthepowerdissipationinwatts; Iisthecurrentinamperes; Visthevoltageinvolts; Ristheresistanceinohms.
Finally,thereisa“nondissipative”elementofinputpowertothemotor;thepowerthatgoestoperform mechanicalworkattheoutputshaft.We’veneglectedthis,asformanysteppermotorapplicationsthemechanicalworkoutputissmallcomparedwiththeresistivewindingloss. Windinginductance—Asaconsequenceofproducingthedesiredmagneticfield,themotorwindingsare inductors.Theirinductancelimitstherateofriseofcurrentthroughthewindingwhenawindingis 127
Chapter8 energized.Fromaperformanceprospective,wewouldlikethewindingcurrenttoimmediatelyassume itsfinalvaluewhenthevoltagestepapplied.We’lllookatthisinmoredetailwhenweconsiderdrive circuits,butlet’sexaminethedifferencebetweenthe5Vand12VversionsofthePF35-48motor. Inintroductoryelectricalcircuitsclass,welearnthatifavoltageisappliedacrossaseriescircuitofan inductorandaresistor,suchasthewindingsofasteppermotor,thecurrentstartsatzeroandincreasesaccordingtoanexponentialfunction,withalimitingvaluedeterminedbytheseriesresistance.Thecurrent versustimerelationshipis: Rt i = I f 1 − e L Where:
Ifisthesteady-statecurrent,inthiscasetheappliedvoltageVdividedbythewinding’sresistanceR,or V If = R
Risthewinding’sresistance(plusanyotherresistanceinthecircuit)inohms; Listhewinding’sinductanceinHenries; tisthetimeinsecondsafterthevoltageisappliedtotheinductor; eisthebasefornaturallogarithms,2.71828182…
Weoftencanuseasimplercalculation—theinductivetimeconstantτforcircuitanalysis: L τ= R Where: τisthetimeconstant,inseconds. Afterthetimeτ,thecurrentwillhavereachedapproximately 63%ofitssteadystatevalue,aftertime2τitwillhavereached 86.4%,etc. Figure8-12showstheresultofaSPICEcircuitsimulation ofthecurrentthroughthe5Vand12Vwindingofabipolar PF35-48motor.Itfollowsthenegativeexponentialform oftheequationshownabove.Althoughthemagnitudesof thetwocurrentsaredifferent,bothreachequalpercentages ofthemaximumatalmostthesametime.Thiscanbeseen eitherbyexaminingFigure8-12,orbycomparingthetime constantsofthetwowindings: Figure8-12:Simulatedcurrentthrough5Vand 12Vsteppermotorwindings,PF35-48motor. 19 × 10 −3 τ 5V = = 1.12 ms 17 124 × 10 −3 τ12V = = 1.24 ms 100 Sincethetwotimeconstantsarealmostidentical,thecurrentthroughthetwocoilswillfollowanalmost identicaltimerelationship,expressedintermsofthepercentageoffinalcurrentversustime.Sincethemotor’storqueisproportionaltoampereturns,andsincethe12Vmotorhasproportionallymoreturnsthanthe 5Vmotor,weconcludethatregardlessofwhetherthe5Vor12Vwindingsareused,thePF35-48’storque versustimeperformancewillbealmostidentical.Thatthe5Vand12Vwindingshavealmostidenticaltime 128
IntroductoryStepperMotors constantsis,ofcourse,notanaccident,butratheraproductofthedesigner’sintentiontoproducetwomotorsthathaveessentiallyidenticalperformance,regardlessofwhetherthe5Vor12Vversionisused. Holdingtorque—isthetorquethatmustbeappliedexternallytorotatetheshaftfromitspositionifpower isappliedtothewindings.It’sstatedinthemetricunitmilli-Newton-meters(mN-m),andmaybe convertedtothecorrespondingImperialunitounce-inchesbytherelationship:1oz-in=7.06mN-m.If youworkinImperialunits,don’tforgetthedifferencebetweenforceandweight;torqueisexpressedin forceunits,notweightunits. Rotorinertia—isthemomentofrotationalinertiaofthemotor’srotor.Forourpurpose,we’lljustnotethat thisvalueisameasureoftheeffortrequiredtogettherotormovingandtostopit,onceitismoving.If youknowhowtousetherotorinertiavalueinyourdynamicperformancecalculations,youdon’tneed metosummarizeithereandifyoudon’tknowhowtomakethoseperformancecalculations,thena shortsummarywon’tdoyouanygood. Startingpulserate,maxandslewingpulseratemax—Bothvaluesaremeasuresofhowfastthemotormay bestepped—fromeitherastandingstart,oroncerotating.Let’sseehowfastwemayrunthemotor,in termsofrevolutionsperminute,atermperhapsmorecommonineverydayusage.We’llassumethemotorstartsfromrest,sothemaximumrateatwhichwemaypulseitis500pps. Inonesecond,therefore,thenumberofrevolutionsisequaltothenumberofstepsdividedbythenumberof steps/revolution:
Rsec =
Steps / sec 500 = = 10.4 rev / sec Steps / rev 48
Toconverttorevolutionsperminute,multiplyby60:
RPM =
60 P 60 × 500 = = 625 N 48
Where
RPMisthespeedinrev/min; Pisthenumberofpulses/sec; Nisthenumberofstepsperrevolutionforthemodebeingused.
Bysmallmotorstandards,thisisamodestspeedindeed.Buttheadvantageofastepperisnotitshighspeed, butratheritsprecisionanditsabilitytoprovidetorqueatslowspeeds. Ifyouhavetowringthelastpossiblebitofspeedfromthemotor,youcanrampthespeedupfromastandingstart. Ambienttemperaturerange–operatingandtemperaturerise—Themotorisratedtooperateinanambient temperaturerangeof–10°C(+14°F)to+50°C(122°F).Itstemperatureriseis55°K.AKelvindegree isnumericallyequaltoaCelsiusdegree,withthedifferencebeingthezeropoint—Celsius’szerois approximatelythefreezingpointofwaterwhile0°Krepresentsabsolutezero—approximately–273°C or–459°F.Hence,ifoperatedatthemaximumpermittedambienttemperature,themotor’stemperature willnotexceed105°C(222°F). Mass—Themotor’sweight.
OperationModes We’vealludedtovariousdrivemethodsearlier,solet’sseewhat’sinvolvedincontrollingastepper. We’llstartwithaunipolarmotor,asit’stheeasiesttounderstand.We’llassumeit’sa6-wiremotorandthatit’s connectedtoapowersupplysettothemotor’sratedvoltage.Figure8-13showsfourSPSTswitchesthaten129
Chapter8 A
– S N
B S
D
A
C
N
S
D
B
+
A
C
S
B
D N
–
ableustoconnectanyofthemotor’sfourwindings toground;inarealcircuit,wewoulduse,forexample,oneofthelowsidedrivercircuitswesawin Chapter3.Buttounderstandtheprinciples,we’ll justthinkofthelowsidedrivercircuitwefinally settleuponanothingmorethanawaytoeither isolatethemotorwindingorconnectittoground.
S
–
F i g u r e 8 - 1 3 : U n i p o l a r m o t o r connection.
S
We’llreturntooursimplifiedmotortoexamine C howwesteptheswitches.We’llseethreepatterns Figure8-14:Wavestepping. produceusefulresults;wave,fullstepandhalf-step. Wave—Figure8-14showshowwemayadvance therotorbysequentiallyenergizingcoilsA,B,CandD(notethatI’veshowntheswitchesinwinding order,notnumericalswitchorder): +
Step 1 2 3 4
S1(WindingA) Closed Open Open Open
S3(WindingB) Open Closed Open Open
S2(WindingC) Open Open Closed Open
S4(WindingD) Open Open Open Closed
Thismodeiscalled“wave”becauseyoucanseeasequenceofswitchclosuressteppingdownandacrossthe table,causingarotatingmagneticwavewithinthemotor.Thestatorpolesarealignedwiththerotorpoles foreachstep. Fullstep—Inwavemode,onlyonewindingisenergizedatanytime.Ifwecouldsimultaneouslyenergize twowindings,wecoulddoublethemagneticstrengthwithinthemotor,therebydoublingthetorque. Canwedothis?Figure8-15showshowwemightaccomplishthis.BysimultaneouslyenergizingwindingsAandB,forexample,wecreatetheequivalentof(almost)adouble-strengthcoil,halfwaybetween AandB.Thus,oursteppingpatternisAB,BC,CD,DA: Step 1 2 3 4
S1(WindingA) Closed Open Open Closed
S3(WindingB) Closed Closed Open Open
130
S2(WindingC) Open Closed Closed Open
S4(WindingD) Open Open Closed Closed
IntroductoryStepperMotors
A
+
A
Start
–
–
S
S
N N
D
B
S
B
S
S
D
Half-Step
+
–
A
A
+ C
–
C
S N
S
S
D
S
D
B
–
A
+
+
–
S
S
N
A
B
– +
C S
C
N
S
B
–
+
N
D
S
B
S
D
+
–
S
– +
C
C
Figure8-15:Full-stepmode.
Next Full Step
Figure8-16:Half-stepmode.
Infact,energizingtwowindingsat90degreestoeachotherdoesn’tquitedoublethetorquecomparedwitha singlewinding,butit’sclose.Therotorpolesalignhalf-waybetweenadjacentenergizedstatorpoles. Half-step—We’veseenthatwavemodemakestherotorstepinalignmentwiththepoles,andfullwave modecausestherotortomovetohalf-waybetweenthepoles.Supposewecombinedandinterleafed waveandfullwavemode.Wecouldthencausetherotortomoveinincrementsofone-halfthenormal stepsize.Figure8-16showshowthisworks.OurexcitationmodeisA,AB,B,BC,andsoon: Step 1 2 3 4 5 6 7 8
S1(WindingA) Closed Closed Open Open Open Open Open Closed
S3(WindingB) Open Closed Closed Closed Open Open Open Open
S2(WindingC) Open Open Open Closed Closed Closed Open Open
S4(WindingD) Open Open Open Open Open Closed Closed Closed
Ifyoucarefullylookatthehalfstepexcitationpattern,youseethatthewaveandfullsteppatternsare interleafed.Youshouldalsoseethathalfsteppingproducesnonuniformtorque—forhalfthestepsonlyone windingisenergizedwhilefortheremaininghalfofthestepstwowindingsareenergized.Thiseffectively limitshalfsteppingoperationtotorquerequirementsthatmaybemetbyonlyonewinding. Althoughwe’velookedatthepatternsforaunipolarmotor,infacttheidenticalpatternsworkforabipolarmotor.Let’slookathowwemightswitchabipolarmotor.Figure8-17showsaconceptualviewofcontrollinga 131
Chapter8 Normal
Reversed
+Motor
Isolated
+Motor
A
+Motor
C
A
Normal
C
Reversed
+Motor
C
Isolated
+Motor
B
A
+Motor
D
B
D
Figure8-17:Bipolarmotorconnection.
bipolarmotor.Foreachwindingpairwehavethree options:currentflowinonedirection,currentflowin theoppositedirectionandunenergized.Forconvenient reference,we’llidentifythecurrentflowdirectionby aplussign.A+/Cforexample,meansthefreeendof windingAispositiveandthefreeendofwindingC isnegative,Figure8-18showswavedriveoperations forthefirstthreesteps.Thewindingexcitationpattern foronecompleterevolutionis:A+/C, B+/D,C+/A,D+/B. We’lluseanelectronicversion F i g u r e 8 - 1 8 : B i p o l a r oftheswitchesshowninFigure connection–wavemode. 18-17,inparticularaSN754410Hbridge.TheH-bridge,aswe’llsee laterinthischapter,hasfourinputs, correspondingtoeachendofthe twowindings.Whenthecorrespondinginputisset atlogichigh(1),thatwindingendisconnectedto thepositivemotorsupply;whenaninputislogic low,theassociatedwindingendisconnectedto ground.Hence,A+/Ccorrespondstoalogicpattern of10,whileA/C+is01.IfACisde-energized,the logicpatternis00.Usingthisterminology,thewave drivepatternforourbipolarstepperis:
132
B
D
IntroductoryStepperMotors Step 1 2 3 4
S1(WindingA) 1 0 0 0
S3(WindingB) 0 1 0 0
S2(WindingC) 0 0 1 0
S4(WindingD) 0 0 0 1
Comparethiswiththedrivepatternforwavedriveofaunipolarmotor.Substitute1foraclosedswitchand 0foranopenswitchandyouwillseethatthetwopatternsareidentical.Sincethefullstepandhalf-steppatternsarealsoidenticalwiththeirunipolarcounterparts,wewon’trepeatthedrawingsandpatternschartsfor bipolarmotors. ComparingFigures8-14and8-18shouldrevealanadvantageofbipolarmotors;inwavedrive,aunipolar motorhasonlyonewindingenergized,whilethebipolarmotorhastwowindingsenergized,thusapproximatelydoublingtheavailabletorque.Ifwemakethesamecomparisonforhalf-stepoperation,wefind thattheunipolarmotorhaseitheroneortwowindingsenergizedwhilethebipolarmotorhastwoorfour windingsenergized,againaboutdoublingtheavailabletorque.Withrespecttofullstepdrive,thetorquedifferenceislesspronounced,asbothmotorhavetwowindingsenergizedforeachstep.However,duetorotor andstatoralignmentissues,abipolarmotortypicallyprovides20%to30%moretorqueinfullstepmode thananotherwiseidenticalunipolarcounterpart.Ofcourse,themotor’spowerandtemperatureratingsmust alsobeconsideredandmaybealimitingfactor.
Programs Let’sstartwithasimple programdemonstrating MBasic’sbuilt-insupport forsteppermotors,viathe SpMotorfunction.Figure 8-19showshowtoconnect thesteppertothe16F877A. Weusenospecialfunctions,soalmostanyPIC maybesubstitutedforthe ‘877A.Themotoryouuse mustbeaunipolarstepper anditmustdrawlessthan 500mA.IusedthePF35-48 unipolarstepperweearlier analyzed.(ThePF35-48 Iusedhas5Vwindings.) Notecarefullythewinding connectionsinfigure8-19. Eachpairofwindingscon- Figure8-19:UnipolarsteppermotorconnectionforProgram8-1. nectstoalternatingoutputs, nottoadjacentoutputs.Setthemotorsupplyvoltagetothestepper’sratedvoltage.Don’tusethebuilt-in +5Vsupplyinthe2840DevelopmentBoardtorunastepper—it’snotsafelyuptothetask. AswelearnedinChapter3,thePIC’soutputcircuitryisnotsuitabletodirectlyconnecttoastepper.Hence weuseaULN2003ADarlingtontransistordriver.DonotconnectastepperdirectlytothePIC;itmaywell
133
Chapter8 destroythePIC.Ifyoudon’trecalltheULN2003A,pleasereviewChapter7wherewewentthroughitsapplication.TheULN2003AcontainssevenDarlingtontransistors,withbuilt-inbasecurrentlimitingresistors. Alogical1ontheULN2003A’sinputsaturatestheoutput,therebyprovidingthefunctionalequivalentof closingoneofthefourmechanicalswitchesinFigure8-13. AswelearnedinChapter3,whenweswitchaninductiveload, thecollapsingmagneticfieldcausesavoltagespikethatmay damagetheswitchingtransistor.Inaddition,thecoupledwindingsofasteppermotoractliketransformerwindingsandcan haveinducedinthemasubstantialvoltagespikewhenother windingsareturnedonoroff.Tocontrolthespike,weusethe built-indiodesoftheULN2003AandanexternalZenerdiode. ThecircuitwillworkwithouttheZener,butwithslowercurrentdecay.Slowercurrentdecaymaynotbeaproblemifyour stepperrunsatslowstepspeeds,buttomaximizespeedadd theZener.Figure8-20isaSPICEsimulationanalysisofthe currentreleaseimprovementaZenerdiodemakesoverusing theULN2003A’sinternalclampingdiode.WithaZener,the motorcurrentdecaystozeroinabout400µs,versus2.3msfor Figure 8-20: A Zener diode improves current releasetime. asimplediodeclamp.Whydowewantthecurrenttoquickly decayafterawindingisde-energized?Thedecaycurrentacts toholdtherotorinplaceandpreventsitfrombeingattractedtothenewlyenergizedwinding.Thismaynotbeso importantifthemotorissteppedslowly,butasweincreasethestepspeed,itbecomesincreasinglyimportantto ensurethecurrentdecaysquicklyuponrelease.Aswe’llseelaterinthischapterandinChapter19,forfaststeppingrateswemustalsoimprovetherateofcurrentincreaseatturn-on. Program8-1 ;Program08-01 ;DemoSpMotorfunctionwithULN2003A ;Bipolarmotor ;Constants ;---------MPin MDelay MStep
Con Con Con
B0 ;startingpinfornibble 10000 ;usec/step 1000 ;totalsteps
Main ;Rotateinonedirection SpMotorMPin,MDelay,MStep Pause1000 ;Nowreversedirection SpMotorMPin,MDelay,-MStep Pause1000 GoToMain
Program8-1exercisesMBasic’sbuilt-insteppermotorfunction,SPMotor,invokedwiththreearguments: SPMotorPin,Delay,Step
Pin—isaconstantorvariablethatdefinesthefirstpinoffourconsecutiveoutputpinsusedbySPMotor. Delay—isaconstantorvariabledefiningthetimebetweensteps.Delayisinmicrosecondswithamaximum 32-bitintegervalue. Step—isavariableorconstantanddefineshowmanystepsaretobetaken,andthedirection.Positivenumbersstepinonedirectionandnegativenumbersstepinthereversedirection. 134
IntroductoryStepperMotors MPin MDelay MStep
Con Con Con
B0 ;startingpinfornibble 10000 ;microseconds/step 1000 ;totalsteps
WestartbydefiningallthreeargumentstoSPMotor;forourtest,we’llusepinsB0…B3,stepat10 ms/stepandtake1000steps.(10msis10000µs.) Main ;Rotateinonedirection SpMotorMPin,MDelay,MStep Pause1000 ;Nowreversedirection SpMotorMPin,MDelay,-MStep Pause1000 GoToMain
Ourprogramstepsthemotor1000stepsinonedirection,pausesforonesecondandsteps1000stepsinthe reversedirection.Afteranotheronesecondpause,thecyclerepeatsendlessly. Nowisasgoodatimeasanytodiscussrotationdirection.AlthoughMBasic’sUser’sGuiderefersto“clockwise”and“counter-clockwise”rotationasbeingassociatedwithpositiveandnegativevaluesofthestep argument,infact,thedirectionofrotationisalsogovernedbytheorderinwhichthewindingsareconnectedto thedriver.Ifthemotorrotatesinadirectionoppositetothewayyouwishittorotate,reverseanywindingpair. Forexample,referringtoFigure8-19,toreversethemotor’s rotationaldirection,interchangethemotorleadsconnected topins16and14oftheULN2003A.Or,interchangethe motorleadsconnectedtopins15and13.However,ifyou interchangebothpairsofleads,youwillrestoretheoriginal rotationaldirection!Accordingly,shouldyourmotorrotate counterclockwiseeventhoughSPMotorhasapositivevalue stepargument,reverseanypairofwindingleadstosynchronizeyourmotor’swindingswithSPMotor’soutputpulse sequence. Let’slookatthewaveformsassociatedwithProgram8-1and thecircuitofFigure8-19.Figure8-21showsthevoltageat Figure8-21:WaveformsofProgram8-1;Ch1: pin16oftheULN2003A(Chan.1)andtheassociatedcurPin16ULN2003A;Ch2:Currentthroughmotor rent(Chan.2)throughthemotorwinding.SinceChannel1 windingconnectedtopin16. oftheoscilloscopeisconnectedtothecollectorofthedrive transistor,currentflowisassociatedwithtakingthecollector low.Let’sseewhatwemaylearnfromFigure8-21. First,wenotethatwhensaturated,theULN2003A’scollectordoesnotdropmuchbelow1V,withthemeasured valuebeing960mV.WelearnedthereasonthataDarlington transistorhasarelativelyhighVSATinChapter3,sothis valueisexpected.However,sinceweareapplyingonly5V tothemotorwindingsandULN2003A,themotorhasonly4 Vappliedacrossitswindings,whichreducesthecurrentand henceitsavailabletorque. Thecurrentthroughthemotorwinding(Channel2)shows atypicalinductivecurrentrise,butwithtwointeresting aspects.Notethekink;currentgoesuprapidly,thenreverses Figure8-22:Expandedviewofcurrentwaveform; momentarilybeforeresumingtherise.Asimilareffectis Ch1:Pin16ULN2003A;Ch2:Currentthrough seenattherelease.(Figures8-21and22weretakenwithout motorwindingconnectedtopin16. 135
Chapter8 theZenerdiode,sotheyshowarelativelyslowcurrentrelease.)Also,theslopeofthecurrentriseisfaster beforethekinkthanafterward.Figure8-22providesanexpandedviewofthecurrentwaveform. Whatcausesthekink?Therearetwofactorsasworkhere.First,whentherotormoves,itsmagneticfieldinducesacurrentbackintothewindings,withthedirectionopposingtheoriginalcurrent.Second,astherotor moves,theinternalgeometryofthemotorisdifferent,givingrisetoachangeininductanceofthewinding. Fromcircuittheory,weknowtherelationshipbetweenaconstantinductanceLandtherateofchangeof currentforaconstantappliedvoltageVis: di V=L dt Rearrangingwefind: di V = dt L ThisrelationshipmaybeinterpretedasV/Lbeingtheslopeofthecurveofcurrentversustimeplot.Ifwe ∆I di substitutefinitechanges,i.e., fortheinfinitesimal ,wedeterminethewindinginductancebeforethe ∆T dt kinkas58mHandafterthekinkas133mH.Thesevaluesshouldonlyberegardedasapproximate,asthere areseveralsourcesoferrorinthissimplisticapproach,nottheleastofwhichbeingLisnotaconstantbutis ratherchangingwiththemotorshaftposition. Finally,youmayaskwhy,sincewesettheparameterMdelayat10ms,thecurrentpulsemeasures20ms duration?Toanswerthisquestion,considertheoutputpatternofafullstepdrive(toclarifytherepetitive nature,I’veincludeafifthstepthattakesusbacktothestartingpoint): Step(starttime) 1(t=0ms) 2(t=10ms) 3(t=20ms) 4(t=30ms) 5(t=40ms)
B0 1 0 0 1 1
B2 1 1 0 0 1
B1 0 1 1 0 0
B3 0 0 1 1 0
AhighonB0…B3correspondstoalowattheDarlingtonoutput,andcurrentflow.Aswesee,eachwinding isheldlowforthedurationoftwoconsecutivesteps,or20msinthiscase. Let’sseeifwecanimprovethecurrentrisetime.Figure8-23showsonesimpleapproachtospeedingup thecurrentrise.Althoughourmotorisratedat5V,we’lluseaseriesresistorandhighervoltagetospeed upthecurrentrise.Whydoesaresistorimproverisetime?Aswelearnedearlier,thecurrentrisetimeis proportionaltoL/R,whereRisthetotalresistanceintheseriescircuit.SinceLisgovernedbythemotor’s construction,andhencenotalterablebyus,wemayreducethequotientL/RbyincreasingR.Alternatively, youmaywishtothinkofthisapproachasusingahighervoltageandaseriesresistortoapproximateaconstantcurrentsource.Thisapproachissometimescalledan“L/Rdrive”design. Wecan’tofcourse,selectaseriesresistanceandvoltagerandomly.Theresistancemustbechosentoprovide theratedmotorcurrent,baseduponthetotalseriesresistance,andthedesireddrivevoltage.Figure8-24 showstherelevantresistancesandvoltagedropswemustconsider.We’vepreviouslymeasuredthevoltage dropVSATacrossQ1at1V.And,ImeasuredRinternalat20ohmsformyPF35-48motor.Wepreviouslycalculatedthemotor’sratedcurrentas265mA.TherelationshipbetweenR1,V1andImotoris: R1 =
V1 − VSAT − RInternal I motor 136
IntroductoryStepperMotors
Figure 8-24: Calculating motor seriesresistorvalue.
Figure8-23:L/Rdriveforunipolarmotor.
Supposewewishtofeedthemotorfroma12Vsupply.WhatisR1’svalue?
R1 =
12 − 1 − 20 = 21.5 Ω 0.265
Toillustratethedifferenceinrisetimeversusseriesresistance,Iconductedtestswith20ohms,40ohmsand 50ohmsseriesexternalresistance.ThetestvoltagesIuseddifferslightlyfromtheoreticallyexactvalues,but arewithinreasonabletolerances.I’vealsomeasuredtheinductanceofawindingas8.5mHat1000Hzwith aGeneralRadio1650ARLCbridgeandwe’llusethisvalueforcalculatingL/R.(Yes,Iknowthisvalue doesn’tcomeclosetothevaluesweestimatedearlierfromtherisetimedata,butitcloselymatchesthedata sheetvalue.) Parameter SupplyVoltage L/R(µs) Figure
R1=0 5 425 Fig8-21
R1=20 11 212 Fig.8-25
R1=40 16 142 Fig.8-26
R1=50 18 121 Fig.8-27
Comparingthefollowingfourfiguresshowssignificantimprovementintheinitialcurrentrisetime.We alsoseediminishingreturnssettingin.ThemaximumsteprateofthePF35-48is550ppsifwerampupthe speedfromastandingstart.Ifweusewaveexcitation,eachmotorcurrentpulsewouldbe1.8ms,asunlike fullstepexcitation,thepulselengthisnotdoubled.Ifwedesiretherisetimetoberoughly10%ofthepulse length,weseethattheseriesresistanceshouldbebetween20and40ohms.Ifwecalculateitexactly,fora risetimeof180µs,wedeterminethatthetotalresistancemustbeatleast47ohms,whichrequires27ohms externalresistanceplusthewindingsinternal20ohms.Therequiredsupplyvoltageisthen13.5V,allowing
137
Chapter8
Figure8-25:20ohmsseriesresistanceand11V supply Ch1: pin 16 ULN2003A; Ch2: current throughmotorwindingconnectedtopin16.
Figure 8-26: 40 ohms series resistance and 16VsupplyCh1:pin16ULN2003A;Ch2:current throughmotorwindingconnectedtopin16.
1VforVSATdropintheULN2003A.Weshouldalsocheck theresistordissipation.We’vedesignedthevoltageand resistancevaluebasedon265mA,sowecancalculatethe resistor’sdissipationbyP=I2R.
Figure 8-27: 50 ohms series resistance and 18VsupplyCh1:pin16ULN2003A;Ch2:current throughmotorwindingconnectedtopin16.
P=I2R=0.2652×27=1.9W Infullstepoperation,theaveragepowerdissipatedwillbe onehalfthisvalue.However,ifweoperatethemotorinthe lockedposition—thatis,awindingpowereduptolockthe rotorinplacewiththemotor’sholdingtorque,R1willdissipatethefull1.9W.R1shouldaccordinglybea27-ohm,5 Wresistor.Whenstopped,SPMotorretainstheoutputvalue ofthelaststepposition,sotwowindingswillbeenergized unlessyouexplicitlydropalloutputpinslow.
Wewillmakeonefinalmeasurement—howhighavoltage spikemightweexpectwithoutaclampingdiode?Ifyou wishtomakethismeasurement,reconfigureyourcircuittothearrangementshowninFigure8-28.Weare intentionallyoperatingtheULN2003Ainanunsafeenvironment,sothereisariskthatyourULN2003A willbedestroyed.Ifyoudon’twanttoriskyourULN2003A,skipthistest.Figure8-29showsthatwithouta clampingdiode,spikesreachcloseto30V.TheclampingdiodesIusedare1A,50VSchottkydevices. Program8-2 Fromversion5.3.0.0onward,MBasic’sSPMotorcanbecommandedtooperateineitherfullsteporhalf stepmodes.ByaddingthelineSPMOTOR_HalfCON0totheprogram,wemayforceSPMotortooperate inhalfstepmode.TheconfigurationlineSPMOTOR_HalfCON0isacompile-timeoption,i.e.,youmay notswitchbetweenhalfandfullstepoperationwhileyourprogramisrunning.Rather,SPMotorwilleither causefullstepoperation(thedefault)orhalfstepoperationifyouincludethecommandSPMOTOR_Half CON.(TheassociatedCD-ROMcontainsanexampleofhalf-stepoperationofSPMotorinasecondversion ofProgram8-1.Ofcourse,thisprogramrequiresMBasic5.3.0.0orlatertocorrectlyoperate.) Toprovidemoreflexibility,let’slookatwritingourownroutinesforbothwaveandhalf-stepmodes.Whilewe’reat it,we’llincludethefullstepmode.Program8-2iscompatiblewithanyofthecircuitsweusedwithProgram8-1. 138
IntroductoryStepperMotors
Figure8-28:Configurationforvoltagespiketest.
Figure 8-29: Spikes from collapsing field; Ch1: clamped with Schottky diode; Ch2: unclamped. ;Program08-02 ;DemoFull,HalfandWavewithULN2003A ;Constants ;---------SeqLen MPin MDelay MStep
Con Con Con Con
8 B0 5 1000
;howmanypatternsforrepeat ;startingpinformotordriver ;millisecondsperstep ;eachMStepcauses8motorcycles ;numberofcyclerepeatstomake
;Followingholdtheoutputpatternsforeachstatedmode. ;FullandWaveare4stepslong,sowerepeateachtomake ;allpatterns8stepslong. HalfStepByteTable8,12,4,6,2,3,1,9 FullStepByteTable12,6,3,9,12,6,3,9 WaveStepByteTable8,4,2,1,8,4,2,1 ;Variables ;---------i j MPort
Var Var Var
Word Word PortB.Nib0
139
Chapter8 ;Initialization ;------------Forj=MPintoMpin+3 Outputj Next MPort=0 Main ;First,fullstepdrive Fori=0toMStep-1 Forj=0toSeqLen-1 MPort=FullStep(j) PauseMDelay Next;j Next MPort=0 Pause1000 ;Nexthalfstep Fori=0toMStep-1 Forj=0toSeqLen-1 MPort=HalfStep(j) PauseMDelay Next;j Next MPort=0 Pause1000 ;Lastlywavedrive Fori=0toMStep-1 Forj=0toSeqLen-1 MPort=WaveStep(j) PauseMDelay Next;j Next MPort=0 Pause1000 GoToMain
TheconceptbehindProgram8-2issimple;wewritethebinarypatterncorrespondingtothedesiredmotor stepsequencetofourconsecutivepinsonaport.Let’srecapthesteppingsequenceforallthreemodes: Mode
Full
Half
Step
Bit3
Bit2
Bit1
Bit0
Decimal
1
1
1
0
0
12
2
0
1
1
0
6
3
0
0
1
1
3
4
1
0
0
1
9
1
1
0
0
0
8
2
1
1
0
0
12
3
0
1
0
0
4
4
0
1
1
0
6
5
0
0
1
0
2
6
0
0
1
1
3
7
0
0
0
1
1
8
1
0
0
1
9
(continued)
140
IntroductoryStepperMotors
Wave
1
1
0
0
0
8
2
0
1
0
0
4
3
0
0
1
0
2
4
0
0
0
1
1
I’veaddedacolumn“decimal”tothetabletoshowthenumericalvalueofthefourpatternbits.Perhapsthe mostconvenientformtoholdthesepatternbitsisabytetable.Wecanconstructthreebytetables,onefor half-step,oneforfullstepandoneforwavedrive. HalfStepByteTable8,12,4,6,2,3,1,9 FullStepByteTable12,6,3,9,12,6,3,9 WaveStepByteTable8,4,2,1,8,4,2,1
Thehalf-steptableentriesfollowthesequencedirectly.Thefullandwavebytetables,however,doubleup thevalues,sothatweuseeightentriestoholdtwocompletefour-steppatterns.Wedothistomakethethree bytetablesidenticallength,asitletsususethesamecodetooutputanyofthethreemodes.(We’llseethe benefitofthisapproachmoreinProgram8-3.) ;Constants ;---------SeqLen MPin MDelay MStep
Con Con Con Con
8 B0 5 1000
;howmanypatternsforrepeat ;startingpinformotordriver ;millisecondsperstep ;eachMStepcauses8motorcycles ;numberofcyclerepeatstomake
We’veusedthesamenamesasinProgram8-1forthekeyconstants.However,we’vedeviatedfromhow Mstepisused.InMBasic’sSPMotorfunction,MStepdefineshowmanyfullstepsthemotormakes.For simplicity,weuseMSteptodefinehowmany8-stepcyclesProgram8-2outputs.(We’llgetbacktoa step-basedapproachinProgram8-3.)Thus,ifwesetMStepto1000,Program8-2outputs1000*8,or8000 motorsteps. MPort
Var
PortB.Nib0
Wealsodefineonevariable,Mport,tousewhenaddressingtheoutputport.Sinceweonlyneedfourpins, weuseanibble.ForconsistencywithProgram8-1,weusePortB’slownibble. Forj=MPintoMpin+3 Outputj Next MPort=0
Weinitializethefouroutputpinstobeoutputs. Main
;First,fullstepdrive Fori=0toMStep-1 Forj=0toSeqLen-1 MPort=FullStep(j) PauseMDelay Next;j Next
Tooutputfullstep,weloopthroughthebytearrayFullStep,sendingeachpatterninsequence.Werepeat thisMSteptimes.
MPort=0 Pause1000
Atthecompletionofoutputtingthefullsteps,wede-energizeallwindingsandpauseforonesecond.
;Nexthalfstep Fori=0toMStep-1 Forj=0toSeqLen-1 MPort=HalfStep(j) PauseMDelay Next;j
141
Chapter8
Next MPort=0 Pause1000
Werepeatthesamesequence,exceptoutputtingthehalfsteppattern. ;Lastlywavedrive Fori=0toMStep-1 Forj=0toSeqLen-1 MPort=WaveStep(j) PauseMDelay Next;j Next MPort=0 Pause1000 GoToMain
Weconcludewithwavedrive,and whencompletedgobacktoMain andstartthesequenceoveragain. AfterverifyingProgram8-2with oneoftheULN2003Acircuitswe usedwithProgram8-1,let’stry analternativedriver.InChapter 3,wesawhowefficientasmall MOSFET,the2N7000,isasalow sidedriver,solet’sreplacethe ULN2003Awithfour2N7000s. Figure8-30showsourcircuit. I’veshownfourSchottkydiodes asclamps,becauseIdidn’thave foursuitableZenerdiodesathand. But,youcansignificantlyimprove thecurrentreleasetimebyadding Zenerdiodesinreverseserieswith thefourSchottkydiodes.IncidenFigure8-30:Unipolardriverusing2N7000s. tally,ifyourmotoronlyhasfive windings,theconnectionarrangementshowninFigure8-31maybeused.Ifwe restrictourselvestofullsteporwavedrive,we canuseasimplerarrangement;useoneseries resistorforallwindings(butonlyonemodefor anyresistorarrangement).Thisispossiblebecausethesamenumberofwindingswillalways beon;oneinthecaseofwavedriveortwoin thecaseoffullstepdrive.Thus,thecircuithas aconstantloadandonecurrentlimitingresistor isadequateforeachmode.(Youcan’tusethe sameresistorforwaveandforfullstepoperation,ofcourse.)However,ifweoperatehalf-step Figure8-31:Connectionarrangementdiffersforfiveandsix mode,thecurrentalternatesbetweenoneandtwo wireunipolarsteppers.
142
IntroductoryStepperMotors windingsenergized,soasinglecurrentlimitingresistorisnot acceptable.Figure8-32showstheoverlapbetweentwomotorwindingsduringfullstepoperation. Program8-3 We’llwrapupourexcursionintotheworldofsteppermotors withaprogramthatdemonstratesanimprovedapproachto thetechniqueintroducedinProgram8-2.We’llencapsulatethenutsandboltsofoutputtingthestepperpatternina subroutine.We’llalsolookatbipolardriversandshowhow toconnectaunipolarmotorasabipolardevice.Toverify theoperationofProgram8-3,youmaystartwithanyofthe Figure 8-32: 2N7000 driver output during full circuitswe’vedevelopedforPrograms8-1and8-2. step operation; Ch1: drain voltage Q1; Ch2: drainvoltageQ2. ;Program08-03 ;DemoFull,HalfandWavewith ;SN754410unipolarandULN2003Abipolaroperation ;Quasi-Functionsubroutine ;Constants ;---------MPin MDelay MStep
Con Con Con
B0 5 1000
;startingpinformotordriver ;millisecondsperstep ;unlikeprogram8-2,MStepisnumberofsteps ;numberofstepstomake ;can’tbemorethan65535.
SeqLen ModeFull ModeWave ModeHalf
Con Con Con Con
8 0 8 16
;howmanypatternsforrepeat ;modeconstants
DFwd DRev
Con Con
1 -1
;directionconstants ;fwdandrevarearbitrary
;0..7posn=full,8...15=wave16-23=half ;forfull&waverepeatforcyclelength=8 StepTableByteTable| 12,6,3,9,12,6,3,9,8,4,2,1,8,4,2,1,8,12,4,6,2,3,1,9 ;Variables ;---------i j MPort Direct Mode
Var Var Var Var Var
Word SByte PortB.Nib0 SByte SByte
;countssteps ;indexespatterns ;outputportpins ;direction ;modetype
;Initialization ;------------;setmotorporttooutput Forj=MPintoMpin+3 Outputj Next ;allwindingsoff MPort=0 Main
143
Chapter8 ;Fullstepforward Mode=ModeFull Direct=DFwd GoSubBiPolar MPort=0 Pause1000 ;Fullstepreverse Direct=DRev GoSubBiPolar MPort=0 Pause1000 ;Halfstepforward Mode=ModeHalf Direct=DFwd GoSubBiPolar MPort=0 Pause1000 ;Halfstepreverse Direct=DRev GoSubBiPolar MPort=0 Pause1000 ;Wavestepforward Mode=ModeWave Direct=DFwd GoSubBiPolar MPort=0 Pause1000 ;Wavestepreverse Direct=DRev GoSubBiPolar MPort=0 Pause1000 GoToMain ;CalledsubroutineneedsMPin,MStepandMDelayset ;DirectandModealsomustbeset.Motorpatternin ;ByteArrayStepTable() ;andneedsi&jfreevariables BiPolar ;------ j=Mode ;startingpointintotable ;Ifreverse,thenstartatendoftableentry IfDirect=DRevThen j=j+SeqLen-1 EndIf ;Stepthroughtherequirednumberofsteps Fori=0toMStep-1 MPort=StepTable(j) ;outputpattern PauseMDelay ;wait j=j+Direct ;nextpatternno. ;onlyhavej<Modeifreversestepping ;checkandwrapbacktostartingpoint If(j<Mode)AND(Direct=DRev)Then j=Mode+SeqLen-1 EndIf ;Likewisej>=Mode+SeqLenifforward.Checkfor ;overrunandwrapbacktostartingpoint If(j>=(Mode+SeqLen))AND(Direct=DFwd)Then j=Mode EndIf Next Return
144
IntroductoryStepperMotors Program8-3usesthesameconstantnamesasinPrograms8-1and8-2todefinethestartingpin,thedelay (inmilliseconds)perstepandthenumberofstepstotake.InordertomorecloselymimicthefunctionalityofthefunctionSPMotor,MStepinProgram8-3definesthenumberofsteps,notthenumberof8-step cyclesasinProgram8-2. MPin MDelay MStep
Con Con Con
B0 5 1000
;startingpinformotordriver ;millisecondsperstep ;unlikeprogram8-2,MStepisnumberofsteps ;numberofstepstomake
AlthoughI’vemadeMDelayandMStepconstants,youmaywishtomakethemvariablesandcomputeorassign theirvaluesbasedonuserinputsorcalculatedparameters.Sinceweuseawordvaluecountertokeeptrackofthe numberofsteps,MStepcan’texceed65535.Ifthisisinadequate,changethecountervariableitobeatypelong. It’salsonecessarytodefineavariabletoaddresstheoutputportnibble.I’venamedthisvariableMPort. MPort
Var
PortB.Nib0
;outputportpins
Ifyouusedifferentpinconnections,don’tforgettochangebothMPinandMPort. ModeFull ModeWave ModeHalf
Con Con Con
0 8 16
;modeconstants
DFwd DRev
Con Con
1 -1
;directionconstants ;fwdandrevarearbitrary
Direct Var Mode
SByte ;direction Var SByte ;modetype
Wesetthedirectionandoperationalmodeusingtwovariables,DirectandMode.Inordertomakeourprogrammoreintelligible,wedefinethreemodeconstants,ModeFull,ModeWaveandModeHalf,representing fullstep,waveandhalf-stepoperation,respectively.We’llseethereasonforchoosingvaluesof0,8and16 fortheseconstantsabitlater.Likewise,wedefinetwodirectionalconstants,DFwdandDRevforforwardand reverse.Yourchoiceofmotorwindingconnection,aswecoveredinconnectionwithProgram8-2,determineswhetherforwardisclockwiseorcounterclockwise. StepTableByteTable12,6,3,9,12,6,3,9,8,4,2,1,8,4,2,1,8,12,4,6,2,3,1,9
Ratherthankeepthreeseparatebytetablestoholdthepatternforfullstep,waveandhalfstep,I’vecombinedthemintoone24-elementbytetable.Elements0…7arethefullsteppatterns,8…15arethewave patternsand16…23arethehalf-steppatterns.AswithProgram8-2,StepTableholdstwocompletecycles offullstepandwavepatterns,sothatfull,waveandhalf-stepallhaveeightentries.Wealsonowseewhy theconstantsModeFull,ModeWaveandModeHalfaredefinedwiththevalues0,8and16—thesenumbers arethestartingpointforindexingintoStepTablefortheirrespectivemodes. ;Initialization ;------------;setmotorporttooutput Forj=MPintoMpin+3 Outputj Next ;allwindingsoff MPort=0
Weinitializebysettingoutputstatethepinswehaveselectedtocontrolthemotorandwede-energizeallthe windings.Inthede-energizedmode,thestepperhasonlyitsresidualtorquetoholdtherotoragainstexternal torque,soyoumayinsteadwishtoinitializethemotorwithonewindingenergized. Let’snowexaminethesubroutineBipolar.InamedthissubroutineBipolarbecauseIoriginallyintended todemonstrateProgram8-3onlywithabipolarmotor,butlaterdecidedthisistoolimiting.Thesteppattern, ifyouusethecorrectdriverandmotorconnections,isidenticalforaunipolarandbipolarmotor.Hence,if properlyconnectedProgram8-3functionsidenticallywitheithermotortype. 145
Chapter8 SubroutineBiPolarassumeswehavedefinedandsetvaluesforMPin,MStep,MDelay,Direct,Mode, andthatMPortisaliasedwiththeportnibbletobeused.Inaddition,itusestwovariablesi,typeword,and j,typesbyte. BiPolar ;------ j=Mode ;startingpointintotable ;Ifreverse,thenstartatendoftableentry IfDirect=DRevThen j=j+SeqLen-1 EndIf
Toreversedirection,westepthroughStepTableinreverseorder,thatis,emittingthevaluesofStepTable inthesequenceStepTable(0),StepTable(1)…StepTable(7)isforward,whilethesequenceStepTable(7),StepTable(6)…StepTable(0)isreverse.Hence,baseduponthevalueofDirect,westart indexingintoStepTableat0,8or16forforward,or7,15or23forreverse.TheconstantSeqLenholdsthe numberofelementsinStepTable—8—foreachmode.Weentertheprogramcontrolloop,therefore,with jproperlysetatthefirstelementinthepatternwewishtosendtothemotor.
;Stepthroughtherequirednumberofsteps Fori=0toMStep-1 MPort=StepTable(j) ;outputpattern PauseMDelay ;wait j=j+Direct ;nextpatternno.
WenowemitMStepnumberofsteps,usingaloopconstructiontocontrolprogramexecution.(Sincewe startwith0,tosendMStepssteps,wemuststopatMStep-1.)Afterthepatternforeachstepisemittedwe updatejwiththestatementj=j+Direct.Directiseither+1(forward)or–1(reverse)sojincrementsordecrementsbaseduponthechosendirectionofrotation,
;onlyhavej<Modeifreversestepping ;checkandwrapbacktostartingpoint If(j<Mode)AND(Direct=DRev)Then j=Mode+SeqLen-1 EndIf
Return
Next
;Likewisej>=Mode+SeqLenifforward.Checkfor ;overrunandwrapbacktostartingpoint If(j>=(Mode+SeqLen))AND(Direct=DFwd)Then j=Mode EndIf
Wemustlimitj’svaluesothatitwrapsaroundwhenitattemptstogooutsidetherangeofvaluespermitted fortheselectedmode.WedothiswithtwoIF…Thenstatements.Ifthedirectionisforward(Direct=DFwd) wechecktoseeifjexceedsthemaximumindex,whichisMode+SeqLen.Ifthisisthecase,weresetthe indexbythestatementj=Mode. Ifthedirectionisreverse(Direct=DRev)wecheckforanunder-run—thatis,jislessthanMode.Ifthisis thecase,weresettheindexbythestatementj=Mode+SeqLen-1. ToshowhowsubroutineBiPolariscalled,wereturntothemainprogramloop.
;Fullstepforward Mode=ModeFull Direct=DFwd GoSubBiPolar MPort=0 Pause1000 ;Fullstepreverse Direct=DRev GoSubBiPolar MPort=0 Pause1000
146
IntroductoryStepperMotors Wesetthevariablesthatdefinethemode,Mode,anddirection,Direct,andthencallBiPolar.Ofcourse, ifwemadeMSteporMDelayvariablesinsteadofconstants,theyalsowouldrequiresettingtoappropriate values. TheremainderofProgram8-3demonstratestheremainingmodesanddirectionsandrequiresnofurther analysis. AfteryouhaveverifiedthatProgram8-3isfunctioningwithaunipolarmotorandanyofthecircuitsdevelopedforPrograms8-1and8-2,wemaynowturntoabipolardriver.Figure8-33showsasuitablecircuit. NotecarefullytheinputandoutputconnectionstotheSN754410.I’veshownconnectionsforeitherapure bipolarmotor,orforconnectinga6-wireunipolarmotorasabipolardevice.And,thecircuitofFigure8-33 maybeusedwiththeProgram8-1or8-2,shouldyousodesire.TheH-bridgecircuitpermitsMBasic’sSPMotorfunctiontodriveabipolarmotor,notjustaunipolarmotorastheUser’sGuidesuggests. +Motor_Voltage
2
1A
3
A
A
A
2A
6
B
B
B
C
C
C
D
D
R3
R1
NC
7
SN754410
B3
10
3A
9
B1
11
3,4 EN
From PIC
1
B0
NC
16
Vcc1
8
1,2 EN
B2
Vcc2
+5V
15 3
4A 4
14
R4
R2
D
GND 12 13
Bipolar Motor
Unipolar Motor
Figure8-33:Bipolarmotordriver.
OurcircuitisbaseduponanSN754410quadhalf-Hbridgedevice.(Bycombiningtwohalf-Hbridges,we getafullH-bridge.)Earlier,inFigure8-17,wesawaconceptualoverviewofan“H”bridge.Bysettingone controlpinhighandtheotherlow,theSN754410permitscurrentflowthroughthewindinginonedirection. Ifthetwocontrolpinsreversestate,currentflowsthroughthewindinginthereversedirection.Pins1and 9are“enable”pinsthatmustbeheldat+5Vfortheirassociatedbridgedriverstofunction.TheSN754410 hastwoVCCconnections;onefor+5Vandthesecondtobeconnectedtothemotorsupply.Don’treverse theseconnectionsorthe“magicsmoke”insidetheSN754410willescapeandyouthencanthrowwhat’sleft intothetrash! TheSN754410’ssuperiorratingsmakeitpreferabletothemorepopularL293.And,makingitevenbetter, theSN754410isfewcentscheaperthantheL293.TheSN754410H-bridgeisconstructedwithDarlington transistorsinboththehighsideandlowsideswitches.Hence,weanticipateapproximatelya1Vdropin 147
Chapter8 boththehighandlowsidemotorconnections.Incomputingthecurrentlimitingresistors,don’tforgettoincludebothvoltagedrops.Inourapplication,theincreasedvoltagedropisnotofmajorconcern,butitmight beforlargermotors.Fortunately,awidevarietyofH-bridgecircuitsareavailable,includingthosewithless voltagedropandhighercurrentratingsthantheSN754410. Figure8-33alsoshowseightSchottkyvoltageclampdiodes,basedontherecommendeddesigninthe SN754410’sdatasheet.TheSN754410containsinternalclampingdiodesandforlowpowersteppermotors, theinternaldiodesmaybeadequate.However,addingexternalclampingdiodesatthemotoritselfisanexcellentsafetyprecaution,andshouldbefollowed.Schottkydiodeshavethedualadvantageofbeingmuchfaster thanconventionalsiliconpowerdiodesofthe1N400Xfamilyandalsoprovidealowerforwardvoltagedrop. TodemonstratehowProgram8-3operatesinthebipolarmode,IusedthesameunipolarPF35-48motorthat appearsthroughoutthischapter.Inthiscase,however,weoperatewithtwowindingsinseries,sothewindingresistanceis40ohms,notthe20ohmsseenforeachindividualwinding. AtwhatvoltageandcurrentshouldweoperatethePF35-48?Sinceeachwindingintheunipolarmodeis5.4 V,weshouldoperatetheseriesconnectionat10.8V,therebyplacing5.4Vacrosseachwinding,correspondingto265mA,right?Well,maybenot.Let’sgobacktothepoweranalysisweconductedearlierinthis chapter.Intheunipolarmode,fullstepexcitation,thePF35-48isratedatabout1.4Wdissipationineachof thetwowindingsthataresimultaneouslyenergized,orabout2.8Wfortheentiremotor.Inunipolaroperation,thereisnocaseinwhichallfourwindingsaresimultaneouslyenergized.Infullstepbipolaroperation, allfourwindingsareenergized.Ifweoperatethemotorat10.8V,therefore,thetotalpowerdissipationwill be5.6W,twicetheratedvalue.Instead,wehavetoreducethecurrentthroughthewindingssothateachpair ofsimultaneouslyenergizedwindingsdissipates1.4W. WeknowthatP=I 2 R,sowecancalculatethesafemaximumcurrent,baseduponatotalmotordissipation of2.8watts. P = I 2 R; I =
P R
1.4 = 187 mA 40 Sincethetotalwindingresistanceis40ohms,thiscurrentcorrespondsto7.5V.Ifweallow1Vforbothsides oftheH-bridge,wemayoperatethemotorat9.5V.
I=
Ifwewishtoimprovethecurrentrisetimebyoperatingthemotorathighervoltageandaddingseriesresistance,weshoulduse187mAasthesafeoperatingcurrentforfullstepoperation.Thiscalculationisbasedupon fullstepoperation;ifweweretooperatethemotorinbipolarwavedrive,onlytwowindingsareenergized atanytime,sowemayusethefullunipolarcurrentratingandoperatethemotorat10.8V,plustheH-bridge drops.Forhalf-stepoperation,thesafecurrentwillbebetweenthesetwovalues,astheaveragenumberof windingsenergizedis3(4stepsat4windings;4stepsat2windings,foranaverageof3energizedwindings.) Whendrivingaunipolarmotorinabipolarcircuit,youshouldbeawarethatthewindinginductancealso increases.Thebipolarconnectedwindinginductanceisapproximatelyfourtimestheinductanceofasingle winding.Theinductancedoesn’tsimplydoublebecausethetwowindingsarecloselymagneticallycoupled andtheirmutualinductancemustbetakenintoaccount.Sincetheseriesresistanceonlydoubles,theL/R timeconstantofthebipolarconnectedwindingistwicethatoftheunipolarconnection. Ofcourse,youneednotgothroughthesecalculationsifthemotorisofbipolardesign,asitsratingswillbe baseduponbipolaroperation.
148
IntroductoryStepperMotors
Figure8-34:Bipolaroperation—fullstepmode; Ch1:off;Ch2:motorcurrent.
Figure 8-35: Bipolar operation—wave mode; Ch1:off;Ch2:motorcurrent.
Let’sseehowthecurrentflowlookswhenrunningProgram 8-3withabipolardriver.Figure8-34showsthecurrent flowthroughonewindinginfullstepoperation.Thecurrentpulsesareapproximatelyequalandshowtheexpected alternatingdirection,+/–/+/–…Figure8-35illustrateswave operation.Thewindingcurrentpatternis+/0/–/0/…,again asexpected.Finally,Figure8-36showshalf-stepoperation. Thecurrentwaveformlooksunusual,doesn’tit?But,it’s exactlywhatweshouldexpect.Let’slookatapieceofthe half-wavepatterntable.ThewindingthatisshowninFigures8-34through8-36isconnectedtotheSN754410’spin 3.Hence,itscurrentflowiscontrolledbyBits0and2ofthe Figure8-36:Bipolaroperation—half-stepmode; outputnibble,correspondingtothePIC’soutputpinsB0and Ch1:off;Ch2:motorcurrent. B2fortheparticularconnectionshowninFigure8-33.(I’ve omittedBits3and1fromthetableextract.)TheSN754410 interpretsinputcommandsas10=currentflowinonedirection;01=currentflowinoppositedirectionand 00=nocurrentflow.Basedonthis,I’veaddedacurrentflowcolumn,arbitrarilyassigningthe10direction asaplus. Mode
Half
Step
Bit2
Bit0
CurrentFlow
1
0
0
None
2
1
0
+
3
1
0
+
4
1
0
+
5
0
0
None
6
0
1
-
7
0
1
-
8
0
1
-
Thus,thecurrentpatternweseeshouldbe0/+/+/+/0/-/-/-,whichisanalternatingcurrentflow,withaperiod ofnocurrentflowbetweenthereversals.Thequiescentperiodshouldbeone-thirdthedurationoftheactive currentflowperiod.And,that’sexactlywhatFigure8-36shows.
149
Chapter8
References [8-1]
ThompsonAirpaxMechatronics,ProductSelectionandEngineeringGuide,(undated),availablefor downloadingathttp://www.thomsonindustries.com/PDFs/Catalogs_and_Brochures/Airpax_Catalog_ Idx.pdf. [8-2] ThompsonAirpaxMechatronics,StepperMotorHandbook,(undated),availablefordownloadingat http://www.allegromicro.com/techpub2/compumot/a04a08.pdf. [8-3] TexasInstruments,SN754410QuadrupleHalf-HDriverDataSheet,Doc.No.SLRS007B,(Nov.1995). [8-4] TelefonaktiebolagetLMEricsson,IndustrialCircuitsDataBookandStepperMotorControlHandbook; StepperMotorBasics,(1995)availablefordownloadathttp://library.solarbotics.net/pdflib/pdf/motorbas.pdf. [8-5] Sax,H.,ApplicationNote235:StepperMotorDriving,SGS-ThomsonMicroelectronics(July1988), availablefordownloadingathttp://library.solarbotics.net/pdflib/pdf/motorbas.pdf. [8-6] Hopkins,ThomasL.,ApplicationNote460:StepperMotorDriverConsiderationsCommonProblems andSolutions,SGS-ThomsonMicroelectronics(2003),availablefordownloadingathttp://www.st.com/ stonline/books/pdf/docs/1675.pdf. [8-7] Condit,Reston,&Jones,DouglasW.,SteppingMotorsFundamentals,AN907,MicrochipTechnology Inc.,Doc.No.DS00907A(2004),availablefordownloadingathttp://www.microchip.com/download/ appnote/pic16/00907a.pdf. [8-8] Condit,Reston,StepperMotorControlUsingthePIC16F684,AN906,MicrochipTechnology,Inc., Doc.No.DS00906A(2004),availablefordownloadingathttp://www.microchip.com/download/appnote/pic16/00906a.pdf. [8-9] Yedamale,Padmaraja,StepperMotorMicrosteppingwithPIC18C452,AN822,MicrochipTechnology, Inc.,Doc.No.DS00822A(2002),availablefordownloadingathttp://www.microchip.com/download/ appnote/pic16/00822a.pdf.
150
9
CHAPTER
RS-232SerialInterface Thecomputersciencedictionarydefines“serial”as“oforrelatingtothesequentialtransmissionofallthe bitsofabyteoveronewire.”Aswe’llsee,therearemanyserialprotocols,suchasI2C(Chapter18),SPI (Chapter21),one-wire(Chapter12)andtheinfraredremotecontrolprotocolREC-80(Chapter22).Inthis chapter,we’lllookatanolderserialprotocol,RS-232,andlearntouseMBasic’sSerIn,SerOut,HSerIn andHserOutprocedures.Alongtheway,we’lldocumentsomeundocumentedfeaturesofMBasicandwrite aninteractivemenuprogram. It’snotcorrecttorefertotheentirebundleofinteractionanddataexchangewe’llexploreinthischapteras “RS-232.”Thedetailsarewellbeyondthescopeofthisbook,buttheopensystemsinterconnection(OSI) referencemodeldefinesaseven-layermodelofnetworkandcomputercommunications.IntheOSImodel, RS-232appliestothelowest,or“physical,”layer,whereitdefinesvoltageandsignallevels,pinwiring,connectorstandardizationandflowcontrol.ButnothingintheRS-232specificationsaysthatwemusttransmit andreceive8-bitbytesoveranRS-232connection,orthatweshouldusetheASCIIcodetorepresenttext, orthatwemustoneofthewidelyrecognizedstandarddataspeeds.Wecould,forexample,usea1930’s Model15Teletypemachinetosendfive-bitBaudotcodeat45.45bits/secoveranRS-232connectionand, aslongaswefollowthepinandconnectorwiringandvoltagestandards,wewouldbeincompletecompliancewithRS-232.IfyouconnecttheModel15TeletypetoyourPC,youwill,ofcourse,receivenothing butgibberishwithoutadditionalprotocolandspeedconversion.Theseprotocolandspeedconversionsare partofhigherlayersintheOSIstack,andifyoucorrectlyimplementthesehigherlayers,youwillbeableto communicatewiththeModel15.Nonetheless,we’regoingto“gowiththeflow”andnotdistinguishthose thingsdefinedintheRS-232standardandthosethingsdefinedinotherstandardsrelatingtohigherlayers intheOSImodel,exceptwhereabsolutelynecessary.Further,we’lloftencallthiscommunicationsprotocol simply“serial.” RS,bytheway,means“recommendedstandard”andtheoriginalversion,RS-232withnolettersuffix,was adoptedbytheElectronicsIndustryAssociationin1962.Thecurrentversionofthestandardisknownas EIA/TIARS-232E.(In1988,theEIAmergedwithatelecommunicationsindustrygroup,andthemerged entityaddedtheTelecommunicationsIndustriesAssociationnametothestandard.)
HowtoConnecttoYourPC Sinceyou’reprogramminginMBasic,youalreadyhaveaPCrunningarecentversionoftheWindowsoperatingsystem.YourPChasatleastoneRS-232serialport,necessarytoconnecttheICPtothePC. We’regoingtouseasecondRS-232connection,theDB9connectormountedonthe2840Development Board,aswellastheotherdevelopmentandprototypeboardsproducedbyBasicMicro.You’llfinditfar moreconvenientifyourcomputerhasasecondRS-232porttoconnecttotheDevelopmentBoard.Ifyour PChasonlyoneserialport,youcanmovetheconnectingcablebetweentheICPandthe2840Board,or, youcanpurchaseaninexpensiveUSB-to-serialadapteranduseittoconnecttothe2840Board.You’llalso 151
Chapter9 needasecondDB9-to-DB9cable.Thiscableshouldbea“modem”cable,i.e.,onewhereeachpinonone endconnectswiththesamenumberedpinontheotherend.(ThecablesoldbyBasicMicroforcomputer-toICPconnectionsisconstructedthisway.) You’llneedtorunaprogramtocommunicatewiththePIC’ssoftware.Thisprogramisusuallycalled“terminal”software,asitallowsthePCtoemulateadumbserialterminal.Windowscomespackagedwitha terminalprogram,Hyperterminal,whichyouwillfindunderProgram|Accessories|Communications.And, forsomepurposes,theterminalutilitythat’spartofMBasic’sIDEisquiteadequate.(Iobservedproblems withitsimplementationofhardwareflowcontrol,however.)Mypersonalfavoritefordevelopmentwork isTerminal[9-2](freewarefromBray++)andIalsofindthediagnosticterminalprogramComTest[9-3](also freeware)fromB&Busefulfordebuggingserialproblems.Terminalprovidesmuchmoreflexiblecontrol overthetechnicalparametersofserialcommunicationsthaneitherHyperterminalorMBasic’sIDEterminal utility,importantconsiderationswhendevelopingandtestingserialcommunicationsprograms. We’llalsoassumeyouunderstandthebasicsofserialcommunications,thattheterminalprogrammust matchthePIC’ssettingsforspeed,numberofbits,parity,stoppulselengthandhandshaking.(Notallterminalprogramshavealltheseparametersaccessibletotheuser.)Ifnot,we’llrecapthesesettings: Parameter ComPort
SettoValue SeeComment
DataBits Parity
8 None
StopBits
1
Handshaking
None
Comment TheComPortsettingmustmatchthephysicalcommunicationsportyou haveconnectedtothePIC’sserialconnector. Ourprogramswillnotuseparity,soall8bitsaredata. Parityisarudimentaryfromoferrorchecking.Wewillnotuseit(MBasic onlysupportsparityforSerOutandSerIn). MBasic’sHserOutsends1stopbit;SerOutisconfigurableforeither1or 2stopbits.Don’tworryifthisisnotanoptiononyourterminalprogram. We’llchangethiswhenweexamineflowcontrol.SupportedforSerOut andSerIn,notHSerOutorHSerIn.
Oneadditionaloptiondeservesabitmorediscussionthancanbesqueezedintothetable—theendofline character(s). SincetheearliestdaysofmechanicalTeletypemachinesinthe1920s,separatekeys(andcodes)existedfor carriagereturnandlinefeedfunctions.Becauseittooklongerfortheheavytypebasketassemblytoreturn totheindexpositionthanfortheplatentoratchetthepaperuponeline,thenormallineendingsequencebecame
,orsometimesevenwherethesecondcarriagereturnensuredenough timeforthecarriagetofullyreturnbeforeprintingresumed.And,iftheTeletypemachinewasconnectedto apoorradiocircuit,thedoublehelpedavoidthedreadedpile-upwhereafulllineoftextturnedintoa blackblobattherighthandmarginduetoamissedcommand.(Theanglebracketsindicateacharactercommand.) Nowthatweuseelectronic,notmechanical,terminals,itisn’tnecessarytoissueseparateand commands,asthetwofunctionsmaybecombinedintoonethroughcodeintheterminalprogram.InASCII, thecarriagereturncodehasavalueof13($D)andthelinefeedcodevalueis10($A).Atraditionalmechanicalprinterend-of-linesequenceisthus<13>,<10>.We’llalmostalwaysomitthelinefeedcharacterand useonlythecarriagereturnsymbol<13>toindicatethestartofanewline.Inmanyterminalprograms,you mustselectabuttonorcheckboxcontrolsuchas“CR=LF”or“CR=CR+LF”toenablethisoption.
VoltageLevelsinRS-232andLevelConversion PICsworkintheworldofdigitallogic,with+5Vand0Vrepresentinglogiclevels1and0,respectively. TheRS-232standardpredateswidespreaduseof+5Vlogicand,foravarietyofreasons,itadoptedsignal 152
RS-232SerialInterface
Figure9-1:RS-232levelconversioninBasicMicro developmentboard.
levelsof+15Vand–15V,aformof“bipolar”signalFigure 9-2: RS-232 and logic level Ch1: logic levelfromPIC;Ch2:RS-232bipolarsignalout ing.(Bipolarsignalinghadlongbeenusedinlandline ofSP232ACN. Teletypecircuits,butwithvoltagelevelsof±100V, neededfortransmissionoverlonglocalloopsand inter-citycircuits.)Hence,it’snecessarytoconverttheRS-232levelstologiclevelscompatiblewithour PIC.BasicMicro’sdevelopmentboardsincludeaconversionchipwithtwologic-to-RS-232levelandtwo RS-232-to-logiclevelconverters,configuredasshowninFigure9-1.TheRS-232sideofthelevelconverter ishardwiredtotheTX(transmit),RX(receive),CTS(clear-to-send)andRTS(request-to-send)pinsofthe DB9connector,whilethelogicsideappearsatfourpositionsofaheader,withcorrespondinglabels. BasicMicrousedSipexSP232ACNlevelconvertersintheboardsIhave,butpin-compatibledevicesare availablefromseveralmanufacturers.Thefollowingtablesummarizestherelationshipbetweenthe±15V RS-232levelsandthe0/+5VlogicemployedbyPICs,whileFigure9-2showstheinversioninatypicalbit stream. RS-232 NominalVoltage +15V –15V
PICLogicLevels
Terminology Spacing,Unasserted/Negate Marking,Asserted/Assert
Voltage 0 +5
Terminology Logic0,LogicalLow Logic1,LogicalHigh
ThetermsAsserted/UnassertedorAssert/Negateapplytocontrolsignals,andthetermsMarkingandSpacingdescribetransmitandreceivedatasignals.Onemorebitofhistory;thetermsmarkingandspacingderive fromtheearliestdaysoftelegraphy,whereaninkingmechanismprintedhigh-speeddotsanddashesontoa movingpapertape,forlaterreadingbyahumantelegrapher.SomeofThomasEdison’searliestinventions wereforrecordingtelegraphequipment.Markingmeantthatthepapertapehadamark;spacingmeantthere wasnomark.Thesetermscarriedoverintothepunchedpapertapeeraaswellastoday’snonmechanical communications. Finally,notetheinversionbetweenRS-232andlogic;apositivevoltageontheRS-232linecorrespondsto0V inlogicanda+5VinlogiccorrespondstoanegativevoltageontheRS-232line. IfyoulookcloselyattheRS-232specification,youwillfindawiderangeofpermittedvoltages: TransmittedLevels(Maximum/Minimum) +15V Space(Logic0) +5V –5V –15V
ReceivedLevels(Maximum/Minimum) +15V Space(Logic0) +3V –3V –15V
Mark(Logic1)
153
Mark(Logic1)
Chapter9 Thetwo-voltdifferencebetweenthebottomendofthepermittedtransmitrangeandtheminimumreceive rangeisfornoisemargin. Sipex’sSP232ACNdatasheet,however,revealsthatitimplementstheRS-232specificationsomewhat diffidently.ThetransmittedRS-232levelsarebetween±9Vand±5V,withinthespecification.(Figure9-2 shows±8Vformy2840Board.)But,forreceivingRS-232signals,althoughitproperlydecodessignallevelsupto±30V,thetypicalvoltagethresholdofamarkingsignalis+1.2Vandthetypicalvoltage thresholdofaspacingsignalis+1.7V.Thesetransitionlevelsbearmorethanapassingresemblancetothe TTLandCMOSlogiclevelswestudiedinChapter4.Hence,itwouldbepossibletodrivetheRS-232input sideofaSP232ACNdirectlywithalogiclevelsignal,implyingthatwemightdispensecompletelywiththe SP232ACNleveltranslator,replacingitwithonlysomeprotectivediodesandcurrentlimitingresistorsto protectourPIC’sinputpins.And,infact,thiswill,undercertaincircumstances,work.But,it’sbadpractice tosaytheleast.SupposeyourPICcircuitiscommunicatingwithaPCthatimplementstheRS-232standards morerigorouslythandoestheSP232ACN,andthatitrequiresatleast–3Vtodecodeavalidmark.Ifyour PICoutputs0V,butthecorrectlyimplementedRS-232terminalrequiresbetween–3Vand–15Vtobe recognizedasamark,yourcommunicationswillfail.
StandardPinConnections The2840Boardimplementsfivelinesofthefull9-pinRS-232standard: Computer(DTE) Pin No. 1 2 3 4 5 6 7 8 9 Shield
SignalName CarrierDetect(DCD) ReceiveData(RX) TransmitData(TX) DataTerminalReady SignalGround DataSetReady RequesttoSend CleartoSend RingIndicator
PICDevelopmentBoard(DCE) RS-232 Name CD RD TD DTR GND DSR RTS CTS RI
Direction ← → ←→ → ←
Pin No. 1 2 3 4 5 6 7 8 9 Shield
SignalName
RS-232 Name
TransmitData(TX) ReceiveData(RX)
TD RD
SignalGround
GND
RequesttoSend CleartoSend
RTS CTS
AsynchronousTransmission,StartBits,StopBitsandBitOrder Serialtransmissioncomesintwoflavors:synchronousandasynchronous.Thesearefancywordsthat describesendingthedatabits,oneafteranotherwithoutanypauseandwithoutanythingtodistinguishone bytefromthenext(synchronous)andsendingthedatabitsframedbyaclearstart-of-byteandend-of-byte markerwiththepossibilityofpausesbetweensuccessivebytes(asynchronous). We’renotgoingtofurtherlookatsynchronousdatatransmissioninthischapter,solet’sseehowanasynchronoussignalemploysstart-of-byteandend-of-bytemarkers.(Andyes,asynchronousdatadoesn’thaveto besentinbyte-sizelengths,butthat’showit’sdoneforPC-to-PICcommunications.) Let’sassumethatnodatahasbeensentandourdatalineisinthemarkstate.Weindicatethestartofabyte bysendingastart(space)bit,followedbytheeightdatapulses(LSBfirst)andfinishwithastop(mark)bit. Insomecases,wemightsendtwostopbits.Then,wedothesameforthenextbyte,ifthereisonetobe sent.Let’sseehowwewouldsendtheletter“A”(65,or%01000001).
154
RS-232SerialInterface S P A C E
+15V
M A R K
-3V
(0)
1
0
DataBits(LSBFirst) 0 0 0 0
1
0
(1)
StartBit→ +3V
StopBit -15V
I’veindicatedthestartandstopbitvaluesinparenthesis,sincewedon’tusuallyconsiderthesetohavea usefuldatavalue.Thedecodingalgorithm(eitherembeddedwithinSerIn,orwithinthePIC’shardwarefor HSerIn)canbethoughtofas: WaitforaStartBit(0) Characterizethenext8bitsare0’sor1’sandstoretheminLSBorderina storagebyte Stopcharacterizingafterthe8thbitandverifythatthenextbitreceivedisa stopbit.Ifitis,thenregardthebyteasvalid;otherwiseitisinvalidandset abaddataflag.
OK,yousay,thatmakessense.ButwhathappensifIstartreceivingdatainthemiddleofatransmission? Howdoesmyalgorithmdecideifa0isastartbitorsimplyoneoftheeightdatabits?Itturnsoutthatfor normaltextsteams,thissimplealgorithmwillcorrectlylockontothestartbitafternotmorethanahalf-dozenorsocharacters.Therearesomepathologicalcases,wherebycertaincharactersrepeatedwithoutapause cancauseafalselock,buttheserarelyhappeninpracticaltextordatatransmission.And,moreimportantly, inmostcircumstancestherewillbeapausebetweencharactersorwordsfromtimetotimeandanidle ensuressynchronization. Althoughwe’vementioned“parity,”we’venotdefinedit.Forourpurpose,evenparityinvolvestakingthe eighthdatabit(theMSBbitofthebytebeingsent)andusingittoholdnotdata,butratherthebinarysum oftheprevioussevendatabits.Sinceweonlyhaveonebittoholdthesum,wecan’tcarry,so%1+%1=%0, not%10.Anotherwayoflookingatitistheparitybitis%0whenthe7databitshaveanevennumberof%1s butitis%1whenthereareanoddnumberof%1’sinthe7databits.Thus,theeighttransmittedbitsalways willhaveanevennumberof%1s.(Oddparityisjustthereverseofthis.)Ifparityisenabled,thereceiving devicecandetectasinglebiterrorandflagthereceivedbyteascorrupt.(Notethat2biterrorswillnotbe detected,but3biterrorswill,andsoforth.Fortunately,singlebiterrorsarefarmorecommonthanmultiple biterrors.)Usingparitymeansweonlycansendseveninformationbits.Ifwelimitourcommunicationsto standardalphanumerictext,thisisnotaproblem,asallnumbers,lettersandpunctuationmarksintheASCII Englishalphabetrequireonly7bits. Onefinalpointandthenwe’lllookatMBasic’ssupportforserialcommunications.Themaximumpermitted errorbetweenthesendingandreceivingdatarates(alsocalledclockskew)isonlyabout5.5%.IfthePIC’s clockiseithercrystalorceramicresonatorcontrolled,thisobjectiveiseasytomeet.However,ifthePIC usesitsinternalRCclock,achievingtheneededtoleranceoverawidetemperaturerangeisproblematic,at best.And,remember,it’snotgoodengineeringpracticetoconsumetheentirepermittederrorrateatoneend ofthelink,therebyforcingtheotherendtooperateperfectlyorelseexperiencedataerrors. 155
Chapter9
MBasic’sProceduresforSerialCommunications MBasicgivesustwoalternativemeansofsendingandreceivingserialcommunications;apurelysoftwareimplementedmethodandahardwaremethod.Bothhavetheirplace,andafterdescribingeach,we’llrecap theirstrongandweakpoints.SinceMBasic’sUser’sGuideprovidesalengthydescriptionofthenutsand boltsoftheserialcommunicationscommands,we’llconcentratemoreonrelatedundocumentedfeatures.
Software-Based MBasic’sproceduresSerInandSerOutaresoftware-basedserialinputandoutputproceduresandmaybe usedwithanyPICsupportedbyMBasic. ThesyntaxforSerInis: SerInRpin\{Fpin},Baudmode,{Plabel},{Timeout,Tlabel},[InputData]
Rpin—isaconstantorvariablethatdefinesthepinthroughwhichdataisreceived. Fpin—isanoptionalpinthatmaybeusedforflowcontrol.FPinisanoutputpinthatisatlogical0when SerInisreadytoacceptdataandatlogical1whenitisunabletoacceptdata.(We’lllookatflowcontrolinconjunctionwithPrograms9-1Aand9-1B). Baudmode—isaconstantorvariable(16-bit)thatdefinesthebitspeed,outputpinstatus,thebitsensepolarity(normalorinverted)thenumberofbits,parityandthenumberofstopbits.SinceweusetheRS-232 levelconverterchip,wemustuseonlyinvertedmodes.And,tokeepthingssimple,wewillonlyusethe 8-bit/no-parityoption. MBasicprovidespredefinedbaudmodeconstantsthatyouwillusetospecifytheseparameters.Fromversion 5.3.0.0.onwards,MBasic’sSerInandSerOutfunctionshaveanewparameterstructureandrevisedbaudmodeconstants,constructedassummarizedbelow. Sense Ltr N
Fcn Normal
I
Inverted
Mode Ltr Fcn Blank Normal O
Open (Bus mode)
DataBits Ltr Fcn 7 7data bits 8 8data bits
Parity Ltr N
Fcn None
E
Even
O
Odd
StopBits Ltr Fcn 1 1stop bit 2 2stop bits
Speed (withleading) _300 _600 _1200 _2400 _4800 _7200 _9600 _12000 _14400 _16800
_19200 _21600 _24000 _26400 _28800 _31200 _33600 _36000 _38400 _57600
Forexample,thebaudmodeconstantforinverted,8databits,noparity,onestopbit,standardmodeis I8N1_9600. Thebaudmodeconstantsweuseinthischapterareinverted,normalmode,eightdatabits,noparity,one stopbit.Hence,theywillbeoftheformI8N1_nnnnwherennnnisoneofthestandarddataspeeds. We’vecoveredalltheseelementsearlierinthischapter,saveforbusmode.Insomecircumstances,multiple serialsendingpins(mostlikelyindifferentPICs)maybebussed—thatis,theyshareacommonconnection. Inthiscase,exceptwhenactuallytransmittingdata,wewishthetransmittingpinstobesettotheir“disconnect”orhighimpedancemode.Otherwise,wecouldeasilyhaveonetransmittingpinfightingasecond transmittingpin.Whilewecouldaccomplishtheswitchfromhighimpedancemodetotransmitmodewith someextracode,wecanalsoletSerOuthandlethisforusviaanappropriatebaudmodeconstant.Toadd busmodeoperationtoI8N1_9600,wesimplyaddtheletter“O”thuschangingittoIO8N1_9600.
156
RS-232SerialInterface Plabel—isanoptionalprogramlabeltowhichexecutionwillbetransferredshouldaparityerroroccur. Timeout&Tlabel—definesaperiod(32-bitvalue,inmicroseconds)inwhichtowaitforaninputandifno inputisreceivedwithinthistime,programexecutiontransferstoprogramlabelTLabel.IfTimeout andTlabelarenotspecified,SerInwillwaitindefinitelyforaninput.IfTimeoutissettozero,andif thereisnodatainthebuffer,thetimeoutwillimmediatelyhappen. InputData—isalistofvariablesandmodifiers.ThemodifiersinstructSerInhowtheincomingdataisformatted.Thedataisstoredintheassociatedvariable(s).(We’lllookatthisaspectofreadinginputdatain moredetailinseveralprogramsinthischapter.) ThesyntaxforSerOut(twoalternativesyntaxforms)is: SerOutTpin,Baudmode,{Pace},[OutputData] SerOutTpin\{Fpin},Baudmode,{Timeout,Tlabel},[OutputData]
Tpin—isaconstantorvariablethatdefinesthepinthroughwhichdataistransmitted. Fpin—isanoptionalpinthatmaybeusedforflowcontrol.FPinisaninputpinthatcontrolsSerOut’sdata transmission;whenFPinisatlogic1,SerOutisdisabledfromsendingdata;whenFPinisatlogic0, datatransmissionisenabled.(We’lllookatflowcontrolinconjunctionwithPrograms9-1Aand9-1B). Baudmode—SameasforSerIn. Pace—Anoptional32-bitvariableorconstantthatdefineshowmanymicrosecondsshouldbepausedbetweensendingsequentialbytes. Timeout&Tlabel—definesaperiod(32-bitvalue,inmicroseconds)inwhichtowaitforahandshakefrom thereceivingprogram,ifflowcontrolisactivated.Ifnoinputisreceivedwithinthistime,program executiontransferstoprogramlabelTLabel. OutputData—isalistofvariablesandmodifiers.ThemodifiersinstructSerOuthowtheoutgoingdata containedinthevariablesistobeformatted.(We’lllookatthisaspectofsendingdatainmoredetailin severalprogramsinthischapter.) Athirdprocedure,SerDetect,isassociatedwithsoftwareserialcommunications.Itautomaticallydetects theincomingbaudrate.WewillnotfurtherdiscussSerDetect.
Hardware(USART)-Based MBasic’sproceduresHSerInandHSerOutarehardware-basedserialinputandoutputproceduresand maybeusedonlywithPICsconstructedwithauniversalsynchronous/asynchronousreceiver/transmitter(USART).Fortunately,mostnewPICshaveUSARThardware,andthussupportHSerIn/HserOut. ThePICsweuseinthisbook,the16F876/876Aandthe16F877/877A,areallequippedwithaUSART. TheUSARTishard-wiredtocertainpins,andthatpinassignmentcannotbechanged.Forexample,inthe 16F876/877PICs,theUSARTtransmitoutputisonC6andthereceiveinputisonC7.OtherPICsmayhave differentUSARTpinassignments. BeforeusingeitherHSerOutorHSerIn,twoinitializationstepsmustbetaken: 1. ThecompilerinstructionEnableHSerialmustappear;and 2. ThefunctionSetHSerialmustbeexecuted.ThesyntaxforSetHSerialis:
SetHSerialmode
ModeisapredefinedconstantaslistedintheUser’sGuide,oftheformH1200(1200bits/sec),H2400(2400 bits/sec),etc.throughH1250000(1250000bits/sec)wherethenumericportionisthebitrate.SetHSerialsetsbothtransmitandreceivebitratesandtherearenooptionsforinversionorparity.Unlessthereis areasontoalterthebitrateduringprogramexecution,SetHSerialneedbeexecutedonlyonce,usuallyas
partofaninitializationsequence.
157
Chapter9 YoushouldbeawareoftheinteractionbetweenClearandSetHSerial.Thefollowingconstructionfails: EnableHSerial SetHSerialH38400 Clear HSerOut[“P28-50”,13,13]
Thedesiredstringisnotemittedovertheserialport.Rather,ClearmustprecedeSetHSerial: EnableHSerial Clear SetHSerialH38400 HSerOut[“P28-50”,13,13]
TheClearcommanderasesthePIC’sRAM,includingcertainbufferinformationneededbyHSerOutand HSerIn.Hence,ifyouusetheClearfunction,itmustprecedeSetHSerial. ThesyntaxforHSerInissimplerthanSerIn,asithasnoflowcontroloptions:
HSerIn{Tlabel,Timeout},[InputData]
Timeout&Tlabel—definesaperiod(32-bitvalue,inmicroseconds)inwhichtowaitforaninputandifno inputisreceivedwithinthistime,programexecutiontransferstoprogramlabelTlabel.IfTimeout andTlabelarenotspecified,HSerInwillwaitindefinitelyforaninput. InputData—isalistofvariablesandmodifiers.ThemodifiersinstructHSerInhowtheincomingdatais formatted.Thedataisstoredintheassociatedvariable(s).(We’lllookatthisaspectofreadinginput datainmoredetailinseveralprogramsinthischapter.) ThesyntaxforHSerOutsimple;noflowcontrol,notimeoutoptions:
HSerOut[OutputData]
OutputData—isalistofvariablesandmodifiers.ThemodifiersinstructHSerOuthowtheoutgoingdata containedinthevariablesistobeformatted.(We’lllookatthisaspectofsendingdatainmoredetailin severalprogramsinthischapter.) HSerStatisanundocumentedcommand.Itssyntaxis: HSerStatcmd{,label} Cmd 0 1 2 3 4 5 6
Function ClearInputbuffer(labelnotused) ClearOutputbuffer(labelnotused) Clearbothbuffers(labelnotused) IfDataavailableininputbufferGoTolabel IfnoDataavailableininputbufferGoTolabel IfDataiswaitingtobesentGoTolabel IfnoDataiswaitingtobesentGoTolabel
Programs9-2A,9-2Band9-3,willshowusthatHSerStatisaverypowerfuladditiontoMBasic’ssuite ofserialtoolsandallowsustowriteprogramsthatexecuteothercodeandperiodicallychecktoseeifany serialdatahasbeenreceived.Thisgivesusaquasi-multitaskingmode,wherethePIC’sserialdatainput functionsrunseeminglyindependentlyoftherestofthecode. Nowthatwe’vetakeaquicklookatMBasic’ssoftwareandhardwaresupportofserialoutput,let’ssummarizethegoodandbadpointsofthesetwoapproaches.
158
RS-232SerialInterface GoodThings
SoftwareSerial(SerIn/SerOut)
NotSoGoodThings
•Assignabletoanypin •CanbeusedwithanyPIC •Canimplementmultipleserialin/out
•Maximumspeedis57,600bits/sec •Noinputoroutputbuffer •Can’texecuteothercodewhile
•Maximumspeedis1250000bits/sec •Hasabuffersodatacanbereceived
•NotallPICshavehardwareserial
streams(butnotactivesimultaneously) •Parityoption •Inversionoption •Busoption •Implementsmorespeedsthan hardwareserial •DoesnotconsumeRAMforabuffer
whiletheprogramisperformingother functions HardwareSerial(HSerIn/HserOut)
waitingforinput
support •Hardwareserialin/outishardconnectedtospecificpins •OnlyoneHSerIn/HserOutstream perPIC •Noparityoption •Noinversionoption(alwaysinverted) •Nowaytoalterthebuffersize;cuts intoRAMmemoryotherwiseavailable totheprogram. •Noflowcontroloptions •Nopacingoption
Althoughthelistof“notsogood”thingsismuchlongerforhardware-basedserialcommunications,infact IpreferittoMBasic’ssoftware-basedprocedures.Aswe’llseelaterinthischapter,theHSerStatfunction andHSerIn’sautomaticreceivebuffergivesusenormousflexibilityinprogramstructurecomparedwiththe software-basedfunctionsSerInandSerOut.
Programs We’llstudyserialcommunicationswithaseriesofsmall,single-purposetestprograms.Then,we’llassembleauser-interactiveserialmenuprogram. Program 9-1A 9-1B 9-1C 9-1D 9-1E 9-1F 9-2A 9-2B 9-3
Subject SimpleSerInandSerOut;RTSflowcontrol CTSflowcontrolwhenreceivingSTRformatarray ReadingstringinputusingSerIn;$0stringtermination UsingtheparameterWaitStrwithSerIn FormattingnumericalandstringoutputswithSerOut ReadinganumericalinputvaluewithSerIn ReadinganinputstringwithhardwareserialfunctionsandHSerStat Convertingastringtonumericvalueusinghardwareserialfunctions InteractivemenuprogramusingHSerStat,HSerInandHserOut
Figure9-3showsthewiringdiagramwe’lluseforalltheprogramsinthischapter. Figure9-4showshowthePCistobeconnectedtothe2840DevelopmentBoard.Asmentionedearlierin thischapter,theDB9-to-DB9cableisa“modem”orstraight-throughcable.Notethatthe2840Boardand thePChavecomplementaryconnections;thetransmitpinofthePCconnectstoareceivepinonthe2840 Boardandviceversa.UsingRS-232terminology,thePC’sconnectionsareDTE(dataterminalequipment) whilethe2840Board’sconnectionsareDCE(datacommunicationsequipment).Regardlessoftheterminology,theimportantthingisthattransmitpinsononeendconnecttoreceivepinsontheother,andviceversa. Afterall,yourcommunicationslinkisn’tgoingtogetveryfarwithtransmitpinstiedonlytoothertransmit pinsandreceivepinstiedonlytootherreceivepins. 159
Chapter9
Figure9-3: Serialtestconfiguration.
Figure9-4:ConnectingthePCtothedevelopmentboard.
Program9-1A We’vebrieflymentionedflowcontrol;let’sseehowitworks,ordoesn’twork,inpractice.Flowcontrolis necessarybecausethesendingandreceivingdevicesmayhavedifferentstorageandprocessingcapabilities.Forexample,supposethesendingdeviceisaPICandthatithasabatchof10characterstosendusing SerOut,andthatthelinkisoperatingat38400bits/sec.Atthisspeed,10characterscanbesentinabout2.6 ms,oronecharacterevery260µs.Let’ssaythereceivingdeviceisalsoaPICusingSerIntoreceivethe dataandthatafterreceivingabyte,ourprogramexaminesit,executesaprogrambranchbasedonthebyte valueandthenexecutessomeadditionalcodeforeachcharacter.We’llalsosaythattheprograminstructions consume2msforeachreceivedcharacter.And,sincewe’reusingSerIn,thereisnogeneralautomaticbufferinwhichincomingcharactersarestored. Theproblemisobvious;charactersarearrivingatarateofoneevery260µsbutittakes2mstodealwith thatcharacterandbereadyforthenext.And,sinceSerInhasnobufferstore,thecharactersthatarrive whiletheprogramisprocessingonecharacterarelost.Whatweneed,therefore,isawayforthereceivingdevicetocommunicatetothesendingdevice“I’vereceivedasmanycharactersasIcanhandle—don’t sendmoreuntilIauthorizeit.”ThistypeofflowcontrolissupportedbyMBasicthrough“hardwarehand-
160
RS-232SerialInterface shaking,”thatis,dedicatedconnectionsbetweenthesendingandreceivingdeviceareassertedornegated tocontroltheflowofinformation.(Manyotherapproachestoflowcontrolexist;oneofthemostcommon alternativesis“X-on/X-off,”wherethereceivingandtransmittingdevicessenddefinedcharacterstoeach otherovertheTXandRXlines.Thischapteronlylooksathardwarehandshaking.) MBasicimplementshardwareflowcontrolwithbothSerInandSerOut: Function
FlowControlPin onRS-232
SerOut
RTS
Inputto SerOut
CTS
Outputfrom SerIn
SerIn
Direction
RS-232 Status
PICLogic Level
Asserted
1
Negated Asserted Negated
0 1 0
Function SerOutholdscharactersandstops sending. SerOutSendingisenabled. SerInnotreadytoacceptdata. SerInreadytoacceptdata.
RTSandCTSareacronymsfor“requesttosend”and“cleartosend.” Now,let’sseehowflowcontrolworksinpractice. ;Program09-1A ;SoftwareSerialI/O ;Constants ;------------TPin RPin CTSPin RTSPin
Con Con Con Con
C6 C7 C5 C4
;transmitpin ;RXPin ;CTSPin ;RTSPin
TXBaudMode Con I8N1_38400 ;inverted/normalpin/noparity/1stop/38400bit/sec RXBaudMode Con I8N1_38400 ;sameforreceive ;Variables ;-------------i Var InByte Var Main
Byte Byte
;loopcounter ;Receivedcharacter
Fori=0to9 SerOutTPin,TXBaudMode,[“i:“,DECi,13] Next Pause100 Fori=10to19 SerOutTPin\RTSPin,TXBaudMode,[“i:“,DECi,13] Next SerOutTPin\RTSPin,TXBaudMode,[“ReadytoReceive:“,13] i=0
RXData SerInRPin\CTSPin,RXBaudMode,[InByte] SerOutTPin\RTSPin,TXBaudMode,| [“InByteValue:“,DECInByte,”Char:“,InByte,13] i=i+1 Ifi<100Then GoToRXData EndIf End
Let’sseehowProgram9-1Aworks.
161
Chapter9 TPin RPin CTSPin RTSPin
Con Con Con Con
C6 C7 C5 C4
;transmitpin ;RXPin ;CTSPin ;RTSPin
We’vedefinedthetransmitandreceivepinsasC6andC7respectively,toavoidrewiringthe2840Boardin laterprogramsusingtheHSerInandHSerOutfunctionsemployingtheUSARTthatishardwiredtoC6/C7. TXBaudMode RXBaudMode
Con Con
I8N1_38400 I8N1_38400
Wewishtosetthespeedto38400bits/secandoperatewitheightdatabits,onestopbit,noparity.And,as welearned,theoutputmustbeinvertedwhereweusealevelconvertertotransformlogiclevelstoRS-232 levels.Hence,ourmodeconstantisI8N1_38400forbothtransmitandreceive.
Fori=0to9 SerOutTPin,TXBaudMode,[“i:“,DECi,13] Next
First,wesimplysendthedigits0…9totheserialport,withnoflowcontrolatall.
Pause100 Fori=10to19 SerOutTPin\RTSPin,TXBaudMode,[“i:“,DECi,13] Next SerOutTPin\RTSPin,TXBaudMode,[“ReadytoReceive:“,13] i=0
Aftera100mspause,wesendthedigits10…19,andthemessage“Readytoreceive”butwithflowcontrolenabled. I’llassumeyouareusingTerminalv1.9bsoftwareandthatit’sconfiguredtothecommunicationsportconnectedtotheDB9connectoronthe2840Board.SetTerminalto38400bits/sec,8databits,noparityand handshaking(flowcontrol)tonone.TheRTSbuttoninthetransmitwindowshouldbesettoclearandthe RTSindicatorshouldnotbeilluminated. RunProgram9-1AandTerminal’sreceivescreenshoulddisplaythefollowing: i:0 i:1 i:2 i:3 i:4 i:5 i:6 i:7 i:8 i:9
NowclickontheRTSSetbutton.Twothingsshouldhappen.First,theRTSindicatorwillilluminategreen andsecond,theremainderoftheoutputshouldbeseeninthereceivescreen: i:10 i:11 i:12 i:13 i:14 i:15 i:16 i:17 i:18 i:19 ReadytoReceive:
162
RS-232SerialInterface Ifyourdisplaydoesnotmatch,checkthevoltagesatC4andseeifittogglesbetween0and+5Vasyouset andcleartheRTSbuttoninTerminal.DisconnectC4fromtheRTSsocketandconnectittoVDDandrerun Program9-1A.Then,connectittoVSSandrerunProgram9-1A.Thiswillillustratethedifferencebetween assertingandnegatingtheRTSline. ThereasonthatwemanuallysetorcleartheRTSline,insteadofshowingitviaasequenceofautomatic startsandstopsinthedisplayeddataresultsfromthefactthatPCsimplementlargereceivebuffersandare somuchfasterthanaPICthatit’salmostimpossibleforourPICtooutputdatasofastthatamodernPC won’tbeabletokeepupwithit.Hence,wesimulatetransmitflowcontrolmanually.
i=0
RXData SerInRPin\CTSPin,RXBaudMode,[InByte] SerOutTPin\RTSPin,TXBaudMode,| [“InByteValue:“,DECInByte,”Char:“,InByte,13] i=i+1 Ifi<100Then GoToRXData EndIf
Next,wetesttheCTSandreceiveddata.ThispartofProgram9-1AreceivesacharacterwiththeSerInfunctionandthenechoesthecharacterbackwithaSerOutfunction.SerInenablesCTS.After100 receivedcharacters,executionstops. SincewehaveenabledCTS,turnselectRTS/CTShandshakinginTerminal.And,enableRTSinthetransmit windowbyclickingonthegreenRTSiconbutton,whichwillilluminate.Nowtrytypingorautomatically repeatingaletterbyholdingitdown.Ifyousenda0,youshouldseethefollowingechoedback: InByteValue:48Char:0
Now,prefillthesendcontrolofTerminalwith0123456789andpressthe“←SEND”button.Weshouldsee tenresponses,0through9,right?Eachcharacterissent,andthenthenextishelduntilitisechoedbackand SerInisreadyforthenextcharacter.Infact,weseesomethingquitedifferent: InByteValue:48Char:0 InByteValue:50Char:2 InByteValue:52Char:4 InByteValue:54Char:6 InByteValue:56Char:8
Howcanthisbe?Figure9-5showstheincomingdataandCTSlineformanualsending.Asexpected,after eachcharacter,theCTSlinegoeshighforafewmillisecondswhilethereceivedcharacterisechoedback.It thengoeslow,indicatingSerInisreadyforthenextcharacter.Thisisexactlyasitshouldbe.Whythenare wemissingeverysecondbytesentautomatically?Themysteryissolvedwhenwemorecloselyexaminethe CTSlineandtheautomaticallysentdata,asseeninFigure9-6.AlthoughtheCTSlinereactsproperly,itreactstooslowly;bythetimetheCTSlineisasserted,Terminalhasalreadystartedtosendthenextcharacter. It’stoolatetostopitfrombeingsent.Hence,Terminaloutputsdatainspurtsoftwocharactersatatime.I triedslowingthedataratedownto600bits/secandfoundthatCTSisnotassertedquicklyenoughtoprevent Terminalfromsendingasecondcharacter. ThepointtobemadefromProgram9-1Aisthatyoumusttestflowcontrolwiththeterminalprogramand dataratesyouexpect;don’tassumethatjustbecauseSerInandSerOutsupportflowcontrol,itworksthe wayyouthinkitshould. Bytheway,theterminalutilitybuiltintoMBasic’sIDEkeepsRTSasserted,regardlessofwhethertheflow controloptionissetat“noflowcontrol”or“flowcontrol.”SinceRTSisalwaysasserted,SerOutwillsend nodata. 163
Chapter9
Figure9-6:ReceiveddataandCTSline;Ch1:RX dataoutofSP232;Ch2:CTSintoSP232.
Figure9-5:ReceiveddataandCTSline;Ch1:RX dataoutofSP232;Ch2:CTSintoSP232.
Program9-1B Program9-1Aaccepteddataonebyteatatime.WhathappenswhenweuseSerIntoreadastringofmultiplecharacters?Doesflowcontrolworkbetterundertheseconditions? ;Program09-1B ;SoftwareSerialI/O ;Constants ;------------TPin RPin CTSPin RTSPin
Con Con Con Con
C6 C7 C5 C4
;transmitpin ;RXPin ;CTSPin ;RTSPin
TXBaudMode Con I8N1_38400 ;inverted/normalpin/noparity/1stop/38400bit/sec RXBaudMode Con I8N1_38400 ;sameforreceive ;Variables ;-------------i Var InByte Var InStr Var
Byte ;loopcounter Byte ;Receivedcharacter Byte(11);Receivedstring
Main
SerOutTPin,TXBaudMode,[“ReadytoReceive:“,13]
RXData End
SerInRPin\CTSPin,RXBaudMode,[StrInStr\10] SerOutTPin,TXBaudMode,[“InStr:“,StrInStr\10,13] i=i+1 Ifi<100Then GoToRXData EndIf
i=0
We’vekepttheskeletonofProgram9-1A,butmodifiedtheSerInstatementtoreadaninputstringof10 characters.
SerInRPin\CTSPin,RXBaudMode,[StrInStr\10]
Afterreadingthestring,weechoitbackwithaSerOutprocedure.
SerOutTPin,TXBaudMode,[“InStr:“,StrInStr\10,13]
164
RS-232SerialInterface TheideabehindProgram9-1BisthatsincewefoundproblemsbeingabletoquicklyenoughassertCTS whenreadingonecharacteratatime,supposewereadtencharactersatatime.WedothisbyusingtheI/O modifier[StrInStr\10].ThisinstructsSerIntoreadaninputstreamof10charactersinlength,andto storethereceivedcharactersinthearrayInStr. Thisshouldsolveourimmediateproblemofbeingabletoreadthesequence“0123456789”sentwithouta breakbetweencharacters,right?KeepingthesameTerminalconfigurationweusedforProgram9-1A,let’s runProgram9-1B.LoadTerminal’ssendbufferwith0123456789andhitthe“←SEND”button.Here’sthe result: ReadytoReceive: InStr:01™&S“éÂÊÿ
Notwhatweexpectedisit?ItlooksliketheinternalsofSerIncan’tkeepupwiththereceiveddata.Ifthis theoryiscorrect,weshouldbeabletoseeadifferenceasthedatarateslows.Let’stryitandseewhathappens. Speed(bits/sec) 38400 19200
ModeConstant I8N1_38400 I8N1_19200
Result InStr:01™&S“éÂÊÿ InStr:0123456789
Sureenough,ifwecutthespeedinhalf,thesentstringisreceivedcorrectly. Thefact,therefore,thatSerInsupportsdataratesupto57600bits/secdoesn’tmeanthatwecansenda stringofcharactersat57600bits/secandexpectthemtobecorrectlyreceived.WealsoseethatSerIn’s flowcontroldidnotcorrecttheproblem.ThisagaincautionsuswhenusingSerInandconsecutivecharacterssentwithoutpause.Ifyousendthe10characters0123456789bytypingasfastasyoucan,you’llnot seeaproblem,asthereismorethanampletimebetweenkeystrokesforSerIntoreceiveeachcharacterand storeitinInStr. Program9-1C Let’slookatamorepracticalstringinputroutine. ;Program09-1C ;SoftwareSerialI/O ;Constants ;------------TPin RPin CTSPin RTSPin
Con Con Con Con
C6 C7 C5 C4
;transmitpin ;RXPin ;CTSPin ;RTSPin
TXBaudMode Con I8N1_38400 ;inverted/normalpin/noparity/1stop/38400bit/sec RXBaudMode Con I8N1_38400 ;sameforreceive ;Variables ;-------------i Var j Var InStr Var Main
Byte ;loopcounter Byte Byte(11);Receivedstring
SerOutTPin,TXBaudMode,[“ReadytoReceive:“,13] i=0
RXData ;waituntil10charsarereceived,orthecarriagereturn Forj=0to10
165
Chapter9 End
InStr(j)=$0 Next;j SerInRPin\CTSPin,RXBaudMode,[StrInStr\10\13] SerOutTPin,TXBaudMode,[“InStr:“,StrInStr,13] SerOutTPin,TXBaudMode,[“InStr:“,StrInStr\10\0,13] j=0 WhileInStr(j)>$0 j=j+1 WEND SerOutTPin,TXBaudMode,[“Length:“,Decj,| “InStr:“,StrInStr\j,13] i=i+1 Ifi<100Then GoToRXData EndIf
Ourgoalistoallowtheusertoenterupto10characters,andtoterminatetheinputwiththeenterkeyif fewercharactersaretobeentered.We’llthenechothereceivedcharactersbacktothescreen.
;waituntil10charsarereceived,orthecarriagereturn Forj=0to10 InStr(j)=$0 Next;j
MBasic’sUser’sGuidestatesthatifweoutputastringwiththeStrmodifier,outputwillstopwhenthefirst $0byteisfound.We’lltestthatstatementinProgram9-1Candseeifit’scorrect. Therefore,firstwe’llpreloadInStrwith$0values.SinceInStrhasalengthof11andsincewewillonly allow10characters,weshouldalwayshavea$0asthelastbyte,evenifweinputthefull10characters.
SerInRPin\CTSPin,RXBaudMode,[StrInStr\10\13] SerOutTPin,TXBaudMode,[“InStr:“,StrInStr,13]
First,wereadtheinputintothearrayInStrandthen,followingthesuggestionintheUser’sGuide,output thearrayInStrasastring,withoutanylengthorexplicitterminationinformation.
SerOutTPin,TXBaudMode,[“InStr:“,StrInStr\10\0,13]
Next,weoutputInStrbutthistimeexplicitlydefiningtheend-of-linecharacter.TheStrmodifierparametersare:
StrVariable\Length\EOL
Where: Variable—isanarrayofbyteholdingthestringinformation,onecharacterperarrayelement. Length—isanoptionalparameterthatdefinesthemaximumnumberofcharacterstobeoutputted. EOL—isanoptionalparameterthatdefinesthe“end-of-line”character.Thestringendswheneither(a) Lengthcharactershavebeenoutputted,or(b)theEOLcharacterisfound,whicheveroccursfirst.
j=0 WhileInStr(j)>$0 j=j+1 WEND SerOutTPin,TXBaudMode,[“Length:“,Decj,| “InStr:“,StrInStr\j,13]
Finally,welookatanotherwayofdefiningtheoutputlength;wecountthecharactersuptothepointwhere wefindtheend-of-lineterminator,$0,storingthelengthinthevariablej.Wethenstopcountingandoutput thestring,usingjtodefinethenumberofcharacterstobeoutputted.
166
RS-232SerialInterface Let’srunProgram9-1C.Inresponsetothe“ReadytoReceive”prompt,enter123<Enter>,i.e.,123followedbytheenterkey. WeseethefollowinginthereceivewindowofTerminal: Received: InStr: 123<00><00><00><00><00><00><00><00>¶} @mƒ& xˆôÀ„S<00><00><00><00>0ƒ33 …@Šl •;•o° <00> ¾ S • <00><00>lX<00><00> <00><00> “ A<00> žO<00><00><00><00>O<00><00><00><00>O <00><00><00><00>X <00><00><00><00><00><00><00>@ <00> <00><00><00><00><00><00> <00><00><00> <00><00><00><00><00> <00><00><00><00><00><00><00><00><00> <00><00<00><00> <00><00> <00><00><00><00><00><00>@<00> F<00> <00><00><00><00><00><00><00><00<00> <00><00>”<00>@<00>„<00> <00><00><00><00><00><00><00><00><00><00><00><00><00>@<00><00><00><00> <00> <00><00><00><00><00> <00><00><00>@<00>’’o o o o o u o x <00> <00> <00><00><00>H <00><00><00><00> <00><00> InStr:123 Length:3InStr:123
TheresultshowsthattheStrmodifierwithoutanexplicitend-of-linedefinitiondoesnotautomaticallyterminateoutputuponthefirst$0byteandtheUser’sGuideisinerrorinthisregard.Rather,weget255bytes ofoutput,regardlessofthenumberof$0bytes. Thelasttwolinesshowthatwemayproperlylimittheoutputbyaddingeitheranexplicitend-of-linedefinitiontotheStrmodifier;orbydeterminingthelengthofvalidcharactersandaddingthelengthtotheStr modifier. Program9-1D We’lllookataspecializedinputmodifiernext,WaitStr. ;Program09-1D ;SoftwareSerialI/O ;Constants ;------------TPin RPin CTSPin RTSPin
Con Con Con Con
C6 C7 C5 C4
;transmitpin ;RXPin ;CTSPin ;RTSPin
167
Chapter9 TXBaudMode bit/sec RXBaudMode
Con
I8N1_38400
;inverted/normalpin/noparity/1stop/38400
Con
I8N1_38400
;sameforreceive
;Variables ;-------------i Var j Var InStr Var
Byte ;loopcounter Byte Byte(11);Receivedstring
Main
SerOutTPin,TXBaudMode,[“ReadytoReceive:“,13]
RXData
Forj=0to2 InStr(j)=“A”+j Next;j Forj=3to10 InStr(j)=$0 Next;j
SerOutTPin,TXBaudMode,[“StrReceived-Value:“,| StrInStr\10\0,13]
End
i=0
SerInRPin\CTSPin,RXBaudMode,[WaitStrInStr\3\13]
i=i+1 Ifi<100Then GoToRXData EndIf
TheWaitStrmodifierinstructsthereceivingproceduretowaituntilthedefinedstringhasbeenreceived.
Forj=0to2 InStr(j)=“A”+j Next;j
First,wemustdefinethestringwearetoawait.We’llusethestring“ABC”andweputtheselettersintothe firstthreeelementsofInStrwiththeabovestatements.Since“B”immediatelyfollows“A”intheASCII collatingsequence,wejustadd1to“A”toget“B,”andadd2to“A”toget“C.”
Forj=3to10 InStr(j)=$0 Next;j
WethenfilltheremainderofInStrwith$0characters.
SerInRPin\CTSPin,RXBaudMode,[WaitStrInStr\3\13]
WethenwaitforthereceivedcharacterstomatchABC.Whentheymatch,executionresumesandthereceivedstringisechoedviatheserialport.
SerOutTPin,TXBaudMode,[“StrReceived-Value:“,| StrInStr\10\0,13]
Let’schallengetheWaitStrwithsomenonmatchingcharacters.Aftereach,we’lluseacarriagereturn.The outputweseematchesexpectation.
168
RS-232SerialInterface SentCharacters
Received ReadytoReceive
Comments Promptmessage
A
Noresponse
B
Noresponse
C
Noresponse
AB ABC
Noresponse StrReceived-Value:ABC
abc
Receivedcharactersmatchtheexpected;executionjumpstonext statementandechoesthereceivedinformation Noresponsetolowercase
WecanuseWaitStrtopluckcertaindesireddataitemsfromasequencewithbothwantedandunwanted items.Forexample,considerthefollowingsampleoftheNMEAstandardoutputfromaGlobalPositioning Satellitereceiver. $GPGLL,3846.4266,N,07722.7589,W,195138.033,A*2D $GPGGA,195138.03,3846.4266,N,07722.7589,W,1,05,4.1,00104,M,,,,*3E $GPRMC,195138.03,A,3846.4266,N,07722.7589,W,00.0,000.0,250104,10,W*4D $GPGSA,A,3,24,20,07,04,09,,,,,,,,05.1,04.1,03.1*0F $PMGNST,04.00,3,T,716,09.7,+03846,00*40
Supposewewishtoreadthe$GPGLLstring,whichcontainsthegeographicpositionlatitudeandlongitude andtimeinformation,butignoreotherstrings.WemightuseWaitStrtomonitortheinputdatastreamuntil themessageidentifier$GPGLLhasbeenreceived.Wethenwouldcapturetherestofthelineanddecodethe latitudeandlongitudeinformation. Program9-1E Let’snowexploreapoorlydocumentedpartofMBasic—theinputandoutputmodifiers.Here’smysummaryoftheundocumentedportionsofinput/outputmodifiers. Modifier Family
Decimal (Dec) (and others)
Modifier Dec Dec1 Dec2 Dec3 Dec4
BaseValue
Output 123 3 23 123
123 123
Decimal (Dec) (and others)
DEC\1 DEC\2 DEC\3 DEC\4
123 123 123
123
0123
Comments ThemodifierDecnwherenisanumber determinesthenumberofdigitsto display,startingfromtheright.Notethat specifyingmoredigitsthanrequiredto displaythenumberdoesnotcauseblanks orleadingzeros.Decwithoutan“n” displaysalldigitsofthenumber. Thissame“addn”todefinedisplayed digitsappliesto: Dec,sDec Hex,iHex,sHex,isHex Bin,iBin,sBin,isBin Theoutputisforcedtothelengthgivenby thevaluefollowingthe\byaddingleading zeros. ThisappliestoDec,sDec Hex,iHex,sHex,isHex Bin,iBin,sBin,isBin
(Continued)
169
Chapter9 Modifier Family Real (floating point numbers)
Modifier Real Real1 Real2 Real3 Real4 Real4Var\1
BaseValue
–123 +123 7B –7B 7B –7B
3.4559936523 23.4559936523 123.4559936523 123.4559936523 123.4 123.45 123.455 123.4559 –123 123 7B –7B $7B $-7B
1111011 –1111011
1111011 –1111011
1111011 –1111011
%1111011 %–1111011
123.456
Real4Var\2 Real4Var\3 Real4Var\4 Signed Decimal SignedHex
sDec sHex
Indicated SignedHex
isHex
Signed Binary
sBin
Indicated Signed Binary
isBin
Output 123.4559936523
Comments Extradigitsareresolutionerror.Without anymodifier,wegetthefull14characters. Usedwithoutanythingelse,Realnworks thesamewayasforDec.However,n appliesonlytodigitstotheleftofthe decimalpoint. Tosetthedigitsdisplayedontherightof thedecimalpoint,usethe/nsyntax.(Var isatypeLong)
Ifvalueis<0,–signappended;no+sign if>0. Ifvalueis<0,–signappended;no+sign if>0. Ifvalueis<0,–signappended;no+sign if>0.Minussignappearsafterthe$hex indicator. Ifvalueis<0,–signappended;no+sign if>0. Ifvalueis<0,–signappended;no+signif >0.Minussignappearsafterthe%binary indicator.
Anotherundocumentedreminder—whenassigningalengthvaluetoastringoutput,MBasicdoesnotcheck thelength.Forexample,consider:
TestStrVar Byte(10) SerOutTPin,TXBaudMode,[StrTestStr\20,13]
Althoughthestringarraybeingwrittentotheserialpinonlyhas10validelements,the\20modifierwrites 20characters.Noerrormessagewillbegenerated,and20characterswillbewritten.Theextra10characters arethecontentsofthenext10RAMmemorylocationsimmediatelyfollowingthelastelementofTestStr. Program9-1Eexercisestheseundocumentedmodifiers. CPU=16F877A MHZ=20 CONFIG16250 ;Program09-1B ;SoftwareSerialI/O ;Constants ;------------TPin RPin CTSPin RTSPin
Con Con Con Con
C6 C7 C5 C4
TXBaudMode RXBaudMode
Con Con
i38400;inverteddrivennoparity i38400;inverteddrivennoparity
;Variables ;-------------i Var
Byte
;transmitpin ;RXPin ;CTSPin ;RTSPin
;loopcounter
170
RS-232SerialInterface j InStr RealVarVar Main
Var Var
SByte Byte(11);Receivedstring Long
;StringOutput InStr=“ABCDEFGHIJK” ;Limitlengthwithexplicitlengthparameter SerOutTPin,TXBaudMode,[“InStr:“,StrInStr\10,13] InStr=“ABCDEFGHIJK” ;LimitwithembeddedEOL InStr(3)=$0 SerOutTPin,TXBaudMode,[“InStr:“,StrInStr\10\0,13] ;Followwithanunderline SerOutTPin,TXBaudMode,[REP“-”\10,13] SerOutTPin,TXBaudMode,[13,13] ;DecimalIntegerOutput i=123 SerOutTPin,TXBaudMode,[“i:”,Deci,”F”,13] SerOutTPin,TXBaudMode,[“i:”,Dec1i,”F”,13] SerOutTPin,TXBaudMode,[“i:”,Dec2i,”F”,13] SerOutTPin,TXBaudMode,[“i:”,Dec3i,”F”,13] SerOutTPin,TXBaudMode,[“i:”,Dec4i,”F”,13] ;Notethefollowingproducesnoerrorcode ;itoutputs30variablesasstring,starting ;ataddressofi. i=88 SerOutTPin,TXBaudMode,[Stri\10,13] SerOutTPin,TXBaudMode,[13,13] ;Signedbyteoptions j=-123 SerOutTPin,TXBaudMode,[“j:“,Decj,13] SerOutTPin,TXBaudMode,[“j:“,SDecj,13] SerOutTPin,TXBaudMode,[“j:“,SDec1j,13] SerOutTPin,TXBaudMode,[“j:“,SDec2j,13] SerOutTPin,TXBaudMode,[“j:“,SDec3j,13] SerOutTPin,TXBaudMode,[“j:“,SDec4j,13] SerOutTPin,TXBaudMode,[13,13]
;Signedbyteoptions j=123 SerOutTPin,TXBaudMode,[“j:“,Decj,13] SerOutTPin,TXBaudMode,[“j:“,SDecj,13] SerOutTPin,TXBaudMode,[“j:“,SDec1j,13] SerOutTPin,TXBaudMode,[“j:“,SDec2j,13] SerOutTPin,TXBaudMode,[“j:“,SDec3j,13] SerOutTPin,TXBaudMode,[“j:“,SDec4j,13]
SerOutTPin,TXBaudMode,[13,13] ;hexoptions i=123 SerOutTPin,TXBaudMode,[“i:“,Hexi,13] SerOutTPin,TXBaudMode,[“i:“,Hex1i,13] SerOutTPin,TXBaudMode,[“i:“,Hex2i,13] SerOutTPin,TXBaudMode,[“i:“,Hex3i,13] SerOutTPin,TXBaudMode,[“i:“,Hex4i,13] SerOutTPin,TXBaudMode,[13,13] ;indicatedhexoptions i=123 SerOutTPin,TXBaudMode,[“i:“,iHexi,13] SerOutTPin,TXBaudMode,[“i:“,iHex1i,13] SerOutTPin,TXBaudMode,[“i:“,iHex2i,13] SerOutTPin,TXBaudMode,[“i:“,iHex3i,13] SerOutTPin,TXBaudMode,[“i:“,iHex4i,13]
171
Chapter9 End
j=-123 SerOutTPin,TXBaudMode,[“j:“,sHexj,13] SerOutTPin,TXBaudMode,[“j:“,isHexj,13] j=123 SerOutTPin,TXBaudMode,[“j:“,sHexj,13] SerOutTPin,TXBaudMode,[“j:“,isHexj,13] SerOutTPin,TXBaudMode,[13,13] i=123 ;binaryoptions SerOutTPin,TXBaudMode,[“i:“,Bini,13] SerOutTPin,TXBaudMode,[“i:“,iBini,13] j=-123 SerOutTPin,TXBaudMode,[“j:“,sBinj,13] SerOutTPin,TXBaudMode,[“j:“,isBinj,13] SerOutTPin,TXBaudMode,[13,13] RealVar=123.456 SerOutTPin,TXBaudMode,[“RealVar:“,RealRealVar,13] SerOutTPin,TXBaudMode,[“RealVar:“,iHexRealVar,13] SerOutTPin,TXBaudMode,[“RealVar:“,Real1RealVar,13] SerOutTPin,TXBaudMode,[“RealVar:“,Real2RealVar,13] SerOutTPin,TXBaudMode,[“RealVar:“,Real3RealVar,13] SerOutTPin,TXBaudMode,[“RealVar:“,Real4RealVar,13] SerOutTPin,TXBaudMode,[“RealVar:“,Real4RealVar\1,13] SerOutTPin,TXBaudMode,[“RealVar:“,Real4RealVar\2,13] SerOutTPin,TXBaudMode,[“RealVar:“,Real4RealVar\3,13] SerOutTPin,TXBaudMode,[“RealVar:“,Real4RealVar\4,13]
Program9-1Eneedsnoanalysis,asitsimplytestsmanyoftheundocumentedoutputmodifierssummarized earlier.Here’stheoutputfromProgram9-1E:(Tosavespace,I’vereformattedtheoutputintofourcolumns): InStr:ABCDEFGHIJ InStr:ABC ---------i:123F i:3F i:23F i:123F i:123F X…ABC<00>EFGH j:4294967173 j:-123 j:-3 j:-23 j:-123 j:-123
j:123 j:123 j:3 j:23 j:123 j:123 i:7B i:B i:7B i:7B i:7B
i:$7B i:$B i:$7B i:$7B i:$7B j:-7B j:$-7B j:7B j:$7B
RealVar:123.4559936523 RealVar:$8576E978 RealVar:3.4559936523 RealVar:23.4559936523 RealVar:123.4559936523 RealVar:123.4559936523 RealVar:123.4 RealVar:123.45 RealVar:123.455 RealVar:123.4559
i:1111011 i:%1111011 j:-1111011 j:%-1111011
AnotherundocumentedfeatureofMBasicisthatmodifierssuchasDec,Hex,andBin(includingtheirvariants,suchasDec2,andtheirindicatedandsignedformssuchasiHex,sHexandisHexandeventheirvariant indicatedandsignedformsuchasisHex3)maybeusedasfunctionstoconvertanumericalvaluetoitsstring representation.
172
RS-232SerialInterface Program9-1F We’velookedatMBasic’sundocumentednumericalmodifierswhenformattingoutputvalues.Thesemodifiers,suchasDec2,isHex3,etc.,maybeusedwhenreceivingdata.Howdotheyworkwhenappliedto numericalinputvariables? WhatI’vebeenabletodistillfromtheresultsofProgram9-1Gare: Automaticbuffer—MBasicassignsa10-digitinputbuffertovaluesreadintoaformattedvariableunlessthe modifierhasanexplicitlengthterm.Forexample,[Decx]willcauseanautomatic10digitbufferto becreated;[Dec2x]createsadefacto2digitbuffer.ThebufferispackedBCDformat,onedigitper nibble. Terminationofinput—Inputterminatesupontheearlierof(a)fillingthebuffer(10digitsifnotdefinedby anexplicitlengthmodifier)or(b)receiptofthefirstnonnumericcharacter. Nonnumericalcharacters—Nonnumericalcharactersareignoredwhenprecedingnumbers,andterminate theinputwhentheyfollowanumber.Thus,iftheinputmodifieris[Decx],enteringxyz123causesx =123.Entering1x23resultsinx=1. Indicatedinput—WheretheindicatedmodifiersiHexoriBinareused,anycharactersotherthantheleadingindicator,“$”or“%”,respectively,areignored.Legitimateinputcharactersare0…FforiHex,and 0…1foriBin.Nocaseconversionisperformed,so$abisrejectedand$ABisaccepted.Nonacceptable charactersprecedingtheindicator,forexample,x$ABwillbeignored.Nonacceptablecharactersafter theindicator,forexample,$xABcausetheentrytoberejected. Signedvalues—Signedmodifiers,suchassDec,acceptboth+and–asvalidleadingindicators.(The+is ignoredasanonnumericcharacter.) Real—AsindicatedintheUser’sGuide,themodifierRealisrestrictedtoonlyoutputstatements.However, it’spossibletoreadtheintegerandfractionalpartsofarealnumberinasinglestatement,suchas[Dec IntegerIn,Dec2FractionIn].Ifanumbersuchas123.45isentered,theresultwillbetosetIntegerIn=123andFractionIn=45.Thesemayberecombinedintoafloatingpointnumberafter suitablemanipulation.(Thetrickypartisthefractionalvalue.) Program9-1Gdemonstratesmanyofthesepossibleinputmodifiers. ;Program09-1F ;SoftwareSerialI/O ;Constants ;------------TPin RPin CTSPin RTSPin
Con Con Con Con
TXBaudMode Con bit/sec RXBaudMode Con ;Variables ;-------------InByte Var Byte InWord Var Word InLong Var Long InSByteVar SByte Main
C6 C7 C5 C4
;transmitpin ;RXPin ;CTSPin ;RTSPin
I8N1_38400
;inverted/normalpin/noparity/1stop/38400
I8N1_38400
;sameforreceive
;input
SerOutTPin,TXBaudMode,[13,”EnterByteDecimalValue:“] SerInRPin\CTSPin,RXBaudMode,[DecInByte] SerOutTPin,TXBaudMode,[13,”Received:“,DecInByte,13]
173
Chapter9
SerOutTPin,TXBaudMode,[13,”EnterByteDec2Value:“] SerInRPin\CTSPin,RXBaudMode,[Dec2InByte] SerOutTPin,TXBaudMode,[13,”Received:“,DecInByte,13] SerOutTPin,TXBaudMode,[13,”EnterWordDecimalValue:“] SerInRPin\CTSPin,RXBaudMode,[DecInWord] SerOutTPin,TXBaudMode,[13,”Received:“,DecInWord,13] SerOutTPin,TXBaudMode,[13,”EnterByte&WordDecValues:“] SerInRPin\CTSPin,RXBaudMode,[DecInByte,DecInWord] SerOutTPin,TXBaudMode,[13,”Received:“,DecInByte,”“,| DecInWord,13]
SerOutTPin,TXBaudMode,[13,”EnterIndicatedHexValue:“] SerInRPin\CTSPin,RXBaudMode,[iHexInByte] SerOutTPin,TXBaudMode,[13,”Received:“,iHexInByte,13] SerOutTPin,TXBaudMode,[13,”EnterIndicatedBinValue:“] SerInRPin\CTSPin,RXBaudMode,[ibinInByte] SerOutTPin,TXBaudMode,[13,”Received:“,ibinInByte,13] SerOutTPin,TXBaudMode,[13,”EnterSignedByteValue:“] SerInRPin\CTSPin,RXBaudMode,[sdecInSByte] SerOutTPin,TXBaudMode,[13,”Received:“,sDecInSByte,13]
GoToMain End
Program9-1G Program9-1Gconsistsofseveralsections;eachstartswithapromptidentifyingthetypeofvariabletobe entered,thenaSerInstatementtoreadthevariable,followedbyoutputtingtheenteredvalue.
SerOutTPin,TXBaudMode,[13,”EnterByteDecimalValue:“] SerInRPin\CTSPin,RXBaudMode,[DecInByte] SerOutTPin,TXBaudMode,[13,”Received:“,DecInByte,13]
Atypicalsectionisabove;itpromptsforadecimalvalue,andreadstheinputwithasimpleDecmodifier. ThereadvalueisthenoutputtedwiththesameDecmodifier. Let’sseehowthesespecificinputsectionsinteractwithvariousinputentries.Thesymbol<E>indicatesthe “Enter”key. Prompt
InputModifier
EnterByteDecimalValue:
[DecInByte]
EnterByteDecimalDec2Value:
[Dec2InByte]
EnterWordDecimalValue
[DecInWord]
EnterByteandWordDecimalValues:
[DecInByte,DecInWord]
EnterIndicatedHexValue:
[iHexInByte]
EnterIndicatedBinaryValue:
[ibinInByte]
EnterSignedByteValue:
[sdecInSByte]
UserResponse 123<E> Xx123y<E> 12<E> Xxx33 1234<E> S%^4321c 11,22<E> 123.4567<E> $AB<E> X$12 %0101<E> %00001111<E> –100<E> +123
Output Received:123 Received:123 Received:12 Received:12 Received:1234 Received:4321 Received:1122 Received:1234567 Received:$AB Received:$12 Received:%101 Received:%1111 Received:–100 Received:123
TogetasenseofhowMBasichandlesformattedinputs,runprogram9-1Fandtryvariouspossibleresponses.
174
RS-232SerialInterface Program9-2A Sofar,allourcodehasusedsoftwareinputandoutputroutines.And,exceptforthoseprovisionsusingflow control,thecodeinPrograms9-1Athrough9-1GisequallyusablewithMBasic’shardware-basedinputand outputroutines,HSerInandHSerOut.Now,however,we’regoingtolookatinputwiththehardware-only HSerStatfunction. We’llstartwithasimpleactivity;readinganinputstringanddeterminingitslength.However,insteadof waitingfortheusertoenterdata,Program9-2Aperformsotherfunctionsandperiodicallycheckstoseeif datahasbeenreceived.Whentheuserhasfinishedenteringthedata,asreflectedbyacarriagereturncharacter,wecountthenumberofcharactersreceivedandoutputthelengthandtheentereddata. ;Constants ;------------MaxStrSize Con
12
;Variables ;-----------i j InStr InByte
Byte Byte Byte(MaxStrSize) Byte
Var Var Var Var
;stringlength
;counter ;counter ;inputstring ;inputbyte
EnableHSerial SetHSerialH38400 HSerOut[“P-09-02A”,13] Pause100 Main Fori=0to255 ;dummyprocedure Pause10 HSerStat3,CheckInput ReturnFromCI Next;i GoToMain CheckInput HSerIn[InByte] ;Echoback HSerOut[StrInByte\1] InStr(j)=InByte j=j+1 Ifj=(MaxStrSize-1)Then j=0 EndIf IfInByte=13Then Ifj>0Then j=j-1;getridofCR EndIf GoSubCRReceived EndIf HSerStat3,CheckInput GoToReturnFromCI CRReceived ;-------------- HSerOut[“CharsReceived:“,Decj,13] Ifj>0Then HSerOut[“CompleteLineReceived:“,StrInStr\j,13]
175
Chapter9 Return
ELSE EndIf j=0
HSerOut[“CRonly”,13]
End
Let’slookatthecode. EnableHSerial SetHSerialH38400
First,wesetthecompilerinstructionEnableHSerial,neededtocausethecompilertoloadthehardware serialsupportlibrary.Next,wemustsetthedesiredbaudrate,usingSetHSerial.SetHSerialestablishes theserialbitrateforbothHSerOutandHSerIn.Sincewehavenoneedtochangeoutputspeed,wesetit once,duringprograminitialization.Also,sincethe16F87xfamily’sUSARTishardwiredtopinsC6(TX out)andC7(RXin),therearenoinputandoutputpinstodefine. Main Fori=0to255 ;dummyprocedure Pause10 HSerStat3,CheckInput ReturnFromCI Next;i GoToMain
ThemainprogramloopisadummyFor-Nextloopthatsimulatesotheractivity,suchascontrollingasteppermotor,ormonitoringtemperature,oranyotherfunctionsuitableforaPICprogrammedwithMBasic. ThekeyelementforourpurposeisthestatementHSerStat3,CheckInput.Aswelearnedearlierin thischapter,HSerStatisanundocumentedfunctionthat,whencalledwithamodeargumentof3,transfers programexecutiontothelabelCheckInputifthereisdataintheinputbuffer. BothHSerInandHSerOuthavebuffers.For16F87xseriesPICs,theinputandoutputbuffersareeach47 byteslong.Moreimportantly,however,isthatoncetheserialportissetupwiththeSetHSerialcommand, anydataonthereceivepinisautomaticallymovedintothebuffer.Ifmorethan47bytesarereceivedbefore thebufferiscleared,thebufferwrapsaroundandnewerdataoverwritesolderdata. Withthisunderstanding,youshouldseeasubtle,butclear,differencebetweenSerInandHSerIn:SerIn establishesthereadprocedureandsetsapinforinput;datasenttothatpinbeforeSerInisoperatingislost. HSerIndoesnotestablishanything;ratheritchecksthereceivebufferopenedbySetHSerialandreadsthat buffer.SetHSerialisthelaunchingevent,notHSerIn.Consequently,HSerInmaybeexecutedatanytime andretrieveswhateverhasarrivedafterSetHSerialhasbeenexecuted,uptothemaximumbuffersize. Formanypurposes,thisdifferencebetweenSerInandHSerInmaybeignored.Ifallwedoissendauser promptmessageviaHSerOutandthenwaitforaresponse,thedifferencebetweenSerInandHSerInis immaterial.But,thisdifferenceiscriticaltoourabilitytoquasi-multitaskthePIC—thatis,toexecuteunrelatedcodewhiledataisbeingreadovertheserialportbytheUSART. WiththisunderstandingofHSerInandHSerStat,let’slookattheCheckInputcode.Remember,this codeisexecutedonlywhenthereisatleastonebyteintheinputbuffer. CheckInput HSerIn[InByte] ;Echoback HSerOut[StrInByte\1] InStr(j)=InByte
176
RS-232SerialInterface First,wefetchonebytefromthebufferwithHSerIn[InByte].Toprovideuserfeedback,weechoback thisbytewithaHSerOutprocedurecall.WethenstorethisbyteinthearrayInStr.(Weinitializedjby settingitto0intheinitializationsectionofProgram9-2Aandwe’llseehowitgetsresetto0later.)
j=j+1 Ifj=(MaxStrSize-1)Then j=0 EndIf
WenowupdatejandseeifitexceedsthesizeofInStr.Ifitdoes,weresetjto0.
IfInByte=13Then Ifj>0Then j=j-1;getridofCR EndIf GoSubCRReceived EndIf
Wenextchecktoseeifwehavereceivedanend-of-line(carriagereturn)character.Ifthecharacterisacarriagereturn,wedecrementjtopreventthecarriagereturnfrombeingconsideredinthelengthofInStr, andweexecutethesubroutineCRReceived. HSerStat3,CheckInput GoToReturnFromCI
Finally,weseeifadditionalbytesremaininthereceivebufferthroughanotherHSerStat3,CheckInput statement.Ifthebufferisnotempty,werecyclethroughtheCheckInputcodeuntilitisempty. CRReceived ;-------------- HSerOut[“CharsReceived:“,Decj,13] Ifj>0Then HSerOut[“CompleteLineReceived:“,StrInStr\j,13] ELSE HSerOut[“CRonly”,13] EndIf j=0 Return
ThesubroutineCRReceivedismostlyadummyprocedure;itsendsamessagethatacompletelinehasbeen receivedanddistinguishesbetweencharactersfollowedbyacarriagereturnfromacarriagereturnonly. We’llseeinProgram9-3howwemayusethisapproachformoreusefulpurposes.Fornow,runProgram 9-2Aandtrydifferingresponsestodataentry.Here’sonetypicalinteraction. OutputofProgram9-2A P-09-02A 123 CharsReceived:3 CompleteLineReceived:123 456 CharsReceived:3 CompleteLineReceived:456 0123456789 CharsReceived:0 CRonly 012345678 CharsReceived:9 CompleteLineReceived:012345678
UserInteraction 123
456
0123456789
012345678
Notethatwhenweenter11characters(0…9plusthecarriagereturn)theIfj=(MaxStrSize-1)conditional istrueandjisresetto0.Thus,theresponseis“CharsReceived0,”exactlyaswewishtheprogramtobehave.Ifwe hadentered12characters,01234567891,forexample,theresponsewouldbeonecharacterreceived,“1.” 177
Chapter9 Program9-2B Acommonprogrammingtaskisparsinginputstrings.Let’sseehowwemightaccomplishpartofthattask. We’llconvertanumericalstringoftheformnnnntoabinarynumberandalsowe’llconvertastringofthe formwemightusetorepresentadateortime,hh:mm:ssordd/mm/yytothreeseparatenumbers.We’llthen usetheseroutinesinProgram9-3. ;Constants ;--------------WorkLenCon
8
;Variables ;---------------WorkStr Var DecNum Var i Var k Var NewVal Var
Byte(WorkLen);workingstringforconversion Long ;outputofstringtodecimal Byte ;counter Byte ;counter Byte(3);fordate/timeitems
;Initialization ;----------------EnableHSerial SetHSerialH38400 Main ;-------- WorkStr=“1234“ GoSubStrToDecimal HSerOut[“InputString:“,StrWorkStr\WorkLen\”“,| “Value:“,DecDecNum,13] WorkStr=“12:34:56“ GoSubStrToDecimal HSerOut[13,”InputString:“,StrWorkStr\WorkLen\”“,| “Value:“,DecDecNum,13] GoSubStrTo3Decimal HSerOut[DecNewVal(0),”-”,DecNewVal(1),”-”,| DecNewVal(2),13] WorkStr=“12/34/56“ GoSubStrToDecimal HSerOut[13,”InputString:“,StrWorkStr\WorkLen\”“,| “Value:“,DecDecNum,13] GoSubStrTo3Decimal HSerOut[DecNewVal(0),”-”,DecNewVal(1),”-”,| DecNewVal(2),13] Pause100 ;don’tforgetpausebeforeENDtoclearbuffer End StrToDecimal ;------------ i=0 DecNum=0 While(WorkStr(i)>=“0”)AND(WorkStr(i)<=“9”) DecNum=DecNum*10 DecNum=DecNum+WorkStr(i)-“0” i=i+1 WEND Return StrTo3Decimal ;----------- i=0 k=0 Fork=0to2 NewVal(k)=0
178
RS-232SerialInterface Return End
While(WorkStr(i)>=“0”)AND(WorkStr(i)<=“9”) NewVal(k)=NewVal(k)*10 NewVal(k)=NewVal(k)+WorkStr(i)-“0” i=i+1 WEND i=i+1 Next;k
Program9-2Bsetsupthreeprepreparedteststrings,“1234,”“12:34:56”and“12/34/56”simulatinguser input.Eachoftheseteststringsisthensubmittedtooneoftwoconversionsubroutines,StrToDecimalor StrTo3Decimal.StrToDecimalassumestheinputresponseisonedecimalvalue,whileStrTo3Decimal assumestheinputisineitheratimeordatestructureanditreturnsthreedecimalvalues,representingthe threenumbersseparatedbycolonsorslashsymbols. TheconvertedsinglenumbervaluewillbeheldinthetypelongvariableDecNum,whilethebytearray WorkStrholdsthesimulatedstringinput.
WorkStr=“1234“ GoSubStrToDecimal HSerOut[“InputString:“,StrWorkStr\WorkLen\”“,| “Value:“,DecDecNum,13]
Let’sseehowsubroutineStrToDecimalconvertsthestringtoanumericalvalue. StrToDecimal ;------------ i=0 DecNum=0 While(WorkStr(i)>=“0”)AND(WorkStr(i)<=“9”) DecNum=DecNum*10 DecNum=DecNum+WorkStr(i)-“0” i=i+1 WEND Return
StrToDecimaliscalledwithWorkStrcontaining“1234”.
WorkStrContents
0 “1”
1 “2”
2 “3”
3 “4”
ElementAddress 4 5 0 0
6 0
7 0
8 0
9 0
Weinitializethecounterindexiandthevalueholder,DecNumbysettingbothto0. TheWhile/WendloopstepsthroughWorkStr,oneelementatatime,startingwithWorkStr(0). Wecheckthiselementtoensureitisavalidnumericalcharacter(between“0”and“9”).Ifitisavalid number,thenweshiftDecNumonedecimalplacetotheleftbymultiplyingitby10.(Thefirstpassthrough thisloop,i=0,sothereisnoshifttotheleft.)Then,weconvertWorkStr(i)toitsnumericalvalueby subtractingtheASCIIvalueof“0”fromthecharacterandaddthatvaluetoDecNum.Let’sgothroughthis numerically. i 0 1 2 3
WorkStr(i) “1” “2” “3” “4”
DecNum 0 1 12 123
DecNum=DecNum*10 0 10 120 1230
DecNum=DecNum+WorkStr(i)-”0” 0+1=1 10+2=12 120+3=123 1230+4=1234
Weusethesamealgorithmtoconvertthethree-valueinputstring,savingthenumericalvaluesinthethreeelementarrayNewVal.
179
Chapter9 StrTo3Decimal ;----------- i=0 k=0 Fork=0to2 NewVal(k)=0 While(WorkStr(i)>=“0”)AND(WorkStr(i)<=“9”) NewVal(k)=NewVal(k)*10 NewVal(k)=NewVal(k)+WorkStr(i)-“0” i=i+1 WEND i=i+1 Next;k Return End
Theextensiontothreevariablesseparatedbyanonnumericalcharactershouldbeobvious. Program9-3 We’veconcentratedonthebasicsinthisbook,andtoemphasizealgorithmsandtechniquesmanyprogram usehardcodedconstantsinsteadofpromptingforuserinputinformation.Asanexercise,therefore,we’ll developtheskeletonofaninteractiveprogramthatmightbeusedtocontroltheweatherstationanddataloggerdevelopedinChapter28.TheprogramsinChapter28usehardcodedtimeanddateconstantstosetthe DS1302realtimeclock.Likewisethedatasaveinterval,thegroundelevationbarometercorrectionconstant andothervaluesarehardcoded. We’llapproachProgram9-3slightlydifferentlythanisournorm.Let’sfirstlookattheuser’sinteraction withProgram9-3.And,youmaywishtoflipthroughChapter28beforegoinganyfurtherinthischapter. UnderstandinghowProgram9-3interactswithuserswillaidunderstandingtheprogramlogic.Manyofthe responsesyou’llseebelowaredummies,asthenecessarymeasurementsandcomputationstosupplynumericalvaluesarecontainedinProgram28-2.Inreviewingtheresponse,userenteredinformationappears afterthepromptsymbol>.Hence,>B?meansthattheuserenteredB?. UserInputandInteractiveResponse
Comments
P09-3 v0.1 >Commands–Letter&?getsmoreinfo ?ThisMenu AAllDataBBarometer CCelsiusTemp DDate EElevationfeet HHumidity ISaveInterval MMode OOutput RRecord SStatus TTime VVersion XStopRecording > >A? Atooutputdate/time/barometer/humidity/tempF/tempC
Introductoryscreen.This informationisdisplayedwhenthe programbootsup.Itistheshort formofthehelpscreen. FFahrenheitTemp Userdataisenteredafterthe promptsymbol>
UserentersA?andreceivesa betterdescriptionofwhattheA prefixisfor. Loweroruppercaseisthesame. EnteringAalonecausesastatus dump.Inthiscase,theoutputisa dummyresponse“Status.” Commandletterfollowedby? givesexpandedhelp
>a Status
>B? BtooutputbarometricpressureininHg&mbar >B BarometerinHg/mbar
Dummybarometerresponse.
180
RS-232SerialInterface UserInputandInteractiveResponse >C? CtooutputcurrenttemperatureindegreesCelsius >c TempxxC
Comments Commandletterfollowedby? givesexpandedhelp DummyCelsiustemperature response.Notethattheresponse wasalowercaseC. D?givesahelpsentence.Note thatDhastwooptions;Dwith nothingelsegivesthedate, Dmm/dd/yysetsthedate.
>D? Dtooutputcurrentdate Dmm/dd/yytosetdate >? Commands-Letter&?getsmoreinfo ?ThisMenu CCelsiusTemp HHumidity OOutput TTime
AAllDataBBarometer DDate EElevationfeet ISaveInterval MMode RRecord SStatus VVersion XStopRecording
FFahrenheitTemp
>E? EtooutputcurrentelevationExxxxtoenternewelevation(feetAMSL)
>E >F? FtooutputcurrenttemperatureindegreesFahrenheit >F TempxxF
A?byitselfgivesthesummary helpmenu.
E?givesahelpsentence.E isanotherdouble-purpose command;eitherreadthecurrent valueorenteranupdatedvalue forgroundelevation. NooutputforanErequestatthe present. Commandletterfollowedby? givesexpandedhelp Outputadummyreportforthe currenttemperature.
>H? Htooutputrelativehumidityin%
Commandletterfollowedby? givesexpandedhelp
>H Humidity >I? ItosetsaveintervalIxxxxinminutes >I ItosetsaveintervalIxxxxinminutes LogInterval >M? MmodeMF:recorddate/time/infoMA:recordinfoonly >M Mode >O? Otooutputsaveddatatoserialport SavedDataOutput >O Otooutputsaveddatatoserialport SavedDataOutput >R? Rtostartsavingdata StartRecording
Dummyhumidityreport. Commandletterfollowedby? givesexpandedhelp Dummyresponsetocommand Commandletterfollowedby? givesexpandedhelp Dummyresponsetocommand Commandletterfollowedby? givesexpandedhelp Dummyresponsetocommand Commandletterfollowedby? givesexpandedhelp
181
Chapter9 UserInputandInteractiveResponse >R Rtostartsavingdata StartRecording >S? Stooutputstatusreport >S Status >T? Ttooutputcurrenttime Thh:mm:sstosettime24hourformatonly >T >V? v0.1 >V v0.1 >X? Xtostopdatarecording >X StopRecording
Comments Dummyresponsetocommand Commandletterfollowedby? givesexpandedhelp Dummyresponsetocommand Commandletterfollowedby? givesexpandedhelp Dummyresponsetocommand Currentsoftwareversionis0.1 Dummyresponsetocommand Commandletterfollowedby? givesexpandedhelp Dummyresponsetocommand
ThecommandsyntaxofProgram9-3is: Command ? A B C D
Name Help AllData Barometer Celsius Date
DataFlow ToUser ToUser ToUser ToUser
Action Displayshortformhelpmenu. Displaysallcurrentweatherinformation. CurrentbarometricpressureininchesHgandhPa. DisplaycurrenttemperatureindegreesCelsius. Dtodisplaycurrentdate. Bidirectional Ddd/mm/yytosetnewdata. E Elevation(feet) Etodisplaycurrentelevation(feetAMSL)setting. Bidirectional ExxxxtosetelevationtoxxxxfeetAMSL. F Fahrenheit ToUser DisplaycurrenttemperatureindegreesFahrenheit. H Humidity ToUser Displaycurrentrelativehumidityinpercentage. I Interval Itodisplaycurrentsaveinterval(minutes). Bidirectional Ixxtosetnewsaveintervaltoxxminutes. M Mode ToUser Reportisdatabeingsavedornot? O OutputDump Outputsthesaveddate/time/temp/humidity/barometerrecords ToUser fromEEPROM. R StartRecording ToUser StartsavingdatatoEEPROM. S Status ToUser Statisticsonrecordssaved,availablespacefornewrecords. T Time Ttodisplaycurrenttime. Thh:mm:sstosetthecurrenttime. V Version ToUser Displaythecurrentsoftwareversion. X StopRecording ToUser StopsavingdatatoEEPROM. Anyletterfollowedbya?yieldsahelpsentenceforthatcommand.
Let’snowlookatthecodeforProgram9-3.We’llthengothroughthehighlights;muchofProgram9-3 we’vealreadycoveredinthischapter. Onefurtherchange—Program9-3isverylong.Ratherthanfollowournormalstructureoflistingtheprograminfull,followedbyasection-by-sectionanalysis,we’llskipthefulllisting.Program9-3,likeallother
182
RS-232SerialInterface programsinthisbook,isavailableinanelectroniccopyintheassociatedCD-ROM.Ifyouneedalistingto followwhilereadingtheanalysis,youmayprintonefromtheprogramfile. Let’sabstractthecodeintoapseudo-codeformtoclarifytheprogramflow: Main
Executeadummylooptosimulateotherprogramcode,suchasthatof Program28-2
Hasanydatabeenenteredbytheuserintotheserialinputbuffer?Ifyes, executeCheckInput ReturnFromCheckInput: GoToMain CheckInput MoveacharacterintheinputbufferintoastringarrayInStr. Hasacarriagereturnbeenreceived?Ifyes,GoSubCRReceived Ifmorecharactersarewaitinginthebuffer,movethemintoInStr. GoToReturnFromCheckInput CRReceived ConvertInStrtouppercase Checkthefirstletterreceived. Ifitmatchesacommandletter,branchtoasubroutine todealwiththatcommandletter. Return SupportingGeneralPurposeSubroutines StrToDecimal—Convertsastringtoanumber StrTo3Decimal—Convertsdd/mm/yyorhh:mm:sstonumbers ContainsData—Determinesifastringcontainsdigits0…9 CopyToTemp—Copyonestringtoanotherstring
We’vealreadyanalyzedCheckInputaswellasStrToDecimalandStrTo3Decimal.Onlyminorchangeshavebeenmadetothesesubroutinesfromtheearlierversions,sowewon’treexaminethiscode. Let’slookatthenewcodeinProgram9-3.We’llstartwithCRReceived.Thissubroutineiscalledonly whenacarriagereturnhasbeenreceived.ThecontentsoftheinputbufferareinthearrayInStr. CRReceived ;-------- Forj=0to(MaxStrSize-1) If(InStr(j)<““)OR(InStr(j)>“z”)Then InStr(j)=$0 ;non-printingchars EndIf ;Convertlowercasetouppercase If(InStr(j)>=“a”)and(InStr(j)<=“z”)Then InStr(j)=InStr(j)-$20 EndIf Next;j
First,wescanthecompletedstringfornonusefulcharactersandconvertanylowercaseletterstouppercase.
;howlongisthevalidpartofthestring? k=0 WhileInStr(k)>=““ k=k+1 WEND
Next,wecountthenumberofvalidcharacters(0…9,A…Zandpunctuationmarks)containedinInStr.
;checkforaCRonly Ifk>0Then k=InStr(0)-“?” Ifk>27Then k=1 EndIf
Ifthebufferholdssomethingmorethanacarriagereturn,wethenexaminethefirstcharacterofInStr (InStr(0))toseeifitisavalidcommandletter.Weconvertthislettertoanordinaldigitbysubtractingthe 183
Chapter9 ASCIIvaluefor“?.”Thus,ifInStr(0)=“?,”thenk=0,ifInStr(0)=“A,”thenk=2,etc.through“Z” correspondingtok=27.Ifthisordinalvalueisexceeded,weforcek=1,therebytrappingoneerrorsource. BranchIndexArray(k), [BR_Unk,BR_Ques,BR_Cent,BR_Date,BR_Fare,BR_Int,BR_Mode,| BR_Out,BR_Rec,BR_Stat,BR_Time,BR_Xstop,BR_Vers,BR_Baro,| BR_Hum,BR_All,BR_Elev] EndIf GoToEndCmd
Wethenbranchtoseparatecodesegmentsforeachcommandletter.But,wedon’tbranchdirectlyonthe valueofk.Rather,webranchonthevalueofthebytetableIndexArray(k).Whywouldwedothis?It addscomplexity,that’sforsure.But,italsomakesiteasierforustoaddordeletecommandletters. Let’slookatIndexArray. IndexArrayByteTable1,0,15,13,2,3,16,4,0,14,5,0,0,0,| 6,0,7,0,0,8,9,10,0,12,0,11,0,0
SupposetheinputletterisC,correspondingtok=4.IndexArray(4)=2.OurBranchinstruction,therefore,executesBR_Cent.We’vefilledIndexArraywith0’sforindexvaluescorrespondingtolettersthatare notpartofourcommandsyntax.Toaddanewcommandsyntaxletter,allwehavetodoisaddthenextopen digittothecorrespondingplaceinIndexArrayandinsertanewbranchlabelattheendintheBranchinstruction.Toadd“Q”asanewcommand,therefore,wenotethecurrenthighestvalueinIndexArrayis15. So,we’llreviseIndexArray(18)tobe16,insteadof15.And,thelastpartoftheBranchstatementwill be[…,BR_All,BR_Elev,BR_QQ].ThisisatleastslightlyeasierthantryingtofigureoutwhereQgoesin Branch,anditletsushaveaBranchstatementthatisfewerthan28elementslong,anotheradvantage. I’vekeptthecodebehindeachBranchlabelasshortaspossible;eachisacalltoaspecificsubroutine,followedbyajumptotheendofCRReceivedsubroutine.Breakingeachcommandletteractionintooneor moresubroutinesmodularizesthecode,makingiteasiertowrite,debugandmaintain. BR_Unk BR_Ques …
GoSubSub_Unk GoToEndCmd GoSubSub_Ques GoToEndCmd
EndCmd HSerStat0 j=0 Return
Let’snowlookatacoupleoftypicalcommand-specificsubroutines. Sub_Unk;Unknowncommand ;------- HSerOut[“UnknownCommand.TryAgain”,13] GoSubSub_Ques Return
Sub_Unkisinvokedforanunknowncharacter—thatis,acharacternotinthecommandsyntax.Itoutputsa messagetotheuserandthencallsthesubroutineSub_Ques. Sub_Ques;?Helprequest ;-------- k=0 WhileHelp1Str(k)<>0 HSerOut[StrHelp1Str(k)\1] k=k+1
184
RS-232SerialInterface Return
WEND k=0 WhileHelp2Str(k)<>0 HSerOut[StrHelp2Str(k)\1] k=k+1 WEND k=0 WhileHelp3Str(k)<>0 HSerOut[StrHelp3Str(k)\1] k=k+1 WEND k=0 WhileHelp4Str(k)<>0 HSerOut[StrHelp4Str(k)\1] k=k+1 WEND k=0 WhileHelp5Str(k)<>0 HSerOut[StrHelp5Str(k)\1] k=k+1 WEND k=0 WhileHelp6Str(k)<>0 HSerOut[StrHelp6Str(k)\1] k=k+1 WEND GoSubSub_Prompt
SubroutineSub_Quesisalsoreachedbyacommandconsistingofonlyaquestionmark;Sub_Ques displayssixlinesofabbreviatedcommandsyntaxhelp.ThesixlinesarestoredinbytearraysHelp1Str throughHelp6Str.Eachofthesestringsisterminatedwitha$0null.Thebytearraysaresentoutonebyte atatimeuntilthe$0isdetected.(Wecouldofcourse,usedMBasic’sinternalend-of-linecommandmodifier.) Sub_Prompt ;------------ HSerOut[“>”] Return
SubroutineSub_Promptdisplaysthe“>”promptsymboltotheuser. Let’slookatoneofthenumericalsubroutines.SubroutineSub_Timeisinvokedwhenthecommandletteris“T.” Sub_Time ;-------- IfInStr(1)=“?”Then k=0 WhileTimeStr(k)<>0 HSerOut[StrTimeStr(k)\1] k=k+1 WEND ELSE GoSubContainsData EndIf
First,weseeifthisisarequestforhelponusingthe“T”command.WedeterminethisbyseeingifInStr(1)=“?”andiftrue,wedisplaytheT-specifichelpstring,containedinthebytearrayTimeStr.If not,wethenseeifInStrhasnumericaldigitsthroughacalltosubroutineContainsData.Subroutine ContainsDatasetsthevariableContainsNumtothenumberofcharacters(“0”…”9”)received.
IfContainsNum>0Then GoSubCopyToTemp GoSubStrTo3Decimal EndIf
185
Chapter9 IfContainsNumbersshowsthepresenceofdigits,weexecutethesubroutineCopyToTempwhich copiesthedigitsanddigitseparatorsfromInStrtoaworkingstringWorkStrthatisanalyzedby StrTo3Decimal,whichisidenticalwiththeStrTo3DecimalsubroutineweanalyzedinProgram9-2A. GoSubSub_Prompt Return
Weendbydisplayingtheprompt. TheremainderofProgram9-3consistsofvariationsonthesealgorithms,andinordernottoexpandan alreadyoverlylongchapterwewillnotconductfurtheranalysis.
IdeasforChangestoProgramsandCircuits •
• •
Thehelpstringsconsumesignificantprogrammemory.Aretherewaystomakethismoreefficient?For example,supposeweadopta5-bitalphabet,sufficienttosupport(capitalletters)A…Zandafewpunctuationsmarks.Wecouldintroduceashiftcharactertoreflectashifttoasecondalphabetconsistingof numbersandadditionalpunctuationmarks.(Yes,thishasbeendonebefore;amongotherthings,it’s theBaudotcode.)Bybitpacking(seeChapter28),wecanfiteight5-bitsymbolsintofivebytes.How elsemightwemakefixedstringstoremoreefficient?Couldwestorecommonwords,suchas“the,” “is,”“enter,”“number,”“temperature”andthelikeinthePIC’son-boardEEPROM,andgiveeachword abyte-lengthindexnumber.Sentencescanthenbeconstructedbystringingaseriesofwordnumbers together.Howefficientwouldthisbe?Howwouldyouincludewordlengthinformationintheword number? Program9-3containslittleerrorchecking.Howwouldyoumodifytheinputroutinestoignoreoutof-limitsdata?Howmuchprogramspacebudgetshouldbedevotedtoerrorcheckingversusrequired computation? HowwouldyoumergePrograms9-3and28-2?Doesa16F87xPIChavesufficientmemorytoruna fullyinteractiveversionofProgram28-2?Howmightthemergedprogrambereducedinsize?
References [9-1]
DallasSemiconductor,FundamentalsofRS-232SerialCommunications,ApplicationNote83(undated). TheprogramTerminal(currentreleasev1.9b)isavailableat:http://bray.velenje.cx/avr/terminal/. [9-3] TheprogramComTestisavailableat:http://www.bb-elec.com/comtest.asp. [9-4] SipexCorporation,SP231A/232A/233A/310A/312AEnhancedRS-232LineDrivers/Receivers,DocumentNo.SP231ADS/01(2000). [9-2]
186
10
CHAPTER
InterruptsandTimers inMBasic Whatareinterrupts?Whataretimers?Howaretheyrelated?And,whyshouldanMBasicprogrammercare?
InterruptsandTimers—Overview WhatisanInterrupt? Aninterruptisaneventthatcausesthecurrentprogramsequencetotemporarilyhalt,andfordifferentcode, calledan“interruptserviceroutine”orISR,tobeexecuted.AftertheISRcompletes,programflowreturnsto thepointitwasatbeforetheinterruptoccurred.YoumightthinkofanISRasasubroutinethatiscallednot byaGoSubinsoftware,butratheranevent.Theeventmaybeexternal,suchasaninputpinchangingstate froma0toa1,orviceversa.Or,theeventmaybeinternaltothePIC,suchasatimerreachingadefined count.Itmayevenbeacombinationofexternalandinternalevents,suchaswhererepeatedexternalsignals causeaninternalcountertoreachapresetvalue. ThischapterfocusesonISRswrittenpurelyinMBasic.Aswe’lllearn,anISRwritteninMBasichasone significantrestriction—itwillbeexecutedonly“between”otherMBasicstatements.Insomecases,thislatencyisaseriousdrawback.Forexample,ifourprogramiswaitingforaninputstringinaSerInstatement, andaninterruptoccurs,theISRwillnotbeexecuteduntiltheSerInstatementcompletes,therebynegating thebenefitofaninterrupt.IfaPause1000statementisexecuted,theMBasicISRwillnotbeexecuted untilthePause1000statementcompletes.We’lllearninChapter15toprogramtheinterrupthandlerin assemblerandhaveitexecuteessentiallyinstantaneouslywhentheinterrupttriggeringeventoccurs.But, we’velearnedinChapter6,forexample,thatwemaysuccessfullyreadarotaryencoderthroughanMBasic ISRfarfasterthanyouwillbeabletospintheencodershaftbyhand.
WhatareTimers? Timersareinternal,programmable,counters.The16F87x/87xAfamilyandmanymid-rangePICshave threehardwaretimers,timer0,timer1andtimer2.Thesetimerscountinputpulsesuntilacertainnumber ofpulsesor“ticks”havebeenreceived.Whenthishappens,aninterruptistriggeredandspecificinterrupt handlercodecanbeexecuted.Thesehardwaremodulesareusuallycalled“timers”insteadof“counters” becausetheirmostoftenusedpurposeistodeterminetimeintervalsbycountingpulsesthatoccuratknown intervals. Atimer’sinputmaycomefromaninternaloscillator,stabilizedbyanexternalcrystal,orfromthePIC’s programclock,orfromanyexternallogic-levelsource.Sometimershaveasoftware-configurableprescaler,permittinginputtickstobedividedby1,2,4or8andsomehavesoftware-configurablepost-scalers, permittingtheoutputtobedividedbydefinedfactorsupto256.Inthecaseofthe16F87xfamily,twotimers have8-bitregisters,whileonehasa16-bitregister.
187
Chapter10
Interrupts Let’sstartbylookingatinterruptsinmoredetail.We’llusethe16F87xfamilyforthisexercise.NotallPICs implementthesameinterrupts,soyoushouldverifythecapabilitiesofaPICyoumaybeconsideringbefore selectingitforyourparticularproject. Beforejumpingintothedetails,let’sfirstlearnabitofterminology.InMicrochip’sreferencedocuments, interruptsareidentifiedbyacronyms,whileMBasicusesaslightlydifferentname.The16F87Xhas14possibleinterrupts,ofwhich11aredirectlysupportedinMBasic: Microchip Acronym ADIF BCLIF
MBasic Identifier ADINT BCLINT
CCP2IF
CCP2INT
CCP1IF
CCP1INT
EEIF
EEINT
INTF
EXTINT
PSPIF
None
RBIF
RBINT
RCIF
RCINT
SSPIF T0IF TMR1IF TMR2IF
SSPINT TMR0INT TMR1INT TMR2INT
TXIF
TXINT
Associated SetupFunction
SetCapture GetCapture SetCompare SetCapture GetCapture SetCompare
SetExtInt
SetTmr0 SetTmr1 SetTmr2
Description Analog-to-digitalconversioniscompleted. Buscollisioninterruptenable;notcurrentlysupportedinMBasic. Interruptoccurswhenthereisacapture/compare/periodmatchwith CCPmodule2. Interruptoccurswhenthereisacapture/compare/periodmatchwith CCPmodule2. EEPROMinterrupt;occurswhenwritingtotheon-boardEEPROMis completed. ChangeofinputpinstateonRB0.Mustseparatelysetmodetoselect 0→1or1→0transitionforthetriggeringevent. Parallelslaveportinterrupt;notsupportedinMBasic. AnypinRB4,RB5,RB6orRB7haschangedstate,ineitherthe0→1or 1→0direction. ReceivedabytethroughthehardwareUSART.Note:Whenusing HSERINorHSEROUTfunctionsRCIFisdisabled. Synchronousserialportinterrupt;notsupportedinMBasic. Timer0overflowhasoccurred. Timer1overflowhasoccurred. Timer2overflowhasoccurred. FinishedtransmittingabytefromthehardwareUSART.Note:When usingHSERINorHSEROUTfunctionsRCIFisdisabled.
The“F”attheendofMicrochip’sacronymsignifiesthatreferenceistothe“interruptflag”bit,whichidentifies sourceoftheinterrupt.Eachofthese14interruptsalsohasanassociated“enable”bit,identifiedwiththeletter “E”attheendoftheacronym,suchasINTEwhichistheenablebitfortheINTinterrupt.We’llsavefurther explanationsuntilChapter15asthisinformationisn’tnecessarytouseMBasic’sinterruptprocedures. Toprogramwithaninterrupt,wefollowafive-elementtemplate: 1. WiththeOnInterruptoperator,linktheinterruptsourcewiththenameoftheassociatedinterrupt serviceroutine. 2. Setupanyoptionalelementsoftheinterruptsource,suchaswhetherEXTINTistobetriggeredonthe 1→0orthe0→1transition,orpresettinganycounters. 3. Enabletheinterrupt. 4. Beforetheinterruptserviceroutine,disableallinterrupts.Thisstepisnecessarytopreventtheinterrupt serviceroutinefrombeingcontinuallyre-triggeredandwindingupinanendlessloop. 5. Theinterruptserviceroutineitself. Let’sseehowthisworksinpractice.
188
InterruptsandTimersinMBasic Program10-1 Configureyour2840DevelopmentBoardasshowninFigure10-1. SwitchSW1isanynormallyopenmomentarycontactswitch.We’ll useaninterrupttobrieflyflashtheLEDwheneverSW1isclosed, eventhoughtheprogramisinthemiddleofmathematicalcalculations.ClosingSW1triggersanEXTINT(changeinpinB0)interrupt andwillinvokeasimpleISRtoflashtheLED. ;Program10-1 ;Elementsofaninterruptprogram ;Constants ;---------InputPin LEDPin ;Variables ;--------i Var j Var k Var
Figure10-1:Program10-1connections. Con Con
B0 B2
;LEDconnected
Byte Byte Word
Initialization ;--------------;SetLEDandflashforatest OutputLEDPin HighLEDPin Pause250 LowLEDPin ;[1]LinkInterrupttoISR ;------------------------OnInterruptExtInt,CloseSwitch ;[2]Setupanyinterruptoptions ;------------------------------SetExtIntExt_H2L ;[3]Enabletheinterrupt ;-----------------------EnableExtInt Main Fori=0to255 Forj=0to255 k=i*j Next;j LowLEDPin Next;k GoToMain ;[4]Complilerdirectivetodisableinterrupts ;---------------------------------------------DisableExtInt ;[5]TheInterruptServiceRoutine CloseSwitch ;---------- HighLEDPin Pause250 LowLEDPin Resume End
189
Chapter10 Afterwiringupthecircuit,runProgram10-1.YoushouldseetheLEDlightbrieflywheneveryoupressthe buttononswitchSW1.Let’sseehowProgram10-1works. Initialization ;--------------;SetLEDandflashforatest OutputLEDPin HighLEDPin Pause250 LowLEDPin
First,weverifythattheLEDflashesbygivingitabriefon/offatinitialization. Now,let’sseehowProgram10-1followsourfive-steptemplate. ;[1]LinkInterrupttoISR ;------------------------OnInterruptExtInt,CloseSwitch
Step1—ThefirststepinthetemplateistoassociatetheinterruptidentifierwiththeISRthroughtheOnInterruptprocedure. MBasic’sOnInterruptproceduretakestwoarguments: OnInterrupt
InterruptSource,Label
InterruptSource—istheinterruptidentifierfromthetableprovidedabove.Itidentifiesthesourceofthe interrupttobeassociatedwiththeISR.InProgram10-1,theinterruptsourceisExtInt. Label—Thenameofthelocation(theISR)towhichprogramexecutionjumpsinwhenanInterruptSourceinterruptoccurs.YouwillnormallystructuretheISRsimilartoasubroutine,exceptinsteadof endingwithaReturn,anISRterminateswithaResumestatement.WhentheISRfinishesrunning, programexecutionreturnstothepointitwaswhentheinterruptwastriggered.InProgram10-1,the ISR’slabelisCloseSwitch. ;[2]Setupanyinterruptoptions ;------------------------------SetExtIntExt_H2L
Step2—Thesecondstepistosetupanyoptionsfortheinterrupt.Theinterruptweuse,EXTINT,issetup withtheSetExtIntprocedure. SetExtIntMode
Mode—hastwopermittedvalues: Ext_H2L—theinterrupttriggersonalogichightolowtransition;or Ext_L2H—theinterrupttriggersonalogiclowtohightransition. SinceSW1isnormallyopen,pinB0willbeheldhighbypullupresistorR1.WhenSW1isclosed,pinB0 willdroptologic0.Hencewewilltriggertheinterruptonahigh-to-lowtransitionandaccordinglyusethe statementSetExtIntExt_H2LtosetupExtInt. ;[3]Enabletheinterrupt ;-----------------------EnableExtInt
Step3—NextweactivatetheinterruptwiththeEnablefunction.Untilaninterruptisenabled,itdoesnot function;theinterrupteventmayoccurbuttheISRwillnotbeexecuted.
Enable{InterruptSource}
IfweuseEnablewithoutanyinterruptsource,allinterruptsareenabledforallcodecompiledaftertheEnablefunction.IfweaddtheInterruptSource,thenonlythatparticularinterruptsourceisenabled.Since we’veusedEnableExtInt,onlytheExtIntwillbeactive. Main
Fori=0to255 Forj=0to255
190
InterruptsandTimersinMBasic k=i*j Next;j LowLEDPin Next;k GoToMain
Tosimulateaprogramperformingothertasks,weusetwoFor…Nextloopstocomputethewordlength productoftwobytevariables. ;[4]Complilerdirectivetodisableinterrupts ;---------------------------------------------DisableExtInt
Step4—Next,wedisabletheExtIntusingtheDisablefunction. Disable{InterruptSource}
UsedwithouttheInterruptSourceargument,Disableistreatedasacompilerdirective,anditdeactivatesallinterruptsforcodecompiledaftertheDisablestatementuntilanEnabledirectiveisreached. ThisparticularprogramwillfunctionequallywellwithouttheDisablecommand,butthat’snotgenerally true.Insomecases,theISRwillgetcalledoverandoveragain,whichwilleventuallycauseMBasic’sinternalstacktooverflow,therebycrashingyourprogram.Hence,we’llalwaysusetheDisablefunction. ;[5]TheInterruptServiceRoutine CloseSwitch ;---------- HighLEDPin Pause250 LowLEDPin Resume
Step5—ThefinalstepistowritetheISR.Remember,theISRendswithaResumestatement,notaReturn statement.TheISRinthiscaseflashestheLEDonfor250ms. Program10-1A Whenyoupresstheswitch,theLEDilluminateswithnoperceptiblelagtimetothehumaneye.Thisis becausenoneoftheMBasicstatementsbeingexecutedinthemainprogramlooprequiremorethanafew hundredmicrosecondstoexecute.Whentheinterruptistriggered,anyMBasicstatementbeingexecuted continuestorunandtheISRisnotcalleduntilthethencurrentlyexecutingstatementcompletes.Thelag timebetweentheinterruptactionandstart-of-executionfortheISRisoftencalledlatency.Let’smodify Program10-1byaddingaPause1000statementaftereachmathcalculation: Fori=0to255 Forj=0to255 k=i*j Pause1000 Next;j LowLEDPin Next;k GoToMain
SavethisasProgram10-1A.Runitandpresstheswitchbutton.Whathappens?Youpresstheswitchbutton andaftersomeperceptibledelay,theLEDilluminates.ThedelaybetweenbuttonpressandLEDilluminationdependsonwhichstatementisexecutingwhereyoupressthebutton.Ifyouareveryfortunate,you pressthebuttonwhileoneoftheindexingstatementsortheproducti*jisbeingcalculated,andtheLED appearstoilluminateinstantaneously.However,thesestatementsrequireonlyintotalafewhundredmicrosecondsorlesstoexecute.Accordingly99.9%ofthetimewhenyoupressthebutton,thePause1000 statementisbeingexecuted.Theaveragelatencyyouwillseeisthereforeabout500ms,andtheworst-case is1000ms.
191
Chapter10 Program10-1B Let’sseetheeffectofonemorechange.DeletethePause1000statementweaddedandreverseExtInt’s triggersensebychangingtheinterruptsetupprocedureto: SetExtIntExt_L2H
We’renowtriggertheinterruptonthelow-to-hightransition.Weexpect,therefore,toseetheLEDilluminatewhenwereleasetheswitch,notwhenwepressit. Whathappens?WhenImadethischange,theLEDilluminatedtwice;oncewhenIpressedtheswitchand thenagainwhenIreleasedtheswitch.What’sgoingonhere?It’souroldfriend,switchbounce,atwork. RememberwhatwelearnedinChapter4?Mechanicalswitchcontactsdon’tcleanlyopenandclose;rather theymayexperiencedozensofveryshortdurationopen/closeperiodsuntilthecontactsstabilizeintheopen orclosedposition.Ifyoudon’tbelieveme,lookatFigure4-11again.Whenwepresstheswitchbutton,its contactsdonotcleanlymakeorbreak.RatherSW1’scontactsbouncecausingRB0toexperienceseveral high-low-high-low-high-lowtransitionsuntilthecontactsstabilizeclosed(low).Eventhoughthesebounces mayseemshortbythestandardsofhumansenses,theymorethanlongenoughtotriggeraninterrupt. Whydidn’tweseemultipleflasheswhenweranProgram10-1then?Mostswitchbounceoccursonmake, notbreak.AtleastwiththeparticularswitchIused,thebreakactionwasclean,withoutbounce.HenceoperatingtheswitchwithProgram10-1producesonlyoneflash,uponswitchclosure.Dependinguponaswitch tocleanlymakeorbreakis,however,notgoodpracticeandapracticaldesignshouldincludedebounce measures. Program10-2 Let’slookattheotherPort Binterrupt;RBINT,or interruptonchangeofRB4, RB5,RB6orRB7.AcommonuseofRBINTistoread arotaryencoder,solet’s seehowthisisdone.Figure 10-2showstheconfigurationrequiredforProgram 10-2.Figure10-2isidentical withFigure6-10and,for thatmatter;Program10-2is identicalwithProgram6-3. Ifyou’vealreadyreadChapter6andfullyunderstand Figure10-2:Program10-2connections. howProgram6-3works, youmayskipouranalysisofProgram10-2.We’llusethesameCTSmodel288T232R161A2two-bitrotary encoderthatwestudiedinChapter6. Program10-2readsarelativerotaryencoderandwritesastepvaluetotheserialport.Rotationclockwise increasesthestepvaluewhilecounterclockwiserotationdecreasesit.TwoLEDsshowtherotationdirection aswell.TheRBINTinterruptisexecutedwheneverthevalueofpinsRB4,RB5,RB6orRB7changes.A changeonanypin,either1→0or0→1triggersanRBINTinterrupt.AswelearnedinChapter6,everystep rotationoftheencodershaftchangesoneoutputbit.
192
InterruptsandTimersinMBasic Direction
↑
B4 0 1 1 0
B5 0 0 1 1
Direction
↓
Hence,everytimetheencodershaftrotatestoanewposition,B4orB5changesstate,andanRBINTistriggered. SinceProgram10-2duplicatesProgram6-2,wewillnotprintitagain.Ifyouneedalistingtofollowwhile readingtheanalysis,refertoProgram6-2orprintProgram10-2fromtheCD-ROMprogramfile. We’veextensivelyanalyzedthepollingversionofthisprograminChapter6,sowe’llconcentrateonlyonits interruptfeatures. OnInterruptRBINT,ReadEncoder EnableRBINT Main ;-------------GoToMain
Youshouldrecognizethefirstthreestepsofourstandardizedinterrupttemplate: Step1—UseOnInterrupttolinktheoccurrenceoftheRBINTtotheISRReadEncoder. Step2—Setanyoptionsfortheinterrupt.RBINThasnooptions,soStep2doesnotexist. Step3—Enabletheinterrupt,viatheEnableprocedure. Now,let’slookattheremainingtwosteps. Disable ReadEncoder CurVal=(PortB&%00110000)>>4 IfCurVal<>OldValThen BranchCurVal,[S0,S1,S2,S3] EndIf AfterBranch Resume
Step4—We’vedisabledinterruptsthroughtheglobalcompilerdirectiveDisable,withoutanyinterrupt argument.ThismeansthatallinterruptsaredisabledforcodebelowtheDisablestatement.Inthis simpleprogram,that’sacceptable.Inacomplexprogramwithmultipleinterruptsenabled,youwould likelywishtoonlydisabletheRBINTinterruptduringtheISR,whichyoumayaccomplishbyinvoking DisableRBINT. Step5—istheISRitself,whichmustconcludewithaResumestatement. Let’stakeaquickpeakathowtheISRfunctions,andwe’lldiscoveronequirkoftheRBINTinterrupt. ReadEncoder CurVal=(PortB&%00110000)>>4 IfCurVal<>OldValThen BranchCurVal,[S0,S1,S2,S3] EndIf AfterBranch Resume
ToreadpinsB4andB5,wereadallPortBpins;thenmaskallbitsbutthoseassociatedwithB4andB5with the&%00110000operatorandthenshifttheresultfourplacestotheright.Theresultistheequivalentof %B5B4,yieldinganumberthatcyclesfrom0through3astheencoderchangesfromonepositiontoanother. (Don’tforgetthattheparenthesesaroundthelogicalANDoperationisrequired,astheANDoperatorislower precedencethantheshift“>>”operator.)
193
Chapter10 Thequirkisthatinordertodeterminewhetherornottogenerateaninterrupt,thePIC’shardwarecompares thestatusofpinsB7…B4withaninternallystoredcopyofpinsB7…B4values.Ifthecurrentvaluediffers fromthestoredvalue,amismatchisdetectedandtheRBINTinterruptisissued.Somehow,therefore,we mustgetthePICtodiscardtheoldstoredcomparisonvalueandreplaceitwiththenewpost-changevalue forpinsB7…B4.ThereisnoexplicitassemblerorMBasicinstruction“refreshthecomparisonstore.” Rather,thisisdoneautomaticallywheneverPortBisread.IntheReadEncoderISR,thestatementCurVal =(PortB&%00110000)>>4causesPortBtoberead.In99.9%ofthecodeyouwillwrite,anRBINT ISRreadsPortBandeverythingworksexactlythewayit’ssupposedto.However,youmayrunacrossthe oddapplicationwhereyoudon’tcareabouttheparticularvalueofpinsB7…B4.Forexample,youmight connectthesefourpinstofoursafetyswitchessothatifanyaretrippedtheassociatedRBINTISRshuts downamotorwithouteverreadingPortB.Inthiscase,thenewswitchsettingswillnotbeupdatedinthe PIC’sinternalRBINTcomparisonstoreandthecodemaynotworkthewayyouthinkitshould.
Timers Figure10-3depictsasimplified,generictimermodule.The 16F87x/87xAseriesPICsincludethreetimermodules,each differentfromtheother,butsharingcertaincommonfeatures illustratedinFigure10-3.We’llgothroughthegenerictimer andthenfocusuponthe16F87x’sthreetimermodules.The 16F87x’stimersarerepresentativeofthetimersfoundinother mid-rangePICs,sowhatwelearninthischapterisnotlimited tothe16F87x/87xAfamily. Let’sfirstconsidertheterm“timer.”Itmeans,inthedictionarysense,adeviceformeasuringtime,oradevicethatcauses actionstobetakenatcertaintimes.APIC’stimersarecapable, withsoftwaresupport,ofbothfunctions.But,ofcourse,aPIC hasnointernaltimepiece;ratherithaseitheraninternalor Figure10-3:Generictimermodule. externaloscillator.Todeterminethetimethatelapsesbetween eventsAandB,thereforerequiresusto(a)knowthedurationofoneoscillatorpulse,td,and(b)tocountthe numberofoscillatorpulses,N,thatoccurbetweeneventsAandB.TheelapsedtimeA-BisthenNtd.Consequently,althoughoftencalleda“timer,”theliteraturemoreaccuratelyreferstothesemodulesandcertainof theircomponentsas“counters.”And,that’swhattheydo;theycountinputevents.Iftheinputeventsoccur atregularintervals,wemayeasilyconvertdiscretecountstoelapsedtime.But,ofcourse,wemightjustas easilyusethecountertodeterminehowmanytimesaswitchisclosed. Ourgenerictimerconsistsofsixcomponents,and,ofcourse,anyparticulartimermaynothaveallofthese componentsoralltheoptionsforanycomponent: Inputsignal—Thecountersectionmusthavealogiclevelinputsignal.Threepossiblesourcesareavailable: (a)thePIC’sclocksignal;(b)anexternalsignalappliedtoaninputpin;or(c)asecondinternaloscillatorwithanexternalcrystal.IfthePIC’sinternalclockisused,thecounterinputsignalistheclock frequencydividedbyfour—thatis,thePIC’sinstructioncycletime,usuallycalledFosc/4. Prescaler—Toprovidemoreflexibility,theinputsignalrunsthroughaprescaler.Aprescalerisapredivider, forexample,iftheprescalerissettodividebyfour,ittakesfourinputcyclestoproduceoneoutput cycletothecounter.Theprescaledivideratioissoftwaresettableandincludesa1:1—thatis,noextra division,setting.
194
InterruptsandTimersinMBasic Counter—Thecounterincrementsonecountforeveryprescaleroutputpulse.Countersmaybeimplementedas8-bitor16-bitdevices.Thecounterisaddressableandmaybereadorwrittentolikeanybyteor wordvariableinMBasic.Writingtothecounterisusuallycalledpreloading. Comparator—Acomparatorisaregister,whichmaybewrittentoinMBasic.Whenthecountervalue equalsthecomparatorvalue,thecounterisresetto0. Postscaler—Theoutputofthecountersectionmaygotoapostscaler.Apostscalerworksjustlikeaprescaler,exceptitsinputisadvancedonepulseeverytimethecounterisresetto0.Thepostscalerdivision ratioisalsosoftwaresettableandcanbesetto1:1,effectivelybypassingthepostscaler. InterruptSource—Despitethedifferencesamongthe16F87x/87xA’sthreetimers,thesamecondition— timeroverflow—causestheirassociatedinterrupttobeissued.Aswewillsee,overflowmayinclude postscalerdivision. Let’scomparethe16F87x/87xA’sthreetimers.Microchipidentifiesthethreetimersastimers0,1and2: Parameter MBasicSet-upFunction MBasicInterruptName
InputClockSources
InputOptions Prescaler? PrescaleRatios Postscaler? PrescaleRatios CounterRegisterLength CounterRegisterName (Read&Write) Howtoget“shortcount”
Timer0 SetTmr0 TMR0INT
Timer1 SetTmr1 TMR1INT
•FOSC/4 •RA4(external) •WatchdogTimer
TMR0 PreloadTMR0
Timer0isalwayson;Don’t enableinterruptifnot needed
InterruptCondition
Overflow(TMR0goesfrom $FFto$00) Sharesprescalerwith watchdogtimer
•FOSC/4 •RC0(external) •SecondOscillator(RC0-
•FOSC/4
Synchronousor asynchronousmode(implicit synchronousforFosc/4)
None
Yes
Yes
1,2,4&8:1
1,4&16:1
No N/A 16-bits Tmr1H&Tmr1Lforhigh andlowbytes PreloadTmr1H&Tmr1L (Butalsoseecompare mode) Off:SetTmr1TMR1Off On:Anyotherconstant Or: On:Tmr1on=%1 Off:Tmr1on=%0 Overflow(TMR1Hgoes from$FFto$00) Canbeusedinconjunction withCompareCCP1or CCP2functions
Yes 16ratios,from1:1to16:1 8-bits
RC1)
(Whenexternalinput) •Incrementonhigh-to-low •Incrementonlow-to-high Yes 9ratios,from1:1through 1:256 No N/A 8-bits
TurnCounteron/off
Notes
Timer2 SetTmr2 TMR2INT
195
TMR2 Loadcomparatorwithvalue; Timer2resetswhencount equalscomparator Off:SetTmr2TMR2Off On:Anyotherconstant Or: On:Tmr2on=%1 Off:Tmr2on=%0 Overflowofpostscaler ForsomereleasesofMBasic, Timer2constantsarewrong
Chapter10 Toselectfromamongthevariousprescaler,postscalerandinputsourceoptions,youuseappropriatetimer setuplibraryconstant,asMBasicprovides,astheargumenttothetimer’ssetupfunction.Therearedozens ofsetupconstants,sowewon’ttryandgothroughthem,exceptaswemayuseaparticularvalueinprogramming.PleaserefertotheMBasicUser’sGuideforthespecificconstantidentifiers. Wemayusetimerswithorwithoutinterrupts.We’llfirstlookatanapplicationwithoutaninterrupt. Program10-3 Let’suseTimer1tomeasuretheexecutiontimeofvariousMBasicstatements.YoumaykeepthesamewiringconnectionasshowninFigure10-2. Ouralgorithmissimple;turntimer1onimmediatelybeforethestatement(s)wewishtotime;turnitoffimmediatelyafterthestatement(s)finishexecuting.Wethenreadtimer1’scounterandmultiplyitbythetime percounter“tick.” ;Program10-3 ;UseTimer2forexecutiontime ;Constants ;---------EnabledCon StoppedCon
%1 %0
;Variables ;-------------i Var j Var k Var Value Var
Byte Byte Word Word
;Initialization ;-------------EnableHSerial SetHSerialH115200 ;Setfor8:1prescale ;with20MHzthisyields1.6us ;pertimertick. SetTmr1Tmr1Int8 Main Tmr1on=Stopped Tmr1H=0 Tmr1L=0 Tmr1on=Enabled Fori=1to100 j=i/2 k=i*j Next Tmr1on=Stopped Value.LowByte=Tmr1L Value.HighByte=Tmr1H HSerOut[“Ticks:“,DecValue,13] Pause100 GoToMain End
Let’sseehowProgram10-3works. ;Constants ;---------EnabledCon StoppedCon
%1 %0
196
InterruptsandTimersinMBasic Forbetterreadability,wedefinetwobitconstantstousewithTmr1On: ;Initialization ;-------------EnableHSerial SetHSerialH115200 ;Setfor8:1prescale ;with20MHzthisyields1.6us ;pertimertick. SetTmr1Tmr1Int8
WefirstmustsetupTimer1.Sincewewishtomeasureelapsedtime,themostconvenientinputclockisthe Fosc/4sourcefromthePIC’sinternalclock.Iusea20MHzresonatorinmydevelopmentboards,soeach Fosc/4clockpulse(whichwewillcall“ticks”)represents200ns.Oneoscillatorpulseis50ns: 1 1 tOSC = = = 50 × 10 −9 6 F × 20 10 OSC HenceFosc/4isfourtimesoneoscillatorperiod,or200ns. Whichpreselectordivisionratioshallweuse?Toselectthedivisionratio,wemustknow,roughly,thetime durationwewishtomeasure.We’regoingtomeasure100loopsthroughaFor…Nextloop,witheachloop havingtwointegermathoperations.Basedonexperience,weestimateeachloopcyclewilltakeabout750µs. Tomeasure100loopcyclesrequiresustomeasure75ms.Timer1hasa16-bitcounter,sowecancounta maximumof65535ticks.Tocountupto75ms,eachtick’sdurationshouldbeabout75ms/65535(1.14µs). Ifourprescaleratiois4:1,thetickdurationis0.800µs(4times200ns),whichistooshort.An8:1prescale ratiogives1.6µspertick,whichmeetsourrequirements. Main
Tmr1on=Stopped Tmr1H=0 Tmr1L=0
Weturnthetimeroffandclearbothbytesofthecounter.
Tmr1on=Enabled Fori=1to100 j=i/2 k=i*j Next Tmr1on=Stopped
Weturnthecounteron,run100cyclesthroughtheloop,andthenturnthecounteroff. Value.LowByte=Tmr1L Value.HighByte=Tmr1H HSerOut[“Ticks:“,DecValue,13] Pause100 GoToMain
Now,wereadthecountervalueandsentitthroughtheserialinterface.Notethatweareabletoreadand writetoTimer1’scounterjustasifitwasanMBasicvariable.This,ofcourse,isbecausethereisnostructuraldifferencebetweenauser-declaredvariableandthePIC’sinternalregister.Wedon’tevenhavetoworry aboutdeclaringthesevariables,asMBasic’scompileralreadydefinesthemforus. Inordertogetthemostinformationoutofourtimer,we’llrunseveralmodifiedversionsofProgram10-3, commentingoutvariousstatementstodetermineindividualexecutiontimes. MBasicCode Tmr1on=Enabled ;Fori=1to100 ;j=i/2 ;k=i*j ;Next Tmr1on=Stopped
Output Ticks:25
Analysis Thistimerepresentstheoverheadinstartingandstopping Timer1.Wewillsubtractthisoverheadfromthelater readingstocalculateaccuratestatementexecutiontimes.
(40.0µs)
197
Chapter10 MBasicCode Tmr1on=Enabled Fori=1to100 ;j=i/2 ;k=i*j Next Tmr1on=Stopped Tmr1on=Enabled Fori=1to100 j=i/2 ;k=i*j Next Tmr1on=Stopped
Output Ticks:10846 (Aftersubtracting overhead:10821 ticks,or17314µs) Ticks:28539 (Aftersubtracting theexecution timeforthebare loop:17693ticks, or28309µs) Ticks:42101 (Aftersubtracting theprior executiontime: 13562ticks,or 21699µs)
Tmr1on=Enabled Fori=1to100 j=i/2 k=i*j Next Tmr1on=Stopped
Analysis TheFor…Nextloop,withnooperationsinsidetheloop,takes 17,314µstoexecute100times.Eachloopcycle,thereforeis 173µs.
Theincreasedexecutiontimebyaddingbackinthej=i/2 statementis28309µs.Sincethej=i/2statementisexecuted 100times,theexecutiontimeforonej=i/2statementis283µs.
Theincreasedexecutiontimefromaddingbackthek=i *jstatementis21699µs.Sincethek=i*jstatementis executed100times,theexecutiontimeforonek=i*j statementis217µs.
Wenowhavedeterminedanaccurateexecutiontimeforeachstatement: Fori=1to100 j=i/2
283µs
k=i*j
217µs
173µs(loopstructureonly)
Next
TheseexecutiontimevaluesareforMBasicversion5.2.1.1.Version5.3.0.0executesafewpercentfaster. Fornow,we’llignoretheerrorsthatarisefromthefiniteexecutiontimeofthestatementsturningtimer1on andoff.We’llseeawayofcompensatingforthiserrorinChapter14. Program10-4 Let’sseehowtimersandinterruptsworktogether.We’llreusethecircuitofFigure10-2butdon’tworryif youdon’thavearotaryencoder,aswon’tuseit.Program10-4usestimer1toflashanLEDbrieflyonce every100ms,andtimer2toilluminateasecondLED,onfor1000msandofffor1000ms. ;Program10-4 ;TwotimerstoflashLEDs ;Constants ;---------Enabled Stopped
Con Con
%1 %0
;Timer2correctedconstants ;--------------------------T2Post1 Con %00000000 T2Post2 Con %00001000 T2Post3 Con %00010000 T2Post4 Con %00011000 T2Post5 Con %00100000 T2Post6 Con %00101000 T2Post7 Con %00110000 T2Post8 Con %00111000 T2Post9 Con %01000000 T2Post10 Con %01001000 T2Post11 Con %01010000 T2Post12 Con %01011000
198
InterruptsandTimersinMBasic T2Post13 T2Post14 T2Post15 T2Post16
Con Con Con Con
%01100000 %01101000 %01110000 %01111000
T2Pre1 T2Pre4 T2Pre16
Con Con Con
%00000100 %00000101 %00000111
;Variables ;---------PreLoad i
Var Var
Word Byte
;Initialization ;-------------SetTmr1Tmr1Int8 ;PreLoadbasedonmeasuredduration PreLoad=3072 OnInterruptTmr1Int,Flash1 ;Calculatedfor1secondwith*128 SetTmr2T2Post16+T2Pre16,153 OnInterruptTmr2Int,Flash2 i=0 OutputA1 LowA1 Enable Main GoToMain Disable Flash1;ISRforTimer1 ;----- ;havetoreloadeverytime Tmr1on=Stopped Tmr1H=PreLoad.HighByte Tmr1L=PreLoad.LowByte Tmr1on=Enabled HighA0 Pauseus300 LowA0 Resume Flash2;ISRforTimer2 ‘---- ;addsanextradivideby128 ;noneedtoreset i=i+1 PortA.Bit1=i.Bit7 Resume End
We’llanalyzeProgram10-4functionally,notsequentially.Let’sfirstlookattimer2. ;Calculatedfor1secondwith*128 SetTmr2T2Post16+T2Pre16,153 OnInterruptTmr2Int,Flash2
Timer2’ssetupfunctionSetTmr2requirestwoarguments: SetTmr2Mode,Period
Mode—isaconstantorvariablethatturnsthecounterofforturnsitonandsetstheprescaleandpostscale ratios.Aswe’veseen,timer2has16possiblepostscaleratios,from1:1to16:1,andthreepossibleprescaleratios,1:1,4:1and16:1.SomeearlierversionsofMBasichaveerrorsinthetimer2modelibrary constants,sowedefinecorrectedconstantsintheConstantssectionofProgram10-4. 199
Chapter10 ;Timer2correctedconstants ;--------------------------T2Post1 Con %00000000 T2Post2 Con %00001000 T2Post3 Con %00010000 T2Post4 Con %00011000 T2Post5 Con %00100000 T2Post6 Con %00101000 T2Post7 Con %00110000 T2Post8 Con %00111000 T2Post9 Con %01000000 T2Post10 Con %01001000 T2Post11 Con %01010000 T2Post12 Con %01011000 T2Post13 Con %01100000 T2Post14 Con %01101000 T2Post15 Con %01110000 T2Post16 Con %01111000 T2Pre1 T2Pre4 T2Pre16
Con Con Con
%00000100 %00000101 %00000111
Weusetheseconstantsinpairs,addedtogether.TheT2Postxxseriesconstantsdefinethepostscaledivide ratio,from1:1(T2Post1)through16:1(T2Post16).TheT2Prexxseriesconstantsdefinetheprescale divideratio,whichis1:1(T2Pre1),4:1(T2Pre4)or16:1(T2Pre16).Atimer2configurationconstantis thusoftheformT2Postxx+T2Prexx.(MBasic’slibraryconstantTmr2Off,whichdisablestimer2,is correct.)Ifwewishtosetthepostscaleratioat8:1andtheprescaleratioat4:1,therequiredmodeconstant isT2Post8+T2Pre4. Period—Timer2’smoduleincludesacomparator,whichcomparesthecounter’svaluewithPeriod.When thecountervalueequalsPeriod,thecounterresetsto0.Sincetimer2hasan8-bitcounter,Period isabytelengthvariableorconstant.Onceset,Perioddoesnotchangewhentimer2’scounterresets. Rememberthattimer2’sinterrupt,Tmr2Int,istriggerednotuponcounterreset,butratheruponpostscaleroverflow.Hence,timer2’sinterruptintervalis: 4 • N PRE • N POST • N PERIOD t2 = FOSC
t2isthetimebetweeninterrupts NPREistheprescaleratio NPOSTisthepostscaleratio NPERIODisSetTmr2’sPeriodargument
Let’sseehowweselectNPRE,NPOSTandNPERIOD.Ourobjectiveistousetimer2toflashanLEDina1000ms on,1000msoffcycle.Whatratiosprovidethistimingsequence?First,let’sdeterminetimer2’sabsolute slowestinterruptperiod.Theslowestinterruptperiodcorrespondstothemaximumprescaleandpostscale values,andthemaximumperiodargument,16:1,16:1and255,respectively.Timer2’smaximuminterrupt period,baseduponthe20MHzresonatorI’veinstalledinmy2840DevelopmentBoard,is:
t2 =
4 × 16 × 16 × 255 = 13.056 × 10 −3 20 × 10 6
Sincetimer2’smaximuminterruptperiodisonly13ms,it’sapparentwecan’trelysolelyupontimer2’s interruptstoilluminateandextinguishtheLED.Insteadweusetimer2interruptstoincrementavariable andcontroltheLEDbaseduponthatvariable’svalue.TheISRcalledwhentimer2issuesaninterruptis
200
InterruptsandTimersinMBasic Flash2: Flash2;ISRforTimer2 ‘---- ;addsanextradivideby128 ;noneedtoreset i=i+1 PortA.Bit1=i.Bit7 EndIf Resume
InsteadofusinganIf…Then…EndIftest,wecanuseafasterprocess,bylettingpinA1’svalueequal i.Bit7.i.Bit7hasvalue%0untiliequals128whenitbecomes%1andstaysat%1untilirollsoverand becomeszero.HencetheLEDattachedtoA1togglesbetweenonandoffevery128timesFlash2iscalled. Inordertomaketheonandoffperiodsequalto1second,Flash2mustbecalled128timespersecond,or every7.8125ms.Inorderfort2tobe7.8125ms,timer2’stotaldivisionratiomustbe:
t2 • FOSC 7.8125 × 10 −3 • 20 × 10 6 = = 39063 4 4 NTOTAListheproductNPRE*NPOST*NPERIOD
We’llsetNPREandNPOSTas16.Hence,wedetermineNPERIOD:
NTOTAL =
39063 = 152.59 16 • 16 Since Periodmustbeabyteinteger,we’llsetPeriodat153. But,canwedobetter?Let’slookatalllegitimatecombinationsofNPOSTandPeriod: N PERIOD =
NPOST
Required Period
Integer Period
ResultingInterruptPeriod (ms)
Error
1
2441.4063
2441
7.811
0.017%
… 9
271.26736
271
7.805
0.099%
10
244.14063
244
7.808
0.058%
11
221.94602
221
7.779
0.426%
12
203.45052
203
7.795
0.221%
13
187.80048
187
7.779
0.426%
14
174.38616
174
7.795
0.221%
15
162.76042
162
7.776
0.467%
16
152.58789
152
7.782
0.385%
SincePeriodisabytevalueitcannotexceed255,whichmeansthatNPOSTcan’tbelessthan10,soI’ve omittedmostofNPOSTvaluesresultinginillegalPeriodvalues.(Thetablecalculatesthezeroerror,floatingpointvalueforPeriod,andthendeterminesthecorrespondingintegervalue.Theerrorcalculationsare basedupontheintegervalue.) OurinitialselectionNPOST=16andPeriod=152isn’tthebestcombination.Wecanreducethetimingerror from0.385%to0.058%,bysettingNPOSTto10andPeriodto244.ThecorrespondingSetTmr2statementis: SetTmr2T2Post10+T2Pre16,244
ForflashinganattentiongettingLED,thiserrorimprovementisimmaterial,butmanytasksdemandgreater accuracy. Let’sseehowweusetimer1. 201
Chapter10 OurobjectistobrieflyflashanLED10timesasecond,correspondingtoaninterruptintervalof100ms. We’lluseFOSC/4asTimer1’sclocksource,soeachtickis0.2µs.Wecalculatetherequireddivisionratioas 100ms/0.2µs,or500000:1.Sincetimer1hasa16-bitcounter,itsmaximumdivisionratiois65535:1,sowe mustuseitsprescalertoachieve500000:1. Ifwesettimer1’sprescalerfor8:1division,therequiredcounterdivisionratiois500000/8,or62500.Setting timer1’scounterdivisionratiorequiresadifferentprocessthanusedwithtimer2.Wepreloadtimer1with astartingvalueandtimer1countsupfromthatvalueuntilitrollsoverto$0000andtriggerstheTmr1Int interrupt.Unfortunately,thepreloadislostwitheveryrolloverandmustbere-enteredaftereveryinterrupt.As welearnedearlier,inMBasicwecanbothreadandwritethetimer1’s16-bitcounterregister,usingthelibrary declaredbytevariablesTmr1H(highbyte)andTmr1L(lowbyte).Hence,topreloadthecounterwiththeword preloadvaluePreLoad,wesetTmr1H=PreLoad.HighByteandTmr1L=PreLoad.LowByte. Therequiredpreloadvaluefortimer1isthus:
N PRELOAD = 65536 − N DIVISION NPRELOADisthevaluetobepreloadedintothetimer1’scountersection NDIVISIONisthedesireddivisionratiofortimer1’scounter.
Sinceourdesireddivisionratiois62500,wecalculatethepreloadvalueas65536-62500,or3036. Let’slookatthetimer1relatedpartsofProgram10-4. SetTmr1Tmr1Int8 ;PreLoadbasedonmeasuredduration PreLoad=3072 OnInterruptTmr1Int,Flash1
TheISRisFlash1: Flash1;ISRforTimer1 ;----- ;havetoreloadeverytime Tmr1on=Stopped Tmr1H=PreLoad.HighByte Tmr1L=PreLoad.LowByte Tmr1on=Enabled HighA0 Pauseus300 LowA0 Resume
Whyuseapreloadof3072whenwecalculated3036asthecorrectvalue?LookatFlash1.Thefirstaction stopstimer1andreloadsthecounterregistersTmr1HandTmr1Lwiththepreloadvalue.Then,werestart timer1.Thesestatementsrequiretimetoexecute,andduringtheexecutiontimetimer1isstopped.Hence, ifweuseourcalculatedpreloadvalue3036,timer1willrunslowandtheresultingperiodwillbelonger thandesired. Withapreloadvalueof3036,Imeasuredtheresultingperiodas100.0693ms.Toarriveatthefinalvalue 3072,Ikeptincreasingthepreloadvalueuntiltheperiodwasascloseto100msaspossible.InProgram 10-4,apreloadof3072resultsinameasuredperiodof99.9980ms.Thedifferencebetween3072and3036 correspondsto57.6µs.Someofthedifferencebetweenourtheoretical3036andtheadjustedvaluemay wellcorrespondtoerrorinthe20MHzresonatorinmy2840DevelopmentBoard. Whathappenswheninterruptrequestscollide?AswelearnedinProgram10-3,inMBasicaninterruptis onlyexecutedinbetweenMBasicstatements.However,sincebothFlash1andFlash2arecompiledafter theDisablecompilerdirective,duringtheexecutionofoneISR,thesecondinterruptispostponed.
202
InterruptsandTimersinMBasic
CaptureandCompare Thefinalinterruptproceduresweexaminearethoserelatedtothecaptureandcomparefunctions.Whatare thecaptureandcomparefunctions?Bytheway,“capture”and“compare”aretwoseparatefunctions,not onefunctioncalled“captureandcompare.” ThesefunctionsarepartofthePIC’s“CCP”hardwaremodule,wheretheacronymCCPstandsfor“capture, compareandpulsewidthmodulationfunctions.We’llseehowthePWMmoduleworksinlaterchapters. The16F87x/87xAseriesPICshavetwoCCPmodules,CCP1andCCP2,andeither,orboth,maybeassignedtocaptureorcomparefunctions.However,shouldyouactivatebothCCPmodules,beawarethatthe modulesinteract,asubjectbeyondthescopeofanintroductorytextsuchasthisone.Moreinformationis availableinMicrochip’s16F87xand16F87xAdatasheets,andinitsMidrangeReferenceManual.Module. CCP1istiedtopinC2,whilEmoduleCCP2istiedtopinC1. Capture—Capturemode“captures”orcopiestimer1’scountervalueintothecaptureregisterCCPR1or CCPR2upontheoccurrenceofchangeininputpinstate.Bothare16-bitregisterscomprisedoftwo8-bit halves,CCPRnLandCCPRnH,forthelowandhighbytes,respectively,wherenis1or2.Thepossible eventoptionsare: • Hightolowtransition • Lowtohightransition • Fourthlowtohightransition • 16thlowtohightransition Whentheselectedeventoccurs,timer1’svalueiscopiedandaninterruptisissued,CCP1INTifCCPmodule1isusedorCCP2INTifCCPmodule2isused. Compare—Comparemodemakestimer1worksomethingliketimer2;thevalueoftimer1’scounteriscontinuouslycomparedwiththevalueloadedineitherCCPR1orCCPR2.Whenthecountervaluematches theCCPR1orCCPR2value,oneoffouroptionaleventsoccur: • PinC1(CCPmodule2)orC2(CCPmodule1)isdrivenhigh • PinC1(CCPmodule2)orC2(CCPmodule1)isdrivenlow • PinC1(CCPmodule2)orC2(CCPmodule1)isunchanged • PinC1(CCPmodule2)orC2(CCPmodule1)isunchangedandtimer1isresettozero.IfCCP module2isactive,andiftheanalog-to-digitalmoduleisactive,anA/Dconversionisstarted. Anduponthematchoccurring,aninterruptisissued,CCP1INTifCCPmodule1isusedorCCP2INTifCCP module2isused.
Capture Howmightweusethecaptureinterrupt?Onepossibilityistomeasurefrequencyorperiod.Supposewe haveapulsewaveformconnectedtoaCCPmodule’sinputpinandwesetittocapturetimer1’svalueevery positivetransition:
t1
t2
Timervaluest1andt2permitustocalculatethewaveform’speriod(t2–t1)anditsfrequency,1/(t2–t1). Weobviouslymustbeconcernedwithtimer1overflowwhenwecomputet2–t1. Program10-5 Program10-5readstheperiodandfrequencyofasquarewaveinputsignalappliedtopinC1.Figure10-4 showstheconnectionarrangementforProgram10-5. 203
Chapter10
Figure10-4: ConnectionsforProgram10-5.
OurapproachinProgram10-5maybesummarizedinpseudo-codeas: SetupCaptureinterrupt Initializetimer1&selecttimer1’sprescaler I=0 MainDummyProcedure InterruptHandler I=i+1 Ifiiseventhen Readtimer1andsaveint1 Ifiisoddthen readtimer1andsaveint2 gosubOutputProcedure Resume OutputProcedure Calculatet2-t1 Adjustift2-t1isnegative Period=timer1interval*(t2-t1) Frequency=1/period Outputfrequencyandperiodtoserialport Return
Here’thecodeimplementingthispseudo-code. ;Program10-5 ;Captureoperation ;Constants ;---------UseCCP1 UseCCP2 usPerTick
Con Con Con
%0 ;PinC2 %1 ;PinC1 1.600
;Variables ;----------t1 t2 i t1f t2f fPeriod fFreq
Var Var Var Var Var Var Var
Word Word Byte Float Float Float Float
;Initialization ;-------------EnableHSerial SetHSerialH115200
204
InterruptsandTimersinMBasic ;setupforcaptureonpinC1 SetCaptureUseCCP2,Capture1L2H OnInterruptCCP2Int,DumpPeriod ;turntimer1on SetTmr1Tmr1Int8 i=0 Enable Main GoToMain DisableCCP2Int DumpPeriod ;--------- i=i+1 Ifi.bit0Then GetCaptureUSeCCP2,t1 Else GetCaptureUSeCCP2,t2 GoSubWriteOutput EndIf Resume WriteOutput ;------------ t1f=ToFloatt1 t2f=ToFloatt2 If(t2<t1)Then t2f=t2f+65536.0 EndIf fPeriod=t2f-t1f HSerOut[Dect1,9,Dect2,9,RealFPeriod,9] fPeriod=fPeriod*usPerTick fFreq=1000000.0/fPeriod HSerOut[RealfPeriod,”us”,9,RealfFreq,”Hz”,13] Pause1000 Return End
Weaddthreenewconstantdefinitions.TheUseCCP1andUseCCP2constantsselectwhichCCPmoduleis selected.TheconstantusPerTickisthedurationinmicrosecondsforeachclockpulse,basedonan8:1prescaleratio.Withversion5.3.0.0onward,wemaydefineafloatingpointconstantdirectly.(Earlierversions requiredthe“FLOAT”prefix.). ;Constants ;---------UseCCP1 UseCCP2 usPerTick
Con Con Con
%0 ;PinC2 %1 ;PinC1 1.600
;Initialization ;-------------SetHSerialH115200 ;setupforcaptureonpinC1 SetCaptureUseCCP2,Capture1L2H
WeinitializethecaptureinterruptusingMBasic’sSetCapturefunction: SetCaptureCCPPin,mode
205
Chapter10 CCPPin—isaconstantorvariableselectingwhichofthetwoCCPmoduleswillbeused.IfCCPPin=%0, CCPmodule1(connectedtopinC2inthe16F87x/16F87xAseriesdevices)willbeused.IfCCPPin= %1,CCPmodule2(connectedtopinC1inthe16F87x/16F87xAseriesdevices)willbeused.Tomake rememberingmoduleselectioneasier,wedefinedthetwoconstantsUseCCP1andUseCCP2. Mode—isavariableoraconstantdefiningwhichoffivemodeswillbeoperational.MBasic’slibrarymode constantsare: LibraryConstantName CaptureOff Capture1H2L Capture1L2H Capture4L2H Capture16L2H
Functionality Disablecapturemodule Capturetimer1oneachhigh-to-lowtransition Capturetimer1oneachlow-to-hightransition Capturetimer1everyfourthlow-to-hightransition Capturetimer1every16thlow-to-hightransition
I’vearbitrarilyusedCCPmodule2andselectedcaptureoneverylow-to-hightransition. OnInterruptCCP2Int,DumpPeriod
WelinktheinterrupthandlerDumpPeriodtotheCCP2IntusingMBasic’sOnInterruptprocedure. ;turntimer1on SetTmr1Tmr1Int8
Inordertousethecapturefunction,timer1mustbeturnedon,whichmaybeconvenientlyaccomplished withMBasic’sSetTmr1procedure.I’vesettimer1’sprescalerto8:1.Why8:1?Aswelearnedearlier,with theprescalerset8:1,wecanmeasureupto104ms,correspondingtoaninputfrequencyjustbelow10Hz. BasedonusingonlyMBasicforourinterrupthandler,weexpectexecutiontimeproblemswilllimitourhigh frequencyresponse,soitmakessensetoconcentrateonmeasuringlowerfrequencies. i=0 Enable
Weuseiasanodd/evendeterminantandinitializeitto0. Main GoToMain DisableCCP2Int
ThemainprogramloopisanemptyGoTostatement. Let’snowlookatourinterrupthandler. DumpPeriod ;--------- i=i+1 Ifi.bit0=0Then GetCaptureUseCCP2,t1 Else GetCaptureUseCCP2,t2 GoSubWriteOutput EndIf Resume
WeuseanIfi.bit0Thentesttoalternatebetweencapturingdatatot1andt2.Sinceiincreasesbyone eachtimeDumpPeriodiscalled,i.bit0alternatesbetween%0and%1.Byalternatingbetweent1and t2,wecaptureonecompletecycleoftheincomingwaveform.Uponthesecondcapture,wecallsubroutine WriteOutputtocomputetheperiodandfrequencyofthewaveformandwritetheresulttotheserialport. WriteOutput ;------------ t1f=ToFloatt1 t2f=ToFloatt2
Weconvertthetwotimerreadingstofloatingpointvariablest1fandt2f.
206
InterruptsandTimersinMBasic
If(t2<t1)Then t2f=t2f+65536.0 EndIf
It’spossiblethattimer1hasrolledoverbetweenthetwocaptures.Ifso,thesecondtimervalue,t2,maybe lessthanthefirstsample,t1.Ifthisisthecase,theirfloatingpointdifference(t2f-t1f)willbenegative. Therolloverisfunctionallyequivalenttocarrying65536tothesecondtimervalue.
fPeriod=t2f-t1f
Theperiod,measuredintermsofcounterticks,isthedifferencebetweenthesecondtimervalueandthe first,orintermsofthefloatingpointvalues,t1f–t2f.
HSerOut[Dect1,9,Dect2,9,RealFPeriod,9]
Next,wewritethetwotimerreadingsandthedifferencetotheserialport.
fPeriod=fPeriod*usPerTick
Weconvertfperiodfromtimertickstomicrosecondsbymultiplyingbythenumberofmicrosecondsper tick,heldintheconstantusPerTick.
fFreq=1000000.0/fPeriod
Frequencyisdefinedasthereciprocaloftheperiod,sowecomputethefloatingpointfrequencyfFreqas 1/fPeriod.However,sincefPeriodisinmicroseconds,wemustmultiplyby106toyieldthefrequencyin Hz. HSerOut[RealfPeriod,”us”,9,RealfFreq,”Hz”,13] Pause1000 Return
Lastly,wewritetheperiodandfrequencytotheserialport.ThePause1000limitsupdatestoonceevery secondandthisvaluemaybereducedshouldyoudesiremorefrequentupdates. Withapproximatelya10Hzinputsignalfromafunctiongenerator,weseeareasonablystableresult. 3573 60778 52444 44094 35763 27415
64940 56609 48275 39923 31591 23245
61367.0000000000 61367.0000000000 61367.0000000000 61365.0000000000 61364.0000000000 61366.0000000000
98187.1875000000µs 98187.1875000000µs 98187.1875000000µs 98183.9921875000µs 98182.3906250000µs 98185.5937500000µs
10.1846275329Hz 10.1846275329Hz 10.1846275329Hz 10.1849594116Hz 10.1851253509Hz 10.1847934722Hz
IfoundthatProgram10-5workedwellbetween10Hzand125Hzorso.Weareconstrainedonthelow frequencysidebythecounterlengthandourpreselectorratiochoice.Above125Hz,thereisn’tenoughtime fortheinterruptandoutputprocedurestocompletetheirtasksandtheresultsfail.Itwouldbepossibleto measurehigherinputfrequenciesbycapturingnoteveryinputpulse,butoneforeveryfourinputcycles,or evenoneforevery16inputcycles,usingtheSetCaptureoptionsCapture4L2HorCapture16L2Hmode libraryconstants. Ultimately,however,ourupperfrequencylimitisconstrainedbythespeedofprogramexecutionandthe lowerfrequencylimitbycounter/preselectorcountmaximumvalues. Youmaybethinking“whynotaddcodetotheISRtoresettimer1tozeroatthetimeofthet1interrupt, therebyremovingthet2–t1subtractionanditsassociatedcarrytest”?Goodquestion. Thecapturefunctionisexecutedindependently,bydedicatedhardwareinthe16F87x/87xAdevice.Thus, withoutregardforwhateversoftwaremaybeexecuting,upontheoccurrenceofthedefinedtriggerevent timer1’scountervalueisinstantaneouslycapturedintoaninternalregisterpair.Atthesametime,thecaptureinterruptflagisset.ButMBasicwillnotactupontheinterruptflagandjumptotheISRuntilthecurrent MBasicinstructioncompletes.Butanycodetozerotimer1cannotnotexecuteuntiltheISRruns,soitis
207
Chapter10 subjecttothelatencyproblemwe’vepreviouslydiscussed.Consequently,resettingtimer1tozerointheISR toremovethet2-t1computationintroducesanunknown—andvariable—timeerrorcomparedwithusingthe approachofProgram10-5.ThefunctionGetCapturereadsthesavedtimer1valueandisnottimesensitive,sothelatencyissuesrelatedtoProgram10-5centeraroundwhetherthesecondtriggeringeventoccurs beforethefirsteventprocessingcompletes. However,we’llseeinChapter15thatit’spossibletoremovealmostalllatencyissuesbywritingtheISRin assemblerusingMBasic’sISRASMfeature.IfyouchoosetohandletheISRinassembler,zeroingtimer1 uponthefirstmeasurementisfeasible,butstillunnecessary.
Compare Thefinalinterruptweexamineistiedtothe“compare”elementofthecapture,compareandpulsewidth modulationmodule. Thecomparefunctioncontinuouslymonitorstimer1’scountervalueagainstthe16-bitvalueheldinthe CCPRxregister.EachCCPmodulehasoneregister,soit’spossibletomonitortimer1’scountervalueagainst twodifferentvalues,oneheldinCCP1’sregisterandoneheldinCCP2’sregister.Uponamatch,oneoffour possibleuser-selectedeventstakesplace: • PinC1(CCPmodule2)orC2(CCPmodule1)isdrivenhigh • PinC1(CCPmodule2)orC2(CCPmodule1)isdrivenlow • PinC1(CCPmodule2)orC2(CCPmodule1)isunchanged • PinC1(CCPmodule2)orC2(CCPmodule1)isunchangedandtimer1isresetto0.Additionally,if CCP2isactive,andtheanalog-to-digitalconversionmoduleisenabled,anA/Dconversionisinitiated. Inallfourcases,uponthematch,aCCPxIntinterruptissues—CCP1Int,orCCP2Int,dependingupon whichCCPmoduleisbeingused. MBasicsupportsthecompareoperationwiththefunctionSetCompare,calledwiththreearguments: SetCompareCCPPin,Mode,CompareValue
CCPPin—isaconstantorvariableselectingwhichofthetwoCCPmoduleswillbeused.IfCCPPin=%0, CCPmodule1(connectedtopinC2inthe16F87x/16F87xAseriesdevices)willbeused.IfCCPPin =%1,CCPmodule2(connectedtopinC1inthe16F87x/16F87xAseriesdevices)willbeused.To makerememberingmoduleselectioneasier,wewilldefinetwocorrespondingconstantsUseCCP1and UseCCP2. Mode—aconstantorvariableselectingtheoperationalmode.Fivelibraryconstantsareavailable: LibraryConstantName CompareOff CompareSetHigh CompareSetLow CompareInt CompareSpecial
Functionality Disablecomparemodule. SetsCCPxpinlowuponmatch. SetsCPPxpinhighuponmatch. Setsinterruptuponmatch,butnochangeinCCPxpin. Resettimer1to0andifCCP2isactiveandA/Dis enabled,anA/Dconversionisstarted.
CompareValue—isa16-bit(word)lengthconstantorvariableagainstwhichtimer1iscompared.InMBasicversion05.2.1.1SetComparehasanerrorthatreversesthebyteorder.Thefollowing“workaround” maybeemployeduntilacompilerfixisavailable: SetCompareCCPPin,Mode,CompareValue CCPR1H=CompareValue.HighByte CCPR1L=CompareValue.LowByte
208
InterruptsandTimersinMBasic Program10-6 Let’sseehowwemightusethecomparefeature.Configureyour2840 DevelopmentBoardasshowninFigure10-5. Program10-6willusetheinterruptuponcomparefeaturetoflashan LED.But,moreimportantly,Program10-6showshowwemayuse timer1toprovidethesameinterruptuponpresetvaluefunctionalityas weobservedwithtimer2.Theadvantageofusingthe16-bittimer1, Figure10-5:CircuitforProgram10-7. insteadofthe8-bittimer2,ofcourseisthefargreaterresolutiontimer 1offers. ;Program10-6 ;Comparetest ;Constants ;---------UseCCP1 UseCCP2
Con Con
%0 %1
;Variables ;--------TripPoint
Var
Word
;PinC2 ;PinC1
;Initialization ;-------------TripPoint=31250 SetCompareUseCCP1,CompareSpecial,TripPoint ;linkinterruptwithISR OnInterruptCCP1Int,Flash1 ;turntimer1on SetTmr1Tmr1Int8 EnableCCP1Int Main ;----GoToMain DisableCCP1Int Flash1;ISRforTimer1 ;----- HighA0 Pauseus300 LowA0 Resume End
We’llholdthecomparevalueinthewordvariableTripPoint. ;Variables ;--------TripPoint
Var
Word
Let’ssettheLEDtoflash20times/second,oroneflashevery50ms.Basedonourearlierwork,weknow thatdurationsinthisrangerequireustosettimer1’spreselectorat8:1.Witha20MHzresonator,eachtick is1.6µs.Wenowmaycalculatethecountrequiredfor50ms:
NCOMPARE =
50 × 10 −3 = 31250 1.6 × 10 −6
209
Chapter10 ;Initialization ;-------------TripPoint=31250 SetCompareUseCCP1,CompareSpecial,TripPoint
WesetthevariableTripPointtothedesiredcount,anduseitintheSetCompareCompareValueargument.BecausewehavenoreasontochangethestateofeitherpinC1orC2,wewillusetheCCP1module andCompareSpecialmode.CompareSpecialgivesuswhatwedesire;aCCP1Intinterruptwhenever timer1equalsTripPointanditalsoautomaticallyresetstimer1tozero. ;linkinterruptwithISR OnInterruptCCP1Int,Flash1
WeassociatetheISR,Flash1,withtheCCP1IntinterruptusingOnInterrupt. ;turntimer1on SetTmr1Tmr1Int8 EnableCCP1Int
Ofcourse,don’tforgettosetuptimer1andenabletheinterrupt.Asdecided,weactivatetimer1with8:1 prescale. Main ;----GoToMain
Mainisadummyloop. DisableCCP1Int
Remembertodisabletheinterruptbeforetheinterrupthandler.Inthisprogram,weonlyusetheCCP1Int interrupt,soweneedonlydisableit.Thismaynotbethecaseinyourprograms,sodisableanyapplicable interrupts.Becarefulinthisregard,assomeMBasicprocedures,suchasHSerOutandHSerInuseinterruptsandablanketDisablestatementmaypreventthesefunctionsfromexecuting. Flash1;ISRforTimer1 ;----- HighA0 Pauseus300 LowA0 Resume
Flash1isidenticalwithourearlier“flashtheLED”interrupthandler.
Howdoesitwork?Ifoundtheperiodjumpedbetweentwovalues—49.9352msand49.9142ms,representing65µsand86µsshortofthedesired50.000msperiod,respectively.(Theperiodjumpsbetweentwo valuesdependingonwhereintheMain…GoToMaincycletheinterruptfires.)Basedonthesemeasurements,TripPoint,shouldbeincreasedby47to31297.(Thisvalueisbaseduponanaverageerrorof75µs, correspondingto47ticksof1.6µs/tick.)Asanexperiment,IchangedTripPointto31297andobserved theperiodjumpingbetween49.9981msand50.0192ms.
References [10-1]
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.OfparticularinterestarethePIC16F87xand PIC16F87xAdatasheets.
210
11
CHAPTER
Analog-to-Digital Conversion Theworldisanalog,notdigital,atleastatscalesperceptiblebyhumansenses.Ifyouareaskedthetemperature,youmightrespond“it’s77degrees.”Howeverthetemperaturedoesn’tabruptlyjumpfrom77to 78degrees.Rather,withasufficientlyaccuratethermometer,youmighthavesaid“it’s77.123degrees,”to whichthequestionermightrespond,“no,accordingtomyhigherprecisionthermometer,it’s77.12345degrees.”Intheory,untilwestarttoreachquantumuncertainties,thereisnolimittotheprecisionwithwhich wemaystatethetemperature,oravoltagereading,ormanyotherparametershumaningenuityisableto measure. ProgramsyouwriteusingMBasic,however,dealwithbitsandbytes;bit,byte,wordandlongvariables andconstantsareindiscretesteps.Abitmustbe0or1,notsomewherebetween0and1.Abytevariable can’thavethevalue128.3;itcanbe128or129,butnotsomethingbetween.EvenifweuseMBasic’s32-bit floatingpointarithmeticpackage,lookedatinsufficientdetailwefinditalsojumpsbetweenfinite,discrete steps,albeitsmallones. ThischapterexamineshowMBasictranslatesbetweentheanaloganddigitalworldsintheanalog-to-digital direction.We’llseeinChapter16howtoaccomplishthereverseprocess—digital-to-analogconversion. We’llassumeinthischapterthatinputsignalstoourA/Dconverterchangeslowlysothatwemayneglect anti-aliasingfiltersandothersampled systemconsiderations.However,we’ll touchuponNyquistsamplingratelimitsin conjunctionwithChapter16andthesame conceptsapplytoA/Dconversion.Ifyou wishtolearnmoreaboutdigitalsampling ratesandfrequencyresponse,Reference [16-4]offersaveryreadableintroduction.
IntroductiontoAnalog-to- DigitalConversion SupposewehaveacrudeA/Dconverterthat haseightpossibleoutputvalues,withone digitaloutputstepperinputvolt.Thus,the possibleoutputvaluesare0volts,1volt…7 volts.Figure11-1illustratesthisconversion process.Althoughouranaloginputvoltagemayassumeanyvalue—forexample 3.123456789volts—theA/Dconverter Figure11-1:TheA/Dprocess.
211
Chapter11 forcesthisinputvalueintooneoftheeightpossibleoutputs,threeinourexample.Thisconverterwillreport 3.4999voltsasthree,and3.5001voltsasfour.Inreality,thetransitionwillhavesomejitteroneithersideof 3.5volts.And,inarealA/Dconverterthetransitionpointwillnotnecessarilybethesameforeachvoltage step.Forexample,thetransitionpointbetweenthreeandfourmayoccurat3.5200volts,whilethetransition betweenfourandfivemayoccurat4.4712volts. WemayaskhowdoestheA/Dconverterknowthateachstepisonevolt?Or,forthatmatter,howdoesit determinewhatvoltageinputcorrespondstoazerooutput?TheanswerisfoundintheA/D’stwovoltage references;VREF+,thepositivereferencevoltageandVREF–,thenegativereferencevoltage.Thevoltageper step,VSTEPissimply:
VSTEP =
(VREF + − VREF − )
2N NisthenumberofbitsreturnedbytheA/Dconverter.
Let’sseehowthisworkswithour3-bitconverter.23=8andwewant1volt/step.Wealsowillassumethat VREF-willbeground,or0volts.Hence,VREF+mustbe8volts.Thereisasubtletyhere,though.Theconversionhasonlysevensteps—0to1volts,1to2volts…and6to7volts.So,itmightappearthatthereference voltageshouldbesevenvolts,noteight.Indeed,someA/Ddesignswouldrequirea7voltreferencetoyield 1volt/stepwitha3-bitconverter—thatis,thedivisorintheequationwouldbe2N–1insteadof2N.However, Microchip’sA/Ddesignrequires2Nasthedivisor. Whataboutthenegativereference?Inmostcases,wewishtomeasureavoltagewithrespecttoacommon referencepoint,generallyreferredtoas“ground”orVSSinour2840DevelopmentBoard.VREF-inthiscase willbethatcommonreferencepoint.But,thereareexcellentreasonstomaketheVREF–connectionatapoint separatefromthedigitalcircuitrygroundplane,primarilytoavoidcontaminatingtheinputsignalwiththe noisefoundonthedigitalgroundplane.Forexample,adigitalvoltmetermayhavetheVREF–pointthenegativebindingpostontheinstrumentfrontpanel.SeeReferences[11-6],[11-7]and[11-8]. ItmayalsobeusefultoworkwithVREF–atapotentialotherthanground.Supposetheinputsignaltobe digitizedisneverbelow1.25voltsandisneverabove2.5volts.SimplysettingVREF–to0voltsandVREF+to 2.5volts,throwsawayhalfthepotentialdigitalrange.Inthiscase,settingVREF–to1.25voltswilldoublethe resolution.However,theremaywellbereasonstosetVREF–to0andtosetVREF+tosomethinggreaterthan 2.5volts,acceptingsomeresolutionloss.Perhapsanerrorconditionexistsiftheinputdropsbelow1.25 voltsorexceeds2.5volts,whichmaybedetectedviaanextendedmeasurementrange.
ResolutionandAccuracy ResolutionisameasureofthenumberofdifferentvaluesthataredetectablebytheA/Dconverter.For example,the16F87x’s10-bitA/Dconverterhasaresolutionof210,or1024possibleoutputvalues.(Chapter 1summarizestheA/DcapabilitiesofselectedPICssupportedbyMBasic.)Usedwithapositivereference voltageof4.096voltsandanegativereferenceofzerovolts,thevoltageresolutionis4.096volts/1024steps, or4.0mVperstep. AccuracyisameasureofthedifferencebetweenthetrueinputvoltageandthevaluereportedbytheA/D converter.Accuracyislimitedbyseveralerrorcomponentsincluding: • QuantizationerrorresultingfromtheA/Dconverter’sfiniteresolution • ErrorswithintheA/D,suchas: o Integrallinearityerror o Differentiallinearityerror
212
Analog-to-DigitalConversion Offseterror Gainerror ErrorsexternaltotheA/Dconverter Noiseontheinputsignaloronthereferencevoltages Errorsinthereferencevoltages Inadequatesettlingtime Excessivesourceimpedance Errorsinanysignalconditioningcircuits EstimatingtheoverallaccuracyoftheA/Dconversionprocessrequirescarefulconsiderationoftheseerror sourcesandothers,bothinmagnitudeanddirection–thatis,arethepossibleerrorscumulativeoroffsetting? Theerrortimeframemustalsobeconsidered;aretheseshort-termerrorsthatmayaffectonemeasurement differentlyfromthenext,oraretheylong-termerrorstowhichallmeasurementsaremoreorlessequally subject? o o o o o o o o
Ignoringthoseerrorssourcesdependentuponthecircuitlayoutandconstructiontechniquesandexternal factors,wecanquantifyseveralpossibleerrorsourcesinourdesign: • Ourdesignwilluseawidelyavailablevoltagereferencedevice,aLinearTechnologyLT1634CCZ4.096voltagereference,withaspecifiederrorof±0.2%overthetemperaturerange0…70°C.Itis bufferedbyaMicrochipMCP601op-ampwith±2mVoffsetvoltageoverthesametemperaturerange. SincetheMCP601isconfiguredasaunitygainbuffer,thisoffsetmustbeaddeddirectlytoanyerrorin thevoltagereferenceitself.Anerrorof0.2%inthereferencerepresents8.2mV,foratotalerrorbudget of±10.2mV,or±0.25%ofthe4.096source. Microchip’s16F87xdatasheetprovidesthefollowingerrorbudget: • Integrallinearityerror<±1LSB • Differentiallinearityerror<±1LSB • Offseterror<±2LSB • Gainerror<±1LSB Aworst-caseestimateassumesalltheinternalA/Derrorsaddinthesamedirection,yielding±5LSB. However,Microchip’sMidrangeReferenceManualclaimstheabsoluteerrorislessthan±1LSBwhenVREF+ equalsVDD,notingthataccuracywill“degradeasVDDdivergesfromVREF+.”(InternalA/Derrorsarespecifiedintermsofhowmanyleastsignificantbits,orLSB,maybeinerror.Inourdesign,oneLSBis4mV.) OurdesignhasVREF+within1voltofVDD,soweareleftintheuncomfortablepositionofwonderingexactly howmuchtheaccuracywilldegradeasaresultofthe1voltdifference.However,spotmeasurementsof thebreadboarddesignagainstaFluke189digitalvoltmeterratedat±0.025%accuracyshowthat±1LSB remainsareasonableinternalerrorfigureforour4.096Vreference. Finally,thereisa±½LSBquantizationerrorinherentinthedigitizationprocess—evenifeverythingelse functionswithzeroerror,intheworstcasetheanaloginputvoltagemaybe½LSBbelowthereading,or½ LSBaboveit.OurA/Dmeasurementthereforehasapossibleerrorof±1.5LSB(6mV),representingabout ±0.2%ofthereading. SupposetheA/Doutputis500counts,correspondingto2.000volts.Whatisthepossibleerror?Ourvoltage referenceerrorbudgetcontributionis0.25%×2.0000volts=5mV.TothismustwemustaddinternalA/D errorsof4mV(1LSB)andinherentquantizationerrorandquantizationerrorcorrespondingto2mV(½ LSB).Thetotalworst-caseerroristhus±11mV—althoughtheA/Dconverterreportsavaluethatcorrespondsto2.000volts,allwecantruthfullysayisthattheactualinputislikelytobebetween1.989voltsand 2.011volts.
213
Chapter11 MBasic’sA/DReadFunction—ADIN MBasicprovidestwoprocedurestoreadananaloginput,ADINandADIN16.Bothprocedureshaveidentical callingsequences,sowe’lllookatADINfirst. ADIN[PinIn],[ClockConstant],[SetupConstant],[ReadVariable]
Theseconstantsinteract,andsettingtheirvaluesisn’talwaysintuitive,solet’slookatthemindetail.For clarity,we’lldiscusstheparametersinadifferentorderthantheyareusedinADIN. Setupconstant—thesetupconstantgovernsfourA/Dsettings,whichwe’llidentifyasa…d: (a-c)InternalSelectionSwitches(3switches) Figure11-2isasimplifiedversionoftheinternal“wiring”withinthe 16F87x.(SimilarinformationforotherPICsappearsintheirdatasheets.) Inessence,wehavethree“switches”toset;(a)onetoselectinternal orexternalpositivereferencevoltageVREF+,(b)onetoselectinternalor externalnegativereferencevoltageVREF–and(c)amultipositionselector switchtodeterminewhichofseveralpossiblepinsconnectstotheA/D convertermoduleinput.But,beforeweconnectapintotheA/Dconverter,thepinmustfirstbeconfiguredtobeananaloginput,insteadof Figure 11-2: Simplified analog switchinginternals16F876. thedefaultdigitalinputoroutput.
(d)DataJustification
ADINreturnsa10-bitresultinReadValueeitherleftorrightjustifiedinawordvariable.SupposetheA/D resultisthe10-bitvalue(decimal)750,orbinary%1011101110.Ourwordvariableis16bitswide,sothis maybestoredasright-justifiedwithsixleading0’sas%0000001011101110orleftjustifiedwithsixtrailing zerosas%1011101110000000.Thelatereffectivelymultipliesthereadingby26or64. LeftJustifiedandLeftJustified10-BitValues 0 1
0 0
0 1
HighByte 0 0 1 1
0 0
1 1
0 1
1 1
1 0
1 0
LowByte 0 1 0 0
1 0
1 0
0 0
Just. Right Left
Hex $2EE $BB80
Decimal 750 48000
Almostalwayswewillwishthe10-bitresulttoberightjustified.Whyhaveleftjustification?Supposewe needonlyan8-bitA/Dconversion.Toobtainan8-bitanswerfromthe10-bitreturnedvaluerequiresdiscardingthetwoleastsignificantconversionbitsandretainingtheeightmostsignificantbits,ortheleftmost eightbits.Thisiseasilyaccomplishedbyusingthehighbyteofaleftjustifiedresult,forexample,ReadValue.Byte1.
PuttingitAllTogether Let’sseehowtheseparametersmaybeset.Thetablebelowpresentsthepossibleconfigurationvaluesforboth the16F877and16F876PICs(including“A”suffixeddevices).The16F876hasfivepossibleanaloginputpins AN0…AN4,whilethe16F877has8possibleanaloginputsAN0…AN7.NotethatanaloginputAN4correspondstoRA5,nottoRA4.(RA4’ssecondfunctionistoserveastheexternalinputtotheTimer0clock.)The 16F877’sanaloginputpinsAN5,AN6andAN7arefoundoninputsRE0,RE1andRE2,respectively.
214
Analog-to-DigitalConversion A/DSet-upConstantsfor16F876/16F877/16F876A/16F877A Hexfor Hexfor
VoltRefs
Ports(AN=Analog--RA/RE=RegisterA/E(Digital) AN7 RE2
AN6 RE1
AN5 RE0
AN4 RA5
AN3 RA3
AN2 RA2
AN1 RA1
AN0 RA0
Left Just.
Right Just.
00
80
A
A
A
A
A
A
A
A
Vdd
Vss
8/0
01
81
A
A
A
A
Vref+
A
A
A
RA3
Vss
7/1
02
82
D
D
D
A
A
A
A
A
Vdd
Vss
5/0
03
83
D
D
D
A
Vref+
A
A
A
RA3
Vss
4/1
04
84
D
D
D
D
A
D
A
A
Vdd
Vss
3/0
05
85
D
D
D
D
Vref+
D
A
A
RA3
Vss
2/1
6/7
86/87
D
D
D
D
D
D
D
D
Vdd
Vss
0/0
08
88
A
A
A
A
Vref+
Vref–
A
A
RA3
RA2
6/2
09
89
D
D
A
A
A
A
A
A
Vdd
Vss
6/0
0A
8A
D
D
A
A
Vref+
A
A
A
RA3
Vss
5/1
Vref+
Vref–
Chan/ Refs
0B
8B
D
D
A
A
Vref+
Vref–
A
A
RA3
RA2
4/2
0C
8C
D
D
D
A
Vref+
Vref–
A
A
RA3
RA2
3/2
0D
8D
D
D
D
D
Vref+
Vref–
A
A
RA3
RA2
2/2
0E
8E
D
D
D
D
D
D
D
A
Vdd
Vss
1/0
0F
8F
D
D
D
D
Vref+
Vref–
D
A
RA3
RA2
1/2
Shadedcellsapplyonlyto16F877.
We’llstartwithasimplesetup—VDDasVREF+,VSSasVREF–,analogvoltagetobemeasuredonpinA0,with rightjustifiedresults.Selectingtheconversionconstant$8Emeetsourdesignrequirements. Clockconstant—TheA/Dconverterrequiresacertainminimumtimetoconverttheanaloginputvoltageto adigitalvalue.Microchipdividestheminimumtimeintotwoperiods: 1. The“acquisitiontime,”TACQ.Duringtheacquisitiontime,thesampleswitchclosesandtheinput voltagechargestheA/D’sinternal120pFcapacitanceCHOLD.TACQisnotusersettableinMBasic. 2. The“analog-to-digital”conversiontime,TAD.Duringtheconversiontime,thesampleswitchopens andthestoredvoltageonCHOLDisconvertedtoadigitalreading.Thecomplete10-digitA/Dconversionrequires12TADperiods. StartswhenA/Dinputchannel selected
StartswhenA/Dconversion initiated
AcquisitionTimeTACQ
12XA/DConversionTimeTAD
Hard-codedintotheMBasiccompiler—not settablebyADINprocedure
DefineTADbyselectingtheClockConstantin theADINprocedure
ADINandADIN16requiresettingTADviatheclockconstantparameter,whichhasfourpossiblevalues: ClockConstantSelection ClockConstant 0 1 2 3
Operation(Divisor) 2TOSC 8TOSC 32TOSC RCClock
215
MaximumPICFrequency 1.25MHz 5MHz 20MHz SeeText
Chapter11 TheminimumTADrecommendedbyMicrochipis1.6µs.Witha20MHzclock,adivisorof32isnecessary toyield1.6µs.Thecomplete10-bitconversiontimewouldthusbe12*1.6µsor19.2µs.ADINexecutesin approximately275µsona16F877witha20MHzclock.Thedifferencebetweenthistimeandthetheoretical19.2µs(plusanacquisitiontimeTACQoftypically10–15µS)isconsumedpartlyinacquisitiontimebut mostlyincompileroverhead. RegardlessofthePIC’sclockfrequency,the16F87x’sinternalRCoscillatorcangenerateTADbysettingthe clockconstanttothree.TheinternalRCoscillatoryieldsanominalTADof4µsbutMicrochipspecifiesthe expecteddurationbetween2µsto6µs,ascomponenttoleranceisnottightlycontrolled. Inputpin—ThefinalparameterrequiredbyADINdefineswhichpinisconnectedtotheanaloginputsource. (TheparameterSetupConstantonlyestablisheswhichpinsmaymaypotentiallybeusedforanalog input.)ThePinInconstantmaybeselectedfromthefollowing: InputPinConstantSelection AnalogInputPin AN0/RA0 AN1/RA1 AN2/RA2 AN3/RA3 AN4/RA5
InputPinConstant 0 1 2 3 4
AN5/RE0 AN6/RE1 AN7/RE2
5 6 7
Notes
NoteRA4isnotavailableforanalog input Notavailableon16F876/876A Notavailableon16F876/876A Notavailableon16F876/876A
ADIN16 Withversion5.3.0.0,MBasicaddedanewA/Dinputfunction,ADIN16. ADIN16[PinIn],[ClockConstant],[SetupConstant],[ReadVariable]
ADIN16isidenticalwithADIN,withonedifference—itconductsmultipleA/Dconversionsandreturnsa
quasi-16-bitresult.Howisitpossibletogeta16-bitreadingfroma10-bitconverter?Theansweristhatby averagingmultiplereadings,itispossibletoimprovetheconverter’sresolution.Averagingreducessome typesoferrors,suchasnoisepickup,butwon’tdoanythingtoreduceothererrorsources,suchasreference voltageerror.ADIN16returns65,535possiblevalues,soifweusea4.096Vreference,eachvoltagestepis 4.096/216,or62.5µV.YouwillhavetodecidewhetherADIN16providesausefulimprovementoverADIN, baseduponyourapplicationandcircuitlayout.
TestingADINandADIN16 Let’sexerciseADINandADIN16withthesimpletestcircuitofFigure11-3byreadingtheforwardvoltage acrossanLEDwithProgram11-1.
Figure11-3:ADINand ADIN16testconfiguration.
216
Analog-to-DigitalConversion Program11-1 ;Program11-1 ;ReadA/Dandoutputtoserial ;Constants ;--------Vdd InPin ADSetUpCon Clk VoltStep
fCon Con Con fCon
$8E
4.9508 ;Vddusedasreference A0 ;pinforinput ;%10001110 2 ;basedon20MHZclock Vdd/1024.0;10bitA/D=1024states
;Variables ;--------ADRaw Volts
Var Var
Word Float
;Initialization ;-------------EnableHSerial SetHSerialH9600 Main ADinInPin,Clk,ADSetup,ADRaw HSerOut[“Raw:“,DecADRaw,9] Volts=(ToFloatADRaw)*VoltStep HSerOut[“Real:“,Real6Volts\3,”V”,13] Pause100 GoToMain End Let’slookatourdefinedconstants: Vdd fCon 4.9508 ;Vddusedasreference InPin Con A0 ;pinforinput ADSetUp Con $8E ;%10001110 Clk Con 2 ;basedon20MHZclock VoltStep fCon Vdd/1024.0;10bitA/D=1024states
Forsimplicity,we’llusethe2840DevelopmentBoard’s+5VregulatedpowersupplyVDDasthereference voltageVREF+.ImeasuredVDDas4.9508Vonmyboard—yourboardwilllikelydiffer,butVDDshouldbe closetothenominal5V.We’vealreadyseenwhyADSetUpis$85—itsetsAN0asananaloginput,right justifiedoutput,VREF+=VDDandVREF-=VSS.Likewise,becausemy2840DevelopmentBoardhasa20MHz resonator,wemustselecttheclockconstant,CLK,as2inordertoassurethecorrectconversiontime.We alsodefineasaconstantthevoltageperA/Dstep.Wedothislettingthecompilerperformtheassociated arithmeticviathedivisionfunction:
VoltStep
fConVdd/1024.0.
Forimprovedgenerality,I’veusedfloatingpointnotationinthiscalculation,soVoltStepisafloatingpoint constantandmustbedefinedusingthefConoperator. Main ADinInPin,Clk,ADSetup,ADRaw HSerOut[“Raw:“,DecADRaw,9] Volts=(ToFloatADRaw)*VoltStep HSerOut[“Real:“,Real6Volts\3,”V”,13] Pause100 GoToMain
ThemainprogramloopreadstheanalogvoltageatpinAN0,andoutputsboththerawreadingADRawand thecomputedanalogvoltageVoltstotheserialport.ThecomputedanalogvalueVolts,is,ofcourse,the productofthevoltageperstep,VoltStep,andthenumberofsteps,Raw.SinceRawisaninteger,wemust convertittoafloatingpointvalueviatheToFloatoperatorbeforeusingitinafloatingpointoperation. Theresultisastringofreadings: Raw:451 Raw:451
Real:2.180V Real:2.180V
217
Chapter11 Raw:451 Raw:450 Raw:451 Raw:452 Raw:451 Raw:453 Raw:451 Raw:453
Real:2.180V Real:2.175V Real:2.180V Real:2.185V Real:2.180V Real:2.190V Real:2.180V Real:2.190V
UsingaFluke189digitalvoltmeterwithspecifiedaccuracyof±0.025%,ImeasuredthevoltageonpinA0 as2.1854V,a0.25%errorfromthemostcommonoutputreading2.180V,andaclosematchtoourerror budget. ToseethedifferenceADIN16makes,modifyProgram11-1bysubstitutingthefollowingcodefortheir counterpartsinProgram11-1andsavingtheresultasProgram11-1A: VoltStep
Con
Vdd/65536.0
;For16bitA/D
SinceADIN16isthefunctionalequivalentofa16-bitconverter,thenumberofstepsincreasesto216or 65536sowemustmodifyVoltStepaccordingly. Main ADin16InPin,Clk,ADSetup,ADRaw HSerOut[“Raw:“,DecADRaw,9] Volts=(ToFloatADRaw)*VoltStep HSerOut[“Real:“,Real8Volts\5,”V”,13] Pause100 GoToMain
ThechangesinMainaretosubstituteADIN16forADINandtorevisetheoutputformattingtoshowmore decimalplaces.Theresultsare: Raw:28865 Raw:28870 Raw:28867 Raw:28865 Raw:28869 Raw:28853 Raw:28867 Raw:28865 Raw:28867 Raw:28868 Raw:28859 Raw:28864 Raw:28862
Real:2.18058V Real:2.18096V Real:2.18073V Real:2.18058V Real:2.18089V Real:2.17968V Real:2.18073V Real:2.18058V Real:2.18073V Real:2.18081V Real:2.18013V Real:2.18051V Real:2.18036V
Theaverageofthesereadingsis2.180559V,0.22%fromthevalueIreadwithaFluke189DVM,noreal improvementoverourADIN10-bitmeasurement.
Self-ContainedDVM Let’sturntoamoreambitiousproject—buildinganautomaticscaling 3-digitdigitalvoltmeter.Figure11-4showsthedisplaysectionofmy breadboardprototype.Thereisnotenoughroomona2840Development Boardforthisproject,soasecondplugboardisrequired.Figure11-5 showsthecircuitweshalluse. TheDVMusesthe7-segmentLEDdrivercircuitandsoftwareroutine developedinChapter7,butinsteadofbeingdrivenbyanup/down switch,theLEDswilldisplaythevoltagewemeasureatpinAN0.Before Figure11-4:3-DigitPIC-basedDVM.
218
Analog-to-DigitalConversion
Figure11-5:DVMschematic.
219
Chapter11 welookatProgram11-2,let’sgothroughahighlevelreviewofFigure11-5.Sincemuchofthecircuitryof Figure11-5isborrowedfromChapter7,we’lldiscussonlythedifferences.Ifyouareabithazyonhowto multiplexa7-segmentdisplay,youmaywishtorereadChapter7. Voltagereference—The4.096referencevoltageisaLinearTechnologyLT1634CCZ-4.096precision source,accurate±0.20%overthetemperaturerange0ºC–70ºC.Tominimizedriftcausedbyinternal heating,I’vebiasedtheLT1634atabout20µAthrougha43kohmresistor.Microchiprecommends thatVREF+bedrivenfromalowimpedancesource.HenceU1,aMicrochipMCP601op-ampbuffersthe voltagereferenceandprovidesalowimpedancesourcetotheVREF+input.TheMCP601bufferadds±2 mVoffseterrortothereferencevoltage.Forgreateraccuracy,aLinearTechnologyLT1634A158-4.096 device,ratedat±0.05%and±10ppm/°C,mightbeconsidered,butit’sthreetimesasexpensiveandis surfacemountonly. R11,a20kpotentiometer,isusedavariablevoltagesourcefortesting. 7-Segmentdisplays—The7-segmentLEDdisplaysareLumexLDS-M514RI-RAcommonanodedevices selectedbecausetheleadsareatrightanglestothedisplaybody,thuspermittingverticalmountingon asingleprintedcircuitboard,oraplug-inbreadboard.Unfortunately,thesedeviceshave0.050inchpin spacing,soforbreadboarding,it’sconvenienttofirstsolderthedisplaytoaCapitalAdvancedTechnologies33117Surfboardadapterwith0.100inchpinspacing. Unlikethe7-segmentdisplaysweusedinChapter7,thesedevicesareconfiguredastwogroupsoffour segmentseach(thesevendigitstroke segmentsplusthedecimalpoint).This requiresthescanningsoftwaretoseparatelyaddresseachhalfofthedisplay. Anodeswitch—ThedisplayLEDanodes areconnectedtoVDDthrough2N4403 PNP,justasinChapter7.However, sinceeachLEDdisplaycomprisestwo half-displays,weneedsixswitching transistors,Q1–Q6,notthree. Cathodeswitch—Inorderforasegmentto illuminate,itsanodemustbeconnected toVDDthroughtheassociated2N4403, anditscathodemustbeconnectedto ground.Wehaveselectedinexpensive 2N7000MOSFETsascathodeswitches. Thispartofourcircuitisidenticalwith thatofChapter7. Ifyoureducethecurrentlimitingresistor below100ohms,itmaybenecessaryto powerthe7-segmentdisplaysfromasupplyotherthantheonefurnishedwithBasic Micro’sdevelopmentboards.Fortunately, 7805regulatorshavebuilt-inovertemperatureprotectionandshouldnotbeharmedby overloads. Lumexratesthedisplayat150mA maximumpeakforwardcurrentwithacorre- Figure11-6:Program11-2structure. 220
Analog-to-DigitalConversion spondingvoltagedropof2.5volts.Thetotalvoltagedropacrossthe2N7000and2N4403isapproximately 300mV.Thisleaves2.2voltsacrossthecurrentlimitingresistor.Foranydesiredsegmentcurrent,thecurrentlimitingresistoristhus:
R=
2200 I
Where:
Ristheresistorvalueinohms IisthedesireddisplaycurrentinmA
Anadditionalstand-aloneLED,D5,isdrivendirectlyfromRC4andilluminateswhenthemeasuredvoltage isbelow1.00voltstoindicatethatthedisplayreadsinmillivolts. Inputlimits—Microchiprecommendsthatthevoltageappliedtoananaloginputpinshouldnotexceed0.3 VaboveVDDnorbemorethan0.3VmorenegativethanthePICsdigitalgroundvoltage.Inputsbeyond theselimitsmayincreaseerrors,and,ifnotcurrentlimited,maydamagethechip.Oursimplecircuit providesnoprotectionagainsttheseproblems.Also,oursimpleDVMcircuitassumesthePIC’sA/D inputpinisdrivenfromalowimpedancesource,sothetimerequiredtochargetheinternalsample-andholdcapacitormaybeignored. Program11-2usesthiscircuittodisplaytheDCvoltageappliedtopinAN0.Program11-2’sstructureisillustratedintheflowchartofFigure11-6. Program11-2 ;Program11-2 ;Read0...4.096voltsonPinRA0anddisplayvoltagereading ;on3LEDdigitreadouts. ;Constants ;-------------------------AN0 Con Clk Con ADSetUp Con AvgLength Con ShiftLen Con Vdd fCon ;Variables ;------------------------i Var j Var k Var Temp Var Decode Var DigitVal Var TempVolt Var Temp10 Var DataStore Var Smooth Var RealVolt Var VoltStep Var DpPosn Var
0 2 $85 32 5 4.096
;UsePinRA0foranaloginput ;setupA/Dconversionclock ;extVref+;GndVref;don’tchange ;Shifttosavetimeoveradivide. ;precisionvoltagereference
Byte ;i,j&kare Byte ;countersusedforvariousindexes Byte ;inarrayandotheraccess Byte ;digitbeingdisplayed Byte(14) ;patternsforLEDdisplay Byte(3) ;digitfordisplay Word ;voltagereading Byte ; Word(AvgLength);bufferarray Word ;Averagedreading Float ;Floatingpointvolts Float ;voltsperA/Dstep Byte ;decimalpointlocation
;Initialization ;---------------------------------- ;ABCDEFG. ;-------- Decode(0)=%11111100 Decode(1)=%01100000 Decode(2)=%11011010 Decode(3)=%11110010
;correspondingsegments ;validfor ;LumexLDS-M514R1-RALED ; ;LEDsareconnectedintwo ;banks,unlikemostdisplays
221
Chapter11 Decode(4)=%01100110 Decode(5)=%10110110 Decode(6)=%00111110 Decode(7)=%11100000 Decode(8)=%11111110 Decode(9)=%11100110 Decode(10)=%00000001 Decode(11)=%10011100 Decode(12)=%11111010 Decode(13)=%00011100 DigitVal(0)=0 DigitVal(1)=0 DigitVal(2)=0 TempVolt=0
;Commonanode ; ; ; ; ; ; ; ; ; ; ; ; ;
Fori=B0toB7 ;B0..B5drivethedigithalves. Outputi ;[1-11-2][2-12-2][3-13-2] Highi ;[1][2][3] Next ;sowescan1-1,1-2,2-1...3-2 ;whenilluminatingtheLEDs ;3-1=Digit3,Pin1 Fori=C0toC4 ;C0..C3drivethediodesvia2N7000. Outputi ;[Pin3][Pin4][Pin5][Pin6] Lowi ;[RC0][RC1][RC2][RC3] Next Fori=0to(AvgLength-1) ;Zerosampledvalues DataStore(i)=0 Next k=0 ;initializetoindexstartingatzero Smooth=0 ;UsedinSmooth=Smooth+Xsomustbe0 DPPosn=0 EnableHSerial SetHSerial H1200 VoltStep=Vdd/1024.0
;Initializetheserialportat1200b/sec ;intentionallyslow!!! ;For10bitA/Dwehave1024states
Main ;-------------------------------------------;Wescanthedigitsfromlefttoright.Foreachdigitwe ;lookattheAhalfthentheBhalf. ;Foreachhalf,weusethecorrespondingnibblefromDecode. Fori=0to2 ;iisthedigit,lefmostdigit=Digit0 j=B0+(2*i) ;jisthedigithalf,sequentially 0,1,2..5 ;Assumewearedisplaythevalue123 Temp=Decode(DigitVal(i)) ;whichdigitareweworking;on? DigitVal()holds(1)(2)(3) ;Pin1-half ;--------------------------- PortC.LowNib=Temp.HighNib ;Highnibble ;holdspatternforSegmentsA,B,C&D Lowj ;topreventghostingorderisimportant Pause2 ;pausetoilluminateLED.Larger=brighter Highj ;Fora20MHzchip,3ismaxbeforeflicker ;isaproblem.2providescleanerdisplay ;Pin2-half ;--------------------------- j=j+1 PortC.LowNib=Temp.LowNib ;repeatforotherhalf ;LownibbleholdspatternforSegmentsE,F,G&DP Ifi=DpPosnThen PortC.Bit0=1 EndIf
222
Analog-to-DigitalConversion Lowj ;sameapproachasforPin1-half Pause2 ;usethisordertoavoidghosting Highj GoSubTakeAvg ;Gettheaveragevoltagevalue GoSubMapVolts;Computesindividualdigits Next GoToMain TakeAvg ;------------------------------------ ;Subtractfromheadofbuffer Smooth=Smooth-DataStore(k) ADinAN0,Clk,ADSetup,DataStore(k) Smooth=Smooth+DataStore(k) ;32elcircularaveraging ;buffer.Thisworksasalowpassfilter k=k+1 Ifk=(AvgLength)Then k=0 EndIf TempVolt=Smooth>>ShiftLen ;Equalto/32 Return MapVolts ;---------------------- RealVolt=VoltStep*(ToFloatTempVolt) ;RealVoltisthefloatingpointvoltage HSerOut[RealRealVolt,13] ;senditviaserialifyouwant LowC4 ;C4istiedtothemillivoltflag ;whenhighdisplayisinmillivolts DpPosn=0 ;Assumevolts,asthestartingpoint TempVolt=ToInt(0.500+(100.0*RealVolt)) ;roundoffin10’sofmillivolts ;the0.5istogetbetterrounding If(TempVolt<100)Then ;Ifwearelessthan1.00voltwewant RealVolt=RealVolt*10.0 ;todisplaymillivoltsdirectly,so DpPosn=2 ;multiplyby10(1,000whenconsidered HighC4 ;withtheFMULearlier)andlightthe TempVolt=ToInt(0.500+(100.0*RealVolt)) ;millivoltLED. EndIf DigitVal(0)=TempVolt/100 ;display0..512divideby2 Temp10=TempVolt-(DigitVal(0)*100) ;1stdigit= DigitVal(1)=Temp10/10 ;2nddigit DigitVal(2)=Temp10-10*DigitVal(1) ;3rddigit Return End
Asusual,wefirstdefineconstantsanddeclarevariables.ThevaluechoicesfortheconstantsrelatedtosettinguptheA/DfunctionADINwillbediscussedinconjunctionwiththesubroutineTakeAvganalysis.). AvgLength ShiftLen Vdd
Con Con fCon
32 ;don’tchange 5 ;Shifttosavetimeoveradivide. 4.096 ;precisionvoltagereference
TheconstantAvgLengthdefinesthelengthofthecircularbufferDataStoreweusetoholdindividual voltagereadingsforaveragingTheconstantShiftLendefinesthenumberofbitsweshiftrighttoequala divideby32(25=32)whenwecomputetheaveragevoltagefromthe32elementarrayDataStore.Vdd holdsthevalueoftheA/Dconvertmodule’sreferencevoltage.
223
Chapter11 Duringtheinitializationsection,weassignvaluestoeachLEDsegmentmappingvariable,Decode(),for example: Decode(0)=%11111100
;digit0display
Wewon’trepeatallthedigit-to-segmentmappingvariables,butshowDecode(0)asanexample.Theprimarydifferencebetweenthedigit-to-segment mappingofChapter7andhererelatestothesplitLEDconfigurationofthe Lumexdevicesusedinthiscircuit.Sinceeachhalf-digitrequirescontrolling four2N7000drivers,alogicalmappingstructureistoholdacompletemap foreachdisplayedcharacterinonebyte,employingonenibbleforeachdigit half.Toholddefinitionsformultipledisplaydigits,weuseanarrayofbytes, Decode().Anilluminatedsegmentisindicatedbyahigh(logical1)inthecorrespondingbitposition.ConsiderDecode(i).Theindexicorrespondstothe desireddigit;thesegmentmappingtodisplaythedigit“7,”forexample,isheld inDecode(7).Thebitassignmentsaremadeasfollows,whereanXindicatinganilluminatedsegmentcorrespondstoalogical1inourmappingvariable, baseduponthesegmentidentifiersofFigure11-7:
F i g u r e 1 1 - 7 : S e g m e n t identifiers for lumex LDSM51RI-RA 7-segment LED display.
DisplayedDigittoSegmentMapping LUMEXLDS-M51RI-RA7-SegmentLEDDisplay
Displayed Digit 0 1 2 3 4 5 6 7 8 9 DP C a L
Firsthalf—Pin1Active(At+5V) Decode().Nib1 Pin3Gnd Pin4Gnd Pin5Gnd Pin6Gnd A B C D X X X
X X X X X
X X X X X X X X X
X X X X
X X X
Secondhalf—Pin2Active(At+5V) Decode().Nib0 Pin3Gnd Pin4Gnd Pin5Gnd Pin6Gnd E F G DP
X
X
X X
X
X X
X
X
X
X
X X X
X X X X X
X X
X X X
X X
X
X X X X X X X Xindicatessegmentilluminated
X X X
Thus,ourassignmentforDecode(0)is%11111100illuminatingallsegmentsexceptSegmentGandthe decimalpoint.Arelateddecisionishowtoholdthenumberstobedisplayed.Supposethevoltagereadingis 1.23volts.Sincewemustdisplaythisonedigitatatime(butscannedquicklysopersistenceofvisionmakes itlookasifalldigitsareonallofthetime),weallocatespaceforathreeelementbytearrayDigitVal. DigitVal,inourexample,wouldholdDigitVal(0)=1,DigitVal(1)=2andDigitVal(2)=3. Fori=0to(AvgLength-1) DataStore(i)=0 Next k=0
;Zerosampledvalues
224
Analog-to-DigitalConversion Smooth=0 DPPosn=0
EnableHSerial SetHSerial
H1200
TheinitializationsectionalsosetsthenecessaryPortBandPortCpinstobeoutputsandzerosvariables.We alsosetthehardwareserialoutputat1200bits/sec.Ifaserialoutputisnotdesired,omitthisinitialization. VoltStep=Vdd/1024.0
;For10bitA/Dwehave1024states
ToconverttheA/Dreadingtovolts,wecalculatethevoltsperstep.Sinceourdesignusesa4.096Vreference,wecalculatethevoltageperstep(4.0mV)withafloatingpointdivision. Themainloopisendlesslyrepeatedandsequentiallyscansthethreedisplaydigits,left(digit0)toright (digit2).Withineachdisplaydigit,pin1isfirstmadeactive,followedbypin2.Theindexvariablei correspondstothedigitandhaspossiblevalues0…2.Thevariablejisapinindexthatsequentiallyputs RB0…RB5low,therebyplacingVDDonthesegmentdisplay’scommonanodepins. Recallinghowwehavestoredthedisplaymappingandthedigitcoding,therelationshipbetweeni,j,and outputpinsinPortsBandCisstraightforward: i 0 1 2
j RB0+0 RB0+1 RB0+2 RB0+3 RB0+4 RB0+5
LowonPin RB0 RB1 RB2 RB3 RB4 RB5
PortC.LowNibbleAssignment Decode(DigitValue(0)).HighNibble Decode(DigitValue(0)).LowNibble Decode(DigitValue(1)).HighNibble Decode(DigitValue(1)).LowNibble Decode(DigitValue(2)).HighNibble Decode(DigitValue(2)).LowNibble
Withthisunderstanding,thelogicflowofthemainprogramloopissimple: Main ;-------------------------------------------Fori=0to2 j=B0+(2*i) Temp=Decode(DigitVal(i))
TosaveabitoflookuptimeweuseanewvariableTempinsteadofrepeatingDecode(DigitVal(i)) whichrequiresadoublearrayindexlookupeachtimeitappears. PortC.LowNib=Temp.HighNib Lowj Pause2 Highj
Sincepins3…6ofthedisplayarecontrolledbyRC0…RC3,weareconcernedwithonlythePortC’slow nibble.Atthispointintheiloopwearedealingwithpin1ofthedisplaydigit,sowemustsetsegmentsA, B,CandDcorrectly.ThesecontrolbitsareheldinthehighnibbleofDecode()arrayelements.Hence,we setPortC.LowNibtoTemp.HighNib. HavingsetthesegmentsA…Dcorrectly,wenowapply+5Vtopin1ofthedisplaydigit.Toavoidaghostimageofincorrectsegments,it’simportanttofirstsetthesegmentsfirst,andonlythendroptheRBpintoapply +5Vtotheanodes.Wekeeptheselectedsegmentsilluminatedfor2msthroughapause2statement. j=j+1 PortC.LowNib=Temp.LowNib Ifi=DpPosnThen PortC.Bit0=1 EndIf
225
Chapter11 Wenowdealwithpin2atVDDbyincrementingjandapplyingthesameprinciplestosegmentsE…DPattachedtopin2ofthedisplaydigit,exceptthesegmentmapiscontainedinTemp.LowNib. Wetreatthedecimalpointseparately—itslocationisdeterminedinsubroutineMapVoltswhichsets DpPosnto0or2,indicatingwhichdigit’sdecimalpointistobeilluminated.ThedecimalpointLEDis connectedtoRC0,soweoverridethePortC.Bit0valuecontainedinTemp.LowNibwithadirectbitassignment. GoSubTakeAvg GoSubMapVolts
TheanalogvoltageisreadinsubroutineTakeAvg.SubroutineMapVoltscomputesthedecimalvoltageand loadsthedigitvaluesintotheDigitValarray. SubroutineTakeAveragereadstheanalogvoltage,andcalculatestheaverageofthelast32digitalvalues. TheresultingaverageismaintainedinthevariableTempVolt.Usingtheaveragevalueinsteadofaninstantaneousreadingreducesjitterandnoise. TakeAvg Smooth=Smooth-DataStore(k) ADinAN0,Clk,ADSetup,DataStore(k)
(ThestatementSmooth=Smooth-DataStore(k)isdiscussedinconnectionwiththeaveragingprocessbelow.) WereadtheanaloginputvoltagewiththeADINprocedure.Thisrequiressettingthreeconstantsusingthe reasoningdevelopedearlierinthischapter.OurA/Drelatedconstantsare: AN0 Clk ADSetUp
Con Con Con
0 2
;UsePinRA0foranaloginput ;setupA/Dconversionclock $85 ;extVref+;GndVref-
Sinceour16F877operateswitha20-MHzclock,andwedonotwishtousetheinternalRCoscillator,our clockconstantmustbe2.Hence,we’vedefinedClkas2. Weuseanexternalvoltagereference,VREF+,andwantRA0/AN0tobeouranaloginputpin.Whileexperimentingwithourbreadboardlayout,weprefertousetheinternalgroundforVREF–,sowewishVREF–tobe assignedtoVSS.Finally,wealsowanttheA/Ddatatoberightjustified.Wewishtheremainingdual-purpose pinstobeavailablefordigitalI/Otothegreatestextentpossible.Hence,oursetupconstantmustbe$85, whichresultsinthefollowinganalogpinassignments: Pin AN0/RA0 AN1/RA1 AN3/RA3
Function AnalogInput AnalogInput(Unused) VREF+
AftertheADINfunctionexecutes,DataStore(k)hasthereturnedA/Ddata,a10-bitvaluerangingfrom 0…1023. Smooth=Smooth+DataStore(k) k=k+1 Ifk=(AvgLength)Then k=0 EndIf TempVolt=Smooth>>ShiftLen Smooth=Smooth-DataStore(k) Return
Theremainderofthesubroutineimplementsa32-samplemovingaverageroutine.DataStoreisacircular bufferthatstoresnewdatainthenextopenposition.Whenall32positionsarefilledwithdata(k=31),the bufferindexkwrapsaroundto0andtheprocessstartsoveragain.Weimplementtheaveragefunctioninan efficientmanner,asillustratedinFigure11-8.Abrute-forceaveragealgorithmwouldsimplysumDataStoreaftereveryreadanddivideby32: 226
Analog-to-DigitalConversion Smooth=0 Form=0toAvgLength Smooth=Smooth+DataStore(m) Next TempVolt=Smooth/AvgLength
Thebrute-forcealgorithmcomputes32sumsforeveryA/Dread,averyinefficientprocess.Amoreelegant approachistonotethateverytimewecompleteanA/Dread,31ofthe32valuesinDataStoreareunchangedfromthepriorread;onlythenewA/Dvaluehasbeenaddedanditreplacestheoldestreading—the ADINcommandwritesthenewvalueovertheoldestreading. Hence,ourstrategyforanefficientaverageis: Keepthesumoftheprior32readingsisinthevariableSmooth Subtracttheoldestreading(heldinDataStore(k))fromSmooth TakeanewreadingstoreitinDataStore(k)andaddittoSmooth DivideSmoothbythenumberofreadingstoobtaintheaverage
Figure11-8:Implementinganefficientaveragingalgorithm.
227
Chapter11 Sincewemaintainthereadingsinacircularbufferarrayindexedbythevariablekwemustaddafifth, housekeeping,itemtoourstrategy: Updatethearrayindexk;ifnecessaryexecuteawraparoundtozero
Onefinalpointisthatsinceinsteadofdividingby32tocomputetheaverage,wecansimplyexecuteafaster 5-bitshiftprocedure: TempVolt=Smooth>>ShiftLen TempVolt=Smooth/AvgLength
Thetwoalternativesaboveproduceidenticalresultsforourwordlengthvariables.Ofcourse,theshiftfunctiononlyworksiftheaverageistakenoveralengthoftheform2N. ThesubroutineMapVolts,fillsthearrayDigitVal,setsthelocationofthedecimalpointandactivatesor deactivatesthemillivoltindicatorLED. MapVolts RealVolt=VoltStep*ToFloatTempVolt HSerOut[RealRealVolt,13] LowC4
WepreviouslydeterminedthevoltageperA/Dstep,VoltStep,sowecalculatethefloatingpointvalueof theinputvoltagebysimplymultiplyingtheaveragedigitalvalueTempVoltfromthesubroutineTakeAvg byVoltStep.SinceTempVoltisawordintegervariable,soitmustbefirstconvertedtoafloatingpoint withtheconversionfunctionToFloat. Ifserialoutputisnotdesired,deletetheHSerOutfunction. DpPosn=0 TempVolt=Int(0.500+(100.0*RealVolt))
Weassumeinthisportionofthesubroutinethatthemeasuredvalueisbetween1.00voltsandthemaximum 4.096volts.Ifso,thedecimalpointafterthefirstdigit(Digit0)shouldbeilluminatedbysettingDpPosn=0. Withthreedisplaydigits,readingsbetween1.00andthemaximum4.096voltshavearesolutionof10mV. Thisvoltagerangecanthusbeconsideredtobe100mV10to409mV10wheremV10meansunitsof10mV, withoutlossofaccuracy.Tomakeourtaskofmappingvoltageintodisplaysegments,therefore,weconvert RealVoltintounitsof10mVbymultiplyingby100(1.00voltis100mV10)andconvertingtheresulttoan integer. MBasic’sToIntconversionfunctiondoesnotroundandismoreaccuratelydescribedasafloorconversion, i.e.,itreturnsthegreatestintegerthatdoesnotexceedthefloatingpointvalue.Forexample,ToInt(99.99) returnsthevalue99,not100.Byadding0.500,weforceroundingtothenearestinteger. If(TempVolt<100)Then RealVolt=RealVolt*10.0 DpPosn=2 HighC4 TempVolt=ToInt(0.500+(100.0*RealVolt)) EndIf
Suppose,however,thattheinputvoltageislessthan1.00volts,or100mV10?Our3digitdisplaywillhave aleadingzero,andwethrowawayotherwiseusefuldisplayspace.Accordingly,weshifttodisplayingmillivoltsona0…999mVrangewhentheinputvoltagedropsbelow1.00.Shiftingthevaluetomillivoltsfrom mV10isaccomplishedbymultiplyingby10,andthenrepeatingtheintegerconversionandroundingprocess. Toalerttheuserthatthescaleisnowmillivolts,wetakeRC4hightoilluminateasentinelLED. DigitVal(0)=TempVolt/100 Temp10=TempVolt-(DigitVal(0)*100) DigitVal(1)=Temp10/10 DigitVal(2)=Temp10-10*DigitVal(1) Return
228
Analog-to-DigitalConversion WhetherthedigitsdisplaymillivoltsormV10isimmaterialtothedisplaycodeinMain;itissimplyconcernedwithilluminatingthesegmentscorrespondingtothevaluesintheDigitValarray. Supposethedesireddisplayis234,representing2.34voltsor234mV,dependingonthelocationofthe decimalpoint.DigitVal(0)shouldcontain2,DigitVal(1)shouldcontain3andDigitVal(2)should contain4.Thus,DigitVal(0)containsthe100’svalue,whichweobtainbysimplydividingTempVoltby 100.(Remembertheseareintegerdivisions.)Tofindthe10’svalueforDigitVal(1),wesubtractthe100’s valuefromTempVoltanddivideby10.ThesameprocessisappliedtofindtheunitsvalueforDigitVal(2).Here’sthenumericalresultofthesesteps,wheretheunderscoreindicatestheresultstobesavedin theDigitValarray: 234/100=2 234-(2*100)=34 34/10=3 34-(3*10)=4
;save2inDigitVal(0) ;save3inDigitVal(1) ;save4inDigitVal(2)
IdeasforModificationstoProgramsandCircuits Althoughourvoltmeterisusableinthebreadboardformat,noonewouldmistakeitforausefullaboratory instrument.Hereareafewideasforadditionalexperimentation: • Highimpedanceinput—buffertheinputwithanop-ampfollower.Figure11-9isasimplifieddepictionoftheA/Dinputcircuitinthe16F87xdevices.BasedonthecircuitconstantsinFigure11-9,what shouldtheoutputimpedanceofthebuffer?Isthebufferoutputimpedanceimportantifweonlyuse ADINorADIN16,wherewecannotcontrolthepreciseA/Dreadtime?
Figure11-9:SimplifiedmodelofA/Dinputmodule.
• • • •
Rangeselectioninput—ourvoltmeterhasalimitedrange.Highervoltagescouldbeaccommodatedby avoltagedividerinput.Lowervoltagerangesmayrequireanamplifiedinput.Thesecan,ofcourse,be combinedwithaninputbufferamplifier. MeasureACvoltages—addanop-ampprecisionrectifierafterabufferedinput.Readthepeakvoltage andaddacalibrationfactortotheprogramtoreflectthedifferencebetweenaverageandRMS,inwhich almostallmetersarecalibrated. MeasureDCcurrents—measurethevoltageacrossacurrentshuntresistorthroughwhichtheunknown currentispassed.IsthedesigneasierifyouusebothAN0andAN1analogvoltageinputpins?Ifyoudo usetwoinputpins,howdoesthetimedelaybetweenconsecutivereadsaffecttheaccuracy? Measureresistance—addanohmmeterfunction,bymeasuringthecurrentthroughtheunknownresistorandthevoltageacrosstheunknown.CalculatetheresistancefromOhm’slaw.
229
Chapter11
References [11-1]
Mitra,S.,etal.UsingtheAnalog-to-DigitalConverter(A/D),MicrochipTechnology,Inc.Application NoteAN546,DocumentNo.DS00546E(1997). [11-2] Bowling,Steve,UnderstandingA/DConverterPerformanceSpecifications,MicrochipTechnology,Inc. ApplicationNoteAN693,DocumentNo.DS00693A(2000). [11-3] D’Souza,Stan,FourChannelDigitalVoltmeterwithDisplayandKeyboard,MicrochipTechnology,Inc. ApplicationNoteAN557,DocumentNo.DS00557C(1997). [11-4] PICmicro™Mid-RangeMCUFamilyReferenceManual,Section23—10-bitA/DConverter,Microchip Technology,Inc.,DocumentNo.DS31023A(Preliminary-1997). [11-5] PIC16F87XDataSheet,Section11Analog-to-Digital(A/D)ConverterModule,MicrochipTechnology, Inc.,DocumentNo.DS30292C(2001). [11-6] Pease,RobertA.,TroubleshootingAnalogCircuits,Chapter10,TheAnalog-DigitalBoundary,Boston: Butterworth-Heinemann,1991paperbackreprint1993. [11-7] Sauerwald,Mark,DesigningwithHigh-SpeedAnalog-to-DigitalConverters,ApplicationNoteAD-01, NationalSemiconductor,Inc.(May1998). [11-8] Rempfer,William,TheCareandFeedingofHighPerformanceADCs:GetalltheBitsYouPaidFor, ApplicationNote71,LinearTechnology(July1997). [11-9] Baker,BonnieC.,LayoutTipsfor12-bitA/DConverterApplication,MicrochipTechnology,Inc. ApplicationNoteAN688,DocumentNo.DS00688B(1999).
230
12
CHAPTER
DigitalTemperatureSensors andReal-TimeClocks We’regoingtolookattwocommunicationsprotocols,“1-wire”and“three-wire”(alsoknownasSPI—SerialPeripheralInterface)forserialdataexchangebetweenaPICandexternalsensors.We’lllookatthese protocolsinthecontextoftwospecificdevices,theDS18B2012-bittemperaturesensorandtheDS1302 realtimeclock,butwe’llseeSPIagaininlaterchapters.(Bytheway,don’tconfuseDallasSemiconductor’s DS18B20sensorwithitssimilar,cheaper,DS18S20device.TheDS18S20isalsoa1-wiretemperaturesensor,butwith9-bitresolution,yielding0.5°Csteps.) Inordertokeepourdiscussionofmanageablelength,we’llbrieflymentionthatthesedevicesarebuttwo examplesfromtheworldofsensors.Oneformoranotherofelectronicsensorcanmeasurealmostanyphysicalparameterofinterest,directlyorindirectly.Historically,sensorsusedananalogchangeinanelectrically measurableparameter—resistance,capacitanceorvoltagebeingthemostcommon—tomeasureachangein anunderlyingparameter,suchastemperature,humidity,pressure,acceleration,orlightintensity.Sincethe sensoroutputisanalog,theresultingvaluemustbereadwithananaloginstrument,orconvertedtoadigital valuewithananalogtodigitalconverter. Pureanalogsensorsarestillwidelyused,buthavebeenaugmentedwithabuilt-indigitalconversion,so theoutputcanbedirectlyreadbyamicrocontroller,eventhoughthemicrocontrollerdoesn’thaveabuilt-in ADC.(Don’tbefooledbythedigitaloutput,however,asinalmosteverycasetheunderlyingphysicalsensor processremainsanalog.)
DS18B20TemperatureSensor One-WireProtocol Beforedelvingintothespecifictemperaturesensorwe’lluse,let’sexploreits1-wireprotocol.(Ifyouwant toskipthisdiscussionandjumprightintotheprogramcode,goahead,asMBasicdoesanexcellentjobof encapsulatingthenutsandboltsof1-wireprotocolintotheOWInandOWOutprocedures.) MaximIntegratedProducts’DallasSemiconductordivisiondevelopedthe“1-wire”protocolasaneconomicalwayofexchanginginformationbetweenmicroprocessorsandancillarychips.It’scalleda1-wire networkbecauseitusesonewire(plusground)tocommunicatewiththemastermicrocontroller.One-wire devicesareslavesandcommunicateonlywhensocommandedbythemaster.Dataistransmittedserially overthedatalineatanequivalent14kb/srate.Figure12-1showshowtoconnect1-wiredevicestoaPIC. Dallashasarangeof1-wiredevicesthatincludememory,encryptionandserialnumbergeneration,inadditiontotemperaturesensing. The1-wiredataprotocoldifferssignificantlyfromotherswe’veseen,however.AlthoughMBasicwillhide thecomplexityforus,let’stakealookattypicalsignalingina1-wiredeviceasshowninFigure12-2.
231
Chapter12
Figure12-2:Resetandpresencepulsesin1-wire protocol.
Figure12-1:Typical1-wiredeviceconnection.
CommunicationsfromthemasterPICtoslave1-wiredevicesstartswiththemasteroutputtinga480µslow resetpulse,followingwhichthemasterswitchestoreceive.The1-wiredevicerespondsbytakingthedata linelowsendinga“presence”pulse,forapproximately150µs.(Wewillusethepresencepulsetodetect whetherornota1-wiredeviceisconnected.)Followingtheresetpulse,themastersendscommandstothe slaveandtheslaveresponds.Figure12-3showsthecompletesequence;thereset/presencepulse,followed bya1-byteinterrogationrequestsentbythemaster,withan8-bytereplybytheslavedevice. Let’stakeacloserlookathowdatabitsaresent.Figure12-4showsthefirstbytetransmittedbyaDS18B20 respondingtoaninterrogationrequesttosenditsdeviceIDcode.(Thefirstbyteisthefamilycode,$28 (%00101000)inthecaseoftheDS18B20,sentleastsignificantbitfirst.)Foreachofthe8bitstobereceived,themasterswitchestooutputmode,dropsthedatalinelowbriefly(atleast1µs),releasesthedata lineandswitchestoinputmode.Thedatalineisthenpulledhighbythepull-upresistor,R1inFigure12-1. Theslave1-wiredevicethenrespondsbyeitherpullingthedatalinelow(transmittinga0)orleavingthe datalinehigh(transmittinga1).Theslavewillmaintainthisstatusfor15µs.Themastermustthereforeread thedatalinestatuswithin15µsafteritswitchestoinputmode.
Figure12-3:Reset–Interrogate–Responsein 1-wireprotocol.
Figure12-4:Typicalbytetransmissionin1-wire protocol.
232
DigitalTemperatureSensorsandReal-TimeClocks Amasterwritestotheslaveusingasimilarprocess,butwithdifferenttiming.Towritea1totheslave,the masterpullsthebuslowfor15µsorlesstimeandeitherreleasesthebustogohigh(writesa1totheslave) orholdsthebuslowforatotaltimeof60µs(writesa0totheslave). Dallasreferstothistechniqueas“timeslot”coding—thatis,theprocessofthemastertakingthedataline lowisseenas“issuingatimeslot.”Theslavedevicethenrespondswithinthetimeslotwitheithera0ora1, andthemasterthenissuesthenexttimeslot(ifany).Whenlookingattheoutputonanoscilloscope,wesee wideandnarrowzero-levelpulses,asreflectedinFigure12-4.Anarrowpulseresultsifa1followsthetime slotissuancefromtheslave;awidepulseresultswhena0followsit. Anintegralpartofthe1-wireprotocolistheabilitytoobtainoperatingpowerforthechipsfromthedata line,withoutaseparatepowersupplyline,sometimesreferredtoas“parasitic”powering.One-wiredevices haveaninternalcapacitorthatchargesfromthedatalineandpoweritwhensendinga0Vsignal.(Ifwelook atitindetail,however,we’llseethatparasiticpowerhasitsdrawbacks,soallofourcircuitsuseexternal powerconnections.) Onelastcommentandwe’llseesomerealcode.Eachindividual1-wirepartproducedhasitsownunique 64-bitserialnumberandmaybeaddressedeitherindividuallythroughtheserialnumber,orglobally,withoutreferencetoitsserialnumber.
ReadingaOne-WireDevices’SerialNumber Program12-1readstheserialnumberofaone-wiredeviceconnectedwiththecircuitshowninFigure12-1 andwritesittotheserialoutputport.(Whenbuildingthecircuitdon’tforgetthepull-upresistor!) Program12-1 ;Program12-1 ;Read1-wiredevicew/READROM$33Command ;WriteROMoutput(DeviceID,SN&CheckSum) ;toserialoutput. ;Onlyworkswith1deviceattached! ;Variables Temp i
Var Var
;Constants ReadRomCon
$33
Byte Byte
EnableHSerial SetHSerialH19200 Main ;IssueuniversalREADROMCommand OWOutB0,1,Main,[ReadRom] ;Responseis8bytes ;DeviceFamily 1Byte ;SN 6Bytes ;CheckSum 1Byte Fori=0to7 OWInB0,0,[Temp] HSerOut[HexTemp,”“] Next ;WriteCR HSerOut[13] Pause1000 GoToMain
233
Chapter12 MBasic’ssupportfor1-wiredevicesiscontainedintwoprocedures;OWOutforwritingtothe1-wiredevice andOWInforreadingfromthe1-wiredevice.Ourfirstactionistoinstructthe1-wiredevicetoreportitsserialnumber,throughthefunction:OWOutB0,1,Main,[ReadRom].OWOutisinvokedwiththreeoptions:
OwoutPin,Mode,{NCLabel},[{Mods}Exp]
Pin—isthepintowhichthedatalineisconnected.Pincanbeeitheraconstantoravariable. Mode—definesthespecificsofthedatatransfer.Permissiblemodevaluesare: Mode 0 1 2 3 4 5
SendReset? No BeforeData AfterData BeforeandAfterData No BeforeData
DataMode Byte Byte Byte Byte Bit Bit
Speed Low Low Low Low Low Low
(DallasSemiconductorisexpandingits1-wireproductlinetoincludenewdeviceswithbitratesofseveral hundredkb/sandhasaproposedanevenhigher1Mb/srate.MBasiccurrentlysupportsonlytheinitial14 kb/sspeed1-wireprotocol.) NCLabel—anoptionaladdresslabeltowhichexecutionwilljumpifno1-wirechipisdetected. Mods—MBasic’sstandardcommandmodifiers,forexample,Str,Real,andsoon. Exp—isavariableorconstantholdingthevaluetobesent.
Figure12-1showsB0asthedatapin.Commandswrittentoa1-wiredevicerequirealeadingresetpulse, we’llusemode1.Forsimplicity,we’llomitdeviceconnectionerrorchecking. We’lllookat1-wirecommandsinmoredetailinconnectionwithlaterprograms,butfornowwe’llnote that$33isthecommandvaluefor“readROM,”thatis,sendtheserialnumberofthedevice.Wedeclarea constant,ReadRom,andsetitsvalueto$33.Hence,ourcommandis:
OWOutB0,1,Main,[ReadRom]
Wenowreadtheresponsefromthe1-wiredevicewithOWInandwritetheoutputtotheserialport,onebyte atatime:
Fori=0to7 OWInB0,0,[Temp] HSerOut[HexTemp,”“] Next
OWinfollowsthesamesyntaxasOWOut:
OWInPin,Mode,{NCLabel},[{Mods}Var]
Pin,ModeandNCLabelareidenticalwiththeircorrespondingelementsinOWOut,andrequirenofurther
description.Sincewearereadingavalue,ofcourse,itmustbereadintoavariable,notaconstant. DallasSemiconductor’s1-wirespecificationsdefinedeviceserialnumbersas8bytes(64bits)long,configuredas: 8-bitCRCCode MSB LSB
48-bitSerialNumber MSB LSB
8-bitFamilyCode MSB LSB
Thefamilycodefor18B20digitalthermometerchipsis$28.TheCRC(cyclicredundancycode)isanerror-checkingfeature,sothat,shouldwedesire,wemayverifythatthe56bitsofthefamilycodeandserial numberhavebeencorrectlyreceivedandwerenotcorrupted.We’llnotfurtherconsiderhowCRCsare calculated,asit’satopicwellbeyondthelevelofthisintroductorybook. 234
DigitalTemperatureSensorsandReal-TimeClocks Whenweruntheprogram,weseethefollowingrepetitiveoutput: 284CD43E000D6 284CD43E000D6 284CD43E000D6 …
Thedigits4CD43E000D6are,ofcourse,dependentupontheparticularDS18B20chip.Ipluggedina secondDS18B20chipandfounditsserialnumber: 28FEDA3E000C1 28FEDA3E000C1 28FEDA3E000C1 …
Intheoutput,$28isthefamilynumberand$D6(or$C1inthesecondexample)istheCRC.Thecentersix bytesrepresenttheserialnumberofthechip.But,there’sadifferencebetweentheresultandtheserialnumberspecificationisn’tthere?ThedefinitionhastheCRCsentfirstandthefamilycodesentlast.Yet,Program 12-1displaysthefamilycodefirst,andtheCRClast.Theexplanationisthat1-wiredevicesstoretheleast significantbyteattheloweraddressandthemostsignificantbyteatthehigheraddress.Bytesaretransmittedandreceivedfromlowestaddresstohighestaddress.Hence,theneteffectisthesend/receivebyteorder isreversedfromthedatasheetdescription.Thisismoreconfusingtodescribethantouse;whenwewishto addressaparticulardevice,wejustrepeatthebyteorderwereadwithProgram12-1.
ReadingtheTemperature Program12-1willconfirmthatyourcircuitisproperlywiredupandtheDS18B20isfunctioning.Program 12-2showshowwecanreadthetemperature.(Rememberthe|symbolisalinecontinuation.) ;Program12-2 ;ReadsaDallas1-wireTemperaturesensor ;DS18B20.AssumesonlyONEdeviceisconnectedtothebus, ;sinceweuseglobaladdressmode. ;Variables ;----------------------Temp Var Word PlusFlag Var Byte Centigrade Var Float Fahrenheit Var Float TH Var Byte TL Var Byte ConfigReg Var Byte
;holdsrawbinarytemperatureoutput ;plus/minusflag ;FloatingpointCtemp ;FloatingpointFtemp ;Loweralarmvalue ;Upperalarmvalue ;Temperatureresolution
;Initialization Init ;------------- EnableHSerial SetHSerialH19200
;$4EWritetoRAM;dummy$FFtoTH&TL ;$7Ftoctrlregfor12-bit OWOutB0,1,Init,[$CC,$4E,$FF,$FF,$7F] OWOutB0,1,Init,[$CC,$48] OWOutB0,1,Init,[$CC,$B8]
;Readscratchpadmemory OWOutB0,1,Init,[$CC,$BE] Pause1000 ;Readoutputandcheckconfiguration OWinB0,0,[Temp.Byte0,Temp.Byte1,TH,TL,ConfigReg] HSerOut[“InitOKR1:“,BINConfigReg.Bit6,”R0:“| ,BINConfigReg.Bit5,13]
235
Chapter12 Main Wait
;Causetempconversiontostart OWOutB0,1,Main,[$CC,$44] ;readoutputandloopuntilconversionisdone. ;conversionfinishedifwritebackof1,0ifnotdone ;Notethisonlyworkswithexternalpower OWInB0,0,[Temp] IfTemp=0ThenWait OWOutB0,1,Main,[$CC,$BE] OWinB0,0,[Temp.Byte0,Temp.Byte1,TH,TL,ConfigReg] ;ReadTH,TLandConfigReg,butdon’tuse ;Temperaturedatareturnedas2’scomplementforbelow0. ;Hence,<0isdetectedbya1inthereturnedhighestbit. PlusFlag=1 IfTemp.HighBit=1Then ;checkfor<0C ;Subtractfrom0toreadbelow0value Temp=$0000-Temp PlusFlag=0 EndIf ;ReturnedinCentigradestepsof0.0625DegC. Centigrade=(ToFloatTemp)*0.0625 IfPlusFlag=0Then ;belowzero,multiplyby-1 Centigrade=-Centigrade EndIf ;StandardconversionformulatogettoFfromC. Fahrenheit=(Centigrade*1.8)+32.0;degF ;Writeoutput.Notethe\2and\1modifiersgivenumberof ;placesafterdecimalpoint HSerOut[“Temperature“,RealFahrenheit\2,”F“,Real|Centigrade\1,” C”,13]
Pause2000 GoToMain
Program12-2initializestheDS18B20to12-bitresolutionmode,andthenevery2secondsreadsthetemperatureandwritesthevalueinFahrenheittotheserialport. Program12-2usesglobaladdressingandwillworkonlyifthereisone1-wiredeviceconnectedtothedatabus. Afterdeclaringthenecessaryvariables,weinitializetheDS18B20. TheDS18B20hasvariableresolution,andcanbeprogrammedfor9,10,11or12-bitresolution.(TheDS18S20is avariantwithonly9-bitresolution.)Thetrade-offforincreasedresolutionislongerconversiontime. Resolution 9-bit 10-bit 11-bit 12-bit
ConversionTime 93.75ms 187.5ms 375ms 750ms
Resolution 0.5°C 0.900°F 0.25°C 0.450°F 0.125°C 0.225°F 0.0625°C 0.113°F
R1 0 0 1 1
R0 0 1 0 1
We’lluse12-bitresolution,thedefaultconfigurationforDS18B20devices.Twooptionbits,R1andR0,in theconfigurationregistercontrolresolution,sowe’llsetbothto1toestablish12-bitresolution.Weshould, ofcourse,notconfuseresolutionandaccuracy.Regardlessoftheresolutionselected,theDS18B20’saccuracyremainsat±0.5°Covertherange–10°Cthrough+85°C. Bit7 0
Bit6 R1
Bit5 R0
ConfigurationRegister Bit4 Bit3 Bit2 1 1 1
236
Bit1 1
Bit0 1
DigitalTemperatureSensorsandReal-TimeClocks Theconfigurationwordtocommand12-bitresolutionisthus%01111111,or$7F.How,then,towrite$7F totheconfigurationregister? TheDS18B20’smemoryisorganizedasninebytesofRAMandthreebytesEEPROM.Theconfiguration registerisbyteno.4: Address 0 1 2 3 4 5 6 7 8
ScratchpadMemoryContents TemperatureLSB(readonly) TemperatureMSB(readonly) THRegister TLRegister ConfigurationRegister Reserved($FF) Reserved($0C) Reserved($10) CRC
EEPROM
←→ ←→ ←→
TH TL Configuration
OurabilitytoselectivelywritetothescratchpadandEEPROMislimited.Infact,wehavebutfourmemory commands,plustwofunctioncommands: DS18B20CommandValues Description CommandValue
Command ConvertTemperature ReadScratchpad WriteScratchpad CopyScratchpad RecallEEPROM ReadPowerSupply
Initiatetemperaturereading
$44
Readall9scratchpadlocations
$BE
Writeall3scratchpadlocations,TH,TL andConfigurationRegister CopiesTH,TLandConfigurationfrom thescratchpadtoEEPROM CopiesTH,TLandConfigurationfrom EEPROMtothescratchpad Informsmasterwhether18B20is directlyorparasiticallypowered
$4E $48 $B8 $B4
1-WireBusActivity Transmitconversionstatus(only withexternalpower) DS18B20transmitsupto9 bytestomaster MastertransmitsTH,TLand ConfigurationtoDS18B20 None DS18B20transmitsrecallstatus tomaster DS18B20transmitspower supplystatustomaster
TowritetheresolutioninformationtotheconfigurationregisterandthentotheEEPROM,wemustwrite3 bytes,TH,TLandtheconfigurationbyte.THandTLarealarmtriggerregistersandstorevaluesforhigh (TH)andlow(TL)temperaturealarms.Weshallnotuseeither,sowewillwriteadummyvalue,$FFtoboth THandTL. Onefinalbitofhousekeepingandthenwe’llwriteourconfigurationbits.Beforea1-wiredevicemay receiveanycommands,itmustbeaddressed.We’llcontinueInProgram12-2withglobaladdressing,$CC. All1-wiredevicesrespondtoa$CCaddress,sotoavoiddeviceconflictwemayhaveonlyone1-wiredevice connectedtopinB0.
OWOutB0,1,Init,[$CC,$4E,$FF,$FF,$7F] OWOutB0,1,Init,[$CC,$48] OWOutB0,1,Init,[$CC,$B8] OWOutB0,1,Init,[$CC,$BE] Pause1000 OWinB0,0,[Temp.Byte0,Temp.Byte1,TH,TL,ConfigReg] HSerOut[“InitOKR1:“,BINConfigReg.Bit6,”R0:“| ,BINConfigReg.Bit5,13]
237
Chapter12 Thefirstfourlinesofcodeimplementourstrategy;wewrite$FF,$FF,$7Ftothescratchpadwiththe $4Ecommand.Wethenmovescratchpadmemorylocations2,3and4toEEPROMwitha$48command. Forourdemonstration,wethencopytheEEPROMbacktoscratchpadmemorywitha$B8commandand, finally,readbackthecontentsofthescratchpadwitha$BEcommand.Notethatineverycase,weissuea resetandaglobaladdress($CC)beforethecommandbyte. Wethenreadbackthebytessentafterthe$BEcommandwiththeOWInprocedureandwritethevaluesto theserialport.Theresponseweseefromtheserialportshouldbe: InitOKR1:1R0:1
Now,weinitiateatemperatureread. Main Wait
;Causetempconversiontostart OWOutB0,1,Main,[$CC,$44] ;readoutputandloopuntilconversionisdone. ;conversionfinishedifwritebackof1,0ifnotdone ;Notethisonlyworkswithexternalpower OWInB0,0,[Temp] IfTemp=0ThenWait
Temperaturereadsmuststartwiththe“converttemperature”$44command.Uponreceiptofthe$44,the DS18B20startsthetemperaturereadingprocessanduponcompletionstoresthevalueinthescratchpadat locations0(leastsignificantbyte)and1(mostsignificantbyte).Ifexternallypowered,theDS18B20will respondduringtheconversionprocesswitha0,changingtoa1whencompleted.Hence,afterinitiatingthe converttemperaturecommand,wekeepreadingtheDS18B20untilitreturnsa1,indicatingtemperature dataisreadytoberead. WenowarereadytoreadthetemperaturefromtheDS18B20’sscratchpadmemory.Thedataisreturnedin increasingaddressorder,from0(leastsignificantbyteoftemperature)to4(configurationregister).
OWOutB0,1,Main,[$CC,$BE] OWinB0,0,[Temp.Byte0,Temp.Byte1,TH,TL,ConfigReg] ;ReadTH,TLandConfigReg,butdon’tuse
Thisisthesamecodeweusedwhenreadingtheconfigurationregisterduringinitialization.Now,however, wediscardallreaddata,saveforTemp.Byte0andTemp.Byte1,asthesecontainourtemperaturereading. Thetemperaturedataisreturnedinthefollowingformat: Temp.Byte0 LeastSignificantByte Temp.Byte1 MostSignificantByte
Bit7 23 Bit15 S
Bit6 22 Bit14 S
Bit5 21 Bit13 S
Bit4 20 Bit12 S
Bit3 2–1 Bit11 S
Bit2 2–2 Bit10 26
Bit1 2–3 Bit9 25
Bit0 2–4 Bit8 24
A1atbit0,forexample,represents1×2–4degreesC,or0.0625°C. SincetherangeoftemperaturesreportedbytheDS18B20extendsbelow0°C,thedataincludesasignbit, identifiedas“S”inthetable.Ifthetemperatureisabove0,Sis0;ifbelow0°C,Sis1.Fortemperatures below0,wemustsubtractthereadingfrom$0000toobtainthenumberofdegreesbelow0°C.(Thedatais storedas“a16-bitsign-extendedtwo’scomplementnumber.”Don’tletthisscareyou;it’ssimpletomakeit useful.)
238
DigitalTemperatureSensorsandReal-TimeClocks Here’showvaluesaround0°CarereportedbytheDS18B20: Temperature +10.125°C +0.5°C 0°C -0.5°C -10.125°C
BinaryOutput 0000000010100010 0000000000001000 0000000000000000 1111111111111000 1111111101011110
HexadecimalOutput $00A2 $0008 $0000 $FFF8 $FF5E
Wereadthetwotemperaturebytesoneatatime,storingtheminthewordvariableTemp.Afterreading Temp,wechecktoseeifthereturnedvalueislessthan0°C,asindicatedbya1inatbit15: PlusFlag=1 IfTemp.HighBit=1Then ;checkfor<0C ;Subtractfrom0toreadbelow0value Temp=$0000-Temp PlusFlag=0 EndIf
Ifa1isfound,thenweremovethetwo’scomplementbysubtractingthevaluefrom$0000.Thisgivesthe numberofdegreesbelow0°C.(Ifyou’renotconvinced,subtractitbyhand,oruseWindow’saccessory calculatorinscientificview.For–10.125°C,$0000–$FF5E=$00A2.Decimal($A2)=162.Eachstepis 0.0625°C,so162*0.0625=10.125.)
;ReturnedinCentigradestepsof0.0625DegC. Centigrade=(ToFloatTemp)*0.0625 IfPlusFlag=0Then ;belowzero,multiplyby-1 Centigrade=-Centigrade EndIf ;StandardconversionformulatogettoFfromC. Fahrenheit=(Centigrade*1.8)+32.0;degF
Wenowconvertthereturnedrawtemperatureword(afteranynecessarybelowzerocorrection)toafloating pointCelsius(Centigrade)valuebymultiplyingitbythestepsize,2–4,or0.0625degreesC/step.(2–4isthe sameas1/24,or1/16,whichis0.0625.)SinceTempisaninteger,wefirstconvertittoafloating-pointvalue withtheToFloatoperator.Wethenmultiplybythestepsize.(IfyouruntheDS18B20atlessthan12-bit resolution,theoutputjumpsinlargerintervals,buteachstepremains0.0625°C.) Ifthereturnedvaluewaslessthan0°C,PlusFlaghasbeensetto0,sowemustmultiplythetemperatureby –1,whichisaccomplishedbyprefixingCentigradewithaminussign. Finally,weconvertthefloatingpointCelsiustemperaturetoFahrenheit.
;Writeoutput.Notethe\2and\1modifiersgivenumberof ;placesafterdecimalpoint HSerOut[“Temperature“,RealFahrenheit\2,”F“,Real| Centigrade\1,”C”,13]
Nowwewritethetemperature(inCelsiusandFahrenheit)totheserialport.Noteouruseoftheundocumented\2and\1modifierstodisplaytwoandonedigitsfollowingthedecimalpoint.Here’sasampleoutput fromProgram12-2: InitOKR1:1R0:1 Temperature74.63F23.6C Temperature74.63F23.6C Temperature74.63F23.6C Temperature74.63F23.6C Temperature73.62F23.1C
239
Chapter12 ReadingMultipleSensorsontheSameBus Aprimaryadvantageofthe1-wirebusisthatwemayplacemanysensorsonit,andselectivelyreadeach one.Let’strysomethingsimple,oneindoortemperaturesensorandoneoutdoorsensor,bothconnectedto B0,asshowninFigure12-5.
Figure12-5:MultipleDS18B20temperaturesensorsononebus.
First,though,runProgram12-1foreachDS18B20andnotetheirserialnumbers.ThetwosensorsIhadon handidentifiedthemselvesas: 284CD43E000D6 28FEDA3E000C1
ImadeasimpletemporaryoutdoorsensormountfromashortlengthofPVC pipeandfittings,asshowninFigure12-6.Thesensorisatthetopofthe“T” fittingandIsoldereditsthreepinstothreeconductorsinashortlengthof CAT5datacable.Istuffedthecableopeningofthe“T”withafewplastic shippingpelletsforweatherproofingandbroughtthefreeendofthecable intomyworkshop.(Reference[12-7]discussescableselectionanddistance issuesandshouldbeconsultedforcablerunsmorethanacoupledozenfeet.) TheothersensorImountedonthebreadboardforanindoorcomparison reading. Program12-3selectivelyreadstheindoorandoutdoorsensorsandwrites theirreadingstotheserialport. Program12-3 ;Program12-3Read2DS18B20temperature ;sensorsconnectedtothesamebus. ;Writethetwotemperaturestoserialoutput ;ThesensorsareaddressedbySN ;Variables
240
Figure12-6:Temporaryoutdoor temperaturesensormounting.
DigitalTemperatureSensorsandReal-TimeClocks ;----------------------Temp Var Word PlusFlag Var Byte Centigrade Var Float Fahrenheit Var Float TH Var Byte TL Var Byte ConfigReg Var Byte
;holdsrawbinarytemperatureoutput ;plus/minusflag ;FloatingpointCtemp ;FloatingpointFtemp ;Loweralarmvalue ;Upperalarmvalue ;Temperatureresolution
;ThefullROMSNofthetwoDS18B20SensorChips ;Chip1$28$FE$DA$3E$0$0$0$C1 ;Chip2$28$48$D4$3E$0$0$0$D6 ;yoursensorswillhavedifferentserialnumbers! ;Initialization ;--------------- EnableHSerial SetHSerialH19200 ;Initializebothsensorsto12-bitresolution. ;Sincewehavemultiplesensorsonsamebus,wemustuse ;selectiveaddressing$55followedby8-bytechipaddress ;Otherwise,routineissameasProgram12-2. Init1 ;---------------OWOutB0,1,Init1,[$55,$28,$FE,$DA,| $3E,$0,$0,$0,$C1,$4E,$FF,$FF,$7F] OWOutB0,1,Init1,[$55,$28,$FE,$DA,$3E,$0,$0,$0,$C1,$48] OWOutB0,1,Init1,[$55,$28,$FE,$DA,$3E,$0,$0,$0,$C1,$B8] OWOutB0,1,Init1,[$55,$28,$FE,$DA,$3E,$0,$0,$0,$C1,$BE] Pause1000 ;Readoutputandcheckconfiguration OWinB0,0,[Temp.Byte0,Temp.Byte1,TH,TL,ConfigReg] HSerOut[“Init1OKR1:“,BINConfigReg.Bit6,| “R0:“,BINConfigReg.Bit5,13] Init2 ;---------------- OWOutB0,1,Init2,[$55,$28,$48,$D4,| $3E,$0,$0,$0,$D6,$4E,$FF,$FF,$7F] OWOutB0,1,Init2,[$55,$28,$48,$D4,$3E,$0,$0,$0,$D6,$48] OWOutB0,1,Init2,[$55,$28,$48,$D4,$3E,$0,$0,$0,$D6,$B8] OWOutB0,1,Init2,[$55,$28,$48,$D4,$3E,$0,$0,$0,$D6,$BE] Pause1000 ;Readoutputandcheckconfiguration OWinB0,0,[Temp.Byte0,Temp.Byte1,TH,TL,ConfigReg] HSerOut[“Init2OKR1:“,BINConfigReg.Bit6,| “R0“,BINConfigReg.Bit5,13] Main ;SelectivestartofconversiononChipNo.1 ;Againwestartwith$55,ChipAddress OWOutB0,1,Main,[$55,$28,$FE,$DA,$3E,$0,$0,$0,$C1,$44] Wait ;Waitforgooddata OWInB0,0,[Temp] IfTemp=0ThenWait ;SelectivereadofdataonChipNo.1 OWOutB0,1,Main,[$55,$28,$FE,$DA,$3E,$0,$0,$0,$C1,$BE] OWinB0,0,[Temp.Byte0,Temp.Byte1] ;Fromrawdata,computeCentigradeandFahrenheit GoSubComputeTemp HSerOut[“Sensor1“] ;WritetheDegreesFandDegreesCtotheserialport GoSubWriteTemp
241
Chapter12 ;------------------------SensorNo.2----------------------;NowwerepeatbutwiththeSensorNo.2SelectiveAddress Part2 OWOutB0,1,Part2,[$55,$28,$48,$D4,$3E,$0,$0,$0,$D6,$44] Wait2 OWInB0,0,[Temp] IfTemp=0ThenWait2 OWOutB0,1,Part2,[$55,$28,$48,$D4,$3E,$0,$0,$0,$D6,$BE] OWinB0,0,[Temp.Byte0,Temp.Byte1] GoSubComputeTemp HSerOut[$9,”Sensor2“] GoSubWriteTemp HSerOut[13] Pause1000 GoToMain ComputeTemp ;-------------
;SubroutineacceptsrawdataandoutputsDegFandDegC
;Rawdataisin2’scomplementiflessthan0C. ;Checkhighbitfor<0
PlusFlag=1 IfTemp.HighBit=1Then;checkfor<0C Temp=$0000-Temp ;Justsubtracttoconvert PlusFlag=0 EndIf Centigrade=(ToFloatTemp)*0.0625;step0.0625degC IfPlusFlag=0Then ;belowzero Centigrade=fnegCentigrade ;If<0addminussign EndIf
Return
;StandardconversionfromCentigradetoFahrenheit Fahrenheit=(Centigrade*1.8)+32.0 ;CentigradetodegF
WriteTemp ;------------- ;Writegenericoutputtoserial ;\2and\1fixthenumberofdigitsafter. ;thataredisplayed HSerOut[RealFahrenheit\2,”F“,RealCentigrade\1,”C”] Return
We’llconcentrateonthechangedpartsofthisprogram,asitlargelyduplicateswhatwelearnedinProgram12-2. SincewehavetwoDS18B20sensorsonthesamebus,wemustselectivelyaddresseachone,insteadofusingthe$CCuniversaladdress.Wedothissimplybyreplacing$CCwith$55,followedbythe8-byteserial numberofthedevice.Hence,toinitializetheconfigurationregisterwehave: Universaladdressversion:
OWOutB0,1,Init,[$CC,$4E,$FF,$FF,$7F]
SelectiveaddressversionforDS18B20withSN$28$FE$DA$3E$00$00$00$C1: OWOutB0,1,Init1,[$55,$28,$FE,$DA,$3E,$0,$0,$0,| $C1,$4E,$FF,$FF,$7F]
(Rememberthe|isthelinecontinuationsymbol.) Sincewehavetwodevicestoinitialize,werepeattheselectiveinitializationtwice,onceforeachdevice. 242
DigitalTemperatureSensorsandReal-TimeClocks Themainprogramlooplikewiseselectivelyaddressesonesensor,callsthesubroutineComputeTempto converttherawtemperaturewordtoCentigradeandFahrenheitvalues,andthencallsasecondsubroutine, WriteTemp,towritetheCentigradeandFahrenheitvaluestotheserialoutputport.(The$9characterisa horizontaltab,usedtospacetheresultsacrosstheterminalscreen.) Thetwosubroutines,ComputeTempandWriteTemptracktheembeddedcodeinProgram12-2. Here’stheoutputofProgram12-3,takenbeforeIassembledtheoutdoorsensorandmoveditoutside: Init1OKR1:1R0:1 Init2OKR1:1R0:1 Sensor174.74F23.7C Sensor174.74F23.7C Sensor173.84F23.2C Sensor174.97F23.8C Sensor180.26F26.8C Sensor178.46F25.8C Sensor177.22F25.1C Sensor176.32F24.6C Sensor175.76F24.3C Sensor175.64F24.2C
Sensor274.74F23.7C Sensor274.74F23.7C Sensor274.63F23.6C Sensor274.63F23.6C Sensor274.86F23.8C←FingeronSensor1 Sensor274.86F23.8C Sensor279.02F26.1C←FingeronSensor2 Sensor282.51F28.0C Sensor280.37F26.8C Sensor278.57F25.8C
Toseehowfastthesensorsreact,Igraspedeachonebetweentwofingersforafewseconds.(Themeasurementcycleisabout4secondsperreading.)Ittookonlyonereadcycletoseethetemperaturestarttorise, andaboutfiveorsixcyclesto returntoambient.
DS1302Real-TimeClock Nowthatwe’vegottenthetemperatureoutoftheway,let’slook attimekeeping.Wecoulduseour PICasaclock,suchasdescribedin Reference[12-9].But,we’regoing tounloadthetimekeepingfunction ontoadedicatedspecialpurpose chipfromDallasSemiconductor, theDS1302. TheDS1302isarealtimeclock, requiringanexternal32.678KHz crystal.TheDS1302provides seconds,minutes,hours,day-ofthe-week,date,monthandyear information,includingleapyear adjustmentupto2100.Italsosupportsbatteryorcapacitorbackup, andincludesanintegratedtrickle charger.TheDS1302communicates withthePICviaathree-wireserial connection,supportedbyMBasic’s ShiftInandShiftOutprocedures. Figure12-7:ConnectingaDS1302real-timeclock. 243
Chapter12 We’llconnecttheDS1302toourPICusingthecircuitshowninFigure12-7.AcouplepointsinFigure12-7 deserveamplification.First,wehavechosenaverylargecapacitor,0.47F,toserveasourpowersupply backup.Oncefullycharged(ittakesalittleover1hour),the0.47FcapacitorwillkeeptheDS1302runningatleastadayiftheprimarypowerisinterrupted.Second,theDS1302’saccuracyisdependentuponthe accuracyofthe32.678KHzcrystal.Thecrystal’sdesigncapacitanceshouldmatchthe6pFspecificationof theDS1302.(Ifwedesireprecisiontimekeeping,therearemanymorethingsthatwillconcernus,butthose arebeyondthescopeofthischapter.See,forexample,Reference[12-10].) TheDS1302hasthreeconnectionstothePIC: SCLK(SerialClockInput)—Theclockdetermineswhendatabitsarereceivedandvalid.Dataistransferred totheDS1302orreadfromtheDS1302whentheclockchangesstate.DataisreceivedbytheDS1302 duringtherisingedge.DataistransmittedbytheDS1302onthefallingedgeoftheclock,butareread bythePICmasterontherisingedge.AllclockpulsesaregeneratedbythePIC;theDS1302onlyreceivesclockpulsesandcannotgeneratethem. I/O(Data)—Thedatalineestablisheswhethera1ora0isreadattheappropriateclockedge.Thedataline isbi-directional;theDS1302maysendtothePICorthePICmaysendtotheDS1302. RST(Reset)—Theresetlineservestwopurposes.First,whentakenhighitturnsontheDS1302’scontrol logic.Second,whentakenfromhightolow,itterminatesdatatransferfromthePICtotheDS1302.The PICcontrolstheresetline. Figure12-8showsasampledataexchangebetweenaPICandaDS1302.Atotalof5bytesareexchanged. Figure12-9moreclearlyillustratetherelationshipbetweentheclockanddatalines.
Figure 12-9: Expanded View of Data Transfer DS1302Ch1:Clock;Ch2:Data
Figure12-8:DataTransferDS1302Ch1:Clock; Ch2:Data.
Fortunately,MBasichidesthedetailsofdatatransfertoandfromtheDS1302. Program12-4readstheDS1302andwritesthecurrenttime,onceeverysecond,totheserialport. Program12-4 ;Program12-4.ReadsaDallas/MaximDS1302 ;Realtimeclock. ;Alsowritesthecurrenttimetotheclock ;Varibles ;--------------RTCCmd Var Temp Var i Var TimeData Var OldSeconds Var
Byte Byte Byte Byte(7) Byte
244
;Commandbyte ;Temporaryvariable ;counter ;lastreadseconds
DigitalTemperatureSensorsandReal-TimeClocks ;Forconvienencewealiasthetimearray Seconds Var TimeData(0) Minutes Var TimeData(1) Hours Var TimeData(2) Date Var TimeData(3) Month Var TimeData(4) Day Var TimeData(5) Year Var TimeData(6)
;Seconds ;Minutes ;Hours ;DayofMonth ;Month ;DayofWeek ;Year
;Constants ;-------------- Clk Con Dta Con Reset Con
()areDIP8numbers A0 ;Clockpin(7) A1 ;Datapin(6) A2 ;Resetpin(5)
CtrlReg
%00111
Con
;InitialloadofSecMinHrsDateMODayYR PreSetByteTable$00,$53,$12,$24,$11,$02,$03 ;TheseareinBCD,henceNovember(Month11) ;isenteredas$11,not11. ;Commandtoselectchargersettings Charger Con %01000 ;1diode,2Kchargingresistance.See ;Figure5ofDS1320datasheet Battery Con %10100101 ;ForDayandMonthnames,usethefollowing.Since ;Sun=1andJan=1weusenulatthebeginninginsteadof ;subtracting1. DayNameByteTable“NulSunMonTueWedThuFriSatSun” MoNameByteTable“NulJanFebMarAprMayJunJulAugSepOctNovDec” ;Initialization ;------------- EnableHSerial SetHSerialH19200
;Tosettheclockwefirstdisablewriteprotection. ;Thensendtheclocksetinformation,andthenrestore ;writeprotection.
SetthedateandtimefromthePresetbytetable Fori=0to6 Temp=Preset(i) RTCCmd=i GoSubPreSetData Next
;DS1302Writeprotectionbackon Temp=$80 RTCCmd=CtrlReg GoSubPreSetData
;DisableDS1302WriteProtectionby0inBit7 Temp=$00 RTCCmd=CtrlReg GoSubPreSetData
;SincewehaveaSuperCapbackup,wewantchargerON Temp=Battery RTCCmd=Charger GoSubPreSetData
Loop ;--------- ;Readtheclockoutput.Ifsecondschanged,writetime GoSubReadData
245
Chapter12
;Writeinform: ;13:10:4511/24/03Mon24-Nov-2003totheserialport ;Newseconds,sowriteoutput IfOldSeconds<>SecondsThen HSerOut[Dec2(BCD2BINHours)\2,”:”,Dec2| (BCD2BINMinutes)\2,”:”,Dec2(BCD2BINSeconds)\2] HSerOut[““,Dec2(BCD2BINMonth)\2,”/”,Dec2| (BCD2BINDate)\2,”/”,Dec2(BCD2BINYear)\2] HSerOut[““,StrDayName(Day*3)\3,”“] HSerOut[Dec2(BCD2BINDate)\2,”-”,Str| MoName(3*BCD2BINMonth)\3,”-20”,Dec2(BCD2BINYear)\2,13] EndIf GoToLoop PreSetData ;RoutinetouploaddatatotheDS1302 ;---------- HighReset ;The%0\1,RTCCmd\5,%10\2resultsintheequivelentof ;sending10RTCCMD0.Eachelementissentinelementorder ;butbitreversed,asrequiredbytheDS1320. ShiftOutDta,Clk,LSBFIRST,[%0\1,RTCCmd\5,%10\2,Temp\8] LowReset Return ReadData ;--------- ;Resetpinmustbehighforread HighReset ;%10111111isBURSTSENDREGISTERcommand,soget8bytes ;thelastbyteisthecontrolregister,whichwedon’tuse ShiftOutDta,Clk,LSBFirst,[%10111111\8] OldSeconds=Seconds ;Nowactuallyreadtheburstsenddata. ShiftInDta,Clk,LSBPRE,[Seconds\8,Minutes\8,Hours\8,| Date\8,Month\8,Day\8,Year\8] LowReset Return
We’vesetupaseven-elementdatastructuretoholdtimeanddateinformationfromtheDS1302: TimeData
Var
Byte(7)
;Forconvienencewealiasthetimearray SecondsVar TimeData(0) MinutesVar TimeData(1) Hours Var TimeData(2) Date Var TimeData(3) Month Var TimeData(4) Day Var TimeData(5) Year Var TimeData(6)
;Seconds ;Minutes ;Hours ;DayofMonth ;Month ;DayofWeek ;Year
ClockandcalendardataisheldintheDS1302ina10-byteregisterstructure: RegisterAddress 0 1 2 3 4 5 6 7 8 9
Contents Seconds Minutes Hours Date(DayofMonth) Month DayofWeek Year ControlRegister TrickleChargerControl ClockBurstRegister
246
DigitalTemperatureSensorsandReal-TimeClocks Inaddition,theDS1302has31bytesofgeneral-purposeRAM,atmemoryaddresses0…31 TheindexvaluesofdataarrayTimeDataalignwiththeDS1302’smemoryaddresses.We’vealsoaliased “userfriendly”functionalnamesforeachelementofTimeData. ;Constants ;-------------- Clk Con Dta Con Reset Con
()areDIP8numbers A0 ;Clockpin(7) A1 ;Datapin(6) A2 ;Resetpin(5)
Asusual,wedefinethethreeconnectionpinsbydeclaringthreecustomconstants,Clk,DtaandReset. ;InitialloadofSecMinHrsDateMODayYR PreSetByteTable$00,$53,$12,$24,$11,$02,$03 ;TheseareinBCD,henceNovember(Month11) ;isenteredas$11,not11.
Atthefirstpower-up—andwheneverpowerisremovedwithoutthebackup“supercap”inplace—wemust initializetheDS1302withthecurrentdate,timeanddayofweek.Forclarity,we’llstoretheinitialization informationinabytetable. Thesevendate,timeanddayofweekvaluesarestoredintheDS1302inbinarycodeddecimalformat. We’vecoveredBCDinChapter7andwon’trevisitithere,excepttoremindyouthateachnibbleinaBCD byteisregardedasaseparatedigit,rangingfrom0…9.Hence,theBCDrepresentationofthenumber28 (decimal)is$28(decimal40).ThedayoftheweekentrystartswithSunday=1.Forconvenienceinsetting theclock,we’llstorethebytetableinthesameorderitwillbesenttotheDS1302—thatis,intheDS1302’s internaladdressorder.Accordingly,12:53:00,Monday,24November2003isstoredinourbytetableas $00,$53,$12,$24,$11,$02,$03. ;Commandtoselectchargersettings Charger Con %01000 ;1diode,2Kchargingresistance.See ;Figure5ofDS1320datasheet Battery Con %10100101
Sinceweprovidebackuppower,it’snecessarytoenabletheinternalchargercircuitryintheDS1302,asthe defaultstatusisdisabled. ThisisanappropriatetimetolookathowweexchangedatawiththeDS1302.It’sastraightforwardtwostepprocess: • SendacommandbytetotheDS1302 • SendoneormorebytesofdatatotheDS1302,orreceiveoneormorebytesofdatafromthe DS1302,ifthecommandbytecallsforreadingdata. TheDS1302’scommandbytestructureisquitelogical: Bit7 0=WriteDisabled 1=WriteEnable
Bit6 0=Register 1=RAM
Bit5
Bit4
Bit3
Bit2
Bit1
5-bitrepresentationofRegisterorRAMAddress
Bit0 0=Write 1=Read
The5-bitrepresentationsoftheregisterorRAMaddressmeansthattheleadingthreezerosaretruncated fromthenormal8-bitbinaryrepresentation.Forexample,thenormalbyte-lengthbinaryrepresentationof thedigit8is%00001000.The5-bitrepresentationis%01000. Bit6ofthecommandbytedetermineswhetherweareaddressingtheDS1302’sregistersoritsgeneral-purposeRAM.(Allofourcommunicationswillbewiththeregisters,andwewon’tusetheDS1302’sRAMat all.Hence,Bit6willalwaysbe0inthischapter’sprograms.) Tosetthevalueofthedayofthemonthtotheday-of-the-monthregisterwesendtwobytestotheDS1302; firstthecommandbyte,followedbythevaluetobeloadedintotheDS1302.Supposewearetosettheday 247
Chapter12 ofthemonthtothe28th.TheBCDrepresentationofthe28this$28.Let’sdeterminethecommandbyte: • Bit7mustbe%1,sincewearewritingdatatotheDS1302 • Bit6mustbe%0,sincewearewritingdatatoaregister,notRAM. • Bits5…1arethe5-bitrepresentationoftheaddressofthedayofthemonthregister.Thedayofthe monthregisterisnumber3,sothe5-bitrepresentationis%00011. • Bit0mustbe%0,sincewearewritingdatatotheDS1302. Hence,ourcommandbyteis: Bit7 1
Bit6 0
Bit5 0
Bit4 0
Bit3 0
Bit2 1
Bit1 1
Bit0 0
Thisbinaryvaluecorrespondsto$86.Hence,tosettheday-of-the-monthtothe28th,wemustsendthetwo bytesequence$86$28totheDS1302. Onemorehousekeepingdetailbeforewesettheclock.Bit7ofthecontrolregisterisamasterwriteprotect bit.Itmustbesetto1beforeanydatamaybewrittentoeithertheDS1302’sregistersorRAM. Bit7 0=MasterWriteEnable 1=MasterWriteDisable
Bit6 0
DS1302ControlRegister Bit5 Bit4 Bit3 0
0
Bit2
Bit1
Bit0
0
0
0
0
Thecontrolregister’saddressis7,soits5-bitbinaryaddressis%00111.We’vepredefinedthisvalueasa constant,CtrlReg,whichwewilluseinsteadof%00111. So,inpseudo-code,we’llusethefollowingalgorithmtosettheclockvalues: TakeResetpinhightopermitwriting SetBit7ofthecontrolregisterto0toenablewrite Sequentiallywritetheclockvalues: Fori=0(Seconds)to6(Years) Constructcontrolbyte Sendcontrolbyte SenddatabytefromPreSet Nexti SetBit7ofthecontrolregisterto1protectingagainst Furtherchangestothedateandtime. TakeResetpinlowtoblockwriting
Here’stheactualcode: ;DisableDS1302WriteProtectionby0inBit7 Temp=$00 RTCCmd=CtrlReg GoSubPreSetData
SetthedateandtimefromthePresetbytetable Fori=0to6 Temp=Preset(i) RTCCmd=i GoSubPreSetData Next
PreSetData ;RoutinetouploaddatatotheDS1302 ;---------- HighReset ;The%0\1,RTCCmd\5,%10\2resultsintheequivelentof ;sending10RTCCMD0.Eachelementissentinelementorder ;butbitreversed,asrequiredbytheDS1320. ShiftOutDta,Clk,LSBFIRST,[%0\1,RTCCmd\5,%10\2,Temp\8] LowReset Return
248
DigitalTemperatureSensorsandReal-TimeClocks Ittracksthepseudo-codequiteclosely.First,themasterwriteprotectbitiscleared,andthentheseventime/ dateregistersareset. Theonlytrickypartofthisprogramfragmentcentersaround: ShiftOutDta,Clk,LSBFIRST,[%0\1,RTCCmd\5,%10\2,Temp\8]
Let’slookatShiftOut.ShiftOutisinvokedwiththreearguments: Dta—Aconstantorvariablethatdefinesthedatapin.(WedeclaredDtaaconstantequaltopinA1.) Clk—Aconstantorvariablethatdefinestheclockpin.(WedeclaredClkaconstantequaltopinA0.) Mode—Modeisavaluethatdefinestheorderinwhichthebitsaresent,andtherelationshipbetweenthe clock(riseorfall)anddatabeingvalid,meaningisthedatavalidonclockriseoronclockfall?Beginningwithversion5.3.0.0,MBasicpermitsShiftOuttohaveoneof12possiblemodes.
HighSpeed (allnewin5.3.0.0)
SlowSpeed (allnewin5.3.0.0)
NormalSpeed {}indicatesbackwards compatibleforolderversions
ModeConstant FASTMSBPRE FASTLSBPRE FASTMSBPOST FASTLSPOST SLOWMSBPRE SLOWLSBPRE SLOWMSBPOST SLOWLSBPOST MSBPRE {MSBFIRST} LSBPRE {LSBFIRST} MSBPOST LSBPOST
BitOrder MSBfirst LSBfirst MSBfirst LSBfirst MSBfirst LSBfirst MSBfirst LSBfirst MSBfirst LSBfirst MSBfirst LSBfirst
Clock/Data Relationship Datavalidon leadingedge Datavalidon fallingedge Datavalidon leadingedge Datavalidon leadingedge Datavalidon leadingedge
Speed (Machine Cyles)
Speed(With 20MHzclock)
25
200KHz (5µs/bit)
100
50KHz (20µs/bit)
50
100KHz (10µs/bit)
Datavalidon leadingedge
TheDS1302requiresmediumspeed,LSB-firstbitorder,andthebitsamplebeforeclockpulsespeed. Hence,themodeweshalluseisLSBFIRST,bothforShiftInandShiftOut. Let’sexaminetheinformationbeingsent,[%0\1,RTCCmd\5,%10\2,Temp\8].Wesendfourseparateelements,%0,RTCCmd,%10,andTemp.Eachelementissentinitsorderofappearance(lefttoright),butwith itsbitssentLSBfirst.Onlythenumberofbitsspecifiedbythe\xcommandissent.Supposewe’reclearingthemasterwriteprotectionbit.Inthiscase,RTCCmdissettoCtrlReg(%00111)andTempissetto $00.Thecontrolbyteissentasthecompositeofthefirstthreeelements,sentinelementorder,butwithbits reversed: %0 1 0
2 1
3 1
SendOrder %00111 4 5 1 0
%10 6 0
7 0
8 1
Insendingorder,therefore,thefirstthreeelementsaresentas%01110001.TheDS1302receiveseight bitsinthatorder,andreassemblesitintothenormalbyteorderas%10001110.Recallinghowthecommandbyteisconstructed,weseethatthebytereassembledbytheDS1302instructsitthatthenextbyteis tobestoredinthecommandregister.Sincethenextbytesent,Temp,is$00,thenetresultofShiftOut Dta,Clk,LSBFIRST,[%0\1,RTCCmd\5,%10\2,Temp\8]istowritea%00000000intothecommand register,thusactivatingthemasterwriteenable. 249
Chapter12 Withthisunderstanding,wecannowseehowthefollowingcodefragmentworks.
Fori=0to6 Temp=Preset(i) RTCCmd=i GoSubPreSetData Next
ThecommandbyteisassembledinthesubroutinePreSetData,justaswe’vegonethrough.Hence,the SecondsvaluethatiscontainedatPreset(0)iswrittentotheSecondsregister(address0intheDS1302), theMinutesvaluethatiscontainedatPreset(1)iswrittentotheMinutesregister(address1inthe DS1302)andsoforth.
;SIncewehaveaSuperCapbackup,wewantchargerON Temp=Battery RTCCmd=Charger GoSubPreSetData
WeusethesameapproachtoenabletheDS1302’sbuilt-inbackuppowersupplychargingcircuit.We’vepredefinedChargeras%01000,or8,theaddressofthechargercontrolregister.Thechargeroptionsbytehas multipleoptions: Bit7
Bit7 Bit5 TrickleChargerControlBits(TCS)
Bit4
Bit3 Bit2 DiodeControlBits
Bit1 Bit0 ResistorControlBits
TheTCSbitsdeterminewhetherthechargerisactive,ordisabled.Thedefaultisdisabled,andonlytheTCS bitpattern%1010enablesthecharger.AnyotherbitpatternintheTCSbitsdisablesthecharger. TopreventthebackuppowerfromtryingtorunallthedevicesconnectedtotheVCCline,theDS1302includesreversecurrentisolationdiodes.Bits3and2determinewhetheroneortwodiodeswillbeinseries. Twodiodesincreasetheisolation,butaddanextra0.7Vdroptothechargingvoltage. Permittedvaluesforbits3and2are: Bit3 0 0 1 1
Bit2 0 1 0 1
DiodeConnection Tricklechargerdisabled,independentlyofTCSbits Oneseriesdiodeselected Twoseriesdiodesselected Tricklechargerdisabled,independentlyofTCSbits
Finally,Bits1and0determinethechargingcurrent,byselectingtheseriesresistorvalue: Bit1 0 0 1 1
Bit0 0 1 0 1
ResistorConnection None Typically2Kohm Typically4Kohm Typically8Kohm
We’veselectedTCS—enabled,onediodeand2Kohmseriesresistance.Hence,ourchargeroptionbyteis %10100101,andwe’vedefinedtheconstantBatteryaccordingly: Battery
Con
%10100101
ToactivatethechargerweusethesubroutinePreSetDatatoloadtheappropriatecommandbyte(constructedinPreSetDatafromthe5-bitaddressCharger),followedbytheBatteryoptionbyte. Abriefwordonbackuppowerisappropriate.Atonetime,ourchoicewouldhavebeenlimitedtoachoice ofbatterychemistry.Wemighthavechosenfromamongavarietyofprimary(nonrechargeable)batteries,
250
DigitalTemperatureSensorsandReal-TimeClocks orsecondary(rechargeable)batteries.But,recentlysupercapacitors—capacitorswithvaluesof0.1Farador more—haveappearedonthemarket.Forlowcurrentdraindevices,asupercaphasmanyadvantagesover abattery,mostimportantlyitsmuchlongerlifetime.Theparticularsupercapwe’reusingisa0.47F,5V device.Itchargestoessentiallyfullcapacityinabout4,000seconds,orjustoveronehour,whenweselect a2KchargingresistorandonediodeoptionsintheDS1302chargeroptionbyte.(Supercapsareknownfor highlevelsofdielectricabsorption,someasurablechargingcurrentmaybeobservedforhundreds,orthousandsofhours.)TheDS1302consumes0.3µAoperatingcurrentandwillcontinuetooperateuntil2.0V.Hence, neglectinginternallossesinthesupercap,the0.47FbackupcapacitorwillallowtheDS1302tocontinue operatingforapproximately3.6millionseconds—about41daysafterpowerisremoved.Inpractice,the supercap’sleakagecurrentmaybeasmuchas10µAormore,whichlimitsthebackupoperationtoaround oneday,stillmorethanadequatetocarryoperationoverduringnormalpoweroutages.Ifwerequireextendedoperationwithoutmainspower,thenweshouldconsiderbatterybackup,perhapsalonglifelithium primarybattery. Sincethetimekeepingcontinuesduringpoweroutages,weneedonlysettheclockonceandthereaftermay commentouttheclocksettingpartsofProgram12-4. Nowthatwe’vesettheclock,let’sreaditandwritethecurrenttimetotheserialport.We’vebundledallthe readcodeintothesubroutineReadData,solet’slookatitfirst. ReadData ;--------- ;Resetpinmustbehighforread HighReset ;%10111111isBURSTSENDREGISTERcommand,soget8bytes ;thelastbyteisthecontrolregister,whichwedon’tuse ShiftOutDta,Clk,LSBFirst,[%10111111\8] OldSeconds=Seconds ;Nowactuallyreadtheburstsenddata. ShiftInDta,Clk,LSBPRE,[Seconds\8,Minutes\8,Hours\8,| Date\8,Month\8,Day\8,Year\8] LowReset Return
Largepartsofthisshouldlookfamiliar. BeforedoinganythingwiththeDS1302,wemustbringtheresetpinhigh.Next,wesendacommandbyte totheDS1302usingShiftOut.Theparticularcommandbytewesendisthe“clock/calendarburstread” command,%10111111,andwedon’thavetoconstructitfromacompositeofthreeelements.Theclock/calendarburstreadcommandinstructstheDS1302tosendthecontentsofthefirsteightregistersinaddress order(startingwithsecondsandendingwiththecontrolregister)sequentially,withoutfurthercommands fromthemasterPIC. Followingtheclock/calendarburstreadcommand,wereadthefirstsevenbyteswiththeShiftIn procedure:ShiftInDta,Clk,LSBPRE,[Seconds\8,Minutes\8,Hours\8,Date\8,Month\8,Day\ 8,Year\8].(ShiftInisthereceiveversionofShiftOutandrequiresthesameargumentsandmode selection,sowewon’telaborateonit.) Wereadthefirst7bytesintothearrayTimeData,usingthealiasvariablesSeconds,Minutes,andsoon thatweearlierdeclared.InsteadofusingtheDS1302’sclock/calendarburstreadfunction,wecouldhave individuallyreadthefirstsevenregistersintotheelementsofTimeData(),usingcodemuchlikethatfound inPreSetData,thatis,sendacommandbytetoreadregister0,thenreadthevalueintoTimeData(0), repeatforregister1,andsoforth. Now,let’slookathowwecallReadDataandwhatwedowiththetimeinformationitreturns.
251
Chapter12 Loop ;--------- ;Readtheclockoutput.Ifsecondschanged,writetime GoSubReadData ;Writeinform: ;13:10:4511/24/03Mon24-Nov-2003totheserialport ;Newseconds,sowriteoutput IfOldSeconds<>SecondsThen HSerOut[Dec2(BCD2BINHours)\2,”:”,Dec2| (BCD2BINMinutes)\2,”:”,Dec2(BCD2BINSeconds)\2] HSerOut[““,Dec2(BCD2BINMonth)\2,”/”,Dec2| (BCD2BINDate)\2,”/”,Dec2(BCD2BINYear)\2] HSerOut[““,StrDayName(Day*3)\3,”“] HSerOut[Dec2(BCD2BINDate)\2,”-”,Str| MoName(3*BCD2BINMonth)\3,”-20”,Dec2(BCD2BINYear)\2,13] EndIf GoToLoop
OurmainprogramloopcallsReadDatatoobtainthecurrenttimeanddate.Wethencomparethecurrent valueofSecondswiththevaluelasttimewecalledReadData,heldinOldSeconds.Ifthevalueisdifferent,wewritethecurrenttimetotheserialportwithaseriesofHserOutcallsandupdatethevalueof OldSeconds. TheHserOutcallsaremostlystraightforward,butafewpointsareworthyofnote.Sincetherawdataisin BCDform,weuseMBasic’sBCD2BINfunctiontoconverttothestandardbinaryformwithwhichweareaccustomed.Togiveamonthnameandday-of-weeknameoutput,weearlierdefinedbytetablesDayNameand MoName(monthname).Weindexintothesearrayswiththeday-of-the-weeknumber,orthemonthnumber. Sinceboththemonthandday-of-weekstartwith1,weaddedthedummystring“Nul”tothebeginningof bothDayNameandMoName.Alternatively,wecouldhavestartedthebytetableswith“Sun”and“Jan”and subtracted1fromtheday-of-weeknumberandmonthnumber. FollowingisasampleofProgram12-4’soutput: 13:20:5611/24/03Mon24-Nov-2003 13:20:5711/24/03Mon24-Nov-2003 13:20:5811/24/03Mon24-Nov-2003 13:20:5911/24/03Mon24-Nov-2003 13:21:0011/24/03Mon24-Nov-2003 13:21:0111/24/03Mon24-Nov-2003 13:21:0211/24/03Mon24-Nov-2003
CombinationDate,TimeandTemperature Let’smergeourprogramtoreadtwotemperaturesensors,andaddaDS1302real-time-clocktoyieldatime andtemperatureloggingoutput.Program12-5readstwoDS18B20temperaturesensorsandaDS1302clock chipandwritesthetimeandtemperaturereadingstotheserialport.Figure12-10showsthecircuithookup. DependingonthelengthofthecabletotheremoteDS18B20,itmaybenecessarytodecreasethevalueof R1,thepull-upresistor.Itcanbeaslowas220ohms,ifrequired. Program12-5 Program12-5isverylongandislargelyacompositeofearlierprogramsinthischapter.Ratherthanfollow ournormalstructureoflistingtheprograminfull,followedbyasection-by-sectionanalysis,we’llskip thefulllisting.Program12-5,likeallotherprogramsinthisbook,isavailableinanelectroniccopyinthe associatedCD-ROM.Ifyouneedalistingtofollowwhilereadingtheanalysis,youmayprintonefromthe programfile.
252
DigitalTemperatureSensorsandReal-TimeClocks
Figure12-10:Circuittoreadtwotemperaturevaluesandtimeofday.
Program12-5should,bynow,requirelittleanalysis,asitsimplymergesprogramswe’veexhaustivelystudied.FollowingisasampleofProgram12-5’soutput: 15:12:0011/24/03 15:13:0011/24/03 15:14:0011/24/03 15:15:0011/24/03 15:16:0011/24/03 15:17:0011/24/03
Sensor173.62F Sensor265.41F Sensor173.73F Sensor265.41F Sensor173.62F Sensor265.52F Sensor173.51F Sensor265.41F Sensor173.39F Sensor265.41F Sensor173.51F Sensor265.29F
We’vesettheprogramtooutputareadingonceeveryminute,buttheoutputintervalmaybeincreasedby changingthevalueoftheconstantInterval. Interval
Con
1
;howoftenreaddata
DefiningIntervalas5,forexample,outputsareadingonceeveryfiveminutes. Figure’s12-11and12-12showtheindoorandoutdoortemperaturereadingscollectedwiththisprogram over24hours.Theabruptdropinoutdoortemperaturecoincidedwiththearrivalofacoldfrontandrainstorm.Thevariationinindoortemperature(thedatawascollectedinmybasementworkshop)resultsfrom theforcedairfurnacecyclingoffandon.
253
Chapter12 Figure12-11:Indoorand outdoortemperature.
Figure12-12:Indoor temperature.
254
DigitalTemperatureSensorsandReal-TimeClocks WhichEdge? Serialclockeddataistransferredoneithertherisingedgeoftheclockpulse,orthefallingedge.Byconvention,clockidleis0V,sotheleadingedgeisthetransitionfrom0to1andthefallingedgeisthetransition from1to0.Figure12-13showsbothpossibilities.Figures12-14and12-15showabitwithvalue1being transferredwiththesetwooptions.Thedatabeingtransferredis%10000000,MSBfirst. Don’tgetconfusedwhenlookingatFigures12-14and15becausethedatapulseiswiderthantheclock pulse.InFigure12-15,forexample,thedataisvalidonthefallingedgeofthefirstclockpulse,butit’salso validontherisingedgeofthesecondclockpulse.But,thedataisonlyreadonceforeachclockpulse;i.e., dataisalwaysreadontherisingedgeorthefallingedge,butnotboth.InFigure12-15,dataisreadonthe fallingedgeofeachclockpulse;hencethedataline’sstatusduringtherisingedgeisimmaterial.
Figure12-13:Risingandfalling clockedgedatatransfer.
Figure 12-14: Data Valid on Rising Edge Ch1: Clock;Ch2:Data.
255
Figure12-15:DataValidonFallingEdgeCh1: Clock;Ch2:Data.
Chapter12 BitOrder Wehavetwochoicestosendtheindividualbitsthatcompriseabyte;frommostsignificant(B7)toleast significant(B0),orfromleastsignificanttomostsignificant.
ReadingtheDataSheet Let’slookattheDS1302datasheettoseewherewefindtheclockedgeandbitorderinformation. Let’sstartwithbitorder,asthat’sthesimplerofthetwo.It’shardtobeclearerthantheDS1302datasheet: DATAINPUT FollowingtheeightSCLKcyclesthatinputawritecommandbyte,adatabyteisinputontherisingedge ofthenexteightSCLKcycles.AdditionalSCLKcyclesareignoredshouldtheyinadvertentlyoccur.Data isinputstartingwithbit0. DATAOUTPUT FollowingtheeightSCLKcyclesthatinputareadcommandbyte,adatabyteisoutputonthefallingedge ofthenexteightSCLKcycles.Notethatthefirstdatabittobetransmittedoccursonthefirstfallingedge afterthelastbitofthecommandbyteiswritten.AdditionalSCLKcyclesretransmitthedatabytesshould theyinadvertentlyoccursolongasRSTremainshigh.Thisoperationpermitscontinuousburstmoderead capability.Also,theI/Opinistri-stateduponeachrisingedgeofSCLK.Dataisoutputstartingwith bit0.
Sincedataisbothinputandoutputstartingwithbit0,thebitorderisLSBfirst. Todeterminewhetherthedataistobereadontherisingorfallingclockedge,weexaminethetimingdiagrams. TIMINGDIAGRAM:READDATATRANSFERFigure5
TIMINGDIAGRAM:WRITEDATATRANSFERFigure6
(FigurescourtesyofMaximIntegratedProducts,Inc.Reprintedwithpermission.)
256
DigitalTemperatureSensorsandReal-TimeClocks WithrespecttotheDS1302readingdata(PICwritingdatawithShiftOut),thedatabitsareshowntobe readbytheDS1302ontherisingedgeoftheclock.HencewewilluseLSBPREmodewithShiftOut. WithrespecttotheDS1302writingdata(PICreadingdatawithShiftIn)thedataisshowntobewritten immediatelyaftertheclock’sfallingedgeandhencemustbereadbythePIContherisingclockedge.Accordingly,wewilluseLSBPREmodewithShiftIn. Figures12-16through12-19showthedifferenceamongthefourorderandclockingoptions.Ineachcase, thebytebeingsentis%01000000.
Figure 12-16: Mode: MSBPRE Ch1: Clock; Ch2:Data.
Figure12-17:Mode:LSBPRECh1:Clock;Ch2: Data.
Figure 12-18: Mode: MSBPOST Ch1: Clock; Ch2:Data.
Figure 12-19: Mode: LSBPOST Ch1: Clock; Ch2:Data.
Predefined Constant MSBPRE (MSBFIRST) LSBPRE (LSBFIRST) MSBPOST LSBPOST
Meaning Value
BitOrder
Clock/DataRelationship
SampleIllustration
0
MSBfirst
Datavalidonleadingedge
Figure12-16
1
LSBfirst
Datavalidonleadingedge
Figure12-17
2 3
MSBfirst LSBfirst
Datavalidonfallingedge Datavalidonfallingedge
Figure12-18 Figure12-19
257
Chapter12 IdeasforModificationstoProgramsandCircuits •
•
• •
TheDS2401isa1-wireelectronicserialnumberchip.Itssolefunctionistoreturna64-bituniqueserial number.Howmightthisdevicebeused?Forexample,itcouldbeusedasasecurityaccessdevice,orit couldidentifyacalibratedprintedcircuitboard.Or,itmightbeusedtomultiplexseveralswitchesona singlebus(eachswitchconnectsadifferentDS2401tothebus.Byreadingtheserialnumbers,which switchisclosedmaybedetermined.)Tryrevisingthecircuitstoreadandusetheuniqueserialnumber availablefromadS2401. Program12-5isastartofaloggingweatherstation.AddaMotorolaMPXA6115AUabsolutepressure sensorforbarometricreadingsandaHumirelHM1500humiditysensortothecircuitofFigure12-10. AddamultilineLCDtodisplayindoortemperature,outdoortemperature,barometricpressureandhumidity.(BoththeHM1500andMPXA6115AUsensorsrequirereadingananalogvoltage.Brushupon A/DconversioninChapter11ifnecessary.) HowlongcanthecableconnectingtheremoteDS18B20bebeforecapacitiveloadingbecomesa problemandtemperaturevaluescannolongerberead?Howdoesthisvarywithcabletype(cablecapacitance)?Howdoeschangingthepull-upresistoralterthedistanceperformance? DallasSemiconductorhasaninterestinglineof1-wiredevices,packagedinstainlesssteel“buttons” calledtheIButton.IButtonproductshavetheirownwebsite,http://www.ibutton.com.Areanyofthe IButtondevicesusefulforyourprojects?HowwouldyougoaboutinterfacingthemwithaPIC? Chapter12Sidebar ShiftOut/ShiftIn–RisingorFallingClockandBitOrder Whentransferringserialclockeddatawemustdecidewhetherthedataistobevalidonthe risingedgeoftheclock,orthefallingedge.Wealsomustdecidewhetherthedataistobe sentisinorderB7…B0(mostsignificantbitfirst)orB0…B7(leastsignificantbitfirst). MBasicprovidesfouroptionswhenwritingserialclockeddatawith ShiftOut,orwhen readingitwithShiftIn. Althoughwetalkoftheseas“options”theyinfactaremandatoryfortheparticulardevice withwhichyouintendtocommunicate.TheDallasSemiconductorDS1302realtimeclock chip,forexample,requiresthedatatobevalidontherisingedgeandfordatatobesentleast significantbytefirst.Notalltypesofchipsthatcommunicateviaserialclockeddatawill usetheseconventions.Forexample,wewillseeinChapter21thattheMCP41010digital potentiometerrequiresMSB-firstbitorderwithdatavalidontherisingedge.Accordingly, youmustdelveintothedevice’sdatasheettodeterminethecorrectclockedgeandthecorrectbitordersequence.
258
DigitalTemperatureSensorsandReal-TimeClocks
References [12-1]
Motorola,Inc.,SensorDeviceDataBook,PublicationDL200/D,Rev.5(January2003). DallasSemiconductorCorp.divisionofMaximIntegratedProducts,Inc.,DS1302TrickleChargeTimekeepingChip,(September29,2001). [12-3] DallasSemiconductorCorp.divisionofMaximIntegratedProducts,Inc.,DS18B20Programmable Resolution1-WireDigitalThermometer,(January5,2002). [12-4] DallasSemiconductorCorp.divisionofMaximIntegratedProducts,Inc.,DS2401SiliconSerialNumber,(February21,2002). [12-5] DallasSemiconductorCorp.divisionofMaximIntegratedProducts,Inc.,1-WireCommunicationwitha MicrochipPICmicroMicrocontroller,(September9,2003). [12-6] Awtrey,Dan,TransmittingDataandPoweroveraOne-WireBus,Sensors,TheJournalofApplied SensingTechnology(February1997). [12-7] DallasSemiconductorCorp.divisionofMaximIntegratedProducts,Inc.,MicroLANDesignGuide— TechBrief1,(September24,2002). [12-8] DallasSemiconductorCorp.divisionofMaximIntegratedProducts,Inc.,PrintedCircuitBoardIdentificationUsing1-WireProducts,ApplicationNote178,(June5,2002). [12-9] Richey,Rodger,YetAnotherClockFeaturingthePIC16C924,AN649,MicrochipTechnology,Inc., Doc.No.DS00649A(1997). [12-10] DallasSemiconductorCorp.divisionofMaximIntegratedProducts,Inc.,CrystalConsiderationsfor DallasReal-TimeClocksApplicationNote58,(December9,2002). [12-2]
259
CHAPTER
13
Assembler101 Attheendofthischapter,youwon’tbeanexpertinassemblerlanguageprogramming.Infact,ifthisisyour firstintroductiontoPICassembler,youwon’tevenqualifyasanovice.WhatIhopetodo,however,istoilluminateafewofthemoreimportantassemblerprogrammingprinciplestopreparethewayforChapters14 and15wherewewilllearnassemblerroutinesthatdothingsotherwiseimpossiblewithMBasicandspeed upcertainoperations.
TheBasics Let’sstartwiththebasics.Tokeepthediscussiontoamanageablelength,we’lllimitourdiscussiontothe 16F876/877/876A/877Aseriesdevices.Formoredetailsonthesedevices,aswellasotherPICs,consultthe sourcesidentifiedintheReferencessection.
WhatisAssembler? AswelearnedinChapter2,theMBasicprogramsyouwritearecompiledintoanassemblerformat,linked withlibraryfunctionsbyalinkerultimatelyconvertedintomachineinstructionexecutablebyaPIC. AssemblerisahumancompatibleformofdirectlyaddressingaPIC’sbuilt-ininstructionset.APIC’s instructionset—andmid-rangePICssuchasthe16F87x/87xAdeviceshaveonly35instructions—works withdataandhardwareatthemostelementarylevel.Typicalassemblerinstructionsinvolvemovingbytes fromonestoragelocationtoanother,orsettingandclearingbits.Eventhemostcomplexmid-rangePIC instructionsdonothingmorethanaddorsubtract8-bitvalues.Consequently,onelineofMBasiccodemay correspondtodozens,orevenhundredsoflinesofassemblercode. WemayillustratethisdifferencebycomparingMBasic,assemblerandmachineinstructionstoaccomplisha verysimpletask:A=123,whereAisabytevariable. MBasic A=123
Assembler
MachineCode 11000001111011 00000011001000
movlw.123 movwfA
It’seasytowriteA=123.It’smoredifficulttowritethetwoassemblerinstructionsandit’sfarmoredifficult andtimeconsumingtomanuallyconstructthemachinecodeinstructions.Fortunately,we’llneverhaveto dealwithmachinecode;MBasic’sintegratedcompilerandassemblerwillmaskthatcomplexityfromus. Whatdothesetwocrypticassemblerinstructionsmean? movlw.123—meanstoloadthe8bitscorrespondingtothedecimalnumber123intothePIC’sworking register,W.Theperiodsymboltellstheassemblerthatthenumberisadecimalnumber,notahexadecimal(writtenintheform0xNN,orabinarynumber,writtenintheformb’NNNNNNNN’).InPIC assemblerterminology,copyingavaluefromonelocationtoanotheriscalledamove.Aconstantis
260
Assembler101 calledaliteralandtheworkingregisteriscalledw.Hence,theassembleroperationcodename(usually calledsimplyanopcode)ismovlw,standingformovealiteraltoregisterw. movwfA—meanstocopythevaluecurrentlyinworkingregisterwintothefilelocationidentifiedbythe valueoftheconstantA.(We’llassumeforthemomentthatArepresentsthestorageregister(file)at physicaladdress$48.)Theopcodenamemovwfisconstructedfromitsactions;tomoveavaluefrom registerwtoafile. Notsofast,you’reprobablythinking.YoujustsaidAisaconstantwithavalueof$48;butnotonepage earlieryousaidAisavariablethatwearegoingtosettohavethevalue123.Makeupyourmind,whichis it?ThemostaccuratedescriptionofAisthatitisneitheravariablenoraconstant,butratheritisanaddress atwhichabyteisstored.Thataddressisstaticandisassigned—bythecompiler,orbyyouifyouwriteonly inassembler—anddoesnotchange,sointhatregardAisaconstant.However,thevaluestoredataddressA canchange.Hence,AcanbeconsideredavariablewhenwerefertothecontentsofthememoryataddressA, oraconstantwhenwerefertothememoryaddressitself.
Terminology Whenstartingouttolearnsomethingnew,thehardestpartisoftenunderstandingtheterminology.Theunderlyingideamaybesimple,butit’sdescribedinunfamiliarwords.Or,thewordsmaybefamiliar,butthey areusedinafashionthatdivorcesthemfromtheirnormalmeaning.We’vealreadythrownaroundthewords, register,file,literal,move,opcode,andaddress,tomentionbutafew. Tounderstandtheterminology,wemustunderstandthePIC’sarchitecture.First,rememberwhatwelearned inChapter1;thePICfollowstheHarvardarchitectureandhasseparateprogrammemoryanddatamemory. Programmemoryholds—formid-rangePICs—aseriesof14-bitmachinecodestatements,similartothose wenotedearlier.Thedatamemoryis8-bitswideandholdsnotonlyvariablesofthetypeweuseinMBasic andassembler,butalsoothervariablescontrollingthePIC’sfunctioning,itshardwareanditsfeatures.
DataMemory Let’slookfirstathowthedatamemoryisorganizedina16F876/877/ 876A/877Adevice.Figure13-1providesaconceptualviewofthedata memory.Thedatamemoryisorganizedintofourbanks,witheachbank having128addresses,givingamaximumof512uniqueaddresses. Eachaddressrepresentsoneofthreetypesof8-bitwideregisterfiles: • General-PurposeRegister—userRAM.The‘87xchipswe’re discussinghave368general-purposeregisters. • SpecialFunctionRegister—afilethatmaybeaccessedbytheuser (inalmostallcases,bothreadandwrite)butitisusedinternally bythePICforafunction.Forexample,allportsarespecialfunctionregisters,andthuswemaybothreadfromandwriteto,for example,PortB. • UnimplementedAddress—anaddressthatisdeadbecauseitisnot physicallyimplemented.The‘87xchipswe’rediscussinghave15 deadaddresses. Figure 13-1: Conceptual view of 16F87xdatamemory. Microchipcallsthesememorylocationsregisterfiles,orregisters,or files.Don’tgetconfused;whetherwecallitaregister,orafile,itisstillthelocationofan8-bitinformation storageunit,identifiedbyanumericaladdressintherange0…511.(Bankingmakestheactualaddressinga bitmorecomplex,aswe’llseelater.)
261
Chapter13 TheworkingorWregisterisspecial—it’san8bitmemorylocationbuiltintothePIC’scentral processingcoreandtiedtothearithmeticandlogic unit.Itdoesn’thaveanaddressinthesamesense thattheregisterfilesdo;ratherit’sidentifiedthrough opcodesasthesourceofdataorthedestinationofa particularaction. Manylogicandarithmeticfunctionrequiretwo operands;suchasaddition,subtractionandlogic operations.Oneoperandmaybeaconstantand theotheraregistervalue,orbothmayberegister values.Thearithmeticandlogicunitportionofthe PICperformsthesefunctionsand,asillustratedin Figure13-2,oneofthetwoinputoperandsmustbe heldintheWregister.Thisisasimple,butinviolate ruleformid-rangePICs—iftheopcodehastwo operands,onemustbeintheWregister.Wherethe resultoftheoperationisstoredisdeterminedby Figure13-2:Wregisterrelationship. theopcode’sdestinationbitandmaybeeitherthe Wregisteroroneoftheoperandregisters.Itcan’tbeathirdregister—it’seithertheWregisteroroneofthe operandregisters. Supposewehavetwofiles,AandBandthatwewishtoaddtheirvaluestogetherandstoretheresultinfile C.InMBasic,thisoperationisC=A+B.(We’llassumethatsomehowthelettersA,BandCarelinked totheaddressesofthreegeneral-purposeregisters.YoudounderstandthatwhenwetalkaboutaddingAto BandputtingtheresultintoC,wearereferringtothecontentsofthememorylocationsA,BandC,right? Ifnotgobackandreadthelastpagesagain.)Additionisatwo-operandfunctionand,aswelearned,two operandfunctionsrequireoneoperandtobeheldinW.Consequently,thereisnosinglemachineinstruction, oropcode,thatletsusaddAandBandstoretheresultatC.Rather,wemustfirstmovethecontentsofAinto W,thenaddBtothecontentsofW,storingtheresultinWandlastlymoveW’scontentstoC. EachSpecialFunctionRegisterhasbeengivenanamebyMicrochipandeachbitwithineachSpecial FunctionRegisterhasaname.It’suptoustoassignnamestoGeneral-PurposeRegistersweusetohold variables. Thefollowingisadetailedregisterfilemapforthe16F876/A/877/Adevices. Bank0
HexAdr
Bank1
HexAdr
Bank2
HexAdr
Bank3
HexAdr
Indirectaddr.(*)
00
Indirectaddr.(*)
80
Indirectaddr.(*)
100
Indirectaddr.(*)
180
TMR0
01
OPTION_REG
81
TMR0
101
OPTION_REG
181
PCL
02
PCL
82
PCL
102
PCL
182
STATUS
03
STATUS
83
STATUS
103
STATUS
183
FSR
104
FSR
FSR
04
FSR
84
PORTA
05
TRISA
85
105 PORTB
PORTB
06
TRISB
86
PORTC
07
TRISC
87
107
187
PORTD(1)
08
TRISD(1)
88
108
188
262
106
184 185
TRISB
186
Assembler101 Bank0 PORTE(1)
HexAdr
Bank1
HexAdr
09
TRISE(1)
89
Bank2
HexAdr
Bank3
109
HexAdr 189
PCLATH
0A
PCLATH
8A
PCLATH
10A
PCLATH
18A
INTCON
0B
INTCON
8B
INTCON
10B
INTCON
18B
PIR1
0C
PIE1
8C
EEDATA
10C
EECON1
18C
PIR2
0D
PIE2
8D
EEADR
10D
EECON2
18D
PCON
TMR1L
0E
8E
EEDATH
10E
Reserved(2)
18E
TMR1H
0F
8F
EEADRH
10F
Reserved(2)
18F
T1CON
10
90
110
TMR2
11
SSPCON2
91
111
191
T2CON
12
PR2
92
112
192
190
SSPBUF
13
SSPADD
93
113
193
SSPCON
14
SSPSTAT
94
114
194
CCPR1L
15
95
CCPR1H
16
96
CCP1CON
17
97
RCSTA
18
TXSTA
98
TXREG
19
SPBRG
99
General Purpose Register (RAM) 16Bytes
115 116 117 118 119
195 General Purpose Register (RAM) 16Bytes
196 197 198 199
RCREG
1A
9A
11A
CCPR2L
1B
9B
11B
19B
CCPR2H
1C
CMCON
9C
11C
19C
CCP2CON
1D
CVRCON
9D
11D
19D
ADRESH
1E
ADRESL
9E
11E
19E
ADCON0
1F 20
ADCON1
9F A0
11F 120
19F 1A0
General Purpose Register (RAM) 80Bytes
GeneralPurpose Register (RAM) 98Bytes
7F
Accesses 70-7F
General Purpose Register (RAM) 80Bytes
General Purpose Register (RAM) 80Bytes
EF
16F
F0
170
Accesses 70-7F
FF
19A
17F
1EF Accesses 70-7F
1F0 1FF
*Notaphysicalregister (1)Notimplementedin‘876 (2)Reserved
Thisisanimportanttable;sotakesometimetocarefullylookitover.Youshouldseeseveralthings: • Certainfilesarerepeatedinmultiplebanks.Thispermitsustoaccessthosefilesregardlessofthecurrentbanksettings. • SomeGeneral-PurposeRegistersaremarked“accesses.”Thisrepresentsmultipleaddressedshared memory;thesame16bytesofmemoryareaddressedat$70…$7D,$F0…$FF,$170…$17Fand $1F0…$1FF.Thispermitsquickaccesstocertainmemorylocationsregardlessofthebanksettings. • It’sfullofstrangenames,likeINTCON,CCP1CONandSSPSTAT.Thisbookisnotacomprehensive tutorialonassemblerprogramming,andwedon’thavetimetodiscusstheseSpecialPurposeRegisters 263
Chapter13 exceptwhenwefinditnecessarytouseone.And,we’llleavethosediscussionstoChapters14and15, andthoseotherchapterswereweincorporateassemblerintoourMBasicprograms.Ofcourse,detailed informationisavailableoneachSpecialPurposeRegisterinMicrochip’sdatasheets.
Banking Let’slookatbanksandbanking.Toaddressmemorylocationsfrom0…$1FF(0…511decimal)requires9 addressbits.Opcodesthatinvolveaddressingfilesmusthavethefileaddressembeddedintheopcode.These opcodeshavethefollowingbitstructure: 13
8 OPCODE 6bits
7 Destination 1bit
6
0 FileAddress 7bits
Forexample,rememberourmovwfAopcodethattranslatedintoamachineinstruction00000011001000? Itturnsoutthattheopcodeformovwfis0000001,representing000000forthemovoperationand1forthe destinationcode.Sincemid-rangePICshaveonlya14-bitinstructionword,thisleavesonly7bitstohold A’saddress,1001000.We’veassignedAtorepresentstorageaddress$48,andsevenbitsareadequate,since allhigherbitsarezeros.But,supposeA’saddressis$196—aperfectlylegitimateuserfilelocation,butone requiringallnineaddressbits. Wehaveaproblem.ThecleanestfixwouldhavebeenforMicrochiptousea16-bitopcodewith9bitsof addressspace,butthatwouldhavedestroyedbackwardscompatibilitywitholderdevicesaswellasrequiringMicrochiptoextensivelyreworkitssiliconlayout,anexpensivetask.Wearethereforeforcedtodeal, forhistoricalandcompatibilityreasons,withthemid-rangePICbeingabletoaddressonlyfileaddressesin therange0…127directlyintheopcode.Microchip’ssolutionwastobreakthe9-bitfileaddressintoa7-bit opcoderelativeaddressportionanda2-bitbankaddressportion. ThebankaddressbitsareheldintheSpecialFunctionRegisterbitsRB1andRP0.(Thesebitsarebits6and 5oftheStatusregister.)Ifwewishtoaddressmemorylocation$196,residinginBank3,therefore,we wouldfirstsetRB1andRB0to%1.Therightmostsevenbitsof$196,or$16representtherelativeaddress. (Don’tworryifthissoundscomplicated—theassemblerhidesmuchofthiscomplexityfromyou.) Tosimplifysettingandclearingthebankbits,wemayuseanassemblermacro,BankSel,invokedwiththe followingsyntax: BankselFileAddress
ThetermFileAddressisthefilename.(Remember,thenameofafileisdefinedasanumberrepresenting itsaddress,sotheassemblersimplyusestheaddressvalue.)Amacrocanbethoughtofasa“userdefined” opcode.Insteadofarealopcodethatgeneratesaspecificmachineinstruction,theassemblerexpandsamacrointooneormore“real”opcodes.Themacro’sadvantagesarespacesavingsandautomatingarepetitive task.Inthiscase,themacroBankSelexpandsintoinstructionsthatsetorclearRB1andRB0corresponding totheFileAddressvalue. SupposeourvariablenameisAanditsataddress$196.(Inassembler,theequateoperation,Equ,isthe equivalenttoMBasic’sconstantassignmentoperator,Con.)HowwouldweuseBankSel? A
Equ
BankSelA movlw movwf
0x196 .123 A
OKyou’rethinkingIunderstandthattheBankSelmacroextractsthetwoleftmostbitsfromthevalueofA, buthowdoesmovwfgettherightmostsevenbitswithoutanyspecialinstruction?Theansweristhatsince
264
Assembler101 thereareonlysevenbitsofopcodespaceavailablefortheaddress,onlytherightmostsevenbitsofAare loadedintotheopcode,withoutadditionalcommands.(Thissimplisticconstructionmaygenerateassembler warnings,sowe’lllearnabetterwaylaterinthischapter.)
ProgramMemory InChapter1,welearnedthatthe16F876/877/876A/877Adevices have8Kprogrammemory.Theprogramcounterinthesedevices is13bitswideand213is8192,soitcanaddressall8Kofprogram memory.TheprogramcounteristhepartofthePIC’scorethat keepstrackofwhichprograminstructioniscurrentlyexecuting andwhichprograminstructionshouldnextbeexecuted.Ifour assemblercodeusesall8Ksequentially,sothateachprogram instructionaddressfollowsthenextinstrictnumericalorder,allis well.
13 bits
Call, Return RETIE, RETLW
Stack Levels 1...8
Reserved Program Memory
Reset Vector
$0000
...
Interrupt Vector
$0004 $0005
Usable Program Memory
However,whenwritingaprogram,it’scommontohaveexecutiontojumpfromonelocationtoanother.Youmightwritesome codeinasubroutinethatyouthencall(theassemblerequivalent ofGoSub)frommultiplelocationswithinyourmainprogram.Or, programexecutionmayneedtojumparoundadatatablestored inprogrammemory.And,youmaywishtorepeatsomecodein theassemblerequivalentofaFor…NextoraWhile…WENDloop. Thisimpliesthatouropcodesmustincludeinstructionstojump executionfromthecurrentprogramcounterlocationtoadifferent location.
Program Counter <12:0>
Page 0 $07FF $0800
Page 1 $0FFF $1000
Page 2 $17FF $1800
Page 3 $1FFF
Doyouseetheproblem?Ouropcodestructuremustaccommodate Figure 13-3: Conceptual view—program aseriesofjumpinstructionsthatsay,inessence,stopexecuting memoryin16F876/877devices. thecurrentcodeandtransferexecutiontoanewprogrammemory address.Butouropcodeonlyhas14-bitsofspaceandafulljumpaddressaloneis13bits.Thisonlyleaves 1bitforalljumpopcodeinstructions,whichisunsatisfactorytosaytheleast.So,theengineersatMicrochipdecidedtosegmenttheprogrammemory,andsplittheprogramcounterintotworegisters.Figure13-3 illustratestheprogrammemorystructure.Insteadofcallingthembanks,theprogrammemorysegmentsare calledpages.The16F876/877deviceshavefourprogrammemorypages,each2Klong. Therearetwojumpopcodesinmid-rangePICs,thecallandgotoinstructions.Bothreserve11bitsforthe jumpaddress: 13
11
10
0
OPCODE 3bits
ExecutionTransferAddress 11bits
Wherethenaretheothertwobitsofthe13-bitjumpaddress?Or,morepertinently,sinceourdatastructure onlydealswitheightbits,howdoweaccessa13-bitprogramcontrolregister?Theanswerisabitcomplicated.The13-bitprogramcontrolregisterissplitintotwoparts:thelower8bitsareheldinthePCLregister, whichmaybereadorwrittento,justlikeanyotherspecialpurposeregister.Theupper5bitsoftheprogram controlregisterarenotdirectlyaccessibleandmaybereachedonlythroughthePCLATHregister.We’llend ourdiscussionofthePCLandPCLATHregistersnow,andreturntotheminthecontextofspecificexamples inChapter14.
265
Chapter13 TheremainingpartsofFigure13-3arethestackmemoryandtheresetandinterruptvectors.Thestackis dedicatedmemorywherethePICstoresreturnaddressesforinterruptandcalloperations.(ThisstackisinternaltothePICandisnotthesameasthegeneral-purposeregisterfilememorythatMBasicrequiresforits stack.)Thisistransparenttotheprogrammerandfortheapplicationsdiscussedinthisbookneednotfurther concernyou.Theresetvectoristhelocationwheretheprogramcounterbeginsexecutingcodeafterareset, whiletheinterruptvectoristhelocationwhereexecutionjumpstointheeventofaninterrupt.Normallythe programmerwillinsertaGoToopcodeinthoselocations,pointingtotherealresetcode,ortherealinterrupt handlercode.Havingtheresetandinterruptstartpointhardwiredto$0000and$0004,respectively,permits theprogrammertobeassuredofknowncodeexecutionpointintheeventofaresetorinterruptevent.Inthe caseofassemblerinterrupthandlers,Chapter15willshowusthatMBasictakescareofmuchofthiswork forus.
InstructionSetTerminology Inreadingtheopcodesummary,we’llmakeextensiveuseofthefollowingfielddescriptors. Field f W b k x d
PC TO PD
DescriptorMeaning Registerfileaddress($00…$7F) WorkingRegister(accumulator) Bitaddresswithinan8-bitfileregister Literalfield,constantdataorlabel Don’tcarelocation(0or1).Theassemblergeneratescode with0. Destinationselection: d=0storeresultinW d=1storeresultinregisterf Defaultisd=1 ProgramCounter Time-outBit Power-downBit
OneSpecialPurposeRegisterthatwewilldealwithfrequentlywhenreviewingtheopcodesistheStatus register: Bit7 IRP
Bit6 RP1
Bit5 RP0
Bit4 TO
Bit3 PD
Bit2 Z
Bit1 DC
Bit0 C
IRP—Registerbankselectbitforindirectaddressing;coveredinChapter14. RP1andRP0—Aswepreviouslysaw,theRP1andRP0bitsarethe9thand8thregisterfileaddressbits, respectively. 11=Bank3 10=Bank2 01=Bank1 00=Bank0 TO—Time-outbit(theoverscoreindicatesinvertedstatus).WewillnotfurtherdiscusstheTObit. PD—Power-downbit(theoverscoreindicatesinvertedstatus).WewillnotfurtherdiscussthePDbit. Z—Zerobit: 1=theresultofthearithmeticorlogicoperationiszero 0=theresultofthearithmeticorlogicoperationisnonzero
266
Assembler101 DC—Digitcarry/Borrowbit(forADDWF,ADDLW,SUBLWandSUBWFinstructions).Forborrow,thebitsense isreversed: 1=Acarry-outfromthe4thloworderbitoftheresultoccurred 0=Nocarry-outfromthe4thlow-orderbitoftheresult C—Carry/Borrowbit(forADDWF,ADDLW,SUBLWandSUBWFinstructions): 1=Acarry-outfromtheMostSignificantbitoftheresultoccurred 0=Nocarry-outfromtheMostSignificantbitoftheresultoccurred. ForBorrow,thebitsenseisreversed.Asubtractionisexecutedbyaddingthetwo’scomplementofthe secondoperand.Forrotate(RRF,RRL)instructions,thisbitisloadedwiththehigh(orlow)orderbitofthe sourceregister.
OpCodes Theremainderofthischapterisasummaryofthe3516F87x/87xAopcodes.Microchip’sMidrangeReferenceManualprovidesmoreinformationandshouldbeconsultedwherenecessary. Whenreadingthesummary,rememberthata“literal”isMicrochip’snameforaconstant.Aliteralmaybea numberentereddirectly,suchas.123orasanamedconstant,linkedtoanumericalvaluewitheitherMBasic’sConoperation,oranEquassignmentinsideanassemblermodule.ThenotationNameindicatesthe NthbitoffileregisterName.Nmayalsobeaname,suchasStatuswhichmeansthebitnamedCof thefileregisternamedStatus. Inprovidingexamples,wewilluseMicrochip’shexadecimalnotation,0xNN,insteadofBasicMicros’s$NN identifier. Thefield“cycles”indicateshowmanyclockcycles(FOSC/4)isrequiredtocompletetheparticularoperation. StandardNotes: Threenotesapplytoseveralopcodes: 1. WhenanI/Oregisterismodifiedasafunctionofitself;forexample,MOVFPORTB,1,thevalue usedwillbethatvaluepresentonthepinsthemselves.Forexample,ifthedatalatchis%1forapin configuredasinputandisdrivenlowbyanexternaldevice,thedatawillbewrittenbackwitha%0. 2. IfthisinstructionisexecutedontheTMR0register(andwhereapplicable,d=1),theprescalerwill beclearedifassignedtotheTimer0module. 3. IfProgramCounter(PC)ismodified,oraconditionaltestistrue,theinstructionrequirestwo cycles.ThesecondcycleisexecutedasaNOP. OpCode
Operands
Description
Cycles
Affected
ADDLW
k
AddLiteralandW
1
C,DC,Z
Notes
Addlwaddsaliteral‘k’tothevaluecurrentlyinW.TheresultremainsinW.Theliteral‘k’mustbeinthe range0…255.Iftheliteralexceeds255,onlythelowest8bitswillbeused.
Example1: Addlw .123
;addsdecimal123tothecurrentcontentsofW
RememberthatWisonly8-bitswideandthatitispossibletheresultwilloverflowW.Intheeventofanoverflow,Statuswillbeset.Ifthesumiszero(suchasWholds128,towhich128isadded)Status willbeset.Inthislatterexample,bothZandCwillbeset. 267
Chapter13 Example2: AssumeAisdefinedasabytevariableanditsaddressis0x30.Thevaluestoredataddress0x30is.128 (0x80).AssumeW’sinitialvalueis0x10. Addlw A
Theresultis0x48,not0x90.ThisisbecauseweareaddingthenumericalvalueofA,whichisitsaddress, notthevalueofthecontentsataddressA.ConfusingA’saddresswiththevalueofthecontentsofthefileat A’saddressisacommonerror. OpCode
Operands
Description
Cycles
Affected
Notes
ADDWF
f,d
AddWandf
1
C,DC,Z
1,2
AddwfaddsthevaluecurrentlyinWtothevalueheldinafile‘f’.TheresultiseitherplacedinW(destination =w)orinthefile‘f’(destination=f).
Example1: Addwf A,f
Beforetheopcodeisexecuted,assumethevalueataddressAis.123andthatWholds.10.Afterexecution, thevalueataddressAwillbe.133andW’svalueremainsat.10. Example2: Addwf A,w
Beforetheopcodeisexecuted,assumethevalueataddressAis.123andthatWholds.10.Afterexecution, thevalueataddressAremainsas.123andWwillhold.133. SincebothWandregisterfilesare8-bitswide,overflowispossible.OverflowwillsetStatus,anda zeroresultwillsetStatus. OpCode
Operands
Description
Cycles
Affected
ANDLW
k
ANDLiteralwithW
1
Z
Notes
Andlwperformsabit-by-bitlogicalANDofthevalueinWandtheliteral‘k.’TheresultisretainedintheW register.
TheANDfunctiontruthtableis: InputA 0 0 1 1
InputB 0 1 0 1
AANDB 0 0 0 1
ThelogicalANDfunctionisoftenusedto“maskoff”bits,asinthefollowingexample. Example1: AssumeWholds.123beforetheinstruction. Andlw
31
;BeforeInstructionW:01111011 ; 31:00011111 ------- AfterW 00011011=27
268
Assembler101 We’llseeinChapter14howtheANDfunctionmaybeusedtocalculatethedivisionremainder.Itmayalso beusedtotestmultiplebitstoseeifallarezerobyusingamaskliteralwith%1valuesintheplaceswhere thebitstobetestedreside.Ifallbitscoincidingwiththe%1maskbitsare0,theresultwillis0andStatus willbeset. OpCode
Operands
Description
Cycles
Affected
Notes
ANDWF
f,d
ANDWwithf
1
Z
1,2
Andwfperformsabit-by-bitlogicalANDofthevalueinWandthevalueheldinafile‘f.’Theresultiseither placedinW(destination=w)orinthefile‘f’(destination=f).
TheANDfunctiontruthtableis: InputA 0 0 1 1
InputB 0 1 0 1
AANDB 0 0 0 1
ThelogicalANDfunctionisoftenusedto“maskoff”bits,asinthefollowingexample. Example1: AssumeWholds.123beforetheinstructionandassumefileAholds.31. Andwf
A,w
;BeforeInstructionW:01111011=.123 ; 31:00011111=.31 ------- AfterW 00011011=.27
ThevaluestoredatfileaddressAremains.31. Example2: AssumeWholds.123beforetheinstructionandassumefileAholds31. Andwf
A,f
;BeforeInstructionW:01111011=.123 ; 31:00011111=.31 ------- Afterf 00011011=.27
ThevalueinWremains.123. OpCode
Operands
Description
Cycles
BCF
f,b
BitClearf
1
Affected
Notes 1,2
BCFclears(makesitazero)bit‘b’ofafile‘f’.Bit‘b’maybeidentifiedwithanumber(0…7)oranamed constantintherange0…7. Example1: AssumePortBissettobeanoutputandwewishtosetpinB0tolow. Bcf
PortB,0
OpCode
Operands
Description
Cycles
BSF
f,b
BitSetf
1
269
Affected
Notes 1,2
Chapter13 BSFsets(makesitaone)bit’b’ofafile‘f’.Bit‘b’maybeidentifiedwithanumber(0…7)oranamed constantintherange0…7. Example1: AssumePortBissettobeanoutputandwewishtosetpinB0tohigh. Bsf
PortB,0
OpCode
Operands
Description
Cycles
BTFSC
f,b
BitTestf,SkipifClear
1(2)
Affected
Notes 3
Btfscchecksthestatusofbit‘b’infile‘f’.Ifbit‘b’isclear(equalto0),thenextopcodeisskipped.Ifbit
‘b’isset(equalto1)thenextopcodeisexecuted. BtfscisaprogramflowcontrolopcodesandisanalogoustoMBasic’sIf…Thentest.
Example1: SupposePortBissetasinputandhasaswitchconnectedtopinB0,withapull-upresistor.Dependingupon whethertheswitchisset(switchopenandB0=%1)orclear(switchclosedandB0=%0)wewishtoexecute differentcode. … Btfsc PortB,0 GoToSwitchOpenRoutine …
;SwitchOpenRoutineexecutedifnoskip ;codefromheredownisexecutedotherwise
TheBtfscopcodetestsPortB’sbit0(pinB0)value.Ifthevalueisclear(B0=0),thenextinstruction(GoTo SwitchOpenRoutine)isskippedandcodeexecutionresumeswiththestatementimmediatelyfollowing theskippedinstruction.IfPortB,bit0isset(B0=1)thenextinstructionisnotskippedsotheGoToSwitchOpenRoutinestatementexecutesandprogramexecutionbranchestothecodebeginningwiththelabel SwitchOpenRoutine. Acommonuseforbtfscistotesttheresultofanarithmeticorlogicaloperationandbranchprogramflow baseduponwhetherStatusorStatusflagsaresetorclear. OpCode
Operands
Description
Cycles
BTFSS
f,b
BitTestf,SkipifSet
1(2)
Affected
Notes 3
Btfsschecksthestatusofbit‘b’infile’f’.Ifbit‘b’isset(equalto1),thenextopcodeisskipped.Ifbit‘b’ isclear(equalto0)thenextopcodeisexecuted.Btfssisthemirrorimageofbtfsc. BtfscisaprogramflowcontrolopcodesandisanalogoustoMBasic’sIf…Thentest.
Example1: SupposePortBissetasinputandhasaswitchconnectedtopinB0,withapull-upresistor.Dependingupon whethertheswitchisset(switchopenandB0=%1)orclear(switchclosedandB0=%0)wewishtoexecute differentcode. … Btfss PortB,0 GoToSwitchClosedRoutine …
;SwitchClosedRoutineexecutedifnoskip ;codefromheredownisexecutedotherwise
TheBtfssopcodetestsPortB’sbit0(pinB0)value.Ifthevalueisset(B0=1),thenextinstruction(GoTo SwitchClosedRoutine)isskippedandcodeexecutionresumeswiththestatementimmediatelyfollowingtheskippedinstruction.IfPortB,bit0isclear(B0=0)thenextinstructionisnotskippedsotheGoTo
270
Assembler101 SwitchClosedRoutinestatementexecutesandprogramexecutionbranchestothecodebeginningwith thelabelSwitchClosedRoutine.
Acommonuseforbtfssistotesttheresultofanarithmeticorlogicaloperationandbranchprogramflow baseduponwhetherStatusorStatusflagsaresetorclear. OpCode
Operands
Description
Cycles
CALL
k
CallSubroutine
2
Affected
Notes
Calltransfersprogramexecutiontoasubroutine,similartoMBasic’sGoSubfunction.Uponreturnfrom thesubroutine,programexecutionresumeswiththeopcodeimmediatelyfollowingtheCalloperator.
Example1:
… CallSubOne …
SubOne … ;subroutinecodegoeshere Return
TheoperandforCallisaliteralvalue,intherange0…2047.However,inmostinstances,youwillwishto usealabel,suchasSubOneintheexample,andallowtheassemblertoresolvethelabelintoanumerical argumentfortheCallopcode.Aswelearnedearlier,therangeofthecallisoneprogrampageandifthe jumpdistanceisgreater,thetwoextrapagebitsmustbegenerated.Thisisanadvancedtopicandwillnotbe furtherconsideredinthischapter. OpCode
Operands
Description
Cycles
Affected
Notes
CLRF
f
Clearf
1
Z
2
Clrfclears,orsetsto0allbitsinfile‘f’.Sincetheresultiszero,Statusissetbythisoperation.
Example1: AssumefileAhasbeendefinedandthatitholdsthevalue.123. Clrf
A
;BeforeinstructionA=.12301111011 ;AfterClrfA A=000000000
OpCode
Operands
Description
Cycles
Affected
CLRW
–
ClearW
1
Z
Notes
Clrwclears,orsetsallbitsto0inregisterW.Sincetheresultiszero,Statusissetbythisoperation.
Example1: AssumeWholdsthevalue.123. Clrw
;BeforeinstructionW=.12301111011 ;AfterClrwA W=000000000
OpCode
Operands
Description
Cycles
Affected
CLRWDT
–
ClearWatchdogTimer
1
TO,PD
ClrWdtclearsthewatchdogtimer.ItalsosetstheTOandPDbits.
271
Notes
Chapter13 OpCode
Operands
Description
Cycles
Affected
Notes
COMF
f,d
Complementf
1
Z
1,2
Comfperformsaone’scomplementonthecontentsoffile‘f.’TheresultiseitherplacedinW(destination =w)orinthefile‘f’(destination=f).Theone’scomplementoperationreplacesall0’sbyone’sandvice
versa. Example1: AssumefileAhasbeendefinedandthatitholdsthevalue.123. Comf
A,f
;BeforeinstructionA=.12301111011 ;AfterComfA A=.13210000100
In8-bitarithmeticusedinWandA,thesumofAanditsone’scomplementis255.Notethisisnotthesame asfortwo’scomplement,wherethesumofAanditstwo’scomplementis256. OpCode
Operands
Description
Cycles
Affected
Notes
DECF
f,d
Decrementf
1
Z
1,2
Decfdecrementsby1thevalueinfile‘f’.If,afterdecrementing,theresultis0,Statusisset.The resultiseitherplacedinW(destination=w)orinthefile‘f’(destination=f).Decfistheassembleranalog ofA=A-1.
Example1: AssumefileAhasbeendefinedandthatitholdsthevalue.123. Decf
A,f
;BeforeinstructionA=.12301111011 ;AfterDecfA A=.12201111010
Theresultofdecrementing0is,ofcourse.255. Decfisusefulincontrolloops,asitcanbecombinedwithabtfssorbtfscoperatortoprovidetheassembleranalogofMBasic’sFor…Nextloop. OpCode
Operands
Description
Cycles
DECFSZ
f,d
Decrementf,Skipif0
1(2)
Affected
Notes 1,2,3
Decfszcombinesthedecrementoperationwithazeroresulttest;thevalueinfile‘f’isdecrementedby1 andiftheresultis0,thenextinstructionisskipped.TheresultiseitherplacedinW(destination=w)orinthe file‘f’(destination=f).
Example1: AssumefileAhasbeendefinedandthatitholdsthevalue.123. Loop …
… Decfsz A,f GoTo Loop
;thiscodeisexecuted123times
WhenprogramexecutionhitstheDecfszinstruction,thethencurrentvalueofAisdecrementedby1and theresulttested.Iftheresultisnonzero,thenextinstructionisexecutedandprogramflowjumpsbacktothe labelLoop.Iftheresultiszero,theGoToLoopstatementisskippedoverandprogramexecutiongoestothe firstopcodefollowingtheGoTo.
272
Assembler101 Example1istheassembleranalogof: A=123 Repeat … A=A-1 UntilA=0
NotethattheassemblercodeinExample1isexecuted123times,not124timesbecausethetestforzerois madeatthebottomoftheloop,afterdecrementingA. OpCode
Operands
Description
Cycles
GOTO
k
GotoAddress
2
Affected
Notes
GoTotransfersprogramexecutiontoacodesequence.ItseffectissimilartoMBasic’sGoTostatement.
Example1: AssumefileAhasbeendefinedandthatitholdsthevalue.123. Loop
… Decfsz A,f GoTo Loop
;thiscodeisexecuted123times
WhenAisnonzero,theGoTostatementisexecutedandprogramflowjumpstotheaddressidentifiedbythe labelLoop. TheoperandforGoToisaliteralvalue,intherange0…2047.However,inmostinstances,youwillwish tousealabel,suchasLoopintheexample,andallowtheassemblertoresolvethelabelintoanumerical argumentfortheGoToopcode.Aswelearnedearlier,therangeofthejumpisoneprogrampageandifthe jumpdistanceisgreater,thetwoextrapagebitsmustbegenerated.Thisisanadvancedtopicandwillnotbe furtherconsideredinthischapter. OpCode
Operands
Description
Cycles
Affected
Notes
INCF
f,d
Incrementf
1
Z
1,2
Incfincrementsby1thevalueinfile‘f.’If,afterincrementing,theresultis0,Statusisset.The resultiseitherplacedinW(destination=w)orinthefile‘f’(destination=f).Incfistheassembleranalog ofA=A+1.
Example1: AssumefileAhasbeendefinedandthatitholdsthevalue.123. Incf
A,f
;BeforeinstructionA=.12301111011 ;AfterDecfA A=.12401111100
Theresultofincrementing.255is,ofcourse.0Inthiscase,Statuswillbeset. Incfisusefulincontrolloops,asitcanbecombinedwithabtfssorbtfscoperatortoprovidetheassembleranalogofMBasic’sFor…Nextlooporothercontrolstructures. OpCode
Operands
Description
Cycles
INCFSZ
f,d
Incrementf,Skipif0
1(2)
Affected
Notes 1,2,3
Incfszcombinestheincrementoperationwithazeroresulttest;thevalueinfile‘f’isincrementedby1 andiftheresultis0,thenextinstructionisskipped.TheresultiseitherplacedinW(destination=w)orinthe file‘f’(destination=f).
273
Chapter13 Example1: AssumefileAhasbeendefinedandthatitholdsthevalue.123. Loop
… Incfsz A,f GoTo Loop …
;thiscodeisexecuted133timesnot123times
WhenprogramexecutionhitstheIncfszinstruction,thethencurrentvalueofAisincrementedby1and theresulttested.Iftheresultisnonzero,thenextinstructionisexecutedandprogramflowjumpsbacktothe labelLoop.Iftheresultiszero,theGoToLoopstatementisskippedoverandprogramexecutiongoestothe firstopcodefollowingtheGoTo. Example1istheassembleranalogof: A=123 Repeat … A=A+1 UntilA=0
Abecomes0,ofcourse,duetorollover.RolloveroccurswhenAshouldbe256,but,sinceAonlyholds8-bits itinsteadiszero.(256is%100000000wherethefirst%1isthe9thbit.)Thenumberoftimestheloopcode willexecuteisthus256-123,or133times. OpCode
Operands
Description
Cycles
Affected
IORLW
k
InclusiveORLiteralwithW
1
Z
Notes
Iorlwperformsabit-by-bitlogicalORofthevalueinWandtheliteral‘k.’TheresultisretainedintheW
register. TheORfunctiontruthtableis: InputA 0 0 1 1
InputB 0 1 0 1
AORB 0 1 1 1
Example1: AssumeWholds.123beforetheinstruction. Iorlw
31
;BeforeInstructionW:01111011=.123 ; 31:00011111=.31 ------- AfterW:01111111=127
OpCode
Operands
Description
Cycles
Affected
Notes
IORWF
f,d
InclusiveORWwithf
1
Z
1,2
Iorwfperformsabit-by-bitlogicalORofthevalueinWandthevalueheldinafile‘f.’Theresultiseither placedinW(destination=w)orinthefile‘f’(destination=f).
274
Assembler101 TheORfunctiontruthtableis: InputA 0 0 1 1
InputB 0 1 0 1
AORB 0 1 1 1
Example1: AssumeWholds.123beforetheinstructionandassumefileAholds.31. Andwf
A,w
;BeforeInstructionW:01111011=.123 ; 31:00011111=.31 ------- AfterW:01111111=.127
ThevaluestoredatfileaddressAremains.31. Example2: AssumeWholds.123beforetheinstructionandassumefileAholds31. Andwf
A,f
;BeforeInstructionW:01111011 ; 31:00011111 ------- Afterf:01111111=127
ThevalueinWremains.123. OpCode
Operands
Description
Cycles
Affected
Notes
MOVF
f,d
Movef
1
Z
1,2
Movfcopiesthevalueinfile‘f’toeitherWorbacktothesamefile‘f.’TheresultiseitherplacedinW(destination=w)orinthesourcefile‘f’(destination=f).
Itmayseempointlesstocopyafilebacktoitself.However,copyingthefilebacktoitselfsetstheStatus flagifthefilevalueis0,soitpermitsustotestthefile‘f’forzerovalue.Movfismostoftenusedto loadWwiththevalueoffile‘f.’ Example1: AssumefileAhasbeendefinedandthatitholdsthevalue.123. Movf
A,w
RegisterWwillcontain.123aftertheoperationisexecuted. Remember—movfdoesnotallowyoutocopythecontentsofonefiletoanotherfile.ThecopyiseithertoW orbacktothesourcefile. OpCode
Operands
Description
Cycles
MOVLW
k
MoveLiteraltoW
1
Affected
MovlwloadsregisterWwiththevalueoftheliteral‘k’wherekisintherange0…255.
Example1: Movlw .123
AfterthisoperationisexecutedWcontainsthevalue.123.
275
Notes
Chapter13 OpCode
Operands
Description
Cycles
MOVWF
f
MoveWtof
1
Affected
Notes
MovwfcopiesthecontentsofregisterWtofile‘f.’MovwfishowresultsinWareplacedinafile‘f.’ Example1: AssumefileAhasbeendefinedandthatitholdsanunknownvalue Movlw .123 Movwf A
First,weloadregisterWwiththeliteral.123.Next,themovwfoperationcopiesW’svaluetofileA.Afterthese twooperationscomplete,Aholdsthevalue.123. OpCode
Operands
Description
Cycles
NOP
–
NoOperation
1
Affected
Notes
NOPisthe“nooperation”code.Itconsumesonecycleandisusedtogeneratebrieftimedelayssuchasto
balanceexecutiontimeswheredifferentcodesegmentsmustexecuteintheidenticaltime. Example1: NOP
AllregisterandfilevaluesareunchangedaftertheNOP. OpCode
Operands
Description
Cycles
RETFIE
–
ReturnfromInterrupt
2
Affected
Notes
Retfieisusedtoterminateaninterrupthandler.
UsingRetfieisadvancedtopicandthisopcodewillnotbefurtherdiscussed.OuruseofMBasic’sassemblerinterruptsupportwillnotrequireustousetheRetfieoperation. OpCode
Operands
Description
Cycles
RETLW
k
ReturnwithLiteralinW
2
Affected
Notes
RetlwreturnsfromaGoTowithaliteral‘k’loadedintheWregister. Retlwisusedmostoftenforadataorlook-uptable,toreturn,andallowsustoimplementtheassembler equivalentofMBasic’sByteTable,wherebywemayaccessX(n),thevalueofthenthdataentry.
Example1: AssumefileAisdeclaredandholdsavaluebetween0…7. movf A,w call GetHalfPattern … GetHalfPattern addwf PCL,f retlw 0x08 retlw 0x0C retlw 0x04 retlw 0x06 retlw 0x02 retlw 0x03 retlw 0x01 retlw 0x09
276
Assembler101 Wisloadedwiththeindexintothetable.AftertheCalloperation,Wholdstheindexedvalue.Forexample, ifAholds.3,aftertheCalloperation,Wholds0x6. OpCode
Operands
Description
Cycles
RETURN
–
ReturnfromSubroutine
2
Affected
Notes
ReturntransfersprogramexecutionbacktotheCallstatementattheendofasubroutine,similarto MBasic’sReturnoperation.Uponreturnfromthesubroutine,programexecutionresumeswiththeopcode immediatelyfollowingtheCalloperator.
Example1:
… CallSubOne …
SubOne … ;subroutinecodegoeshere Return OpCode
Operands
Description
Cycles
Affected
Notes
RLF
f,d
RotateLeftfthroughCarry
1
C
1,2
RLFrotatesthevalueheldinfile‘f’onebittotheleft,throughthecarryflag.TheresultiseitherplacedinW (destination=w)orinthesourcefile‘f’(destination=f).Thisprocessre-circulatesthebits.
Example1: AssumefileAisdeclaredandholdsthevalue.179. RLFA,f RLFA,f Status 0 1 0
B7 1 0 1
B6 0 1 1
B5 1 1 0
RegisterA B4 B3 1 0 0 0 0 1
B2 0 1 1
B1 1 1 0
B0 1 0 1
Comments Beforerotatecommand,A=179 Firstshifttotheleft.A=102 Secondshifttoleft;notethe1shiftedthroughcarryhas nowreappearedatB7.A=205
Ifyouwishastraightshift,notre-circulation,itisnecessarytoclearStatusaftereachRLF. OpCode
Operands
Description
Cycles
Affected
Notes
RRF
f,d
RotateRightfthroughCarry
1
C
1,2
RRFrotatesthevalueheldinfile‘f’onebittotheright,throughthecarryflag.TheresultiseitherplacedinW (destination=w)orinthesourcefile‘f’(destination=f).Thisprocessre-circulatesthebits.
Example1: AssumefileAisdeclaredandholdsthevalue.123. RRFA,f RRFA,f
277
Chapter13 Status 0 1 1
B7 0 0 1
B6 0 0 0
B5 1 0 0
RegisterA B4 B3 1 0 1 1 0 1
B2 0 0 1
B1 1 0 0
B0 1 1 0
Comments Beforerotatecommand,A=123 Firstshifttotheright.A=25 Secondshifttoright;notethe1shiftedthroughcarry hasnowreappearedatB7.A=140
Ifyouwishastraightshift,notre-circulation,itisnecessarytoclearStatusaftereachRRF. OpCode
Operands
Description
Cycles
Affected
SLEEP
–
GointoStandbymode
1
TO,PD
Notes
SleepplacesthePICintostandbymode.Thisisanadvancedtopicandwillnotbefurtherdiscussed. OpCode
Operands
Description
Cycles
Affected
SUBLW
k
SubtractWfromLiteral
1
C,DC,Z
Notes
SublwsubtractstheWregisterfromtheliteral‘k’usingtwo’scomplementarithmetic.Notetheorderof subtractionisW=k-W.
Example1: SupposefileAisdeclaredandholdsthevalue.47 movfA&0x7F,w sublw .100
;w=.47 ;w=(.100-.47)=.53
Example2: SupposefileAisdeclaredandholdsthevalue.123 movfA&0x7F,w sublw .100
;w=.123 ;w=(.100-.123)=.233
Example2hasthesubtrahendlargerthantheminuend.Theresultmaybecalculatedusingthetwo’scomplementoffset,.256: Result=.256+.100-.123=.233.Alternatively,the.256maybeviewedasacarrytothe9thbit. OpCode
Operands
Description
Cycles
Affected
Notes
SUBWF
f,d
SubtractWfromf
1
C,DC,Z
1,2
SubwfsubtractsthevalueinregisterWfromthevalueinfile‘f’usingtwo’scomplementarithmetic.The resultiseitherplacedinW(destination=w)orinthesourcefile‘f’(destination=f).NotetheorderofsubtractionisResult=f-W.
Example1: SupposefileAisdeclaredandholdsthevalue.100 movlw.47 subwfA,f
;A=.100 ;W=.47 ;A=(.100-.47)=.53
278
Assembler101 Example2: SupposefileAisdeclaredandholdsthevalue.100 ;A=.100 movlw.123 ;W=.123 subwfA&0x7F,f;A=(.100-.123)=.233
Example2hasthesubtrahendlargerthantheminuend.Theresultmaybecalculatedusingthetwo’scomplementoffset,.256: Result=.256+.100–.123=.233.Alternatively,the.256maybeviewedasacarrytothe9thbit. OpCode
Operands
Description
Cycles
SWAPF
f,d
Swapnibblesinf
1
Affected
Notes 1,2
Swapfreversesthehighandlownibbleinfile‘f.’TheresultiseitherplacedinW(destination=w)orinthe sourcefile‘f’(destination=f).
Example1: AssumefileAhasbeendefinedandthatitholdsthevalue.123. Swapf A,f
;BeforeInstructionA:01111011=.123 ;AfterSwapf A:10110111=.183
OpCode
Operands
Description
Cycles
Affected
XORLW
k
ExclusiveORLiteralwithW
1
Z
Notes
Xorlwperformsabit-by-bitlogicalXORofthevalueinWwiththeliteral‘k.’TheresultisretainedintheW register. InputA 0 0 1 1
InputB 0 1 0 1
AXORB 0 1 1 0
Example1: AssumeWholds.123beforetheinstruction. Xorlw
31
;BeforeInstructionW:01111011=.123 ; 31:00011111=.31 ------- AfterW:01100100=.100
OpCode
Operands
Description
Cycles
Affected
Notes
XORWF
f,d
ExclusiveORWwithf
1
Z
1,2
Xorwfperformsabit-by-bitlogicalXORofthevalueinWwiththeliteral‘k.’TheresultisretainedintheW register. InputA 0 0 1 1
InputB 0 1 0 1
279
AXORB 0 1 1 0
Chapter13 Example1: AssumethefileAisdeclaredandholdsthevalue.123andthatWholds.31beforetheinstruction. Xorwf
A,w
;BeforeInstructionA:01111011=.123 ; W:00011111=.31 ------- AfterW:01100100=.100
References [13-1]
AcompletedatasheetformostPICscomprisestwoelements;(a)adetailed“family”referencemanual and(b)theparticulardevicedatasheet.MBasicsupportsonlyPICsfromMicrochip’s“midrange”familyandtheassociatedPICmicro™Mid-RangeMCUFamilyReferenceManualmaybedownloaded athttp://www.microchip.com/download/lit/suppdoc/refernce/midrange/33023.pdf.Thisisa688-page document,inalmostmindnumbingdetail,butnonethelessisanessentialreferencetoacomplete understandingofPICs.ForindividualPICfamilymemberdatasheets,theeasiestsourceistogoto http://www.microchip.com/1010/pline/picmicro/index.htmandselecteitherthePIC12orPIC16group andfromthatlinkthenselecttheindividualPICdevice. [13-2] Benson,David,EasyPIC’nABeginnersGuidetoUsingPICMicrocontrollersversion3.1,Square1 Electronics,Kelseyville,CA(1999). [13-3] Benson,David,PIC’nUpthePacePICMicrocontrollerApplicationsGuideversion1.1,Square1Electronics,Kelseyville,CA(1999). [13-4] Predko,Myke,ProgrammingandCustomizingPICmicroMicrocontrollers,SecondEd.,McGrawHill, NewYork(2002). [13-5] Predko,Myke,PICMicroMicrocontrollerPocketReference,McGrawHill,NewYork(2001).
280
14
CHAPTER
In-LineAssembler Chapter13describedtherudimentsofassemblerlanguage,soit’snowtimetoseehowthatknowledgemay beusedinMBasic.Ourfocusisnotuponlearninghowtowritecomplexassemblerprograms,butrather howtoaugmentMBasicbyaddingafewlinesofassemblerhereandthere,makingourprogramsrunfaster oraccessPICfeaturesnototherwiseavailabletous.Thischapterprovidesaseriesof“bolt-in”replacements, simpleassemblerroutinesthatmaybedirectlysubstitutedforMBasicstatements.Wewilllearnaprocess ofstepwiserefinement,wherewereplaceMBasicstatementsoneatatime,proceedingtothenextstatement onlyafterverifyingtheearlierreplacement. We’llmakefrequentuseoftheword“macro”inthischapter,solet’sfirstagreewhatamacrois.A“macro” inourcontextisashortcutthatisautomaticallyexpandedbytheassemblerintooneormorerealopcodes. Let’sinventamacroforMBasic.MBasicdoesn’tallowuser-definedmacros,butwe’llsupposeitdoes.Our fictitiousmacrowillsaveusfromtypingthefulldetailstosetupaFor…Nextloop.Itinvokedas:@Fv,s, fwherevisthevariablename,sisthestartvaluefortheloopandfisthefinalvalue.Thus,ourfictitious macropermitsustoentertheline@Fi,0,10.Thecompilerwouldthenexpandthismacroshorthandinto Fori=0to10…Nextfunctionality. Ifthatwereallthemacrodoes,itwouldbeaninterestingwaytosaveafewkeystrokes,butnotallthat useful.There’snothingstoppingus—atleastintherealmofinventingfeaturesforMBasicthatdon’t exist—fromwritingasecondversionofthismacro,@F2i,10thatexpandsintoFori=0to2*10… Next,wheretheblanktemplatemacroisFor<>=0to2*<>Nextwherethefirst<>iscompleted withthevariablename,iinthisexample,andthesecond<>iscompletedwiththesecondmacroargument, 10inthisexample.Thepointisthatourmacrocancontainmathematicalcomputationsandconstants.In manycomputerlanguages,macroscanbemultilineprograms,soitmaybemoreaccuratetothinkofthem asaspecialtypeofsubroutine.And,infact,the@bankmacrowe’llrunintointhischapterisamultiline constructthatincludesanif…thentest.Wewon’tdiscussthedetailsofhowmacrosareconstructed,butyou shouldunderstandthegeneralconceptofwhatamacrodoes.And,toconfuseyouevenmore,MBasic’sinlineassemblermacroshavethesamenameastheassembleropcodeswestudiedinChapter13. Ifyouintendtodoseriousassemblerprogramming,you’llneedmoreinformationthanimpartedinthis book.Thereferencessectionrecommendssomeusefulpublications.
AddingAssemblertoMBasicPrograms MBasicprovidesfourwaystoaddassemblercodetoyourprogram: Librarymacros—MBasichaslibrarymacros,forcertainfunctions,suchas@highforthestandardfunctionhigh,thatautomaticallysubstitutequickassemblercodeforslowerMBasiccode.(We’llalsosee anotherlibrarymacroforassembleropcodes.We’lllookatthesewhenweexaminehowMBasicdeals withgeneral-purposeregisterfileaddressing.)LibrarymacrosareanundocumentedfeatureofMBasic andarenotcoveredinthecurrentUser’sGuide. 281
Chapter14 Assembleropcodemacros—MBasicalsohaslibrarymacrosforalmosteveryassembleropcodesotheymay beusedalmostasiftheywereastandardBASIClanguageoperator.Thesemacrosarenotprefixedwith the@symbol,butratherhavethesamenameastheassociatedopcode;forexample,thedirectmacro fortheassembleropcodebcfisbcf.(Thecallopcodesarenotsodefinedandmustbeusedthroughthe @calland@gotomacros,orviaanASMdirectives.) ASMdirective—Wemaypackageassemblercode,groupedwithcurlybraces{…},followingthecompiler directiveASM.Codewithinthecurlybracesispasseddirectlytotheassembler. Interrupthandler—MBasic’sspecialprovisionsforassemblerinterruptcode,ISRASM,iscoveredinChapter15.
MeasuringExecutionSpeed Sinceexecutionspeedisthereasonwe substituteassembler,beforewedelveinto howtomixassemblercodewithMBasic let’sfirstdevelopasimplewaytomeasure statementexecutionspeed.Aswelearned inChapter10,almosteveryPICincludesat leastonetimer.Sincewe’reworkingwith the16F87x/87xAseriesdevices,we’lluse the16-bittimer1.Totimehowlongittakes foranMBasicstatementorstatementsto execute,we’llusetheconceptdeveloped inProgram10-3,butsignificantlyimprove uponitsperformancebyusingassembler start/stoproutines.Theonlyconnectionto thedevelopmentboardistoconnectthePIC totheserialoutputasshowninFigure14-1. Ourconceptis,inpseudo-code:
Figure14-1:ConnectPICtoserialoutput.
SetTimer1tozero StartTimer1 Executecodetobeprofiled StopTimer1 Readtimer1’svalue
Program14-1implementsthispseudo-code. Program14-1 ;Program14-1 ;MeasureExecutionSpeed ;Constants ;---------;For20MHzclock,Fosc/4=5MHz ;sothereare5ticks/usecor0.2uspertick usPerTick fCon 0.2 ;howmanyclockticksforzerofunction Latency Con4 ;Variables ;---------;holdsthetimervalue t2 Var Extime Var A Var
Word Float Byte
282
In-LineAssembler ;Initialization ;-------------;noprescaler SetTmr1Tmr1Int1 tmr1on=1 EnableHSerial SetHSerialH115200
;starttimer(T1CON,bit0[Bank0]1=on0=off)
Main ASM{ CallStartTime} ;statementstobetimedgohere ASM{ CallStopTime} GoSubDumpTime Pause1000 GoToMain ASM { StartTime bcft1con,0 clrftmr1h clrftmr1l bsft1con,0 Return StopTime bcft1con,0 Return }
;resettimer1to0 ;stoptimer ;clearhighbyte ;clearlowbyte ;turntimeron ;stoptimer1
DumpTime ;------- t2.lowbyte=tmr1l t2.highbyte=tmr1h t2=t2-Latency Extime=usPerTick*(Floatt2) HSerOut[RealExTime\2,”us”,13] Pause10 Return End
Tomaximizeourmeasurementresolution,timer1runswithasshortatickintervalaspossible,thatis,the prescalersetfor1:1.My2840DevelopmentBoardhasa20MHzresonatorinstalled,soaswelearnedin Chapter10,withtheprescalersetfor1:1,timer1willreceiveonetickeveryFosc/4,oronceevery0.2µs. Sincewewishtheresultinmicroseconds,wedefinetheconversionconstantusPerTickas0.2sothatwhen timer1’scountismultipliedbythisconstant,theproductiselapsedtimeinmicroseconds. ;For20MHzclock,Fosc/4=5MHz ;sothereare5ticks/usecor0.2uspertick usPerTick fCon 0.2
WealsorememberfromChapter10thatitisn’tpossibletostartorstopatimerinstantaneously;therewill alwaysbesomelatencyinturningitonandoff.We’lldefineaconstant,Latency,toholdthisdeadtimeas wewishtosubtractitfromourmeasureddatatoprovideanaccuratetimereading. ;howmanyclockticksforzerofunction Latency Con4
We’llseehowtodeterminethevalueforLatencylaterinthisdiscussion. ;Initialization ;-------------;noprescaler SetTmr1Tmr1Int1 tmr1on=1 EnableHSerial SetHSerialH115200
;starttimer(T1CON,bit0[Bank0]1=on0=off)
Theinitializationsetstimer1totheoperatingconditionwedesire—internalticksatFosc/4andprescale ratioof1:1. 283
Chapter14 Main ASM{ CallStartTime} ;statementstobetimedgohere ASM{ CallStopTime} GoSubDumpTime Pause1000 GoToMain
We’veencapsulatedthecodetostartandstoptimer1intotwoassemblersubroutines,StartTimeand StopTime.TheMBasicorassemblercodewewishtotimemustbeaddedbetweenthesetwoCallstatements.BothareaccessedbytheassemblerequivalentofGoSub,theCallopcode.Sincetheseareassembler statements,we’llusetheASMcompilerdirectiveandenclosetheassemblerlanguageportionofourcodein curlybraces.(We’lllearnmoreaboutthislaterinthischapter;fornowtakeitasarequirement.) ASM { StartTime ;resettimer1to0 bcft1con,0 ;stoptimer clrftmr1h;clearhighbyte clrftmr1l;clearlowbyte bsft1con,0;turntimeron Return StopTime bcft1con,0;stoptimer1 Return }
Youshouldseesomefamiliaropcodeshere. Thisassemblermodulehastwolabels,StartTimeandStopTimethat,astheirnamessuggest,starttimer1 andstoptimer1. StartTime—First,weensuretimer1isstoppedbysettingto0itson/offcontrolbit,heldinthet1con registeratbit0.(Weknowthecontrolregisterisnamedt1conandthattheon/offcontrolbitisbit0because weconsultedthe16F87xAdatasheet,Section5.)Weusethebitclearfile,bcf,opcodetoclearthecontrol bit.Next,weresettimer1’sregisterfilesto0bythoughtheclrfopcode.Sincetimer1isa16-bitmodule, weseparatelyclearitshighandlowbytes,tmr1handtmr1l,respectively.Lastly,weturntimer1onby settingitscontrolbitt1con,bit0to1throughabsfoperation,thenreturningtothecallinglocationviathe returnoperator. StopTime—Allwedotostoptimer1istoclearitscontrolbit,t1con,bit0,usingthebcfoperation. DumpTime ;------- t2.lowbyte=tmr1l t2.highbyte=tmr1h t2=t2-Latency Extime=usPerTick*(ToFloatt2) HSerOut[RealExTime\2,”us”,13] Pause10 Return
Afterwehavestoppedtimer1,wecalculatetheelapsedtimeinmicrosecondsandsendthevalueoverthe serialportwithsubroutineDumpTime. WecandeterminethepropervaluefortheconstantLatencybyexperimentation.WiththetwoASMCall statementsadjacenttoeachotherwithoutanyinterveningMBasiccode,setLatencyto0andrunProgram 14-1.Itshouldreturn0.8us,correspondingtofourFosc/4instructions.YoucanthensetLatencyto4and re-runProgram14-1.Thistime,itshouldreport0microseconds.(Or,ofcourse,wemaysimplycalculate therequiredLatencyvaluebasedonthenumberofFosc/4intervalsrequiredtoexecuteeachinstruction.)
284
In-LineAssembler Program14-1A Let’sverifyProgram14-1providesmeaningfultiminginformation.ModifyProgram14-1byaddingabyte arithmeticfunctionandtimeit: Main ASM{ CallStartTime} A=A+1;statementstobetimedgohere ASM{ CallStopTime} GoSubDumpTime Pause1000 GoToMain
We’llcallthisversionProgram14-1A,andithasnootherchanges.(Program14-1declaredAasabytevariable,butdidn’tdoanythingwithit.)RunProgram14-1Aandyoushouldseethefollowingresultdisplayed inyourterminalprogram:
87.59us
TheassignmentoperationA=A+1requires87.6µs,witha20MHzoscillator.(Underversion5.2.1.1,the resultwas96.99µs,soweseeversion5.3.0.0offersannoticeableimprovementinexecutiontime.)
LibraryMacros Thisdetourcompleted,let’sstartwiththesimplestwaytoaddassemblertoyourMBasicprograms,the librarymacro.Infact,it’ssosimple,it’stransparenttoyouwhenprogramming.Librarymacrosaredefined forthefollowingfunctions: StandardName MacroName PinAssignmentFunctions High @High Low @Low Input @Input Output @Output TimingFunctions Pause @MSDelay Pauseus @USDelay AssemblerOnly BankSel @Bank Call @Call GoTo @GoTo Return @Return None @TblJmp None @RateDelay
Themacronameisusuallyformedbyaddinga“@”prefixtotheMBasicnormalname.ThemacrofunctionshaveonemajorlimitcomparedwiththestandardMBasicversion;theirargumentmustbeaconstant. Inthecaseofthefourpinassignmentfunctions,theobjectofthemacroisincreasedspeed;forthetwodelay statements,theobjectisincreasedaccuracyforshortdelays. Toseethedifferencebetweenthestandardandmacroversionsforthepinassignmentfunctions,let’stest theminProgram14-1.ReplacetheMain…GoToMaincodewiththefollowingandsaveitasProgram14-1B.
285
Chapter14 Main ASM{ CallStartTime} HighA0 ASM{ CallStopTime} HSerOut[“HighA0”,9] GoSubDumpTime Pause1000 ASM{ CallStartTime} @HighA0 ASM{ CallStopTime} HSerOut[“@HighA0”,9] GoSubDumpTime Pause1000 ASM{ CallStartTime} LowA0 ASM{ CallStopTime} HSerOut[“LowA0”,9] GoSubDumpTime Pause1000 ASM{ CallStartTime} @LowA0 ASM{ CallStopTime} HSerOut[“@LowA0”,9] GoSubDumpTime Pause1000 ASM{ CallStartTime} InputA0 ASM{ CallStopTime} HSerOut[“InputA0”,9] GoSubDumpTime Pause1000 ASM{ CallStartTime} @InputA0 ASM{ CallStopTime} HSerOut[“@InputA0”,9] GoSubDumpTime Pause1000 ASM{ CallStartTime} OutputA0 ASM{ CallStopTime} HSerOut[“OutputA0”,9] GoSubDumpTime Pause1000 ASM{ CallStartTime} @OutputA0 ASM{ CallStopTime} HSerOut[“@OutputA0”,9] GoSubDumpTime Pause1000 GoToMain StandardMBasicv5.3.0.0 (timingforv.5.2.1.1) Name ExecutionSpeed(µs) High 23.2 (28.6) Low 23.0 (28.4) Input 22.6 (28.0) Output 23.0 (28.4)
Name @High @Low @Input @Output
286
MBasicLibraryMacros ExecutionSpeed(µs) 0.8 0.8 0.6 0.6
In-LineAssembler Thefourpinassignmentproceduresshowremarkableimprovement;fromaround23µsinstandardMBasic v5.3.0.0towellunder1µsinmacroform. Thetwomacrodelayfunctions,@USDelayand@MSDelaywillnotbefurtherdiscussed,astheyhaveperfectlyserviceableMBasicforms,andthetablejumpmacro,@TblJmp,isanadvancedmacroandwillnotbe furtheranalyzed. Finally,youmayhavenoticedtheASM{CallStartTimer}codeisreplacedbythe@Callmacro: @callStartTimer.Themacrooffersacleanerrepresentationandexecutesinidenticaltime.
MBasicVariables Beforewediscussthelibraryassemblermacros andtheASMcompilerdirective,wemusttake yetanotherbriefdetourandexaminetheway MBasicpassesvariableinformationontothe assembler.AswelearnedinChapter2,the compilertranslatesMBasicstatementsintoassemblercommands,writingafilewiththesame nameasyour.BASfile,butwiththeextension .ASM.MBasicthenrunsassemblerandlinker programs(fromv5.3.0.0onward,GPASM; earlierversionsusedMicrochip’sMPASMv.3 assemblerandlinker)thatmergesthedirectly translatedassemblercodewithMBasic’slibrary functions,andassemblesthecompositecode intoaformsuitableforloadingintothePICby aloaderprogram.Figure14-2illustratesthis process. WelearnedinChapter13thatthe16F87x/ 87xA’sregisteraddressesareintherange 0…511,andrequirea9-bitaddress.Wealso learnedthatthe9-bitregisteraddressisbroken Figure14-2:Compilingandlinkingactions. intoa7-bitpartthatmaybeusedasanopcode argumenttodirectlyaddressaregisterinthecurrentbank,withthetwohigherorderbitsbeing“bankselectionbits”thatselectbetweenoneoffourregisterbanks.Ifthissoundsunfamiliartoyou,takeamomentand rereadChapter13,asit’sessentialthatyougrasphowthe16F87x/87xAaddressesdataregisters. Let’sseehowMBasic’scompileridentifiesvariableaddresses.Remember,ofcourse,thatthevariablewe definethuslyasAVarByteistransformedintoaregisteraddress,i.e.,anumber.Intheassembleroutput ofthecompiler,therefore,thisstatementislinkedtoaspecificregisterassignment,usingtheassembler equatedirective. Program14-2 Let’sseehowthisworksinasimpleprogramthatdoesnothingmorethandefinesvariables: ;Variables ;----------AByte AWord ALong
Var Var Var
Byte Word Long
287
Chapter14 ABit1 ABit2 ByteArray WordArray Clear
Var Var Var Var
Bit Bit Byte(8) Word(4)
End
Let’snowlookatthepertinentportionsofcompiler’sassembleroutput,foundinProgram14-2.ASM.About themiddleofProgram14-2.ASMwefindthevariableassignments: ALONGequ0AA0h AWORDequ06A4h WORDARRAYequ06A6h ABYTEequ02AEh BYTEARRAYequ02AFh ABIT1equ08B7h ABIT2equ018B7h
ThevariableAbyte,forexample,isstoredinregisteraddress02AEh(remember,theassemblerusesah suffixinsteadofa$prefixforhexadecimalnotation),correspondingtodecimal686.Waitjustaminute,you say.Youjustfinishedtellingmethatthehighestpossibleregisteraddressisdecimal512,sinceitmustbe heldina9-bitnumber,butheretheassemblerassignedavariabletoregisteraddress686.What’sgoingon here? Theansweristhatthecompilerrequirescertaininformationconcerningthetypeofvariable,whetheritisan array,andsoforth.Consequently,thecompilerassignsthevariablea16-bitidentifier,addingsevencompiler controlbitstothe9-bitregisterfileaddress: B15 AM
B14 B13 B12 Bit/NibIndex
B11 B10 B9 VariableType
B8 B7 BankNo.
B6
B5 B4 B3 B2 B1 7-bitFileAddressforOpCodes 9-bitFileAddress
B0
AM=SignedVariableMarker B14alsoidentifiessigned/unsignedvariables
Thethreevariabletypebitsareassignedaccordingtothefollowingarrangement,asfoundnearthetopof Program14-2.ASM: ASMEquates _FLOATTYPEequ0E00h _SLONGTYPEequ4A00h _LONGTYPEequ0A00h _SWORDTYPEequ4600h _SBYTETYPEequ4200h _WORDTYPEequ0600h _BYTETYPEequ0200h _NIBTYPEequ0400h _BITTYPEequ0800h
Bit/NibIndex 000 100 000 100 100 000 000 000 000
VariableTypeBitAssignment 111 101 101 011 001 011 001 010 100
Comments (newin5.3.0.0) (newin5.3.0.0)
Thebits/nibindexrunsfrom0…7andapplieswheremorethanonenibbleormorethanonebitvariable isallocated.Thecompilerattemptstoefficientlyusememoryspace,soupto8bit-lengthvariableswillbe packedintoonebyte,anduptotwonibbleswillbepackedintoonebyte.Wordandlongvariablesarestored inconsecutivebyteswiththelowestorderbyteoccupyingthelowestmemoryaddress.Thesetypeidentifiers maychangewithnewcompilerreleases. Wherethevariableisamultibytetype,suchasatypeword,typelongoranarrayofbytes,wordsorlongs, thecompilerassignedaddressisthe“base”address,i.e.,thelocationofthelowestbyteinthecollectionof
288
In-LineAssembler registersthatareassignedtoholdthevariable.Inanarrayofbyte,forexample,BarrayVarByte(5), theaddressrepresentsthelocationofBArray(0).Inthecaseofawordvariable,forexample,AWordVar Word,theassignedaddressrepresentsAWord.Byte0.Thecompilerwillnotsplitamultibytetypevariable acrossdifferentbanks,however.Arraysmayoccupymorethanonebank,butwithinthearraynovariable willbesplitacrossbanks.
AssemblerMacrosversusASMCompilerDirective WhyhavewetakenthisdetourtoexaminethedetailsofhowMBasic’scompilerallocatesvariablestospecificregisterfiles?Theansweristhatitisnecessarytounderstandthedifferencebetweenthetwofollowing alternateassemblystructures: ASMConstruct AByte Var Byte
InLineMacroConstruct AByte Var Byte
ASM { ClrfAByte }
clrfAByte
Bothaccomplishthesametask;settingthebytevariableABytetozero.Program14-3incorporatesthese twoconstructs. Program14-3 ;Variables ;----------AByte Var
Byte
Clear Main End
ASM { ClrfAByte } clrfAByte
WhathappenswhenwerunProgram14-3?Thecompilerreportswarningmessages: Warnings/Errors/Messages: Warning[219]C:\PROGRA~1\MBasic~1\PROGRAMS\CHAP14~1\PR22DF~1.ASM140:InvalidRAMlocationspecified. Message[302]Message[302]C:\PROGRA~1\MBasic~1\PROGRAMS\CHAP14~1\PR22DF~1.ASM140:Registerinoperandnot inbank0.Ensurebankbitsarecorrect.
ThesewarningmessagesrelatenottotheMBasicsourcecode,butrathertoproblemstheassemblerfound withthecompiler’soutput.Todeterminewheretheoffendinglineis,opentheassociatedassemblerfile, Program14-3.ASMandgotoline140.Itis:
CLRFABYTE(theoneinsidetheASMbraces{})
Bynow,youshouldunderstandwhytheassemblerobjectedtothisoperation;theargumentfortheclrfoperatormustbea7-bitregisteraddressintherange0…127,nota16-bitaddressconstructedtoalsoprovide compiler-specificinformation.Nowonder,therefore,thattheassemblerwarnsusthattheaddressforABYTE isnotintheexpectedrange.
289
Chapter14 Wemust,therefore“trimoff”theseexcesscompilerbitstoextractthe7-bitregisteraddressinasuitable formtouseasavariableaddresswithanassembleroperator.Theeasiestwaytotrimthehighorderbitsisto takeadvantageoftheassemblerprogram’sabilitytoperformbitwiselogicaloperationswithargumentsand usethelogicalANDfunctionwithamaskingvariable.(We’veseenhowtheANDfunctionworksasamask whenstudyingtheANDLWopcodeinChapter13.).Accordingly,wemayextractthe7-bitregisteraddress fromthe16-bitcompiler-generatedversionwiththefollowingoperation: 7-BitVersion=16-BitVersionAND%1111111
Toimplementthiswithassembler,wewouldsimplywrite:
CLRFABYTE&0x7F
Wheretheampersand“&”istheANDoperatorand0x7Fisthehexadecimalformof%1111111. Let’stryanamendedversionofProgram14-3. Program14-3A ;Variables ;----------AByte Var
Byte
Clear Main End
ASM { ClrfAByte&0x7F } clrfAByte
Thecompilerreportsnoerrors.But,istheprogramcorrect?Unfortunately,itisn’t,asAByteisinBank1. We’llseehowweknowthisandhowtofixthebankingbitswhenwere-examineProgram14-3Alaterin thischapter. Whydidnotthemacroclearoperation,clrfAbyte,generateawarningmessage?Afterall,ithasthe same16-bitversionofAbyte’saddressasdidthepureassembleropcodeinsidetheASM{…}section.The answeristhatthemacroclrf,aswithalltheotherassembler-namedlibrarymacrosdefinedinMBasic automaticallyincorporatethe&0x7Ffunction.However,thesemacrosdonotincorporateautomaticbanking selection. ItalsoturnsoutthatMBasichasyetanothersetoflibrarymacrosthatautomaticallyincludeaddresstrimming.ThesemacrosmaybeusedonlyinsidetheASM{…}sectionandareidentifiedas_@opcode.For example,_@clrfistheaddresstrimmingmacroversionoftheassembleropcodeclrf,anditmaybeused onlyinsidetheASM{…}section. Oneadditionalpointisthatalthoughusingthe16-bitaddressformgenerates“Warnings/ErrorMessages,” infactthecodewillassembleandfunctioncorrectly(assuming,ofcourse,thatyouhavecorrectlysetany requiredbankingbits!)astheassemblerignoresallbitsbeyondthesevenlegitimateaddressbits.And,it’s possibletoturnofftheseerrormessagesbyanassemblerdirective. UsingMBasicvariablesinassemblerroutinesisabitconfusingtothebeginner,particularlysincemacros andtheactualopcodessharethesamename.ThefollowingtablesummarizestheoptionsinusingMBasic variableaddressesinassemblercode:
290
In-LineAssembler IfyouwritetheassemblercodeinASM{…}form
IfyouuseinlinecodewithouttheASM{…}directive
•Trimtheextrabitsoffwiththe&0x7Foperator:
•UsetheMBasicmacrowiththesamenameastheassembler opcode.Themacroautomaticallytrimstheextrabits. clrfAByte
clrf0x7F&Abyte
•Usetheassemblermacroversion(prefixedwiththe_@). Thismacroautomaticallytrimstheextrabits. _@clrfAByte •Don’ttrimtheextrabitsandeitherignorethewarning messagesorsuppressthewarningmessagesbyaddingthe followingassemblerdirectivebeforeyourASM{…}code: ASM { errorlevel-219 errorlevel-302 }
BankSelection Nowthatwe’velearnedhowtomakethe7-bitregisteraddressavailabletoourassemblercode,howdowe dealwiththebankselection?Forthepurposeofthisdiscussion,I’llassumeyouaredealingonlywithbyte variables,notbytearrays,noranyothervariabletype.(We’llseehowtoaccesssomenon-bytevariables laterinthischapter.) Wehaveseveraloptions: InspecttheAssemblerCodeandDetermineAllVariablesareinBank0
Let’sdealwiththesimplestcasefirst.Afterdeclaringallthevariablesyouintendtouseinyourprogram, compileitandinspecttheassociatedASMfile.Usingthetechniqueswelearnedmanuallydeterminewhich bankisassociatedwitheachvariableyouplantouseinassemblercode.MBasicsetsthebankingbitsto Bank0whenithandsovercontroltoyourassemblycode,soifallthevariablesandspecialpurposeregisters youplantouseinyourassemblerroutineareinbank0,youdon’thavetoworryaboutbankswitching. TodetermineintowhichbankMBasichasplacedavariable,convertthevariable’shexadecimaladdressto binaryandexaminebits8and7;iftheyarebothzero,thevariableisinbank0.Toconvertfromhexadecimal tobinaryyoumayusethecalculatorprogramincludedMicrosoftWindows.(It’sfoundunderAccessories. Don’tforgetthatyouhavetoswitchittoscientificmodetogethexadecimaltobinaryconversionfeatures.) Or,youmaykeeptheMicrosoftcalculatorinhexadecimalmode,enterthevariable’saddressandANDthe addresswith$1FF.Thenshiftthecalculatordisplaytobinary.Bits8and7givethebanknumber.Sincethe calculatorblanksleading0’s,thedisplaymayshowfewerthanninebits. Manuallyinspectingtheresultisanacceptableprocessonlyforsimpleprogramsthatyoudon’tintendto modify.It’stooeasytoaddavariableortwoandshiftavariableyouareusingintoadifferentbankwithout realizingit.Orifyoudorealizeit,youareforcedtosearchyourworkandaddbankselectioncodewiththe riskthatyoumissmakingthechangeinaplaceortwo. IfwelookattheassemblyoutputforProgram14-3A,weseethecompiler(v5.3.0.0)hasmadethefollowingmemoryallocation: ABYTEequ02A0h
Converting$02A0tobinary,wefind(afteraddingspacesforclarity)1010100000.ThistellsusthevariableAbyteisassignedspaceinBank%01(decimal1),atrelativeaddress%0100000(decimal32).Abyte’s 9-bitaddressis%010100000,or$A0.(This9-bitaddresscanalsobecomputedbyANDingtheequate valuefoundintheASMlistingwith$1FF.) 291
Chapter14 MBasicchangeditsvariableassignmentprocedure,beginningwithversion5.3.0.0.Priorversionsbydefault reservedthefirstavailable20words(40bytes)ofmemoryforthecompiler’sinternalstack.(Largeror smallerstacksizescouldbesetbythroughtheSTACKcommand.)Uservariablescommencedwiththe41st byteofRAM.Sincethe16F87xfamilyhas98bytesofRAMinbank0,48byteswereavailableforassignmenttouservariables.Beginningwithversion5.3.0.0,MBasic’sdefaultistoreserve100%ofbank0 memoryforitsinternalstackrequirements.Thus,alluservariablesinversion5.3.0.0willbeinbanks1…3, unlessyouoverridethedefaultstacksettingtoclaimlessthan100%ofbank0. Ifyoudecidetooverridethedefaultstacksetting,youmighttrySTACK=10asastartingpoint,whichreserves40bytesforstackmemory,freeingup28bytesinbank0foruservariables.(In5.3.0.0,thestacksize isspecifiedinincrementsof4bytes,achangefrom5.2.1.1wherethestacksizeisspecifiedinincrementsof 2bytes.)Ifyouseerandomerrorsorfreezesinyourcode,youmayneedtoincreasethestackreservation. Inthe16F87xfamily,MBasic’scompilermakesanumberofstandardmemoryassignmentsinbank0for internaluse.Youwillseldomneedtousethesereservedvariables,butitisusefultounderstandhowMBasic carvesupbank0memory. RAMAddress(hex) $20 $21 $22 $23 $24 $25 $26 $27 $28 $29 $2A $2B $2C
$2C+4*N
MBasicReservationName _WORK _WORK2 _WORK3 _WORK4 __ENHWORK __ENHWORK2 __ENHWORK3 __ENHWORK4 __ENHWORK5 __ENHWORK6 __ENHWORK7 __ENHWORK8 STACKstart … … … … STACKend
$70 $71 $72 $73 $74 $75 $76 $77 $78 $79 $7A $7B $7C $7D $7E $7F
PossibleUserVariableMemory _PC _PCH _PCU _PCSP _SP _CMDand_DEBUGWORK _CMD2_andDEBUGWORK2 _CMD3and_DEBUGWORK3 _CMD4and_DEBUGWORK4 _CMD5and_DEBUGWORK5 _INTSTATE _INTSTATEH _fsr_temp _pclath_temp _status_temp _w_temp
292
Comment 4bytesforworkingvariables
8bytesforextendedworkingvariables
Thestackusesmemorylocationsstarting at$2C.Theamountofmemoryitusesis determinedbythecompilerdirectiveSTACK =N,where4*Nbytesarereservedforstack memory. Maximumstacksize68bytes(N=17) Ifstackisnotsetatmaximum
16bytesfortemporarystorage Note:Theseaddressesare“ACCESS ADDRESSES”andarereachableinanybankvia thevariables7-bitoffsetaddresswithoutregard forthebankselectionbits
In-LineAssembler ForceaBankSelectionwithBankSel
Theassemblermacro,BankSel,automaticallydecodesthevariableaddressandgeneratesassemblercode settingthecorrectbankselectionbits. BankselusagechangedslightlybeginningwithMBasicversion5.3.0.0.MBasicbefore5.3.0.0usedMicrochip’sMPASMassembler,inwhichBankSelexpectsa9-bitargument,i.e.,anaddressintherange0…511.
Toprovidethisargument,wemustmaskouttheuppersevenbitsofthe16-bitcompilerversionvariable address.WemayaccomplishthisbyusingthesamelogicalANDprocessweusedtomaskallbutthelower sevenbitsforopcodearguments.Inthiscase,however,ourmaskvariablewillbe%111111111,or0x1FF: BankSel
Abyte&0x1FF
ThefollowingexampleshowsBankSel’susageinMBasicbeforeversion5.3.0.0:
;versionsearlierthan5.3.0.0 ASM { bankselAByte&0x1FF ClrfAByte&0x7F }
Withversion5.3.0.0,MBasicswitchedtotheGPASMassembler,whichrequiresthevariabletobeused withouttrimmingtotherange0.511:
;version5.3.0.0onward ASM { bankselAbyte ClrfAByte&0x7F }
Ifyouusethe&01FFoperatorwiththebankselmacroinversion5.3.0.0andlater,youwillreceivean“illegallabel”errormessageandthecodewillnotassemble. MakeanOptionalBankSelectionwithThe_@Bankorthe@BankMacros
ThedisadvantageofforcingabankselectionwiththeBankSelmacroisthatitaddsbankselectioncode whetherit’srequiredornot.Ifthebankselectorbitsarealreadysetforbank0,andAbyteisinbank0,the operationBankSelAbyteaddsunnecessarycodetotheprogram.MBasichasdefinedtwoassemblermacrosthattestwhetherachangedbankselectionisnecessaryandgeneratescodeonlyifthenewvariableisnot inthesamebankastheoldvariable. ForuseinsidetheASM{…}construction,themacrois_@bank,withsyntax: _@bankOldVar,NewVar
OldVaristhelastvariableused NewVaristhenewvariable,tobetestedagainstOldVarandabankselectionperformedifnecessary.The followingexampleshows_@bank’susage: Main
ASM {_@bank0,AByte ClrfAByte&0x7F _@bank,Abyte,0 }
Thefirsttimeweinvoke_@Bank,theOldVarargumentis0,becauseuponenteringanASM{…}structure, MBasicsetsthebankselectorto0.TheNewVarargumentisAbyte,andbecausethemacrotakescareof trimmingunnecessarybits,werequirenomaskingoperation.WethenaccessthevariableAByte,anduse _@Bankasecondtimetorestorethebankselectorto0,asMBasicexpectsthebankselectortobesetto0 whenexitinganASM{…}structure. 293
Chapter14 Foruseininlinecode,MBasicdefinesthemacro@bank,withsyntaxidenticaltothatof_@bank: @bankOldVar,NewVar
Thefollowingexampleshows@bank’susage: Main End
@bank0,AByte clrfAByte
Themacrotakescareoftrimmingunnecessarybitsfromthe16-bitaddress.
MacrosinISRASM Beforeversion5.3.0.0,MBasic’sassemblermacros,thatis,allmacrosprefixedwith_@suchas_@bank, areunusableinsideanISRASMroutine.ThisisbecausethemacrosaredefinedaftertheISRASMcodeand hencearenotrecognizedbytheassembler.Chapter15providesmoredetailonthislimitation.Fortunately, thisrestrictionisremovedin5.3.0.0.
PageSelection Wealsolearnedthatthe16F87x/87xAdevicesarelimitedtoa2048locationjumppagerestrictionforGoTo andCalloperations.MBasichasdefinedsomemacrostoassistinmakingjumpsoutsideapage(sometimes calledlongjumpsorlongcalls)buttheseareadvancedtopicsandwillnotbedirectlydealtwithinthisintroductorylevelbook.
_@RateDelayMacro Let’scloseoutthissectionbylookingattheoneofthetworemainingspecialassemblermacros,_@RateDelay.(Thelastmacro,@TblJmp,we’llleaveforafuturebookdealingwithmoreadvancedsubjects.) _@RateDelayisintendedtohelpprogramloopsthatmustprovideanoutputatadefinedperiodicrate,butit
alsoworksasastand-alonedelayfunctionnotassociatedwithaloop.Itssyntaxis: _@RateDelayRate,Offset
Rate—isaconstantthatdefineshowmanytimespersecondtheloopistocycle.Ifyouwishtheloopto cycle5000timespersecond,setRateat5000. Offset—isaconstantdefininghowmanyinstructioncyclesareconsumedbycodeintherestoftheloop.
Forexample,thefollowingassemblerloophasfiveinstructioncycles: loop: @ratedelay1000,5 movfwtemp;1 decftemp,w;1 movwftemp;1 gotoloop;2
(ThenumberofinstructioncycleseachassemblerinstructionconsumescanbefoundineitherMicrochip’s MidrangeReferenceManual,orthespecificdatasheetforthedeviceyouareusing.) Let’slookathow@ratedelaymightbeusedinyourcode.Thiscodefragmentassumesiisdeclaredasa bytevariable.Itputsatrainof10briefpositivepulsesoutonpinB0attherateof5000pulsespersecond, waits1secondandrepeatsthepulsetrain. Main Loop:
i=10;timestorepeatloop ASM { ;setfor5000reps/sec,or200us/rep _@ratedelay5000,6 bsf PortB,0 ;1
294
In-LineAssembler NOP ;1delayforpulsewidth bcf PortB,0 ;1 _@decfsz i,f ;1 GoToLoop ;2 NOP ;providesonemachinecycletomakeitexact } Pause1000 GoToMain
TheextraNOPaftertheloopcompensatesforthedifferenceinthedecfszinstruction,whichisone(no skip)ortwo(skip)instructioncycles.WhencombinedwiththeGoToloop,theinstructionpairexecutesin eitherthreeinstructioncycles(GoToloopexecuted)ortwoinstructioncycles(i=0,sotheGoToisskipped). Hence,weareshortoneinstructioncycleattheend,whichwemakeupforbytheNOP.
Bolt-InAssemblerFunctions Theremainderofthischapterwillfocusuponspecificcodeexamplesthatyoumayusetoreplacecertain MBasicoperations.Ourfocusisuponsimplereplacementsandaprocessofstepwiserefinement.We’renot, forexample,goingtowriteanassemblerreplacementforgeneral-purposemultiplicationordivision.But,we willshowsomefastwaystodividebyabinarypower,suchas2,4,8…ortoobtaintheremainderfunction aftersuchadivision.Withabitofcareandplanning,mostifnotallbottleneckfunctionscanbeconvertedto anassemblerroutinebaseduponcodeinthischapter.
StepwiseRefinement TheprocessofstepwiserefinementistowriteanddebugtheprograminMBasicandthendeterminewhethergreaterspeedisrequiredtomeetyourobjectives.Ifincreasedspeedisnecessary,thenwestartreplacing smallelementsofMBasic—perhapsassmallasonelineofcode—withassemblerroutines.Aftereach replacementistestedanddebugged,weagaindetermineifourspeedobjectivesaremet.Ifnot,werepeatthe processuntileitherwe’verunoutofcodetoconvertorourtargetismet. Chapter19providesadetailedexampleofapplyingstepwiserefinementtoasteppermotorcontrolprogram. The100%MBasiccontrolloopofProgram19-1permitsamaximummotorspeedof55.8RPM.Aswe progressivelyreplacedMBasicstatementswithassemblerroutines,themaximummotorspeedincreasedto 317RPM,a5.7:1speedup.Program19-2showsthecompletedreplacement.Atthispoint,ourperformance objectiveshadbeenachieved. Here’sthemainloopofProgram19-1: Main ;---Fori=0toCyCLen-1 j=(i+8)/16 k=i//32 n=(i+16)//32 HPWM0,PWMPeriod,Cosine(k) HPWM1,PWMPeriod,Cosine(n) MPort=FullStep(j) Next
YoumaywishtotakeabreakfromthischapterandsneakapeakatChapter19,butthefollowingtable showstheeffectivenessofeachreplacement: RefinementStep 0 1 2
MBasicCodeReplaced None–100%MBasic j=(i+8)/16 k=i//32
MaximumMotorSpeed 55.8RPM 71.6RPM 95.8RPM
(Continued)
295
Chapter14 RefinementStep 3 4 5 6
MBasicCodeReplaced n=(i+16)//32 MPort=FullStep(j) HPWM0,PWMPeriod,Cosine(k) HPWM1,PWMPeriod,Cosine(n)
MaximumMotorSpeed 158.2RPM 185.2RPM 231RPM 317RPM
IretainedthemainFori…NextloopinMBasic,aswehadmorethanmetourperformanceobjective throughreplacingthesixstatements.Theorderofreplacementroughlyfollowedtheorderofcomplexity; theeasieststatementsweretheonesfirstreplaced.Youalsowillnotethatthedivision,remainderandadditionvaluesareallpowersof2.Thatisnotanaccidentasitsimplifiedtheassemblerroutines. Let’snowturnto“boltin”assemblerroutines.Theterm“bolt-in”meansthatyoushould,withminimal work,beabletoreplaceanMBasicstatementwiththeassemblercode.Inessence,youunbolttheMBasic codeandboltintheassemblercode.Ofcourse,someadjustmentsmaybenecessary,andyoumustverifythe result. Toverifytheoperationofthecode,andthespeedtiming,we’lluseProgram14-4asthetemplate. ;Program14-4template Stack=10 ;Constants ;---------;For20MHzclock,Fosc/4=5MHz ;sothereare5ticks/usecor0.2uspertick usPerTick fCon 0.2 ;howmanyclockticksforzerofunction Latency Con4 ACon BCon CCon
Con Con Con
2 8 16
;Variables ;---------;holdsthetimervalue t2 Var Word Extime Var Float AByte BByte CByte
Var Var Var
Byte Byte Byte
AWord BWord CWord
Var Var Var
Word Word Word
;Initialization ;-------------;noprescaler SetTmr1Tmr1Int1 tmr1on=1 EnableHSerial SetHSerialH115200 Main
;starttimer(T1CON,bit0[Bank0]1=on0=off)
@CallStartTime @CallStopTime HSerOut[“Null”,9] GoSubDumpTime Pause1000
GoToMain ASM
296
In-LineAssembler { StartTime bcft1con,0 clrftmr1h clrftmr1l bsft1con,0 Return StopTime bcft1con,0 Return }
;resettimer1to0 ;stoptimer ;clearhighbyte ;clearlowbyte ;turntimeron ;stoptimer1
DumpTime ;------- t2.lowbyte=tmr1l t2.highbyte=tmr1h t2=t2-Latency Extime=usPerTick*(ToFloatt2) HSerOut[RealExTime\2,”us”,13] Pause25 Return End
Thisisourearliertimingprogram,towhichwe’veaddedthreeconstants,threebytevariablesandthree wordvariablestouseinourtestcode. ACon Con BCon Con CCon Con AByte BByte CByte AWord BWord CWord
Var Var Var Var Var Var
2 8 16 Byte Byte Byte Word Word Word
Allexecutiontimedataistakenusinga20MHzresonatorwiththecompileroptimizationswitchsetto “speed.”Thetimesshownareforversion5.3.0.0,withtimesforversion5.2.1.1showninparentheses.Since allvariablesinthetestprogramsareinbank0,theexecutiontimefortheassemblerversiondoesnotinclude bankswitchingtime.I’veensuredthesevariablesareinbank0bylimitingthestacksizeviaaStack=10 compilerdirective.However,forgenerality,I’veincludedbankswitchingcodeinthesamples.Ifrequired, bankswitchingadds0.2µsexecutiontimeforeachswitchoperation,assuminga20MHzresonator. Finally,Iwillshowonlythein-linemacrocodeversionoftheassembleralgorithm.Baseduponwhatyou’ve learnedinthischapter,youshouldbeabletorewritethecodeusingtheASM{…}convention,shouldyouso desire. There’sanotherdifferencebetweenusinganin-linemacroor_@macrocomparedwithusingpureassembler insideanASM{…}construction.UsingpureassemblerinsideASM{…}permitstheassemblertoinserta defaultvalueformissingdestinationparameters.Ifyouforgettoaddthedestinationparameterinthecorrespondingmacro,youwillreceiveanerrormessage.Thisisactuallyabenefit,asthedefaultdestination assignedbytheassemblermaynotbetheoneyouintended. MBasicsetsthedefaultradixforassemblerliteralsasdecimal.However,itisnotgoodpracticetorelyupon defaultradixsettings,andyoushouldalwaysexplicitlyidentifyanyliteralsyouuse,forexample: • .123fordecimal • 0x123forhexadecimal • b’010101010’forbinary
297
Chapter14 MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AByte=0
36.0(38.2)
0.2
Restrictions:Bytevariable Program14-100
Weusetheclrfoperationtosetallbitsofthevariabletozero. Main ;MBasic ;--------------- AByte=99 @CallStartTime AByte=0 @CallStopTime HSerOut[DecAByte,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- AByte=99 @CallStartTime @Bank0,AByte clrfAByte @BankAByte,0 @CallStopTime HSerOut[DecAByte,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AWord=0
37.6(38.8)
0.4
Restrictions:Wordvariable Program14-101
Weusetheclrfoperationtosetallbitsofthevariabletozero.Sincethevariableistypeword,wemust separatelyclearboththelowbyte(ataddressAWord)andthehighbyte(ataddressAWord+1). Main ;MBasic ;--------------- AWord=9999 @CallStartTime AWord=0 @CallStopTime HSerOut[DecAWord,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- AWord=9999 @CallStartTime @Bank0,AWord clrfAWord clrfAWord+1 @BankAWord,0 @CallStopTime HSerOut[DecAWord,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain
298
In-LineAssembler MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AByte=Constant
38.8(40.8)
0.4
Restrictions:Bytevariable Program14-102
Loadingaconstanttoavariablerequiresatwo-stepmove.First,copytheconstantintoWandsecond,copy thevalueofWtotheregisterfile.Thesamplecodeshowsanamedconstant,butaliteralmaybedirectly substituted—thatis,movlw.123. Main ;MBasic ;--------------- @CallStartTime AByte=CCon @CallStopTime HSerOut[DecAByte,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- @CallStartTime @Bank0,AByte movlw CCon movwfAByte @BankAByte,0 @CallStopTime HSerOut[DecAByte,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AWord=Constant
40.4(45.0)
0.8
Restrictions:Wordvariable—maybeusedonlyinsideASM{...}construction Program14-103
Loadingaconstantintoawordvariablerequiresustoapplythetechniqueusedtoloadaconstantintoabyte variable,buttoapplyittwice,oncetothelowbyteandoncetothehighbyte.Itis,ofcourse,necessarytocopy thelowbyteoftheconstanttothelowbyteofthevariableandthehighbyteoftheconstanttothehighbyteof thevariable.Wemayusetheassemblerfunctionhighandlowtoselectthehighandlowbytesoftheconstant. Thecodealsoworksifaliteral,suchas.1234isusedinsteadofadefinedconstantsuchasCCcon. ThisprogramusestheASM{…}construction,necessarybecauseMBasicdoesnotdefinein-linemacrosfor theassemblermathematicaloperationshighandlow,asthesekeywordsarealreadyusedforotherfunctions.Hence,thein-lineversionofthiscodefailsandshouldnotbeused. Main
;MBasic ;---------------@CallStartTime AWord=CCon @CallStopTime HSerOut[DecAWord,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;----------------------AWord=1111 @CallStartTime
299
Chapter14
@Bank0,AWord ASM { movlwLowCCon _@movwfAWord movlwHighCCon _@movwfAWord+1 } @BankAWord,0 @CallStopTime HSerOut[DecAWord,9,”Assembler”,9] GoSubDumpTime Pause1000
GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AByte=Abyte+1
90.0(97.0)
0.2
Restrictions:Bytevariable Program14-104
Incrementingabytevariableisataskdirectlysuitedtotheincfoperator.Don’tforgetthattheresultofthe incrementshouldbestoredbackinthevariable,sothedestinationshouldbe‘f’.Thedemonstrationprogram 14-104alsosetsAByteandBbyteto0intheinitializationstage,andseparatelyincrementsbothvariables, tomakethedemonstrationclearer. Main ;MBasic ;--------------- @CallStartTime BByte=BByte+1 @CallStopTime HSerOut[DecBByte,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- @CallStartTime @Bank0,AByte incfAByte,f @BankAByte,0 @CallStopTime HSerOut[DecAByte,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AWord=AWord+1
93.0(100.0)
0.6
Restrictions:Wordvariable Program14-105
Toincrementawordvariable,weincrementitslowbyteandtesttheStatusbittoseeifthelowbyte iszero.Ifitis,itmeansthelowbytehasrolledoverfrom255to000andhencethehighbytemustbeincremented.Thetestconditionisimplementedinabtfsctest;ifZisclear(norollover)skipincrementingthe highbyte.IfZisset(rollover)thenincrementthehighbyte.WeneednotchangebankswhentestingZasthe Statusregisterisreachablefromallfourbanks.
300
In-LineAssembler (Ifdesired,thissequencecanbeextendedfora4-bytetypelongvariable.) Main ;MBasic ;--------------- @CallStartTime BWord=BWord+1 @CallStopTime HSerOut[DecBWord,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- @CallStartTime @Bank0,AWord incfAWord,f btfscStatus,Z incfAWord+1,f @BankAWord,0 @CallStopTime HSerOut[DecAWord,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AByte=AByte–1
94.4(101.2)
0.2
Restrictions:Bytevariable Program14-106
Decrementingabytevariableisataskdirectlysuitedtothedecfoperator.Don’tforgetthattheresultofthe decrementshouldbestoredbackinthevariable,sothedestinationshouldbe‘f’. Main ;MBasic ;--------------- @CallStartTime BByte=BByte-1 @CallStopTime HSerOut[DecBByte,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- @CallStartTime @Bank0,AByte decfAByte,f @BankAByte,0 @CallStopTime HSerOut[DecAByte,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AWord=AWord–1
96.4(104.2)
0.8
Restrictions:Wordvariable Program14-107
301
Chapter14 Todecrementawordvariable,weusethesameprincipleofdecrementingthelowbyteandhighbyteseparately,buttheorderofdecrementsiscritical.Beforedecrementing,wetestthelowbytebycopyingitback toitselfusingthemovfoperator,withthedestinationsetto‘f.’ThisoperationsetstheStatusbitif thelowbyteiszero.WetestforZwiththebtfscoperatorandifZisset(lowbyteiszero)wedecrement thehighbyte.Ifnot,weskipthehighbytedecrement.Then,regardlessofwhetherwehavedecrementedthe highbyteornot,wedecrementthelowbyte.Decrementsusethedecfcommand,withadestinationof‘f’to placetheresultbackinthevariable. Main ;MBasic ;--------------- @CallStartTime BWord=BWord-1 @CallStopTime HSerOut[DecBWord,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- @CallStartTime @Bank0,AWord movfAWord,f btfscStatus,Z decfAWord+1,f decfAWord,f @BankAWord,0 @CallStopTime HSerOut[DecAWord,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AByte=BByte+CByte
98.0(105.4)
0.8
Restrictions:Bytevariable Program14-108
FormingthesumAByte=BByte+CByteinassemblermaybeaccomplishedinfoursteps: 1. CopyBByte’svaluetoW; 2. CopyWtoAByte(atthispoint,AByte=BByte); 3. CopyCBytetoW; 4. AddWtoAByteandstoreresultinAByte(atthispointAByte=AByte+CByte). Theadditionfunctioninstep4usestheaddwfopcode.Notethatsinceweusethreeregisterfiles,wemust ensurethat,ifnecessary,thecorrectbankbitsaresetbeforeeachreadorwrite. IfthedesiredoperationisAByte=AByte+CByte,onlysteps3and4needbeused. Main
;MBasic ;---------------@CallStartTime AByte=BByte+CByte @CallStopTime HSerOut[DecAByte,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;-----------------------
302
In-LineAssembler AByte=0 @CallStartTime @Bank0,BByte movfBByte,w @BankBByte,AByte movwfAByte @BankAByte,CByte movfCByte,w @BankCByte,AByte addwfAByte,f @BankAByte,0 @CallStopTime HSerOut[DecAByte,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AWord=BWord+CWord
102.4(109.8)
2.00
Restrictions:Wordvariable Program14-109
FormingthesumAWord=BWord+CWordinassemblermaybeaccomplishedinninesteps: 1. CopyBWordlowbytetoW; 2. CopyWtoAWordlowbyte(atthispointAWord.LowByte=BWord.LowByte); 3. CopyBWordhighbytetoW; 4. CopyWtoAWordhighbyte(atthispointAWord=BWord); 5. CopyCwordhighbytetoW; 6. AddWtoAWordhighbyte,savingresultinAWordhighbyte; 7. CopyCwordlowbytetoW; 8. AddWtoAWordlowbyte,savingresultinAWordlowbyte; 9. Iftheresultofstep8isacarry,incrementAWordhighbyte. Weusetheaddwfoperatortoperformtheadditioninsteps6and8,andtestthecarrybit,Status,in step9usingabtfsctest.Ifthecarrybitisset,incrementAWordhighbytewiththeincfoperation;ifitis clearskiptheincrement.Byperformingtheadditioninhigh-byte-firstorder,ourcodeissomewhatsimplified.Eachtimewereadorwritetheregisterfiles,wemustconsiderthebankstatus,sothiscodemakes frequentuseofthe@bankmacro. Remember,inassemblerawordvariablehasitslowbyteatthebaseaddressanditshighbyteatitsbase address+1. Main
;MBasic ;---------------@CallStartTime AWord=BWord+CWord @CallStopTime HSerOut[DecAWord,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;----------------------AWord=0 @CallStartTime @Bank0,BWord movfBWord,w @BankBWord,AWord movwfAWord
303
Chapter14
@BankAWord+1,BWord+1 movfBWord+1,w @BankBWord+1,AWord+1 movwfAWord+1 @bankAWord+1,CWord+1 movfCWord+1,w @bankCWord+1,AWord+1 addwfAWord+1,f
@BankAWord+1,CWord movfCWord,w @BankCWord,AWord addwfAWord,f btfscStatus,C incfAWord+1,f @BankAWord+1,0 @CallStopTime HSerOut[DecAWord,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AByte=AByte–Constant
93.4(101.2)
0.4
Restrictions:Bytevariable Program14-110
Tosubtractaconstantfromabytevariable,weusethesubwfoperation.Thisrequiresatwostepprocess: 1. CopythesubtrahendtoWusingthemovlwopcode; 2. SubtractWfromregisterfileAByteusingthesubwfoperation,savingtheresultinfileAByte. Ifyouwishtosubtractanumber,suchas123,directlyinsteadofusingadefinedconstant,thelinemovlw CConisreplacedbymovlw.123. Main ;MBasic ;--------------- AByte=222 @CallStartTime AByte=AByte-CCon @CallStopTime HSerOut[DecAByte,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- AByte=222 @CallStartTime movlwCCon @Bank0,AByte subwfAByte,f @BankAByte,0 @CallStopTime HSerOut[DecAByte,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain
304
In-LineAssembler MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
AWord=AWord–Constant
81.8(104.2)
0.8
Restrictions:Wordvariable Program14-111
Tosubtractaconstantfromawordvariable,weapplythesubwfoperatortoboththehighandlowbytesand adjustforacarry,ifnecessary.Thisrequiressixsteps: 1. CopythehighbyteoftheconstantintoW; 2. SubtractW(highbyteofconstant)fromAWordhighbyte,savingtheresultinAWordhighbyte; 3. CopythelowbyteoftheconstantintoW; 4. SubtractW(lowbyteofconstant)fromAWordlowbyte,savingtheresultinAWordlowbyte; 5. Iftheresultofstep4setsthecarryflag,Status,thendecrementAWordhighbyte. Ifyouwishtosubtractanumber,suchas(decimal)123,directlyinsteadofusingadefinedconstant,the linemovlwHighCConisreplacedbymovlwHigh.123andthelinemovlwLowCConisreplacedby movlwLow.123. Aswithsubtractionofvariables,weproceedinthehigh-byte-firstordertosimplifythecarrytest. Main ;MBasic ;--------------- AWord=2222 @CallStartTime AWord=AWord-CCon @CallStopTime HSerOut[DecAWord,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- AWord=2222 @CallStartTime ASM { _@movlwHighCCon _@Bank0,AWord _@subwfAWord+1,f _@movlwLowCCon _@subwfAWord,f _@btfssStatus,C _@decfAWord+1,f _@BankAWord,0 } @CallStopTime HSerOut[DecAWord,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
SwapAByteandBByte
81.8(65.6)
0.8
Restrictions:Bytevariable Program14-112
It’soccasionallynecessarytoswaptwovariables.MBasichasaspecialfunctionSwaptoperformthistask. Toavoidusinganintermediatestorageregisterfile,weuseanarithmetictrickfromReference[14-5]requiringfoursteps: 305
Chapter14 1. CopyABytetoW; 2. SubtractWfromBByte,storeresultinW.(W=BByte–AByte); 3. AddABytetoW,storetheresultinAByte.(AByte=AByte+(BByte–AByte),orAByte= BByte); 4. SubtractWfromBByteandstoretheresultinBByte.(BByte=BByte–(BByte–AByte),or BByte=BByte–BByte+AByte,soBByte=AByte). ThisalgorithmrequiresonlyfourFosc/4clockperiodstocomplete,andisthusfasterthantheusual approachtoswappingavariablewithoutusinganintermediatevariable,usingthreeconsecutiveXORoperations,whichrequiressixclockperiods:
movfBByte,w xorwfAByte,f movfAByte,w xorwfBByte,f movfBByte,w xorwfAByte,f
ThepreviousXORexampleomitsbankselection. Main ;MBasic ;--------------- AByte=ACon BByte=BCon @CallStartTime SwapAByte,BByte @CallStopTime HSerOut[DecAByte,9,DecBByte,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- @CallStartTime @Bank0,AByte movfAByte,w @BankAByte,BByte subwfBByte,w @BankBByte,AByte addwfAByte,f @BankAByte,BByte subwfBByte,f @BankBByte,0 @CallStopTime HSerOut[DecAByte,9,DecBByte,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
Remainder(Special)
266.8(277.8)
0.8
Restrictions:Bytevariable;Divisorisofform2N Program14-113
Theremainderoperation,//inMBasic,maybeeasilyimplementedwithamaskingoperationwherethe divisorisapowerof2;forexample,2,4…128.WemaskoffallhigherorderbitswithanappropriateAND mask,(2N–1).Forexample,supposethedivisoris32,soN=5.Themaskis32–1,or31.Weseehowthis worksbyexamining31inbinary:%00011111;soitmasksoffthethreehighbits.Thisisthefunctional equivalentoftheremainderafterdividingby32.
306
In-LineAssembler Theremainderfunctionisoftenusedtokeepavariablewithinacertainrange.Examplesofthiscanbeseenin Program19-1and19-2,whereaFori=0to63…Nextloophastwoinnerthatvariablesmustcyclefrom 0…31withintheouterloop.Thesesub-loopvariables,kandnareeasilyobtained,forexample,k=i//32. TocomputeCByte=AByte//DivisorwhereDivisorhastheform2N,thealgorithmhasthreesteps: 1. Copythedividend(AByte)toW; 2. ANDWwiththedivisorminus1(2N–1); 3. CopyW(whichholdstheremainder)toCByte. Theexampleusesadivisorof32(25)and25–1is31. Main ForAByte=0to255 ;MBasic ;--------------- @CallStartTime BByte=AByte//32 @CallStopTime HSerOut[DecBByte,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- @CallStartTime @Bank0,AByte movfAByte,w andlw(.32-.1) @bankAByte,CByte movwfCByte @BankCByte,0 @CallStopTime HSerOut[DecCByte,9,”Assembler”,9] GoSubDumpTime Pause1000 Next GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
Division(Special)
266.8(277.8)
6.2*
Restrictions:Bytevariable;Divisorisofform2 *=timefor/16;otherdivisorswillbedifferent RequiresauxiliarybytevariableTemp Program14-114 N
Ifthedivisorisoftheform2N,wemayperformdivisionbyshiftingrightNbits.Sincetheassemblerrotate operationshiftsthroughcarry,wemustzerooutthecarrybit. TheoperationtobeduplicatedinassemblerisCByte=AByte/16.Thesimplicityofthealgorithmis maskedbythecomplexityintroducedindealingwithbankselection: 1. Thedivisormustbeoftheform2N.Sincethedivisorintheexampleis16,N=4.CopyNintoa temporarybytevariableTemp.ThisisdonebyamovlwopcodetogetNintoWfollowedbyamovf operationtocopyNintothefileTemp. 2. CopyAByteintoCByte,usingthetwo-stepcopyprocess;copyABytetoWandthencopyWto CByte. 3. ShiftCByteonebittotherightwiththeRRFoperator.Thisrotationputsthebit0intothecarrybit, Status. 4. ClearthecarrybitStatustoconverttherotationintoashiftandlossoperation. 307
Chapter14 5. DecrementTemp. 6. TestTemptoseeifitiszero,indicatingwehavecompletedNsteps.IfTempisnotzero,gotoStep 3.Weusethedecfszoperatortocombinesteps5andthetestpartofStep6intooneoperation. BecausewecannotbesurethatTempandCByteareinthesamebank,wemustmakeanauxiliaryjump toFixUp,whereweaddbankselectioncode.Afterthebankselectioniscompleted,wegobacktoShift (Step3intheabovedescription). SinceGoToisanMBasicfunction,thein-linemacrofortheassembleropcodeGoTois@GoTo. Weuse“short”GoTocallshere,whichmeansthatallcode(includingtheassociatedMBasiccode)mustbe withinthesame2Kprogrampage.Callsoutsidethecurrentprogrampageareanadvancedtopicandwillnot beconsideredinthisbook. Main ForAByte=0to255 ;MBasic ;--------------- @CallStartTime BByte=AByte/16 @CallStopTime HSerOut[DecBByte,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- @CallStartTime movlw 0x4 movwf Temp&0x7F ;temp=4 @Bank 0,AByte movf AByte,w @Bank AByte,CByte movwf CByte Shift RRF CByte,f;/2butthisisrotate,notshift bcf STATUS,C ;clearthecarryflag @bank CByte,Temp decfsz Temp,f ;temp=temp-1 @GoTo FixUp ;whileTemp>0GoToShift @GoTo EndIt FixUp @bank temp,CByte @GoTo Shift EndIt @CallStopTime HSerOut[DecCByte,9,”Assembler”,9] GoSubDumpTime Pause1000 Next GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
Set/ClearPortBit
26.6(31.2)Set 26.6(31.0)Clear
0.2Set 0.2Clear
Restrictions:Bitmustbeaconstant Program14-115
Thebfsandbfcopcodesprovideadirectwaytosetorclearanoutputpin. TheexampleshowsclearingB0(MBasiccommandlowB0).TosetB0(MBasiccommandHighB0) replacethebcfoperationwiththebsffunction.PortsA…EareallinBank0,soiftheportbitsaresetor 308
In-LineAssembler clearedwithoutfurtherassemblercode,the@bankmacrosareunnecessary.Don’tforgettosetthedesired pintooutputmode.ThismaybeconvenientlydoneinMBasic;forexample,OutputB0. Main
;MBasic ;---------------@CallStartTime LowB0 @CallStopTime HSerOut[“MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;----------------------@CallStartTime @Bank0,PortB bcfPortB,0 @BankPortB,0
@CallStopTime HSerOut[“Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
Set/ClearPortBit andSettoOutput
26.6(31.2)Set 26.6(31.0)Clear
0.8Set 0.8Clear
Restrictions:Bitmustbeaconstant Program14-116
Ifyouwishtoalsosettheporttooutputdirectioninassembler,itisnecessarytocleartheassociatedbit intheTRISfileregister.TRISAcorrespondstoPortA,TRISBtoPortB,etc.PortBpin0correspondsto TRISBbit0,etc.SettingthepintoinputrequiressettingtheassociatedTRISbitto%1;settingthepinto outputrequiressettingtheassociatedTRISbitto%0. TosetB0(MBasiccommandHighB0)replacethebcfoperationwiththebsffunction. Thisisacasewherethetwofileregistersweaddressareindifferentbanks,sothebankselectionmacro causescodetobegenerated,accountingfortheextratwoFosc/4cyclesconsumedabovethetimerequired forthetwobcfoperators. Remember,youcan’tuseMBasic’slibrarypinconstants,suchasB0,here.Rather,youmustidentifypinsby digits0…7.(Or,youcanlettheassemblerdothemathforyou;forexample,toreferencepinB6,use(B6B0)asthebitidentifier.Theassemblerwillperformthesubtraction,comingupwiththecorrectnumber.) Main
;MBasic ;---------------@CallStartTime LowB0 @CallStopTime HSerOut[“MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;----------------------@CallStartTime
309
Chapter14
@Bank0,TRISB bcf TRISB,0 @BankTRISB,PortB bcfPortB,0 @BankPortB,0
@CallStopTime HSerOut[“Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
For…NextLoop
164.8(183.2)*
1.4
Restrictions: LoopVariablemustbeabyte Stepis+1or–1 Stepisaconstant *Timestatedisforoneemptyloopiteration Program14-117
We’llstructureasimpleFor…Nextloop,butbynowyoushouldseehowtoextendittousevariablesfor stepandthestart/finishbounds. Theloopexampleimplementsanassemblerversionof:
ForTemp=AContoCCon ;MBasiccodehere Next
Ourassembleralgorithmhasfoursteps: 1. CopyAContoWusingthemovlwoperatorandcopyWtoTempusingthemovfoperator.Theresult isTemp=ACon; 2. InserttheassemblerorMBasiccodethatresideswithintheloop; 3. CopyTemptoWwiththemovfoperatorandsubtractWfromCConusingthesubwfopcode; 4. Iftheresultofstep3iszero(Statusisset)thenwearefinishedandarereadytoexecutethe nextcodesequence.ThisisaccomplishedviaabtfscStatus,Ztest.IfZisset,thenextinstruction,theGoToEndItinstructionexecutesandthecodegoesontothenextsequence.IfZisnotset (Temp<>CCon)incrementTempthroughtheIncfoperator.AfterincrementingTemp,thenGoTo step2. SinceGoToisanMBasicfunction,themacrofortheassembleropcodeGoTois@GoTo. Weuse“short”GoTocallshere,whichmeansthatallcode(includingtheassociatedMBasiccode)mustbe withinthesame2Kprogrampage.Callsoutsidethecurrentprogrampageareanadvancedtopicandwillnot beconsideredinthisbook.
ForTemp=AContoCConStep-1 ;MBasiccodehere Next
Ifwewishtoreversestep—thatis,Step=–1inMBasiccode,replacetheincfTemp,finstructionwith decfTemp,f. Main
;MBasic ;---------------BByte=0 @CallStartTime ForTemp=AContoCCon
310
In-LineAssembler ;MBasiccodehere Next @CallStopTime HSerOut[DecBByte,9,”MBasic”,9] GoSubDumpTime Pause1000 ;AssemblerIn-LineMacro ;---------------------- BByte=0 @CallStartTime movlwACon @Bank0,Temp movwfTemp Loop ;assemblercodehere movf temp,w sublw CCon btfscStatus,Z @GoTo EndIt incf Temp,f @GoTo Loop EndIt @bankTemp,0 @CallStopTime HSerOut[DecBByte,9,”Assembler”,9] GoSubDumpTime Pause1000 GoToMain MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
ByteTable
74.0(76.6)
2.6
Restrictions: Tablesize<256elements Tableonlybyteelements Indexintotablebytevariable Program14-118
Thetwomostcomplicatedassemblermoduleswewillconcernourselveswithinvolveindexingintodataand variables.ThismoduleprovidesafasteralternativetoMBasic’sByteTablefunction,whilealatermodule willshowhowtoreadfromandwritetoanarrayofbytevariables. ThealgorithmweuseisbaseduponReferences[14-4]and[14-7]andimplementsanassemblerequivalent of: AByte=FullStepTable(Temp)
WhereFullStepTableisthefunctionalequivalentofaByteTabledataarray. Let’sconsiderahighlevelviewofhowourassemblercodeworks: 1. Thetableentrynumber(0…7inoursampletable)isinthebytevariableTemp.Thedatatableitself startsatlabelFullStepTable. 2. EachelementinFullStepTableisaretlwoperator,followedbyaliteral,theelementvaluecorrespondingwiththatoffsetintothetable.Theretlwoperatorexecutesareturnfromcallwithits literalargumentloadedintoW. 3. TheactofaccessingthetablecanbethoughtofasacomputedGoTo.Acalloperatorresultsin programexecutionjumpingtotheprogramcodeatpositionFullStepTable+Temp.TheopcodeatFullStepTable+Tempisaretlwoperatorthatcausesprogramexecutiontojumpback tothestatementimmediatelyfollowingtheCalloperation.
311
Chapter14 Inturningthishighleveldescriptionintofunctioningcode,wehavetodealwithacoupleofPICarchitecturalissues: • AswelearnedinChapter13,theprogramcounterinthe16F87x/87xAdevicesis13bitswideand wehavedirectaccessonlytotheprogramcounter’slow8-bits,containedinthePCLregister.SupposethattheaddressofthedatatableissuchthatthePCLregister’svalueis.250andthatweare indexing10positionsintothetable.TherequiredPCLaddressis.250+.10=.260.However,since thePCLisonlyan8-bitregister,theresult,.260,overflowsandwrapsaroundtogiveanincorrect result. • AswealsolearnedinChapter13,CallandGoToinstructionsonlyuse11addressbits,andhence arerestrictedto2Kpageboundaries.Supposethedatatableisinadifferentpage?Ifso,wemust incrementordecrementthepagecounteraccordingly. Thesamplecodeprovidedtakescareofbothofthesearchitecturalissues. I’mnotgoingtoprovideadetailedline-by-lineanalysisofthiscode.Ifyouareinterestedinlearningmore abouthowitworks,consultReferences[14-4]and[14-7]. Tomodifythiscodeforyourownuse,change: • thetablename(FullStepTable) • theindexvariable(Temp) • thevariablethereturnedtablevalueisplacedin(AByte) Therestofthecodecanremainasshown.Onefinalnote—becauseweusethehighandlowassembleroperators,thatpartofthecallingcodemustbecontainedinanASM{…}structure.Forconsistency,I’mplaced theentirecallingcodesequenceinanASM{…}structure.ThetableitselfmayeitherresideinsideanASM {…}construction,oryoumayusein-linecode. ACon CCon
Con Con
0 7
BTableByteTable$C,$6,$3,$9,$C,$6,$3,$9 Main
;MBasic ;---------------BByte=0 ForTemp=AContoCCon @CallStartTime AByte=BTable(Temp) @CallStopTime HSerOut[DecAByte,9,”MBasic”,9] GoSubDumpTime Pause1000 Next ;AssemblerIn-LineMacro ;----------------------BByte=0 ForTemp=AContoCCon @CallStartTime ASM { _@movlwHIGHFullStepTable _@movwfPCLATH _@movlwLOW(FullStepTable+1) _@bank0,Temp _@addwfTemp,w _@btfscSTATUS,C _@incf PCLATH,f _@call FullStepTable
312
In-LineAssembler _@bank Temp,AByte _@movwfAByte _@bankAByte,0 } @CallStopTime HSerOut[DecAByte,9,”Assembler”,9] GoSubDumpTime Pause1000 Next GoToMain FullStepTable movwfPCL retlw0xc retlw0x6 retlw0x3 retlw0x9 retlw0xc retlw0x6 retlw0x3 retlw0x9 MBasicCode
MBasicTime(µs)
AssemblerTime(µs)
ByteVariableArray ReadandWrite
82.8(87.4)(Read) 82.8(87.4)(Write)
2.0(Read) 2.0(Write)
Restrictions: Arrayofbytes Arraycannotspanbanks Program14-119-A(Read),14-119B(Write)
Ourfinalmoduleshowshowtoreadfromandwritetoanarrayofbytevariables.Aswiththetableread, we’llconfineourdescriptiontoarelativelyhighlevelanalysis. Arrayaccessinvolvesindirectmemoryaddressing—insteadofaddressingaregisterfilewithaspecific address,theregisterfiletobeaddressedisdefinedascomputedlocation.Thisis,ofcourse,exactlyhowan arrayvariableisaddressed;thearrayindexistheoffsetintothearray.Supposewedefineanarrayofbytes ByteArray.TheregisterfilepointedtobyByteArray(N)hasanaddressofByteArray(0)’saddress plusN.Infact,inMBasicwecanreferencethebaseaddressByteArray(0)simplyasByteArray.(This discussionassumesthatthearraydoesnotspanregisterbanks;MBasicsupportsmultibankarrays,butour assemblercodedoesnot.) MidrangePICshavetwospecialfeaturestofacilitateindirectmemoryaddressing,theindirectfileregister, orindf,registerandthefileselectionregisterorFSR.Theindfregisterhasanaddressof$0,$80,$100 and$180soitmaybereachedwithanaddressof0,regardlessofthebankselectionbits.Theindfregister isafictitiousregister;writingtoindfactuallywritestoarealregisterattheaddresscorrespondingtothe valueinFSR.Likewise,readingfromindfactuallyreadsfromtherealregisterattheaddresscorresponding tothevalueinFSR. Wemustpayattentiontothemid-rangePICarchitecture.FSRisan8-bitregister,sothispermitsustoaccess memoryaddressesintherange0…255,thatis,banks0and1inthe16F98x/87xAdevices.The9thaddress bit,necessarytoaddressallfourbanks,isheldinStatus<7>,namedtheIRPbit.IftheIRPbitis0,we mayaddressbanks0and1;ittheIRPbitis1,weaddressbanks2and3.Thebankingbitsetting,heldin RP1:RP0doesnotapplywhenusingindirectaddressingthroughtheFSR/indfprocess.
313
Chapter14 AssumingourbytearrayisByteArray,andthattheindexvariableintoByteArrayisTemp,(accessesare thusviatheequivalentofByteArray(Temp))ourstrategyforindirectlyaddressingmemoryis: 1. Loadthestartingaddress(ByteArray)intoWviaamovlwoperation.ByteArrayisa16-bit variable,sinceitisintheformofanMBasiccompiler-compatiblevariableaddress.Themovlw operationonlycopiesthelower8bits,whichisexactlyourdesire. 2. Addtheoffset(Temp)toWwithanaddwfoperation,savingtheresultinW.ThencopyWtoFSRvia amovwfoperator.Atthispoint,FSRholdsthe8-bitaddressofthesubjectregisterfile. 3. ToputtheIRPbitintoaknownstate,weclearitwithabcfStatus,IRPoperation. 4. TodetermineifByteArrayisinbanks2or3,weneedtodetermineifthe9thbitofByteArray’s 16-bitMBasiccompiler-compatibleaddressissetorclear.Thisweaccomplishbyloadingthehigh byteofByteArrayintoWusingthemovlwHIGHByteArrayoperation,usingtheassemblerto handlethehighbyteconversion.Aswe’veseenearlier,thekeywordconflictbetweentheassembler operatorHIGHandMBasic’sHighfunctionrequirethispartofthecodetobewithinanASM{…} segment.AfterloadingthehighbyteofByteArray’s16-bitaddressintoW,the9thbitisnowW bit0.WetestWbit0byalogicalANDofWand%00000001tomaskoffallbutbit0.Iftheresult iszero,the9thbitiszeroandStatusisset.Iftheresultis%1,Statusisnotset.This permitsustotestforbit9=0withabtfssStatustest,immediatelyfollowedbyabsf Status,IRPoperationtosettheIRPbittoreflectbanks2and3.IfZisset,thebsfStatus, IRPoperationisskippedandIRPremainscleared.IfZisclear(bit9=1),thebsfStatus,IRP executesandthebank2/3bitisset. 5. WenoweitherwritetoINDForreadfromINDF,asINDFiscorrectlypointingtotheregisterfile addressByteArray+Temp. Thisalgorithmrequiresthearraytobecompletelycontainedwithinonebank,aswedonotcheckfordiscontinuousaddressing.Forbothreadandwritedemonstrationprograms,wemakethefollowingchangesto ourtemplateprogram: • Modifytheconstantdefinitions:
ACon CCon
Con Con
•
Defineanewbytearray:
0 7
ByteArrayVar
•
Initializethebytearraytoholdsomearbitraryvalues:
Byte(CCon)
ForTemp=0toCCon ByteArray(Temp)=Temp+10 Next
Thecodeforreadingfromthebytearray(AByte=ByteArray(Temp): Main
;MBasic ;---------------BByte=0 ForTemp=AContoCCon @CallStartTime AByte=ByteArray(Temp) @CallStopTime HSerOut[DecTemp,9,DecAByte,9,”MBasic”,9] GoSubDumpTime Pause1000 Next
314
In-LineAssembler
;AssemblerIn-LineMacro ;-----------------------
ForTemp=AContoCCon @CallStartTime @Bank 0,ByteArray movlw ByteArray @Bank ByteArray,Temp addwf Temp,0 movwf FSR bcf Status,IRP ASM{ movlw HIGHByteArray} andlw0x1 btfss Status,Z bsf Status,IRP @Bank ByteArray,AByte movf INDF,0 movwf AByte @Bank AByte,0 @CallStopTime HSerOut[DecTemp,9,DecAByte,9,”Assembler”,9] GoSubDumpTime Pause1000 Next GoToMain
Thecodeforwritingtothebyearray(ByteArray(Temp)=AByte): Main
;MBasic ;---------------BByte=0 ForTemp=AContoCCon AByte=Temp+20 @CallStartTime ByteArray(Temp)=AByte @CallStopTime HSerOut[DecTemp,9,DecByteArray(Temp),9,”MBasic”,9] GoSubDumpTime Pause1000 Next ;AssemblerIn-LineMacro ;-----------------------
ForTemp=AContoCCon AByte=Temp+30 @CallStartTime @Bank 0,ByteArray movlw ByteArray @Bank ByteArray,Temp addwf Temp,w movwf FSR bcf Status,IRP ASM{ movlw HIGHByteArray} andlw0x1 btfss Status,Z bsf Status,IRP @Bank ByteArray,AByte movf AByte,w movwf INDF @Bank AByte,0 @CallStopTime HSerOut[DecTemp,9,| DecByteArray(Temp),9,”Assembler”,9] GoSubDumpTime Pause1000 Next GoToMain
315
Chapter14
References [14-1]
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,inalmostmind-numbingdetail,butnonethelessisanessentialreferencetoacomplete understandingofPICs.ForindividualPICfamilymemberdatasheets,theeasiestsourceistogoto http://www.microchip.com/1010/pline/picmicro/index.htmandselecteitherthePIC12orPIC16group andfromthatlinkthenselecttheindividualPICdevice. [14-2] Benson,David,EasyPIC’nABeginnersGuidetoUsingPICMicrocontrollersversion3.1,Square1 Electronics,Kelseyville,CA(1999). [14-3] Benson,David,PIC’nUpthePacePICMicrocontrollerApplicationsGuideversion1.1,Square1Electronics,Kelseyville,CA(1999). [14-4] Predko,Myke,ProgrammingandCustomizingPICmicroMicrocontrollers,SecondEd.,McGrawHill, NewYork(2002). [14-5] Predko,Myke,PICMicroMicrocontrollerPocketReference,McGrawHill,NewYork(2001). [14-6] MicrochipTechnology,Inc.,MPASMUser’sGuidewithMPLinkandMPLib.Availablefordownloadat Microchip’swebsite,http://www.microchip.comunderDevelopmentTools,MPLAB.MPLABisalarge programthatcontains,amongotherthings,MPASManditsdocumentation.MPASMiscurrentlyinversion6.x,andalthoughversion3istheoneusedinMBasicpriortov.5.3.0.0,thecurrentMPASMUser’s Guidewillbeofimportancetoyouinlearningtoprograminassembler.GPASM,usedbeginningwith MBasicv.5.3.0.0.AguidetoGPASMmaybedownloadedat:http://gputils.sourceforge.net/gputils.pdf. SinceGPASMisbroadlycompatiblewithMPASM,MPASMdocumentationisusefulaswell. [14-7] D’Souza,Stan,ImplementingaTableRead,AN556,MicrochipTechnologies,Inc.,Doc.No.DS00556E (2000).
316
15
CHAPTER
InterruptHandlers andTimersinAssembler WeseenhowtimersandinterruptsworkinMBasic(Chapter10)andlearnedabitaboutassemblerprogramming(Chapter13)andhowtomixassemblerwithMBasic(Chapter14).It’stimenowtofusethese threestrandsintoone—writinganassemblerinterruptserviceroutine.We’llseethattheassemblerISRhas severaladvantagesoveritsMBasiccousin;perhapsmostimportantly,itsolvesthelatencyproblemswe observedinChapter10.Itsprimarydisadvantageisthatitmustbewrittensolelyinassembler.That’snotto saythattheassemblerISRcan’tcommunicatewiththerestoftheMBasicprogram—becausewe’llseehow todoexactlythat—butitdoesmeanthatwecan’tseamlessalternatein-lineassemblerandMBasiccode insidetheISR,aswewereabletoinChapter14. Chapter10offersthefollowingdefinitionofaninterrupt: Aninterruptisaneventthatcausesthecurrentprogramsequencetotemporarilyhalt,andfordifferent code,calledan“interruptserviceroutine”orISR,tobeexecuted.WhentheISRiscompleted,programflow returnstothepointitwasatbeforetheinterruptoccurred.YoumightthinkofanISRasasubroutinethat iscallednotbysoftware,butratheranevent.Theeventmaybeanexternal,suchasaninputpinchangingstatefroma0toa1,orviceversa.Or,theeventmaybeinternaltothePIC,suchasatimerreaching adefinedcount.Itmayevenbeacombinationofexternalandinternalevents,suchaswhererepeated externalsignalscauseaninternalcountertoreachapresetvalue.
ISRASM–MBasic’sGatewaytoAssemblerInterruptServiceRoutines There’sgoodnewsandbadnewsaboutwritinganassemblerISRinMBasic.ThegoodnewsisthatMBasic includesapowerfulaidtowritinganassemblerISR—theISRASMfunction.ThebadnewsisthatISRASMis undocumentedintheMBasicUser’sGuide.BeforewedelveintotheISRASMfunction,however,let’sstep backandlookathowaPICdealswithaninterrupt.And,sincewemustdealwithinterruptsinassembler, we’llneedtoexaminesomedetailsthatMBasic’sOnInterruptprocedureautomaticallyhandlesforusand thereforeweomittedfromChapter10. We’llbaseourdiscussionuponPICsofthe16F87x/87xAseries.OtherPICsmaynotimplementallthe interruptswediscussormayimplementothers.AllmidrangePICs,however,followthesameinterruptprocess,sowhatyoulearnherewillbedirectlytransferabletoothermidrangedevices.Whenprogrammingin assembler,readMicrochip’sMidrangeReferenceManualandthespecificdatasheetforthedeviceyouwill beusing.Itmayseemimpenetrablethefirsttimeyoureadit,butdon’tgiveup.Youcandoagreatdealwith MBasicwithouteveropeningMicrochip’sdocuments;thatisnotthecasewhenwestartdealingdirectly withthePIC’shardwareandinternalfirmwareinanISRASMprocedure. Chapter10developedafive-elementtemplateforMBasicinterrupthandling.We’llrecastthattemplatefor ourassembly-basedISR: 1. Setupanyoptionsfortheinterrupt,suchastimerpreselectors,timersourcesignals,directionofinput change,andsoforth. 317
Chapter15 2. Cleartheinterruptflag.(Theinterruptflagsareclearedaspartofprocessorinitialization,soinmany casesyoucanskipthisstep.) 3. Enable: a. Thespecificinterrupt; b. Enableglobalinterrupts(GIE);and c. Enableperipheralinterrupts(PEIE)ifthespecificinterruptisamemberoftheperipheralinterrupt family 4. WritetheinterruptservicehandlerinsidetheISRASMwrapper.Include: a. Checkthesourceofinterrupttoseeifitistheoneyourcodeexpects.Ifnot,passcodeexecution totheendoftheISRASMwrapper.(Youcan,ofcourse,checkformultipleinterruptsourcesand branchtoappropriatecoderoutinesbasedupontheparticularcallinginterrupt. b. Iftheinterrupttypeisnotself-clearing,cleartheinterruptbitinyourassemblercode. c. Thenaddyourcodetotakewhateveractionsyouwishbasedontheinterrupt. Becausetheyaresocloselyrelated,we’lltreatsteps1,2and3together. Everyinterrupthasonededicatedcontrolbitandonestatusbit,perhapsmoreoftencalleda“statusflag” ratherthanastatusbit.Someinterruptshaveathirdcontrolelement;turningtheunderlyingdeviceonoroff. ControlBit—Thecontrol,or“enable,”bitturnstheinterruptonoroff.Whenthecontrolbitissetto%0,the interruptisdisabled;whenitissetto%1,theinterruptisenabled.Onceenabled,theinterruptremain enableduntilthecontrolbitiscleared. StatusBit—Thestatusbit,or“statusflag,”issetto%1toindicatethattheconditioncausingtheinterrupthas occurred.Theuserisresponsibleforclearingthestatusbitformanyinterrupts. DeviceControl—Someinterrupt-generatinginternalmodules,suchasthetimers,haveathirdcontrolbitto turnthemoduleonoroff.Forcertainmodules,turningthemoduleonsetstheinterruptflag,whetheror nottheinterruptisenabled.We’lldealwithdevicecontrolonlyinthecontextofspecificexamples. Inadditiontothecontrolbitassociatedwitheachinterrupt,someinterruptsaregroupedintotheperipheralinterruptfamilywhichmaybecollectivelydisabledorenabled.Inorderforamemberofthisinterrupt familytofunction,boththePIfamilymustbeenabledandtheparticularinterruptmustbeenabled.Finally, thereisaglobalinterruptenablebitthatmustbesetforanyinterrupttowork. Wherearethesevariouscontrolandstatusbits?Theyareinvariousspecialpurposeregisters,associated withtheinterrupthardwareorsoftware.Thedetailsofhoweachinterruptworks,andhowitiscontrolled, canbefoundinMicrochip’sreferencedocuments.Butlet’ssummarizeall14interruptsfoundinthe16F87x/ 87xAseriesPICs. Control MBasic Identifier ADINT BCLINT CCP2INT
CCP1INT
Description Analog-to-digitalconversionis completed. Buscollisioninterruptenable;not supportedinMBasic Interruptoccurswhenthereisa capture/compare/periodmatch withCCPmodule2 Interruptoccurswhenthereisa capture/compare/periodmatch withCCPmodule2
Status
Peripheral Family?
Register
Bit
Register
Flag
Yes
PIE1
ADIE
PIR1
ADIF*
Yes
PIE2
BCLIE
PIR2
BCLIF*
Yes
PIE2
CCP2IE
PIR2
CCP2IF
Yes
PIE1
CCP1IE
PIR1
CCP1IF
(Continued)
318
InterruptHandlersandTimersinAssembler Control MBasic Identifier
Description
Peripheral Family?
Register
Status Bit
Register
Flag
EEPROMinterrupt;occurswhen EEINT writingtotheon-boardEEPROMis Yes PIE2 EEIE PIR2 EEIF completed. ChangeofinputpinstateonRB0. Mustseparatelysetmodetoselect EXTINT No INTCON INTE INTCON INTF 0→1or1→0transitionforthe triggeringevent Parallelslaveportinterrupt;not None Yes PIE1 PSPIE PIR1 PSPIF* supportedinMBasic AnypinRB4,RB5,RB6orRB7has RBINT changedstate,ineitherthe0→1 No INTCON RBIE INTCON RBIF** or1→0direction. Receivedabytethroughthe hardwareUSART.Note:When Yes PIE1 RCIE PIR1 RCIF* RCINT usingHSERINorHSEROUT functionsRCIFisdisabled. Synchronousserialportinterrupt; SSPINT Yes PIE1 SSPIE PIR1 SSPIF notsupportedinMBasic TMR0INT Timer0overflowhasoccurred No INTCON T0IE INTCON T0IF TMR1INT Timer1overflowhasoccurred Yes PIE1 TMR1IE PIR1 TMR1IF TMR2INT Timer2overflowhasoccurred Yes PIE1 TMR2IE PIR1 TMR2IF Finishedtransmittingabyte fromthehardwareUSART.Note: TXINT Yes PIE1 TXIE PIR1 TXIF* WhenusingHSERINorHSEROUT functionsRCIFisdisabled. *IndicatesaflagthatisautomaticallyclearedbythePIC;allotherflagsrequiresoftwareclearingintheinterruptserviceroutine. **InadditiontoclearingtheRBIFflaginsoftware,youmustreadthePortBregistertoreloadtheinternalcomparisonlatch.
Afterreadingthistable,youshouldseeseveralpatterns: • Theenableandinterruptflagbitsshareacommonnamingsystem,withtheenablebitacronymending in“E”forenablewhiletheinterruptflagbitendsinan“F”forflag. • Onlytheoldestinterrupts(oldestinthesensethattheyhavebeeninthePICarchitecturesincetheearliestPICsweredesigned)havetheirenableandflagbitsintheinterruptcontrolregister,INTCON. • Interruptsassociatedwith“newer”featuresareallmembersoftheperipheralinterruptfamilyandhave theirenablebitsintwoperipheralinterruptenable(PIE)registers,PIE1andPIE2.Theircorresponding flagbitsareheldintwoperipheralinterruptregisters(PIR),PIR1andPIR2.Infact,althoughnotseen inthetable,theregisterandbitsequencealignbetweenthePIEandPIRregisters,forexample,PIE1 bit0istheenablebitfortimer1,whilePIR1bit0istheinterruptflagfortimer1. • The7-bitregisteraddressesalignbetweenthePIEandPIRregisters,withthePIRregistersinbank0 andthePIRregistersinbank1.Forexample,PIR1’srelativeaddressis$0C,inbank0,whilePIE1’s relativeaddressis$0Cinbank1. Inaddition,wehavetwohigherlevelinterruptcontrolbits: Function Globalinterruptenablebit—controlsall interrupts Peripheralfamilyinterruptenablebit— controlsallinterruptsthataremembers oftheperipheralfamily
Register
Bit
INTCON
GIE
INTCON
PEIE
319
Chapter15 Wehaveseveralchoicesinhowtoenableanddisableinterruptsandsetanyassociatedoptions: • SetoptionsusingMBasiccommandsexactlyaswelearnedinChapter10—ThisisthesimplestapproachasitencapsulatesthedetailsintoasimpleMBasicprocedureortwo: o SetuptheinterruptusingtheappropriateMBasicsetupfunction,suchasSetExtInt,orSetTmr0, etc.Forexamplewesetuptheexternal(RB0)interrupttotriggeronthe1→0transitionwiththe followingMBasicstatement:
•
SetExtIntExt_H2L
o YoucannotenableordisabletheinterruptusingMBasic’sEnableandDisablefunctions,however.ThesefunctionsworkonlyifyoualsoestablishaninterrupthandlerusingtheOnInterrupt function,whichconflictswithanISRASMroutine.Rather,youmustuseoneofthethreeapproaches discussedbelowtoenableanddisabletheinterrupt. SetorclearthesetupandenablebitsfromMBasic—Allofthecontrolandflagbitidentifiersshownin theinterrupttablearealsolibrarydefinedMBasicbitvariablesandmaybewrittentoorreadfromlike anyothervariable.Theassociatedspecialpurposefileregistersarealsolibrarydefinedbytevariables. Toenabletheexternalinterrupt(RB0)eitherofthefollowingtwoMBasicstatementsmaybeused: Inte=%0 INTCON.Bit4=%0
TodeterminethattheInteflagcorrespondstoIntcon.bit4,youmustconsultthe16F87xor 16F87xAdatasheet.Youmayalsousethisapproachtosetupinterruptoptions.Forexample,thechoice betweenRB0interruptoccurringonthe0→1or1→0directionisdeterminedbythecontrolbitIntEdg, whichisOption_Reg.Bit6.Fromthedatasheet,wedeterminethattriggeringtheinterruptupona 1→0transition(fallingedge)correspondstoIntEdgbeingcleared.ThisgivesusthreewaysinMBasic toconfiguretheexternal(RB0)interrupt: SetExtIntExt_H2L IntEdg=%0 Option_Reg.Bit6=%0
•
Usein-lineassemblertosetorclearenableandsetupbits—Fromthedatasheetforthedeviceyou areusing,identifytherelevantenableandoptioncontrolregistersandbits.Then,setorcleartheseas, appropriate,usingthein-lineassemblermacrosbsfandbcf.Forexample,tosetupandenablethe external(RB0)interrupt,wemayusethefollowingin-linecode(assuming,ofcourse,thatthepriorbank isbank0): @bank0,Option_Reg bcfOption_Reg,6 ;sameasSetExtIntExt_H2L bcfOption_Reg,IntEdg;canusenamedconstIntEdg bsfIntcon,4 bsfIntcon,Inte
•
;enabletheinterrupt ;canusenamedconstantInte
UseASM{…}assemblercodetosetorclearenablebits—Usingthesameapproachasforin-lineassemblercode,weidentifytherelevantenableandoptioncontrolregistersandbits.Wethensetorclearthese, asappropriate,usingassemblertheopcodesbsfandbcf,ortheirmacroversions_@bsfand_@bcf. ASM {
_@bank0,Option_Reg bcfOption_Reg,6 bcfOption_Reg,IntEdg bsfIntcon,4 bsfIntcon,Inte
;sameasSetExtIntExt_H2L ;usenamedconstantinstead ;enabletheinterrupt ;canusednamedconstant
} ASM {
320
InterruptHandlersandTimersinAssembler }
_@bank0,Option_Reg _@bcfOption_Reg,6 _@bcfOption_Reg,IntEdg _@bsfIntcon,4 _@bsfIntcon,Inte
;sameasSetExtIntExt_H2L ;usenamedconstant ;enabletheinterrupt ;usenamedconstant
CheckingthememorymapinChapter13,ortheMicrochipdatasheet,wedeterminethatOption_Regisin bank1,andIntconisduplicatedacrossallfourbanks,soitmaybeaddressedfromanybanksetting.Ifwe chosetowritetoOption_Regwitheitherin-lineassemblermacrosorfromwithinanASM{…}block,we mustensurethattheproperbankbitsareset. I’veshowntwowaystoidentifythebitarguments;bylookingupthebitnumberinMicrochip’sdocumentation,orusingthenamedlibraryconstant:
bsfIntcon,4 bsfIntcon,Inte
;enabletheinterruptbynumber ;or(preferable)usednamedconstant
Bothoftheseassemblerstatementsperformidenticaltasks,butusingthenamedconstant,Inte,makesthe codemorehumanreadable,andispreferredoverthenumericalform.You’llfindthenamedconstantsforall specialpurposeregistersandbitsinMicrochip’sdevice-specificdatasheet.Interruptenableandflagrelated registerandbitnamesalsoappearinthesummarytableearlierinthischapter. Sincetheinterruptflagisclearedatprocessorreset,manuallyclearingtheflagisnotalwaysnecessary,but youmaywishtodoitaspartofinterruptsetupandinitialization.It’sgoodprogrammingpracticetoclearthe associatedinterruptflagforalltheinterruptsyouintendtouse,particularlyiftheinterrupthasbeenrespondingtoinputsduringinitialization,sothatitsflagstatusisunknown. Wehavethesamethreeoptionstocleartheinterruptflag: • FromMBasicusingthelibraryvariableidenticaltotheinterruptflagname.Forexample,toclearthe INTFflagassociatedwiththeINTEinterrupt,wecouldusethefollowingassignment:
INTF=%0
•
Usingin-lineassemblermacros.Wefirstmustdeterminetheaddressandbitnumberoftheflagwewish toclear.Fortheexternal(RB0)interrupt,Microchip’sdatasheetinformsusthattheinterruptflagisat INTCON<1>,orINTCONWecheckINTCON’sbankanddiscoverthatitisaliasedatallfour banks,soweneednotconcernourselveswithbanksetting.Thefollowingbitclearoperationcanbe used:
•
UsetheASM{…}construction,eitherwithassemblermacros,orwithpureassembleropcodes:
Bcf
Intcon,Intf
ASM { _@bcf Intcon,Intf Bcf Intcon,Intf }
;macroversion ;assembleropcodeversion
WhatHappensWhentheInterruptFires? Afterlaboringinthedetailsofspecialpurposeregistersandfiles,let’sstepbackamomentandlookatwhathappenswhenaninterrupteventoccurs.InMBasic,aswelearnedinChapter10,theinterrupthandlerisexecuted atthecompletionoftheMBasicstatementexecutingattheinstanttheinterruptoccurs.Wedemonstratedthe resultinglatencycouldbedozensofmicroseconds,orevenmuchlonger,dependingupontheparticularMBasic statement.Wealsolearnedhowtoassociateaninterrupthandlerwiththesourceoftheinterrupt,sothatthecompilerautomaticallydeterminedthesourceoftheinterruptandroutescontroltotheappropriatehandler. FromtheprospectiveoftheMBasicprogrammer,theassembler-basedISRASMhandlerworksquitedifferently.Whenaninterrupteventoccurs,twothingshappen:
321
Chapter15 • •
Theflagbitassociatedwiththeinterruptisset. Theprocessorstopsexecutingthecurrentcodewithin,atmost,twoFosc/4instructionintervalsand transfersprogramexecutiontowhateverassemblercoderesidesatcodeaddress$0004,thelocation oftheinterruptvector.ThisjumpmayoccurinthemiddleofanMBasicinstruction.Attheendofthe ISRASMroutine,programflowreturnstotheMBasiccodeseamlesslyandwithoutlossofinformation. Regardlessoftheinterruptsource,allinterruptscausethecodeat$0004tobeexecuted.(Somemore complexmicroprocessorsdispatchdifferentinterruptsourcestocodeatdifferentaddresses;notsowiththe mid-rangePIC’swe’reusing,however.)It’suptoyou,theprogrammer,towritecodetodeterminewhich interruptsentexecutiontoyourISRASMroutineandwhattodoiftheinterruptisn’tfromthesourceyou expected.(MBasic,forexample,usestheTXIEandRCIEhardwareserialmoduleinterruptsinsendingand receivingserialdataviaHSerOutandHSerIn.Ifyourprogramusesthesefunctions,yourISRASMcode mustpasstheTXIEandRCIEinterruptsthroughwithoutchange,orelsetheHSerInorHSerOutfunctions mayfailtocorrectlyperform.) Whyislocation$0004calledaninterruptvector?Thetermcomesfromthefactthatuponaninterruptevent occurring,programexecutionjumps,orisvectoredto,theprogramcodeatlocation$0004.Usually,the programcodeatlocation$0004isaGoTostatementthattransfersprogramexecutiontoadifferentmemory locationwheretherealinterruptserviceroutineresides. There’sabitofhousekeepingthatmustoccurinorderforprogramexecutiontoseamlesslyreturntoMBasic processingafterinterruptioninthemiddleofaMBasicstatement.Forexample,wemustsavetheW,Status,PCLathandFSRregistersandthenjumptotheISRASMmodule.UponcompletionoftheISRASM code,wemustrestorethemtothevaluetheyhadbeforetheinterrupt.Theseprocessesareoftencalledcontextsavingandcontextrestorationor,generally,contextswitching.ThegoodnewsisthatMBasic’sISRASM automaticallyperformscontextswitching.Wemayhavetoaccountfortheextradelaycausedbycontext switchingifourinterruptisengagedcriticaltimemeasurementactivity,butbyinlargecontextswitchingis invisibletoyouwhenwritingISRASMcode. Anothertwistthatyoumustconsideriswhathappensifanotherinterruptoccursinthemiddleofyour ISRASMcode?YourISRASMcodeisn’tlikelytobereentrant,soyouwillwishtodisableallinterruptsatthe outsetoftheISRASMcode.Don’tforgettoturnthembackonattheendoftheISRASMcode.
SpecialConsiderationsforISRASMCode Beforewestartlookingatsamplecode,there’sonefinalpointyoushouldbeawareof.Inversionspriorto 5.3.0.0,ISRASMproceduresdonotworkwithMBasic’spre-definedin-linemacros,orassemblermacros. Thisisaby-productoftheMBasic’scompilerorderoflibrarylinkagethatwasmodifiedinversion5.3.0.0. Intheseearlierversions,MBasic’smacrolibraryfollowsISRASMcodeassembly,andhencetheassembler doesn’tseethemacrodefinitions. Inordertomaintaincompatibilitywithearlierreleases,theISRASMcodeinthisbookwillnotuseanypredefinedmacro.(Youcouldwriteyourownmacros,ofcourse,butifyouknowenoughtodothat,youdon’t needthisbooktotellyouhow.)Ourcodingthereforeincorporatesthefollowingfeatures: • Wewillnotuseany@prefixedmacros,or_@prefixedmacros. • Wewillnotuseourtimesavingoptionalbankselectionmacro,@bank.Instead,ifweareuncertainof whichbankaparticularregisterisinandwhetherweneedtochangebanks,wemustforceabankselectionusingthemacrodefinedinsidetheassembler,BankSel.Thebankselmacroiscalledwiththe followingsyntax:
Banksel
322
InterruptHandlersandTimersinAssembler Bankselexpectsa9-bitargument.Itgeneratesthecodetochangethebankbitstopointatthe
•
bankcorrespondingtothe9-bitaddress.Thebankselectioncodewillalwaysbegenerated,evenif thebankbitswerealreadysetcorrectlybeforethebankselmacro. Inordertoavoidastringoferrormessages,wewillstriptheexcesscompilerbitsfromregisterfile definitions. o Toobtaina7-bitregisteraddressforopcodearguments,wetrimwiththefollowingoperation: RegisterName&0x7F o InMBasicversionsearlierthan5.3.0.0whichuseMicrochip’sMPASMassembler,itisnecessary toobtaina9-bitregisteraddressforbanksel,whichwedobywetrimmingtheexcessbitswith thefollowingoperation:RegisterName&0x1FF.TheGPASMassemblerusedwithversion 5.3.0.0onwarddoesrequiretheexcessbitstobetrimmedviathe&0x1FFmask.Rather,thevariablenamemustbeuseddirectly,forexample,bankselRegisterName.Usinga&0x1FFmask causestheassemblertogeneratean“invalidlabel”errormessage,preventingyourfromcompiling.
ProgramExamples Let’sstartwithanISRASMversionofProgram10-1.Configureyour 2840DevelopmentBoardasshowninFigure15-1.Asyoumayrecall, Program10-1monitorsthestatusofpinB0throughtheexternalinterrupt.WhentheswitchSW1isclosed,B0goeslowandcausesthe externalinterrupttobeissued.Theexternalinterruptflag,INTFisset andexecutionjumpstoourISRASMcode.We’lltakethesameaction inProgram15-1aswedidinProgram10-1;we’llbrieflyflashthe LEDconnectedtopinB2everytimeSW1isclosed. Figure15-1:Program15-1Connection]. Asyoumayrecall
Program15-1 Stack=10 ;Constants ;--------Dly
Con
255
;Variables ;--------i
Var
Byte
;MBasicInitialization ;--------------------InputB0 ;SwitchonB0 OutputB2 ;LEDonB2 HighB2 ;testthatitworks Pause250 LowB2 i=Dly
;mustusevariableoritwon’tbeallocated
;........................ ;InterruptInitialization ;........................ ;======================== ;(A)setuptheinterrupt ;======================== ;(1)MBasicfunction ;---------------
323
Chapter15 SetExtIntExt_H2L ;======================== ;(B)enabletheinterrupt ;======================== ;(1)WritetoenablebitinMBasic Inte=%1 ;usenamedbitvariable ;==================================== ;(C)EnablePEIE(Ifnecessary)&GIE ;==================================== ;(1)WritetoenablebitinMBasic ;(PEIEnotnecessaryforthisinterrupt ;butit’sshownforcompleteness) PEIE=%1 ;usenamedbitvariable GIE=%1 ;========================================================== israsm ;========================================================== { ;INTCONisshadowedinall4banks,noneedtobanksel bcf Intcon,GIE ;disableinterrupts ;----------------- ;testsourceofinterruptandifINTFnotset,gotoend btfss Intcon,Intf ;ifnotINTFthenjumptotheend GoTo EndProc ;-----------------;FollowingcodeexecutedonlyforINTF bcf Intcon,intf ;cleartheinterruptflag BankSelPortB ;lighttheLEDonB2 bsf PortB,2 ;pauseforabrieftimewithdelayloop ;loadsvalueofDlyintoianddecrementsuntilzero movlw Dly ;w=Dly BankSeli ;getrightbank-nomaskisallowed! movwf i&0x7F ;i=Dly ;simpledelayloop=10*Dlyvalue ;measuredinFosc/4cycles LoopIt NOP ;totaldelayis10Fosc/4cycles NOP ;foronepassthroughtheloop NOP NOP NOP NOP decfsz i&0x7F,f GoTo LoopIt bankselPortB ;backtoPortB’sbank bcf PortB,2;turnLEDoff ;endofISRASM ;-----------------EndProc ;----------------- bsf BankSel0 }
IntCon,GIE
;enableinterrupts ;pointatBank0forMBasic
Main ;-----GoToMain End
324
InterruptHandlersandTimersinAssembler WhenyoucloseSW1,youshouldseetheLEDbrieflyilluminate. Let’sgothroughthecode. Dly i
Con Var
255 Byte
Wedefineoneconstant,Dlyandonevariablei.WeusebothtocreateadelaybetweenturningtheLEDon andturningitoff. ;MBasicInitialization ;--------------------InputB0 ;SwitchonB0 OutputB2 ;LEDonB2 HighB2 ;testthatitworks Pause250 LowB2
WesetupB0asaninput—thedefaultisinput,butit’sgoodpracticetoexplicitlydefinethepin’sinput/outputstatus.WealsodefineB2asanoutputandbrieflyflashtheLEDtoverifythatit’sproperlyconnected. i=Dly
;mustusevariableoritwon’tbeallocated
AswelearnedinChapters13and14,MBasicisanoptimizingcompilerandwillnotallocatestoragefor variablesthatareunusedwithinMBasiccode.OnewaytoefficientlyaccomplishthisistheClearprocedure,whichsetsallvariablestozero,therebyforcingthecompilertoallocatespaceforalldeclared variables.We’lljustuseiinanassignmentstatement,therebyensuringthecompilerallocatesspaceforit. Nowwegothroughthemultisteptemplatewedevelopedearlier. ;InterruptInitialization ;(A)setuptheinterrupt ;(1)MBasicfunction ;--------------SetExtIntExt_H2L
Sinceweonlyinitializetheinterruptonce,there’snobenefitfromusingin-lineorotherassemblercode. Hence,we’llusetheMBasicSetExtIntfunctiontosettheRB0interrupttofireonthehigh-to-lowtransitions. ;(B)enabletheinterrupt ;(1)WritetoenablebitinMBasic Inte=%1 ;usenamedbitvariable
Thenextstepinourinterrupttemplateistoenabletheinterrupt.Again,sinceweonlyinitializetheinterrupt once,there’snobenefitfromusinganythingotherthanMBasic. ;(C)EnablePEIE(Ifnecessary)&GIE ;(1)WritetoenablebitinMBasic ;(PEIEnotnecessaryforthisinterrupt ;butit’sshownforcompleteness) PEIE=%1 ;usenamedbitvariable GIE=%1
Nextwesettheglobalinterruptenablebit,GIE.Aswelearnedearlier,theGIEisamasterswitchthatmust besetforanyinterrupttowork.Whileweareatit,we’llalsosettheperipheralinterruptbit,PEIE,asecond masterswitchrequiredtobesetbeforeanyperipheralinterruptwilltrigger.Theparticularinterruptweuse, theexternalorRB0,interruptisnotamemberoftheperipheralinterruptfamily;soenablingthePEIEisn’t necessary.But,we’llenableittodemonstratehowitisdone. We’llskipthestepofclearingtheexternalinterruptflag,INTFasitisn’tnecessaryforthissimpleprogram. Ifyouwishtodoso,clearingtheflagmaybeaccomplishedbyaddingtheMBasicstatementINTF=%0. NowwereachtheISRASMitself.NotethattheISRASMisfollowedbycurlybracestocontainalltheinterruptroutine’sassemblercode.Itisn’tnecessarytoaddthecompilerinstructionASM.
325
Chapter15 IliketoplacetheISRASMcodenearthetopoftheprogram,aftervariablesandconstantsaredeclaredand afterinitialization.Thisis,however,apersonalpreferenceandyoumayplacetheISRASMcodeanywhere outsideprogramflow,suchasatthebottomoftheprogram,evenaftertheEndstatement. israsm { ;INTCONisshadowedinall4banks,noneedtobanksel bcf Intcon,GIE ;disableinterrupts
Firstthingwedisableallinterruptsbyopeningthemasterinterruptswitch—clearingtheglobalinterruptenablebit.Wedon’twantourcodetobere-triggeredbyanotherinterruptbeforeithascompletedexecuting.
;testsourceofinterruptandifINTFnotset,gotoend btfss Intcon,Intf ;ifnotINTFthenjumptotheend GoTo EndProc
Thenextstep—anditshouldnotbepostponeduntillaterintheISRASMcode—istodeterminetheinterruptsourceandterminatetheISRASMroutineiftheinterruptisnotfromasourcewewishtohandleinthe ISRASM.Inthiscase,withonlyoneinterrupttohandle,wetesttoseeiftheassociatedflagbit,Intf,isset. IftheIntfflagisclear(notset)wetransferexecution,viatheGoTostatement,tocodestartingatthelabel EndProc,whichwewillfindcompletesonesmallhousekeepingfunctionandthenendstheISRASM.(All 14possibleinterruptflagsareinregisterslocatedinBank0,andweknowMBasichandsovercontroltothe ISRASMinbank0,sowedonothavetoworryaboutbankselection.) ;FollowingcodeexecutedonlyforINTF bcf Intcon,intf ;cleartheinterruptflag
Next,wecleartheinterruptflag,sothattheinterruptdoesn’tgointoanendlessloop.
BankSelPortB ;lighttheLEDonB2 bsf PortB,2
WeturntheLEDonbysettingpinB2highviathebsfoperation,performedonPortB,bit2.Weknowthat PortBisinbank0,sothebankselPortBoperationisunnecessary,butIincludeditasareminderthatwe mustalwaysbeconsciousofbanking.
;pauseforabrieftimewithdelayloop ;loadsvalueofDlyintoianddecrementsuntilzero movlw Dly ;w=Dly BankSeli ;getrightbank movwf i&0x7F ;i=Dly
We’lluseasimpledelaylooptopauselongenoughforustoseetheLEDilluminate.First,wecopythe numberofrepeatcyclesinthedelayloop,heldintheconstantDly,intothecountervariablei.We’veseen howthisisaccomplishedinChapters13and14.NoteweusetheBankselimacrotosetthebankingbits. LoopIt
;simpledelayloop=10*Dlyvalue ;measuredinFosc/4cycles NOP ;totaldelayis10Fosc/4cycles NOP ;foronepassthroughtheloop NOP NOP NOP NOP NOP decfsz i&0x7F,f GoTo LoopIt
Theloopstructureusesthedecfszoperation,whichissimilartotheFor…Nextassemblertemplate discussedinChapter14.Thedecfszoperatordecrementstheregisterfileiandtestsiforzero.Ifiis notzero,thestatementimmediatelyfollowingthedecfszoperatorexecutes;ifiiszero,thatstatement isskippedandexecutionbranchestothesecondstatementfollowingthedecfszoperator.Thisstructure causestheLoopItstatementtoberepeatedDlytimes.ThedecfszandGoTooperationsconsumeacom326
InterruptHandlersandTimersinAssembler binedtotalofthreeinstructioncycles,sotoprovidemoredelay,weaddsevenno-operationinstructions,for atotalofteninstructioncyclesdelay.OneinstructioncycleisFosc/4,orforthe20MHzclock,0.200µs.Ten suchinstructioncyclesis2µs,andwhenrepeated255timesresultsinatotaldelayof5100µs.
banksel bcf
PortB PortB,2
;backtoPortB’sbank ;turnLEDoff
Afterthedelay,weturntheLEDoffbytakingpinB2low. ;endofISRASM EndProc bsf }
IntCon,GIE
;enableinterrupts
AttheendoftheISRASM—whetherwereachitbyavalidinterruptandcompletionofthedelaylooporby anonexpectedinterruptandthejumptoEndProc,allweneeddotowrapuptheISRASMistoreactivate themasterinterruptswitchbysettingGIEandensurethatthebankingbitsareselectedforbank0,which MBasicexpects.We’veearlierusedbankselportBtosetthebankingbits,andsincePortBisinbank0, weneednoadditionalbankselectiontomeetMBasic’sre-entryrequirements. That’sit.Prettysimple,isn’tit?MBasichidesthecontextswitchingfromus,permittingustoconcentrateon usefulcodetodealwiththeinterrupt. Main ;-----GoToMain End
Finally,haveanendlessMain…GoToMainlooptokeeptheMBasicprogramelementsexercised. Runprogram15-1andpressswitchSW1.Withnodelayperceptibletoyoureye,theLEDwillbrieflyflash. Sofar,nomajorimprovementoverProgram10-1,right?Ineitherprogram,youperceivenodelaybetween switchclosureandLEDillumination. Let’smodifyProgram15-1bychangingthefollowing: Main ;----- Pause1000 GoToMain
We’llnametheamendedcodeProgram15-1-A.Recompileandrunit.Pressthebuttonandwhatdoyou see?NochangefromProgram15-1;theLEDflasheswithnoperceptibledelayassoonasyouoperateSW1. ThisisquitedifferentbehaviorthanweobservedafteraddingdelaytoProgram10-1.There,inwhatbecame Program10-1-A,wesawnoticeableandvariabledelay—uptoonesecond—betweenSW1’soperationand LEDillumination.TheextendeddelayinProgram10-1-Aresultsfromexecutinginterruptsonlybetween MBasicstatements;incontrast,thenearinstantaneousresponseinProgram15-1-Aisaproductofthe ISRASMexecutingafteranyofthedozensorhundredsofmachine instructionsthatcompriseanysingleMBasicstatement. Program15-2 SinceourprogramcanhavebutoneISRASMprocedure,howdo weaccommodatemultipleinterrupts?Let’slookatasimplewayto supportmultipleinterrupts.AddasecondLEDandcurrentlimitingresistortoyour2840DevelopmentBoard,asshowninFigure 15-2.We’llusetimer1toflashtheLEDconnectedtopinB1with approximately128mson/128msoffperiods.We’llalsotestfor changeofstatusonpinB0withtheexternalinterruptand,whenthe Figure15-2:Wiringforprogram15-2. 327
Chapter15 switchconnectedtopinB0closes,we’llflashtheLEDonpinB2usingathirdinterrupt,timer2,tocontrol theflashduration.Thus,Program15-2musthandlethreeinterrupts. ;Program15-2 ;multipleinterrupts ;Constants ;--------TicksPerms
Con $FFFF-5000
LED2 LED1
Con Con
;fortimer1
2;LEDonPinB2 1;LEDonPinB1
;IncaseMBasic’serrorsinTimer2constantshavenotbeen ;fixed,wesupplyourown T2Post1 Con %00000000 T2Post2 Con %00001000 T2Post3 Con %00010000 T2Post4 Con %00011000 T2Post5 Con %00100000 T2Post6 Con %00101000 T2Post7 Con %00110000 T2Post8 Con %00111000 T2Post9 Con %01000000 T2Post10 Con %01001000 T2Post11 Con %01010000 T2Post12 Con %01011000 T2Post13 Con %01100000 T2Post14 Con %01101000 T2Post15 Con %01110000 T2Post16 Con %01111000 T2Pre1 T2Pre4 T2Pre16
Con Con Con
%00000100 %00000101 %00000111
;weselect8uspercomparisionunit,soweneed ;atotalpre*postof40:1. Tmr2SetUp Con T2Post10+P2Pre4 ;for1mson,theperiodmustbe125 Tmr2Period Con 125 ;Variables ;--------i
Var
Byte
;MBasicInitialization ;--------------------InputB0 ;SwitchonB0 OutputB2 ;LEDonB2 HighB2 ;testthatitworks Pause250 LowB2 OutputB1 HighB1 Pause250 LowB1
;LEDonB1 ;testthatitworks
Clear
;mustusevariableoritwon’tbeallocated
;........................ ;InterruptInitialization ;........................ ;======================== ;(A)setuptheinterrupt ;========================
328
InterruptHandlersandTimersinAssembler ;(1)MBasicfunction ;--------------SetExtIntExt_H2L SetTmr1Tmr1Int1
;theB0interrupt ;setuptimer1,prescale=1,internal
;settimer2for10:1post&4:1pre&125divideso ;thatwegeta1000usperiod SetTmr2Tmr2Setup,Tmr2Period Tmr2On=%0
;turntimer2offuntilweneedit
;======================== ;(B)enabletheinterrupt ;======================== ;(1)WritetoenablebitinMBasic Inte=%1 ;enabletimer1interrupt Tmr1IE=%1 ;timer1interrupton Tmr2IE=%1 ;timer2interrupton ;============================= ;(C)Cleartheinterruptflags ;============================= intf=%0 Tmr1If=%0 Tmr2IF=%0 ;==================================== ;(D)EnablePEIE(Ifnecessary)&GIE ;==================================== ;(1)WritetoenablebitinMBasic ;PEIEisnecessaryforTmr1interrupt PEIE=%1 ;usenamedbitvariable GIE=%1 ;globals ;========================================================== israsm ;========================================================== { ;INTCONisshadowedinall4banks,noneedtobanksel ;MBasicsetsbank=0goingintoisrasm bcf Intcon,GIE ;disableinterrupts ;----------------- ;testsourceofinterruptandifINTFnotset,gotoend btfsc Intcon,Intf ;ifnotINTFthenjumptotheend Goto IntfProc ;ifsetexecuteIntfProc btfsc PIR1,Tmr2IF ;testfortimer2interrupt GoTo Tmr2Proc ;ifsourceofinterruptistimer2 btfsc PIR1,Tmr1IF ;testfortimer1interrupt GoTo Tmr1Proc ;ifsourceofinterruptistimer1 ;allothercases-gotoend GoTo EndProc ;-----------------IntfProc ;-----------------;FollowingcodeexecutedonlyforINTF bcf Intcon,intf ;cleartheinterruptflag bsf PortB,LED2 ;turnB2LEDon ;bothPIR1andT2Conareinbank0,noneedtochange bcf PIR1,Tmr2IF;cleartimer2interruptflag ;cleartimer2 clrf Tmr2 ;cleartimer2’smaincounter ;writetoT2conalsoclearspre&postscalecounters bsf T2Con,Tmr2On;turntimer2on GoTo EndProc
329
Chapter15 ;------------------Tmr2Proc ;------------------;followingcodeexecutedonlyifTimer2interrupt ;calledwithbank=0 bcf PortB,LED2 ;turnB2LEDoff ;bothPIR1andT2Conareinbank0,noneedtochange bcf PIR1,Tmr2IF;cleartimer2interruptflag bcf T2Con,Tmr2On;turntimer2off GoTo EndProc ;-----------------Tmr1Proc ;-----------------;followingcodeexecutedonlyifTimer1interrupt ;calledwithbank=0 bcf PIR1,Tmr1IF;cleartimer1interruptflag ;timer1mustbereseteverytimeitrollsover. ;highbytefirst-avoidsrolloverduring ;thetimeittakestoresetthecounter. movlw HighTicksPerms ;puthighbyteofloadintoW ;timerspr’sareinBank0noneedforbanksel movwf TMR1H ;moveintotimerregister movlw LowTicksPerms ;nowforthelowbyte movwf TMR1L ;moveintotimerregister BankSelI ;whereisi? incf i&0x7F,f ;i=i+1 btfss i&0x7F,7 ;usebit7as/128flash Goto TurnOff BankSelPortB bsf PortB,LED1 GoTo EndProc TurnOff BankSelPortB bcf PortB,LED1 GoTo EndProc ;endofISRASM ;-----------------EndProc ;----------------- bsf IntCon,GIE ;enableinterrupts } Main ;----- Pause1000 GoToMain End
Let’sstartouranalysisofProgram15-2withapseudo-codeviewofourISRASMstructure.Forclarity,we’ll useMBasictypepseudo-codeinsteadofassembleroperators. Initialization SetupTimer2toprovide1msperiod SetupTimer1toprovide1msperiod SetupTimer1,Timer2andExternalInterrupts ISRASM DeterminesourceofInterrupt: IfExternal(Buttonpushed) ClearTimer2interruptflag TurnLEDonB2on ResetTimer2 TurnTimer2on
330
InterruptHandlersandTimersinAssembler
IfTimer2 TurnLEDonB2off TurnTimer2off
IfTimer1 Reloadtimer1pre-setvalues i=i+1 LEDonB1=i.Bit7
Ifnoneoftheabove,exitISRASM
MBasicdummyroutine: Main Pause1000ms GoToMain
Whysettimers1and2for1ms?And,whycomplicatethingswithasecondtimer,whenthedelayprocess ofProgram15-1works? Let’stakethesecondquestionfirst.Remember,thefirstthingwedointheISRASMprocedureisdisable interrupts.Hence,toreducelatencyproblemscausedbyinterruptsfiringbutnotbeingrecognizedduringthe ISRASMprocedure,weshouldkeeptheISRASMcodeasshortasfeasible.InsteadofstoppinginterruptsduringthedelayperiodweusedinProgram15-1,we’lloffloadthedelaytotimer2—ahardwaremodulethat consumesnosoftwareresources.Thus,otherthanafewmicrosecondsittakesexecutetheminimumneeded code,ourprogramisfreetorespondtoanyotherinterrupts. Iselected1msfortimer2becauseityieldsaneasilyviewedbutstillbriefflashfromanLED.Theexact on-timeisn’tcritical,soexperimentifyouwish.IwantedtoflashthesecondLEDataratethatmakesa noticeableon/offsequence.And,IwantedminimumhousekeepingtoalternatetheLEDbetweenonandoff, soIplanedtouseatrickwe’veseenbefore—incrementabytevariablecounterandmaketheLEDpintrack thecounter’shighbit.Thisgives128periodsoff,followedby128periodson.Ifweincrementthecounter onceevery1ms,theresultisavisuallypleasant128msoff/128msoncycle. We’velearnedinChapter10howtosettimers1and2toproducetheseintervals.Witha20MHzresonatorinmy2840DevelopmentBoard,itrequiresatotalcountof5000toproduceinterruptsonceeveryone millisecond.Fortimer2,weachievethe5000countwithaprescalevalueof4,apostscalevalueof10anda counterperiodof125.Fortimer1,wemaysettheprescaleratioas1:1andpre-loaditscounterregisterwith $FFFF-5000.Ifyoudon’tunderstandhowIarrivedatthesenumbers,gobackandrereadChapter10.We’ll cheatabitandnotworryaboutcounterdeadtime,sinceourpurposehereistodemonstratetherudiments oftheISRASMprocedureandafewmicrosecondserrorisn’timportant.Toseehowtocorrectfordeadtime whensettingtimer1,studyProgram19-3. TicksPerms LED2 LED1 Tmr2SetUp Tmr2Period
Con Con Con Con Con
$FFFF-5000 ;fortimer1 2 ;LEDonPinB2 1 ;LEDonPinB1 T2Post10+P2Pre4 125
Basedonthesecalculations,wedefinethethreetimer-relatedconstantsshownabove.Toimproveprogram readability,wedefinetwoconstantsLED2andLED1toreferencePortB’sbitnumberscorrespondingtothe LEDsonpinsB2(LED2)andB1(LED1). Let’sconcentrateonthechangesfromProgram15-1ininterruptsetup. ;InterruptInitialization ;(A)setuptheinterrupt ;(1)MBasicfunction ;--------------SetExtIntExt_H2L ;theB0interrupt SetTmr1Tmr1Int1 ;setuptimer1,prescale=1,internal
331
Chapter15 ;settimer2for10:1post&4:1pre&125divideso ;thatwegeta1000usperiod SetTmr2Tmr2Setup,Tmr2Period Tmr2On=%0
;turntimer2offuntilweneedit
We’veaddedsetupcodefortimers1and2.Rememberourusefortimer2isasa“oneshot”action;itis turnedonwhentheexternalinterruptfires,cyclesonceandisturnedoffuntilthenexttimetheexternal interruptfires.Hence,wesetuptimer2,butturnifoffasitisn’tneededyet. ;(B)enabletheinterrupt ;(1)WritetoenablebitinMBasic Inte=%1 ;enabletimer1interrupt Tmr1IE=%1;timer1interrupton Tmr2IE=%1 ;timer2interrupton
WeuseMBasictoenabletheinterrupts.Thereisnoadvantagetoenablingtheinterruptsinassembler. ;(C)Cleartheinterruptflags intf=%0 Tmr1If=%0 Tmr2IF=%0
Todemonstratehowit’saccomplishedinMBasic,we’veaddedaflagclearingsectiontoourinitialization code. ;(D)EnablePEIE(Ifnecessary)&GIE ;(1)WritetoenablebitinMBasic ;PEIEisnecessaryforTmr1interrupt PEIE=%1 ;usenamedbitvariable GIE=%1 ;globals
Attheendoftheinitializationsection,weenableglobalandperipheralinterrupts.Bothtimers1and2are membersoftheperipheralinterruptfamily,sowemustenableperipheralinterruptsbysettingthePEIEbit. israsm { ;INTCONisshadowedinall4banks,noneedtobanksel ;MBasicsetsbank=0goingintoisrasm bcf Intcon,GIE ;disableinterrupts
AsinProgram15-1,thefirstorderofbusinessintheISRASMprocedureistodisableinterruptstoavoidmultipletriggers.Weusethesame“masterswitch”approachdiscussedinouranalysisofProgram15-1.
;testsourceofinterruptandifINTFnotset,gotoend btfsc Intcon,Intf ;ifnotINTFthenjumptotheend Goto IntfProc ;ifsetexecuteIntfProc btfsc GoTo
PIR1,Tmr2IF Tmr2Proc
;testfortimer2interrupt ;ifsourceofinterruptistimer2
btfsc GoTo GoTo
PIR1,Tmr1IF Tmr1Proc EndProc
;testfortimer1interrupt ;ifsourceofinterruptistimer1 ;allothercases-gotoend
Ourinterrupthandlermustrecognizeanddealwiththreeinterrupts—external(RB0),timer1andtimer2.We testeachofthethreeassociatedinterruptflagswithabtfscoperation;ifthebitisset,executionbranchesto theassociatedinterrupthandlercodeviaaGoTo,otherwise(theflagbitisclear)thetestproceedstothenext btfsccomparison.Iftheinterruptflaghasnotbeenfoundafterthelasttest,theinterruptsourcemustbe oneotherthanthethreeweintend,soexecutionjumpstotheendoftheISRASMcodeviatheGoToEndProcoperation. TheIntfProccodeisexecutediftheinterruptsourceistheexternalinterrupt(RB0).MBasicsetsthebank selectionbitstobank0goingintoISRASM,andourflagtestsequencedoesnotalterthebankingbits,sowe areassuredentrytoeachofthethreeinterrupt-specificsectionsinbank0.
332
InterruptHandlersandTimersinAssembler IntfProc ;-----------------;FollowingcodeexecutedonlyforINTF bcf Intcon,intf ;cleartheinterruptflag bsf PortB,LED2 ;turnB2LEDon ;bothPIR1andT2Conareinbank0,noneedtochange bcf PIR1,Tmr2IF ;cleartimer2interruptflag ;cleartimer2 clrf Tmr2 ;cleartimer2’smaincounter ;writetoT2conalsoclearspre&postscalecounters bsf T2Con,Tmr2On ;turntimer2on GoTo EndProc
WefirstcleartheintfinterruptflagtoavoidmultipletriggersofISRASM.WenextsetPortBpinB2high toilluminatetheLED.Now,wemustinitializeandstarttimer2sothatwemayuseittoturntheLEDoff after1ms.Beforewedoanythingelse,wecleartimer2’sinterruptflag.Thisflagshouldalreadybeclear,but asamatterofcaution,we’llclearitanyway.Nextweinitializetimer2,whichrequiresustoclearits8-bit counterregister,Tmr2,anditsprescalerandpostscaler.WeclearTmr2withaclrfoperation.(Whenwe writetotimer2’scontrolregistertoturntimer2on,theprescalerandpostscalerareautomaticallyreset,so theyneednoexplicitclearingoperation.)Thefinalstepistoturntimer2on,whichwedobysettingT2Con high.Beforewritingthecode,weverified,ofcourse,thatthePIR1,Tmr2andT2Conspecial purposeregistersareallinbank0,sonobankseloperationisnecessary. Tmr2Proc ;------------------;followingcodeexecutedonlyifTimer2interrupt ;calledwithbank=0 bcf PortB,LED2 ;turnB2LEDoff ;bothPIR1andT2Conareinbank0,noneedtochange bcf PIR1,Tmr2IF;cleartimer2interruptflag bcf T2Con,Tmr2On;turntimer2off GoTo EndProc
Whenthetimer2interruptisdetected,weturnofftheLEDbytakingPortB,pinB2lowthroughthebcf PortB,LED2operation.Sinceweusetimer2asa“one-shot”event,wecleartimer2’sinterruptflag,Tmr2If, andshuttimer2downbyclearingtheTmr2Onbit.Untilrestartedfollowinganexternalinterrupt,timer2remainsoff.PIR1andT2CONregistersbothareinbank0,soweneednotalterthebankingbitselection. Tmr1Proc ;-----------------;followingcodeexecutedonlyifTimer1interrupt ;calledwithbank=0 bcf PIR1,Tmr1IF;cleartimer1interruptflag ;timer1mustbereseteverytimeitrollsover. ;highbytefirst-avoidsrolloverduring ;thetimeittakestoresetthecounter.
movlw HighTicksPerms ;puthighbyteofloadintoW ;timerspr’sareinBank0noneedforbanksel movwf TMR1H ;moveintotimerregister movlw LowTicksPerms;nowforthelowbyte movwf TMR1L ;moveintotimerregister BankSeli& incf btfss Goto BankSelPortB bsf GoTo
i&0x7F,f i&0x7F,7 TurnOff
;whereisi? ;i=i+1 ;usebit7as/128flash
PortB,LED1 EndProc
Timer1requiresabitmorecomplextreatment.First,ofcourse,wecleartimer1’sinterruptflag,Tmr1IF.
333
Chapter15 AsyoumayrecallfromChapter10,tomaketimer1reset(andcauseaninterrupt)atourtargetnumberof counts,wepreloadthecounterregisterwith$FFFF-targetvalue.Timer1countsupandwhenitrollsoverat $0000,itresets.But,wemustreloadtimer1withthispresetvalueeverytimeitrollsover,orelsethecounterresumesfrom$0000,notthedesiredpreloadedvalue.Wepreloadthecounterhighbytefirst,toavoid havingthelowercounterbyterolloverduringthetimeittakestoaccomplishthepreload. Afterpreloadingtimer1,wethenincrementtheon/offcounter,i.Ourstrategyistouseitobothcountthe numberof1msinterruptsandtoserveasastatusholdertodeterminewhentoturnthepinB1LEDonand off.Weusei.bit7tocontroltheLED;ifi.bit7ishigh,weturntheLEDonbysettingPortB,LED1 high,otherwiseweclearPortB,LED1. Becausewearenotsureinwhichbankiresides,weaddbankseloperations.(SincewehavenotoverriddenMBasic’sdefaultstacksettinginProgram15-3,andsinceweonlyhaveonevariable,infact,weknowi isinbank1.But,thesecircumstancesmaynotalwaysbetrue,sowe’lluseabankseloperatortoensurethe correctbanking.) TurnOff BankSelPortB bcf GoTo
PortB,LED1 EndProc
Sincetheturn-offprocessrequiresmorecodethanwecangetintooneline,wejumptothelabelTurnOff whenthei.bit7islow. ;endofISRASM EndProc bsf }
IntCon,GIE
;enableinterrupts
WewrapuptheISRASMprocedurebyre-enablingthemasterinterruptswitch,GIE. WhenrunningProgram15-2,youshouldseetheLEDconnectedtopinB1flashingaboutfourtimesasecondandtheLEDatpinB2shouldflashoncefor1mseverytimeSW1ispressed. Whathappensiftimers1and2firetheirinterruptssimultaneously?Orwhathappensifallthreeinterrupts firesimultaneously?Ifso,theISRASMwillbeexecutedonceforeachinterruptthathasfired,withtheinterruptsdealtwithoneatatimebytheISRASMcode,intheorderestablishedbythetest/jumpstatementsatthe beginningoftheISRASMprocedure.Ifsimultaneousinterruptsarepossible,andifhandlingsimultaneous interruptsinaspecificorderisimportant,thenyourISRASMcodeshouldbestructuredtoservicetheinterruptsinthedesiredorder. Ratherthanextendingthischaptertoprovideadditionalabstractexamplesofinterrupthandling,youshould examinethespecificuseswe’vemadeofISRASMroutinesin: • Chapter16—togenerateasynthesizedsinewavebydirectdigitalsynthesis; • Chapter19—tocontrolsteppermotors;and • Chapter25—toreadbarcodes.
References [15-1]
MBasic’sISRASMprocedureisdocumentedonlyincommentspostedinBasicMicro’sUser’sForum, whichmaybereachedathttp://forums.basicmicro.net/.Searchfor“israsm”toreviewtheavailable information. [15-2] Withrespecttoassemblerprogrammingingeneral,thereferencesprovidedatChapters13and14may beconsulted.
334
CHAPTER
16
Digital-to-Analog Conversion Digital-to-analogconversion(DAC)istheprocessofconvertinganumericvaluetoananalogparameter, oftenavoltage.Thevoltagemayrepresentanalerting“beep”tonedrivingaloudspeaker,oritmay,through anamplifier,controlthespeedofaDCmotor,oritmaybeusedforwiderangeofotherapplications.The voltagemayhavea1:1relationshiptothedigitalvalue(numericalvalue123generates123volts)oritmay scaled(numericalvalue123generates1.23volts),levelshifted(digitalvalue123generates523volts;digital 124generates524volts)orotherwiselinearlyornonlinearlytransformed.Theoutputmaychangewithtime, asthedigitalvaluechangeswithtime.Finally,thedigitalvaluemaybeusercontrolledoritmaybegeneratedbythePICinresponsetoanexternalsensor. WewillexploreMBasic’sdigital-to-analogabilitiesbybuildingadirectdigitalsynthesissinewavegenerator.Ourfirstapproach,entirelyinMBasic,hasamaximumoutputfrequencyjustunder1KHz.Bycoding timecriticalelementsinassembler,we’llseeusableresultsatmorethan10kHz.Wewillalsocomparethe DDSdesignwithotherD/AapproachesavailablewithMBasic.
IntroductiontoDigital-to-AnalogConversion
TheDAChasthesameneedforpositiveandnegativereferencevoltages VREF+andVREF–astheADCandthe formulawedevelopedinChapter11 forcalculatingtheADCstepsizeappliestoaDACequallywell:
8 7
7 6
6
Output Analog Voltage
Let’sexamineasimpledigital-toanalogvoltageconverter,theDAC equivalentofthe3-bitADCwe examinedinChapter11.Figure16-1 illustratestherelationshipbetween digitalinputandoutputforthisDAC. ComparingFigure11-1withFigure 16-1shows—anditshouldbenogreat surprise—digital-to-analogconversion istheinverseoftheanalog-to-digital process.Eachinputvalueresultsina specificoutputvoltage.Sincethedigitalinputcanonlyhavediscretevalues, 0,1,2…7,theoutputvoltagelikewise assumesdistinctvalues.
5
5 4
4 3
3 2
2 1
1 0
0 0
1
2
3
4
5
Digital Input Value
Figure16-1:Thedigital-to-analogconversionprocess.
335
6
7
Chapter16
VSTEP =
(VREF + − VREF − )
2N NisthenumberofinputbitsusedbytheDAC.
Let’sapplythistoourhypothetical3-bitDAC.Supposewewishtogenerateanoutputvoltagethatsteps from0to3.5voltsin0.5voltsteps.Sinceourminimumvoltageistobe0,wewillsetVREF–asground.VREF+ isthusrequiredtobe4.0volts,sinceVSTEPisdesiredtobe0.5volts.Theoutputvoltageisthus0.5multiplied bytheinputvalue. Remember,though,thatourhypothetical3-bitDAConlyhas0..7asvalidinputs.Hence,themaximumvoltage itcanoutputis3.5volts,not4.0,thereferencevoltage.Ifwesettheinputto8(binary1000)our3-bitDAC, beingconnectedtoonlytherightmostthreebits(000),willobliginglyoutput0V,notthedesired4.0V. AsinthecaseoftheADC,weselectVREF+andVREF-tomeetouroverallcircuitdesigngoals,consist,ofcourse, withthephysicallimitsoftheDAC.ManyDACspermitVREF-tobenegativewithrespecttoground,auseful optionifwewishourwaveformtoswingtoeithersideofground.IfwesetVREF+at+5VandVREF–at–5V,for example,wecanoutputawaveformoneithersideofgroundwithapeak-to-peakvoltageofnearly10V. AlthoughweusuallyuseastableDCreferencevoltage,manyDACspermitaudiofrequencyortimevarying DCvoltagereferences.Inthiscase,theDACfunctionsasaprogrammableattenuator.(Inexpensivedevices knownas“digitalpotentiometers”areavailabletoperformthatfunctionandarediscussedinChapter21.)
Resolution–AccuracyandSignal-to-NoiseRatio Let’slookindetailataparticularDAC,TexasInstruments’modelTLC7528parallelloadingdual8-bit DAC.Thisinexpensive($3.30insinglelotquantities,atthetimeofthiswriting)deviceisavailableina 20-pinDIPpackagesuitableforplugboardconstruction.ItusesthecommonR-2Rladderdesignandmaybe operatedeitherasacurrent-modeorvoltage-modeoutputdevice. ResolutionisameasureofthenumberofdifferentoutputlevelsthatDACcangenerate.TheTLC7528is an8-bitdeviceandhencehas28or256possibleoutputvalues.Ifweuse+5voltsasthepositivereference voltagefortheDACand0volts(ground)asthenegativereference,eachoutputwilldifferfromtheadjacent stepby5.00V/256or19.53mV.AswasthecasewiththeADC,ifwewishouroutputtohaveconvenient stepintervals,weshouldselectareferencevoltagethatisanappropriatemultipleofthedevicespan.The LT1634CCZ-4.096precisionreferenceweusedinChapter11’sdigitalvoltmeterdesign,forexample,yields aconvenient16mVstepintervalwhenusedwithaTLC7528DAC.Toavoidunduecomplexityandsince ourpurposeistoillustrateprinciples,nottobuildaproductioncircuitwithaccurateamplitudecontrol,out designusesthe2840DevelopmentBoard’sVDDsupplyasthereferencevoltage. AccuracyisameasureofthedifferencebetweentheDAC’soutputandthedesiredvalue.Althoughwewill notbuildit,let’sbrieflyexamineahypotheticalTLC7528circuitwithaprecisionLT1634CCZ-4.096voltage reference,followedupbyanop-ampbufferandaswitchedcapacitorlow-passfilter.VSTEPis4.096V/256,or 16.0mV.Supposewewishtogenerate1.0000V.Weimmediatelyseeoneproblem;ifwesettheDACinput to62,itoutputs0.992V,while63generates1.008V.Eitherway,weare8mVfromourtarget.Unfortunately,thisquantizationerrorisnottheendofourproblems.Apartiallistofpotentialerrorsourcesincludes manyofthesuspectsseeninChapter11’sADCdiscussion,whichwewon’trepeathere. AswithourADCanalysis,wemustconsiderthemagnitudeanddirectionoftheseerrorsources.Arethey short-termorlongterm?Doesoneerroroffsetinwholeorinpartanothererror,ordotheydirectlyadd? Ignoringthoseerrorsourcesdependentuponthelayoutandexternalfactors,wecanidentifyseveralpossible errorsourcesinourhypotheticaldesign: 336
Digital-to-AnalogConversion •
Referencevoltageerror—TheLT1634CCZ-4.096hasaspecifiederrorof±0.2%overthetemperature range0…70ºC.Anerrorof0.2%inthereferencerepresents8.2mV. • Linearityerror—TexasInstruments’quotestheTLC7528DACasnottoexceed±½LSBincurrent modeor±1LSBinvoltagemode. • Outputbufferamplifiererror—Thevoltageoutputbufferamplifier,aLF411op-ampconfiguredasa voltagefollower,adds±0.5mVoffsetvoltageerror. • Quantizationerror—inherently±½LSBinourdeviceanddesign. • Errorsinthelow-passfilter—Manyactivelow-passfiltershaveDCamplitudeerrors,inadditiontothe expectedfrequencyandtransientbasederrors • ACerrorsinthelow-passfilter—TheACresponseofthelow-passfiltersisnotperfectlyflatinthe passbandandtransientwaveformsmayexperienceovershootandundershootfromthefilteraswell. Aworst-caseerroranalysis(whereallerrorsareinthesamedirection)yieldsamaximumerrorintothe low-passfilteris±1LSB(DAClinearity)±0.5mV(LF411offset)±0.2%(referenceerror)±½LSBmV (quantizationerror).Since1LSBis16mV,wecanrestatethegeneralerroras±0.2%,±24.5mV,orwhere thedesiredvoltageisanintegralnumberofvoltagesteps±0.2%,±16.5mV.Ifwewishtogenerate2.000 volts,therefore,theexpectederrormagnitudeis0.002*2.000+16.5mV=20.5mV.Ifweweredesigninga productioninstrument,ofcourse,acomprehensiveerrorandstabilityanalysisoftheentirecircuit,including thelow-passfilter,isrequired.OurpurposehereislimitedtohighlightingafewDACaccuracyconcerns.
Signal-to-NoiseRatio Inherentinquantization—bothA/DandD/A—isnoise.Therelationshipbetweenthemaximumsignalto noiseratioandthenumberofbitsinthesampleis:
SNRdB=6.02N+1.76
Nisthenumberofbitsofamplitudelevelusedinthesample
SNRdBisthesignaltonoiseratioindecibels.
TheTLC7528DACisan8-bitdevice,sothemaximumsignaltonoiseratiowemayexpectis49.92dB. ThisfiguremaybemisleadingasquantizationnoiseisspreadovertheentireNyquistsamplingrangeof0 toone-halfthesamplingfrequency.Ifwegeneratea1KHzwaveform,usinga100KHzsamplefrequency, andiftheDACisfollowedbya2KHzlow-passfilter,quantizationnoise—appearingovertherange0-50 KHz—mayreducedbyasmuchas14dBmeasuredatthelow-passfilteroutput,yieldinganexpectedSNR approaching65dB.
HenryNyquistandhisSamplingTheorem WhenanalyzingthedigitalvoltmeterinChapter11wemore-or-lessimplicitlyassumedthevoltagetobe measuredwasconstant,oratleastchangedveryslowlywithtime.Itwasn’tnecessary,therefore,todelve intowhathappenswhenwedigitizeatimevariantsignal.OurDACprojectwouldbedullindeedifallitdid weretoputoutaconstantvoltage.Sincewehavechosentogenerateatimevaryingsignal—inparticular asinewave—wemustbrieflyexamineatheoremthatunderpinsmuchofmodernelectronics,Nyquist’s samplingtheorem.Weshallskipoverallbutthemostessentialdetailbuttheinterestedreadercanconsult Reference[16-4]foramoredetailed,buthighlyreadable,explorationoftheA/DandD/Aprocesses. Nyquistdiscovered—in1927,twodecadesbeforethetransistorwasinvented—thatinordertoaccurately reproduceananalogsignal,itmustbedigitallysampledataratetwicethehighestfrequencytobereproduced.Or,inthecontextofaDAC,thehighestfrequencythatmaybegeneratedwithouterrorisone-halfthe samplingrate.
337
Chapter16 SupposeourDDSprogramsends1,000updatedsinecalculations(samples)totheDACeverysecond.In thiscase,Nyquistprovedthatwecannotaccuratelyreproduceafrequencyexceeding(1000samples/sec)/2, or500Hz.(Toallowforimperfectionsinthelow-passfilter,welikelywouldnottrustthisdesignbeyond about400Hz.)Thisfundamentalsamplerateversusoutputfrequencylimitationdrivesourquesttomake DDSprogramsexecuteintheminimumpossibletime. InadditiontoobservingNyquist’ssamplingrate,thenumberofbitsthatquantifytheanalogsignalisimportant;themorebits(greaterresolution),themoreaccuratelythesignalamplitudemaybedescribed.Suppose, forexample,wehavea1-bitsystem,withVSTEPof1volt.Theonlypossibleoutputwaveformsare(a)nothingor(b)onewithapeakvalueof1volt.Ifourtargetoutputis0.5volts,weclearlyareintrouble.(One-bit systemscanbemadetoprovidemuchgreaterresolutionthanthissimplifieddiscussionindicates—we’llsee anexamplelaterinthischapterwhenwelookatMBasic’sPWMfunction.) OurminimalDACconfigurationisillustrated inFigure16-2;aPICtogeneratenumerical valuesdefiningthedesiredwaveform,aDAC toconvertthosevaluestoanalogvoltagesand, finally,alow-passfilterwithacutofffrequency one-halftheDACsamplingrate,orlower. Thelow-passfilterisacriticalelementinthe analogconversionprocessasitsuppresses artifactscausedbythesteppednatureofthe DAC’soutput.Itmustbechosenwithcare.If wereproduceonlyasinusoidaloutput,atone Figure16-2:DACconfiguration. fixedfrequencyorslowlyvaryingfrequencies, afilterofferingexcellentattenuationversusfrequencycharacteristics(butwithpoortransientresponse),such asaChebyshevorCauer(elliptical)designispreferred.Ifwewishtogenerateanarbitrarywaveformwithfast riseandfalltimes,ourfilterneedsgoodtransientresponse(butwhichcomeswithrelativelypoorerattenuationversusfrequencycharacteristics)suchasaBesselorlinearphasedesign.Sincewewilldemonstrateboth sinusoidalandarbitrarywaveforms,ourdesignusesButterworthfiltersasacompromise.Butterworthfilters offerreasonabletransientresponse,andacceptableattenuationversusfrequencyperformanceinthestopband. Considerablecautionmustbeappliedwhenchoosingalow-passfiltertofollowaDAC—thisisoneareawhere a“ifalittlebitofstopbandattenuationisgood,alotmustbeevenbetter”approachcancausetrouble. Foroutputsbelow1KHz,weuseaLTC1062fifth-orderswitchedcapacitorlow-passfilterwithacut-off frequencyof1KHzand,foroutputswithamaximumfrequencybetween1KHzand10KHz,asecondorderactiveRClow-passdesignwitha10KHzcut-off.The10KHzfilterisimplementedasamultiple feedbackactiveRCfilterandisinverting. AlthoughoursinewavegeneratordesignfocusesupondirectdigitalsynthesiswithanexternalDAC,infact wehavearichchoiceofmethodstogeneratesinusoidalanalogoutputsignalswithaPIC: • GenerateasquarewavewithMBasic’sSOUNDorPULSOUTproceduresandconvertittoasinewaveform bypassingitthroughsignalprocessingcircuitry. • UseMBasic’sPWMorFREQOUTproceduretogenerateapulsewidthmodulatedwaveform,andconvert thePWMoutputtoananalogsignalwithalow-passfilter. • UseaspecializedPIC,suchasthe16C781and16C782,withabuilt-inDAC.MBasic,however,does notcurrentlysupportthesedevices.
338
Digital-to-AnalogConversion •
UsethehardwarePWMbuiltintomanyPICs,includingthe16F87xfamily.(MBasic’sPWMprocedureis implementedinsoftwareonlyanddoesnotusethePIC’shardwarePWM,supportedbytheHWPMfunction,usedinChapter24formotorspeedcontrol.) • Finally,ourpreferredsolution;useanexternalDACtodirectlyconvertadigitalvaluetoadefinedvoltagelevel.Dependingonthedesiredwaveformpurity,additionalsignalfilteringmaynotberequired. AftercompletingtheDDSdesign,wewillexaminetheseotheroptions.
DACCircuitDesign Figure16-3showstheDACPICconnection.TheTLC7528 DACisaparallel-loaddevice andconnectstoPIC’spins RB0…RB7.Sinceweonlyuse oneofthetwoDACsinthe TLC7528anddonotsharethe RB0…RB7buswithanyother device,wehardconnectthe ChipSelect(pin15),DACA/B (pin6)andWriteEnable(pin 16)toground. TheTLC7528operatesineither “currentmode”or“voltage mode,”thatis,wheretheDAC controlbyteinputsetstheoutputcurrentoroutputvoltage. Incurrentmode,anop-amp Figure16-3:TLC7528DACconnectiontoPIC. current-to-voltageconverter usuallyfollowstheDAC.We’lluseasimplerapproachandoperatetheDACinvoltagemodeandbuffer itsoutputwithaunitygainLF411op-amp.We’llusedthe2840DevelopmentBoard’sVDDasourreference voltage.TheLF411bufferoutputconnectstotwoparallellow-passfilters: 1KHzlow-pass—Weusean LTC1062switchedcapacitorfifth-orderButterworth designasshowninFigure 16-4.Forourpurpose,we cantreattheLTC1062as a“blackbox”thatimplementsafilter.Ourdesign followstheLTC1062data sheetwhichyoushould readbeforestartingconFigure16-4:1KHzlow-passfilter. struction.I’veselecteda 100:1FCLOCK:F3dBratioby connectingtheratiopin(pin4)to+7V.Accordingly,fora1KHzcutoff,weneeda100KHzclock. RatherthanaddanexternalclocksourceweusetheLTC1062’sinternaltimer,trimmingitto100KHz withcapacitor,C2.C2isnominally12pF,butmustbeselectedtoyield100KHzwithyourparticular 339
Chapter16 chipandbreadboardlayout.SelectC2bymeasuringFCLOCKwithacounteroroscilloscopeatpin5or basedonthefilter’sfrequencyresponse.IfyoumeasureFCLOCKatpin5,alowcapacitanceprobeisnecessary,asevena10XprobehasenoughshuntcapacitancetoappreciablyshiftFCLOCK’sfrequency.
TheLTC1062hastwooutputs;pin7isDCaccuratebuthasnobuffering,whilepin8isbuffered,butis subjecttooffseterrorsintheinternalamplifier.TheLTC1062isamixeddigital/analogdevicesowe followitwithasimpleRCfiltertosuppressclockfeedthrough. 10KHzlow-pass—Foroutputfrequencies between1KHzand10KHz,weusea 10KHzcutoffsecondorderButterworth activeRClow-passfilter.Toreducethe needforprecisioncomponents,we’lluse amultiplefeedbackdesign.Figure16-5 showsbothprovidesboththetheoreticallyrequiredcomponentvaluesandthe 5%tolerancecomponentsIusedwhen developingthecircuit.Itisn’tnecessary Figure16-5:10KHzlow-passfilter. touse1%toleranceresistorsand5% tolerancecapacitors,butifyouhavethemavailable,thefilter’sperformancewillbeclosertothedesign objectives.Thedesignisinverting,i.e.,positivevoltagesarechangedtonegativeandviceversa.Finally, notethatourdesignrequiresbothpositiveandnegativepowersupplies.I’veshown±7VsupplyvoltagesinFigure16-5,butyoumaysubstituteanythingfrom±5to±15V.
WhatisDDS? OurobjectiveistoproduceahighqualitysinewaveoutputfromtheDAC.DDS,ourpreferredwaytomeetthis objective,generatesawaveform(often,butnotnecessarily,asinusoid)byoutputtingtheprecomputedvoltage valueofthewaveformataconstanttimeinterval.Ateachtimestep,aDACconvertsthenumericvaluetoa correspondingvoltage.Forthisreason,aDDSisalsoknownasa“numericallycontrolledoscillator.” First,aquickreviewofelementarytrigonometryandsinusoidalwaveforms.Foranytimet(inseconds)the instantaneousvoltageVOUTofasinusoidalwaveformis:
vout=a×sin(2πft)
where
voutistheinstantaneousoutputvoltageandrangesfrom–ato+a
aisthepeakamplitudeinvolts
fisthefrequencyinHz
tistimeinseconds
Fromhighschooltrigonometry,wealsorecallthatsinisarepeatingfunction—thatis,sin(x)=sin(x+2π). Accordingly,ifweknowthevalueforsin(x)overtherange0…x…2πwecanfindsin(y)foranypositive valuey,orindegreessin(x)=sin(x+360°),since2πradiansis360°. Weusuallythinkoftheargumentofthesinefunctionasanangle,suchas“thesineof45°is0.707…”The term2πftisthusrepresentsthephase(angle,inradians)ofthewaveformattimet.Duringaperiodoftime equalto1/f,thewaveformphaseanglegoesthrough2πradians,or360°.Itisoftenfarmoreconvenientto refertothevalueofasinewaveataspecificphaseangle,ratherthanatsomespecifictimeinmicroseconds ormilliseconds. 340
Digital-to-AnalogConversion ConsideraverysimpleDDSsystemusinga3-bitDACandanoutputrangeof0…7V.We’llcalculateour sinewavetargetevery45degreesandstoreinarraySX()theassociatednumericvaluestheDACistooutput at0,45,90…360degrees.Thus,bysteppingSX(i),i=0to8,theDACoutputsonecompletesinecycle. (Sincesin(360°)equalssin(0°),SX(8)=SX(0).Therefore,wemaysimplywraptheindexvariableiaround 7sothereisnoneedforanarrayelementSX(8)orforanygreatervalueofi.Sincethemaximumvalueof thesinefunctionis1,wewillincreasetheresolutionofitsdigitalrepresentationbymultiplyingitby3.(We canalwaysusea1:3voltagedividerontheDAC’soutputifwedesirea1voltmaximum.)Finally,webias thestoredvalueupwardbyadding4,sothatwedonothavetoworryaboutoutputtingnegativevoltages. TheSX(1)value(45°)forexampleiscomputedas3*Sin(45°)+4=6.121.SinceSX()mustbeaninteger 0…7,weroundto6.SX()holdsthefollowingvalues: Index(i)
Angle (Degrees)
Sin(Angle)
0
0
0.000
4
1
45
0.707
6
2
90
1.000
7
3
135
0.707
6
4
180
0.000
4
5
225
–0.707
2
6
270
–1.000
1
7
315
–0.707
2
ArraySx(i)
Figure16-6plotsSX()andweseethatwithasfewaseightsamples,theresultcloselyresemblesacontinuoussinusoidalwhendrawnwithasmoothconnectingcurve,mathematicallyequivalenttopassingitthrough alow-passfilter. SupposethatourelementaryDDSprogramoutputsoneSX()valueevery0.100seconds,andthatwedesireto synthesizea3Hzsinewave.Onecompletesinecycle(360°)requires8indexsteps.Hence,forthreecomplete cycles,werequire24indexstepsor1080°.Sinceoursamplerateis0.1steps/second,weoutputSX()attherate of0.1×24,or2.4indexesperclockstep,thatis,SX(0),SX(2.4),SX(4.8),andsoon.Thisisequivalentto1080° ×0.10,or108.0°phaseadvanceperclockstep.Obviouslywecan’toutputSX(2.4);itmustbeeitherSX(2)or SX(3).Figure16-7illustratesthisprocess.WemayrepresentSX()asacirculararray,sinceSX(8)=SX(0),SX(9) =SX(1),andsoon.Imaginethatevery0.100secondclockstep,thearrowadvancesclockwise108.0°.ThearrayindexvalueitowhichthearrowpointsisthevalueusedinoutputtingSX(i).Figure16-8showstheindexes selectedfortimesteps0,1,2and3,whilethefollowingtableshowsthecompletefirstsecondofoutput.
Figure16-7:Phasewheel. Figure16-6:Sinusoidformedfromeightdata points.
341
Figure16-8:Phasewheel afterthreesteps.
Chapter16 Time (Seconds)
(Phase PhaseAngle Accumulator) PerfectIndex TimeStep (Degrees)
WrapAround IntegerSX(i) Index Index
IndexError
DACOutput
0.000
0
0
0
0
0
0
4
0.100
1
108
2.4
2.4
2
0.4
7
0.200
2
216
4.8
4.8
4
0.8
4
0.300
3
324
7.2
7.2
7
0.2
2
0.400
4
432
9.6
1.6
1
0.6
6
0.500
5
540
12
4
4
0
4
0.600
6
648
14.4
6.4
6
0.4
1
0.700
7
756
16.8
0.8
0
0.8
4
0.800
8
864
19.2
3.2
3
0.2
6
0.900
9
972
21.6
5.6
5
0.6
2
1.000
10
1080
24
0
0
0
4
PlottingtheDACoutputwithasmoothcurveweseea3Hz sinusoidalwaveform.AsFigure16-9shows,evenwithcoarse voltageandphasestepstheDDSoutputafterpassingthrough themathematicalequivalentofalow-passfilterlookslike thesinusoidweexpect.(Pointsinthegraphareconnectedby splineinterpolationwhichcanbeshowntoberelatedtolowpassfilteringinthetimedomain.) Inourhypothetical,thephasestepsizeis108°or2.4units.The totalphaseisheldinthephaseaccumulator.Therelationship amongthevariousparameterswehavediscussedis:
φ STEP =
Fout 2 N FClock
Figure16-9:Simulated3Hzoutput.
φSTEPisthephasestepinindexunits.
FOUTistheoutputfrequencyinHz
FCLOCKisthenumberofoutputsamplespersecond
NisthenumberofbitsrequiredtoholdtheindextoSX().
Apseudo-codealgorithmtooutputour3Hzsinewavewouldbe: Fout=3.00 FClock=10 IndexSize=8 PhaseStep=(Fout*IndexSize)/FClock PhaseAccum=0.0;phaseaccumulatorisafloatingpoint ;variable i=0 Main OutputtotheDACSX(i) PhaseAccum=PhaseAccum+PhaseStep i=INT(PhaseAccumMODIndexSize) Pauseuntilthefull100msperiodisup. GoToMain
TheMODor“modulus”functionisMBasic’s//orremainderoperator.(MBasicdoesn’timplement//for floatingpointnumbers,sotherealcodegetsmessierthanthepseudo-codeindicates.)
342
Digital-to-AnalogConversion Thisalgorithm,althoughcorrectfromacomputationalprospective,hasonemajorpracticalproblem—floatingpointarithmeticoperationsareslowinaPICandunfortunatelyappearinsidethemainloop.Microchip didnotdesignitsmidrangePICproductstobemathematicalpowerhousesnortobedigitalsignalprocessing devices.It’satestamenttotheinherentpowerinaPICandtoBasicMicro’sMBasiccompilerthatwecan obtainusefulresultsatallthisapproach.Let’slookatworkingcodeimplementingthissimplealgorithm. Program16-1 ;Program16-1 ;Constants ;------------------------Interval Con StepsPerCycle Con
515 32
;Variables ;------------------------i Var OutIndex Var Sx Var Accum Var Freq Var FStep Var PhaseAdder Var Ftemp Var
Byte Byte Byte(32) Word Float Float Word Float
;uSecsforoutput ;stepsper1completecycle
;countervariable ;lookupindex ;holdssinetable ;phaseaccumulator ;desiredfrequency ;realphasestep ;stepsadded ;debuggingvariable
;Initialization ;----------------------Clear ;Preloadsinelookuptable Fori=0to31 Sx(i)=Sin(i*8)+128 Next ;PortBisconnectedtoDAC Fori=B0toB7 Outputi Lowi Next ;C0usedforo’scopetiming OutputC0 LowC0 ;wehardcodeinthedesiredoutputfreq ;inarealprogram,thismightbe ;enteredbyRS232,keypadorswitches Freq=60.0 ;Hz ;calculatethenumberofstepspersecond FStep=ToFloat(StepsPerCycle)*(Freq*ToFloatInterval) FStep=FStep/1000000.0 FTemp=(FStep*256.0) PhaseAdder=ToIntFTemp Main ;---------GoSubOutToPort GoToMain OutToPort ;---------- ;470uSexecutiontimenotcountingoverhead bsf PortC,0 ;advancephaseaccumulator Accum=Accum+PhaseAdder ;lookonlyat“integer”partofAccum ;andMOD32the“integer”part OutIndex=Accum.HighByte//32 PortB=Sx(OutIndex) bcf PortC,0 Return End
343
Chapter16 Program16-1followsthepseudo-codewithsomeimportantspeed-upfactors: SXarray—ThearraySXis32elementslong,anditsvaluesarefilledthroughMBasic’sSINfunction.MBasic’sSINfunction’sargumentis0…255,i.e,itdividesthecircleinto256angularunitsanditreturns signedbytevaluesfrom–127…128.Hence,whenfillingSX(i)overtherange0...31,wemultiplyi*8 andadd127toshifttheoutputto0…255. Calculatethephaseadvance—Wefirstcalculatethefloatingpointphaseadvance. FStep=ToFloat(StepsPerCycle)*(Freq*ToFloatInterval) FStep=FStep/1000000.0
Thiscomputationfollowsthedefinitionofphaseadvancedevelopedearlier.Ratherthantryingtomake Program16-1outputsamplevaluesatapre-determinedinterval,wewritethecodeandacceptwhatevertime intervalresults—wedetermineIntervalbymeasuringtheexecutiontimeofthemainprogramloopin microsecondsandthendefineitasaconstant: Interval
Con
515
;uSecsforoutput
YoucanusetheexecutiontimerroutineseeninProgram14-1amongothers,oryoucanmeasuretheoutput frequencyandadjustIntervaluntilthemeasuredfrequencymatchesthetargetfrequency.Imeasured Intervalas515µs,butyourtimemaydiffer,asthisvalueisbasedonaprereleaseversionofMBasic’s version5.3.0.0compiler.SinceIntervalisinmicroseconds,itisnecessarytodivideby1,000,000to converttoseconds.And,sincefrequencyis1/intervalinsteadofdividingbyFclock,wemultiplyby1/Fclock,a mathematicallyidenticaloperation. Afterthesetwolinesofcodehavebeenexecuted,FSTEPequals0.98880. Integerconversion—Astandardfloatingpointphaseaccumulatorincursasignificantspeedpenalty.For improvedexecutionspeed,we’llkeepthephaseaccumulatorinaword(16-bit)variableandworkwith onlyintegerarithmeticinsidetimesensitiveprogramloops.Todothis,weconsiderthe16-bitphaseaccumulatorvariableAccumtoconsistoftwo8-bithalves: Accum.HighByte IntegerValue
Accum.LowByte FractionalValue
Thefractionalcomponentisinunitsof1/256.Weconvertthefloatingpointaccumulatorvaluetothis16-bit integer/fractionformbymultiplyingFSTEP*256andconvertingtheproducttoaninteger. FTemp=(FStep*256.0) PhaseAdder=ToIntFTemp
Inthiscase,PhaseAddercontainsInt(0.98880*256.0),or253,representing0+253/256.IfFstephad beengreaterthan1,say1.23,theresultwouldhavebeen314.However,PhaseAdder’slowbytewouldstill containthe1/256fractionalvalueapproximating0.23.(Notconvinced?314-256=58;Int(0.23*256)= 58.)Inthiscase,wewouldunderstandPhaseAdder’scontentstobe1+58/256,orapproximately1.23. Ifthephaseaccumulatorhadfivedecimaldigitsresolution,afterthesecondstepitwouldcontain0.98880+ 0.98880,or1.9776.Our16-bitphaseaccumulatorAccumwillcontain(253+253)/256,or1.9766,a0.05% error. Generationloop—Herewegeneratethenextoutputindexbyaddingthephasesteptothecurrentphaseaccumulatorvalue. Accum=Accum+PhaseAdder
TherolloverasAccumexceeds65535isnotofconcernsinceweuserelativephase. ;lookonlyat“integer”partofAccum ;andMOD32the“integer”part OutIndex=Accum.HighByte//32 PortB=Sx(OutIndex)
344
Digital-to-AnalogConversion SinceSX(i)hasonly32elements,wemustwrapthe“integer”partofAccum,thatis,Accum.HighByte,around32. Thisisconvenientlydonethroughremainderdivisionwith the//32operator.(Atthecostofamorecomplexexample, wecouldhavemadethephaseaccumulatormoreaccurateby makingthefractionalpartthelower11bitsofAccum,andthe integerparttheupper5bits,thuspreservingthefull16bits forusefuldata.Asitis,thephaseaccumulatoriseffectively 13bitswide,not16.) Figure16-10showstheDACoutput(Ch1)andtheoutput followingthe1KHzlow-passfilter(Ch2).Theresultisa quiteacceptable60Hzwaveform.
Figure16-10:60HzoutputfromProgram16-1.
TheproblemswithProgram16-1centeronexecutionspeed. Chan1:DACOutput;Chan2:Following1KHz low-passfilter. Theoutputintervalis515µs,correspondingtoFclock= 1.942KHz.Nyquist’ssamplingrulewouldthuslimitour maximumoutputfrequencytoFclock/2or970Hz.And,MBasiccan’tbedependedupontogeneratejitterlesstiminginaGoToorGoSubloop,with±2µsvariationsintimingobserved.Formanypurposes,acouple microsecondjitterinlooptimingisimmaterial,butinDDS,clockjittertranslatesintofrequencyjitterand unwantednoisemodulationandsidebands. Program16-2amelioratesourspeedconcernsbycodingalltimesensitiveelementsinassemblerandrelying uponatimer-driveninterruptclocktoestablishthesampleinterval.UsinganISRASMinterruptprocedure doesnottotallyremovejitter,butreducesittolessthan1µs.And,witha20MHzoscillatorweareableto operatewitha80KHzFclock,permittingupto40KHzoutput.We’llalsousea256elementwaveform table. Program16-2 ;Program16-2 ;ProgramSimplePhaseAccum-7.bas ;Demonstratetheprinciplesbehind ;aDDSsinewavesystemusingaPIC ;Constants ;------------------------Interval Con 20 ;uSecsforoutput StepsPerCycle Con 256 ;stepsper1completecycle ;Intervalbetweenstepsinus.Can’tbelessthan13 ;becausedelayinISRoverhead&ISRprocedure T2Post1 Con %00000000 T2Post2 Con %00001000 T2Post3 Con %00010000 T2Post4 Con %00011000 T2Post5 Con %00100000 T2Post6 Con %00101000 T2Post7 Con %00110000 T2Post8 Con %00111000 T2Post9 Con %01000000 T2Post10 Con %01001000 T2Post11 Con %01010000 T2Post12 Con %01011000 T2Post13 Con %01100000 T2Post14 Con %01101000 T2Post15 Con %01110000 T2Post16 Con %01111000 ;Notethatbit3isTmr2Onandisset ;tobeON T2Pre1 Con %00000100
345
Chapter16 T2Pre4 Con %00000101 T2Pre16 Con %00000111 ;Dividetheclockby5 ;Fora20MHzPICclockTimer2 ;PreloadisdirectlyinuSec CounterSetupCon T2Post5+T2Pre1 ;Variables ;------------------------i Var Byte ;countervariable Accum Var Word ;phaseaccumulator Freq Var Float ;desiredfrequency FStep Var Float ;realphasestep PhaseAdder Var Word ;stepsadded Ftemp Var Float ;debuggingvariable ;Initialization ;----------------------Clear ;Minfreq=Samplespersec/AccumSize ;=50000/2**16=MinFreq ;Minimumfrequency0.762Hzfor20ussteps ;Defultgenerationfrequency Freq=1000.0 ;Hz ;PortBisconnectedtoDAC Fori=B0toB7 Outputi Lowi Next ;C0usedforo’scopetiming OutputC0 LowC0 ;C1usedforprograminterruptforexternal ;datainputtobeaddedifdesired InputC1 ;setupfrequencyrelatedelements GoSubSetUp ;Timer2Setup ;---------------------------------------------------------------‘Don’tforgetthe-1here,asCounter2startsat00 SetTmr2CounterSetup,Interval-1 peie=1 ;peripheralinterruptenable(INTCON,bit6[Bank0/1/2/3]) gie=1 ;globalinterruptenable(INTCON,bit7[Bank0/1/2/3]) tmr2ie=1 ;EnableTmr2Int ;EnableTmr2Int ;================================================================ israsm ;================================================================ { bcf PIR1,tmr2if ;resettimer2interruptflag bsf PortC,0 ;flagforo’scopetiming ;advancephaseaccumulator ;Accum=Accum+PhaseAdder ;------------------------- ;16bitaddfromPICMicroMicrocontrollerPocketReference ; banksel PhaseAdder movf (PhaseAdder&0x7F)+1,w ;addthehighbytes banksel Accum addwf (Accum&0x7F)+1,f banksel PhaseAdder movf (PhaseAdder&0x7F),w ;addthelowbytes banksel Accum addwf (Accum&0x7F),f btfsc STATUS,C ;add1tohighbytesifcarry incf (Accum&0x7F)+1,f banksel PortC bcf PortC,0 ;foro’scopetiming ;lookonlyat“integer”partofAccum
346
Digital-to-AnalogConversion ;PortB=Sx(OutIndex) movlw HIGHGetSine ;w=highbytetablelocation movwf PCLATH ;PCLATHhashighbyteoftable movlw LOW(GetSine+1) ;firstactualdatapoint banksel Accum addwf (Accum&0x7F)+1,w ;offsetadrofdatapoint btfsc STATUS,C Incf PCLATH,f call GetSine ;whatissinevalue banksel PortB movwf PortB ;outputittoPortB GoTo EndRoutine GetSine movwfPCL retlw128 retlw131 retlw134 <<note–remainderofGetSinetableomittedfromthislisting>> <<seeProgram16-2.basforall256tablevalues>> EndRoutine bankselPortC ;bcf PortC,0 } ;---------Main ;--------- IfPortC.Bit1=0Then tmr2on=0 GoSubGetNewFreq GoSubSetUp ELSE tmr2on=1 EndIf GoToMain SetUp ;--------------- ;wehardcodeinthedesiredoutputfreq ;inarealprogram,thismightbe ;enteredbyRS232,keypadorswitches ;calculatethenumberofstepspersecond FStep=ToFloat(StepsPerCycle)*(Freq*ToFloatInterval) FStep=FStep/1000000.0 FTemp=(FStep*256.0)+0.50 PhaseAdder=ToIntFTemp Return GetNewFreq ;--------------;Subroutinetogetthefrequencyfromuserkeypad,switches, ;RS-232,etccanbeplacedhere.justputdummyinnow Freq=440.0 ;Hz Return End
Constants—Asusual,westartdefiningnecessaryconstants.TheequivalentofSX(i)is256elementslong, soStepsPerCycleisdefinedas256.Theinterruptistobecalledviatimer2every20µs,thevalueto whichIntervalisdefined. SomeversionsofMBasichaveerroneousdefinitionsofcertainofthetimer2predefinedconstants,sowedefineourowntimer2constants.Timer2’sclocksourcerunsatFosc/4,or5MHzfora20MHzmasterclock. Bysettingthepostscalerat5,eachtimercountcorrespondsto1µs. Variables—WedefineawordvariableAccumasthephaseaccumulatorandawordvariablePhaseAdder toholdthephasestepinterval.Threefloatingpointvariables,Freq(frequency),Fstep(floatingpoint phasestep)andFtemp(atemporaryvariable)aredeclared,asfloatingpointvariables.
347
Chapter16 Initialization—Program16-2hasnoprovisionforfrequencyentryotherthanthevaluehardcodedinat initialization,althoughahookisprovidedtoapossiblefrequencyentryprocedure.ChangetheFreq= 1000.0lineasdesired. InDDS,theoutputfrequencyFOUTPUTisconstrainedtobeanintegermultipleoftheminimumfrequencystep. F FSTEP = CLOCK 2N Nisthenumberofbitsinthephaseaccumulator,16inthisprogram
FCLOCKisthesamplerate,50,000Hzfora20µsinterval
Hence, FOUTPUT = kFSTEP
Wherek=1,2…2N-1
Fora20µssampleintervalanda16-bitaccumulator,FSTEPis50,000/65536,or0.76294Hz.Byincreasing Interval,i.e.,slowingtheoutputclock,thefrequencystepmaybereduced.However,themaximumpossiblefrequencywillcorrespondinglybechanged.If,forexample,wedecreaseFCLOCKto20KHzbysetting IntervalCon50,wemaysetthefrequencyoutputinstepsof0.3Hz.However,themaximumoutput frequencywillbereducedto10KHz. WecalculatethephasestepinthesubroutineSetUpandplacethisinitializationcodeinasubroutinesothat itmaybecalledasnecessaryforasthefrequencyoutputischanged. SubroutineSetUp—SetUpreplicatesthecorrespondingcodeinProgram16-1. Timer2Setup—Thiscodeenablesallinterrupts(GIE)andperipheralinterrupts(PEIE),ofwhichtimer2 interruptisasubset.SeeChapter15,“InterruptHandlingandTimersinAssembly.”Finally,timer2is enabled. ISRASM—ThecodeintheinterruptserviceroutineisanassemblerversionofthecodefoundinProgram 16-1,withlimitedchanges.ThecorrespondingMBasicstatementsappearascomments.PortC,bit0is usedtomeasuretheexecutionspeedofcertainassemblerstatementsbyanexternaloscilloscopeand associatedbitsetandbitclearstatements(bsf/bcfPortC,0)maybeomittediftiminginformationis ofnoconcern. Insteadofstoringthesinelook-upvaluesinanMBasicarraysuchasSX(i)inProgram16-1,wehave implementedastandard“jumptable”asdiscussedatChapter14.Jumptableaccessloadsthewregisterwith thedesiredindexiandprogramexecutionjumpstotheithretlwstatementfollowingthestartofthetable. Theretlwstatementthenreturnstheassociatedliteralvalueinthewregister.WethensendthereturnedliteralvaluetoPortBwhereitisconvertedtoavoltagebytheDAC.Thisprocessisthefunctionalequivalent ofPortB=SX(i)butexecutesperhaps100timesfaster.Theindexi,ofcourse,isactuallythehighbyte ofAccum. Wehaveimplementedthesinetableinthesimplestformusingall256elementsbutitcouldbereducedto 64elementsthroughtwotrigonometricidentities: • Sin(x)wherexisintherange90°…180°equalssin(180°–x). • Sin(x)wherexisintherange180°…360°equals–sin(x–180°). Theextracomputationsassociatedwiththeseidentitieswouldobscuretheprinciplehoweverandwehave amplecodespace.
348
Digital-to-AnalogConversion Main—Mainisasimpleendlessloop,withacheckofPortC,bit1.IfPortC,bit1islow,programexecutionjumpstothesubroutineGetNewFreq.Thisservesasanexampleofhowasubroutinepermitting theusertoenteranewfrequencymightbeaddedtoProgram16-2.Followingnewfrequencyentry,the newphaseadvanceiscalculatedbycallingsubroutineSetUp. SubroutineGetNewFreq—Atthepresent,GetNewFreqisadummysubroutine.Itsimplysubstitutesa newpre-determinedfrequencyfortheoneestablishedattheinitializationsectionoftheprogram.Tobe useful,thissubroutinecould,forexample,readasetofthumb-wheelswitches,keypadpresses,oran RS-232input,toallowtheusertoselectanewoutputfrequency.
PuttingItThroughItsPaces ItestedProgram16-2foroutputatnominalfrequenciesof100Hz,1000Hzand10000Hz.Thefiguresin thischapterareforanintervalof10µsundertheMBasic5.2.1.1versionofProgram16-2.I’vemodifiedthis chapter’sISRASMinterrupthandlercodetobelessdependentuponbank0registeraccess,andthusmore version5.3.0.0friendly,buttheaddedbankselectionoverheadincreasestheminimumintervalinProgram 16-2toabout15µs.Fortheversion5.2.1.1code,witha10µsoutputinterval,thefrequencyincrementis 1.526Hz,andthecorrespondingactualoutputfrequenciesare100.7Hz,999.4Hzand10000.6Hz,subject totheresidualerrorfromthePIC’s20MHzresonator. I’vecapturedtwooscilloscopewaveformsforeachoutputfrequency,alongwithspectrumanalysisplots. Channel1istherawDACoutput,whilechannel2istheoutputofthelow-passfilter,theLTC1062inthe caseof100Hzand1KHznominalfrequenciesandthetwo-poleactivelow-passinthecaseof10KHz nominalfrequency. Forcomparison,Figures16-11and16-12showa1KHzsinusoidalgeneratedbyananalogfunctiongenerator.Althoughtheanalogoscillatorprovidesalownoiseoutput,itsuffersfromdrift,tuningprecisionand otherproblemsthathaveleadtoincreasingDDSuse.EventhesimplebreadboardDDSdeviceinthischapterisfarmorestablethantheanalogfunctiongenerator.WhethertheDDS’sunwantedspurioussidebands, harmonicsandnoiseareacceptabledependsontheapplication.And,weshouldnotforgetthatacommercial DDSchipshave32bitorlargerphaseaccumulatorsthatsignificantlyreducemanyoftheartifactsseenin oursimpledesign.
Figure16-12:Referencespectrumview1KHzsine waveformfromanalogfunctiongenerator.
Figures16-11:Reference1KHzsinewaveform fromanalogfunctiongenerator.
349
Chapter16 Note:Thefollowinggraphicshavenoexplicittextreferenceotherthanthepreviouspage.
Figure 16-13: 1 KHz DDS Output. Ch1: DAC Output;Ch2:following1KHzlow-passfilter.
Figure16-14:1KHzDDS.Spectrumanalysisof DACoutput.
Figure16-15:1KHzDDS.SpectrumAnalysisof DACoutputfollowinglow-passfilter.Notefilter feed-throughinthebreadboardlayoutisseen athigherfrequencies.
Figure16-16:100HzDDS.Ch1:DACOutput; Ch2:following1KHzlow-passfilter.
Figure16-17:100HzDDS.Spectrumanalysis ofDACoutput.
Figure16-18:100HzDDS.Spectrumsnalysisof1KHz low-passfilteroutput.Sincethe100Hzfundamental iswellbelowthefiltercut-offfrequency,proportional harmonicsuppressionismuchlessthanseenforthe 1KHzDDSsignal.
350
Digital-to-AnalogConversion
Figure16-19:10KHzDDS.Ch1:DACOutput; Ch2:Following10KHzlow-passfilter.
Figure 16-20: 100 Hz DDS. Spectrum analysis ofDACoutput.
Figure16-21:10KHzDDS.SpectrumAnalysisof10 KHzlow-passfilteroutput.Thislow-passisasecond order filter and accordingly rolls off slower with frequencythanthefifth-order1KHzlow-pass.
Figure 16-22: 1 KHz DDS output following 1 KHzlow-passfilter.Spectrumanalysiscentered onsignal.Closeinsidebandsareapproximately –32dBc.
Figure 16-23: Expanded view of 1 KHz DDS outputfollowing1KHzlow-passfilter.Spectrum analysiscenteredonsignal.Closeinsidebandsare approximately±20Hzfromthe1KHzsignal.
Figure16-24:10KHzDDSoutputfollowing10 KHzlow-passfilter.Spectrumanalysiscentered onsignal.
351
Chapter16 Insteadofusingthejumptabletodefineasinusoidalwaveform,itcouldjustaseasilydefineanyarbitrary waveformthatcanfitinto256segments,suchastheoneshowninFigure16-25.Whenacorresponding retlwtableissubstitutedinProgram16-2,theDACoutputcanbeseenatFigures16-26(10KHzlow-pass filter)and16-27(1KHzlow-passfilter). Whenclockedoutat25µs/step,thearbitrarywaveformhasmanyfasttransitionsthatrequirehighfrequency responsebeaccuratelyreproduced,andthe1KHzlow-passfilteredoutputfailstoaccuratelymimicour desiredwaveform.Increasingtheoutputbandwidthwitha10KHzlow-passfilterallowsmuchbetterreproductionofthewaveform’stransitions.(The10KHzlow-passfilterisinverting;hencethefilteredwaveform is“upsidedown”comparedwiththeDACoutputinFigure16-26.)
Figure 16-25: Arbitrary waveform designed in Excelandloadedintotheretlwjumptable.
Figure16-26:Arbitrarysignaloutput.Ch1:DAC Output;Ch2:Following10KHzlow-passfilter. Note that the 10 KHz filter is inverting. DAC clockedat25µs/step.
AlternativeAnalogOutputSolutions We’llcloseChapter16withalookatsomeof MBasic’sbuilt-inwaveformoutputfunctions—PWM, FreqOut,Sound,andPulsOut.We’llthenwritea simpleprogramtotesteachofthesefourfunctions. (MBasic’shardwarepulsewidthmodulationfunction, HWPM,iscoveredinChapter24andwon’tbeconsideredhere.NorwillweexaminetheDTMFfunctions, DTMFandDTMF2astheyarespecializedfunctionsto generatetouchtonedialingfrequencies.)
PulseWidthModulation MBasic’sPWMandFREQOUTproceduresallowaPIC Figure16-27:Arbitrarysignaloutput.Ch1:DAC toproduceananalogoutputvoltagewithoutanexteroutput; Ch2: Following 1 KHz low-pass filter. nalDACthroughpulsewidthmodulation,orPWM, Notethe1KHzfiltermasksallthehighfrequency techniques.FREQOUTisaspecialapplicationofPWM components of the arbitrary waveform. DAC thatoutputsaPWM-basedsinewave.PWMsimuclockedat25µs/step. latesananalogsignalbyrapidlytogglinganoutputpin between0andVDDandisessentiallya1-bitDAC.Theoff/onoutputisaveragedbyalow-passfilter—evenasimple RCnetwork—intoasmoothedoutputwheretheindividualpulsesareinconsequential.Forahighervoltage,longer VDDpulsesaresent;foralowervoltageshorter0pulsesaresent.The“wider”and“shorter”pulsesareproducedby consolidatingmultipleshortpulses. 352
Digital-to-AnalogConversion MBasic’sPWMprocedurehasthefollowinginvocation: PWMpin,duty,cycles Pinisaconstantspecifyingtheoutputpintobeused. Dutyisaconstantorvariablespecifyingthedesiredoutputlevelwithapermissiblevaluebetween0
and255.0representsapproximately0volts,255isapproximatelyVDD. Cyclesisaconstantorvariable(32-bit)specifyingthedurationoftheoutputinmicrosecondsfrom
about24µsto232µs,permittingamaximumdurationofapproximately4295seconds. Figures16-28,16-29and16-30showthePWMoutput(Ch1istherawPWMoutputfromthePIC’sC1pin; Ch2isthePWMoutputfollowinga4.7k/0.033µFRClow-passfilterasshowninFigure16-35)forDuty valuesof240,128and16respectively.Eachindividualpulseis4µsduration.(Figure16-29hasanexpandedtimeaxiscomparedwiththeothertwofigures.)AstheratioofVDDpulsesto0Vpulseschange,the filteredoutputvoltagetracksquitewell.Weseelinearityproblems,however,neareitherendoftheoutput scale,asalowonthePIC’soutputpinis0.6V,not0VandahighisVDD–0.7V,notVDD.Ifabsolutelynecessary,thesefigurescouldbeimprovedthroughoutboardcircuitry.
Figure 16-29: PWM 128 Output. Ch1: PWM Output unfiltered; Ch2: PWM following RC filter.
Figure 16-28: PWM 240 Output. Ch1: PWM Output unfiltered; Ch2: PWM following RC filter.
Toproduceatimevaryinganalogoutput,therefore, wecouldusetheconceptsdevelopedfortheexternal DACandinsteadusethePWMprocedure.Toproduce asawtoothrampoutput,clockedoutatonevoltage steppermillisecond,forexample,wemightusethe followingcode: Fori=16to240 PWMC1,i,1000 Next
Althoughwecouldusethisconceptinconjunction withProgram16-1toproduceaPWM-basedsine waveoutput,it’smucheasiertotakeadvantageof MBasic’sFREQOUTprocedureasitperformsexactly thatfunction.FreqOutisinvokedas:
353
Figure 16-30: PWM 16 Output. Ch1: PWM Output unfiltered; Ch2: PWM following RC filter.
Chapter16 FREQOUTPin,Duration,Freq1,{Freq2} Pinisaconstantspecifyingtheoutputpintobeused. Durationisaconstantorvariable(32-bit)specifyingthedurationoftheoutputforeachfrequency
argument,inunitsof0.5microsecondsfromabout24unitsto232units,permittingamaximum durationofapproximately2147seconds. Freq1isaconstantorvariablespecifyingthefrequencyinHzoftheoutputsinewavefrom0to32767Hz. Freq2isaconstantorvariablespecifyingthefrequencyinHzofanoptionalsecondsimultaneousoutputsinewavefrom0to32767Hz.. Figure16-31showstherawPWMoutput(Ch1)andtheRCfiltered(Ch2)1KHzsinegeneratedbyFREQOUT C1,65535,1000.ThesimpleRCfiltertakesoutmost,butnotallthehighfrequencycomponentofthe individualPWMpulses. ComparingthespectrumoftherawPWMoutputshowninFigure16-32withthatoftheRCfilteredoutput ofFigure16-33weseetheRCfilteryieldsasignificantreductioninbroadbandnoiseandharmonics.Of course,awelldesignedprintedcircuitboardwithagoodgroundplanewillproducemuchlessnoisethan ourquickanddirtysolderlessbreadboardtrial.
Figure16-31:FreqOut1000Hz.Ch1:RawPWM output;Ch2:RCFilteredoutput.
Figure16-32:1KHzFreqOutSpectrumanalysis rawPWMoutput.
Figure 16-33: 1 KHz FreqOut Spectrum analysis PWM output following RC lowpassfilter.
Figure16-34:FreqOut25KHz.Ch1:RawPWM output;Ch2:RCfilteredoutput.
354
Digital-to-AnalogConversion AswetrytoproducehigherfrequencyoutputswithFreqOut,however,theindividual4µspulsesbecomea greaterproportionofthedesiredwaveform.At1KHz,eachsinewaveoutputcyclecomprises2504µs-wide PWMpulses.A25KHzoutput,however,eachoutputsinewaveisconstructedfromonly10PWMpulses withtheresultshowninFigure16-34.(For25KHzoutputtheRCfiltervaluesare4.7kand0.001µF.). Ifourrequirementsarenotoverlycritical,FreqOutandPWMshouldnotberejected.Combinedwithahigh qualitylow-passfilter,suchastheLTC1062fifth-orderdevice,quitedecentoutputqualitycanbeachieved. Iflesserqualitycanbeaccepted,averysimpleRCfiltercanbeused,oroneop-ampmightbeconfiguredas atwo-polelow-passfilter.And,onlyoneoutputpinisrequiredtosupportFreqOutandPWM.
CalculatingRCFilterValues Figure16-35showsthesimpleRClow-passfilterwewilluse.Usuallywedesignsothatthe3dBcutoff frequencyoftheRCfilterequalsthehighestfrequencywaveformtobegenerated.Fromelementarycircuit analysis,weknowthe–3dBfrequencyofanRCnetworkis: 1 f3 dB = 2 πRC fisthefrequencyinHz Ristheresistanceinohms Cisthecapacitanceinfarads WearbitrarilyselectRas4.7k,andcalculateCforaf3dBof1000Hz: 1 1 C= = = 33.9 × 10 −9 F or 0.0339µF 2 πf3 dB R 2 × 3.14159 × 1000 × 4700 Theneareststandardvalueis0.033µFor33nF.Figure16-36illustratesthefrequencyresponseofthisRCfilter.
Figure16-35:RClow-passfilter.
Figure16-36:RCfilterfrequencyresponse.
SoundandPulsOutSolutions ThelasttwoanalogoutputproceduresweconsiderareMBasic’sPulsOutandSoundprocedures.Aswith therelationshipbetweenPWMandFreqOut,PulsOutisagenericprocedureandSoundprepackagesthe codenecessarytoproduceanaudiofrequencyrangeoutputusingPulsOuttechniques.Wewillconcentrate upontheSoundprocedure.
355
Chapter16 Soundgeneratesoneoraseriesofoutputsandisinvokedas:
SoundPin,[duration1\note1,duration2\note2,…durationN\noteN] Pinisaconstantspecifyingtheoutputpintobeused. DurationXisaconstantorvariable(32-bit)specifyingthedurationoftheoutputforxthfrequency
argument,inmicrosecondsfromabout24µsto232µs,permittingamaximumdurationofapproximately4295seconds. NoteXisaconstantorvariablespecifyingthefrequencyinHzfrom0to32767forthexthoutput.A0 noteindicatesnooutput. Unfortunately,SoundgeneratesasquarewaveatthefrequencyNote.AnRCfilterdoesn’tcomecloseto transformingthesquarewaveintoasine,asillustratedinFigure16-37.Thebestthatcanbesaidforthe RCfilteredwaveformseeninCh.2ofthefigureisthatitisbetterthantheunfilteredwaveform.Ifwefeed thesquarewaveintoanLTC1062fifth-orderlow-passfilter,ofcourse,weobtainahighquality,cleansine output,asshowninFigure16-38.
Figure16-37:Sound1000Hz.Ch1:RawSound output;Ch2:FollowingRCfilter.
Figure16-38:Sound1000Hz.Ch1:RawSound output; Ch2: Following LTC1062 Butterworth low-passfilter.
Ifourobjectistoproduceasineoutputoveralimitedfrequencyrangeandatfixedamplitude,theSound procedurefollowedbyamultipolelow-passfilterisquiteviable.Ithasthreemajordrawbacks,however: • TheoutputlevelisnotcontrolledbySound.Ifsoftware levelcontrolisdesiredanexternaldevice,suchasa digitalpotentiometer,isrequired. • Astheoutputfrequencydropsbelowaboutone-third thelow-passfiltercornerfrequencydistortionincreases significantly,sinceasquarewave’sfirstsignificant harmonicisthethird.Thus,awiderangefrequency generatorwillrequireeitheratrackingorswitch-selectedlow-passfilter,oracceptanceofhighdistortionfor lowerfrequencysignals.See,forexample,Figure16-39 showingtheresultofa250HzSoundprocedurewitha1 KHzlow-passfilter. • Ifwearegoingtothetroubleofaddinganexpensive Figure16-39:Sound250Hz.Ch1:RawSound low-passfilter,whynotoptforaPWMoutputusingthe Output; Ch 2: Following LTC062 fifth-order Butterworthlow-passfilter. FreqOutprocedure? 356
Digital-to-AnalogConversion TheseproblemslimittheusefulnessoftheSoundproceduretoalerttonesorotheruncriticalapplications,or tothoseapplicationswhereasquarewaveisdesired.
SampleProgram Program16-3illustrateshowthesealternativeanalogoutputproceduresareused.Bychangingthedefinition ofSoundMode,theprogramwillbranchtooneofthefouralternativeoutputs.AlloutputsareatpinC1.All branchesoutputthefrequencyfreq,exceptPWMProc,whichoutputsastaticPWMsignalwithaveragelevel definedbyPwmValue.SincePulsOutonlydefinesthedurationofthehighleveloutput,ThePulsOutProc usesthePauseusproceduretoproduceanoutputsignalwithequaldurationhighandlowoutputs.Thelow outputdurationalsoincludestheoverheadassociatedwiththeGoToandBranchcontrolelements,sowe subtractanoffsetof170µstothePauseusprocedure.Ifthehighandlowportionsoftheoutputarenotof equalduration,significantdistortionofsineoutputresults.CompareFigures16-40and16-41.
Figure 16-41: PulsOut 1 KHz with equal 59% low/41% low. Ch1: Raw Sound Output; Ch 2: FollowingLTC062fifth-orderButterworthlowpassfilter.
Figure16-40:PulsOut1KHzwithequalhigh/low periods.Ch1:RawSoundOutput;Ch2:Following LTC062fifth-orderButterworthlow-passfilter.
Program16-3 ;Program16-3 ;Constants ;-------------------;changethistoselect ;generationmethod ;ChangeSoundModetousedesired ;methodofgeneratingoutput SoundMode Con 1 OutPin Con C1 Freq Con 1000 Period Con 1000000/Freq;periodinus HalfPeriod Con 500000/Freq PWMValue Con 128 ;DCAvgoutputdesired ;Initialize ;----------OutputOutPin LowOutPin Main ;-------BranchSoundMode,[SoundProc,PulsOutProc,PWMProc,FreqOutProc] SoundProc ;---------
;UsesSoundprocedure
357
Chapter16 SoundOutPin,[1000000\Freq] GoToMain PulsOutProc ;UsesPulsOutprocedure ;---------- PulsOutOutPin,HalfPeriod ;nowpauseforsametime ;beausethepausetimeincludestheGoTo ;wemustsubtract170uStoallowfor ;theGoTooverhead PauseUsHalfPeriod-170 GoToMain PWMProc ;---------- ;Outputasteady-statePWMvalue PWMOutPin,PwmValue,65535 GoToMain FreqOutProc ;----------FreqOutOutPin,10000000,Freq GoToMain End;
;removeextra0whenFreqOutfixed
Program16-3requireslittleanalysis.BychangingthevalueoftheconstantSoundMode,programexecution jumpstooneoffourpossibleoutputsubroutines,eachofwhichdemonstratesoneofthefourprocedures we’veanalyzedearlier.
IdeasforModificationstoProgramsandCircuits • • • • • • • • • •
Replacethe1KHzswitchedcapacitorfilterwithanactivelow-passfilter. Cascadethefilters,withtheDACoutputgoingfirsttothe10KHzLPF,andtheoutputofthatfilterto theinputofthe1KHzfilter. Addtheabilityoftheusertoinputthedesiredfrequency. UsethesecondDACoutputasanamplitudeinputtothefirstDAC.Thiswillallowtheoutputlevelof theDACNo.1tobeunderprogramcontrol.ApplyadifferentfrequencytoeachDACandobservethe outputisanamplitudemodulatedsignal. Allowtheusertosetthelevelviaswitchesorotherinputdevices. UsetwoDACstooutputtwodifferentfrequenciesandcombinethem. Experimentmorewitharbitrarywaveforms HaveFCLOCKchangeproportionallytofrequency Addaprecisionvoltagereference. Shiftbetweentwofrequenciesdependinguponthestatusofaninputpin.Thisisamodulationtechnique knownasfrequencyshiftkeying.Shiftthephaseofasinglefrequencyoutput(phaseshiftkeying).
References [16-1]
Brokaw,PaulA.,AnalogSignal-HandlingforHighSpeedandAccuracy,AnalogDevices,Inc.ApplicationNoteAN-342(undated). [16-2] Buchanan,David,ChoosingDACsforDirectDigitalSynthesis,AnalogDevices,Inc.ApplicationNote AN-237(undated). [16-3] TLC7528C,TLC7528E,TLC7528IDual8-BitMultiplyingDigital-to-AnalogConverters,TexasInstruments,Inc.,DocumentNo.SLAS062C(Rev.Sept2000). [16-4] Smith,StevenW.TheScientistandEngineer’sGuidetoDigitalSignalProcessing,CaliforniaTechnicalPublishing(1999).Note:ThisbookisavailableforfreedownloadingontheInternetathttp://www. DSPguide.com.
358
Digital-to-AnalogConversion [16-5]
Zverev,AnatolI.HandbookofFilterSynthesis,JohnWiley&Sons(1967). Lancaster,Don,Active-FilterCookbook2ndedition,Butterworth-Heinemann,(1996). [16-7] LTC10625thOrderLowpassFilter,LinearTechnology,Inc.,(undated). [16-8] MAX280/MXL10625thOrdeer,ZeroDCError,LowpassFilter,MaximIntegratedProducts(August 1995)(Note:bothLinearTechnologyandMaximdatasheetsmustbeconsultedtoobtainacomplete viewofLTC1062performanceissues.) [16-9] FundamentalsofSampledDataSystems,AnalogDevices,Inc.,ApplicationNoteAN-282(undated).
[16-6]
359
CHAPTER
17
DTMFToneDecoding andTelephoneInterface We’velookedatstate-of-the-arthigh-speedinter-ICcommunicationsprotocols,butwe’llseethere’sstilllife inthe1960’stouch-tonesignalingtechnology.(touch-tonewasaregisteredservicemarkofAT&T,butis nowapublicdomainterm.)We’llseehowtodecodetouch-tonesignalswithaspecialpurposedecoderIC andbuildanautomaticremotecontrolansweringmachinetoreceivetouch-tonecommands.
WhatisTouch-ToneSignaling? Touch-toneisanexampleofdual-tonemultifrequency(DTMF)signaling.Asthenamesuggests,touch-toneinvolvessimultaneouslysending twotonesfromasetofmultipletones.AsshowninFigure17-1,eachrow andeachcolumninastandardkeypadisassignedauniqueaudiotone frequency.(Onlyafewspecialtytelephoneshavecolumn4keys.)When youpressabutton,itsrowandcolumnfrequenciesaresimultaneously sent.Figure17-2showstheresultingenvelopewaveform,andFigure 17-3showsthecorrespondingspectrumdisplay.Figure17-3showsthe spectrumofthe“*”key,involvingsimultaneoustransmissionof941Hz and1209Hztones. Touch-toneisnottheonlyexampleofDTMFusedwithinthetelephone Figure17-1:StandardTouch-tone network.Atonetime,theBellSystemextensivelyused“inter-office” frequencies. DTMF—another4×4matrixsystembutwithtonefrequenciesincompatiblewithtouch-tone—tosetupcallswithinitsnetwork.Inter-officemultifrequencysignaling—alongwith other“in-band”signaling—however,turnedouttobevulnerabletohackingandhaslargelybeenreplaced
Figure17-3:Frequencydomaindisplayoftouchtonesignal.
Figure7-2:Timedomaindisplayoftouch-tone signal.
360
DTMFToneDecodingandTelephoneInterface bymoreefficientandmoresecurecommonchanneldigitalsignalingtechnology,suchasSignalSystemNo. 7.(Inter-officeMFsignaling,orsimplyMFsignalingasitiscommonlycalled,isstillusedonsomeanalog trunks,andtotransfercaller-IDinformationtosome911callcenters.)
GeneratingTouch-ToneSignals Todevelopandtestthetouch-tonedecoderhardwareandsoftware,you’llneedasourceoftestsignals.You coulduseasecondPICtogeneratetesttouch-tonesignals,viatheDTMFoutorDTMFOut2functions.Or, youcouldpurchaseanewtouch-tonegeneratorpad.But,ifyouhaveanoldunusedWesternElectrictouchtonetelephonearound,it’seasytoremovethedialandsetitupasatouch-tonegenerator.(Eventhougha touch-tonepadisn’troundanddoesn’trotate,it’sstilladialintelephoneterminology.)Figure17-4shows howtoconnectacommonWestern Electric/Lucenttouch-tonedialto functionasastand-alonetouch-tone generator.It’snecessarytopowerthe dialwithatleast9V,andIusually runmy1969-vintagedialwith18 to20V.Thedialonlydrawscurrent whenakeyispressed,soapairof 9Vtransistorradiobatteriesisa suitablepowersource.Don’tforget thecurrentlimitingresistor,R1. Withoutit,youmaydestroythedial. Inordertoreducetheoutputlevelto amoreusablelevel,weuseavoltage divider,R2andR3.Theoutputof thepadaloneisaround0dBm,and Figure17-4:WiringaTouch-Tonedial. theR2/R3voltagedividerreduces ittoapproximately–17dBm.(IfyouarenotfamiliarwithmeasuringoutputlevelsindBm,Chapter21has abriefrefresherondecibels.)Thischapter’sdBmreferencesarenotrigorous,asweareseldommeasuring voltageorpowerlevelsatthestandard600-ohmaudioreferenceimpedancelevel.
DecodingaTouch-ToneSignal Decodingatouch-tonesignalrequiresustodeterminewhichtonepairsarebeingsentatanygiveninstant andtodiscoverfromthebriefno-toneperiodwhenonedigitstopsandaseconddigitbegins.Thegoodnews isthatit’spossibletodothiswithaPICinsoftwarealone.Thebadnewsisthatyoucan’tdoitinMBasic;it requiresmanylinesoftightlywrittenassemblercode.SinceourobjectiveistointroduceyoutoMBasicwith asmatteringofassemblerhereandthere,we’lluseaspecialpurposetouch-tonedecoderIC. PerhapsthetwomostreadilyavailabledecoderICsareMotorola’sMC145436A(andtheearlierMC145436) andMitel’sMT8870devices.MotorolarecentlydiscontinuedtheMC145436butit’sstillavailablefrom somedistributors.TheMT8870anditscloneshavesimilarperformancespecificationstotheMC145436A butarenotquiteaseasytouse.We’lluseanMC145436A,butanMT8870canbesubstitutedwithonly minorchangesinthecircuit. Figure17-5showshowwemayconnectanMC145436AtoaPIC.Let’sreviewafewnonobviousaspectsof Figure17-5.
361
Chapter17 TheMCP145436Aoperatesfrom asingle+5Vsupply.Itincludes anintervalVDD/2biasgeneratorso it’snecessarycouplethetouch-tone inputtoitsanalogsignalinputpin, “Ain”viaablockingcapacitor,C1. Theenablepin,ENB,setsthefour outputpinstoahighimpedance tri-statewhenlowandtoanormal outputstatewhenhigh.WeaccordinglytieENBto+5V. It’spossibletooperatemul- tipleMCP145436A’sfroma singlemasterclock,ortouseone MCP145436A’sclocktodriveother MCP145436As.Sinceweonlyuse oneMCP145436A,wewillenable itsinternaloscillator(bytyingXen Figure17-5:ConnectingMC145436AtoPIC. to+5V)andconnecta3.579545 MHzcrystalbetweentheXinandXoutpins.(ThisisaninexpensiveTVcolorburstcrystal.)Abuffered oscillatoroutputsignalisavailableontheATBpin,whichwewillleaveunconnected. TheMCP145436A’soutputisfoundonthefourpinsD1,D2,D4andD8.Thefollowingnumericdesignationindicatesthepin’sbinaryweighting. Key 0 1 2 3 4 5 6 7
D8 1 0 0 0 0 0 0 0
D4 0 0 0 0 1 1 1 1
D2 1 0 1 1 0 0 1 1
D1 0 1 0 1 0 1 0 1
Dec. 10 1 2 3 4 5 6 7
Key 8 9 * # A B C D
D8 1 1 1 1 1 1 1 0
D4 0 0 0 1 1 1 1 0
D2 0 0 1 0 0 1 1 0
D1 0 1 1 0 1 0 1 0
Dec. 8 9 11 12 13 14 15 0
Keys1…9decodedirectlyfromtheirnumericalvalue;the0key,however,decodesas10.The*and#keys decodeas11and12,respectively.We’veconnectedthesefourdataoutputpinstothePIC’sB0…B3pinsso thatwemayreadtheMC145436A’sdecodedoutputasPortB.LowNib. Howthen,doweknowwhenonekeypressendsandasecondbegins?And,howdowepreventonetone fromtriggeringanoutput?(Ifyousimultaneouslypresstwokeysinaroworinacolumn,thesingletone correspondingtothatroworcolumnisgenerated.)TheanswertothesequestionsisthattheDV(digitvalid) outputpingoeshighonlywhentheMC145436Adecodesavalidtonepair.Asingletoneortonepairsoutsidethe±2.5%frequencytolerancewindowwillnotcausetheDVpintogohigh.We’veconnectedtheDV outputtothePIC’sB4pin. Afinalissueconcernshowlongavalidtonepairmustbereceivedinordertobeproperlydecodedandthe DVpintogohigh.Herewehavetwooptions;ifwetietheGT(guardtime)pinto+5V,werequirelonger timefortonedetection.Ifthepinisleftdisconnectedordirectlygrounded,thedetectiontimeisshortened.
362
DTMFToneDecodingandTelephoneInterface DetectionTime Minimum Maximum 32 50 22 40
GPPinStatus +5V Ground
ReleaseTime Minimum 18 28
Maximum 30 40
OperatingwithGTtiedto+5VisbetteratrejectingvoicewhileGPatgroundisbetterifthesignalhas noiseanddrop-outs.Forourapplication,thereislittleornodifferencebetweenthetwooptions,sowe’ll arbitrarilytieGTto+5V.Manualkeypressesyieldtypicaltonedurationsofabout100mswitha100ms pausebetweenkeys,soeitherstateworkswithmanualsending.
Program17-1 Let’ssee,then,howtoreadtheMC145436Awhenconnectedinthecircuitof17-5.Don’tforget,ofcourse, toconnectasourceoftouch-tonesignalstothe“DTMF_Input”pointinFigure17-5.TheMC145436A’s maximumpermittedsignallevelis–2dBm(615mVRMS)anditsminimumguaranteedsignallevelis–35 dBm(13.8mVRMS).Ourtargetlevelis–17dBm,or109mVRMS.Don’tworryaboutgettingthisexactly right;anywherefrom50mVto200mViscloseenough. Program17-1 ;Program17-1 ;ReadsaMotorolaMC145436ADTMF ;Decoderchip.D1...D8connectedto ;B0...B3toreadvalueonlowernibble ;B4connectedtoValidDatapinondecoder ;Constants ;-----------;MapsBCDagainstkeycapcaption KeyNameByteTable“D1234567890*#ABC” ;Variables ;----------BCDOut
Var
Byte
;Initialization ;--------------TRISB=$FF EnableHSerial SetHSerialH115200 HSerOut[13,”P17-1”,13,13] Main ;---
;Checktoseeifvalidoutput BCDOut=PortB ;Ifnothing,gobackandwaitsomemore IfBCDOut.Bit4=0Then GoToMain EndIf ;Validoutput;writetheresult HSerOut[iHexBCDOut.Nib0,”“,| StrKeyName(BCDOut.Nib0)\1,13]
;WaitforresetofValidDatapin Waiting Repeat BCDOut=PortB UntilBCDOut.Bit4=0 GoToMain End
363
Chapter17 TomaptheMC145436’sdecodedvaluetotheASCIIstringrepresentationofkeyname,weusethebyte tableKeyName: KeyNameByteTable“D1234567890*#ABC”
Adecodedvalueof12,forexamplereturnsKeyName(12),orthe“#”character.
;Checktoseeifvalidoutput BCDOut=PortB ;Ifnothing,gobackandwaitsomemore IfBCDOut.Bit4=0Then GoToMain
Thecodeissimple;wekeepcheckingthestatusoftheMC145436A’sDVpin.Whenitgoeshigh,weknowa validtouch-tonekeysequencehasbeenreceived.Tosaveabitoftime,wereadalleightPortBpinsandcopy thevalueintothevariableBCDOut.(BCDOutisn’tnamedforBinaryCodedDecimal,becausetheMC145436A doesn’thaveabinarycodeddecimaloutput.Rather,it’smymnemonicforbinarycodedata.)Wethencheckthe statusoftheDVpinbytestingBCDOut.Bit4.Ifit’s0,weknowavaliddigithasnotbeenreceived,soweloop backandreadBCDOutagain,waitingforittoread1,indicatingreceiptofavaliddigit.
;Validoutput;writetheresult HSerOut[iHexBCDOut.Nib0,”“,| StrKeyName(BCDOut.Nib0)\1,13]
Whenavaliddigithasbeenreceived,wewritetheinformationtotheserialport. ;WaitforresetofValidDatapin Waiting Repeat BCDOut=PortB UntilBCDOut.Bit4=0 GoToMain
Finally,toavoidmultiplereadingsofthesamekeypress,wewaituntiltheDVpingoeslow,indicatingthe currentkeypresshasended.WhenDVgoeslow,weloopbacktoMainandawaitanotherkeypress.Here’s theoutputfromProgram17-1resultingfrompressingthetouch-tonekeysfromlefttoright,toptobottom. ThefirstdigitisthehexvalueoutputoftheMC145436Awhilethesecondcharacteristhecorresponding stringfromKeyName.SinceIuseda12-buttondial,thespecialtouch-tonecharactersA,B,CandDdonot appearinthedecodedoutput. P17-1 $11 $22 $33 $44 $55 $66 $77 $88 $99 $B* $A0 $C#
Program17-2 Sinceit’ssoeasytoreadthetouch-toneoutput,let’sdosomethingslightlymoreusefulthanreadingsingle digits.We’llreadastringofdigitsandusethesetolatchaPIC’soutputpinhighorlow,tosimulatedriving anexternalcircuit.ThecircuitisthesameweonewedevelopedforProgram17-1. 364
DTMFToneDecodingandTelephoneInterface Program17-2 ;Program17-2 ;ReadsaMotorolaMC145436ADTMF ;Decoderchip.D1...D8connectedto ;B0...B3toreadvalueonlowernibble ;B4connectedtoValidDatapinondecoder ;Wewilldecodeseveralmulti-digitstrings\ ;forfunctionselection/deselection ;Canbeusedforremotecontrol ;Constants ;-----------;MapsBCDagainstkeycapcaption KeyName ByteTable“D1234567890*#ABC” Fcn1 Con $123456;codeforfunction1 Fcn2 Con $654321;codeforfunction2 CodeLen Con 6 ;digitsincode Timeout Con 3 ;numberoffalseattemptsbeforetimeout ;Variables ;----------BCDOut FcnInput DigitCount DigitVal InDigits i CodeTries
Var Var Var Var Var Var Var
Byte ;PortBvalue Long Byte ;howmanydigitsreceived? BCDOut.Nib0 ;outputnibble Byte(CodeLen+2);holdsreceivedbcd Byte ;counterforwork Byte
;Initialization ;--------------Clear LowC0 ;LEDisonC0turnedon/offviacode TRISB=$FF ;Btoinput EnableHSerial SetHSerialH115200 HSerOut[13,”P17-2”,13,13] Main ;---
;Checktoseeifvalidoutput BCDOut=PortB ;Ifnothing,gobackandwaitsomemore IfBCDOut.Bit4=0Then GoToMain EndIf ;WaitforValidDigittoclear Repeat BCDOut=PortB UntilBCDOut.Bit4=0 ;Resetifcharacteris“*” IfDigitVal=11Then DigitCount=0 EndIf ;StorereceiveddigitinInDIgits() InDigits(DigitCount)=DigitVal ;FordemonstrationReportInfodumpsdata GoSubReportInfo ;Validstartandendkeysintherightplaces? ;Ifso,maybewehaveagoodinputcode If(InDigits(0)=11)AND(InDigits(CodeLen+1)=12)Then IfDigitCount=(CodeLen+1)Then GoSubCheckCode EndIf EndIf
365
Chapter17
;Readyfornextdigit DigitCount=DigitCount+1 ;Can’tletitoverflowthearray IfDigitCount=(CodeLen+2)Then DigitCount=0 EndIf ;Topreventbruteforceattackoncode,freezefromnew ;codereceptionforaminuteortwoafterseveralattempts ;atcodebreakin IfCodeTries=TimeOutThen HSerOut[“AttemptedCodeBreakin!!”,13] ;Insertlongpause,keepitshortfordevelopment Pause10 EndIf
GoToMain ReportInfo ;---------- ;Reportinfoforprogramdevelopmentpurposes HSerOut[“DCnt:“,DecDigitCount,9] Fori=0toDigitCount HSerOut[Deci,”/”,DecInDigits(i),”“] Next HSerOut[13] Return CheckCode ;---------- ;ConvertthearrayintoaLongvalue FcnInput=0 ;Addeachnibbleatrightandshiftleftfor ;thenextnibble.Don’tshiftattheend Fori=1toCodeLen FcnInput.Nib0=InDigits(i) Ifi<>CodeLenThen FcnInput=FcnInput<<4 EndIf Next ;Reportfordevelopment HSerOut[“FcnInput:“,iHexFcnInput,13] CodeTries=CodeTries+1 ;Checktoseeifvalidcode.Ifsobranchto ;appropriatefunctionsubroutine IfFcnInput=Fcn1Then GoSubFunction1 CodeTries=0 EndIf IfFcnInput=Fcn2Then GoSubFunction2 CodeTries=0 EndIf Return Function1 ;-------- ;Insertcodetoperformthedesiredtask HSerOut[“Function1”,13] ;TurnLEDon HighC0 Return
366
DTMFToneDecodingandTelephoneInterface Function2 ;-------- ;Insertcodetoperformthedesiredtask HSerOut[“Function2”,13] ;TurnLEDoff LowC0 Return End
We’llassume,untilwereachProgram17-3,thatthetouch-tonesignalarrivesattheMC145436A’sanalog inputpinbydirectconnectiontoadial,suchasshowninFigure17-4. We’llstartbydefiningtwomulticharacterdigits: Fcn1 Fcn2
Con Con
$123456;codeforfunction1 $654321;codeforfunction2
Function1turnstheLEDconnectedtoC0on;Function2turnsitoff.Notethatwe’vedefinedthesetwo digitsashex.Thisletsustakeadvantageofthewayahexadecimalnumberisstored;eachdigitisstoredin aseparatenibble.(Thisalsomeansifwewishtohaveusethe0keyinthepassword,itmustbestoredas $A.)Thus,bylookingatFcn1anibbleatatime,wecanaccessthedecimalnumbers1,2,3,4,5,6.Ifwe triedstoringourfunctioncodeindecimalasFcnCon123456,itwouldbestoredas$1E240,notwhatwe intended.Alternatively,wecouldstorethefunctioncodesinRAMbytevariablearrays,suchasFcn1(6), witheachelementofFcn1()holdingoneoffunctioncode1’sdigits.But,thiswouldbewastefulofRAM. CodeLenCon TimeoutCon
6 3
;digitsincode ;numberoffalseattemptsbeforetimeout
We’vealsodefinedthenumberofdigitsinthetwocodes,andthenumberofattemptstheusergetsbefore beinglockedoutofenteringthecodes.(Sincewestoreadecodedvalueinatypelongvariable,CodeLen cannotexceed8.) Tosimplifyouralgorithm,we’llrequirethatvalidfunctioncodesbeenteredas*NNNNNN#,thatis,you startwiththe*key,enterthefunctioncodedigitsfollowedbythe#key. Wereusethe“waitforavaliddigit”codefromProgram17-1.Onceavaliddigithasbeenreceived,weadd ittothearrayInDigits(DigitCount)withthefollowingcode.
;Resetifcharacteris“*” IfDigitVal=11Then DigitCount=0 EndIf ;StorereceiveddigitinInDIgits() InDigits(DigitCount)=DigitVal ;FordemonstrationReportInfodumpsdata GoSubReportInfo
Weusethe*key(readasdecimalvalue11)toresetDigitCount,soweareguaranteedofafixedstarting pointwhenweevaluatethereceivedkeystrokestoseeiftheymatchFcn1orFcn2.
;Validstartandendkeysintherightplaces? ;Ifso,maybewehaveagoodinputcode If(InDigits(0)=11)AND(InDigits(CodeLen+1)=12)Then IfDigitCount=(CodeLen+1)Then GoSubCheckCode EndIf EndIf
Wethenchecktoseeifwehaveapotentiallyvalidcodesequence—a*(value11)atInDigits(0)and a#(value12)atInDigits(CodeLength+1).Ifso,wethenexecutesubroutineCheckCodetoseeifthe potentiallyvalidentrymatchesarealfunctioncode.(We’lllookatsubroutineCheckCodeafterwefinishthe restofthemainprogramloop.)
367
Chapter17
;Readyfornextdigit DigitCount=DigitCount+1 ;Can’tletitoverflowthearray IfDigitCount=(CodeLen+2)Then DigitCount=0 EndIf
WenextbumpuptheDigitCounttobereadyforthenextreceivedkeystroke,andcheckifwehave reachedthemaximumpermittedDigitCountvalue.Ifso,weresettozero.
;Topreventbruteforceattackoncode,freezefromnew ;codereceptionforaminuteortwoafterseveralattempts ;atcodebreakin IfCodeTries=TimeOutThen HSerOut[“AttemptedCodeBreakin!!”,13] ;Insertlongpause,keepitshortfordevelopment Pause10 EndIf
GoToMain
Finally,wechecktoanattemptedbreak-in.Ifthecorrectfunctioncodeshavenotbeenreceivedinarequired numberofattempts,welockoutfurtherinputforatime. Let’snowlookatsubroutineCheckCode. CheckCode ;---------- ;ConvertthearrayintoaLongvalue FcnInput=0 ;Addeachnibbleatrightandshiftleftfor ;thenextnibble.Don’tshiftattheend Fori=1toCodeLen FcnInput.Nib0=InDigits(i) Ifi<>CodeLenThen FcnInput=FcnInput<<4 EndIf Next
Tocomparethereceivedkeystrokeswiththefunctioncodes,weplacethekeystrokevaluesinatypeLong variableFcnInput.Wedothisonenibbleatatime,addingeachkeystrokevaluetotheFcnInput.Nib0. Aftereachnibbleisentered,weshiftFcnInputfourbitstotheleft,tomakeroomforthenextkeystroke value.(Wedon’tshiftafterthelastdigitisentered,becausethereisnonextvaluetoadd.)Wecouldhave simplyhard-codedthisconversion: FcnInput.Nib0=InDigits(1) FcnInput.Nib1=InDigits(2) Etc.
But,usingaloopandshiftprocedureallowsustochangethecodelengthbyalteringthevalueofCodeLen withoutmuckingaboutintherestofthecode.
HSerOut[“FcnInput:“,iHexFcnInput,13] CodeTries=CodeTries+1
WereachsubroutineCheckCodeonlyiftheentryappearstobeavalidfunctioncode,soit’sappropriateto increasetheCodeTriescounter.(Remember,weuseCodeTriestodetectattemptedbreak-ins.)
;Checktoseeifvalidcode.Ifsobranchto ;appropriatefunctionsubroutine IfFcnInput=Fcn1Then GoSubFunction1 CodeTries=0 EndIf IfFcnInput=Fcn2Then GoSubFunction2 CodeTries=0
368
DTMFToneDecodingandTelephoneInterface EndIf Return
HavingputthekeystrokesintoFcnInput,it’sasimplematterofcomparingFcnInputtothepre-defined functioncodesFcn1andFcn2.Ifthere’samatch,thenweexecutecodespecifictothatfunction,andreset CodeTriesto0,sincewehavereceivedavalidfunctioncode. Function1 ;-------- ;Insertcodetoperformthedesiredtask HSerOut[“Function1”,13] ;TurnLEDon HighC0 Return Function2 ;-------- ;Insertcodetoperformthedesiredtask HSerOut[“Function2”,13] ;TurnLEDoff LowC0 Return
ThefunctionsassociatedwiththeFcn1andFcn2codesturnonorofftheLEDattachedtopinC0. AswithProgram17-1,tohelpunderstandanddevelopthecode,weoutputinformationtotheserialport. Eachlinereportsthecurrentdigitcount(DCnt)andthenthecontentsofInDigits(i)intheformindex/ valuefori=0toDigitCount.Here’satypicalinteractionreport,withmycommentsaddedinbold. P17-2 DCnt:00/1 DCnt:10/11/2 DCnt:20/11/22/3 DCnt:30/11/22/33/4 DCnt:40/11/22/33/44/5 DCnt:50/11/22/33/44/55/6 DCnt:60/11/22/33/44/55/66/7 DCnt:70/11/22/33/44/55/66/77/8 DCnt:00/9 DCnt:00/11 DCnt:10/111/10 DCnt:20/111/102/12 DCnt:00/11 DCnt:10/111/1 DCnt:20/111/12/2 DCnt:30/111/12/23/3 DCnt:40/111/12/23/34/4 DCnt:50/111/12/23/34/45/5 DCnt:60/111/12/23/34/45/56/6 DCnt:70/111/12/23/34/45/56/67/12 FcnInput:$123456 Function1 DCnt:00/11 DCnt:10/111/6 DCnt:20/111/62/5 DCnt:30/111/62/53/4 DCnt:40/111/62/53/44/3
Keyedintoomanydigits,soDigitCountresetsto0
Startafunctioncodewiththe*key 1key 2key 3key 4key 5key 6key Endthefunctioncodewiththe#key Keypressinputreceivedas$123456 Function1executedbasedoncorrectreceptionofFcn1 SamebutFunction2tobeexecuted
369
Chapter17 DCnt:50/111/62/53/44/35/2 DCnt:60/111/62/53/44/35/26/1 DCnt:70/111/62/53/44/35/26/17/12 FcnInput:$654321 Function2 DCnt:00/11 DCnt:10/111/1 DCnt:20/111/12/4 DCnt:30/111/12/43/7 DCnt:40/111/12/43/74/2 DCnt:50/111/12/43/74/25/5 DCnt:60/111/12/43/74/25/56/8 DCnt:70/111/12/43/74/25/56/87/12 FcnInput:$147258 DCnt:00/11 DCnt:10/111/7 DCnt:20/111/72/8 DCnt:30/111/72/83/9 DCnt:40/111/72/83/94/9 DCnt:50/111/72/83/94/95/8 DCnt:60/111/72/83/94/95/86/7 DCnt:70/111/72/83/94/95/86/77/12 FcnInput:$789987 DCnt:00/11 DCnt:10/111/6 DCnt:20/111/62/5 DCnt:30/111/62/53/4 DCnt:40/111/62/53/44/6 DCnt:50/111/62/53/44/65/5 DCnt:60/111/62/53/44/65/56/4 DCnt:70/111/62/53/44/65/56/47/12 FcnInput:$654654 AttemptedCodeBreakin!!
Keypressinputreceivedas$654321 Function2executedbasedoncorrectreceptionofFcn2 Nowwetestsomefalsefunctioncodestoverifythe programwillrejectincorrectentries
Keypressinputreceivedas$147258 Doesnotcorrespondtoanyknownfunctioncode
Secondattemptatbreak-in Keypressinputreceivedas$789987 Doesnotcorrespondtoanyknownfunctioncode
Thirdattemptatbreak-in Keypressinputreceivedas$654654 Attemptedbreak-indetectedafterthreeinvalidattempts
Program17-3 Nowthatwecanreadmultikeystrokeentriesandtakeactionbasedontheirvalue,let’sseehowwemight builduponProgram17-2andusethetelephonenetworktoremotecontroldevicesinyourhomeoroffice. Program17-3allowsyoutodialatelephonenumberandhaveitautomaticallyanswered.Ifyouenterthe correctpassword,youcanthensendfour-digitcommandsbytouch-tone.Thefour-digitcommandstructure ispatternedaftertheX10homeautomationprotocol,coveredinalaterchapter.TokeepProgram17-3at amanageablelength,we’llomitthetouch-tone-to-X10transmissionelements.First,however,we’lltakea sidetripandexaminetheanalogtelephonenetworksubscriberconnection. Figure17-6providesaconceptualoverviewofthetraditionalsingle-partytelephoneconnectionandFigure17-7 providesasimilarpictureofatypicalsubscriberinstrument.We’lllookatnonelectronicsubscriberinstruments,but thesamefunctionality—implementedwithelectroniccircuitry,notelectromechanicalcomponents—isfoundin modernsubscribersets.And,ofcourse,asimilarelectronicrevolutionhasreplacedelectromechanicalcrossbarand step-by-stepswitchesinthecentralofficewithcomputer-controlledequipment.But,thefunctionalityisthesameand it’seasiertounderstandtheelectromechanicaltechnology.Therearetwocomponentswewillexamine;signaling (answeringandplacingacall)andcommunications(transmissionandreceptionofvoicefrequencysignals). 370
DTMFToneDecodingandTelephoneInterface We’llfirstconsidersignalinginthe localloop.FromFigure17-7,it shouldbeapparentthatwhenthe subscriberinstrumentison-hook, noDCcurrentflowsthroughthe subscriberloop. Answeringacall—Whenringing voltage(A20Hzsinusoidal waveform,typically100V RMS)isappliedatthecentraloffice,ACcurrentflows throughtheringer,which causesitsarmaturetostrikea bellgong.Toanswer,youpick upthehandset,whichcloses thehookswitch,therebypermittingDCcurrenttoflowthrough thesubscriberloop.The inductorsL1andL2shownin Figure17-6areactuallyrelay coils,andthustheirassociated Figure17-6:Simplifiedviewofsubscriberloop. contactsarepulledinbythe DCcurrentflow,informingthecentral officethatthesubscriberhaspicked upthelineandhasthusansweredthe call.Ringingvoltageisdisconnected andconversationmaycommence. Originatingacall—Whenyouliftthe handset,thehookswitchclosesand permitsDCcurrenttoflowthroughthe subscriberloop.TheinductorsL1and L2showninFigure17-6areactually relaycoils,andthustheirassociated Figure17-7:Simplifiedviewofsubscriberinstrument. contactsarepulledinbytheDCcur (Shownon-hook.) rentflow,informingthecentraloffice thatthesubscriberhaspickedupthe line.Sincethereisnoringsignalbeingapplied,thecentralofficeknowsyouareattemptingtooriginate acall,andthusconnectsthelinetoadialtonegeneratorandatouch-tonedigitreceiver. Communicationsoverthesubscriberlooprequiresacompletedconnection,thatis,theremustbeDCcurrentflow throughthelocalloopsufficientforthecentralofficetorecognizesupervisionofthecallandcutthroughtheaudiopath.Thesubscriberloopsupportsbothtalkandreceiveaudiosignalsoverasinglepairofwires.Atthecentral office,andatthesubscriberend,however,wemusthaveseparateaudiopathsfortalkandreceive,orelsewewill haveundesiredfeedbackandanunusableconnection.(Intelephoneterminology,acircuitwithseparatetransmit andreceivepathsisa“four-wire”system.)Atwo-wiretofour-wireconverteriscalledahybrid,andhistorically wasconstructedasamultiwindingtransformer.It’snowusuallydonewithseveralop-ampsinasubtractionconfigurationwherealocalcopyofthetransmitsignalissubtractedfromthereceivesignal. 371
Chapter17 Weshouldnotassumethelocalloopissimplyapieceofwirethatconnectsyouwiththecentraloffice.It’sa transmissionline,whichhasloss,DCresistanceandcharacteristicimpedance.TheDCresistanceisusually afewhundredohms,suchthat,whencombinedwiththeresistancesofrelaycoilsinthecentraloffice,typically15to30mAofoff-hookcurrentcanbedrawn.Thenominalcharacteristicimpedanceofthelocalloop is600ohms,butinfactitvarieswithfrequencyandotherfactors. Althoughthelocalloopisgroundreferencedatthecentraloffice,youshouldnevertreatitasanythingother thanabalancedcircuit;donotgroundoneconductor,anddonotapplysignalsbetweengroundandone conductor.Undersomecircumstances,itmightappeartowork,butyouruntheriskofcouplingyoursignals intoothersubscriberloops.Likewise,therearelimitsonthemaximumsignallevelthatyoumaytransmit intothesubscriberloop;fordata-typesignalsitis–9dBm,or275mVRMS.Donotexceedthislevel. IntheUnitedStates,theFCChasestablishedacomplexsetofrulesgoverningequipmentthatmaybedirectlyconnectedtothetelephonenetwork.We’regoingtotakeadvantageofaprovisionintheFCC’srulesthat allowsustoconnecthomemadecircuitrythrougharegistereddataaccessarrangement(DAA).TheDAA we’lluseisaCermetekmodelCH1837Acoupler.Similardevicesareavailablefromothermanufactures, suchasXecom’sXE0068orZarlink’sMH88422.(Indeed,someDAAsincludeatouch-toneencoderand decoder,removingtheneedforaseparateMC154436Achip.)We’regoingtocheatalittlebit,though.The FCCregisteredversionoftheCH1837AcoupleristheCH1840anditsellsforaround$60eachinsingle lotquantities.We’llusetheun-registeredCH1837A,whichcontainsidenticalcircuitry,andispin-for-pin interchangeablewiththeCH1840,butcostsonly$18.Thedifference?CermetekhasgonethroughtheFCC paperworktoregistertheCH1840andwilltransferacopyofitsregistrationtoyouwitheachCH1840you purchase,butyouareresponsibleforregisteringtheCH1837A.Forhomemadeone-offexperimentalwork, we’llusetheunregisteredCH1837Aandfollowgoodengineeringpractices,butnotfileanypaperworkwith theFCC,which,inanyevent,isn’tpracticalforthehomeexperimenter. Lastly,anythingconnectedtoasubscriberloopmustbeprotectedfromover-voltageandover-current.Usually thisisaccomplishedwithvoltageclampingzincoxidevaristorsandfuses.Cermetek’sCH1837Adatasheet providesasampleschematicofatypicalprotectivearrangement.I’veomittedtheseelementsfromtheschematictoavoidclutter,butifyouleavetheCH1837Aconnectedformorethanbrieftests,youmustaddthevaristor andfusecircuitrydescribedbyCermetekforyourownsafetyaswellastoprotectthetelephonenetwork. Figure17-8showstheCH1837AconnectedtotheMC145436Atouch-tonedecoderandthePIC.Let’slook athowweinterfacewiththeCH1837A. ThesubscriberloopconnectstotheCH1837A’stipandringconnections.(Thetermstipandring,bytheway, gobacktothedaysofplug-boardswitchboards,beforeautomaticdialing,whenonesideoftheloopconnected tothetipoftheplugandtheothersideconnectedtotheringconnection.Thesleeveoftheplugwasground.) Whenringingvoltageisdetected,theCH1837A’sringingindicator(RI)pingoeslow.TheRIpin’sresponse isfastenoughtofollowtheindividualcyclesofthe20Hzringingvoltage,soweadda4.7µFcapacitorto provideasinglepulseforeveryringinterval.(Ringingvoltageisappliedfortwoseconds,followedbyfour secondsofsilence.)Figure17-9showsRI’sresponseduringringing.Theindividualcyclesofringingvoltagearebridgedover,soRIstayslowduringtheentireringingvoltageinterval.We’veconnectedRItothe PIC’sC2pinsowemayreadRI’sstatus. TotaketheCH1837Aoff-hook,thatis,toansweraring,ortoseizethelinetooriginateacall,youtakethe OFFHKpinhigh.AlowonOFFHKplacestheCH1837Aintheon-hookmode.We’veconnectedOFFHKto thePIC’sC0pinsowemayplacetheCH1837Aineithertheon-hookoroff-hookmodeviasoftwarecontrol. Todisconnectacall,wereturntoon-hookmode. TheCH1837Aperformsthehybridfunction,givingusindependenttransmitandreceiveaudiopaths.The netlossineitherdirectionisnominally0dB,sothesignallevelappliedtotheCH1837A’stransmitport
372
DTMFToneDecodingandTelephoneInterface
Figure17-8:TelephoneinterfacetoPICandTTdecoder.
appearswithoutlossonthetipandringconnectionsandthe receivesignallevelonthetipandringconnectionsappear withoutlossattheCH1837A’sreceiveport. • Thereceivesignal,i.e.,thetouch-tonesignalcoming infromtheremoteuser,appearsattheRCVpin.Itisa single-endedsignal,thatis,itiswithrespecttoground, DCbiasedatapproximatelyVCC/2.Hence,wecouple outofRCVwitha0.1µFblockingcapacitor.Basedon thetelephonecompany’snominallossplans,weexpect thereceivedtouch-tonesignaltobeinthe–10dBmto –20dBmrange.Figure17-10showsatypicaltouch-tone signal(–16dBm)asseenattheCH1837A’sRXpin. • Thetransmitsignal,i.e.,theaudiopromptsignalswe willsendtotheremoteuser,isapplieddifferentially totheXMIT+andXMIT-pins.Bothofthesepinsare internallybiasedatapproximatelyVCC/2.Sinceit’s moreconvenientforthePICtogenerateasingled-ended signal,we’llconnecttheXMIT+inputtogroundthrough a0.1µFblockingcapacitorandconnecttheXMIT-inputtothePIC’sC1pin.Again,weusea0.1µFblocking capacitortoavoiddisruptingtheinternalVCC/2bias.And, sincetherawoutputwegenerateiswelloverthe–9dBm transmitlimit,weuseR2andR3asaresistivevoltage divider.(Wegeneratetheresponsetoneasasquarewave onC0.C0swingsfrom+5Vto0V,orpeak-to-peak5 V.Asinusoidalwaveformat–9dBmhasapeak-to-peak
373
Figure 17-9: RI pin with 4.7 µF filter during ringing.
Figure 17-10: Touch-Tone signal as received atRXpin.
Chapter17 valueof777mV.Forsafety—andtoavoidcomplexityindiscussingthedifferenceinRMSversuspeak valuesbetweensinusoidalandasquarewaves,we’lllimitthepeak-to-peakvalueofthesquarewavewe generateto500mV.Thisrequiresa10:1voltagedivider,whichweaccomplishwithR2andR3.) IndevelopingandtestingProgram17-3,it’squiteusefultolistentothereceivedandtransmittedaudiosignals.Figure17-11isasimple,low-poweraudioamplifierthatyoumayconnecttothecircuitofFigure17-8 tolistentoboththereceivedandtransmittedaudiosignals.TheLM386isaself-containedlow-poweraudio amplifier.InFigure17-11,theLM386issetforafixedgainof20,whichismorethanenoughformonitoringpurposes.Thiscircuitresistivelymixestransmitandreceivesignalsattheinputtothemastervolume control,andthusdegradestheCH1837A’shybridisolation.But,sinceourcircuitisimmunetofeedback, wecoulddowithoutthehybrid.(It’simmunetofeedbackbecausethereisnocouplingmechanismwhereby thereceivedsignalisamplifiedandfedbacktothetransmitside;thereceivedsignalterminatesinthe MC145436A;thetransmitsignalisasquarewavegeneratedbythePIC.)
Figure17-11:Simpleaudioamplifierfortesting.
BeforewelookatthecodeforProgram17-3,let’ssummarizeinpseudo-codewhatweexpectittoaccomplish. WaitonHookforRing. Countringsandafterapresetnumberofrings, Answerthecallbygoingoff-hook Sendawelcomepromptsignaltotheuser Userinputsapasswordintheform*NNNNNN# Ifthecorrectpasswordisnotenteredafterapresetnumberofattempts,senda responsemessageanddisconnectbygoingon-hook Ifthecorrectpasswordisentered,acknowledgeitandallowtheusertoenter commands. Commandsareoftheform*XXYZ#where XXis0…15 Yis0…1andZis0…9 IfXX,YorZisoutofbounds,sendanappropriateerrormessagetotheuser. IftheXXYZiswithinbounds,echoitbacktotheuser Disconnectif*9999#codeisreceived,oriftherearenokeypressesforacertain interval
374
DTMFToneDecodingandTelephoneInterface Wemustdecidehowtocommunicatewiththeuser.Unfortunately,simplespeechsynthesizerchipsareno longerreadilyavailable,andthosechipsthatareavailablearetoocomplexforbeginner’sprojects.So,we areleftwithasimpletoneorbeeptyperesponse.BecauseI’vebeenahamradiooperatorsinceIwasateenager,manyyearsago,I’vemadeProgram17-3respondwithMorsecodepromptsandmessages.Ifyoudon’t knowMorsecode,I’llsuggestasimplebeeproutinealternative.(It’snotthatdifficulttolearnafewcharactersofMorse.WhenIwasagraduatestudentinelectricalengineeringatWayneStateUniversityinthelate 1960’s,IworkedonaresearchprojectwiththeDetroitPoliceDepartmentandspentquiteabitoftimeat theDPD’sBelleIslemobileradiorepairshop.Abouthalftheofficersattheshopwerehamsandinsteadof avoicePAsystemtoannounce“telephonecallforJoeonline1,”theyusedanaudiooscillatorandMorse keytosendtheinitialsofthepersonbeingcalled.Itdidn’ttakelongfornon-hamstolearnenoughMorseto identifytheirinitialswhenheardoverthesoundsystem.Toshowhowfarthetechnologyhascome,itwas onlyinthemid-60sthattheregionalpoliceMorsecodeemergencyradionetworkwasabandoned.) Program17-3 Program17-3isverylong.Ratherthanfollowournormalstructureoflistingtheprograminfull,followed byasection-by-sectionanalysis,we’llskipthefulllisting.Program17-3,likeallotherprogramsinthis book,isavailableinanelectroniccopyintheassociatedCD-ROM.Ifyouneedalistingtofollowwhile readingtheanalysis,youmayprintonefromtheprogramfile. We’lllookatourconstants,variablesandMorsecoderoutinesafterweworkthroughthemainelementsof Program17-3. Asusual,thefirstorderofbusinessafterdefiningconstantsanddeclaringvariablesistoinitializevariables andestablishpinsandinputoroutput. Initialization ;--------------TRISB=$FF ;Btoinput TickCtr=0 ;timepassage RingCount=0 ;ringsreceived EnableHSerial SetHSerialH115200 SetTmr1TMR1Int8 ;With20MHzclockthisyields ;onetickaboutevery105mS OnInterruptTmr1Int,UpDateTicks
It’simportantthatourprogramreleasethesubscriberloopautomaticallyifauserforgetstoenterthedisconnectcode,oriftheremotecontrollineiscalledinerrororbyatelemarketer.Wekeeptrackofelapsedtime afteransweringwithaninterruptserviceroutine,UpDateTicks.Approximatelyevery0.1second,UpDateTicksincrementsthevariableTickCtrsowecandetermineelapsedtimebythevalueofTickCtr. TheforegoingcodeinitializesTickCtrandestablishestheentrycallfortheinterrupthandler.(Timer1isa 16-bittimer,andwe’vesetittooperatewitha8:1prescalerwithitsinputbeingtheinstructionclock.Hence, witha20MHzclockrate,timer1’sinterruptserviceroutineiscalledonceevery(8×65536/5×106)or 0.1049seconds.SeeChapter10formoreinformationontimersandinterruptserviceroutines.) ;Serialoutputfordevelopment;removeifun-necessary HSerOut[13,”P17-3”,13,13] DigitCount=0 PWOK=Bad;nopasswordyet Input RIPin OutputOffHook Low OffHook EnableTmr1Int
;Ringindicator ;pintocontrolconnection ;Readytoreceiveacall ;startcountingticks
Next,wesetthepinsconnectedtotheCH1837A’sRIandOffHookpinsasinputandoutput,respectively. (WealiasedtheconstantsRIPintoC2andOffHooktoC0inthedefinitionsfile.)And,lastly,westarttimer 1’sinterruptprocess. 375
Chapter17 ;InitializationMorseCode ;-------------------------ELtime=1200/WPM;FromPARIS=50Elements=1Word LowTonePin
NowwecalculatethebaselengthoftimefortheshortestelementofaMorsecodesymbol(asingledot). Morsecodespeedisuniversallydefinedin“wordsperminute”andthe“standardword”“PARIS”iscomprisedof50elements,includinginter-character,inter-letterandinter-wordspaces.We’llspendamoretime ontheMorsecodeaspectsofProgram17-3later. Main ;-----
;ReturnfromWaitForRingonlyafterdefinednumber ;ofringsreceived GoSubWaitForRing ;Gooff-hookwhenringstops ;Waitforringingtostop GoSubAnswerPhone ;Atthisstage,answeredcallandwaitingforuserTTinput ;Allowcertaintimetoentervalidpasswordanduserdata. ;Timer1checksforidlecondition TickCtr=0 EnableTmr1Int
Westartthemainportionoftheprogrambywaitingforapre-determinednumberofrings,followingwhich occurrenceweplacetheCH1837Aoff-hook.Thefunctionalcodeforthesetwoactivitiesappearsinthe subroutinesWaitForRingandAnswerPhone. WaitForRing ;-----------Waiting ;Waitingforring IfRI=%1Then GoToWaiting EndIf TickCtr=0
Fori=0to99:Pause10:Next
(Indeclaringvariables,wehavealiasedRItoPortC.Bit2.)Whenringingvoltageisdetectedbythe CH1837A,itdropsRIlow.HencewecontinuouslytestRI’sstatusuntilitislow.UponRIgoinglow,we resetTickCtrandwaitfor1second.(BecauseMBasicexecutesinterruptserviceroutinesonlybetween BASICstatements,we’veused100delaysof10msinsteadofone1000msdelay.Thisway,theinterrupt serviceroutinewillcontinueexecutingwithoutmorethan10mslatency.)
IfRI=%1Then GoToWaiting EndIf
Onesecondafterdetectingringing,wechecktoseeifRIisstilllow.Ifitis,welikelyhaveavalidring,and notjustamomentaryvoltagespikeonthesubscriberloop.
;Wait2seconds Fori=0to199:Pause10:Next
RingCount=RingCount+1
Wethenwaittwoseconds,atwhichtimeweshouldbeinthefour-secondwindowbetweenringingvoltage pulses.Weupdatetheringcount.
IfTickCtr>(RingVal*60)Then RingCount=0 EndIf IfRingCount<RingValThen
;Ringlimitreached?
376
DTMFToneDecodingandTelephoneInterface
EndIf
GoToWaiting
RingCount=0 Return
WeneedawayofresettingRingCounttoavoidthecaseofseveralisolatedrings,orlinedisturbance,beingconsideredavalidanswercriteria.WedothisbyresettingRingCountiftherequisitenumberofrings(RingVal)has notbeenreachedwithin6secondsforeachexpectedring.(TickCtrincrements10times/second.) ;Answerphonewhenringstops AnswerPhone ;------------AnswerOnQuiet IfRI=%0Then GoToAnswerOnQuiet EndIf ;Ringingstopped-nowanswerbytakingOffHookHIGH HighOffHook TickCtr=0 ;Sendwelcomemessage GoSubWelcome PWOK=Bad Return
SubroutineAnswerPhonedoesexactlythat;wheninvoked,itwaitsuntilthereisnoringingvoltagedetected andthentakesOffHookhigh,whichcausestheCH1837Atogooff-hookandsignalthecentralofficethat thecallhasbeenanswered.(We’vealiasedOffHooktoC0.)NotealsoweresetTickCtrto0,aswemust monitortheconnectedcallforinactivityanddisconnectifappropriate.SubroutineWelcomesends“?”by Morsecodeasawelcomemessage. ;Afterautoanswersendwelcomemsg ;------Welcome ;------ Pause2000 ;Wait2seconds Message=“?[“ Message(2)=0 GoSubSendMsg Return
Wewait2secondsbeforesendingthemessageastheringtoneindicatorheardbythecallingpartyisnot necessarilyinphasewiththeringingvoltageonthecalledline.IfyouarenotimplementingMorsecode, thensubstitutearoutinethatsends,forexample,twoshortpipsaftera2-seconddelay. Beforelookingattherestofthemainprogramloop,let’slookattheidletimeoutfeaturewe’veimplemented.Themainprogramlooplookssomethinglikethiswhenstrippedofdetail: Main <<Waitforringandanswerifvalidrings>> CheckForTimeout IfTickCtr>TimeOutValThen GoSubGoodBye ;Iftimedout,disconnect GoToMain ;Waitfornewcall EndIf <<Checkforkeypresses--ifKeyPressedresetTickCtrto0>> GoToCheckForTimeout
Everytimeakeyispressedandavalidtouch-tonesignalisreceived,TickCtrisresetto0.Thus,whilethe lineisidle(speechisregardedasidle,asitisunlikelytobeacceptedasavalidtouch-tonekeypressbythe MC145436Adecoder)TickCtrkeepsincrementing,approximately10timeseverysecond.IfTickCtr exceedsthetimeoutconstantTimeOutVal,subroutineGoodByeisexecutedandprogramexecutionreturns toMain,whereitawaitsthenextringsequence. 377
Chapter17 ;ExitwithSKanddisconnect GoodBye ;------------ Message=“\” ;SendSK Message(1)=0 GoSubSendMsg Pause2000 ;nosignal LowOffHook ;Disconnect Return
SubroutineGoodByesendsadisconnectmessage,theMorsecodesignfor“endofcommunications”—the lettersSKsentwithoutaletterspace—waitstwosecondsandtheninstructstheCH1837Atodisconnectby takingOffHooklow.The2-secondwaitfollowsFCCrulesrequiring2silentsecondsprecedingdisconnect. Again,youcouldsubstituteagoodbyebeepsignal,orsimplysilentlydisconnectthecall. We’llnowgobacktothemainprogramloop. CheckForTimeout
IfTickCtr>TimeOutValThen GoSubGoodBye GoToMain EndIf
;Iftimedout,disconnect ;Waitfornewcall
;Waitforakeypress BCDOut=PortB ;Ifnothing,gobackandwaitsomemore IfPortB.Bit4=0Then;ValidDigit=0->nokeypress GoToCheckForTimeOut EndIf ;WaitforValidDigittoclear Repeat BCDOut=PortB UntilBCDOut.Bit4=0 ;Resetifcharacteris“*” IfDigitVal=11Then DigitCount=0 EndIf ;StorereceiveddigitinInDIgits() InDigits(DigitCount)=DigitVal ;FordemonstrationReportInfodumpsdata GoSubReportInfo
Theabovecodeis,byinlarge,lifteddirectlyfromProgram17-2andrequireslittlediscussion;waitfor avaliddigittobereceived,andstoreitsnumericalvalueinthearrayInDigits(DigitCount).Reset DigitCountwhena*keyispressed.
If(InDigits(0)=11)AND(InDigits(CodeLen+1)=12)Then IfDigitCount=(CodeLen+1)Then GoSubCheckCode EndIf EndIf
Likewise,theabovecodetodetermineifakeypresssequencemeetstheformatforbeingavalidpasswordis lifteddirectlyfromProgram17-2.ThesubroutineCheckCodealsofollowsitsnamesakeinProgram17-2. CheckCode ;---------- ;Remember0isreportedas10 ;weneednumericalsomustzeroit Fori=1toCodeLen IfInDigits(i)=10Then InDigits(i)=0 EndIf Next
378
DTMFToneDecodingandTelephoneInterface Return
;ConvertthearrayintoaLongvalue FcnInput=0 ;Addeachnibbleatrightandshiftleftfor ;thenextnibble.Don’tshiftattheend Fori=1toCodeLen FcnInput.Nib0=InDigits(i) Ifi<>CodeLenThen FcnInput=FcnInput<<4 EndIf Next ;Reportfordevelopment HSerOut[“FcnInput:“,iHexFcnInput,13] ;Attemptedpasswordentries CodeTries=CodeTries+1 ;Checktoseeifvalidcode.Ifsobranchto ;appropriatefunctionsubroutine IfFcnInput=PasswordThen GoSubPasswordOK CodeTries=0 EndIf ;IfbadPW,send?.Don’tsendonlasttrybecausewe ;senddifferentmessage If(CodeTries>0)AND(CodeTries<Attempts)Then Message=“[?[“ Message(3)=0 GoSubSendMsg EndIf
Ifthereceivedpasswordentryisinvalid,wesentaMorse“?”andincreasethecounterCodeTries.You couldsubstitutearoutinethatsendsaseriesofshortpipstoindicateabadpassword. PasswordOK ;-------- TickCtr=0 ;Resetthetimer PWOK=Good ;;Goodpassword ;Insertcodetoperformthedesiredtask HSerOut[“PasswordOK”,13] Message=“OK[“ Message(3)=0 GoSubSendMsg Return
Ifthepasswordentryisvalid,“OK”issentbyMorsetothecallingparty.ThesentinelvariablePWOKissetto theconstantGood,therebyindicatingavalidpasswordhasbeenreceived. Returningtothemainprogramloop,wenextchecktoseeifthekeysequencematchesthatofafunction command.
If(InDigits(0)=11)AND(InDigits(CommandLen+1)=12)AND| PWOK=Good)AND(DigitCount=5)Then GoSubFunctionCheck DigitCount=0 EndIf
Rememberthatfunctioncommandsarefourdigitslong.Hencewecheckfora*(value11)atInDigits(0)anda#(value12)atInDigits(5).Ifthekeysequencematchesthefunctioncommandtemplate, weevaluatethekeysequenceatsubroutineFunctionCheck. FunctionCheck ;-------------- ;Remember0isreportedas10 ;weneednumericalsomustzeroit Fori=1to4 IfInDigits(i)=10Then
379
Chapter17
InDigits(i)=0 EndIf Next
First,wemodifyInDigits()toholdthedecimalvaluesofthekeys.Sinceonlythe0keydiffersfromthe decimalvalueofthekeyfacelabel,weonlyneedconvertanyarrayelementwithavalueof10to0. Remember,functioncommandsareoftheformXXYZ,whereXXistheaddress,Yistheapplicationnumber andZistheapplicationvalue.ThevariablesassociatedwiththeseareXX:FcnAdr,Y:AppNoandZ:AppVal.
FcnAdr=10*InDigits(1)+InDigits(2) IfFcnAdr=99Then RingCount=0 TickCtr=0 CodeTries=0 GoSubGoodBye GoToMain EndIf
Weuse*99NN#(whereNNisanydigit0…9)asanexitcommand,sofirstcheckfortheexitcode.Iffound, weusethesubroutineGoodByetoperformthedisconnectsequence.
IfFcnAdr>15Then Message=“ADR?[“ Message(5)=0 GoSubSendMsg FcnAdr=BadData EndIf
ValidX10addressesareintherange0…15,sowecheckforvalidaddresses.Iftheaddressisbad,wesetthe FcnAdrtoaBadDataflagvalueandsendanerrormessagebyMorse.Youmay,ofcourse,substitutebeeps forMorse.
AppnNo=InDigits(3) IfAppnNo>1Then Message=“APP?[“ Message(5)=0 GoSubSendMsg AppnNo=BadData EndIf
Wedothesamethingfortheapplicationnumber,whichisvalidonlyfor0and1.
AppnVal=InDigits(4) IfAppnVal>9Then Message=“VAL?[“ Message(5)=0 GoSubSendMsg AppnVal=BadData EndIf
Wethenchecktheapplicationvalueforvalidity,andsendanerrormessageifitisinerror.
If(FcnAdr<>BadData)AND(AppnNo<>BadData)AND| (AppnVal<>BadData)Then Message(0)=InDigits(1)+“0” Message(1)=InDigits(2)+“0” Message(2)=“,” Message(3)=InDigits(3)+“0” Message(4)=“,” Message(5)=InDigits(4)+“0” Message(6)=“[“ Message(7)=“O” Message(8)=“K” Message(9)=0 GoSubSendMsg ;Insertcodetoactuallyexecutefunction EndIf
380
DTMFToneDecodingandTelephoneInterface TickCtr=0 Return
Ifallthreeelementsofthefunctioncodearecorrect,weechothecodebackviaMorse.Aftersendingthe Morsemessage,weinsertcodetosendthefunctionvalueviaanX10transceivertoX10receivingmodules. Ofcourse,there’snothingstoppingyoufromusingothercontrolapproaches,suchasturningonoroffa relayortriacviasettingorclearingaPICoutputpininresponsetoafour-digitfunctioncode. Theremainderofthemainprogramloopperformssomehousekeepingactivitiesandchecksforattempted passwordbreak-ins. ;Readyfornextdigit DigitCount=DigitCount+1 ;Can’tletitoverflowthearray IfDigitCount=(CodeLen+2)Then DigitCount=0 EndIf ;Topreventbruteforceattackonpassworddisconnectafter ;definednumberofattempts.Coulddelayre-answer IfCodeTries=AttemptsThen HSerOut[“AttemptedCodeBreakin!!”,13] Message=“BAD[PW[“ Message(8)=0 CodeTries=0 GoSubSendMsg GoSubGoodBye GoToMain EndIf GoToCheckForTimeout
IfthecorrectpasswordhasnotbeenenteredinAttemptstries(setat3),anerrormessageissentinMorse andthetelephoneconnectionisbroken.Foradditionalsecurity,youcouldaddadelayloopthatprevents answeringanothercalluntilafteraconsiderabletime,perhapsfiveortenminuteshaspassed. We’venowgonethroughthemainprogramanditssubroutines,sowe’lltakeaquicklookatthevariables andconstants. ;Constants ;-----------;MapsBCDagainstkeycapcaption KeyNameByteTable“D1234567890*#ABC” PassWord Con $012345;MasterPassword CodeLen Con 6 ;digitsincode<<--Donotuse4 Attempts Con 3 ;numberoffalseattemptsbeforetimeout RIPin Con C2 ;!RingIndicator-goeslowonRing OffHook Con C0 ;Off/OnHook.Takehightoreceive TimeOutVal Con 250 ;Timetowaitforvalidpasswordin;seconds/10 CommandLen Con 4 ;commandlength RingVal Con 3 ;Howmanyringsforanswer>>NTE4!!<< Bad Con 0 ;forpasswordstatus Good Con 1 ;forpasswordstatus BadData Con 98 ;Badaddress ;MorseCodeConstants ;-------------------;EncodeMorsecharactersasdi-bitsinaWord: ;-=11 ;.=10 ;Space=01 ;End=00 ;Numbers0...9&SomeSpecials ;-------------,-./01234 ;56789 NumsWordTable|
381
Chapter17 $FAF0,$EAC0,$BBB0,$EB80,$FFC0,$BFC0,$AFC0,$ABC0,$AAC0,$AA80,| $EA80,$FA80,$FE80,$FF80 ;LettersA...Z&SomeSpecials ;-------------?@ABCDEF GHIJKLMNO AlphaWordTable| $AFA0,$BB80,$B000,$EA00,$EE00,$E800,$8000,$AE00,$F800,$AA00,| $A000,$BF00,$EC00,$BA00,$F000,$E000,$FC00,| $BE00,$FB00,$B800,$A800,$C000,$AC00,$AB00,$BC00,$EB00,$EF00,| $FA00,$4000,$ABB0,$AB80 ;PQRSTUVWXYZ ;[space\SK]SN WPM TonePin Dash Dot WSpaceCh EndCh
Con Con Con Con Con Con
30 C1 %11 %10 %01 %00
;speedinWPM ;Pinforbeep/Morseoutput ;DiBitforDash ;DiBitforDot ;DiBitforWordSpace ;endofMorsedibits
Theconstraintsofpagelengthrendersomeoftheembeddedcommentsinthereproducedcodeabitcryptic. Let’slookatwhatarelikelythemostconfusingpartsoftheconstantdefinitions,thoserelatedtotheMorse codesending.Morsecodeiscomprisednotonlyof“dots”and“dashes”but,equallyimportantly,spaces.The durationofdots,dashesandspacesaredefinedwithrespecttothedurationofasingledot.Therelationshipis: 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,isaninfrequentletterisEnglishandisassignedalongsymbol,dash-dash-dot-dash,andrequires14dotlengthstosend—threedashesatfourdotlengthseach(threefor thedashplusoneforthefollowingspace)andonedotoftwodotlengths(oneforthedot,oneforthespace). OurinitialideamightbetousebinarytorepresenttheMorsecharacters,a0fordotsanda1fordashes.In thiscode,Eis%0andQis%1101.Thisisperfectlypractical,asfarasitgoes,buthowdoweknowwhenthe elementscomprisingacharacterend?Wemusthaveanadditionalpieceofinformation—thelengthofeach dot/dashsequence.ThelongestMorsecharacterswe’llusearethepunctuationmarks,withsixelements, suchasthecomma:dash-dash-dot-dot-dash-dash.Ittakesthreebitstostorethenumbers0…7,sowecould thereforerepresentaMorsecharacterusingninebits,organizedas[3bitlengthinformation][upto6bitsof dot/dashsequences].AlthoughnoletterornumberinMorsehasmorethanfiveelements,punctuationmarks do.Hencewemusteitherusea16-bitwordforstorageofeachcharacter,oruseamorecomplexstorage scheme,suchasbytepacking,orbytesforalphanumericcharactersandwordsforallothers. Idecidedtouseadifferentapproach,andencodetheelementsofeachMorsecharacterwith2bits,ora“di-bit”: Element Dash Dot WordSpace EndofCharacter
Di-Bit 11 10 01 00
382
Decimal 3 2 1 0
DTMFToneDecodingandTelephoneInterface Westillmustuse16bitstoholdeachcharacter,butdi-bitencodinggivesusalogicalapproach.Let’ssee howweencodeEandQ,andthecomma: Nibble3 $8 10 00 $F
E
Q ,
11 $F 11
Nibble2 $0 00 00 B 11 11
10 $A 10
Nibble1 $0 00 00 $0 11 10
00 $F 11
Nibble0 $0 00 00 $0 00 11
00 $0 00
00 00
Thus,thehexvaluesforE,Qandcommaare$8000,$FB00and$FAF0,respectively. Finally,wemustdecideinwhichordertoplacetheencodedwords.Wewishtobeabletoeasilyindexinto oneortwowordtable(s)toretrievetheencodedcharacter.ExaminingtheASCIIcollatingsequenceshows thatalthoughwecoulduseonewordtable,itwouldbequitelong.(TheASCIIcollatingsequencecanbe foundatMBasicUser’sGuide,AppendixC.)We’llthereforehavetwotables,onefornumbers0…9andone forlettersA…Z.InlookingovertheASCIIcollatingsequence,itmakessensetoincludethecomma,period, dashandslant(fractionsign)intheirorderimmediatelypreceding0,andtoprecede“A”with“?”and“@,” withthethoughtthatthe“@”signmaybeusedforaspecialcharacter.Likewise,wetackonthecharacters “]”,“\”and“]”afterZ.WeusetheseASCIIcharactersforspecialpurpose“prosign”Morsecharacters. (ProsigncharactersaretwoletterssentasasingleMorsecharacter,thatis,theinter-letterspacingisreduced toaninter-elementspace.Theprosignshavespecialmeanings.) ASCII @ [ \ ]
MorseCharacter AR None SK SN
Meaning Endtransmission WordSpace Endofcontact Understood
Tomaintaincontinuityinouranalysis,let’slookattheMorseroutines. ;FollowingsubroutinessendMorsecode. ;Replacewithbeepsifyoudon’twantMorseoutputs ;--------SendMsg ;Mainsubroutine-SendmessageheldinMessage() ;--------- ;Mustuseuppercase.Use[forspace. ;Message()endswitha0 ixx=0 WhileMessage(ixx)>0 ;areweattheendofmessage? ;checkfornumeric&specialsequence,ifso ;gettheoffsetvalue IfMessage(ixx)>=“?”Then x=Alpha(Message(ixx)-”?”) EndIf ;Ischaracterinrangecommato9? ;Ifsogetitsoffsetvalue If(Message(ixx)>=“,”)AND(Message(ixx)<=“9”)| Then x=Nums(Message(ixx)-”,”) EndIf ;GetDiBitgoingintosendloop DiBit=2*x.Bit15+X.Bit14 WhileDiBit>EndCh ;areweattheend?
383
Chapter17 Return
;WhatistheDiBit?UseSubssocan’tBranch IfDiBit=DotThen:GoSubDitOut :EndIf IfDiBit=DashThen:GoSubDahOut :EndIf IfDiBit=WSpaceChThen:GoSubWspaceOut| :EndIf ;GetthenextDiBit x=x<<2 DiBit=2*x.Bit15+X.Bit14 ;IfthenextdibitisEnd,then ;addaCharacterSpace IfDiBit=EndChThen:GoSubCSpaceOut:EndIf WEND;individualelementofacharacter ixx=ixx+1 WEND;Message(ixx)loop
;Subroutinesbelowsenddot/dashorspace ;StandardMorseisdot/elementspace=1 ;-------DitOut ;------- SoundTonePin,[1000*ELtime\440] PauseElTime Return ;Dashis3xdotplusonespace ;-----DahOut ;----- SoundTonePin,[3000*ElTIme\440] PauseElTime Return ;Characterspaceis3xelementtime ;alreadyhave1spaceafterelement ;-------CSpaceOut ;------- Pause2*ElTime Return ;Wordspaceis7xelementtime ;Alreadyhave3spacesautomaticallyadded ;byendofcharacter ;------WSpaceOut ;------ Pause4*ElTime Return
ThemainsubroutineisSendMessage.Itassumesthatthetexttobesenthasbeenloadedintothebytearray Message()andthatafterthelastcharactertobesentMessage()containsa0,nottheASCIIsymbolfor “0,”but$0. SendMsg ixx=0 WhileMessage(ixx)>0 ;areweattheendofmessage? IfMessage(ixx)>=“?”Then x=Alpha(Message(ixx)-”?”) EndIf If(Message(ixx)>=“,”)AND(Message(ixx)<=“9”)| Then x=Nums(Message(ixx)-”,”) EndIf
384
DTMFToneDecodingandTelephoneInterface SincewehaveputourencodedMorsewordvaluesintoawordtable,inASCIIcollationorder,toobtainthe encodedvalueforanyletter,wesimplyindexintothewordtableusingthelettertobesent,minustheASCII valueofthecharacteratthebaseofthetable.Sincethestartofthetableis“?”forthealphabeticlettersand “,”forthenumericgroup,theoffsetisfoundbysubtracting“?”or“,”fromthelettertobesent.Weusethe wordvariablextoholdtheencodedMorsedefinition. Wethenpeeloffeachdi-bituntilwereachtheendofcharacterdi-bit,%00. Return
DiBit=2*x.Bit15+X.Bit14 WhileDiBit>EndCh IfDiBit=DotThen:GoSubDitOut :EndIf IfDiBit=DashThen:GoSubDahOut :EndIf IfDiBit=WSpaceChThen:GoSubWspaceOut| :EndIf x=x<<2 DiBit=2*x.Bit15+X.Bit14 IfDiBit=EndChThen:GoSubCSpaceOut:EndIf WEND ixx=ixx+1 WEND;Message(ixx)loop
(WedefinedconstantsDot(%10),Dash(%11),WspaceCh(%01)andEndCh(%00)intheconstantsdefinition section.)Baseduponthevalueofeachdi-bit,wegotoanaccordingsubroutine;sendadot(DitOut),senda dash(DahOut)orsendawordspace(WspaceOut.) WhentheWhile/Wendloopreadstheend-of-characterdi-bitEndCh,thecompletecharacterhasbeensent andSendMessagechecksifadditionalcharactersremaininMessage(). TheremainingsubroutinesinourMorsesectionsenddots,dashes,characterspaceorwordspace. ;Subroutinesbelowsenddot/dashorspace ;StandardMorseisdot/elementspace=1 ;-------DitOut ;------- SoundTonePin,[1000*ELtime\440] PauseElTime Return ;Dashis3xdotplusonespace ;-----DahOut ;----- SoundTonePin,[3000*ElTIme\440] PauseElTime Return ;Characterspaceis3xelementtime ;alreadyhave1spaceafterelement ;-------CSpaceOut ;------- Pause2*ElTime Return ;Wordspaceis7xelementtime ;Alreadyhave3spacesautomaticallyadded ;byendofcharacter ;------WSpaceOut ;------ Pause4*ElTime Return
385
Chapter17 Alltimingistiedtothebasicunit,elementtime,ElTime,calculatedfromthedesiredwordsperminute speed.I’veselectedatonepitchof440Hz,asit’smypersonalpreference.ManypeopleprefertheirMorse tobereceivedwithapitchofabout800Hz.SinceMBasic’sSoundfunctionrequiresitsdurationargument inmicroseconds,andElTimeisinmilliseconds,wemultiplyby1000toconvertmstoµs. And,incaseyoudon’thaveit,here’stheMorse“cheatsheet.” 0
_
_
_
_
_
M
_
_
1
.
_
_
_
_
N
_
.
2
.
.
_
_
_
O
_
_
_
3
.
.
.
_
_
P
.
_
_
.
4
.
.
.
.
_
Q
_
_
.
_
5
.
.
.
.
.
R
.
_
.
.
. _
6
_
.
.
.
.
S
.
7
_
_
.
.
.
T
_
8
_
_
_
.
.
U
.
.
9
_
_
_
_
.
V
.
.
.
A
.
_
W
.
_
_
B
_
.
.
.
X
_
.
.
_
.
Y
_
.
_
_
Z
_
_
.
.
?
.
.
_
_
.
“/”
_
.
.
_
.
.
.
_
.
_
.
_
,
_
_
.
.
_
_
=
_
.
.
.
_
C
_
.
_
D
_
.
.
E
.
F
.
.
_
G
_
_
.
H
.
.
.
I
.
.
J
.
_
_
K
_
.
_
L
.
_
.
. . _ .
_
SK
.
.
.
_
.
AR
.
_
.
_
.
SN
.
.
.
_
.
.
_
Wenowreturntothevariabledeclarations. ;Variables ;----------BCDOut FcnInput DigitCount DigitVal InDigits i CodeTries RI TickCtr RingCount PWOK
Var Var Var Var Var Var Var Var Var Var Var
Byte ;PortBvalue Long Byte ;howmanydigitsreceived? BCDOut.Nib0 ;outputnibble Byte(CodeLen+2);holdsreceivedbcd Byte ;counterforwork Byte ;Howmanytriesforpassword PortC.Bit2 ;RingIndicator Byte ;Timertickcounter(0.1sec/tick) Byte ;Howmanyringsreceived Byte ;Passwordrcvd=1Notrcvd=0
;CommandisFcnAdr+AppnNo+AppnVal FcnAdr Var Byte ;2digits AppnNo Var Byte ;1digit AppnVal Var Byte ;1digit ;MorseCodeVariables ;------------------ELtime Var Word ixx Var Byte
;Elementlengthinmilliseconds ;Loop
386
DTMFToneDecodingandTelephoneInterface DiBit x Message
Var Var Var
Byte ;elementvariable Word ;tempvariable Byte(32);messagetobesent
Program17-3isfarfromafinishedproduct.Forexample,it’simportantthatasoftwareglitch,perhaps causedbyamomentarypowerinterruption,notresultintheCH1837Aseizingthephonelineandnotreleasingit.SuchafeaturemightmakeuseofthewatchdogtimerinadditiontoemployingMBasic’sONBOR brownoutresetcommand.
IdeasforModificationstoProgramsandCircuits •
•
• •
Althoughwe’veusedtheCH1837Atoautomaticallyansweracall,itcanjustaseasilyoriginateacall. TakingitsOFFHKpinhighwillcausetheservingcentralofficetosenddialtoneandwaitforacall.If yousendtouch-tonesignalsthroughtheCH1837A’sTXport,theywillbetreatedjustasmanualdialing.Howmightyouuseautomaticcallorigination?(Remember,MBasichastwofunctionstogenerate touch-tonesignals,DTMFOutandDTMFOut2.) o Developaremotetemperaturealarm.UseaDS18B20temperaturesensortosensetemperatureand automaticallycallaprogrammednumberifthetemperaturedropsbelowadefinedlimit.Whatpracticalconsiderationsenterintosuchaprogram?Howdoesthecallingprogramknowthatdialtone hasbeenplacedontheline?Howmanytimesshoulditattempttomakeacall? o Makeanautomaticdialertoworkinconjunctionwithaconventionaltelephone.HowdoyouconnectthetelephoneandCH1837A? TheCH1837Amayserveastheheartofaspeakerphone.Asmallamplifier,suchastheLM386for receivedaudio,amicrophoneandamplifierfortransmittedaudioandaPICfordialingandcontrolcompletethedesign.Howwouldyouassembleaspeakerphone?Howwouldyoupreventfeedbackbetween thespeakerandmicrophone,sincethehybridcancellationisnotperfect? SupposeyouwishtosendslowbitrateinformationusinginexpensiveFamilyRadioServicelowpower UHFradiotransceivers.Forexample,youmightwishtoremotelytelemeterwaterlevelatacreek.Is thisanappropriateuseoftouch-tonesignaling?Howmightyousensestreamlevelandsenditback? HowwouldyouaddaLCDdisplaytoProgram17-3?Whatlocalcontrolfeatureswouldyouadd?
387
Chapter17
References [17-1]
Motorola,Inc.,MC145436ALow-PowerDualToneMultipleFrequencyReceiver(1996). MitelNetworksCorp.,MT8870D/MT8870D-1IntegratedDTMFReceiver,(undated). [17-3] CermetekMicroelectronics,Inc.,CH1837A/7F/8ADataAccessArrangementModuleV34.bisHigh SpeedDAAModule(2002). [17-4] Hedley,David,ConnectingaPICmicroMicrocontrollertoaStandardAnalogTelephoneLineAN854, MicrochipTechnologies,Inc.,DocumentNo.DS00854A(2002). [17-5] Hulous,Joel&Morel,Patrice,ApplicationNotePhoneRemoteSystem,AN488/0695,SGS-Thompson Microelectronics(1995). [17-6] Deosthali,Amey,etal.,ALow-ComplexityITU-CompliantDualToneMultipleFrequencyDetector, IEEETrans.OnSignalProcessing(Oct.1999).(Implementedwitha16C711.) [17-7] PhilipsSemiconductors,ApplicationNoteDataaccessarrangement(DAA)AN812(2003). [17-8] Lancaster,Don,TechMusingsNo.127,(August1998).Downloadableathttp://tinaja.com/glib/ muse127.pdf. [17-9] MicrochipTechnologies,Inc.,DTMFDecodingonPIC18,DocumentDTF18,presentedatMicrochip’s 2003Master’sConference;availableathttp://techtrain.microchip.com/masters2003/. [17-10] ConstantinescuRadu,DTMFRemotecontrol–AsoftwareDTMFdecoderforPIC16F87X,including associatedassemblercode,availableathttp://www.geocities.com/constantinescuradu/content/dtmf.htm. ImplementsasoftwareDTMFdecoder,relaycontrollerandLCDdisplayinsome2200linesofassemblercode. [17-11] AT&TCompany,LongLinesDepartment,PrinciplesofElectricityappliedtoTelephoneandTelegraph Work(1953).Probablybestknownas“theGreenBook,”usedastrainingtextbytheBellSystemfor manyyears.Ifyouareatallinterestedinhowtheclassicaltelephonesystemwasbuilt,searchtheused bookstoresforacopy. [17-12] AT&TCompany,NetworkPlanningDivision,NotesontheNetwork,(1980).Originallypublishedas NotesonDistanceDialing,andsubsequentlypublishedunderothernames,suchasBellcoreNoteson theNetworkand,mostrecently,TelcordiaNotesontheNetwork.Thecurrentpricetagof$575fora printedcopyofTelcordiaNotesontheNetwork,however,isdifficulttojustifyunlessyouareinvolved inthetelecombusiness. [17-2]
388
18
CHAPTER
ExternalMemory TherearetimeswhentheinternalRAMandEEPROMmemoryinaPICjustisn’tenough.Youmightwish tosavesensorreadingsforlateranalysis,orperhapsyourprogramdisplayslongtextstringsthatcan’tbe squeezedintotheavailablememory.Inthischapter,we’lllookattwotypesofexternalmemory—slowserial EEPROMdevicesandfastparallelstaticRAM(SRAM)chips.
I2C-BusDevices Serialmemorychipareavailableinseveralinterfaceprotocols.Sincewe’vealreadystudied1-wireandSPI (3-wire)serialprotocolsinothercontexts,tolearnsomethingnewwe’lllimitourexaminationofexternal memorychipstothoseemployingthe“InterIC”bus,orI2C,originallydevelopedbyPhilipsSemiconductors,butwidelyadoptedbyothermanufactures.Althoughwe’llstudyitinthecontextofexternalmemory, manyotherchips,suchasLCDcontrollers,analog-to-digitalconvertersandfrequencysynthesizersareI2C buscontrolled. TheI2Cshareselementsofboththe1-wireandSPIprotocols,but,asmightbeexpected,addsitsown flavors.SinceMBasic’sI2CoutandI2CinfunctionsencapsulatethedetailsofI2Ccommunications,we’ll satisfyourselveswithanoverviewoftheprotocol.I2Cisatwo-wireinterface,withseparateclockanddata lines.Originallythedataspeedwassetatamaximumof100Kbits/s,nowcalledthe“standard”mode,but newerdevicesareratedat400Kbit/s,or“fast”modeorupto3.4Mbit/s,the“high-speed”mode.I2Cout andI2Cinsupportonlystandardmodedatatransfers,butallhigherspeeddevicesremaincompatiblewith standardmodedataspeeds.Atanyinstant,onedeviceontheI2Cbusisthemasteranditcommunicateswith aslavedevice.Themasterdevicegeneratestheclock,andinitiatesandterminatesdatatransfer.Duringdata transfer,themasterandslavedevicesalternatetransmittingandreceivingdata. AswiththeSPIprotocol,severalI2Cdevicesmaybeparalleledfromasinglepairofclockanddatalines, butindividualchipselectlinesarenotrequired.Rather,individualI2CdevicesareselectedbyacombinationofhardwareaddressandcommandbytefamilyIDcode.We’llseehowthisworkswhenweparalleltwo 24LC256memorychips. TheI2Cstandardscontemplatemultiplemicrocontrollersononebus,includingpossibleinter-controller communications,i.e.,microcontrollersmaybeeitherslavesormastersandmayalternatethatrole.And,a busmayhavemultiplemasters.Mastermicrocontrollerscommunicateonlywithslavemicrocontrollers; master-to-mastercommunicationsisnotallowed.MBasic’sI2CoutandI2Cinproceduressupportonly masteroperationandhencecannotbeusedforinter-PICcommunications. Finally,we’llseethatalthoughtheI2Cprotocoliswellstandardized,memorychipmanufactureshavenot alwaysapproachedchipoperationconsistently.
389
Chapter18 24LC16B16KbitEEPROM Let’slookasimpleapplication,readingandwritingtoa16kbitEEPROMchip,aMicrochip24LC16B. Bytheway,thestandardidentificationsystemforgenericserialEEPROMchipsstartswiththenumber24, followedbyanidentifyingletterortwoindicatingitsmanufacturingprocessandpossibilyitsvoltagerating, endingwithdigitsindicatingthenumberofkilobitsofdatacapacity.Hencea24LC16Bisalow(L)voltage capable(2.5Vto5.5V)memorychipmanufacturedwithCMOS(C)technology,andwithadatacapacityof 16kbits.(Microchip’s24AA16isanextendedvoltagerangechip,operatingdownto1.8V.)Sincewewill readandwritein8-bitbytes,the24LC16B’sstoragecapacityisperhapsmoreusefullystatedas2Kbytes. Figure18-1showshowweconnectthe24LC16BtoaPIC.Don’tforgetthepullupresistor!Thethree“chip address”pins,A0,A1andA2arenotusedonthe24LC16Bandhenceareleftunconnected.(We’llseethese inuseinconnectionwithProgram18-2.)Thegenericconnectionsfor24-familydevicesare:
Figure18-1:Connectinga24LC16BI2CEEPROMchip.
PinName A0 A1 A2 VSS
8-pinDIPPin Number 1 2 3 4
SDA
5
SCL
6
WP
7
VDD
8
FunctionandComments ChipaddressbitA0inmost24-familydevices;unusedin24LC16B ChipaddressbitA1inmost24-familydevices;unusedin24LC16B ChipaddressbitA2inmost24-familydevices;unusedin24LC16B Ground(IdentifiedasGndbysomemanufacturers) SerialData.Thisisanopendrainpinandmusthaveapull-upresistor.10Kisa suitablevalueforStandardSpeeddatatransfer. SerialClock WriteProtect(activehigh).Whenhigh,thedeviceisread-only;forreadandwrite mustbelow. Pluspowersupply;+5Vinourbreadboarddesigns.(IdentifiedasVCCbysome manufacturers.
We’vearbitrarilydecidedtousethePIC’sA0pinasthedata(SDA)connection,anditsA1pinastheclock (SCL)connection. Program18-1showshowwewritetoandreadfromthe24LC16B. Program18-1 ;Program18-1toread/write ;16Kbit24LC16BSerialEEPROM ;I2Ccommunications ;Demonstraterandomread/write ;Constants ;--------Clk
Con
A0
;clockisonA0
390
ExternalMemory Dta RCtrl Con DisplayCon
Con
A1 ;dataonA1 ;havetoaddthepageselecttoCtrl ;8-bitaddressword,soendsin0 %10100000 ;controlwordstartingpoint 1;setto0toblockwritingtoserialport
;Variables ;---------PSel CtrlB i j InStr
Var Var Var Var Var
Byte Byte
;Pageselector ;controlbyte Word ;index Byte ;bytevalueto/from25LC16B Byte(12) ;textstring
;Initialization ;-------------;Communicatewithoutsideworldviaserial EnableHSerial SetHSerialH19200 Main
;Demonstraterandomaccessbyteatatime ;16LC16Bisorganizedas8pagesof256bytes. ;The8pagesareaddressedinthecontrolbyte Fori=0to2047 ;CtrlBytepageaddressisBitsBit3/Bit2/Bit1 CtrlB=(i.HighByte*2)+RCtrl ;TowritesomethingdistinctivetoRAM ;wewritetheindexplustheoffset j=i.LowByte+i.HighByte ;Writetoaddressedmemory I2COutDta,Clk,ErrorMsg,CtrlB,i.LowByte,[j] Pause4 IfDisplay>0Then HSerOut[“Writei:“,Deci,| “Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf Next j=0 ;Nowreaditback Fori=0to2047 ;Setupthecontrolbyteinthesameway CtrlB=(i.HighByte*2)+RCtrl I2CInDta,Clk,ErrorMsg,CtrlB,i.LowByte,[j] IfDisplay>0Then HSerOut[“Readi:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf Next ;Now,atotallyrandomwriteandread,toproveit ;tothedoubtful i=1111 CtrlB=(i.HighByte*2)+RCtrl j=77 HSerOut[“CustomWritei:“,Deci,”Data:“,Decj,13] Pause50 I2COutDta,Clk,ErrorMsg,CtrlB,i.LowByte,[j] j=0 ;Ifpause<4,I2COuthangsup Pause4 I2CInDta,Clk,ErrorMsg,CtrlB,i.LowByte,[j] HSerOut[“CustomReadi:“,Deci,”Data:“,Decj,13] Pause50
391
Chapter18 TextWrite: ;How,let’strytextread/write i=0 InStr=“xxxxxxxxxxxx” CtrlB=(i.HighByte*2)+RCtrl ;Writetoaddressedmemory I2COutDta,Clk,ErrorMsg,CtrlB,i.LowByte,[“HelloWorld!”] HSerOut[“Writei:“,Deci,”Data:“,StrInStr\12,13] Pause50 i=0 ;Setupthecontrolbyteinthesameway CtrlB=(i.HighByte*2)+RCtrl I2CInDta,Clk,ErrorMsg,CtrlB,i.LowByte,[StrInStr\12] HSerOut[“Readi:“,Deci,”Data:“,StrInStr\12,13] ;delayneededtoletHSerOutflushbeforeEnd! Pause50 End ;GoToMain ErrorMsg HSerOut[“Error!”] Pause50 End
Let’sfirstlookatMBasic’sI2Csupportfunctions,I2CoutandI2CinasweuseitinProgram18-1.
I2COutDta,Clk,ErrorMsg,CtrlB,i.LowByte,[j]
I2Coutisinvokedwithsixarguments:
Dta—Aconstantorvariabledefiningthepinusedforthedataline.SincewewishtousepinA1asthedata line,weearlierdefinedaconstantDtaasA1. Clk—Aconstantorvariabledefiningthepinusedfortheclockline.SincewewishtousepinA0asthe clockline,weearlierdefinedaconstantClkasA0. ErrorMsg—Anoptionalprogramlabeltowhichexecutionwilljumpintheeventofanerrorcommunicating withtheslavedevice.Program18-1hasabrieferrorroutinethatwritesanalertmessagetotheserial port. CtrlB—Thecontrolbytethatselectsthechipandcertainoptions,aswewillseebelow. i—Anoptionalmemoryaddresstowhichtowrite.Ifthememoryaddressisomitted,theexternalmemory chipusesitsinternaladdresscountertowritetothenextaddress.Theinternaladdresscounterincrementsaftereachbyteiswritten.Inmostcases,however,wewillwishtowriteandreadatspecific addressesandhencewilluseanexplicitmemoryaddress.Aswe’llseelater,iisawordvariableand 24LC16B’srequiresabyte-lengthmemoryaddress,soweusei’sloworderbyte. [Argument]—ThespecificdatatobewrittentotheEEPROMappearsinthesquarebrackets[],where MBasic’sstandardmodifier/expressionrulesapply.Myexperiments,however,showthatthedatatobe writtenmustbeintheformofindividualbytes,suchas[Byte1,Byte2,Byte3…]oranarrayofbytes suchas[“HelloWorld!”].Iwasunabletosuccessfullywriteorreadwordorlongvariableswithout breakingthemup—thatis,[WordVar]fails,but[WordVar.Byte1,WordVar.Byte0]works. Let’slookatthecontrolbyte.It’scomprisedofthreeelements: Bit7
DeviceFamilyCode Bit6 Bit5
ChipAddressingInformation Bit3 Bit2 Bit1
Bit4
8/16Bit Bit0
DeviceFamilyCode—Theuppernibbleofthecontrolbytedefinesthefamilytype.TheEEPROMchipswe areinterestedinare“GroupA”devices,sotheirfamilycodeis$A,or%1010.The16possiblefamily codesareasfollows:
392
ExternalMemory Group 0 1 2 3 4 5 6 7 8 9 A B C D
Bit7 0 0 0 0 0 0 0 0 1 1 1 1 1 1
Bit6 0 0 0 0 1 1 1 1 0 0 0 0 1 1
Bit5 0 0 1 1 0 0 1 1 0 0 1 1 0 0
Bit4 0 1 0 1 0 1 0 1 0 1 0 1 0 1
E F
1 1
1 1
1 1
0 1
DeviceGroupTypes Generalcall Digitalreceivers&demodulators FMandTVrelated CD-ROMandaudiorelated MPEG,speech,DAC,DTMF,pagers UnidentifiedbyPhilips Computermonitordevices LCDcontrollers,videocontrollers AudioandTVprocessorsanddecoders TVprocessors EEPROM AudioandTVprocessorsanddecoders RadioandTVRFdevices,frequencysynthesizers Miscellaneous,includingclock/calendar,mobile telephone,satellite. Specialpurpose Reserved
SomenewerI2Cdevicesusea10-bitcontrolsequence,butI2CinandI2Coutdonotsupportthismode. 8/16-bitaddressing—We’lltaketheremainingtwoelementsoutoforder.Bit0determineswhetherthe EEPROMaddressinformationsentimmediatelyfollowingthecontrolbyteisasingle8-bitbyte(256 possibleaddresses)ora16-bitword(65536possibleaddresses).IfBit0is0,theaddressissentasan 8-bitbyte;ifBit0is1,theaddressissentasa16-bitword. IfyoulookatthecontrolbytedefinitioninadatasheetforanI2Cdevice,youwillfindthatBit0isdefined asthe“read/write”orR/Wbit,andthatitdeterminesthedirectionofdatatransfer;if0,themastersends andif1,theslavesends.However,MBasic,forreasonsofcompatibilitywithotherversionsofPICBASIC, automaticallyinsertsthecorrectR/WbitandinsteadusesBit0ofthecontrolbyteforaddresslengthinformation.It’seasytogetconfused,sothisisanothercasewhereattentiontodetailiscritical. Todeterminewhetherthe24LC16Brequires8-bitor16-bitaddressing,weconsultitsdatasheet.Wesee thatthememoryisorganizedas“eightblocksof256×8-bitmemory,”andthatthebytewriteandbyteread instructionsshowan8-bitaddress.Hence,wesetBit0as0inpreparingthecontrolbyte. AddressingInformation—PerhapsthemostconfusingaspectsofusingserialEEPROMdevicesisunderstandinghowthethreechipaddressbitsinthecontrolbyteareused.We’llseeeachofthefour EEPROMsmodelsexaminedinthischapterhasadifferentchipaddressbitconfiguration. DeviceType
Bit3
Bit2
Bit1
24LC16B
B2
B1
B0
AT24C256
0
A1
A0
AT24C512
0
A1
A0
Comments B2,B1andB0areblockselectionbits;theyselectwhich ofeight256-bytememoryblocksisactive.[Requires8-bit memoryaddressingwithineachblock.] A1andA0selectthechipaddressmatchofPinsA0and A1.[Memoryisorganizedasone32K-byteblock;noblock selectionbit.Requires16-bitaddressing.] A1andA0selectthechipaddressmatchofPinsA0and A1.[Memoryisorganizedasone64K-byteblock;noblock selectionbit.Requires16-bitaddressing.]
(Continued)
393
Chapter18 DeviceType
Bit3
Bit2
Bit1
24FC515
B0
A1
A0
Comments B0selectswhichoftwo32K-bytememoryblocksisactive; A1andA0selectthechipaddressmatchofPinsA0andA1. [Requires16-bitmemoryaddressingwithineachblock.]
Aswelearnedearlier,the24LC16B’s2048bytesofmemoryisorganizedaseight256-byteblocks.The threechipaddressbitsdefinewhichblockisactive.Towritetoblock2(%010),forexample,thecontrolbyte willbe%10100100.Ifwearetowritethevalue99tomemorycellno.34(startingfrom0)inblock2,our commandwillbeI2CoutDta,Clk,ErrorMsg,%10100100,34,[99]. Weratherwouldhaveaflat,orlinear,addressspace,thatwemightaddressfrom0…2047,insteadofworryingaboutblocksandoffsetineachblock.Usingiastheword-lengthaddressfrom0…2047,wecan constructthecontrolbyte,CtrlB,asfollows:
CtrlB=(i.HighByte*2)+RCtrl
Sinceiisawordvariable,i.LowByteissimplythe0…255individualblockoffset.Thehighbyte, i.HighByte,runsfrom0…7asigoesfrom0…2047.Wethereforeinsertthelowthreebitsof i.HighByteintoP2/P1/P0ofCtrlB,bymultiplyingi.HighByteby2(functionallyequivalenttoshiftingthebitsoneplacetotheleft)andaddingtheresulttoCtrlB.WehavedefinedtheconstantRCtrlas %10100000inProgram18-1,addingitto(i.HighByte*2)yieldsthecompletecontrolword. Withthisunderstanding,let’sexaminethewriteloopinProgram18-1:
Fori=0to2047 CtrlB=(i.HighByte*2)+RCtrl j=i.LowByte+i.HighByte I2COutDta,Clk,ErrorMsg,CtrlB,i.LowByte,[j] Pause4 IfDisplay>0Then HSerOut[“Writei:“,Deci,| “Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf Next
Ourdemonstrationprogramwritesanarbitrarybytevaluetoeachofthe2048memorylocationsinthe 24LC16B.Ratherthanwritethesamevalue,we’llwriteuniquevalue,j,wherej=i.LowByte+i. HighBytetoeachmemorycell.Eachmemorycellthuscontainsthesumofits0…255indexplustheblock number.Sincememorycellsarebytelength,jrollsoverto0wheni.LowByte+i.HighByteexceeds255. If,forexample,i.LowByte+i.HighByteis257,jholdsthevalue2.Withthisunderstanding,thewrite commandshouldbeclear:
I2COutDta,Clk,ErrorMsg,CtrlB,i.LowByte,[j] Pause4
EEPROMsrequiretimetowritetomemory,withthedevicesweuseinthischapterhaving5msmaximum writecycleduration.Weaccordinglypausefor4ms,withtheremainingcycletimebeingtheoverheadassociatedwiththeremainderofthecodeintheForiwriteloop.It’simportantnottoforgetthewritecycle timewhenwritingtoEEPROM. Theremainderofthewriteloopwrites,ifdesired,iandjtotheserialport,wheretheprogressmaybe observed. Afterwritingthedata,wenextreaditback.
;Nowreaditback Fori=0to2047 ;Setupthecontrolbyteinthesameway CtrlB=(i.HighByte*2)+RCtrl
394
ExternalMemory
Next
I2CInDta,Clk,ErrorMsg,CtrlB,i.LowByte,[j] IfDisplay>0Then HSerOut[“Readi:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf
Thecodeforreadingthe24LC16Btracksthewritecode,exceptthatweuseMBasic’sI2Creadprocedure, I2Cin: I2CInDta,Clk,ErrorMsg,CtrlB,i.LowByte,[j]
SinceI2CinisanexactanalogofI2Cout,withthesameargumentswewillnotfurtherdiscussit,except toaddareminderthatBit0inCtrlBisthe8/16-bitswitch,andisnotaread/writeselectorbit.MBasicautomaticallyaddstheappropriateread/writeselectorbit.Notealsothatnodelayisrequiredafterreadingthe EEPROM.Afterthedataisreadweoptionallywriteittotheserialport. We’vesofardemonstratebyte-at-a-timereadingandwriting,butI2CoutandI2Cinsupportmultiplebyte writesandreads.Let’sseehowthisworkswithabytearraystring.
;How,let’strytextread/write i=0 InStr=“xxxxxxxxxxxx” CtrlB=(i.HighByte*2)+RCtrl ;Writetoaddressedmemory I2COutDta,Clk,ErrorMsg,CtrlB,i.LowByte,[“HelloWorld!”] HSerOut[“Writei:“,Deci,”Data:“,StrInStr\12,13] Pause50 i=0 ;Setupthecontrolbyteinthesameway CtrlB=(i.HighByte*2)+RCtrl I2CInDta,Clk,ErrorMsg,CtrlB,i.LowByte,[StrInStr\12] HSerOut[“Readi:“,Deci,”Data:“,StrInStr\12,13] ;delayneededtoletHSerOutflushbeforeEnd! Pause50
We’vearbitrarilywrittenthetextstringatmemoryaddress0,butalmostanyaddressintherange0…2047 couldhavebeenused.Ofcourse,wecan’tstartwriting12bytesat2047andexpectthemtobesaved.More subtly,however,whenwritinginthisfashionwecannotspanablockboundary.Let’slookatanexample. Supposewestartwritingati=253.Thiswritesthefirstthreecharactersof“HelloWorld!”atblock0,locations253,254and255,buttheremainingcharacterswillnotbewrittenatBlock1,locations0…8.Rather, sincetheblockselectbitsdonotchangefrom000duringthemultibyteI2Coutprocedure,theremaining ninecharacterswillbesavedatblock0, locations0…8.Likewise,wecannotread acrossthe24LC16B’sblockboundariesin oneI2Cinstatement.Ifweareconcerned withspanningblockboundaries,wemust reverttoasystemsuchasthatseenearlier intheprogram,writingandreadingone byteatatime,witheachbytehavingits ownI2Coutstatementanditsowncontrol byte.
Multiple24LC256256Kbit EEPROMs We’llnowturnourattentiontoparalleling multipleserialmemorychips.Figure18-2 Figure18-2:Multiple24LC256SerialEEPROMs.
395
Chapter18 showstwoparallel24LC256256Kbitserialmemorydevices.Figure18-2followsFigure18-1,exceptfor thethreechipaddresspins,A0,A1andA2.The24LC256datasheetshowsthatA0,A1andA2areallactive addresspins. ByselectivelysettingA0,A1andA2ateithergroundorVDD,weassigneach24LC256auniquechipaddress.Sincewehavethreechipaddresspins,wehave23,oreight,possibleuniqueaddresses,0…7.We’ve assignedU1’saddressas%000bygroundingA2,A1andA0.BysettingU2’sA0pintoVDD,we’vesetits addressat%001,or1.Onelastpoint;don’tforgetthe10Kpull-upresistoronthedataline. Program18-2exercisesthepairof24LC256EEPROMsjustaswedidthe24LC16B.However,sincethe 24LC256issetupasasingle32Kbytearray,with16-bitaddressing,wemustmakesomeadjustmentstothe codefromProgram18-1. Program18-2 ;Program18-2toread/write ;selectivelytotwo256Kbit24LC256SerialEEPROM ;I2Ccommunications;Demonstraterandomread/write ;Constants ;--------Clk Dta RCtrl Display Adr0 Adr1
Con Con Con Con Con Con
A0 A1 1 0 1
;clockisonA0 ;dataonA1 ;havetoaddthepageselecttoCtrl ;16-bitaddressword,soendsin1 %10100001 ;controlwordstartingpoint ;setto0toblockwritingtoserialport ;Addressof24LC256No.1A0=A1=A2=0 ;Addressof24LC256No.2A0=1A1=A2=0
;Variables ;---------CtrlB i j InStr
Var Var Var Var
Byte ;controlbyte Word ;index Byte ;bytevalueto/from25LC256 Byte(12);textstring
;Initialization ;-------------;Communicatewithoutsideworldviaserial EnableHSerial SetHSerialH19200 Main
;Demonstraterandomaccessbyteatatime ;16LC256isorganizedasone32Kbytepage. ;Upto8chipsareaddressedinthecontrolbyte Fori=0to65535 ;$FFFE ;ChipSelectaddressis:Bit3/Bit2/Bit1 CtrlB=RCtrl CtrlB.Bit1=i.Bit15;selectoneoftwo32Kchips ;TowritesomethingdistinctivetoRAM ;wewritetheindexplustheoffset j=i.LowByte+i.HighByte ;Writetoaddressedmemory I2COutDta,Clk,ErrorMsg,CtrlB,i,[j] Pause4
396
ExternalMemory End
Next
IfDisplay>0Then HSerOut[“Writei:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf
j=0 Pause50 HSerOut[“EndofWrite”,13] Pause50 ;Nowreaditback Fori=0to65535 ;Setupthecontrolbyteinthesameway ;ChipSelectaddressis:Bit3/Bit2/Bit1 CtrlB=RCtrl CtrlB.Bit1=i.Bit15;selectoneoftwo32Kchips I2CInDta,Clk,ErrorMsg,CtrlB,i,[j] IfDisplay>0Then HSerOut[“Readi:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf Next ;Proveaccessistruelyrandom,readaddress12345. ;Shouldhave(12345-12288)=57plusoffset. ;12288-12543hasoffset48,soweexpecttoread105. i=12345 CtrlB=RCtrl CtrlB.Bit1=i.Bit15;selectoneoftwo32Kchips I2CInDta,Clk,ErrorMsg,CtrlB,i,[j] HSerOut[13,”CustomReadi:“,Deci,”Data:“,Decj,13] Pause50 ;How,let’strytextread/write i=45000 InStr=“xxxxxxxxxxxx” CtrlB=RCtrl CtrlB.Bit1=i.Bit15;selectoneoftwo32Kchips ;Writetoaddressedmemory I2COutDta,Clk,ErrorMsg,CtrlB,i,[“HelloWorld!”] HSerOut[“Writei:“,Deci,”Data:“,StrInStr\12,13] Pause50 i=45000 ;Setupthecontrolbyteinthesameway CtrlB=RCtrl CtrlB.Bit1=i.Bit15;selectoneoftwo32Kchips I2CInDta,Clk,ErrorMsg,CtrlB,i,[StrInStr\12] HSerOut[“Readi:“,Deci,”Data:“,StrInStr\12,13] ;delayneededtoletHSerOutflushbeforeEnd! Pause50
ErrorMsg HSerOut[“Error!”] Pause50 End
SinceProgram18-2largelyduplicatesProgram18-1we’llconcentrateonthedifferences.Althoughwehave twoseparate32Kbytememories,we’lladdressthemasifwehadone64Kbytememory. WehavewiredU1andU2withchipaddresses0and1,respectively.Further,the24LC256’sdatasheet statesthatthememoryisorganizedasasingle32K×8-bitblockandthatconsequently15memoryaddress bitsarerequired.(Weactuallywrite16bits,butthe24LC256ignorestheleadingbit.)Basedonthisinformation,wecandefinethecontrolbytestoaddressU1andU2.
397
Chapter18 DeviceFamilyCode Fig18-2Chip U1 U2
Bit7 1 1
Bit6 0 0
Bit5 1 1
Bit4 0 0
ChipAddressing Information Bit3 Bit2 Bit1 (A2) (A1) (A0) 0 0 0 0 0 1
8/16Bit Bit0 1 1
AsinProgram18-1,wewouldlikeaseamlesslinearaddressspace0…65535sowedon’thavetoworry aboutindividualchipaddressing.Let’sseehowweaccomplishthis.
Fori=0to65535 ;$FFFF CtrlB=RCtrl CtrlB.Bit1=i.Bit15;selectoneoftwo32Kchips j=i.LowByte+i.HighByte I2COutDta,Clk,ErrorMsg,CtrlB,i,[j] Pause4 Next
Forclarity,theabovecodefragmentisstrippedofcommentsandserialwritecommands.Westartbynoting thatearlierintheprogramwedefinedtheconstantRCtrltoholdthebaselinecontrolbyte.(Sincewemust use16-byteaddressing,RCtrl.Bit0is1,unlikethecaseinProgram18-1.) RCtrl
Con
%10100001
WethensetthebytevariableCtrlBtoRCtrl.
CtrlB=RCtrl
NowweinsertthechipaddressbitsintoCtrlB,asnecessary. CtrlB.Bit1=i.Bit15
Bydefiningthetwochipaddressesas0and1,wegreatlysimplifysettingthecontrolbyte’saddressbits. Wheni<=32767,i.Bit0is0;wheni>32767,i.Bit0is1.Hence,toautomaticallyswitchbetween U1andU2whenevericrossesoverthe32Kboundaryallweneedtoistocopyi.Bit0tothecontrolbyte’s A0position,CtrlB.Bit1.IfwehadassignedU1andU2differentaddresses,suchas3and5,respectively, wewouldneedamorecomplicatedassignmentscheme,likelyinvolvinganIfi.Bit15=0Then… construction.It’smoreelegant,nottomentionyieldingfasterexecutingcode,towirethechipaddressesas0 and1andmakeasimplebitassignment. Ifweusefour24LC256memorychips,forexample,andwiretheiraddressesas0,1,2and3,thissimple bitassignmentiseasilyextended.Inthiscase,ofcourse,theindeximustbeatypelongvariable,andit’s necessarytoassigntwobits(i.Bit15andi.Bit16)toCtrlB,buttheconceptisidentical.
j=i.LowByte+i.HighByte
AsforProgram18-1,weconstructauniquebytejtobewrittentomemorybysummingi.LowByteand i.HighByte.
I2COutDta,Clk,ErrorMsg,CtrlB,i,[j]
Finally,wewritejtoEEPROM,usingtheI2Coutprocedure.Note,however,weuseall16bitsofiinthe I2Coutprocedure,andwedonotforcei.Bit15to0toaccommodatetheeach24LC256’s32Kaddress spacelimit.Wecangetawaywiththistimesavingmeasurebecausethe24LC256’sdatasheetdefinesthisas a“don’tcare”bit,ignoredwhenthechipinternallydecodesthereceived16addressbits. TheremainderofProgram18-2isidenticalwithProgram18-1,saveforthosechangesrelatingtotheaddressing.Beforewelookatthenextmemorychipvariation,however,weagainremindourselvesthatwe cannotcontinuouslyreadorwriteacrosschipboundarieswithamultiple-byteI2CinorI2Coutstatement. OnefinalnoteapplyingtoMBasicversionsearlierthan5.3.0.0;I2CinandI2Coutprocessesfreezewhen addressingmemory65535.Thisproblemisfixedinversion5.3.0.0onward. 398
ExternalMemory 24LC515 Let’slookatthe24LC515EEPROMnext.Itisa64K×8-bit device,organizedastwobanksof 32K×8-bitmemory.Asusual,we startbyexaminingthedatasheet, andfindtheusualthreechipaddresspins,A0,A1andA2havea peculiarity;A0andA1arenormal addresspins;A2isa“nonconfigurableChipSelect”whichmustbe Figure18-3:Connectinga24LC515EEPROMDevice. tiedtoVDDforthe24LC515to function.Accordingly,asshownat A2isstrappedtoVDD,whileA0andA1arestrappedtoground,yieldingachipaddressof0. Finally,welearnfromthedatasheethowtoselectbetweenthetwo32K×8-bitbanksinthe24LC515. Bit7 1
DeviceFamilyCode Bit6 Bit5 0 1
ChipAddressingInformation Bit3 Bit2 Bit1 B1 A1 A0
Bit4 0
8/16Bit Bit0 1
Reminiscentofthe24LC16B,the24LC515usesbit3ofthecontrolbytetoselectbetweenthetwo32Kbanks. OurProgram18-2Btoexercisethe24LC515willaccordinglyresembleProgram18-1’sbankselection. Program18-2A ;Program18-2toread/write ;selectivelyto512Kbit24FC515SerialEEPROM ;I2Ccommunications;Demonstraterandomread/write ;Constants ;--------Clk Dta RCtrl Display Adr0
Con A0 ;clockisonA0 Con A1 ;dataonA1 ;havetoaddthepageselecttoCtrl ;16-bitaddressword,soendsin1 Con %10100001 ;controlwordstartingpoint Con 0;setto0toblockwritingvaluestoserialport Con 0;Addressof24FC515A0=A1=0 ;IMPORTANT-Pin3MUST=+5V24FC515differsfrom ;24FC512inthisregard! ;Also24FC515hasabankselectionbit ;thatmustbesettojumpbetween32Kbanks
;Variables ;---------CtrlB i j ShouldBe
Var Var Var Var
Byte Word Byte Byte
;controlbyte ;index ;bytevalueto/from25FC512 ;calculatedreadvalue
;Initialization ;-------------;Communicatewithoutsideworldviaserial EnableHSerial SetHSerialH19200
;Demonstraterandomaccessbyteatatime
399
Chapter18 End
;24LC515isorganizedastwo32bytepages. ;Upto4chipsareaddressedinthecontrolbyte ;hangsupifuse$FFFF HSerOut[13,”IntoWrite”,13] Pause50 Fori=$0000to$FFFE ;BlockSelectaddressis:Bit3toselect32Kblocks CtrlB=RCtrl+Adr0 CtrlB.Bit3=i.Bit15 ;TowritesomethingdistinctivetoRAM ;wewritetheindexplustheoffset j=i.LowByte+i.HighByte ;Writetoaddressedmemory I2COutDta,Clk,ErrorMsg,CtrlB,i,[j] Pause5;neededforwritetime IfDisplay>0Then HSerOut[“Writei:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf If(i//256)=0Then HSerOut[“Writei:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf Next j=0 Pause50 HSerOut[“EndofWrite”,13] Pause50 ;Nowreaditback Fori=$0000to$FFFE ;Setupthecontrolbyteinthesameway ;ChipSelectaddressis:Bit2/Bit1 CtrlB=RCtrl+Adr0 ;Bit3isabankselectionswitch CtrlB.Bit3=i.Bit15 ShouldBe=i.LowByte+i.HighByte I2CInDta,Clk,ErrorMsg,CtrlB,i,[j] IfDisplay>0Then HSerOut[“Readi:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf If(i//256)=0Then HSerOut[“Readi:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf Ifj<>ShouldBeThen HSerOut[“Readi:“,Deci,”Data:“,Decj] HSerOut[“<--Error!”,13] Pause25 EndIf Next HSerOut[“EndofRead”,13] Pause50
ErrorMsg HSerOut[“Error!”] Pause50 End
400
ExternalMemory Let’slookatthewritecode,againstrippedofcommentsandserialoutputstatements.
Fori=$0000to$FFFF CtrlB=RCtrl+Adr0 CtrlB.Bit3=i.Bit15 j=i.LowByte+i.HighByte I2COutDta,Clk,ErrorMsg,CtrlB,i,[j] Pause5;neededforwritetime Next
Insteadofusingdecimalnotationfortheilooplimits,Program18-2Buseshexadecimal.Hexadecimal notationisclearer,onceyouarefamiliarwithit,asthe64Kaddressboundaryis$FFFF.
CtrlB=RCtrl+Adr0 CtrlB.Bit3=i.Bit15
WeconstructthecontrolbyteandaddressbankselectionjustaswedidinProgram18-1,exceptthatherewe needdealonlywithonebankselectionbit.Sincewehavehardwiredthechipselectaddressto%00,andwe haveonlyone24LC515device,thechipselectionbitsA0andA1aresetto0. j=i.LowByte+i.HighByte I2COutDta,Clk,ErrorMsg,CtrlB,i,[j] Pause5;neededforwritetime
Wecomputeabytetowrite,j,exactlyasbefore,andtheI2Coutstatementisidentical.Again,themost significantbitofiisignoredbythe24LC515andweneednotforceittozero. Thereadloopissimilar,exceptwepre-computethevalueweexpecttoreadfromthememoryandsendan errormessageovertheserialoutputshouldtheexpectedvaluenotmatchwhatisreadfromtheEEPROM.
AT24C512 Asweshouldalwaysdo,wefirstcheck Atmel’sdatasheetfortheAT24C512. Itisa64K×8-bitdevice,butunlikethe 24FC515,itisorganizedasonecontiguousaddressspace,withoutpages.(Don’t getconfusedwhenthedatasheetsays internallytheAT24C512isorganizedas 512pagesof128byteseach.Fromthe prospectiveofreadingandwritingtothe Figure18-4:ConnectinganAT24C512EEPROMDevice. devicefromMBasic,itappearstohavea linear64Kbyteaddressspaceandweneednotconcernourselveswiththespecificchipconstruction.)Chip addresspinsandbitsA0andA1areactive;whatisnormallychipaddresspinA2isunused.Hence,ifwe neededextramemory,wecouldparalleluptofourAT24C512devicesforatotalof256K×8-bitcapacity. AsreflectedinFigure18-4we’llstrapA0andA1toground,settingthechipaddressat%00.Ourcontrol byteisthus: Bit7 1
DeviceFamilyCode Bit6 Bit5 0 1
ChipAddressingInformation Bit3 Bit2 Bit1 X 0 0
Bit4 0
8/16Bit Bit0 1
Bit3is“don’tcare,”sowe’llsetitatzero. Program18-2Bperformsthesamesamplewrite,readandcheckforerrorfunctionsfortheAT24C512that Program18-2Adoesforthe24FC515chip.
401
Chapter18 Program18-2B ;Program18-2Btoread/write ;selectivelyto512KbitAT24C512SerialEEPROM ;I2Ccommunications;Demonstraterandomread/write ;Constants ;--------Clk Dta RCtrl Display Adr0
Con Con Con Con Con
A0 ;clockisonA0 A1 ;dataonA1 ;havetoaddthepageselecttoCtrl ;16-bitaddressword,soendsin1 %10100001 ;controlwordstartingpoint 0;setto0toblockwritingvaluestoserialport 0;AddressofAT24C512A0=A1=0 ;hasfull64Kwriteaddressspace
;Variables ;---------CtrlB i j ShouldBe
Var Var Var Var
Byte Word Byte Byte
;controlbyte ;index ;bytevalueto/fromAT24C512 ;calculatedreadvalue
;Initialization ;-------------;Communicatewithoutsideworldviaserial EnableHSerial SetHSerialH19200
;Demonstraterandomaccessbyteatatime ;AT24C512isorganizedasone64Kbytespace ;Upto4chipsareaddressedinthecontrolbyte ;hangsupifuse$FFFF HSerOut[13,”IntoWrite”,13] Pause50 Fori=$0000to$FFFE CtrlB=RCtrl+Adr0 ;TowritesomethingdistinctivetoRAM ;wewritetheindexplustheoffset j=i.LowByte+i.HighByte ;Writetoaddressedmemory I2COutDta,Clk,ErrorMsg,CtrlB,i,[j] Pause5;neededforwritetime IfDisplay>0Then HSerOut[“Writei:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf If(i//256)=0Then HSerOut[“Writei:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf Next j=0 Pause50 HSerOut[“EndofWrite”,13] Pause50 ;Nowreaditback Fori=$0000to$FFFE ;Setupthecontrolbyteinthesameway CtrlB=RCtrl+Adr0 ShouldBe=i.LowByte+i.HighByte I2CInDta,Clk,ErrorMsg,CtrlB,i,[j]
402
ExternalMemory End
IfDisplay>0Then HSerOut[“Readi:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf If(i//256)=0Then HSerOut[“Readi:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf Ifj<>ShouldBeThen HSerOut[“Readi:“,Deci,”Data:“,Decj] HSerOut[“<--Error!”,13] Pause25 EndIf Next HSerOut[“EndofRead”,13] Pause50
ErrorMsg HSerOut[“Error!”] Pause50 End
Again,let’slookatasimplifiedversionofthewriteloop.
Fori=$0000to$FFFE CtrlB=RCtrl+Adr0 j=i.LowByte+i.HighByte ;Writetoaddressedmemory I2COutDta,Clk,ErrorMsg,CtrlB,i,[j] Pause5;neededforwritetime Next
SincetheAT24C512issetupasaflat64Kmemory,wehavenopageorchipboundaryconcerns;wecan simplyreadandwritewithafull16-bitaddresswithoutworry.Ofcourse,wecouldexpandtoamaximum offourAT24C512chipsontheI2Cbus,inwhichcasewewouldmodifyourprogramalongthelinessuggestedinconnectionwithProgram18-2.
PracticalUseofExternalEEPROM OurdemonstrationprogramswritingandreadingarbitrarybytesinEEPROMareinteresting,sofarasthey go,butarenotallthatusefulbythemselves.WhywouldwewantabunchofextraEEPROMmemoryhangingonourPIC? Savingdataforlaterretrieval—We’llseethisindetailinChapter28,butperhapsthemostcommonuse ofexternalEEPROMistosavecaptureddataforlaterretrieval.Forexample,aroadsidetrafficcounter mightsavehourlylaneaxlecounttotals,alongwithclockdata.Aftercapturingdataforaweekortwo, thecounteriscollectedandthestoreddataistransferredtoaPCforanalysis. Stringdata—It’spossibletoprogramtheexternalEEPROMwithaseriesofstringmessagesandaddthe pre-programmedEEPROMtoyourcircuit.(Ifyouhavethecorrectadapter,BasicMicro’sPICprogrammeralsowillprogrammanyI2CEEPROMdevices.Otherwise,youcouldwriteasimpleprogramusing aPICtodonothingbutloadyourstringdataintoanEEPROM.) Memoryswap—It’spossibletoindirectlyextendPIC’sinternalRAMbyswappingdatabetweenRAMand EEPROM.Suppose,forexample,youprogrammustgeneratevaluesfortwo100-elementbytearraysA andB,andstoretheword-lengthproductsofthetwoarraysina10,000elementarrayX.Leavingaside thequestionofwhetheraPICisthebestvehicleforsuchmathematicallyintensivecomputations,we canuseanexternalAT24C512EEPROMtoholdboththeindividualarrays,andtheirproduct.
403
Chapter18 Let’stakealookathowwemightaccomplishthis.Inpseudo-code,ouralgorithmis: CreatearrayA(i)fori=0…99 SavearrayAinEEPROM CreatearrayB(j)forj=0…99 SavearrayBinEEPROM Fori=0to99 RetreiveA(i)fromEEPROM Forj=0to99 RetreiveB(j)fromEEPROM X=A(i)*B(j) StoreXinEEPROM Nextj Nexti
Program18-3containsfunctioningcode. Program18-3 ;Program18-3 ;ShowshowtouseexternalEEPROM ;fora100x100elementarrayproduct ;UseasingleAT24C51264KEEPROM ;Addresshardwiredto%00 ; ;Constants ;---------RCtrl Con %10100001 iStart Con 0 jStart Con 100 xStart Con 200 Clk Con A0 Dta Con A1
;controlwordstartingpoint ;inthiscasecanusedirectly ;memorystartingpointforiArray ;memorystartingpointforjarray ;memorystartingpointforXarray ;clockisonA0 ;dataonA1
;Variables ;----------i j k Prod RTemp Ti Tj ShouldBe
;ArrayAindex ;ArrayBindex ;ArrayXindex ;ProductA(i)*B(j) ;Randomvariable ;temporaryiarray ;temporaryjarray ;A*Bcalculated
Var Var Var Var Var Var Var Var
Byte Byte Word Word Word Byte Byte Word
;Initialization ;--------------EnableHSerial SetHSerialH19200 ;Main ;------RTemp=77 ;CreatearrayAandwritetoEEPROM ;---------------------------------HSerOut[13,13,”***Write***”,13] Fori=0to99 ;fillarrayAwithrandomnumbers RTemp=RandomRTemp Ti=RTemp.LowByte ;writeAarraytoEEPROM I2COutDta,Clk,ErrorMsg,RCtrl,i+iStart,[Ti] Pause5 Next;i
404
ExternalMemory ;NowcreatearrayBandfillwithrandoms ;---------------------------------------Forj=0to99 RTemp=RandomRTemp Tj=RTemp.LowByte ;writeBarraytoEEPROM I2COutDta,Clk,ErrorMsg,RCtrl,j+jStart,[Tj] Pause5 Next;j ;NowmultiplyX=A*B ;-----------------Fori=0to99 I2CInDta,Clk,ErrorMsg,RCtrl,i+iStart,[Ti] Forj=0to99 I2CInDta,Clk,ErrorMsg,RCtrl,j+jStart,[Tj] Prod=Ti*Tj ;calculatestorageindexforproduct k=i*200+(j*2)+XStart ‘writetheproducttoEEPROM I2COutDta,Clk,ErrorMsg,RCtrl,k,| [Prod.HighByte,Prod.LowByte] Pause5 GoSubWriteInfo Next;j Next;i ;ReadEEPROM ;--------------HSerOut[“***Read***”,13] Fori=0to99 ;ReadtheA(i)values I2CInDta,Clk,ErrorMsg,RCtrl,i+iStart,[Ti] Forj=0to99 ;ReadtheB(j)values I2CInDta,Clk,ErrorMsg,RCtrl,j+jStart,[Tj] ShouldBe=Ti*Tj ;calculatestorageindexforproduct k=i*200+(j*2)+XStart ‘writetheproducttoEEPROM I2CinDta,Clk,ErrorMsg,RCtrl,k,| [Prod.HighByte,Prod.LowByte] IfShouldBe<>ProdThen HSerOut[“***ERROR!***”,9] EndIf GoSubWriteInfo Next;j Next;i End WriteInfo ;------- HSerOut[“A(“,Deci,”):“,DecTi,”*B(“,Decj,”):“,DecTj,9,”A*B=“,Dec Prod,13] Pause25 Return ErrorMsg ;-------- HserOut[“Error!”] End
405
Chapter18 Beforewewritethefirstlineofcode,wemustdeviseamemoryallocationplan.Wehavethreearraysto save,A(0…99)andB(0…99),bothbytelength,andX(0…99,0…99),wordlength. We’lluseasimpleallocationplanforarraysAandB: 0 A(0) 100 B(0)
AT24C512MemoryAddress ArrayAvalue AT24C512MemoryAddress ArrayBvalue
1 A(1) 101 B(1)
2 A(2) 102 B(2)
3 A(3) 103 B(3)
… A(…) … B(…)
98 A(98) 198 B(98)
99 A(99) 199 B(99)
Hence,we’llreservethefirst200bytesofspaceintheAT24C512forAandB. We’llstarttheproductarrayXataddress200.SinceX(i,j)isaword-lengthvariable,wemustreservetwo bytesforeachelement. AT24C512Memory Address ArrayXvalue
200 X(0).Byte1
201 X(0).Byte0
202 X(1).Byte1
203 X(1).Byte0
… X(…)
20198 X(9999).Byte1
20199 X(9999). Byte0
Theresultingmemorymapis: 65535 Free 20200 20199 X(0…99,0…99) 00200 00199 B(0…99) 00100 00099 A(0…99) 00000
Let’sseehowwegoaboutcalculatingthememoryindexestoreadandwritethesememorylocations. • MemoryAddressforA()issimpleenough;weindexintomemorywithi. • MemoryAddressforB()isj+100. • MemoryAddressforX()startsat200,butjumpsintwobytesteps,toaccommodatethewordlength variable.We’lldefinethestartingpointasaconstant,XStart.ArrayX(0…9999)canbemoreconvenientlythoughtofasatwo-dimensionalarrayX(0…99,0…99),orX(i,j).Foreachi,therefore, wereserve200bytesandstepwithj,butinintervalsoftwobytes.Thus,k=i*200+(j*2)+ Xstart,wherekisthememoryaddressforX(i,j).Byte1. Aftermappingmemoryusage,thecodeisstraightforward. ;CreatearrayAandwritetoEEPROM ;---------------------------------HSerOut[13,13,”***Write***”,13] Fori=0to99 ;fillarrayAwithrandomnumbers RTemp=RandomRTemp Ti=RTemp.LowByte ;writeAarraytoEEPROM I2COutDta,Clk,ErrorMsg,RCtrl,i+iStart,[Ti] Pause5 Next;i
406
ExternalMemory ;NowcreatearrayBandfillwithrandoms ;---------------------------------------Forj=0to99 RTemp=RandomRTemp Tj=RTemp.LowByte ;writeBarraytoEEPROM I2COutDta,Clk,ErrorMsg,RCtrl,j+jStart,[Tj] Pause5 Next;j
TheabovecodefragmentconstructsthearraysA()andB(),fillsthemwithrandomvalues,usingMBasic’s Randomfunction,andwritesthearraystoEEPROMatthememoryaddresseswedeveloped.Ofcourse,ina realprogramthesearrayswouldbefilledwithmeasuredorcalculateddataofmoreutilitythanourrandom numberassignments. Forincreasedgenerality,wepreviouslydefinedthestartingpointsfori(iStart)andj(jStart)memory segments.Inaccordancewithourmemoryplan,iStartisdefinedas0,andjStartisdefinedas100 ;NowmultiplyX=A*B ;-----------------Fori=0to99 I2CInDta,Clk,ErrorMsg,RCtrl,i+iStart,[Ti] Forj=0to99 I2CInDta,Clk,ErrorMsg,RCtrl,j+jStart,[Tj] Prod=Ti*Tj ;calculatestorageindexforproduct k=i*200+(j*2)+XStart ‘writetheproducttoEEPROM I2COutDta,Clk,ErrorMsg,RCtrl,k,| [Prod.HighByte,Prod.LowByte] Pause5 GoSubWriteInfo Next;j Next;i
NowthatwehavethearraysAandBdefined,weareinapositiontocalculatetheproductofeachelement ofAandB.WedothisbyreadingtheAT24C512fortheelements.TiisA(i)andTjisB(j)vianested Forloops.TheproductA(i)*B(j)issimplyTi*Tj.Westorethisproduct,whichweassigntotheword variableProd,intheAT24C512atlocationk.WestoreProd.HighByteandProd.LowBytesequentially inoneI2Coutprocedurecall. ThesubroutineWriteInfooutputsi,jTi,TjandProdtotheserialdataport. ;ReadEEPROM ;--------------HSerOut[“***Read***”,13] Fori=0to99 ;ReadtheA(i)values I2CInDta,Clk,ErrorMsg,RCtrl,i+iStart,[Ti] Forj=0to99 ;ReadtheB(j)values I2CInDta,Clk,ErrorMsg,RCtrl,j+jStart,[Tj] ShouldBe=Ti*Tj ;calculatestorageindexforproduct k=i*200+(j*2)+XStart ‘writetheproducttoEEPROM I2CinDta,Clk,ErrorMsg,RCtrl,k,| [Prod.HighByte,Prod.LowByte] IfShouldBe<>ProdThen HSerOut[“***ERROR!***”,9] EndIf GoSubWriteInfo
407
Chapter18 Next;j Next;i
Finally,weverifythatthedatahasbeencorrectlycomputedandsaved,byrepeatingtheproductcalculation, savingitasthewordvariableShouldBe,andcomparingthatwiththevalueretrievedfromtheAT24C512. Shouldtheretrievedvaluedifferfromthenewlycomputedvalue,anerrorflagiswrittenfromtheserialport. Here’sasampleoftheserialportoutput: ***Write*** A(0):155*B(0):150 A(0):155*B(1):44 A(0):155*B(2):89 A(0):155*B(3):178 A(0):155*B(4):101 A(0):155*B(5):203 A(0):155*B(6):150
A*B=23250 A*B=6820 A*B=13795 A*B=27590 A*B=15655 A*B=31465 A*B=23250
***Read*** A(0):155*B(0):150 A(0):155*B(1):44 A(0):155*B(2):89 A(0):155*B(3):178 A(0):155*B(4):101 A(0):155*B(5):203 A(0):155*B(6):150
A*B=23250 A*B=6820 A*B=13795 A*B=27590 A*B=15655 A*B=31465 A*B=23250
Afinalreminder;ifwetrywritingandreadingawordvariable,suchas: I2COutDta,Clk,ErrorMsg,RCtrl,k,[Prod] I2CinDta,Clk,ErrorMsg,RCtrl,k,[Prod]
onlytheProd.LowByteisactuallystoredandread.I2CoutandI2Cinfunctioncorrectlywithindividual byteorbyte-arrayarguments,notmultibytetypes,suchasWord,LongorReal.
ParallelAccessMemory SerialEEPROMmemoryiscompact,inexpensiveandconsumesonlytwoPICpins,oftenascarceresource. But,it’sslow—writingtoEEPROMrequires5msforthedeviceswe’veexaminedinthischapter.Even thoughnopauseisrequired,readingabytefromEEPROMatstandardspeedrequiresseveralhundredmicroseconds. Whywouldwewantfasteraccess?Supposewewishtocaptureafastchanginganaloginputsignalwiththe A/Dconverter,storeseveralkilobytesofconsecutiveA/Dvaluesandthenanalyzetheresultspost-capture. PerhapswewishtodoafastFouriertransform(FFT)onthedata,orhavethePICtakeactionbasedon someothermathematicalanalysisofthedata.IfwemustcapturemorethanacouplehundredbytesofA/D readings,thePIC’sonboardRAMisinadequate,sowemustlooktoexternalmemory.FromChapter11,we knowthatanA/DreadinMBasicconsumeslessthan300µs,butifittakes5mstosaveeachresulttoserial EEPROMmemory,ourA/Dcapture-saveratedropsmarkedly.We’llseethatevenifwekeepourprogrammingtoonlyMBasic,wecansaveabytevalueinSRAMinabout300µs,ahugeimprovementoverwriting toserialEEPROM.And,ifwearen’tafraidtomixabitofassemblerintoourMBasicprogramming,wecan shavetheSRAM-savetimetounder10µs,thusmakingtheA/Dconversionroutinethelimitingfactorinthe A/Dcapture-savecycle.
408
ExternalMemory Forfasteraccess,wemightlook atserialmemorythatusesstatic RAM,notEEPROM,technology. SRAMcanbewrittentoinnanoseconds,withoutthelongwaitfor EEPROMwriting.SRAMmemory retainsinformationwithoutperiodicrefreshingsolongaspower ismaintained.UnlikeEEPROM, however,SRAMwillnotretaininformationoncepowerisremoved. And,unfortunatelytherearenot manyserialSRAMdevicesavailable,andthosethatareavailable carrypricetagssignificantlyabove thoseofserialEEPROM. Ifwerequireinexpensivefast SRAMaccess,unfortunately,we areoftenleftwithonlyparallelac- Figure18-5:ParallelaccessDRAM. cessdevices.And,paralleldevices consumePICpinslikethereisnotomorrow.Let’slookatasimpleapplicationofparallelSRAMwithCypressSemiconductor’sCY7C128A2K×8-bitSRAMdevice.Figure18-5showsthestrategyforconnecting aparallelSRAMmemorychiptoaPIC.EvenwithalatchtoshareaddressanddatapinsonPortB,thePIC stillmustdedicate14pinstocommunicationswiththeCY7C128A. BeforewelookatthecodeassociatedwiththeCY7C128A,let’slookatthetwoactivedeviceswe’lluse. (Thisoverviewisnosubstituteforathoroughreviewofthedatasheet.) TheCY7C128Amemoryisa2K×8-bitSRAMwith11addressinputs,A0…A10andeightbidirectional outputpins,I/O0…I/O7,andthreecontrolpins:chipenable(CE),outputenable(OE)andwriteenable (WE).(Thesethreepinsareactivelow,normallyshownbyahorizontalbarovertheacronym.) TheI/Opinsarebidirectional;muchlikeaPICtheymaybeswitchedbetweeninputandoutputfunctions. Inaddition,theI/Opinsmaybeplacedinathird,highimpedance,statewheretheyareeffectivelydisconnectedfromtheoutsideworld. Function
CE
WriteDatato SRAM
Low
ReadDatafrom SRAM
Low
WE SetupAddressandDatatobeWritten withWEHigh.TakeWELowtoWrite DatatoSRAM Highduringrelevanttime
OE Highduringrelevanttime SetupAddressandgointoReadWith OEHighandTakeLowtoOutputValid Data
The74ACT843isa9-bitlatch.(Weonlyuse8-bits,butIhada74ACT843onhandandusedit.Youmay substitutean8-bitlatch,suchas74ACT574,ifyouwish.)Alatchperformsthefunctionthatitsnamesuggests;ifthelatchenable(LE)pinishigh,theeachoutputfollowsitsassociatedinput,butwhentheLEis pulledlow,theoutputsare“latched”intothestatetheywereinonthefallingedgeoftheLEwaveform.The
409
Chapter18 outputsstayinthatstateuntiltheLEpinishigh,atwhichtimetheoutputsgobacktotrackingtheirassociatedinputs. The‘843latchallowsustousePortBforbothaddressing(A0…A7)theSRAMandfordatatransfertoand fromtheSRAM,thussavingeightpins.Thismeans,however,thatourcodemustensurethatthePortBand theSRAMI/Opinsareneversimultaneouslyinoutputmode,orelseweriskdamagetothedevices. Basedonthisinformation,wecanpreparepseudo-codeforSRAMaccess: WritetoSRAM ;------------HighOE-tristateoutputsofSRAM HighWE–readyforactivity HighLE–latchistransparent SetupAddressesA8…A10 MakePortBOutput OutputAddressA0…A7fromPortB LowLEtolockaddressintoplace OutputDataonPortBtoI/OlinesIO0…IO7 TakeWELowBrieflyforSRAMtoinputthedata HighWE–readyfornextactivity HighLE–latchistransparent ReadfromSRAM ;------------HighWE–readyforactivity HighOE–tristateoutputsofSRAM SetupAddressesA8…A10 MakePortBOutput OutputAddressA0…A7fromPortB LowLEtolockaddressintoplace MakePortBInput LowOE–putI/Oonlinenowavoidingclash ReadPortB,therebyReadingDataonI/OlinesIO0…IO7 HighOE–backtotristateforSRAMoutputs HighLE–latchistransparent
Thiscircuitpressesthelimitsofwhatisfeasibletosimulateonaplug-boardstylebreadboard.The CY7C128Aisahigh-speedchip,withtheoneIusedhavinganaccesstimeof25nsandisaccordinglysensitivetogroundbounceandotherartifactsthatmightbeignoredbyslowerspeedlogic.(Youcanpurchase CY7C128Aversionswithaslittleas15nsaccesstime.)Thespaceona2840developmentboardismarginal atbestsoIbuiltthelatchandSRAMelementsonalarger,separately-poweredplug-board,anduseda6” 14-pinDIP-to-DIPjumpercabletoconnectittothe2840board.Ifoundleaddressandjumperwirerouting wascriticalandthatIcouldcauserandomreadorwriteerrorsbychangingcertainjumperwires’physical positionorrouting. Onefinalpoint;Iuseda16F877Aforthisproject,butyoucouldsubstitutea16F876ifdesired.Ifso,substituteC0…C2fortheE0…E2connections. Program18-4writesdatatotheSRAMandreadsitback.Anydiscrepancybetweenthevaluethatshould havebeenwrittenandtheas-readvaluesendsanerrormessageovertheserialport. Program18-4 ;Program18-4.Minimalist ;R/WtoCY7C128A2Kx8SRAM ;UsesSN74ABT843Latch ;SeeMicrochipTB011 ;Constants ;--------------RAM_ALECon E2 RAM_WRCon E1
;addresslatchenableonSN74ABT843latch ;WriteEnable
410
ExternalMemory RAM_RD Display
Con Con
;Variables ;--------------RamAdr Var RamData Var i Var ShouldBe Var
E0 0
;OutputEnable ;0blockswritingtoserialport
Word Byte Word Byte
;RAMread/writeaddress ;datatobereadorwritten ;Loopvariable ;Readbackvalueshouldbe
;Initialization ;-------------TRISB=%00000000 ;DualPurposeIn/Out TRISA=%00000000 ;UseA0..A3asoutputs TRISE=%00000000 ; ;Communicatewithoutsideworldviaserial EnableHSerial SetHSerialH19200 HighRAM_RD HighRAM_WR HighRAM_ALE Main End
Fori=0to2047 RamAdr=i RamData=i.LowByte+i.HighByte GoSubWriteRam IfDisplay>0Then HSerOut[“i:“,Deci,”Write:“,DecRamData,13] pause25 EndIf Next HSerOut[13,13] Fori=0to2047 RamAdr=i GoSubReadRam IfDisplay>0Then HSerOut[“i:“,Deci,”Read:“,DecRamData,13] Pause25 EndIf ShouldBe=i.LowByte+i.HighByte If(RamData<>ShouldBe)Then HSerOut[“i:“,Deci,”Read:“,iHexRamData,| “ShouldBe:“,iHexShouldBe,”<--Error!”,13] Pause500 EndIf Next HSerOut[“Endit”,13] Pause30
WriteRAM ;------- ;Subroutineexecutesin320uSec,notcountingcall/return PortA.LowNib=RamAdr.Nib2 ;gethigh3bitsofaddress TRISB=$00 backtooutput PortB=RamAdr.LowByte LowRAM_ALE PortB=RamData ;writethedata PulsOutRAM_WR,5 ;accomplishthewritetoRAM HighRAM_ALE
411
Chapter18 Return ReadRAM ;------- ;Subroutineexecutesin350uSec,notcountingcall/return ;PortBandPortAareinoutputmode PortA.LowNib=RamAdr.Nib2;gethigh3bitsofaddress TRISB=$00 PortB=RAMAdr.LowByte LowRAM_ALE TRISB=$FF ;PICpinsnowinputsinput LowRAM_RD ;enableoutputdriversinRAM RamData=PortB ;readthedata HighRAM_RD ;tristatetodisableoutputdrivers HighRAM_ALE Return End
FollowingMicrochip’sApplicationNoteTB11,westartbygivingthethreecontrolpinsaliasesthatare moreunderstandable: RAM_ALECon RAM_WRCon RAM_RD Con
E2 E1 E0
;addresslatchenableonSN74ABT843latch ;WriteEnable ;OutputEnableusedforReadRAM
ThemainForiloopsshouldbefamiliar,astheylargelyreproducetheconceptwedevelopedforserial EEPROMtesting;fillthememorywithtestbytesgeneratedbysummingthetwoaddressbytes,readthe memoryandcomparethereadvaluewiththecalculatedvalueandwriteanerrormessageifthetwovalues differ.Hence,ouranalysiswilljumptothetwosubroutinesthatperformtheheavyliftinginProgram18-4, WriteRAMandReadRAM. BothWriteRamandReadRamtrackthepseudo-codequiteclosely. Pseudo-Code WritetoSRAM ;------------HighOE-tristateoutputsofSRAM HighWE–readyforactivity HighLE–latchistransparent SetupAddressesA8…A10 MakePortBOutput OutputAddressA0…A7fromPortB LowLEtolockaddressintoplace OutputDataonPortBtoI/OlinesIO0…IO7 TakeWELowBrieflyforSRAMtoinputthe data HighWE–readyfornextactivity HighLE–latchistransparent
WriteRamSubroutine WriteRAM ;--------
PortA.LowNib=RamAdr.Nib2 TRISB=$00 PortB=RamAdr.LowByte LowRAM_ALE PortB=RamData PulsOutRAM_WR,5 HighRAM_ALE Return
Wecanomitseveralofthecontrollinesettingsthatwereshowninthepseudo-codeforclaritybecausethey areimplicitlydealtwith.Forexample,RAM_ALEisalwayshighgoingintoWriteRam,soitisn’tnecessary toexplicitlysetithighagain.Similarly,MBasic’scommandPulsOutleavesRAM_WRinthestate(high)it wasinbeforebeingcalled,andinsertsabrieflowpulse,soresettingRAM_WRhighisunnecessary.
412
ExternalMemory WeseethesameparallelisminReadRam: Pseudo-Code ReadfromSRAM ;------------HighWE–readyforactivity HighOE–tristateoutputsofSRAM SetupAddressesA8…A10 MakePortBOutput OutputAddressA0…A7fromPortB LowLEtolockaddressintoplace MakePortBInput LowOE–putI/Oonlinenowavoidingclash ReadPortB,therebyReadingDataonI/O linesIO0…IO7 HighOE–backtotristateforSRAMoutputs HighLE–latchistransparent
ReadRamSubroutine ReadRAM ;-------PortA.LowNib=RamAdr.Nib2 TRISB=$00 PortB=RAMAdr.LowByte LowRAM_ALE TRISB=$FF LowRAM_RD RamData=PortB HighRAM_RD HighRAM_ALE Return
Again,we’vebeenabletoomitthetwoentranceset-upcommandsinthepseudo-codebecausethestatusis knownwhenthesubroutineiscalled. AfterallthisworkinmakingnanosecondSRAMworkwithaPIC,youmaywonderwhyexpendsomuch effortifitstilltakes300µsorsotoreadorwriteabyte.Well,wecanknock290µsoffthattimebyrecoding WriteRAMandReadRAMinassembler,resultinginexecutiontimesof10–11µs. OurapproachtoassemblerprogramminginChapters13and14emphasizedaprocessof“stepwisesubstitution,”wherebywedevelopanddebugaprograminpureMBasicandthen,fortime-criticalprogram elements,writeanin-lineassemblerreplacement,onestatementatatime.(Weleavecomplicatedthings, suchasserialoutput,floatingpointroutinesandthelikeinMBasic.)AfterreplacingoneMBasicstatement, wedebugandtestthenewchunkofassemblercodeandwhenfunctioning,movetothenextMBasicstatement.Whencompleted,wemaymergethevariousindividualin-lineassemblercodechunksintoasingle longerin-linesegment,orleavetheminplace. Program18-5showshowwemightreplacetheMBasiccodeinbothWriteRAMandReadRAMwithassemblerchunks.I’veintentionallynotmergedthecodeintoasinglelongin-lineassemblersegmentsothat youmightseehoweachMBasicstatementissimplyrenderedintoafewlinesofassembler.However,I’ve removedtheintermediateBankSelcommands,necessarywhenexitingassemblerandreturningtoMBasic. (GPASMwillreporterrormessageswhenassemblingtheinstructionbanksel0.So,wesubstituteaknown bank0register,suchasPortA—thatis,bankselPortA.) Program18-5 ThelistingforProgram18-5isavailableintheassociatedCD-ROMandasaspacesavingmeasurewillnot beshown.
;PortA.LowNib=RamAdr.Nib2 ;gethighthreeaddressbits ASM { BankSelRamAdr1 movf (RamAdr+1)&0x7F,w BankSelPortA movwf PortA }
413
Chapter18 Wecheatabitinwritingthethreehigh-bitaddressesA8…A10toPortA.TheMBasiccodewritesonlyto PortA.LowNib,butsinceweusePortAfornootherpurpose,theassemblercodesimplywritesRamAdr. HighBytetoPortA.InaccessingawordvariabledeclaredinMBasic,itshighbyteisthebaseaddress plus1;henceinassemblerweuse(RamAdr+1)astheequivalentofMBasic’sRamAdr.HighByte.Inorder toavoidoperatorprecedenceissues,weforceRamAdr+1tobeexecutedfirstbyenclosingitinparentheses.TheassemblercodecopiesRamAdr+1tothePIC’sWregisterandthencopiestheWregistercontents toPortA,yieldingtheequivalentofPortA=RamAdr.HighByte.GPASMdoesnotpermitustoperform (RamAdr+1)asanargumentforBankSel,sowehavecreatedRamAdr1asanaliasforRamAdr.HighByte intheMBasicvariabledefinitions.
;TRISB=$00 ASM { BankSelTRISB Clrf TRISB }
;backtooutput
Settingafiletozeroisaccomplishedquicklyandefficientlyinassemblerbyclearingit.
;PortB=RamAdr.LowByte ASM { BankSelRamAdr movfRamAdr&0x7F,w BankSelPortB movwfPortB }
WewriteRamAdr.LowBytetoPortBinthesamefashionwedidwiththeRamAdr.HighByteandPortA; copyRamAdrtotheWregisterandthencopytheWregistertoPortB.SinceRamAdr’saddressisthelow byte,weneednotdoanythingspecialtoloadRamAdr.LowByteintoW.
;LowRAM_ALE ASM { BankSelPortE bcf }
PortE,2
WedropRAM_ALEtolowbyclearingitsdefinedPortEbit,therebylatchingtheloworderaddressvalues A0…A7.
;PortB=RamData ;writethedata ASM { BankSelRamData movf RamData&0x7F,w BankSelPortB movwf PortB }
Copyingthedatabyte,RamDatatoPortBisidenticalwithhowwemovedthelowbyteoftheaddressto PortB.
;PulsOutRAM_WR,5 ;accomplishthewritetoRAM ASM { BankSelPortE bcf PortE,1 NOP NOP NOP NOP bsf PortE,1 }
414
ExternalMemory Togenerateabriefzero-levelpulseonRAM_WR,weclearitsassociatedbitinPortEwithabcfoperation. WefollowwithfourNOPsforabriefdelay(0.8µs)andthenrestoreRAM_WRtohighbysettingtheassociatedbitwithabsfoperation.ThedelayweusedinMBasicwas5µs,farlongerthanrequiredbythe CY7C128A.(MBasic’sPulsOutfunctionhasaminimumperiodof4µs.) Return
;HighRAM_ALE ASM { BankSelPortE bsf }
PortE,2
Finally,wereturnRAM_ALEtohighbysettingtheassociatedbitinPortE,therebyenablingthe‘843latch’s outputpinstoagainfollowinputvalues. Forcompleteness,we’llstepthroughReadRam. ReadRAM ;------- ;PortA.LowNib=RamAdr.Nib2;gethigh3bitsofaddress ASM { BankSelRamAdr1 movf (RamAdr+1)&0x7F,w BankSelPortA movwf PortA }
SamecodeasinWriteRam.
;TRISB=$00 ASM { BankSelTRISB Clrf TRISB }
SamecodeasinWriteRam.
;PortB=RAMAdr.LowByte ASM { BankSelRamAdr movfRamAdr&0x7F,w BankSelPortB movwfPortB }
SamecodeasinWriteRam.
;LowRAM_ALE ASM { BankSelPortE bcf }
PortE,2
SamecodeasinWriteRam.
;TRISB=$FF ;PICpinsnowinputs ASM { BankSelTRISB movlw 0xFF movwf TRISB }
InWriteRam,PortBwasoutputtingdatatotheSRAMsoTRISBwaskeptat$00;however,herewemust readdatafromtheSRAM.Hence,wesetPortBtoinputbysettingTRISBto$FF.Weaccomplishthisby loadingregisterWwith$FFandcopyingregisterWtoTRISB. 415
Chapter18
;LowRAM_RD ASM { BankSelPortE bcf }
;enableoutputdriversinRAM
PortE,0
WedropRam_RDlowbyclearingitsassociatedbitonPortE.
;RamData=PortB;readthedata ASM { BankSelPortB movf PortB,w BankSelRamData movwf RamData&0x7F }
Atthistime,theSRAMI/OpinshaveshiftedtooutputandcontainthebytevaluetobereadbyPortBand thentransferredtoRamData.WefirstcopyPortB’svaluetotheWregisterandthencopytheWregister’s valuetoRamData.
;HighRAM_RD ASM { BankSelPortE bsf }
;tristatetodisableoutputdrivers
PortE,0
Totri-statetheSRAM’soutputdrivers,wesimplybringtheRAM_RDpinhighbysettingitsassociated PortEpinthroughabsfoperation. Return
;HighRAM_ALE ASM { BankSelPortE bsf PortE,2 BankSelPortB ;switchestoBank0forMBasic }
WefinishwiththesamecodeasinWriteRamtore-enablethe‘843latch. Perhapssomeofthesestepscouldbeaccomplishedmoreelegantlyinassembler,butwe’veoptedforclarity overelegance.
References [18-1]
PhilipsSemiconductors,TheI2C-BusSpecificationVersion2.1,January2000,DocumentNo.9398393 40011(2000). [18-2] MicrochipTechnology,Inc.,24AA16/24LC16B16KI2CSerialEEPROM,DocumentNo.DS21703C (2003). [18-3] MicrochipTechnology,Inc.,24AA256/24LC256/24FC256256KI2CCMOSSerialEEPROM,DocumentNo.DS21203K(2003). [18-4] MicrochipTechnology,Inc.,24AA515/24LC515/24FC515512KI2CCMOSSerialEEPROM,DocumentNo.DS21673C(2003). [18-5] AtmelCorp.,2-wireSerialEEPROM512K(65536x8)AT24C512,Rev.1116J-SEEPR-7/03(2003) [18-6] TexasInstrumentsInc.,SN54ABT843,SN74ABT8439-BitBus-InterfaceD-TypeLatchesWith3-State Outputs,(1997). [18-7] CypressSemiconductorCorp.,CY7C128A2Kx8StaticRAM,DocumentNo.38-05028(Aug.24, 2001). [18-8] Evans,Rick,UsingSRAMwithaPIC16CXXX,TB011,MicrochipTechnology,Inc.,DocumentNo. DS91011A(1997). 416
ExternalMemory [18-9]
AtmelCorp.,InterfacingAT24CXXSerialEEPROMswithAT89CX051Microcontrollers,Rev.0507D05/01(2001) [18-10] PhilipsSemiconductors,I2C-busallocationtableGeneral,(Mar.3,1997)..
417
CHAPTER
19
Advanced StepperMotors Chapter8introducesthesteppermotor,andshowshowtodrivebothunipolarandbipolarsteppersinfullstep, halfstepandwavemodes.ItalsocoversthefundamentalsofmotorspeedupthroughL/Rdrivemethods. Thischaptercoverstwomoreadvancedtopics;microsteppingandageneral-purposeserial-controlledstepperdriverprogram.BothtopicsareillustratedwithprogramsthatblendMBasicwithassemblerlanguagefor time-criticalroutines.Ifyouhaven’treadChapters8,10,13,14and15yet,nowisagoodtimetodoso. Onefinalnote;thischapterfocusesonbipolarsteppermotors,butasyouknowfromChapter8,unipolar motorsworkwithsameprogrambysimplychangingthedrivinghardwarefromabipolarH-bridgetoone aimedatunipolarmotors.And,youmayevenusethesamebipolarH-bridgedrivertodriveaunipolarmotor,operatinginbipolarmode.
Microstepping Introduction Let’sgobacktotheconceptualbipolarsteppermotorintroducedinChapter8.AsillustratedinFigure19-1ifthecurrents throughwindingsA-CandB-Dareequal,therotororients itselfatananglehalfwaybetweenthetwostatorpoles,inour simplefourstepsperrevolutionmotor,at45degrees.We’ll sayourimaginarymotorhas1ampereflowingthroughboth windingsA-CandB-D.SupposewemaintainwindingsB-Dat 1ampere,butreduceA-C’scurrentto0.5ampere.Intuitively, youshouldseethattherotorwillshifttobeingmoreclosely alignedwithwindingB-D.IfwemaintainwindingsB-Dat1 ampereandreducethecurrentthroughwindingA-Cfurther,to say0.25ampere,therotorwillmoveevenmoretowardsalignmentwithwindingB-D’spoles. Thus,byholdingthecurrentconstantinonewindingpairand reducingitintheotherpair,wecanpositiontherotor,atleastin theory,atanyarbitraryangle.Thethingthatmakesasteppermotor whatitis—theabilitytomoveinpreciseincrementsorsteps—can Figure19-1:Microstepping. benegated,turningthestepperintoacontinuouslypositionalvariablemotor.Inpractice,thereareadvantagesinvaryingthecurrenttoprovideabinarypowerofintermediatesteps, forexample,8,16or32.Programs19-1and19-2use16intermediatesteps.Ifappliedtoa48-stepmotor,suchasthe PF35-48weuseinChapter8,themotorhas48×16,or768microstepsperrevolution.Appliedtoa200-step/revolutionmotor,theresultis3,200microstepsperrevolution,correspondingto0.112°permicrostep.
418
AdvancedStepperMotors Winding 1
Winding 2
Winding Current
Isthistoogoodtobetrue—thatwecantakeastepper motorandpositiontheshaftwithin6.75arc-minutes? Thedevil,asusual,isinthedetails,andinthecaseof microstepping,thedetailsaregettingthecurrentratios correct.But,evenifthecurrentratioisn’tquiteaccurate, microsteppingprovidesanothermajoradvantagebyreplacingtheabrupton/offcurrentwaveformweobserved inChapter8withasmooth,continuouslyvaryingone. Thisimprovesmotorefficiencyandsmoothesthestep transitions.Thecurrenterror,moreover,appliesonlyto intermediatemicrosteps—fullsteppositionsareidenticaltothoseofaconventionalfullstepcontroller.
+
Normal StepIncrements 0
1
2
3
4
–
Figure19-2:CurrentDistributionforMicrostepping.
Figure19-2illustratesthetheoreticallydesiredcurrent distribution.Thetargetcurrentwaveformholdsthecurrentinonewindingpairconstantwhilethecurrentinthe secondwindingpairisvariedfollowingacosinewaveshape,repeatingtheprocesswiththesecondwinding pairheldconstantwhilethefirstvariesinacosinepattern.Figure19-2simulatesthecosinedistribution.
DriveCircuit Howdoweefficientlygeneratethesecurrentwaveforms?Oneapproachwouldbeavariableconstantcurrent supplyunderPICcontrolthroughaD/Aconverter.However,anactiveconstantcurrentsourceisbeyondthe complexityappropriateforanintroductorybooksuchasthisone.Hence,we’llusesomethingabitsimpler, butnotasgood.AswelearnedinChapter8,whenvoltageisappliedtoastepperwinding,theresultingcurrentisafunctionbothoftime(theL/Rtimeconstant),theappliedvoltageandseriesresistanceofthemotor windingplusanyexternalrisetimeimprovementresistors.Iftheincrementalmotorstepsoccurrelatively slowlysothatwemaydisregardtheL/Rcomponentofthecurrentresponse,thewindingcurrentisproportionaltotheappliedvoltage.So,we’llrampthemotorsupplyvoltageupanddown,andtrustthatthemotor currentwillfollowthesupplyvoltage.Aswe’llseewhenweexaminetheperformanceofoursimplecircuit, thistrustisnotmisplaced;althoughthecurrentwaveformisn’talwayswhatwedesire,it’sadequateto demonstratetheprinciples behindmicrostepping. Let’stakeanotherlook atourSN754410bipolar drivercircuitfromChapter 8,reproducedasFigure19-3. Whatweneedisaway ofeasilyandefficiently independentlyvaryingthe voltageacrosseachmotorwinding.Fortunately, thereissuchaway.The SN754410hastwoextra “enable”pinsconnected directlytothe+5Vline
Figure19-3:Bipolarcontrolcircuit.
419
Chapter19 inFigure19-3.Thesepins,however,allowustogatethevoltageappliedtothemotoroffandon,aswesee whenwelookattheSN754410’struthtable: Inputs A Enable H H L H X L H=highlevel L=lowlevel X=irrelevant(couldbeeitherHorL) Z=highimpedance(off)state
Output Y H L Z
The“A”connectionsarethebridgedriverinputs,pins2,7,10and15inFigure19-3.The“Y”connections aretheoutputs,pins3,6,11and14inFigure19-3.Bytakingtheenablepinhighorlow,wegatetheoutput offoron.(Whentheoutputisinahighimpedancestate,itiseffectivelyanopencircuit.)Eachenablepin controlsonesetofwindingswhentheSN754410isconfiguredaccordingtoFigure19-3. We’velookedatpulsewidth modulationingeneralin Chapter16,andinChapters 24and26atthehardware pulsewidthmodulation (PWM)modulefoundin mostPICs.Aswe’llseelaterinthischapterwhenwe lookatProgram19-1,we usethePWMmodulesto drivetheenableinputofthe SN754410,withthecircuit showninFigure19-4.Ifthe PWMmoduleoperateswith adutycycleof50%,we reducetheaveragevoltage acrossthemotorby50%. IfthePWMdutycycleis Figure19-4:SN754410H-BridgeWithPWMControlforMicrostepping. 1%,theaveragevoltageis reducedto1%.Thisallowsustovarythemotor’svoltageandthusitscurrentthroughacompletelydigital mechanismunderPICcontrol. WecouldextendthisconceptfurtherandusePWMtocontrolthemotorcurrentdirectly,notthevoltage, constructingwhatisknownasa“chopperdrive”circuit.However,theSN754410offersnoeasywayto senseindividualwindingcurrentandaPIC-controlledconstantcurrentchopperdriveismorecomplexthan appropriateforourdiscussionlevel.
Programs Program19-1 Beforewelookatcodetoimplementmicrostepping,let’sgothroughthemotorcontrolsequence.We’ll breakeachstepinto16microsteps.Ourhighlevelstrategyistoholdthecurrentthroughonewindingpair 420
AdvancedStepperMotors constantwhilerampingthecurrentthroughtheotherwindingpair,followingthecosinefunction: FullSteps 1 2 3 4
Microsteps 0…15 16…31 32…47 48…63
WindingsA-C CosineRampfrom+to– HoldConstant– CosineRampfrom–to+ HoldConstant+
WindingsB-D HoldConstant+ CosineRampfrom+to– HoldConstant– CosineRamp–to+
Let’sdigintothisindetail.We’llrearrangethebitorderfromthenormalB3…B0sequencesothatthemotorsignbitsmatchthewindingconnectionstotheSN754410;WindingsA–CaredrivenviaPICpinsB2–B0 andwindingsB–DviaPICpinsB3–B1inFigure19-4.
Full Step
WindingA-C
WindingB-D
P
P
S
S
µstep
B3
MotorSign Bits B1 B2
R C 0…6 1 0 1 A O 7 1 0 1 + M N 8…14 0 1 1 – P T 15 0 1 1 2 C R 16…22 0 1 1 + O A 23 0 1 1 – N M 24…30 0 1 0 – T P 31 0 1 0 3 R C 32…38 0 1 0 – A O 39 0 1 0 – M N 40…46 1 0 0 + P T 47 1 0 0 4 C R 48…54 1 0 0 – O A 55 1 0 0 + N M 56…62 1 0 1 1b + T P 63 1 0 1 P=polarityofcurrentintowindings S=status; RAMP—currentchangeincosinerelationship CONT—constantcurrent Underlineindicateschangedvalue;intermediatestepsfollowcorrespondingly 1a
+
B0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0
Binary Value 12 12 6 6 6 6 3 3 3 3 9 9 9 9 12 12
Thisisacomplicatedtable,butsinceit’skeytounderstandingourcode,we’llstudyitcarefully.Thefirst fivecolumnsexpandthesummarytable,withtwo“winding”columnsshowingthepolarityofthecurrent (P),anditsstatus(S),whichmaybeeitherconstant(CONT)orramping(RAMP).The“fullstep”and“microstep”columnsshowthefullstepnumberanditsrelationshiptothemicrostepincrements.Themotorsign bitsandbinaryvaluecolumnsaredirectlyrepeatedfromthefullsteppatternsdevelopedinChapter8,that is,step1correspondsto%1010,ordecimal12,step2correspondsto%0110orbinary6,andsoon.Ifthis representationisuncleartoyou,takeabreakandrereadChapter8. I’vebrokenfullstep1into“1a”and“1b”halvestobettershowhowthepatternrepeats.But,there’samore importantreasonforbreakingthestepsthisway.Ifweexaminethepolarityreversalsduringcurrentramping,weseethatthebreakpointsfrompositivetonegativeareexactlyalignedwiththefullsteptransitions. ThismeansthatwemayusethePIC’smotorcontrolbitsB3…B0todriveourSN754410motorcontroller andlettheSN75440takecareofpolarity,whilewepulsewidthmodulatethecorrespondingenablepinsto
421
Chapter19 controlthecurrentlevel.Inotherwords,wemayusethestructureoftheafullstepmotorcontrolprogram, suchasthoseofChapter8andoverlayontopofittwoPWM-basedcosinerampwaveforms,oneforeach winding.Ofcourse,wemustensuretherampwaveformsaresynchronizedwiththefullstepswitching,but that’saneasytask. Programs19-1through19-3usethecircuitshowninFigure19-4.Usingthemethodologydevelopedin Chapter8,determinetheappropriatevaluesofseriesresistanceandmotorvoltageforyoursteppermotor. TheoscilloscopeillustrationsinthischapterareofaPF35-4848-stepunipolarwoundmotor,withnoexternalseriesresistanceand8VintotheSN754410.And,toremindyouagain,don’tusethe2840Development Board’s+5Vsupplytodriveyourstepper—itcan’tsafelysupplyenoughcurrenttopoweranythingbutthe smalleststeppersandit’smarginalforthat. Withthisunderstanding,let’slookatProgram19-1. ;Program19-1Microstep ;inMBasic ;Constants ;---------------------PWMPeriod Con 255 DefaultDC Con 128 MPin Con B0 CycLen Con 64
;PWMwidth20MHzclock=12.75us ;correspondto78KHz ;defaultdutycycle50% ;startingpinformotordriver ;micro-cyclesperrepetition
;Cosinelookuptablefor180degrees ;Weaddthesteady-stateparttosimplifythesteppingcode CosineByteTable252,243,224,196,161,120,| 74,25,25,74,120,161,196,224,243,252,| 255,255,255,255,255,255,| 255,255,255,255,255,255,255,255,255,255 FullStepByteTable12,6,3,9,12,6,3,9;jis0...4 ;Variables ;------------------i Var j Var k Var n Var MPort Var
Byte ;overallcounter Byte ;fullstepindex Byte ;cosindexforw1 Byte ;cosindexforw2 PortB.Nib0 ;outputportpins
;Initialization ;---------------- HPWM0,PWMPeriod,DefaultDC HPWM1,PWMPeriod,DefaultDC ;setmotorporttooutput Forj=MPintoMPin+3 Outputj Next ;allwindingsoff MPort=0 Main ;---Fori=0toCyCLen-1 j=(i+8)/16 k=i//32 n=(i+16)//32 HPWM0,PWMPeriod,Cosine(k) HPWM1,PWMPeriod,Cosine(n) MPort=FullStep(j) Next
422
AdvancedStepperMotors GoToMain End
We’llstartbylookingattheconstants. ;Constants ;---------------------PWMPeriod Con 255 DefaultDC Con 128
;PWMwidth20MHzclock=12.75us ;correspondto78KHz ;defaultdutycycle50%
MBasic’sHPWMfunctiontakesperiodanddutycycleargumentsbetween0and16383.Forreasonsthatwill becomeapparentwhenwestudyProgram19-2,I’vesettheperiodat255,thelargestpossiblebytevalue.The perioddoesnotchange,soI’vedefinedaconstant,PWMPeriod,toholdthisvalue.Chapter24discussesthe HPWMfunctionextensivelyandifyouarenotfamiliarwithit,abriefdetourtoChapter24maybeinorder. MBasicsupportshardwarePWMthroughthefunctionHPWM,withsyntax: HPWMCCPx,Period,Duty CCPx—identifiesthePWMmoduletouse.The16F87xdevices,forexample,havetwohardwarePWM modules,onehardwiredtopinC1andtheotherhardwiredtopinC2.CCPxmaybeaconstantoravariable,
andhastwopermissiblevalues,0and1: CCPxvalue 0 1
PWMGeneratorUsed CCPModule1 CCPModule2
16F87xPinConnection C2 C1
Insomeprintings,MBasic’sUser’sGuideincorrectlyreversestheCCPxvaluesrequiredtoselecttheCCP modules.Incidentally,thetermCCPisusedbecausethehardwaremodulesmaybeconfiguredtoperform threefunctions,capture,compareandPWM,orCCPforshort. PeriodandDuty—Theseparametersareinterrelated,sowe’lllookatthemtogether.We’llusewaveform BtoillustratetheterminologyusedinHPWM. ←Duty→ B
+12 0 ←Period→
Timemarkers(us)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Theperiodmightmoreclearlybereferredtoasthe“repetitionperiod,”i.e.,thetimebetweensuccessive repetitionsoftheoutputwaveform,measuredfromleadingedgetoleadingedge.Intheexample,theperiod is8µs.Dutyisthetimethattheoutputwaveformisatlogicalhigh,4µsintheexample.Acommonlyused termis“dutycycle,”whichistheratioofhightolowperiods.Intheexample,thedutycycleis4µs/8µsor 0.50.Thevalueisoftenexpressedasapercentage,soourexamplehasadutycycleof50%.(Occasionally dutycycleisusedtoexpressthepercentageoftimelow,nothigh,sowatchthecontextinwhichtheterm isused.)TheaverageDCoutputofthePWMwaveformisthedutycycle.We’vesettheperiodat255,soby varyingdutyfrom0…255,wevarytheaveragevalueoftheDCoutputfrom0to100%ofthemaximum. AswelearninChapter24,thehardwarePWMmodule’speriodissetbytherelationship: N tp = fOSC
423
Chapter19
tpisthepulseperiod(duration)inseconds
NistheperiodargumenttotheMBasicfunctionHPWM,255inProgram19-1
fOSCisthePIC’soscillatorclockfrequency,20MHzinmycase tp =
255 = 12.75 × 10 −6 20 × 10 6
Thepulsefrequencyshouldn’tbesolowastocauseacousticnoise,norsohighastocauseexcessiveloss.A periodof12.75µscorrespondsto78KHz,whichisabithigh,butstillwithintheacceptablerange. WeinitializethedutycyclesothatthePWMoutputisapproximatelyasquarewave,witha50%dutycycle, thusrequiringHPWM’sdutycycleargumenttoequal128.Accordingly,wedefineaconstant,DefaultDC, equalto128,touseininitializingthePWMmodules. MPin CycLen
Con Con
B0 64
;startingpinformotordriver ;micro-cyclesperrep
MPinisthestartingpinforthedrivepattern;CycLenisthenumberofmicrostepsbeforethemicrostepcycle repeatsitself.
Althoughthefullrepetitionperiodis64microsteps,lookingatwindingsA-Cweseethatthesecond32microstepsrepeatthefirst32,exceptforthedirectionofcurrentflow.Likewise,weseethatthecurrentflowin windingsB-DhasanidenticalpatterntowindingsA-C,exceptthatB-Disdelayedby16microsteps.These symmetriessuggestthatwecreateabytetableoflength32,startingwithalength16cosineramp,followed byalength16constanttrailer.SincethePWMperiodargumentis255,thedutycyclerangesfrom0(no output)to255(maximumoutput).Wethereforescalethemaximumandminimumcosinevaluestorange from0…255. CosineByteTable
252,243,224,196,161,120,| 74,25,25,74,120,161,196,224,243,252,| 255,255,255,255,255,255,| 255,255,255,255,255,255,255,255,255,255
Let’sseehowweconstructedthistable.Figure19-5isaviewofthecosinetransitioncurrentwaveformobjective,quantizedin16steps.Sincewedeterminethesignofthecurrentseparately,ourbytetablecontains
300
300
200
250
200
Magnitude
Magnitude
100
0
150
100
–100 50
–200 0
–300 0
10
20
30
40
50
0
60
Microstep Number
Figure19-5:WindingA-CCurrentwaveform.
8
16 Microstep Number
24
Figure19-6:Desiredcosinebytetablevalues.
424
32
AdvancedStepperMotors onlythemagnitudeofthecosinefunction,and,becauseofsymmetry,itneedbeonlylength32.Figure19-6 showstheresultingdesiredbytetablevalues.Mathematically,thefirsteightentriesmaybecalculatedas: ( N + 0.5) × 360 BT ( N ) = 255 × cos 32
Nisthemicrostepnumber,0…7.Weaddone-halfsteptoNtogetabetterapproximationtotheaverage valueofthecosinefunction,sinceweevaluateitwithonlyeightsteps. 255Isthemultipliernecessarytoscalethecosinefunctionvalue.OvertherangeN=0…7,thevalueof cosinerangesfrom+1to0;hencewemultiplyitby255torescaleitsrangeto0…255 cosisthetrigonometriccosinefunction,withtheargumentstatedindegrees Usingthisrelationship,wecalculatethefirsteightentriesinthetable.Thenexteightentriesareidenticalto thefirsteight,butinreverseorder.Thefinal16entriesareconstant,setatthemaximumoutput,255. FullStepByteTable12,6,3,9,12,6,3,9;jis0...4
Wealsorequireaccesstothefullsteppattern,soastoaccomplishthepolarityreversals.Thebytetable FullStep,copiedfromChapter8,providesthisaccess. ;Initialization ;----------------
HPWM0,PWMPeriod,DefaultDC HPWM1,PWMPeriod,DefaultDC ;setmotorporttooutput Forj=MPintoMPin+3 Outputj Next ;allwindingsoff MPort=0
Atinitialization,weturnbothPWMmodulesonandsettheperiodanddutycycleatthedefaultvalues, previouslydefinedas256and128respectively.Wealsosettheoutputpinstooutputmode,butmadelowto unenergizethemotorwindings. Main ;---Fori=0toCyCLen-1 j=(i+8)/16 k=i//32 n=(i+16)//32 HPWM0,PWMPeriod,Cosine(k) HPWM1,PWMPeriod,Cosine(n) MPort=FullStep(j) Next GoToMain
Themainprogramreliesonfourindexvariables,i,j,kandn: i—runsfrom0…63andrepresentsonecompletemicrostepcycle. j—indexesintothebytetableFullStep().Inourearliertableoverview,FullStep(j)returnsthe “binaryvalue”value.Toaccomplishthis,jstepsfrom0…4,witheachjincrementamountingto16 microsteps.Sincethefirstfullstepisdividedintotwohalfsteps,weaddonehalfof16microstepsasan offset.Hence,j=(i+8)/16. k—indexesintothecosinearraycosine()forwindingsA-C.Basedonourearliertable,kmustrun0…31 andthenrepeat0…31asiruns0…63. n—indexesintothecosinearraycosine()forwindingsB-D.Basedonourearliertable,ntracksk,but withanoffsetof16microsteps.Hence,wecomputen=(i+16)//32. 425
Chapter19 Aftereachcompletemicrostepcycleisrepeated,theGoToMainrestartsthecycle. Let’sseehowthesefourvariablesandthetwobytetablesfitintooursummary: WindingA-C Full Step
MotorSign Bits
WindingB-D
P *
S P S µstep B3 B1 B2 B0 Cosine(k) * Cosine(n) i FullStep(j) R C 0…6 1 0 1 0 1a + A O 7 1 0 1 0 + M N 8…14 0 1 1 0 P T 15 0 1 1 0 2 C R 16…22 0 1 1 0 + O A 23 0 1 1 0 N M 24…30 0 1 0 1 T P 31 0 1 0 1 3 R C 32…38 0 1 0 1 A O 39 0 1 0 1 M N 40…46 1 0 0 1 + P T 47 1 0 0 1 4 C R 48…54 1 0 0 1 O A 55 1 0 0 1 + N M 56…62 1 0 1 0 1b + T P 63 1 0 1 0 P=polarityofcurrentintowindings S=status; RAMP—currentchangeincosinerelationship CONT—constantcurrent Underlineindicateschangedvalue;intermediatestepsfollowcorrespondingly *=thesignistakencareofautomaticallybyFullStep(j)
Binary Value 12 12 6 6 6 6 3 3 3 3 9 9 9 9 12 12
There’salotgoingoninsixlinesofcode,solet’sunrolltheloopandseeexactlywhathappensaswego throughonecompletecycleof64microsteps. i 0 1 2 3 4 5 6 7 8 9 10 11 12
J 0 0 0 0 0 0 0 0 1 1 1 1 1
FW(J) 12 12 12 12 12 12 12 12 6 6 6 6 6
B3 1 1 1 1 1 1 1 1 0 0 0 0 0
B1 0 0 0 0 0 0 0 0 1 1 1 1 1
B2 1 1 1 1 1 1 1 1 1 1 1 1 1
B0 0 0 0 0 0 0 0 0 0 0 0 0 0
k 0 1 2 3 4 5 6 7 8 9 10 11 12
Cosine (k) 252 243 224 196 161 120 74 25 25 74 120 161 195
n 16 17 18 19 20 21 22 23 24 25 26 27 28
Cosine (n) 255 255 255 255 255 255 255 255 255 255 255 255 255
Comments AC=+BD=+
Reversal:AC=-/BD=+
(Continued)
426
AdvancedStepperMotors i
J
FW(J)
B3
B1
B2
B0
k
Cosine (k)
n
Cosine (n)
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4
6 6 6 6 6 6 6 6 6 6 6 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 12
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
224 243 252 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 252 243 224 196 161 120 74 25 25 74 120 161 195 224 243 252 255 255 255 255 255 255 255 255 255
29 30 31 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6 7 8
255 255 255 252 243 224 196 161 120 74 25 25 74 120 161 195 224 243 252 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 252 243 224 196 161 120 74 25 25
Comments
Reversal:AC=-/BD=-
ReversalAC=+BD=-
Reversal:AC=+/BD=+
(Continued)
427
Chapter19 i
J
FW(J)
B3
B1
B2
B0
k
Cosine (k)
n
Cosine (n)
57 58 59 60 61 62 63
4 4 4 4 4 4 4
12 12 12 12 12 12 12
1 1 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 1 1
0 0 0 0 0 0 0
25 26 27 28 29 30 31
255 255 255 255 255 255 255
9 10 11 12 13 14 15
74 120 161 195 224 243 252
Comments
Let’sseehowProgram19-1works.It’seasiertoillustrateProgram19-1’swaveformswitharesistorinstead ofsteppermotorwindings,soIsubstitutedan8ohm,5wattresistorforthesteppermotorwindingconnectedbetweentheSN754410’spins3and6forFigures19-7through19-9.Figure19-7showstheenable voltage(pin1)totheSN754410andtheresultingcurrent(pin3).Bothmatchourdesiredtargetquitewell; thecurrentswingssmoothlybetweenitsmaximumpositiveandnegativevalues.I’veexpandedthetimebase inFigure19-8soyoumayseethatthecurrentandvoltageareindeedquantizedindiscretevalues.
Figure 19-7: Program 19-1 Output; Ch1: SN754410Pin1;Ch2:CurrentfromSN754410 Pin3.
Figure19-8:ExpandedViewofProgram19-1 Output; Ch1: SN754410 Pin 1; Ch2: Current fromSN754410Pin3.
But,justaminuteyou’rethinking.Figures19-7and8showtheSN754410’senableinputdrivenbyan analogvoltage,notalogic-levelPWMoutput.Goodcatch,butwhatyouseeisadigitalsamplingoscilloscopeartifact.AswesawinChapters11and16,any analog-to-digitalconversiononlyaccuratelyrepresentsthe inputwaveformuptofrequenciesofone-halfofthesample rate.Figure19-8istakenata25kilo-samples/sec,permiting accuratereproductionofinputsignalsuptoonlyabout12.5 KHz.WhatChannel1showsinbothFigures19-7and8is theaveragevoltageoutputoftheHWPMmodule.Ifwefurtherexpandthetimebaseto25mega-samples/sec,asshown inFigure19-9,weseeexactlywhatshouldbethere;aPWM digitaloutputthatswitchesbetweenlogical0and1. Nowthatwe’veverifiedProgram19-1doeswhatisexpected,connectasteppermotortotheSN754410.Itruns,but veryslowlycomparedwithChapter8’sprograms.Measur-
428
Figure 19-9: Ch1: SN754410 Pin 1; Ch2: Unused.
AdvancedStepperMotors ingthedurationfortwocurrentreversals,(64microsteps)wefindthatonemicrosteprequiresabout1410µs. Sinceittakes768microstepsforonerevolutionofmyPF35-48stepper,wecalculate1.08secondsforeach motorshaftrevolution,about55.4RPM. Program19-2 Program19-2answersthequestion“canweimproveProgram19-1toamoreusefulspeed”?Theanswer isyes,wecanincreasethespeedaboutsix-foldbyreplacingallMBasicstatementswithintheFori=0 toCyCLen-1…Nextloopbyassemblerroutines.We’llusethestepwiserefinementapproachdevelopedin Chapter14—replaceoneMBasicstatementwithanassemblerroutineandverifyitsoperation,repeatingthe processwithdifferentMBasicstatementsuntilourspeedobjectiveismet.And,we’llmakeliberaluseofthe “bolt-in”MBasic-to-assemblerreplacementsinChapter14. There’slittlepointinprovidingsixdifferentversionsofProgram19-2,eachwithonemoreMBasicstatementconvertedtoassembler.Instead,we’llshowthe“asconverted”program,makingclearwhichMBasic statementisreplacedbyassemblercode.Ofcourse,thisisnotthewayProgram19-2evolved.Aswelearned inChapter14,it’smucheasiertoreplacethestatementsone-at-a-timeandgotothenextreplacementonly afterthefirstisdebuggedandverified. ;Program19-2Microstep ;inMBasicwithassemblerspeedups STACK=10
;needspaceinBank0forvariables
;Constants ;---------------------PWMPeriod Con 255 ;PWMwidth20MHzclock=12.75us ;correspondto78KHz DefaultDC Con 128 ;defaultdutycycle50% MPin Con B0 ;startingpinformotordriver MDelay Con 2000 ;microsecondsdelayperstep CycLen Con 64 ;micro-cyclesperrev Zero Con 0 ;forbanking ;Variables ;------------------i Var j Var k Var n Var l Var x Var MPort Var
Byte ;overallcounter Byte ;fullstepindex Byte ;cosindexforw1 Byte ;cosindexforw2 Byte ;ASMcounterindex Byte ;temp PortB.Nib0 ;outputportpins
;Cosinelookuptablefor180degrees ;Weaddthesteady-stateparttosimplifythesteppingcode ;Onlycommentoutthesetwobytetablesafterconvertingto;assemblycode,asthey areneededduringthepiecewiseBASIC-to-;Assemblerconversions. ;Cosine ByteTable 252,243,224,196,161,120,74,25,| ; 25,74,120,161,196,224,243,252,| ; 255,255,255,255,255,255,255,255,| ; 255,255,255,255,255,255,255,255 ; ;FullStep ByteTable12,6,3,9,12,6,3,9;jis0...4 ;Initialization ;----------------
HPWM0,PWMPeriod,DefaultDC HPWM1,PWMPeriod,DefaultDC ;setmotorporttooutput Forj=MPintoMPin+3
429
Chapter19 Outputj Next ;allwindingsoff MPort=0 l=0 i=0 k=0 n=0 x=0 Main ;---Fori=0toCyCLen-1 ;j=(i+8)/16 ASM { movf i&0x7F,w ;i+8 addlw 0x8 movwf j&0x7F ;j=i+8 movlw 0x4 movwf l&0x7F ;L=4 Shift16 RRF j&0x7F,f ;/2butthisisrotate,notshift bcf STATUS,C ;clearthecarryflag decfsz l&0x7F,f ;L=L-1 GoTo Shift16 ;whileL>0GoToShift } ;k=i//32 ASM { movf i&0x7F,w andlw b’00011111’ ;masksouthigh3bits=//32 movwf k&0x7F } ;n=(i+16)//32 ASM { movf i&0x7F,w ;i+8 addlw .16 andlw b’00011111’ ;masksouthigh3bits=//32 movwf n&0x7F ;j=i+8 } ;HPWM0,PWMPeriod,Cosine(k);PinC2 ;HPWM1,PWMPeriod,Cosine(n) ;PinC1 ASM { ;PWMNo.1onPinC2 ;--------------------- movlw HIGHCosineTable ;w=highbytetablelocation movwf PCLATH ;PCLATHhashighbyte movlw LOW(CosineTable+1) ;firstdatapoint addwf k&0x7F,w ;offsetaddressofdatapoint btfsc STATUS,C incf PCLATH,f call CosineTable ;whatisdutycyclevalue movwf x&0x7F ;Storeinx
;nowgettwoLSBandmovetoCCP1CONhome ;twolowestbitsofdutycycleareheldinCCP1CON<5>&<4> ;presumptiveclearCCP1CON<4>
bcf CCP1CON,4 ;IfDutyCycle.Bit0=1thensetCCP1CON<4>=1 btfsc x&0x7F,0
430
AdvancedStepperMotors
bsf CCP1CON,4 ;PresumptiveclearofCCP1CON<5> bcf CCP1CON,5 ;IfDutyCycle.Bit1=1thenSetCCP1CON<5>=1 btfsc x&0x7F,1 bsf CCP1CON,4 ;nowwemoveDutyCycletoCCPR1L.Butfirstmust ;maskofflowertwobitsandshiftright2bits movlw b’11111100’ andwf x&0x7F,f ;maskinplace rrf x&0x7F,f ;right1bit rrf x&0x7F,f ;right1morebit movf x&0x7F,w ;copyittow movwf CCPR1L ;nowinsertintoCCPR1L ;PWMNo.2onPinC1 ;--------------------movlw HIGHCosineTable movwf PCLATH movlw LOW(CosineTable+1) addwf n&0x7F,w btfsc STATUS,C incf PCLATH,f call CosineTable movwf x&0x7F
;w=highbytetablelocation ;PCLATH=highbyteoftable ;firstdatapoint ;offsetaddressofdatapoint ;whatisdutycyclevalue ;Storeinx
;nowgettwoLSBandmovetoCCP2CONhome ;twolowestbitsofdutycycleareheldinCCP2CON<5>&<4> ;presumptiveclearCCP2CON<4> bcf CCP2CON,4 ;IfDutyCycle.Bit0=1thensetCCP2CON<4>=1 btfsc x&0x7F,0 bsf CCP2CON,4
;PresumptiveclearofCCP2CON<5> bcf CCP2CON,5 ;IfDutyCycle.Bit1=1thenSetCCP2CON<5>=1 btfsc x&0x7F,1 bsf CCP2CON,4
;nowwemoveDutyCycletoCCPR2L.Butfirstmust ;maskofflowertwobitsandshiftright2bits movlw b’11111100’ andwf x&0x7F,f ;maskinplace rrf x&0x7F,f ;right1bit rrf x&0x7F,f ;right1morebit movf x&0x7F,w ;copyittow movwf CCPR2L ;nowinsertintoCCPR1L GoTo EndCosRoutine CosineTable movwfPCL retlw0xfc retlw0xf3 retlw0xe0 retlw0xc4 retlw0xa1 retlw0x78 retlw0x4a retlw0x19 retlw0x19 retlw0x4a retlw0x78 retlw0xa1 retlw0xc4 retlw0xe0 retlw0xf3 retlw0xfc retlw0xff
431
Chapter19 retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff retlw0xff EndCosRoutine } ;MPort=FullStep(j) ASM { movlw HIGHFullStepTable ;w=highbytetablelocation movwf PCLATH ;PCLATH=highbyteoftable movlw LOW(FullStepTable+1) ;firstdatapoint addwf j&0x7F,w ;offsetaddressofdatapoint btfsc STATUS,C incf PCLATH,f call FullStepTable ;whatisstepvalue movwf MPort&0x7F ;outputittoPortB GoTo EndRoutine FullStepTable movwfPCL retlw0xc retlw0x6 retlw0x3 retlw0x9 retlw0xc retlw0x6 retlw0x3 retlw0x9 EndRoutine BankSelZero } ;Formaxspeed,removethefollowingstatement PauseusMDelay Next GoToMain End
TheconstantsandvariabledeclarationsectiontracksProgram19-1,withfourexceptions: MDelay Con
2000
;microsecondsdelayperstep
l x Zero
Var Var Con
Byte Byte 0
;ASMcounterindex ;temp ;forbanking
SinceProgram19-2executesamicrostepin246µs,inmanyapplicationsitmaybenecessarytoslowit down.Hence,we’veaddedapauseusstatementtothemicrostepcontrolloop;MDelayisthevalueofthe delay,inmicroseconds.I’vemadethisaconstanttosimplifyourprogramming,butyoumaywishtomake thedelaytimeauser-settablevariable.TheassemblerprogramGPASM,usedwithMBasic5.3.0.0onward, willnotacceptanumericalargumentforbanksel;hencewedefinethesymbolicconstantzeroas0thus permittingustosetthebankselectorbitsto0usingtheoperationbankselzero.Theoperationbanksel 0,permissibleinMPASMusedinMBasic’searlierversionsisnotacceptedbyGPASM’scurrentrelease.
432
AdvancedStepperMotors Twoadditionalbytevariables,landxareusedintheassemblerroutines.
HPWM0,PWMPeriod,DefaultDC HPWM1,PWMPeriod,DefaultDC ;setmotorporttooutput Forj=MPintoMPin+3 Outputj Next ;allwindingsoff MPort=0 l=0 i=0 k=0 n=0 x=0
Theonlyinitializationchangeadds“variable=0”statementsforallvariablesonlyusedinanassembler routine.AswelearnedinChapter14,MBasic’scompilerallocatesspaceforavariableonlyifit’susedin anMBasicstatement.Toforcethecompilertoallocatespace,weeitherusethevariable(suchasusingj intheFor…Nextloop)forsomebeneficialpurpose,orwesetittosomevalue,0inthiscase,inadummy statement.(ThevariableiisusedinaFor..Nextloop,soitdoesnotrequireadummyassignmentinthe initializationsection.) Beforewedigintothecode,tworeminders: • Ourassemblerprogramdoesnotusebankselorotherwisesetthebankingbits,exceptonceattheend oftheasmcode.Thisisbecauseallthevariables,portsandregistersweaccessareinBank0,andwhen MBasicpassescontroltoanin-lineassemblerroutine,thebankingbitsarealreadysettobank0.Chapters13and14explainhowtoverifywhetherbankselectionisnecessary.InProgram14-2,weforcethe compilertoreservespaceinbank0forourvariablesbymanuallysettingthemaximumstacksizeto40 bytesviatheSTACK=10instruction. • Toremovespuriousassemblerwarnings,I’vetrimmedoffthecompilercontrolbitsby“anding” variableswith$7F,usingtheoperator&0x7F.(Rememberassemblerusestheprefix0xinsteadof$to indicatehexadecimal.)ToloadthecontentofmemorylocationiintothePIC’swregister,therefore,we writemovfi&0x7F,w.Correctcodewillbegeneratedifthecompilercontrolbitsarenotmaskedoff, aswouldbethecaseifthisstatementwerewrittenmovfi,w,buttheassemblerwillissuewarning messagessuchasthefollowing: Warning[219]C:\DOCUME~1\JSMITH\MYDOCU~1\MEASUR~1\EXPERI~1\CH19SE~1\PROGRAMS\PROGRA~2.ASM197: InvalidRAMlocationspecified. Message[302]C:\DOCUME~1\JSMITH\MYDOCU~1\MEASUR~1\EXPERI~1\CH19SE~1\PROGRAMS\PROGRA~2.ASM197: Registerinoperandnotinbank0.Ensurethatbankbitsarecorrect.
Speedup1:Weconvertj=(i+8)/16toassembler.Thisconversionsaves319µsoverthepure-MBasic code,andincreasesthemaximumspeedofmyPF35-48stepperfrom55.4RPMunderpure-MBasiccodeto 71.6RPM. Whenprogrammingamultipartmathematicalexpression,wemustfunctionasa“humanparser”andbreak theexpressionintoalogicalevaluationorder.We’llfollowthestandardorderofprecedencerulesforarithmetic,andevaluatetheexpressionintwosteps: 1. Calculatethevaluei+8.Storethisvalueinj. 2. Calculatej/16andstoretheanswerinj.
;j=(i+8)/16 ASM { movf i&0x7F,w
;i+8
433
Chapter19
addlw 0x8 movwf j&0x7F
;j=i+8
Weknowthatiisalwaysintherange0…63,soi+8cannotexceed71.Hence,wehavenoworryabout overflowingbytelengtharithmeticandmayuseasimplealgorithmforaddition.Wefirstcopythevalueof iintotheworkingregisterwwiththemovfoperator.Wethenusetheoperatoraddlwtoaddthevalueofa constant8(a“literal”inMicrochipterminology)tow,retainingthesumi+8inw.Lastly,wecopythevalue ofthewregistertothevariablejbytheoperatormovwf. Shift16
movlw 0x4 movwf l&0x7F RRF bcf decfsz GoTo }
;L=4
j&0x7F,f STATUS,C l&0x7F,f Shift16
;/2butthisisrotate,notshift ;clearthecarryflag ;L=L-1 ;whileL>0GoToShift
Wenowdividejby16.Since16isanexactbinarypower,24,integerdivisionissimplybit-shiftingjfour bitstotheright.(Itwasn’taccidentalthatwedecidedtouse16microstepsperfullstepinsteadof10or12;by keepingthisrelationshipasanexactbinarypowervalue,wesimplifythedivisionalgorithmconsiderably.) Torepeattheshiftfourtimes,weusetheloopoperator,decfsz.First,weloadatemporaryvariablelwith thenumberoftimeswewishthelooptobeexecuted,fourinthiscase.Sincethemid-rangePIChasno direct“loadaconstanttomemory”operator,wefirstload4intothewregisterwiththemovlwoperator,and thencopyw’svalueintolwiththemovwfoperator. Theoperatordecfszf,ddecrementsthevalueofthefilefandreturnsthedecrementedvaluetodestinationd.Inourcase,thefileisvariableislandwewishtheresulttobereturnedtol,sothedestination optionwillbef.Consequently,theassemblerstatement(includingthecompilertrimprovision)isdecfsz l&0x7F,f.Ifl=0,thenextinstructionisskipped.Ifl<>0,thenextinstructionisexecuted.Hence,thecode structureusingdecfsztorepeatagroupofassemblerinstructionsNtimes,inpseudo-assembler,is: SetatemporaryvariableltoN Loop1 Assemblercodetoberepeatedgoeshere decfszl,f GoToLoop1
Notethatthedecrementisperformedbeforethecomparison.Hencetoexecuteacodesequencefourtimes, thecountervariablemustbepreloadedwith4.Afterdecrementingandcomparing,thefirstthreetimes throughtheloop,theresultwillbenonzero,sotheoperationGoToLoop1willbeexecuted.Afterthefourth passthroughtheloop,lequals1.Thedecfszoperatorthendecrementslagain,atwhichpointitiszero. Thetestforzeroisnowtrue,sotheGoToLoop1statementisskippedandexecutionproceedstothenext statementaftertheGoTo.Thecodewithintheloophasbeenexecutedexactlyfourtimes,aswedesired. Microchip’smid-rangePICsimplementbitshiftingastheassemblerinstructionsRLFandRRF,standingforrotate leftthroughcarryflagandrotaterightthroughcarryflag.Thisisnotquitebinarydivision.Let’sseehowRRF works.Supposewewishtodividethevalue51by4.(I’vehighlightedthemovementofthecarrybitinbold.) C 0 1 1
B7 0 0 1
B6 0 0 0
B5 1 0 0
Register B4 B3 1 0 1 1 0 1
B2 0 0 1
B1 1 0 0
B0 1 1 0
Comments Value=123 Firstshifttotheright;equivalentto/2;resultis25 Secondshifttoright;notethe1shiftedthroughcarryhas nowreappearedatB7.Thedecimalvalueisnow140,not 12asdesired.
434
AdvancedStepperMotors Whathappenedisasweshiftonebittotheright,the%1weshiftedoutmovestothecarrybitinthePIC’s statusregister.Withthenextshift,thecarrybitmovestotheregister’sB7bit.Thisrotatethroughcarry mightbemoreproperlynamed“re-circulation”asthebitsweshiftoutdon’tdisappear,butratherarerecirculatedbackthroughthecarryflagbitbacktothehighorderbitintheregister.Topreventtheseunwanted bitsfrombeingre-circulated,weadoptastrategyofshift,followedbyclearingthecarrybit.Repeatingour calculationsfordividing51by4,weseethatcorrectanswerisproduced. C 0 1 0 1
B7 0 0 0 0
B6 0 0 0 0
Register B4 B3 1 0 1 1 1 1 0 1
B5 1 0 0 0
B2 0 0 0 1
B1 1 0 0 0
B0 1 1 1 0
Comments Value=123 Firstshifttotheright;equivalentto/2;resultis25 Nowclearthecarrybit Secondshift.Theresultis12,asdesired
Toclearthecarryflag,weusethebitclearoperator,bcf,withfileStatus,wherethecarryflagbitisheldat bitC.Hence,ourtwo-operatorrotateandclearsequenceisimplementedas:
RRF bcf
j&0x7F,f STATUS,C
;/2butthisisrotate,notshift ;clearthecarryflag
Speedup2:Hereweconvertk=i//32toassembler.Thisconversionsaves276µs,andincreasesthemaximumspeedofmyPF35-48stepperto95.8RPM.
;k=i//32 ASM { movf i&0x7F,w andlw b’00011111’ movwf k&0x7F }
;masksouthigh3bits=//32
MBasic’s//operatoristhemodulusorremainderfunction.Herewemaytakeadvantageofanotherconvenientfeatureofusinganexactbinarypowerasthedivisor.Ifthedivisorisoftheform2N,themoduluscanbe obtainedbymaskingouthigherorderbitsofthedividend,retainingonlythebottomNbits.And,wemaysimplymaskoffbitsbythebitwiseANDoperator.Let’sseehowthisworksincalculatingi//32supposingi=51. B7 0 0
B6 0 0
B5 1 0
B4 1 1
B3 0 0
B2 0 0
B1 1 1
B0 1 1
Comment =51 Right5bitsonly=19
LogicalANDtoperformthebitmasking 0 0 0
0 0 0
1 0 0
1 1 1
0 1 0
0 1 0
1 1 1
1 1 1
=51 =(32-1) 51AND31=19
Toimplementthisalgorithm,ourassemblercodecopiesthevalueofiintothewregister,masksouttheupperthreebitsbyANDingwwiththeliteralvalue%00011111andcopiestheresultintok. Speedup3:Hereweconvertn=(i+16)//32toassembler.Thisconversionsaves320µs,andincreasesthe maximumspeedofmyPF35-48stepperto158.2RPM. We’vealreadydonebothpartsofthisconversioninSpeedupsoneandtwo.Sincei+16canneverbegreater than79,theresultfitsinasinglebyteandweneednotworryaboutoverflowintheaddition.Applyingthe lawsofmathematicalprecedence,weevaluatethisexpressionas:
435
Chapter19 1. Copythecontentsofitoregisterwandadd16 2. Maskoutthehighestthreebitsinregisterw,therebyyieldingtheremainderafterdividingby32.Copy thecontentsofwton.
;n=(i+16)//32 ASM { movf i&0x7F,w addlw .16 andlw b’00011111’ movwf n&0x7F }
;i+8 ;masksouthigh3bits=//32 ;j=i+8
Theabovecodeimplementsthisstrategy,usingthesametechniquesweusedearlier. Speedup4:HereweconvertMPort=FullStep(j)toassembler.Thisconversionsaves72µs,andincreasesthemaximumspeedofmyPF35-48stepperto185.2RPM. Theassemblercodeimplementsastandardjumptable.JumptablesarediscussedatChapter14andthetable herefollowsthetemplatedevelopedthere.Inessence,weloadthewregisterwiththedesiredindexjand programexecutionjumpstothejthretlwstatementfollowingthestartofthetable. TheretlwstatementthenreturnstheassociatedliteralvalueinthewregisterthatwethensendtoPortB. ;MPort=FullStep(j) ASM { movlw movwf movlw
HIGHFullStepTable ;w=highbytetableloc’n PCLATH ;PCLATH=highbyteoftable LOW(FullStepTable+1) ;firstdatapoint
Togetprogramexecutiontojumptothedesiredretlwstatement,weloadthestartingaddressoftheretlw sequence(identifiedbythelabelFullStepTablehere)intotheprogramcounterandaddtheoffsetto retrievethespecificitem.Mid-rangePICs—includingthe16F877Aweusehere—havea13-bitprogram counter,sowecan’tloadacompleteaddressinonestepwiththePIC’s8-bitwidedatamemory.And,the upperfivebitsoftheprogramcounterareonlyindirectlyaddressableviathePCLATHregister.Hence,we loadthestartingaddressofthejumptableintwopieces;thehighbyteoftheaddressisloadedviathe PCLATHregister,whilethelowaddressbyteisdirectlyenteredintoPCL,whichholdsthelow8bitsofthe programcounter. addwf btfsc incf call
j&0x7F,w STATUS,C PCLATH,f FullStepTable
;offsetaddressofdatapoint ;whatisstepvalue
WethenaddtheoffsetaddresstoPCLtoobtainthefull13-bitaddressofthedesiredjumptableentry.Ifthe resultofaddingtheoffsetaddresstothelower8bitsoftheprogramcounterisgreaterthan255,theoverflow setsthecarryflag.Ifthecarryflagisset,thestatementfollowingthebtfscSTATUS,Cisexecutedandwe add%1toPCLATH,therebybumpingupthehighorderfivebitsbyonetorepresentthecarry.Ifthecarryflag isnotset(nocarry),theincfPCLath,fstatementisskipped.Theactualjumpisexecutedthroughthe calloperator. movwf GoTo
MPort&0x7F EndRoutine
;outputittoPortB
Executionreturnstothestatementafterthecall,andwiththeindexedvaluestoredinw.Wethencopyw’s valuetotheoutputportthroughthemovwfoperator.Lastly,wejumpoverthedatatableviaaGoTothat transfersexecutiontotheendofthisroutine. FullStepTable movwfPCL retlw0xc retlw0x6
436
AdvancedStepperMotors retlw0x3 retlw0x9 retlw0xc retlw0x6 retlw0x3 retlw0x9 EndRoutine
Speedup5:HereweconvertHPWM0,PWMPeriod,Cosine(k)toassembler.Thisconversionsaves85µs, andincreasesthemaximumspeedofmyPF35-48stepperto231RPM.
ASM { ;PWMNo.1onPinC2 ;---------------------movlw HIGHCosineTable ;w=highbytetablelocation movwf PCLATH ;PCLATHhashighbyte movlw LOW(CosineTable+1) ;firstdatapoint addwf k&0x7F,w ;offsetaddressofdatapoint btfsc STATUS,C incf PCLATH,f call CosineTable ;whatisdutycyclevalue movwf x&0x7F ;Storeinx
Theabovecodeisanotherjumptablelookup,performingthesamefunction,andwiththesamealgorithm,we usedinconnectionwiththeFullStepTablelookup.TheonlydifferencesarethatweindexbasedonthevariablekandthelookuptableisCosineTable.Hence,wewillnotfurtheranalyzethispartofthecode. ThereturnedvaluefromCosineTableisstoredinthetemporaryvariablex.Wewillnowseehowthevalue ofxiscopiedintothePWMdutycyclecontrolregisters.Thedutycyclevalueis10bitswide,organizedas 2-bitand8-bitsegments: B9
B8
B7
B7
B6
B5
10-bitDutyCycleValue(B9…B0) B6 B5 B4 B3 B2 CCPR1L B4 B3
B2
B1
B0
B1
B0
CCP1CON B5 B4
ThemostsignificanteightdutycyclebitsarecontainedintheCCPR1Lregister,whilethetwoleastsignificantbitsarestoredatbits5and4intheCCP1CONregister.Althoughwewishtowritean8-bitdutycycle value,wemustsplititintoa6-bitanda2-bitsegmentandplacethevaluesinCCPR1LandCCP1CON.After insertingthevalueofxintothedutycyclecontrolregisters,theresultwillbethefollowing,wherex.7 meansbitno.7ofthevalueofourtemporarydutycycleholderx,x.6meansbitno.6ofx,etc.: B7 0
B6 0
B5 x.7
CCPR1L B4 B3 x.6 x.5
B2 x.4
B1 x.3
B0 x.2
CCP1CON B5 B4 x.1 x.0
bcf CCP1CON,4 ;IfDutyCycle.Bit0=1thensetCCP1CON<4>=1 btfsc x&0x7F,0 bsf CCP1CON,4
MidrangePICsdonothavea“copybit”operation,sotomovetheabitfromonelocationtoanother,wefollowatwo-stepprocess: 1. Setthedestinationbitto%0usingthebitclearfilebcfoperator. 2. Checkthesourcebitusingthebittestfileskipifclearbtfscoperator.Ifthesourcebitis%0,weare finished.Ifitis%1,setthedestinationbitto%1usingthebitsetfilebsfoperator. Theabovecodeimplementsthisalgorithmforbitx.0.
437
Chapter19
;PresumptiveclearofCCP1CON<5> bcf CCP1CON,5 ;IfDutyCycle.Bit1=1thenSetCCP1CON<5>=1 btfsc x&0x7F,1 bsf CCP1CON,4
Thesethreelinesimplementthesamealgorithmforbitx.1. Now,wemustmovex’ssixhighorderbitstoCCPR1L,rightjustifyingthesixbitsintheprocess.We couldusetherotatethroughcarryfunctionandzerooutthecarryflag,aswhendidwhendividingby16 earlier.We’lluseanalternativeapproachandforcethelowesttwoorderbitsofxtozerobyANDingwith %11111100andthenrotate.
;nowwemoveDutyCycletoCCPR1L.Butfirstmust ;maskofflowertwobitsandshiftright2bits movlw b’11111100’ andwf x&0x7F,f ;maskinplace
Toaccomplishthis,wemovethemaskliteral%11111100tothewregisterandthenANDthewregister’s valuewithx,storingtheresultinx,withtheabovetwooperations.
rrf rrf
x&0x7F,f x&0x7F,f
;right1bit ;right1morebit
Sincetherightmosttwobitsarezero,wemayrotatetwoplacestotherightwithoutworrythat%1’swillbe shiftedoutandreturnthroughthecarryflag.Afterthesetworotations,thesixbitsleftarerightjustifiedinx.
movf movwf
x&0x7F,w CCPR1L
;copyittow ;nowinsertintoCCPR1L
Thelaststepremainingistocopyx’svaluetotheCCPR1Lregister,whichwedointheusualwaybyfirst copyingx’svaluetothewregisterandthencopyingthewregistertothedestination,CCPR1L. Speedup6:HereweconvertHPWM1,PWMPeriod,Cosine(n)toassembler.Thisconversionsaves91µs, andincreasesthemaximumspeedofmyPF35-48stepperto317RPM. ThiscodeduplicatesthecodeinSpeedup5,exceptitisforsecondhardwarePWMmodule.Theonly changesareintheindexintotheCosineTable(ninsteadofk)andthedestinationregistersfortheduty cyclevalues(CCPR2LinsteadofCCPR1LandCCP2CONinsteadofCCP1CON).Thereisnoneed,therefore,to furtheranalyzeSpeedup6. Aftermakingthesesixreplacements,wehavereplacedalmostallthecodeinsidethecontrolloop: Main Fori=0toCyCLen-1 … Next GotoMain
TheonlyremainingMBasiccodeisanoptionalPauseus statementtoprovidespeedcontrol.Whilewecouldreplace theFor…Nextloop,oreventheMain…GoToMainloop,with assemblercode,wewon’t.BykeepingthesecontrolstructuresinMBasic,wepermiteasiercontrolormodification byotherMBasicstatements.We’llseethisconceptinmore detailinProgram19-3. Let’stakealookattheoutputofProgram19-2.Figure19-10 showstheoutputfrombothhardwarePWMmodules.Aswe discussedbefore,theselooklikeanalogwaveformsbecause thedigitalsamplingoscilloscopesamplerateismuchslower thanthePWMrate.Thecosinerampwaveformsareout-ofFigure 19-10: Output of Hardware PWM ModulesCh1:PICC2;Ch2:PICC1. phasebyone-halfwaveform,whichiscorrect. 438
AdvancedStepperMotors Figures19-11through19-15showthehardwarePWMoutputandtheassociatedmotorcurrentunder Program19-2withaddeddelaysof0,500,1000,1500and2000µspermicrostep,respectively.Thecurrent waveformsdepartquitemarkedlyfromtheresistivewaveforms,particularasthestepspeedincreases.These figuresweretakenwith8Vdriveandnoadditionalseriesresistance,andthedeviationiscausedbytherelativelyslowL/Rtimeconstantforthisdrivearrangementcomparedwiththeslewrateoftheappliedaverage motorvoltage.Evenwiththedivergencefromthedesiredcurrentwaveform,themotorfollowsmicrosteps reasonablywell,particularlyatslowerspeed.
Fig 19-11: Ch-19-K.TIF Caption: Output of Program19-2,NoDelay;Ch1:HPWMOutput; Ch2:PF45-48MotorCurrent.
Figure 19-12: Output of Program 19-2, 500 µs Delay; Ch1: HPWM Output; Ch2: PF45-48 MotorCurrent.
Figure 19-13: Output of Program 19-2, 1000 µs Delay; Ch1: HPWM Output; Ch2: PF45-48 MotorCurrent.
Figure 19-14: Output of Program 19-2, 1500 µs Delay; Ch1: HPWM Output; Ch2: PF45-48 MotorCurrent.
439
Chapter19
Figure 19-15: Output of Program 19-2, 2000 µs Delay; Ch1: HPWM Output; Ch2: PF45-48 MotorCurrent.
Program19-3 Program19-3allowsustoseriallycontrolasteppermotorthrougheightcommands: Command U12345 DForDR S MForMH T12345 # ForL Z
Function Setdelaybetweenmotorstepsat12345us SetdirectionForward(DF)orReverse(DR) Statusreportofparameters Setmodetohalf-step(MH)orfullstep(MF) Settargetpositionto12345motorsteps;stop whenreached Execute;startmotorrotating Stopmotor,releasecurrenttofreethemotorshaft (F)orkeepcurrentflowingtolockmotorinplace(L) Zerothemotorposition.Z?reportsthecurrent motorposition.
StatusQuery? U? D? — M? T? — — Z?
WhenreadingProgram19-3,theflowchartsofFigures19-16and19-17mayhelpyouunderstandtheprogramstructure.AswithProgram19-2,itdemonstratestheeasewithwhichMBasicandassemblermaybe mixed,witheachworkingtoitsrespectivestrongpoints. Program19-3isinterruptdriven—weloadthetimebetweenmotorstepsintotimer1andeverytimetimer1 determinestheprogrammedtimehaspassed,itissuesaninterrupt.Theassemblerlanguageinterruptservice routineISRASMisimmediatelyexecutedandadvancesthemotoronestep,ifithasnotpreviouslyreached itstargetposition.Italsoupdatesthelocationcounterandresetstimer1.Theseoperationsaretransparentto anyMBasicstatementthatmightbeexecutingwhentheinterruptserviceroutineiscalled. Program19-3workswithabipolarmotorusingthecircuitofFigure19-3,andwithunipolarmotorsusinganyunipolardrivercircuitsshowninChapter8.However,don’tforgettoconnectthePIC’shardware serialinputandoutputpinstotheRS-232interfaceport.Figure19-18showstheseconnectionsaddedto anSN754410bipolardrivercircuit.Figure19-19showshowyoumayusetheSN754410inpureunipolar mode.Youmayalsousethiscircuitforanyofotherstepperdriverprogramsinthischapter,orthosein Chapter8.
440
AdvancedStepperMotors Figure19-16: OverallFlowchart—Program19-3.
441
Chapter19
Figure19-17:InterruptService RoutineFlowchart—Program19-3.
442
AdvancedStepperMotors
Figure19-18:SN754410 bipolardriveandPIC-to-serial connections.
SinceProgram19-3isquitelengthy,andsincewe’veseenalmostallitsconceptselsewhere,we’llnotprovideaprintedlistinginthetextandwealsodepartfromournormalformofanalysisandwillnotreproduce theprograminsections,followedbyadetailedanalysis,exceptinafewcaseswherejustified.Pleasereferto theCD-ROMelectroniccopyofProgram19-3.
443
Chapter19
Figure19-19:SN754410Configured forunipolardriveandPIC-to-serial communications.
ConstantsandVariables Attheoutset,wedefineallneededvariablesandconstants.CertainvariablesareusedinbothMBasicand assemblerroutines.AsweremindedyouinthecaseofProgram19-2,MBasicisanoptimizingcompilerand avariabledefinedinthenormalwayinMBasicbutusedonlyinanassemblerroutine,willnotbeallocated space.TheClearcommandsetsallMBasicvariablestozeroandensuresthatthecompilerdefinesandallocatesallvariables,evenifusedonlyinanassemblerroutine,suchasSmotorStep. Forconvenience,wedefineconstantsFullStep,HalfStep,FwdandRevsothatcomparisonsmaybewritteninamoremeaningfulfashion.Forexample,thefollowingtwoformsareequal,butoneisclearlymore meaningfultothereader. IfStepMode=0Then… IfStepMode=FullStepThen… Wealsodecidedtodeclarethetwopositionvariables,CurrentPosandTargetastypeword,thuslimiting theirrangeto0…65,535.Forasteppermotorwith400halfstepsperrevolution,usingwordvariablespermitscountingtojustover163revolutions.Definingthesetwovariablesastypelongwouldprovideamuch greatercountingrange,butwouldhavecomplicatedtheassemblerportionsoftheprogramconsiderably.
444
AdvancedStepperMotors Initialization WeuseCleartosetallvariablesto0andensuretheMBasiccompilerallocatesspaceforeachvariable.I’ve settheserialinputspeedat9600b/s.Thisisanarbitrarychoiceandcanbechangedtootherstandardvalues asdesired.SincetheUSARTimplementsabuffer,highdataspeedsarenotbeaproblem.Next,PortB,pins B0…B3aredefinedasoutputsandinitializedlow.PortC,pinC0isalsodefinedasanoutput.IuseC0 tomeasureexecutiontimesbyconnectingittoanoscilloscope.AtthestartofaparticularroutineC0isset high,anddroppedlowattheendoftheroutine,sothepositivepulsewidthmeasuredontheoscilloscope providestheexecutiontimeforthecodebracketedbytheC0high/lowoperations. TheshortassemblyroutineweusetogetthePIC’sclockspeedisinteresting: ASM { movlw(_MHz/.1000000);_MHzisaconstant BankselFosc MovwfFosc&0x7F ;likewiseforcommand Banksel0 ;CompilerexpectsBank0onexit }
InordertocalculatetheTimer1presetvaluetoachieveadefineddelayinmicroseconds,wemustknowthe clockspeed.Beginninginversion5.3.0.0,theclockspeedisdefinedatthetopofanMBasicprogramaspart oftheinitializationstring.ThisinitializationstringisnormallyhiddenbyMBasic’seditor,butmaybeseen byexaminingyour.basfilewithatexteditor,suchasNotepad: ;%CONFIG%16F877A$1312d00$3f3a$0$0$0$0$0$0$0$0 $0$0$0$0$0$0$0$0
I’vehighlightedtheclockvaluebyenclosingitinabox.ThisnumberisthevalueyouenterfromMBasic’s configurationdialogboxastheoscillatorfrequencyinHz.Thisinitializationstringisfromaprogramfora 16F877APIC,witha20MHzclock(20000000Hz).20,000,000inhexadecimalis$1312D00. Whenyourprogramiscompiled,theclockspeedvalueisconvertedintoaconstantappearingintheassemblerfileas: _MHZequ01312D00h
Thefourlinesofassemblercodeabovecopythe_MHZvalueintothebytevariableFosc,accessibletoMBasic.WeusetheassemblertoperformthearithmetictoconvertthefrequencyinHztoMHz,thatis,todivide by1,000,000. Wenowareinapositiontocalculatethenumberofnanosecondspertimer1“tick”—4000/Fosc.Thefactor 4comesaboutbecauseeachtimertickis4oscillatorcycles,whilethefactor1000convertsmicrosecondsto nanoseconds.Wetheninitializetimer1,enableitsinterrupt,butdonotturntimer1on,asitsinterruptsare notyetrequired. ISRASM We’llpostponediscussionoftheinterruptserviceroutineuntillaterinthischapter. WaitforInputStringandCleanUpReceivedData Theprogramassumestheuserwillsendaseriesofcommandstrings,witheachstringterminatedbyacarriagereturnorcarriagereturn/linefeedcombination.(Don’tforgettoconnectthePIC’shardwaretransmit andreceivepinstotheRS-232socketonyour2840DevelopmentBoard.) HSerIn[StrTempStore\ArraySize\$D]
445
Chapter19 Theprogrampausesattheabovestatementandwaitsforacommandstring.Uponreceiptof10characters (recallthatwedefinedArraySizeas10)oruponreceiptofacarriagereturn(Hexvalue$D)thereceived stringisstoredinTempStoreandexecutionpassestothenextprogramstatement. ThelengthofincomingstringiscalculatedandstoredinvariableCtr. ThesubroutineCleanUpiscalledtoremoveanycontrolcharactersthatmighthavebeenincludedintheinputstringandconvertlowercasealphabeticcharacterstouppercasetoremovecasesensitivity.Thecleaned stringiscopiedintoWorkArrayandTempStoreiszeroedoutandisreadyforthenextanalysis. AnalyzeandDispatch Thecleanedupcommandstring,nowcontainedinWorkArray,isanalyzedinsubroutineDispatcher. Thefirstcharacterofthecommandstring,inWorkArray(0)isanalyzedandcontrolispassedtooneofa numberofsubroutinesbaseduponWorkArray(0). Followingisanoverviewofthecommandsequence: Command U12345 DForDR S MForMH T12345 # ForL Z
Function Setdelaybetweenmotorstepsat12345us SetdirectionForward(DF)orReverse(DR) Statusreportofparameters Setmodetohalf-step(MH)orfullstep(MF) Settargetpositionto12345motorsteps;stop whenreached Execute;startmotorrotating Stopmotor,releasecurrent(F)orkeepcurrent flowingtolockmotorinplace(L) Zerothemotorposition.NoteZ?reportsthecurrent motorposition.
StatusQuery? U? D? — M? T? — — Z?
Eachsubroutinelooksattheremainingcharacters(ifany)inWorkArrayandexecutestheappropriatefunctions. ManysubroutinescallthesubroutineConverttogetthenumericvalueassociatedwiththecommandstring. Consider,forexample,thesetdelayfunctionU.AcommandstringbeginningwithUwillbeevaluatedby thesubroutineGetUSec. First,GetUSecchecksWorkArray(1).Ifthischaracterisaquestionmark“?”thecommandstringcallsfor aparameterreport.UsingtheHserOutfunction,GetUSecreportsthecurrentdelayvalue. IfWorkArray(1)isnotaquestionmark,WorkArrayisevaluatedbythesubroutineConvert,whereitis convertedtoaLongvariable,TempLong.IfTempLongexceedsthemaximum16-bitvalue,65535,anerror flagissetandanerrormessagesentbacktotheuser.Iftheconvertedvalueiswithinthepermissiblerange, itisstoredinTempWord. GetUSecthenmustcomputethepropertimer1loadsettingtoyieldthedesiredintervalbetweenmotor
steps.First,arawcountvalueiscomputed,whichisthecountloadvalueassumingthereisnolosttimein resettingthetimeronceaninterruptistriggered.However,sometimeisalwayslostduetotheinterruptcallingprocedureandalsoduetoelapsedtimebetweenstartingtheinterruptserviceroutineandthecodethat actuallyresetsthetimer.Thislosttimeisaconstant(unlesstheearlyportionsoftheISRASMroutineare modified)andisheldintheconstantT1Offset.Toarriveatthefinaltimerpreload,T1Timer,T1Offsetis addedtotherawcountvalue.(Timer1countsup,sobyaddinganoffset,theactualelapsedtimeisreduced, therebymakingupfortimelostincallingoverhead.)IfyourPICdoesnotusea20MHzclock,youmay finditnecessarytochangeT1Offset. 446
AdvancedStepperMotors ISRASMPortionProgramStructure General Aswe’vementionedinChapter15,MBasichandlesthecomplicated“stuff”bothgoingintoandreturning fromanAssemblerInterruptServiceRoutine(ISR).ItsavesthenecessaryinformationintheMBasicstack andrestoresthecontextattheendoftheISR,therebyfreeingtheusertoconcentrateonthefunctionalityof theinterruptcode. VariablesdefinedinMBasicareavailableintheISR,butwithsometwists.MBasicaddsextrabitstoits variableaddresslocationsthatareusedbythecompiler.Whenwearereadingorwritingtheseaddresslocationsinassembler,wetrimtheseextrabitsoff.WealsomustconsiderinwhichbankMBasichasstored eachvariable.Fortunately,thesetasksaresimplerthantheysound. BankSelectionandAddressIssues—Beforereadingorwritingavariablewemustensurethatthecorrect bankselectionbitsareset.InanISR,weareusethepre-definedBankSelassemblermacro.Thus,before wemovedatainoroutofthebytelengthvariableStepModewewillfirstexecutetheBankSelcommand: BankSel
StepMode
Whenmovingormodifyingdatainthevariable,wetrimofftheextracompilercontrolbits: movf
StepMode&0x7F,w
;putStepModeintow
HerewearecopyingthevalueofthevariableStepModeintothe16F876’sworkingregister,W. AttheendoftheISR,wewillexecuteaBankSelcommand,asMBasicexpectsbank0tobeselectedwhen exitingtheISR. Manytimeswewishtoaccessawordvariable.Thisisstraightforward—theloworderbyteisaddressedat thebaseaddress,whilethehighorderbyteisatthebaseaddressplusone.ThisisillustratedbelowindealingwiththewordvariableCurrentPos. BankSelCurrentPos IncfCurrentPos&0x7F,f btfssSTATUS,Z GoToCompareWithTarget BankSelCurrentPos incf(CurrentPos+1)&0x7F,f
ThefirsttwoinstructionsdealwiththelowbyteofCurrentPos;thelasttwoinstructionsdealwiththehigh byteofCurrentPos.ThehighbyteisaddressedasCurrentPos+1.(Rememberthatwearedealinghere withtheaddressofCurrentPos,notitsvalue.Thus,onereadstheinstructionincfastoaddonetothe valuestoredataddressCurrentPos.)SinceMBasic’scompilerwillnotbreakawordvariableacrossbank boundaries,bothCurrentPosandCurrentPos+1areinthesamebankandmaybesetviabankselCurrentPos.(TheGPASMassemblerwillnotacceptBankSel(CurrentPos+1)asalegitimateargument.) ChecktheInterruptType Inadditiontointerruptsgeneratedbytimer1,otherinterruptsmaybetriggered.Inparticular,HSerIn causesaninterruptuponcharacterreceipt.WedonotwishtointerferewithMBasic’shandlingoftheseinterrupts,sothefirstthingwecheckiswhetherthetimer1interruptflag,bittmr1ifofregisterPIR1,isset. Ifitisset,wehaveatimer1interrupt;ifitiscleartheinterruptcamefromanothersourceandprogramflow immediatelyjumpstotheendsothattheinterruptserviceroutineestablishedbytheMBasiccompilermay servicetheinterruptcall.
447
Chapter19 ResetTimer1 Afterclearingthetmr1ifinterruptflag(topreventmultiplecallsofthesameinterrupt)wemustresetthe timer1preload.ThisroutinefollowsMicrochip’srecommendedinstructionsequence,settingthehighbyte first,followedbythelowbyte. CheckModeandOutputBits Next,theISRoutputsthebitpatterntoPortB,pinsB0…B3.Wehavetheoptionofeitherhalfstepsorfull steps.Ittakeseighthalfstepsforacompletepatternrepeat,butonlyfourfullsteps.Ratherthanusetwo differentcounters,onerangingfrom0…3andtheotherfrom0…7,weinsteadjustdouble-upthefull-step patternanduseasingle0…7counterSMotorStep.ThisisthesameapproachdevelopedinChapter8.Note thefullsteprepeat.
SmotorStep 0 1 2 3 4 5 6 7
B0 1 1 0 0 0 0 0 1
HalfStep B1 B2 0 0 1 0 1 0 1 1 0 1 0 1 0 0 0 0
B3 0 0 0 0 0 1 1 1
B0 1 1 0 0 1 1 0 0
FullStep B1 B2 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1
B3 1 0 0 1 1 0 0 1
It’snecessary,ofcourse,tooutputeitherthefullorhalfsteppatterns,dependinguponthestatusofstep modevariable,StepMode.Weaccomplishthisbyusingeitherafull-step(GetFullPattern)orhalfstepsubroutine(GetHalfPattern),asappropriate.Thesubroutinejumpstotheaddressrepresentedby SmotorStepplustheentrypoint,implementedbytheaddwfPCL,finstruction.Theretlw0xnncommandthenreturnstheliteralvaluennintheWregister.TheWregistertheniscopiedtoPortB. Sincethepatternsubroutinesimmediatelyfollowtheircallingcommand,andthisisashortassembler program,weneednotworryaboutpageboundariesinthesubroutinecall.Cautionshouldbeexercisedin general,ofcourse,toensurethatpageboundariesarenotinadvertentlycrossedwithoutproperconsideration.(CompareourjumptablecallingprocedureinProgram19-2whichdoesconsiderpageboundariesand theoneweusehere,whichdoesnot.) DetermineDirectionandUpdateSmotorStep WeuseSmotorStepastheindexintoeitherthehalf-steporfull-steppatterns.SmotorStepmustrunfrom0…7. Ifwearemovingintheforwarddirection,weincrementSmotorStep,sotheindexruns0,1,…7.Ifweare movinginthereversedirection,wedecrementSmotorStep,sotheindexruns7,6,…0. WeaccomplishthisbyasimplecheckofthedirectionvariableDirection,anduseeitheranincrement (incf)oradecrement(decf)instructiononSMotorStep,asappropriate. FollowingincrementingordecrementingSmotorStep,wemustensureitdoesnotgooutsidetherange 0…7.Since0…7representstherangeofthelastthelastthreebitsofthebytevariable,wecansimplymask offthehigher5bitswiththeAND0x7command.Thisgivesathree-bitcounterthatisforcedtorangebetween0and7.
448
AdvancedStepperMotors CountCompletedSteps Wealsodesiretokeeptrackofhowmanystepinstructionshavebeenexecuted,sotheymaybecompared againstthetargetposition.CompletedinstructionsarestoredinCurrentPos,awordvariable. BecauseCurrentPosisawordvariable,wecannotuseonesimpleincfinstructiontocount.Rather,we dealseparatelywiththelowandhighorderbytesthatcompriseCurrentPos. First,weincrementtheloworderbyteandcheckitforzero.Ifitiszero,wehavecountedpast255and thereforemustrolloveronecounttothehighorderbyte. CheckAgainstTarget Finally,wemustcheckthecurrentmotorpositionagainstthetargetposition.Ifthematch,wewillturnoff timer1andstopthemotor. InMBasicthiswouldbeasimpleIFCurrentPos=TargetThenStopMotorstatement.Assembler requiresustogetabitclosertothenutsandboltsofthesetwovariables,however. Thecomparisonfollowsthealgorithmofreference[19-2]fora16-bitcomparison—comparethehighorder bytes;iftheyareequal,comparetheloworderbytes.Ifboththehighandloworderbytesareequal,thetwo 16-bitvariablesareequal. Finally,ifCurrentPosisidenticalwithTarget,thenwecleartheTmr1Onbit,therebydisablingTimer1 andstoppingthemotor. CommandStructure Commandsarecaseinsensitive—thatis,uisthesameasU.Whereanumericcommandistobesentupto 5digitsmaybeused.Donotaddcommas.Afterenteringacommand,theresponsewillbethestringsent backOK. Command Type Motor Speed
Specific Command U?
Unnnnn
Description Reportthecurrentintervalinmicrosecondsbetweenmotorsteps.Responsewillbe: Delay12345 Where12345willbereplacedbytheactualdelayinmicroseconds Settheintervalbetweenpulses.Nnnnnisinmicroseconds.Themaximumintervalis dependentupontheclockspeedofthePIC.Fora20MHzclock,themaximuminterval is13,100µs(13.1ms). Theminimumclockintervalisalsodependentupontheclockspeed,butforalmostany steppermotor,thelimitingfactorwillbethesteppermotoritself.(Sinceweareentering thetimebetweenpulses,theshorterthetime,thefasterthemotorwillstep.) TocalculatetherequiredpulseintervalforadesiredmotorRPM,usethefollowing formula:
u=
1, 000, 000 N × RPM 60
where: uistheintervalinmicroseconds RPMisthedesiredrevolutionsperminute Nisthenumberofstepsperrevolution,forthesteppingmodeinwhichthemotor willbeoperated.Half-stepoperationdoublesthenumberofstepsperrevolution,for example,infullstepmodeforaparticularmotor,N=48,butinhalf-stepmodeN=96.
449
Chapter19 Command Type
Specific Command
Description Example: RPM=60 N=48(fullstep)/96(halfstep).Wewilloperateinhalfstepmode.
u=
1, 000, 000 1, 000, 000 = = 10417 96 × 60 96 60
Tosetthisspeedandmode,thefollowingcommandswouldbeused: MH (settohalf-stepmode) U10417 (setsstepintervalat10417uSeconds) Motor Direction
D?
DF DR
Status
S
Reportthecurrentmotordirection.Responsewillbeeither: Forward Reverse Notethatthedirectionsforwardandreversearearbitraryanddependuponthemotor connections. SetthemotortoDirectionForward SetthemotortoDirectionReverse YouwillreceiveanOKresponseafterasuccessfulDF/DRcommand. Outputsastatusreportofvariousparameters: VariableDump Foscnn DelaynnnnnuSec TimerStatusnT1Timer“nnnnn CurPosnnnnnn TargetPosnnnnnn FoscistheoscillatorfrequencyinMHzassetintheMHZ=line Delayisthetimeintervalinmicrosecondsbetweenmotorsteps TimerStatusis0or1,0=offand1=on. T1TimeristhenumericvalueoftheTimer1countload CurPosnisthenumberofmotorstepsexecuted Targetisthenumberofmotorstepstobeexecutedtocauseamotorstop HalfSteporFullStepindicatesthecurrentmode ForwardorReverseindicatesthecurrentdirection.
StepMode
M?
NotethatCurPosnisasofthetimethedataissentbackandthatthemotorwill continuetostep. Reportthecurrentstepmode.Responsewillbeeither: HalfStep FullStep
MH MF
SetModetoHalfStep SetModetoFullStep YouwillreceiveanOKresponseafterasuccessfulMH/MFcommand.
450
AdvancedStepperMotors Command Type SetTarget Position
Specific Command T?
Description Reportonthecurrenttargetposition.Theresponseis:
Tnnnnn
TargetPosnnnnnn
nnnnnwillbethetargetstepcount. SettheTargetposition.Whenthennnnnmotorpulseshavebeengenerated,the motorstops.nnnnnisinunitsofmotorsteps.If,forexample,themotorhas98steps/ revolutionand10completerevolutionsaredesired,thecommandwouldbe:
T980
NotethatthemotorwillnotstartsteppinguntilanExecutecommandhasbeen received. TargetisanunsignedWord,sothemaximumvalueis65536. Targetisanrelativevalue,i.e.,itwillexecuteanadditionalTargetstepsbasedupon thecurrentpositionatthetimetheTargetcommandisreceived.Ifabsolutepositionis required,i.e.,fromsomefixedzero,theuserisresponsibleforkeepingtrackofabsolute positionsandtranslatingthemtorelativeTargetvalues. Basedupontheenteredparameters,startthemotorrunning.
Execute (Start Rotation)
#
Stop
F
Stopsthemotorandde-energizesthemotorwindings,sothemotorshaftisFree.
L
Stopsthemotorwiththelaststeppingpatterninplace,sothemotorwindingsare energizedandthemotorshaftisLocked.
Notethatonlyminimalerrorcheckinghasbeenimplementedinthesamplesoftware,so theuserisresponsibleforensuringthatreasonableparametershavebeenentered. YouwillreceiveanOKresponseafterasuccessful#command.
TheFandLcommandsretaintheCurrentPosition.Hencea#willresumefromthe currentposition.IftheuserdesirestoresettheCurrentPosition,azero(Z)command maybeissued. Zero (Zero Current Motor Position andReport Positon)
Z?
YouwillreceiveanOKresponseafterasuccessfulStopcommand. Reportsthecurrentmotorpositionincompletedsteps:
CurPosnnnnnn
Wherennnniscompletedmotorsteps.Ifthemotorisrunning,thereportedpositionwill varysomewhatfromtheactualpositionatthetimethestringisreceivedduetointernal programandserialtransmissiontimelags. Z
SetsthecurrentmotorpositiontoZero. Whileitispossibletozerothemotorpositionwhilethemotorisrunning,theuser shouldrememberthattherewillbeatimelagbetweensendingthemotorcommand andtheinternalexecutionofthezeroing.Inmostcases,youwillwishtostopthemotor beforesendingazerocommand. YouwillreceiveanOKresponseafterasuccessfulZcommand.
451
Chapter19 IdeasforChangestoProgramsandCircuits • • •
MergetheconceptsinPrograms19-2and19-3,alongwiththeworkofChapter8togivetheuserthe optionoffourmodes:fullstep,halfstep,waveandmicrostep. ModifyProgram19-2toallowtheusertoselectdifferentsizemicrosteps,suchas4,8,16or32microstepsperfullstep.Thiswillinvolverewritingsomeoftheassemblycodetoreplaceconstantswith variables. ModifyProgram19-2toincreaseuserinteraction,notnecessarilytotheextentofProgram19-3,but beyondenteringhardcodedvaluesatprogramtime.Whichparametersshouldbeusersettable?Howdo youprocessuserinputs(mostofthetimeforwhichisspentwaitingforkeystrokes)withoutbeingtoo muchofaprocessingtimeburdeninthetime-sensitivemainprogramloop?
References [19-1]
Condit,Reston,StepperMotorControlUsingthePIC16F684,AN906,MicrochipTechnology,Inc., Doc.No.DS00906A(2004). [19-2] Predko,Myke,ProgrammingandCustomizingPICmicroMicrocontrollers,McGraw-Hill/TAB Electronics;2ndedition(December,2000). [19-3] Predko,Myke,PICmicroMicrocontrollerPocketReference,McGraw-Hill/TABElectronics, Pocketedition(November2000). [19-4] TexasInstruments,SN754410QuadrupleHalf-HDriverDatasheet,Doc.No.SLRS007B,(Nov.1995).
452
CHAPTER
20
X-10HomeAutomation Inthelate1970’s,asmallScottishcompany,PicoElectronics,joinedwithBSR,famedforitshighfidelity turntables,toproduceinexpensivehomeautomationequipment.PicoElectronics’deceptivelysimpleidea wastouseahome’spowerwiringtocommunicatefromacontrollertosmallremotecontrolmodules.The resultwastheBSRSystemX10,originallysoldatRadioShackandSears.BSRisnolongerinbusiness,but itsX-10businessiscarriedonbyX10USA.(TheCompany’snameis“X10”butthetechnologyisidentifiedas“X-10.”)ManymanufacturershavelicensedX-10technology,andawidevarietyofremoteswitches, dimmersandotherdevicesareavailable. MBasic’sXinandXoutfunctionsprovidebuilt-insupportforbothtransmittingandreceivingX-10signals. ThischapteralsocoversnontraditionaluseofX-10technology,suchastelemeteringtemperaturereadings.
HowX-10Works Introduction ThetechnologybehindX-10istosendbriefburstsof120KHzsignalsoverthepowerlines,timingthe burststocoincidewiththe60Hzpowerlinezero-voltagecrossings.Atthezerovoltagepointthepowerline noiselevelisataminimumandthe120KHzsignalhasthebestchancetobereceivedbyaremotecontrol module.We’llgothroughX-10’sprotocolbystartingatthetopandworkingdowntothebitlevel. Atthehighestlevel,X-10messagesarecomprisedofthreeelements: HouseCode
UnitCode
FunctionCode
Let’slookateachelementinmoredetail. HouseCode—Thereare16possiblehousecodes,conventionallyidentifiedasA…P. ForconveniencewhenusingXinandXout,MBasicprovideslibraryconstantsof theformX_A…X_P. UnitCode—Thereare16possibleunitcodes,conventionallyidentifiedas1…16.For conveniencewhenusingXinandXout,MBasicprovideslibraryconstantsofthe formX_1…X_16. FunctionCode—Thereare16possiblefunctioncodes,identifiedbytheiroperations, suchas“On,”“Off”and“Dim.”ForconveniencewhenusingXinandXout,MBasicprovideslibraryconstantsoftheformX_On,X_OffandX_Dim,etc. Controlledmodulesareaddressedbybothhouseandunitcodes.Figure20-1showsthe settingswitchforatypicalX-10controlmodule.Byrotatingtheswitches,themodule’s addressissettothedesiredhouseandunitcodes.Figure20-1showsanaddressset Figure 20-1: House to“B-8,”whichmeansthatitwillonlyrespondtofunctioncodesprefixedwithhouse andunitcodesetting codeB,unitcode8.(Somemodulesaredesignedtoalsoaccept“allcall”signals, switches,
453
Chapter20 whereonlythehousecodemustmatchthemodulesetting.Inthiscasetheinstruction“BOff”wouldturn offallmodulessettohousecodeB,regardlessoftheunitcodesetting.)ThemoduleshowninFigure20-1 willturnoffuponreceiptofthecodesequencecorrespondingto“B8OFF”andwillignorethecodesequences“C8OFF”and“B7OFF.” Sincethereare16housecodesand16unitcodes,wehaveamaximumof256possibleuniqueaddresses. Modulesrecognizeonlycertainfunctioncodesassociatedwiththeirpurpose.Forexample,the“appliance control”moduleislimitedtoturningloadsonandoff;itaccordinglyrecognizesonlyonandofffunction commands.Inadditiontooffandon,alightdimmermodulealsorecognizesthedimandbrightcommands. TheremainderofthissectiondelvesintotheTW523transceiverandthedetailsofX-10transmission.You maytreattheTW523asablackboxandskipovertheX-10theory,shouldyouprefer.
TW523X-10Transceiver MBasic’sXinandXoutfunctionsassumethePICisconnectedtoanX-10transmitter,or,inthecaseof Xin,anX-10transceiver.We’lluseaTW523transceiverforthischapter’sprograms.Ifyouareinterested inonlytransmittingX-10commands,thetransmit-onlyPL513deviceisslightlycheaper.Irecentlypaid$24 foraTW523,whileaPL513cost$16fromthesamesupplier.And,althoughthedeviceIboughtwassoldas a“TW523,”itturnedouttocarrythepartnumberPSC05.Regardlessofthenumber,theX-10ProPSC05 Ipurchasedispin-compatiblewithaTW523.WhenIrefertotheX-10transceiver,I’llcallitaTW523,but notallmanufacturersusethispartnumbertoidentifytheirX-10transceivermodule. Let’stakeaquicklookatwhat’sinsideaTW523.Figures20-2and20-3showbothaTW523andaPAM02 on/offappliancecontrolmodule.TheTW523isattheleftinbothphotosandmaybeidentifiedbytheRJ11 4-pinmodularconnector.Figure20-4providesasimplifiedblockdiagramoftheTW523.(Reference[20-1] includesacomponent-levelschematicforboththeTW523andPL513devices.) Figure20-4:Blockdiagram ofTW523X-10controlmodule.
Figures20-2:TW523X-10transceiver andPAM02appliancecontrolmodule, frontview.
Figure20-3:TW523X-10transceiver andPAM02appliancecontrolmodule, backview.
454
X-10HomeAutomation TheTW523usesopto-couplerstoisolateitsinputandoutputcircuitsfromthe120Vpowerline.However,the TW523’sinternalcircuitryisnotisolatedfromthe120Vpowerlineandyoushouldnotsuccumbtothetemptationtodisassemblethedeviceandstartprobingaroundwithyouroscilloscope.We’veseenopto-couplersin Chapters3and4.Ifyouneedarefresheronhowanopto-couplerworks,takeamomentandreadChapters3and4. We’llgointothepurposeofeachoftheTW523’sthreeinput/outputlineslaterinthischapterwhentakea detaillookatXinandXout.Fornow,we’llcontentourselvesbynotingthatithasazero-crossingdetectorthattogglesbetweenlogic1andlogic0wheneverthe120Vlinechangessign;atransmitinputlinefor sendingdataandareceiveoutputlineforincomingdata.
TheX-10Protocol Continuinginthetop-downdirection,let’slookatthebitleveldataflowintheX-10protocol.Abinary1is representedasa1msdurationburstof120KHzsignal,whileabinary0isrepresentedasanabsenceof120 KHzsignal.Eachburst(orabsenceofburst)occurswithin200µsfollowinga60Hzzerocrossing.Figure 20-5showsasinglelogic1burst.Therearethree1msbursts,separatedby2.78msbecauseinathree-phase powersystemtherearethreezerocrossings,eachseparatedfromtheotherby60ºcorrespondingto2.78ms ina60Hzsystem.Figure20-6showstherelationshipbetweenzerocrossingsinthree-phasepower.You’re probablythinking“threephasepower?Idon’thavethreephasepowerinmyhouse.”And,youarecorrect. However,X-10’sdesignerswantedtheirproducttoincludeindustrialandcommercialusers,wherethreephasepoweristhenorm.And,insomeEuropeancountriesthreephaseresidentialserviceiscommon.
Figure20-5:Logic1bursts.
Figure20-7:Transmittinga120KHzburst.
Figure 20-6: Zero crossings in three-phase powersystem.
Next,youmaybethinking,“evenifIhadthreephase power,whytransmitatallthreezerocrossings?”The answeristhattheX-10transmitterandreceivermay notbepoweredfromthesamephase.Bytransmitting theburstonceforeachpossiblezerocrossing,theprotocolensuresthatthereceivingdeviceisguaranteedto receiveasignalatitszerocrossing,regardlessofwhen thetransmitter’szerocrossingoccurs.And,atthelocal receiver’szerocrossing,theinterferenceandnoise onthepowerlinewillbeataminimum.Figure20-7 providesaconceptualviewofhowthe120KHztone burstappearswhentransmittedovera60Hzpower 455
Chapter20 line.Thepowerlinehasthesumofthe60Hzpowerandthesuperimposed120KHztonebursts.Forclarity, I’veshownthe120KHzburstsasabout20Vpeak-to-peak,buttheactual120KHzsignallevelfoundonthe powerlineismuchless,typicallyafewhundredmillivolts. TheTW523automaticallymanagesreceivingmultipleburstsandreturnsonepulse—coincidingwiththe localzerocrossing—foreachreceivedbursttriplet.WhentransmittingthroughtheTW523,MBasic’sXout functionincorporatestimingandmultiburstrequirementswithoutadditionalintervention.Hence,wewon’t furtherconcernourselveswiththefactthattheX-10standardcallsforburststobesentintriplets. Let’slookathowX-10commandsaresent.(Thecomplementofabitisshownbyanoverscore.Transmitted bitsareshowninitalics.)We’llsendthehousecodeA,followedbytheunitcode2. HouseCode StartCode 1 1
1 1 0 1 1 0 SC=1110
H1 1
H1 0 0
H2 1
H2 0
H4 1
Data H4 0
H8 0
1 1 HouseCode=“A”(0110)
H8 1
D1 1
0
D1
D2 1
1
D2 1
D4 1
D4
D8 0
D8
D16 0
1 0 UnitCode=2(11100)
D16 0
X-10dataissentinthreeconsecutiveblocks;eachblockcomprisinga4-bitstartblock,an8-bithouseblock anda10-bitdatablock.(Thestartcodeisalways1110.)Exceptforthestartbits,eachbitissenttwiceconsecutively,firstinitsnormalortrueform,followedimmediatelybyitscomplement,orinvertedform.Abinary1 isthussentas10andabinary0issentas01.Thisdoublesthetransmissionlengthofthehousecodeandunit codes,but,aswe’llseeinProgram20-7,permitsustodetecttransmissionerrors.Forfurtherinsuranceagainst receivingfalsedata,thetransmissionisrepeatedafteranidletimeofthreepowerlinecycles. Therearetwoimportantpointsthatyoushouldseeinthistable;first,thebitsaresentinLSB-firstorder, andsecond,thetransmissionprotocoldoesn’tfollowthehousecode/unitcode/functioncodeformatwe discussedearlier. Sinceit’stheeasier,let’sdealwiththesecondpointfirst.Althoughwestructureourtransmissioninahouse code/unitcode/functioncodesequence,whatareactuallysentarehousecode/unitcodefollowedby asecondtransmissionofhousecode/functioncode.Todescribethissequencebetter,theX-10literature definesthetransmissionsequenceashousecode/data,wheredatarepresentseitherunitorfunctioncodes. Thereceivingdeviceisresponsibleforassociatingthethreeelementsintotheorderhousecode/unitcode/ functioncode.Arelatedpointmaystrikeyouaswell;ifunitandfunctioncodesrangeonlyfrom1…16,why usefivebitswhenfourissufficient?TheansweristhatX-10literatureconsidersunitandfunctioncodesas asinglegroupoffive-bitbinarydatavalues,runningfrom0…31,withvaluesfrom0…15beingunitcodes andvaluesfrom16…31beingfunctioncodes.We’lllookatthisinmoredetailwhenweconsiderthetransmittedbitorder. Thus,acompletetransmissionofahousecode/unitcode/functioncoderequirestheTW523tosendthe followingsequence: SC
Block1 HC
UC
IDL
RepeatBlock1 SC HC UC
IDL
SC=StartCode HC=HouseCode UC=UnitCode FC=FunctionCode IDL=IdleTime
456
SC
Block2 HC
FC
IDL
RepeatBlock2 SC HC FC
X-10HomeAutomation Fortunately,theTW523andMBasic’sXinandXoutfunctionscooperatetohidethiscomplexityfromus. Let’snowlookatthesecondcuriosity;bitorder.Byconvention,Microchip’sdocumentation(andvirtually alloftherestofthemicrocontrollerandmicrocomputerindustry)showsbinaryvaluesmostsignificantbit first.(Thisistheway,ofcourse,wenormallywritenumber,e.g.,1234isinmostsignificantdigitfirstorder.) Thus,thebinaryrepresentationofdecimal1is%00000001.If,ontheotherhand,wedecidedtodisplay bitsstartingwiththeleastsignificantbitfirst,%00000001representsdecimal128,not1.Whentransmitting abyteserially,there’snothingthatmakessendingitLSBfirstorMSBfirstpreferable.Infact,thePCserial interfacesendsbitsLSBfirst.Whatisimportantisconsistency;nothingbuttroublewillensueifwetransmit bitsLSBfirst,butthereceivingprograminterpretsthereceiveddataasbeingMSBfirstorviceversa.Inthe caseofserialtransmissiontoorfromaPCtoaPIC,boththetransmittingandreceivingendsunderstandthe dataissentLSBfirst,sothereisnoconfusion. AslongasyousticktoMBasic’slibraryconstantsforhouse,unitandfunctioncodes,youneednotconcern yourselfwithbitorderandvalues.ThelibraryconstantX_A,forexample,producesthecorrectbitsequence forhousecode“A”whenusedasanargumentinXinorXout.However,whenreading“official”X-10documents,youshouldnotethatbinaryvaluesarepresentedinLSBfirstorder.Thefollowingtablecross-references MBasic’slibraryconstantswiththenamesandbitsequencesfollowedinX-10documents. X-10Documentation TW-523 TW523LSBValue firstOrder (Decimal)
Library Constant Name
HouseCode A
0110
MBasic Library Constant Value Decimal
Hex
6
X_A
6
6
B
1110
7
X_B
14
E
C
0010
4
X_C
2
2
D
1010
5
X_D
10
A
E
0001
8
X_E
1
1
F
1001
9
X_F
9
9
G
0101
10
X_G
5
5
H
1101
11
X_H
13
D
I
0111
14
X_I
7
7
J
1111
15
X_J
15
F
K
0011
12
X_K
3
3
L
1011
13
X_L
11
B
M
0000
0
X_M
0
0
N
1000
1
X_N
8
8
O
0100
2
X_O
4
4
P
1100
3
X_P
12
C
457
Chapter20 X-10Documentation Library Constant Name
TW523LSB-firstOrder
MBasic Library Constant Value
UnitCode/ FunctionName
D1
D2
D4
D8
D16
Decimal Value
1
0
1
1
0
0
6
X_1
12
C
2
1
1
1
0
0
7
X_2
28
1C
3
0
0
1
0
0
4
X_3
4
4
4
1
0
1
0
0
5
X_4
20
14
5
0
0
0
1
0
8
X_5
2
2
6
1
0
0
1
0
9
X_6
18
12
7
0
1
0
1
0
10
X_7
10
A
8
1
1
0
1
0
11
X_8
26
1A
9
0
1
1
1
0
14
X_9
14
E
10
1
1
1
1
0
15
X_10
30
1E
11
0
0
1
1
0
12
X_11
6
6
12
1
0
1
1
0
13
X_12
22
16
13
0
0
0
0
0
0
X_13
0
0
14
1
0
0
0
0
1
X_14
16
10
15
0
1
0
0
0
2
X_15
8
8 18
Decimal
Hex
16
1
1
0
0
0
3
X_16
24
AllUnitsOff
0
0
0
0
1
16
X_Units_On*
1
1
AllLightsOn
0
0
0
1
1
24
X_Lights_On
3
3
On
0
0
1
0
1
20
X_On
5
5
Off
0
0
1
1
1
28
X_Off
7
7
Dim
0
1
0
0
1
18
X_Dim
9
9
Bright
0
1
0
1
1
26
X_Bright
11
B D
AllLightsOff
0
1
1
0
1
22
X_Lights_Off
13
ExtendedCode
0
1
1
1
1
30
X_Hail
15
F
HailRequest
1
0
0
0
1
17
N/A
17
11 13
HailAcknowledge
1
0
0
1
1
25
N/A
19
ExtendedData(Analog)
1
1
0
0
1
19
N/A
25
19
Status=on
1
1
0
1
1
27
X_Status_On
27
1B 1D
Status=off
1
1
1
0
1
23
X_Status_Off
29
StatusRequest
1
1
1
1
1
31
X_Status_Request
31
1F
Pre-SetDim0
1
0
1
0
1
21
N/A
21
15
Pre-SetDim1
1
0
1
1
1
29
N/A
23
17
*Thisconstantappearstobemis-namedinMBasic,asthefunctionisidentifiedinX-10literatureas“off”not“on.”
X-10’sdesignersworkedwithLSB-firstbitorderwhenpreparingtheencodingscheme,asisapparentfrom thefactthatthedatacodesseparatenicelyinto0…15(unitcodes)and16…31(functioncode)groups.When thesebinaryvaluesarereversed,thiscleangroupingisbroken. TheXinandXoutsectionsoftheMBasicUser’sGuideprovidebinaryequivalentsforthecompilerlibrary functionandunitconstants.Thesebinaryequivalentsare,however,inerror,anddonotcorrespondtothe 458
X-10HomeAutomation actualbinaryvaluesofthenamedconstants.Instead,thebinaryinformationpresentedconsistsofthebinary equivalent(MSBfirstorder)oftheTW523numericalvalues.IfthesebinaryvaluesareusedinXinorXout insteadofthelibraryconstantnames,incorrectcodeswillbesent. Toclarifythisexplanation,let’slookatX_1:
Unit Constant X_1
MBasicUser’sGuide Valueof ActualValue Binary ofX_1 Constant Constant Constantas (MSBfirst; inMBasic Statedin Decimal Library User’sGuide Value) (Decimal) %00110 6 12
X-10Documentation
Binary Representation of12(Decimal) %01100
TW523 Value (Decimal)of Unit1Code 6
TW523 Representation ofUnit1Code (LSBFirst) 01100
Forexample,tosendthecodeforUnit1,thebitsmustbesentinthefollowingorder0-1-1-0-0.Ifthesebits areheldinaMBasicbytevariableandaresentleft-to-right,theMBasicbytevaluemustbedecimal12($C). Infact,thevalueoftheconstantX_1is$Cordecimal12.However,thebitvalueshownintheUser’sGuide is%00110.Thiscorrespondstodecimal6($6),nottheactualvalueofX_1.Thisisadocumentationerror, andthenamedconstantsworkcorrectlywhenusedwithMBasic’sXinandXoutfunctions.
Programs Let’snowlookatsomecodeimplementingwhatwe’velearnedaboutX-10.ConnectyourTW523asshown inFigure20-8.AnoscilloscopeconnectedtoRB0willdisplaythezerocrossingoutputwaveform,asshown inFigure20-9.
Figure20-8:Configurationforprogram20-1.
Figure20-9:ZeroCrossingWaveform;Ch1:Pin B0;Ch2:NotUsed.
ToverifyProgram20-1’sfunctionality,IusedtwoX-10PromodelPAM02appliancemodules,settocodes K8andJ8.IpluggedbothappliancemodulesintothesamepowerdistributionstripastheTW523module. Anappliancemoduleimplementsonlyon/offfunctionality,andinthecaseofthePAM02modules,the switchingelementisamechanicalrelay. Program20-1commandstheappliancemodulestoturnon,and,afterabriefpause,toturnoff.Ittestsboth house/unit/functionaddressingandhouse/function“allcall”modes. Program20-1 ;Program20-01.Verifytransmit ;andcontrolwithminimalprogram ;Constants
459
Chapter20 ;-----------DataOutPin DataInPin ZeroXPin
Con Con Con
B2 B1 B0
;TW523-4datafromPIC ;TW523-3dataintoPIC ;TW523-1zerocrossing ;TW523-2goestoVSS
HouseCode1 HouseCode2 UnitCode
Con Con Con
X_K X_J X_8
;testtwohousecodes ;thesearearbitrary ;selected
Main ;ByomittingtheUnitCodewecontrolall ;unitswiththesameHouseCode XOutDataOutPin\ZeroXPin,HouseCode1,[X_On] Pause1000 XOutDataOutPin\ZeroXPin,HouseCode1,[X_Off] Pause1000 ;AddtheUnitCodetoaddressspecificcontroller XOutDataOutPin\ZeroXPin,HouseCode1,[UnitCode,X_On] Pause1000 XOutDataOutPin\ZeroXPin,HouseCode1,[UnitCode,X_Off] Pause1000 XOutDataOutPin\ZeroXPin,HouseCode2,[X_On];X_On Pause1000 XOutDataOutPin\ZeroXPin,HouseCode2,[X_Off];X_Off Pause1000 ;AddtheUnitCodetoaddressspecificcontroller XOutDataOutPin\ZeroXPin,HouseCode2,[UnitCode,X_On] Pause1000 XOutDataOutPin\ZeroXPin,HouseCode2,[UnitCode,X_Off] Pause1000 GoToMain End
Asusual,westartbydefiningconstants. ;Constants ;-----------DataOutPin DataInPin ZeroXPin HouseCode1 HouseCode2 UnitCode
Con Con Con Con Con Con
B2 B1 B0 X_K X_J X_8
;TW523-4datafromPIC ;TW523-3dataintoPIC ;TW523-1zerocrossing ;TW523-2goestoVSS ;testtwohousecodes ;thesearearbitrary ;selected
Inthiscase,wedefineallthreeTW523connections,eventhoughProgram20-1doesn’tusethedatapin. I’vearbitrarilysetthetwoappliancemodulesatcodesK8andJ8,anddefinedthreecorrespondingconstants, HouseCode1,HouseCode2andUnitCode. Althoughitreceivesfrequentmentionearlierinthischapter,thisisourfirstofficialintroductiontoMBasic’s functionXout.Let’sseehowweuseXouttotransmitX-10codes.
XoutDataPin\ZeroPin,House,[{Unit},{Modifiers},KeyCode]
DataPin—isaconstantorvariableidentifyingthedataoutputpin.ThispinconnectstotheTW523’spin 4.Nopull-upresistorisrequired.AsseeninFigure20-4,theTW523’stransmitdatalineisconnected totheLEDsectionofanopto-isolator.InFigure20-4andelsewhereinthischapter,I’veshownthe PIC’sdatapindrivingtheLEDwithoutacurrentlimitingseriesresistor.Thisisacceptableforbrief experiments;butforpermanentconstructionIrecommendaseriesresistorof100to220ohmstolimit theLED’sdrivecurrent.TheTW523datasheet[20-1]sampleinterfacecircuitshows100ohmsseries resistanceandshouldbeconsultedformoredetaileddesignrecommendations. 460
X-10HomeAutomation ZeroPin—isaconstantorvariableidentifyingthezerocrossinginputpin.ThispinconnectstotheTW523’s pin1.Don’tforgetthispinrequiresapull-upresistor.Figure20-8showsa5.1K,butanyvalueinthe range3.3Kthrough10Kisacceptable. House—isaconstantorvariableholdingthehousecode.Thehousecodemustbeintherange0…15.MBasichasdefinedlibraryconstantsX_A…X_Pthatprovidetheproperhousecodevaluecorrespondingto housecodesA…P. Unit—isaconstantorvariableholdingtheunitcode.MBasichasdefinedlibraryconstantsX_1…X_16that providetheproperunitcodevaluescorrespondingtounitcodes1…16. KeyCode—isaconstantorvariableholdingthekeycode.MBasichasdefinedlibraryconstantsforcertain keycodes,suchasX_OnandX_Off.Forkeycodeswithoutalibraryconstant,valuesprovidedearlierin thischaptermaybeused. Xoutwithbothaunitcodeandkeycodeargumentsendsthesequence<start> followedby<start>>.(Forsimplicity,I’momittingthefact,aswelearned earlier,thateachsequenceissenttwice.)Iftheunitcodeargumentisomitted,thetransmittedsequence is<start>.Inotherwords,Xoutsendsthesequence<start><argumentN>forallarguments1…Nwithinthesquarebrackets. Main
;ByomittingtheUnitCodewecontrolall ;unitswiththesameHouseCode XOutDataOutPin\ZeroXPin,HouseCode1,[X_On] Pause1000 XOutDataOutPin\ZeroXPin,HouseCode1,<X_Off] Pause1000
ThefirstcalltoXoutsendsthe“allcall”version,whichcausesallreceiverswithhousecodesequalto HouseCode1toswitchto“on”mode.Aftera1secondpause,werepeattheallcalltransmission,butthis timewithan“off”command.
;AddtheUnitCodetoaddressspecificcontroller XOutDataOutPin\ZeroXPin,HouseCode1,
Next,werepeattheon/offsequence,butwithbothahousecodeandaunitcodeaddress. XOutDataOutPin\ZeroXPin,HouseCode2,<X_On];X_On Pause1000 XOutDataOutPin\ZeroXPin,HouseCode2,<X_Off];X_Off Pause1000 ;AddtheUnitCodetoaddressspecificcontroller XOutDataOutPin\ZeroXPin,HouseCode2,
Wethenrepeatthissequence,butforthesecondappliancemodule.(Yourmodulemayormaynotrespond toan“allcall”sequence.MyPAM02modulesdonotrecognize“allcall”commands.) Let’slookatthePIC’sdataoutputpinwhilesendingcommands.Figure20-10showspartofanoutput sequence.AlogichighonChannel2representsanX-10logichigh.Aswelearnedearlier,eachhighissent threetimes,atintervalsrepresenting60degreesphaseat60Hz.Figure20-11expandsoneoutputtripletto showhowtheburststructurefitsthe60Hzzerocrossings. I’vecaptionedthelogiclevelsinFigure20-12.Let’sseeifwecandeterminewhattheseparticularbitsmean. ThevisiblepartofthedatastreaminFigure20-12is010010110101.WeknowtheX-10protocolrequirebit pairsofeither10or01(exceptforthestartsignal)tobetransmitted.Hence,theonlypermissiblepatternsof 461
Chapter20
Figure20-10:XoutOutputCh1:ZeroCrossing Reference;Ch2:DataOutput.
Figure 20-11: Expanded View of Data Output Ch1: Zero Crossing Reference; Ch2: Data Output.
Figure20-12:CaptionedXoutOutputCh1:Zero CrossingReference;Ch2:DataOutput, Figure20-13:CircuitforProgram20-2.
11or00mustoccuraspartsof0110oradjacent1001patterns.Theonlypossiblebitpatternsequencethat meetsthisrequirementis010010110101.Wecanaddthemissingelementsatthetwoedgesandconcludetheactualsequenceis10100101101010.Or,droppingtheredundantcomplementbits,thesentbits thatgeneratedthisoscilloscopewaveformare1100111. Program20-2 Next,let’scyclethroughallthepossibletransmitcodes.Thisletsustestthefalsecoderejectionabilityof anX-10module.(IranProgram20-2fortwodaysandobservednofalsetriggers.)And,moreimportantly, Program20-2servesasatesttransmitterwhenwedevelopreceivingprograms20-3and20-7. Figure20-13showstheconnectionarrangement.We’veaddedanLEDtoshowprogressandajumperbetweenthePIC’shardwareserialoutputportandthe2840DevelopmentBoard’sRS-232socket. ;Program20-02.Verifytransmit ;andcontrolwithminimalprogram ;Constants ;------------
462
X-10HomeAutomation DataOutPin DataInPin ZeroXPin LEDPin
Con Con Con Con
B2 B1 B0 B7
;TW523-4datafromPIC ;TW523-3dataintoPIC ;TW523-1zerocrossing ;TW523-2goestoVSS ;LEDtoflashtoshowstatus
KeyMax KeyMin
Con Con
15 0
;16legitkeycodes
UnitMin UnitMax
Con Con
0 15
;16legitunitcodes
HouseMin HouseMax
Con Con
0 15
;16legithousecodes
;Becausethecodesarenotinnumericalsequenceweconstruct ;atableforeachtogettheordercorrect. XUnit ByteTableX_1,X_2,X_3,X_4,X_5,X_6,X_7,X_8,X_9,X_10,| X_11,X_12,X_13,X_14,X_15,X_16 XhouseByteTableX_A,X_B,X_C,X_D,X_E,X_F,X_G,X_H,X_I,X_J,X_K,| X_L,X_M,X_N,X_O,X_P ;Useallkeys,intheordergiveninTW523interfacedocuments XKey ByteTable1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31 ;Eachentry=13bytes;index(N*13) ;IntheordergiveninTW523interfacedocuments KeyNameByteTable“AllUnitsOff”,|;1 “AllLghtsOn“,| “On“,| “Off“,| “Dim“,| “Bright“,| “AllLghtsOff”,| “ExtendedCode”,| “HailRequest“,| “HailAcknldge”,| “Pre-SetDim0”,| “Status=Off“,| “ExtendedData”,| “Status=On“,| “Pre-setDim1”,| “StatusRqst“ ;Variables ;------------uc Var Byte kc Var Byte hc Var Byte
;3 ;5 ;7 ;9 ;11 ;13 ;15 ;17 ;19 ;21 ;23 ;25 ;27 ;29 ;31
;unitcode ;keycode ;housecode
;Initialization ;--------------- EnableHSerial SetHSerialH115200 HSerOut[“P20-02”,13,13] ;dumpfunctioncodesandvalues&names HSerOut[“FunctionCodes”,13] Forkc=KeyMintoKeyMax HSerOut[Deckc,9,”Code:“,DecXKey(kc),| 9,iBinXKey(kc)\5,9,| StrKeyName((kc)*13)\13,13] Next HSerOut[13] Pause1000 ;Dumpunitcodevalues
463
Chapter20
HSerOut[“UnitCodes”,13] Foruc=UnitMintoUnitMax HSerOut[Decuc,9,iHexXUnit(uc)\2,| 9,iBinXUnit(uc)\5,13] Next HSerOut[13] ;Dumphousecodes HSerOut[“HouseCodes”,13] Forhc=HouseMintoHouseMax HSerOut[Dechc,9,iHexXHouse(hc),| 9,iBinXHouse(hc)\4,13] Next HSerOut[13,13] OutputLEDPin GoSubFlash
Main
;Loopthroughallpossiblehouse/unit/functioncodes Forhc=HouseMintoHouseMax Foruc=UnitMintoUnitMax ;SendALLtohousecodewhenhousecodechanges Ifuc=0Then Forkc=KeyMintoKeyMax XOutDataOutPin\ZeroXPin,| XHouse(hc),[XKey(kc)] HSerOut[(“A”+hc),”-ALL”,9] HSerOut[StrKeyName((kc)*13)\13,| 13] Next EndIf Forkc=KeyMintoKeyMax ;togetthesein ;orderA-01AllUnitsoff,etc. ;weusetheindextablesw XOutDataOutPin\ZeroXPin,| XHouse(hc),[Xunit(uc),XKey(kc)] ;Outputtoserialporttoknow ;what’sbeingsent HSerOut[(“A”+hc),”-”] HSerOut[Decuc+1\2,9] HSerOut[StrKeyName((kc)*13)\13,13] Next ;Visualindicationforusers GoSubFlash Next GoSubFlash GoSubFlash Next GoSubFlash GoSubFlash GoSubFlash GoToMain ;SubroutineflashestheLEDoncefor ;250ms. Flash ;----- HighLEDPin Pause250 LowLEDPin Pause250 Return End
We’llstartbylookingatProgram20-2’sdatastructure.Ourobjectiveistotransmitallpossiblehouse,unit andfunctioncodes,butinalogicalorder.WewishtostartwithA-1-AllUnitsOffandendwithP-16-Status Request.Aswe’veseenearlierinthischapter,theMBasiclibraryconstantvaluesarenotinanorderthat 464
X-10HomeAutomation permitsusto,forexample,usealoopstructureForHouseCode=X_AtoX_P…Next.Similarissues existfortheunitcodesandfunctioncodes.Hence,wereturntoadatastructurewe’veseenbefore;wecreate abytetabletoholdtheunderlyingvalues,organizedintheorderwewishthemtobeused. XUnit ByteTableX_1,X_2,X_3,X_4,X_5,X_6,X_7,X_8,X_9,X_10,| X_11,X_12,X_13,X_14,X_15,X_16
ThebytetableXUnit,forexample,iscomprisedoftheunitcodelibraryconstantsX_1throughX_16,inthe orderwewishthemtobesent.TheselibraryconstantsareeasilyaccessedbyaloopconstructFori=0 to15UnitCode=Xunit(i)…Next. XhouseByteTableX_A,X_B,X_C,X_D,X_E,X_F,X_G,X_H,X_I,X_J,X_K,| X_L,X_M,X_N,X_O,X_P XKey
ByteTable1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31
Wemodifythisapproachslightlyforthefunctioncodes.MBasicprovideslibraryconstantsfor11ofthe16 possiblefunctioncodes.So,insteadofmixinglibraryconstantidentifiers,suchasX_Onwithnumericalvalues,thefunctionbytetableXkeyusesonlynumericalvalues.Thevalues1,3,5…arefromtheconsolidated tabledevelopedearlierinthischapter. Welearnedearlierinthischapterthatunitcodesandfunctioncodesaresubsetsofaunified5-bitdataset. And,ifthenumericalvaluesofthosecodesareevaluatedinthebitordersent,unitcodesareintherange 0…15andfunctioncodesareintherange16…31.Ifwelookatthenumericalsequenceweuse,however, thefunctionkeyvaluesareoddintegersintherange1…31.Whythediscrepancy?Xoutsendsitsarguments inleft-to-rightorder,i.e.,MSB-first.ButtheX-10’sdevelopersestablisheditscommandstructureassuming dataissentLSB-first.Abitoftimewiththetablespresentedearlierdemonstratesthatthereversedbitorder causestheodd/eveninterleavingeffect. Sinceunitcodesareallevenintegersandfunctioncodesarealloddintegers,couldn’twesimplifymatters considerably,skippingboththeunitandfunctionbytetables,byaconstructsuchas: ForUnitCode=0to30Step2 ForFunctionCode=1to31Step2 SendUnitCodeandFunctionCode NextFunctionCode NextUnitCode
Theansweris“yeswecould.”But,wecannotusethisconstructandhavetheunitcodescomeoutinthe sequencewedesire.Thefirstthreeunitcodevaluessentwouldbe0,2and4.Thesevaluescorrespondto unitaddresses13,5and3. KeyNameByteTable
“AllUnitsOff”,|;1 “AllLghtsOn“,|;3 “On“,|;5 “Off“,|;7 “Dim“,|;9 “Bright“,|;11 “AllLghtsOff”,|;13 “ExtendedCode”,|;15 “HailRequest“,|;17 “HailAcknldge”,|;19 “Pre-SetDim0”,|;21 “Status=Off“,|;23 “ExtendedData”,|;25 “Status=On“,|;27 “Pre-setDim1”,|;29 “StatusRqst“;31
Toidentifythefunctioncodebeingtransmitted,weconstructanadditionalbytetableholdingthename functioncode’scommandname.Forconvenience,I’vemadeeachcommandname13byteslong. ThisallowsustoindexintothetableandwritethestringtotheserialportwithviathecommandStr 465
Chapter20 KeyName((kc)*13)\13wherekcisthekeycodeindex,0…15.ThecommandnamesinKeyNamearein thesameorderasthefunctioncodevaluesareinXkey. ;Variables ;------------uc Var Byte kc Var Byte hc Var Byte
;unitcode ;keycode ;housecode
Thethreeindexvariablesareuc,kcandhc,forunit,key(function)andhousecodes,respectively. Theinitializationcodelargelyconcernsitselfwithwritingthebytetablestotheserialportsowemayverify thedataentryagainstthevaluescontainedinthetablesearlierinthischapter.Theinitializationsectionof Program20-2isstraightforwardandneedsnodetailedanalysis. Let’snowturntothemainprogramloop. Main
;Loopthroughallpossiblehouse/unit/functioncodes Forhc=HouseMintoHouseMax Foruc=UnitMintoUnitMax
OurprogramstructureisthreenestedFor…Nextloops.Theoutertwoloopsarethehousecodeandunit codeloops.We’vedefinedconstantsHouseMin(0),HouseMax(15),UnitMin(0)andUnitMax(0)to serveastheloopranges.
;SendALLtohousecodewhenhousecodechanges Ifuc=0Then Forkc=KeyMintoKeyMax XOutDataOutPin\ZeroXPin,| XHouse(hc),[XKey(kc)] HSerOut[(“A”+hc),”-ALL”,9] HSerOut[StrKeyName((kc)*13)\13,| 13] Next EndIf
Forcompleteness,wealsowishtosendthe“allcall”commands,i.e.,sequencesofthetype,omittingtheunitcode.We’llsendtheallcallcommandsbeforestartingtheunitcode sequence1…16.Theabovecodesequencechecksforanewhousecode(whichweidentifybytheunitcode loopindexucbeingzero)andwhenuc=0,wecyclethroughall16possiblefunctioncodecombinations withtheForkc=KeyMintoKeyMaxloop.TheXoutstatementisXOutDataOutPin\ZeroXPin,XH ouse(hc),[XKey(kc)]whichomitstheunitidentifier.And,ofcourse,weusetheindexvariableshcand kctoindexintothebytetablesXhouseandXkey,forthereasonsearlierdeveloped.
Forkc=KeyMintoKeyMax ;togetthesein ;orderA-01AllUnitsoff,etc. ;weusetheindextablesw XOutDataOutPin\ZeroXPin,| XHouse(hc),[Xunit(uc),XKey(kc)] ;Outputtoserialporttoknow ;what’sbeingsent HSerOut[(“A”+hc),”-”] HSerOut[Decuc+1\2,9] HSerOut[StrKeyName((kc)*13)\13,13] Next
Aftergettingtheallcallsequenceoutoftheway,weloopthroughall16possiblefunctioncodes,thistime sendingthesequence,ascanbeseenwhenweexaminetheXout statement:XOutDataOutPin\ZeroXPin,XHouse(hc),[Xunit(uc),XKey(kc)].
;Visualindicationforusers GoSubFlash Next GoSubFlash
466
X-10HomeAutomation GoSubFlash Next GoSubFlash GoSubFlash GoSubFlash GoToMain
Finally,weclosethevariousFor…NextloopswithcallstosubroutineFlash.FlashblinksanLEDto provideavisualcueoftheprogram’sprogressandneedsnodetailedanalysis. TheserialoutputofProgram20-2isshownbelow.Tosavespace,I’vereformattedtheoutputintotwocolumns. P20-02 FunctionCodes 0 Code:1 %00001 1 Code:3 %00011 2 Code:5 %00101 3 Code:7 %00111 4 Code:9 %01001 5 Code:11 %01011 6 Code:13 %01101 7 Code:15 %01111 8 Code:17 %10001 9 Code:19 %10011 10 Code:21 %10101 11 Code:23 %10111 12 Code:25 %11001 13 Code:27 %11011 14 Code:29 %11101 15 Code:31 %11111 UnitCodes 0 $0C %01100 1 $1C %11100 2 $04 %00100 3 $14 %10100 4 $02 %00010 5 $12 %10010 6 $0A %01010 7 $1A %11010 8 $0E %01110 9 $1E %11110 10 $06 %00110 11 $16 %10110 12 $00 %00000 13 $10 %10000 14 $08 %01000 15 $18 %11000
AllUnitsOff AllLghtsOn On Off Dim Bright AllLghtsOff ExtendedCode HailRequest HailAcknldge Pre-SetDim0 Status=Off ExtendedData Status=On Pre-setDim1 StatusRqst
HouseCodes 0 $6 %0110 1 $E %1110 2 $2 %0010 3 $A %1010 4 $1 %0001 5 $9 %1001 6 $5 %0101 7 $D %1101 8 $7 %0111 9 $F %1111 10 $3 %0011 11 $B %1011 12 $0 %0000 13 $8 %1000 14 $4 %0100 15 $C %1100 A-ALL AllUnitsOff A-ALL AllLghtsOn A-ALL On A-ALL Off A-ALL Dim A-ALL Bright A-ALL AllLghtsOff A-ALL ExtendedCode A-ALL HailRequest A-ALL HailAcknldge A-ALL Pre-SetDim0 A-ALL Status=Off A-ALL ExtendedData A-ALL Status=On A-ALL Pre-setDim1 A-ALL StatusRqst A-01 AllUnitsOff A-01 AllLghtsOn A-01 On A-01 Off A-01 Dim
Program20-2’soutputcontinuesthroughP-16StatusRequestandthenbeginsagainwithA-ALLAllUnitsOff.
467
Chapter20 Program20-3 Let’snowtryreceivingX-10signals.Thisrequirestwo2840DevelopmentBoards,aswellastwoTW523s, oroneTW523transceiverandonePL513transmitter.TransmitandreceiveDevelopmentBoardsshouldbe connectedasillustratedinFigure20-13.ThetransmitDevelopmentBoardshouldberunningProgram20-2. ;Program20-03 ;Readspecifichousecodeinfo ;DemonstratesXIN ;Constants ;-----------DataOutPin DataInPin ZeroXPin HouseCode
Con Con Con Con
B2 B1 B0 X_K
;Variables ;-----------RcvdCode
Var
Byte;willholdreceivedinfo
;TW523-4datafromPIC ;TW523-3dataintoPIC ;TW523-1zerocrossing ;TW523-2goestoVSS ;selectedcodetolistenfor
;Initialization ;---------------EnableHSerial SetHSerialH115200 Main ;---- ;Eachtransmissionthathasaunitcodeand ;afunctioncodewillgivetworeturnsfrom ;XIN.Onefortheunitcodeandoneforfcncode XINDataInPin\ZeroXPin,HouseCode,[RcvdCode] ;Echoouttoserialport HSerOut[“Rcvd:“,DecRcvdCode,13] GoToMain End
WeusethesamepinconnectionsandpinidentifierconstantsasinProgram20-1and20-1.Themainprogramloopwaitsfordatatobereceived,storesthereceiveddatabyteinRcvdCodeandsendsRcvdCodeout theserialport. Main ;---- XINDataInPin\ZeroXPin,HouseCode,[RcvdCode] ;Echoouttoserialport HSerOut[“Rcvd:“,DecRcvdCode,13] GoToMain
Aftereachbyteisreceived,executionreturnstoMaintoawaitthenextreceiveddataelement. BeforeweseeProgram20-3’soutput,let’slookatMBasic’sXinprocedure. XinDataPin\ZeroPin,House,{TimeoutLabel,TimeoutCount},[{{Modifier},Variable]
DataPin—isaconstantorvariableidentifyingthedatainputpin.ThispinconnectstotheTW523’spin3. Don’tforgettherequiredpull-upresistor. ZeroPin—isaconstantorvariableidentifyingthezerocrossinginputpin.ThispinconnectstotheTW523’s pin1.Don’tforgetthispinrequiresapull-upresistor.Figure20-8showsa5.1K,butanyvalueinthe range3.3Kthrough10Kisacceptable.
468
X-10HomeAutomation TimeoutLabelandTimeoutCount—areoptionalparameters.IfTimeoutCountcommandsarereceivedwithoutamatchforHouse,executionwilljumptotheprogramlabelTimeoutLabel. House—isaconstantorvariableholdingthehousecode.Thehousecodemustbeintherange0…15.MBasichasdefinedlibraryconstantsX_A…X_Pthatprovidetheproperhousecodevaluecorrespondingto housecodesA…P. Variable—isabytelengthvariableholdingthereceived5-bitdatavalue. XinonlyreturnsavalueforVariablewhenthereceivedX-10sequencehasahouse codethatmatchesHouse.IfHousedoesnotmatchthereceivedsequence,Xincontinuesto monitortheinputdatastreamanddoesnotcompleteexecution. Let’scompareProgram20-3’soutputwiththetransmissionsofProgram20-2. Program20-02Sending K-07 Pre-SetDim0 K-07
Status=Off
K-07
ExtendedData
K-07
Status=On
K-07
Pre-setDim1
K-07
StatusRqst
K-08
AllUnitsOff
K-08
AllLghtsOn
K-08
On
K-08
Off
K-08
Dim
K-08
Bright
Program20-03Receiving Rcvd:10 Rcvd:21 Rcvd:10 Rcvd:23 Rcvd:10 Rcvd:25 Rcvd:10 Rcvd:27 Rcvd:10 Rcvd:29 Rcvd:10 Rcvd:31 Rcvd:26 Rcvd:1 Rcvd:26 Rcvd:3 Rcvd:26 Rcvd:5 Rcvd:26 Rcvd:7 Rcvd:26 Rcvd:9 Rcvd:26 Rcvd:11
Ifwecheckourearlierdatatable,weseethevalueofX_7,is10andX_8’svalueis26.Thesevaluesmatch thedecodedvaluereportedbyProgram20-3.Likewise,wecancheckthefunctioncodevalues,forexample X_Off,anddeterminethatitis7,whichmatchesthedecodedvaluereportedbyProgram20-3. Program20-4 Asexplainedattheoutsetofthischapter,ourfocusisnotonusingX-10tocontrollightsorappliances,but ratherondatatransmissionviatheX-10interface.IfyouwishtobuildaX-10housecontroller,bythetime youcompetethisbookyoushouldhavelearnedenoughtodesign,constructandprogramacontrollerthat meetsyourspecificrequirements. Let’sfirstverifyourabilitytotransmitandreceiveunrestricteddatavariables(butrestrictedtovaluesinthe range0…31)throughProgram20-4. ;Program20-04.Verifytransmit ;andcontrolwithminimalprogram
469
Chapter20 ;Constants ;-----------DataOutPin DataInPin ZeroXPin HouseCode
Con Con Con Con
B2 B1 B0 X_J
;Variables ;----------i
Var
Byte
;TW523-4datafromPIC ;TW523-3dataintoPIC ;TW523-1zerocrossing ;TW523-2goestoVSS
Main Fori=0to31 XOutDataOutPin\ZeroXPin,HouseCode,[i] Pause1000 Next GoToMain End
Program20-4sendsthevalues0…31usinghousecodeX_J.ItspurposeistodemonstratethatProgram20-3 correctlyreceivesthesevalues. LoadProgram20-4intothetransmittingDevelopmentBoardandexaminetheoutputfromProgram20-3. Youshouldseethefollowingoutput(reformattedtofourcolumnstosavespace): Rcvd:0 Rcvd:1 Rcvd:2 Rcvd:3 Rcvd:4 Rcvd:5 Rcvd:6 Rcvd:7
Rcvd:8 Rcvd:9 Rcvd:10 Rcvd:11 Rcvd:12 Rcvd:13 Rcvd:14 Rcvd:15
Rcvd:16 Rcvd:17 Rcvd:18 Rcvd:19 Rcvd:20 Rcvd:21 Rcvd:22 Rcvd:23
Rcvd:24 Rcvd:25 Rcvd:26 Rcvd:27 Rcvd:28 Rcvd:29 Rcvd:30 Rcvd:31
Program20-5 Let’strysendingsomethingabitmore adventuresome—thecurrenttemperature.Reconfigureyourtransmitting2840 DevelopmentBoardbyaddingaDallas SemiconductorDS18B20digitaltemperaturesensorasshowninFigure20-14. We’veextensivelycoveredtheDS18B20 inChapter12soifyou’veskippedahead withoutreadingChapter12first,you mightwishtoreaditnow.Inshort,readingaDS18B20temperaturesensorreturns a12-bittemperaturereading(inCelsius) overaone-wireinterface.MBasicsupportstheone-wireinterfacewiththeOWin andOwoutproceduresforreadingfrom Figure20-14:X-10temperaturetransmittingcircuit. andwritingtoone-wiredevices.
470
X-10HomeAutomation Program20-5readstheambienttemperaturefromtheDS18B20andtransmitsthevalueoveranX-10link toareceivingprogram.We’lltestProgram20-5’sfunctionalitywithProgram20-3,andthenwriteProgram 20-6toproperlymanageanddisplayreceivedtemperaturedata. ;Program20-05. ;ReadsaDallas1-wireTemperaturesensor ;DS18B20.AssumesonlyONEdeviceisconnectedtothebus, ;sinceweuseglobaladdressmode.Sendsthetempdata ;overtheX10interfaceforreadingremotely. ;Constants ;-----------DataOutPin DataInPin ZeroXPin SensorPin
Con Con Con Con
B2 B1 B0 B6
;TW523-4datafromPIC ;TW523-3dataintoPIC ;TW523-1zerocrossing ;TW523-2goestoVSS ;DS18B20tothispin
;Dataissentas:<StartData> ;<EndData> ;Dataelementsare0...9,+.-,. StartData Con 10 ;firstelement EndData Con 11 ;lastelement DecimalPt Con 12 ;decimalpoint Minus Con 13 ;minussign Plus Con 14 ;plussign Channel0 Con 16 ;datachannels0 Channel1 Con 17 ;datachannel1 ;Number=Channel+16 ;ReadsaDallas1-wireTemperaturesensor ;DS18B20.AssumesonlyONEdeviceisconnectedtothebus, ;sinceweuseglobaladdressmode. HouseCode
Con
X_J;arbitraryselection
;Variables ;----------i Temp PlusFlag Centigrade Fahrenheit TH TL ConfigReg FStringVar OutByteVar ChannelVar
Var Var Var Var Var Var Var Var
Byte Word ;holdsrawbinarytemperatureoutput Byte ;plus/minusflag Float ;FloatingpointCtemp Float ;FloatingpointFtemp Byte ;Loweralarmvalue Byte ;Upperalarmvalue Byte ;Temperatureresolution Byte(10);holdsdegreesFinstring Byte ;outputtoX10transmitter Byte ;DataChannel
;Initialization Init ;------------- EnableHSerial SetHSerialH115200
;$4EWritetoRAM;dummy$FFtoTH&TL, ;$7Ftoctrlregfor12-bit OWOutSensorPin,1,Init,[$CC,$4E,$FF,$FF,$7F] ;WritefromscratchpadtoEEPROM OWOutSensorPin,1,Init,[$CC,$48] ;readbackfromEEPROMtoscratchpad OWOutSensorPin,1,Init,[$CC,$B8] ;Readscratchpadmemory OWOutSensorPin,1,Init,[$CC,$BE] Pause1000 ;Readoutputandcheckconfiguration OWinSensorPin,0,[Temp.Byte0,Temp.Byte1,TH,TL,ConfigReg]
471
Chapter20 Main Wait
HSerOut[“InitOKR1:“,BINConfigReg.Bit6,”R0:“,| BINConfigReg.Bit5,13] ;Causetempconversiontostart OWOutSensorPin,1,Main,[$CC,$44] ;readoutputandloopuntilconversionisdone. ;conversiondonethroughawritebackof1,0ifnotdone ;Notethisonlyworkswithexternalpower OWInSensorPin,0,[Temp] IfTemp=0ThenWait OWOutSensorPin,1,Main,[$CC,$BE] OWinSensorPin,0,[Temp.Byte0,Temp.Byte1,TH,TL,ConfigReg] ;readTH,TLandConfigReg,wewon’tusethisinformation ;Temperaturedatareturnedas2’scomplementforbelow0. ;Hence,below0=1inthereturnedhighestbit. PlusFlag=1 IfTemp.HighBit=1Then ;checkfor<0C ;Subtractfrom0toreadbelow0value Temp=$0000-Temp PlusFlag=0 EndIf ;ReturnedvalueisinCentigradestepsof0.0625DegreesC. Centigrade=(ToFloatTemp)*0.0625 IfPlusFlag=0Then ;belowzero,multiplyby-1 Centigrade=-Centigrade EndIf ;StandardconversionformulatogettoFfromC. Fahrenheit=(Centigrade*1.8)+32.0;converttoF ;Writeoutput.Notethe\2and\1modifiers ;givenumberofplacesafterdecimalpoint HSerOut[“Temperature“,RealFahrenheit\2,”F“,| RealCentigrade\1,”C”,13] ;UseModifierasFunctiontoconverttostring Fstring=RealFahrenheit\2 HserOut[“Sending:“,9,StrFString\10\0,13] Channel=Channel0 GoSubSendData
Fstring=RealCentigrade\2 HserOut[“Sending:“,9,StrFString\10\0,13] Channel=Channel1 GoSubSendData GoToMain
;StringtobesentisinFString ;ChannelnoisinChannel SendData ;-----------;nowwesendthestringviaX10transmitter ;startwithStartDataandChannelNo. XOutDataOutPin\ZeroXPin,HouseCode,[StartData,Channel] Pause100 i=0 ;stripthestringapartandlookfor ;-and.andnumbers.Encodethese While(FString(i)<>0)AND(i<10) ;printingchar IfFString(i)=“-”Then OutByte=Minus EndIf IfFString(i)=“.”Then OutByte=DecimalPt EndIf
472
X-10HomeAutomation Return End
If(FString(i)>=“0”)AND(FString(i)<=”9”)Then OutByte=FString(i)-“0” EndIf ;nowsendtheencodedbyte XOutDataOutPin\ZeroXPin,HouseCode,[OutByte] i=i+1 Pause50 WEND ;alldatagone,nowwrapitupwithenddata XOutDataOutPin\ZeroXPin,HouseCode,[EndData] ;zeroFStringforthenextdatavalue Fori=0to9 FString(i)=0 Next Pause1000
BeforeplungingintoProgram20-5’scode,let’sconsiderhowwemightgoabouttransmittinggenericdata overanX-10interface.TheX-10protocollimitsustofivedatabits.Wecouldspliteverytransmittedbyte intoitshighandlownibblesandtransmiteachnibbleseparately.Or,ifwewishtomakemaximumadvantageofX-10’sfive-bytetransmissionspace,wecouldpackfivebytesofdataintoeightX-10messages. Program20-5takesadifferentapproach.First,convertthenumericaldatatobetransmittedtoastringrepresentation.Then,transmitacodedversionofthestring.And,tomakethetransmissionprotocolmoregeneral, we’llstructureitasa16-channeltelemetrysystem.Thestructureweuseis: StartData
Channel Code
DataElement 1
DataElement 2
…
DataElement N
EndData
ThevaluesfortheseelementsaredefinedintheConstantssectionofProgram20-5: ;Dataelementsare0...9,+.-,. StartData Con EndData Con DecimalPt Con Minus Con Plus Con Channel0 Con Channel1 Con
10 ;firstelement 11 ;lastelement 12 ;decimalpoint 13 ;minussign 14 ;plussign 16 ;datachannels0 17;datachannel1 ;Number=Channel+16
Thestringdigits0…9arerepresentedbydatavalues0…9.Thedecimalpoint,plusandminussignshave datavalues12,14and13,respectively.Thechannelnumberrunsfrom16…31,representingdatachannels 0…16.Ifyouwouldratherhave32datachannels,letthechannelnumbersrunfrom0…31. Eachelementofthisstructureissentseparately,withaprecedinghousecode,sothattheactualtransmissionsequenceis<startcode> …<endcode>.IfyouwishtousetheX-10protocolonly fordatatransmission,andhavenoX-10receivingmodules,youcouldcombinethehousecodeanddata elementsintoasingle9-bitdataspaceandsendafullbytewitheveryXoutcommand.However,thiswill requireyoutowriteageneral-purposeinputroutine,suchastheonewepresentinProgram20-7,asXin willnotreturnboththehouseanddataelements. Now,let’slookattheinitializationsection ;Initialization Init ;------------- EnableHSerial SetHSerialH115200
;$4EWritetoRAM;dummy$FFtoTH&TL, ;$7Ftoctrlregfor12-bit
473
Chapter20
OWOutSensorPin,1,Init,[$CC,$4E,$FF,$FF,$7F] ;WritefromscratchpadtoEEPROM OWOutSensorPin,1,Init,[$CC,$48] ;readbackfromEEPROMtoscratchpad OWOutSensorPin,1,Init,[$CC,$B8] ;Readscratchpadmemory OWOutSensorPin,1,Init,[$CC,$BE] Pause1000 ;Readoutputandcheckconfiguration OWinSensorPin,0,[Temp.Byte0,Temp.Byte1,TH,TL,ConfigReg] HSerOut[“InitOKR1:“,BINConfigReg.Bit6,”R0:“,| BINConfigReg.Bit5,13]
Theinitializationcode,otherthansettingthehardwareserialoutputspeed,setstheDS18B20for12-bit accuracy.ThisinitializationsectionduplicatesthecodeofProgram12-2andtheanalysistherewillnotbe repeatedhere. We’llstepthroughtheDS18B20relatedcodequickly,whichisclonedfromProgram12-2. Main Wait
;Causetempconversiontostart OWOutSensorPin,1,Main,[$CC,$44] ;readoutputandloopuntilconversionisdone. ;conversiondonethroughawritebackof1,0ifnotdone ;Notethisonlyworkswithexternalpower OWInSensorPin,0,[Temp] IfTemp=0ThenWait
Theabovecodeinitiatesatemperaturereadingandthenloopsuntilthetemperaturereadingiscompleted.
OWOutSensorPin,1,Main,[$CC,$BE] OWinSensorPin,0,[Temp.Byte0,Temp.Byte1,TH,TL,ConfigReg] ;readTH,TLandConfigReg,wewon’tusethisinformation ;Temperaturedatareturnedas2’scomplementforbelow0. ;Hence,below0=1inthereturnedhighestbit. PlusFlag=1 IfTemp.HighBit=1Then ;checkfor<0C ;Subtractfrom0toreadbelow0value Temp=$0000-Temp PlusFlag=0 EndIf
Afterthetemperaturereadingiscomplete,theabovecodereadsthe12-bitresult,and,iftheresultisbelow zeroCelsius,decomplementsthedataandclearsaplus/minusflag,PlusFlag.
;ReturnedvalueisinCentigradestepsof0.0625DegreesC. Centigrade=(ToFloatTemp)*0.0625 IfPlusFlag=0Then ;belowzero,multiplyby-1 Centigrade=-Centigrade EndIf ;StandardconversionformulatogettoFfromC. Fahrenheit=(Centigrade*1.8)+32.0;converttoF
Now,therawtemperaturereadingisconvertedtofloatingpointCelsiusandFahrenheitvalues,heldinthe variablesCentigradeandFahrenheit.
;Writeoutput.Notethe\2and\1modifiers ;givenumberofplacesafterdecimalpoint HSerOut[“Temperature“,RealFahrenheit\2,”F“,| RealCentigrade\1,”C”,13] ;UseModifierasFunctiontoconverttostring Fstring=RealFahrenheit\2 HserOut[“Sending:“,9,StrFString\10\0,13]
ToconvertthefloatingpointFahrenheittoastring,Fstring,weusetheRealmodifierasafunction. MBasic’sabilitytouseamodifierasaconversionfunctionisundocumentedinitsUser’sGuide.Atthis
474
X-10HomeAutomation point,FstringholdsastringrepresentationofthefloatingpointFahrenheit.If,forexample,Fahrenheitholdsthevalue74.123456,afterFstring=RealFahrenheit\2,thevariableFstringequals “74.12.”
Channel=Channel0 GoSubSendData
WecallsubroutineSendDatatooutputFstringovertheX-10interface.WesetChannel=Channel0to sendFstringwithachannelidentifierofChannel0. Fstring=RealCentigrade\2 HserOut[“Sending:“,9,StrFString\10\0,13] Channel=Channel1 GoSubSendData GoToMain
WerepeattheprocesswiththeCelsiustemperaturefloatingpointvariableCentigrade,butsenditwitha channelidentifierofChannel1. Let’sexaminethesubroutineSendData.SendDatarequirestheoutputstringtobeheldinthevariable Fstring,andthatFstring’scharactersarerestrictedtothedigits0…9,decimalpoint,plusandminus signs.ThechannelnumberissetinthevariableChannel. ;StringtobesentisinFString ;ChannelnoisinChannel SendData ;-----------;nowwesendthestringviaX10transmitter ;startwithStartDataandChannelNo. XOutDataOutPin\ZeroXPin,HouseCode,[StartData,Channel] Pause100 i=0
Weknowthechannelnumbersowecansendthestartdatacodeandthechannelnumber.Iaddeda100ms pausefordebuggingpurposes,butitisn’tnecessaryandmayberemovedifyoudesire. Return
;stripthestringapartandlookfor ;-and.andnumbers.Encodethese While(FString(i)<>0)AND(i<10) ;printingchar IfFString(i)=“-”Then OutByte=Minus EndIf IfFString(i)=“.”Then OutByte=DecimalPt EndIf If(FString(i)>=“0”)AND(FString(i)<=”9”)Then OutByte=FString(i)-“0” EndIf ;nowsendtheencodedbyte XOutDataOutPin\ZeroXPin,HouseCode,[OutByte] i=i+1 Pause50 WEND ;alldatagone,nowwrapitupwithenddata XOutDataOutPin\ZeroXPin,HouseCode,[EndData] ;zeroFStringforthenextdatavalue Fori=0to9 FString(i)=0 Next Pause1000
ThemainbodyofSendDataloopsthroughFstringsolongasithasdata,orthelengthofFstring, whicheveroccursfirst.AWhile…WENDloopprovidesanappropriatecontrolstructure,asitpermitscheckingtheendconditionsatthetopofthecontrolloop.
475
Chapter20 EachcharacterinFstringistestedtoseeifitisaspecialcharacter,i.e.,decimalpoint,oraplusorminussign.Ifitis,OutByteissettotheappropriatecharactercode.Ifthecharacterisanumbercharacter “0”…”9”OutByteissettothenumericalvalue0…9bysubtractingthevalueofthezerocharacter“0.” OutByteisthensentviatheXoutprocedure. AfterallcharactersinFstringhavebeensent,theEndDatacodeissentandFstringzeroedtobeready forthenextstringtobesent. Let’sseehowProgram20-3receivesthesentdata. Program20-05Sending Temperature71.37F21.8C Sending: 71.37 Sending: 21.87
Program20-03Receiving Rcvd:10 Rcvd:16 Rcvd:7 Rcvd:1 Rcvd:12 Rcvd:3 Rcvd:7 Rcvd:11 Rcvd:10 Rcvd:17 Rcvd:2 Rcvd:1 Rcvd:12 Rcvd:8 Rcvd:7 Rcvd:11
Comments StartCode FDataisonChannel0 7 1 . 3 7 EndCode StartCode CDataisonChannel1 2 1 . 8 7 EndCode
Program20-6 Program20-3’soutputverifiesthatthetemperaturedataiscorrectlyencodedandset,sowemaynowconcentrateonanimproveddisplayofreceiveddata.Program20-6usesthesamereceivingconfigurationas Program20-3. ;Program20-06demonstratesreadingtheremote ;telemetereddatafromProgram20-05.Weread ;Channel0anddisplaythetempinDegF. ;Constants ;-----------DataOutPin DataInPin ZeroXPin HouseCode
Con Con Con Con
B2 B1 B0 X_J
;Dataissentas:<StartData> ;<EndData> ;Dataelementsare0...9,+.-,. StartData Con 10 EndData Con 11 DecimalPt Con 12 Minus Con 13 Plus Con 14 Channel0 Con 16 ;reservedlengthforreceivedstring RXStrLen Con 12 ;statusofmainloop
476
;TW523-4datafromPIC ;TW523-3dataintoPIC ;TW523-1zerocrossing ;TW523-2goestoVSS ;Unusedcontrolcode
;firstelement ;lastelement ;decimalpoint ;minussign ;plussign ;datachannels0...15 ;Number=Channel+16 ;arbitraryselection
X-10HomeAutomation Waiting ValidStart ValidEnd Unknown
Con Con Con Con
0 1 2 3
;waitingforinput ;hasrcvd“StartData” ;hasrcvd“EndData” ;Unknownstatus
;Wehaveonlytwotelemetrychannelsnow ;We’llsendDegFonChannel0andDegCon ;Channel1 ChannelUnits ByteTable“DegF”,”DegC” ;Variables ;-----------RcvdCode i j RcvdData RcvdStr InStatus ChannelNo
Var Var Var Var Var Var Var
Byte ;5-bitreceiveddata Byte ;loopcounter Byte ;loopcounter Byte(RxStrLen);holdsincomingRcvdCodes Byte(RxStrLen);decodedstring Byte ;holdsstatusofmainloop Byte ;telemetrychannelnumber
;Initialization ;---------------EnableHSerial SetHSerialH115200 ;settonull Fori=0to(RXStrLen-1) RcvdStr=0 Next ;don’tknowwherestatusis InStatus=Unknown i=0 Main ;----
;readdatainput-mustmatchHouseCode XINDataInPin\ZeroXPin,HouseCode,[RcvdCode] ;removecommentstoseerawdata ;HSerOut[“Rcvd:“,DecRcvdCode,13] ;Ifwehavestartbytesetstatus IfRcvdCode=StartDataThen InStatus=ValidStart EndIf IfRcvdCode=EndDataThen InStatus=ValidEnd EndIf IfInStatus=ValidStartThen RcvdData(i)=RcvdCode i=i+1 Ifi=RXStrLenThen i=0 EndIf EndIf IfInStatus=ValidEndThen Forj=0to(RXStrLen-1) RcvdStr(j)=0 Next ChannelNo=RcvdData(1)-16 Forj=0to(i-3) RcvdStr(j)=RcvdData(j+2)+”0” IfRcvdData(j+2)=DecimalPtThen RcvdStr(j)=“.” EndIf IfRcvdData(j+2)=PlusThen RcvdStr(j)=“+” EndIf IfRcvdData(j+2)=MinusThen RcvdStr(j)=“-” EndIf
477
Chapter20 EndIf GoToMain End
Next HSerOut[“Chan:“,9,DecChannelNo,9] HSerOut[StrRcvdStr\RXStrLen-1\0,9] HSerOut[StrChannelUnits(ChannelNo*5)\5,13] InStatus=Unknown i=0
TheconstantandinitializationsectionofProgram20-6issimilartoProgram20-5andwillnotbeanalyzed. Ourapproachtoreadingtheincomingdatastreamistobegincollectingdatawhenthestartcodeisreceived, andstopcollectingdatawhentheendcodeisreceived.Wecontrolprogramflowwithastatusvariable,InStatus.Inpseudo-codeouralgorithmis:
InitializeInStatus=Unknown
MainStart Readincomingcharacter IsitStart?IfsothenInStatus=ValidStart IsitEnd?IfsothenInStatus=EndData IfInStatus=ValidStartthen: StoretheincomingcharacterinthearrayRcvdData(i) Increment(i) IfInStatus=EndDatathen: ConvertRcvdDatatonumericalvalueanddisplay Resetito0 GotoMainStartandreadthenextcharacter
Untilwereceivethestartcharacter,nothingisstored;theprogramcontinuestoloopthroughreadingthe incomingcharacter.Whenastartcharacterisreceived,thestatevariableInStatuslatchestoValidStart conditionandwestoreeachreceivedcharacterinthearrayRcvdDatasolongasInStatusremainsinValidStartcondition.Whentheendcharacterisreceived,InStatuschangestoanewstatus,ValidEnd,and remainsinValidEndstateuntilanewstartcharacterisreceived.AtthetimethestatuschangesfromValidStarttoValidEnd,weconvertthesaveddatainRcvdDatatothedesiredformatanddisplaytheresults. Let’sseehowwemightimplementthisalgorithm. InStatus=Unknown i=0
WeinitializeInStatusasunknownandsetthecountervariabletoito0.Thisprovidesaknownstarting point;sinceInStatusisneitherValidStartnorValidEnd,noneoftheactivitiesassociatedwiththelattertwostateswillbeexecuted.Instead,weawaiteitherastartorendcode. Main ;----
;readdatainput-mustmatchHouseCode XINDataInPin\ZeroXPin,HouseCode,[RcvdCode] ;removecommentstoseerawdata ;HSerOut[“Rcvd:“,DecRcvdCode,13] ;Ifwehavestartbytesetstatus
IfRcvdCode=StartDataThen InStatus=ValidStart EndIf
IfRcvdCode=EndDataThen InStatus=ValidEnd EndIf
WereadtheincomingdataandchangeInStatusbasedonthereceiveddata.Remember,InStatustogglesbetweenValidStartorValidEndstatus,anditstaysinonevalueuntilitflipstotheoppositevalue. 478
X-10HomeAutomation
IfInStatus=ValidStartThen RcvdData(i)=RcvdCode i=i+1 Ifi=RXStrLenThen i=0 EndIf EndIf
Ifthedatastreamisvalid,asevidencedbyreceiptofthestartcode,andInStatus=ValidStart,we savethereceivedcharacterinRcvdData(i)andincrementi.Wealsocheckforpossibleioverflowand reset(i=0)ifnecessarytopreventoverflow.
IfInStatus=ValidEndThen
Atthispoint,RcvdDataholds: i=
0
RcvdData(i)=
StartData
1 Channel Code
2 Data Element1
3 Data Element2
…
i-1 Data ElementN
i EndData
Forj=0to(RXStrLen-1) RcvdStr(j)=0 Next
WenextinitializeanewarrayvariableRcvdStrbyfillingitwithnull(0)characters.
ChannelNo=RcvdData(1)-16
ThechannelnumberisheldasthesecondelementinRcvdData,withabiasof16.Weconvertittoanintegervalue0…15bysubtracting16.
Forj=0to(i-3) RcvdStr(j)=RcvdData(j+2)+”0” IfRcvdData(j+2)=DecimalPtThen RcvdStr(j)=“.” EndIf IfRcvdData(j+2)=PlusThen RcvdStr(j)=“+” EndIf IfRcvdData(j+2)=MinusThen RcvdStr(j)=“-” EndIf Next
Next,wecopythedataelementbytesfromRcvdDatatoRcvdStr.Aswe’veseen,thefirstvaliddataelementisRcvdData(2)andthelastvaliddataelementisRcvdData(i-1).Ourobjectiveistocopyonly thedataelementbytesfromRcvdDatatoRcvdStr,andleftjustifythecopieddatainRcvdStr.Theabove codeaccomplishesthistask. Wealsoconvertthedatabytevaluestoastringcharacterbyadding“0”andcheckingforthethreespecial characters,decimalpointandtheplusandminussigns.Ifanyofthesespecialcharactersarefound,weinsert theappropriatestringsymbol. EndIf GoToMain
HSerOut[“Chan:“,9,DecChannelNo,9] HSerOut[StrRcvdStr\RXStrLen-1\0,9] HSerOut[StrChannelUnits(ChannelNo*5)\5,13] InStatus=Unknown i=0
Finally,wewritethedecodedstringtotheserialport.Todisplaytheappropriatedimensionname,weearlier defineddimensionalconstantsforChannels0and1: ChannelUnits
ByteTable“DegF”,”DegC”
WeindexintothebytetableChannelUnitsbyChannelNo*5.Hence,Channel0returns“DegF”while Channel1returns“DegC.” 479
Chapter20 FollowingistheoutputfromProgram20-5comparedwiththereceiveddatafromProgram20-6: Program20-5Sending Temperature70.58F21.4C Sending: 70.58 Sending: 21.43 Temperature70.69F21.5C Sending: 70.69 Sending: 21.50 Temperature70.69F21.5C Sending: 70.69 Sending: 21.50 Temperature70.81F21.5C Sending: 70.81 Sending: 21.56 Temperature70.81F21.5C Sending: 70.81 Sending: 21.56 Temperature70.81F21.5C Sending: 70.81 Sending: 21.56 Temperature70.81F21.5C Sending: 70.81 Sending: 21.56 Temperature70.92F21.6C Sending: 70.92 Sending: 21.62 Temperature70.81F21.5C Sending: 70.81 Sending: 21.56
Program20-6Receiving Chan: Chan:
0 1
70.58 21.43
DegF DegC
Chan: Chan:
0 1
70.69 21.50
DegF DegC
Chan: Chan:
0 1
70.69 21.50
DegF DegC
Chan: Chan:
0 1
70.81 21.56
DegF DegC
Chan: Chan:
0 1
70.81 21.56
DegF DegC
Chan: Chan:
0 1
70.81 21.56
DegF DegC
Chan: Chan:
0 1
70.81 21.56
DegF DegC
Chan: Chan:
0 1
70.92 21.62
DegF DegC
Chan: Chan:
0 1
70.81 21.56
DegF DegC
Program20-7 Ourfinalprogramisan“X-10codesniffer”thatmonitorsthepowerlineanddisplaysthelastfourX-10 commandsonanLCDdisplay.ItalsooutputsreceivedcommandsovertheRS-232port.Itbuildsonthe algorithmofProgram20-6,butwithasoftwareversionofXin. Program20-7isverylong.Ratherthan followournormalstructureoflistingthe programinfull,followedbyasection-bysectionanalysis,we’llskipthefulllisting. Program20-7,likeallotherprograms inthisbook,isavailableinanelectronic copyintheassociatedCD-ROM.Ifyou needalistingtofollowwhilereading theanalysis,youmayprintonefromthe programfile. Figure20-15showsthecircuitIusedwith Program20-7.AlthoughIuseda20×4 LCDdisplay,onlysimplechangesare necessarytoProgram20-7shouldyour displayhavefewerlinesorcharacters. Figure20-15:CircuitforProgram20-7.
480
X-10HomeAutomation ToillustratethatwemaysuccessfullyworkwitheitherLSB-firstorMSB-firstbitorder,we’lluseLSB-first orderinProgram20-7. AlthoughwewillusethesamebytetableapproachasinProgram20-2,thetableordersaredifferent,to reflecttheLSB-firstapproach.WealsodefineanewbytetablePowerTabletoassistusincalculatingthe valueofreceiveddatainLSB-firstorder. Ifyouexaminetheearliercomparisontable,youwillseethatvaluesinHouseTable,UnitTableandKeyNameareinthesequenceoftheTW523LSB-firstdocumentation. PowerTable
ByteTable1,2,4,8,16
HouseTable
ByteTable“MNOPCDABEFGHKLIJ”
UnitTable
ByteTable13,14,15,16,3,4,1,2,5,6,7,8,11,12,9,10
KeyName
ByteTable
“AllUnitsOff”,| “HailRequest“,| “Dim“,| “ExtDta-Analg”,| “On“,| “Pre-SetDim0”,| “AllLghtsOff”,| “Status=Off“,| “AllLghtsOn“,| “HailAcknldge”,| “Bright“,| “Status=On“,| “Off“,| “Pre-SetDim1”,| “ExtendedCode”,| “StatusRqst“
TheinitializationsectioninitializestheLCDdisplay: ;Initialization ;--------------- Pause500 ;AllowstheLCDtoinitialize ;CleartheLCD LCDWRITERegSel\Clk,LCDNib,[INITLCD1,INITLCD2,| TWOLINE,CLEAR,HOME,SCRBLK] LineNo=1 LCDWriteRegSel\Clk,LCDNib,[ScrRAM+LineOFf(LineNo)] LCDWriteRegSel\Clk,LCDNib,[“P-20-07”] Pause2000 LCDWRITERegSel\Clk,LCDNib,[INITLCD1,INITLCD2,| TWOLINE,CLEAR,HOME,SCRBLK]
Sincewe’vepreviouslycoveredLCDinitializationinChapter5,wewillnotreviewtheaboveinitialization code,savetonotethatwedefinedthebytetableLineOff: LineOffByteTable$0,$0,$40,$14,$54
LineOff(LineNo)returnstheLCDRAMoffsettopositionthetexttostartattheleftedgeforlines1…4 (LineNo=1…4).LineOff(0)returnsadummyvalue,0,aslegitimatelinenumbersdonotinclude0.
EnableHSerial SetHSerialH115200 HSerOut[“P-20-07”,13] Pause500 InputB0 ;readzerocrossing InputB1 ;readdata
OldXPin=%0 j=0 i=0 RXStatus=Waiting
481
Chapter20 Theremainderoftheinitializationsectionestablishesinitialvaluesforseveralvariables.Inparticular,we usethesamediscretestatestructureinProgram20-7thatwedidinProgram20-6.Forthereasonsdiscussed earlier,therefore,weinitializethecontrolvariableRXStatustoWaiting. OurstrategyinProgram20-7mimicsProgram20-6iskeyrespects.Insteadofreadingasequenceofbytes, insteadherewemustreadasequenceofbitsfromtheTW523.Eachbitmustbereadimmediatelyafterthe zerocrossingpinchangesstate.Let’slookatouralgorithminpseudo-code. ReadZeroCrossingpin IfZeroCrossingPinchangesstate(0→1)or(1→0)Then ReadDataPin InvertDataPinValue(TW523outputhasinvertedlogic) Countnumberofconsecutive1’sreceived Ifthreeconsecutive1’sreceivedthe: itisastartsignal SetRXStatustoValidStart
IfRXStatus=ValidStart,savedatapinvalueinRcvdBit(i) Incrementiandtestvalueofi Ifi
IfRXBitLenbitshavebeenreceived,then: ChangeRXStatustoWaiting DecodethedataheldinRcvdBit() Gobackandwaitfornextzerocrossing
Let’sseehowweimplementthisalgorithm. ReadXPin ;------- ;readzero-crossingpinandwaitforachangeinvalue IfXPin=OldXPinThen GoToReadXPin EndIf
Wereadthevalueofthezerocrossingpinanddetectachangeinstatebycomparingthecurrentlyreadvalue (Xpin)withthelastreadvalue,heldinOldRXPin.Untilthezerocrossingpinchangesstate,theprogram remainsinatightloop,continuingtoreadandcomparethezerocrossingpinvalue.
;Haveazerocrossing,soreadthedatapinvalue OldXPin=XPin InVal=InPin ;TW-523has+5V=LOGIC0,soinvertby ;adding%1. InVal=InVal+1%
Whenthezerocrossingpinchangesstate,weupdatethe oldpinstatus(OldXPin)andreadthedatapin.Figure 20-16showsthereceiveddataoutputfromaTW523.The TW523’soutputisinvertedlogic;logic1inthePICworld isrepresentedasalowTW523output.Toinvertthedatapin reading,weadd%1totheresult.(%1+%1=0;%0+%1=%1) AsFigure20-16shows,theTW523maintainsitslogic1(low voltage)outputcommencingimmediatelyuponzerocrossing andholdsthevalueforapproximately1ms.Aswelearned earlier,theTW523consolidatesthemultipletonebursttransmissionsrequiredbytheX-10protocolintoonelogicoutput, Figure 20-16: TW523 Receiving; Ch1: Zero coincidentwiththezerocrossing. CrossingPin;Ch2:DataPin.
482
X-10HomeAutomation
;X10startbitpatternis1110.Thisisaunique ;pattern.Todetectit,wecountconsecutive1’s ;viaj=j+1.Resetj=0ifreadaninput0 IfInVal=%1Then j=j+1 Else j=0 EndIf
Aswelearnedearlierinthischapter,theX-10protocolstartseachdatasequencewithauniquestartingcode %1110.Todetectthisstartingcode,wecountconsecutivelogic1s,resettingthecounterjtozerowhenever logic0isreceived.
;GiventheValue/InvertedValueformatofX10 ;weonlyhave111patternatstartcode.Receiptof ;111givesj=3 Ifj=3Then RXStatus=ValidStart ;status=start i=0 j=0 EndIf
Uponreceiving%111,weassumeavalidstartcodeisreceived.(Actually,weshouldwaitandverifythatthe nextbitisa%0,butwe’lltakecareofthatwhenweverifythebitcomplements.)Whenreceived,wetoggle theRXStatustoValidStartandbegincapturingthereceivedbits. ;Afteravalidstart,wecapturethebitdatain ;thearrayRcvdBit.StorereceivedbitinRcvdBit(i) ;andbumpupthecounter(i). IfRXStatus=ValidStartThen RcvdBit(i)=InVal i=i+1 Ifi=RXBitLenThen ;checkforexactreceipt RXStatus=Waiting ;ifoverflowrestart GoSubDumpOutput ;anddumpoutput EndIf EndIf GoToReadXPin
Weknowthatavalidsequence—andthebitarrayRcvdBit—willcontain20bits: Start HouseCode S2 S3 H1 H1 H2 H2 H4 H4 x x x x x 1 0 x 0 1 2 3 4 5 6 7 S2andS3arethelasttwoofthefourstartbits Harehousecodebits Daredatabits Theoverscoreindicatesbitcomplement xIndicateseither1or0
H8 x 8
H8 x 9
D1 x 10
D1 x 11
D2 x 12
D2 x 13
D4 x 14
Data D4 x 15
D8 x 16
D8 x 17
D16 x 18
D16 x 19
ThelasttwostartbitsareincludedbecausewestartsavingreceivedbitsinRcvdBituponthethirdconsecutive%1.Thismeanswesavethelast2bitsofthe4-bitstartsequence. Whenwehavereceived20bits,wecallsubroutineDumpOutputtoupdatetheLCDandalsowritethedecodedinformationtotheserialport. DumpOutput ;-------- IfDataDump=%1Then Fork=0toRXBitLen-1 If(k=StartHouse)OR(k=StartData)Then HSerOut[“/“] EndIf HSerOut[BinRcvdBit(k),”“] Next
483
Chapter20
EndIf
HSerOut[13]
BysettingtheconstantDataDump(DataDumpCon%1),thebitsheldinRcvdBitwillbesenttotheserial port.Thiscanbeusefulwhendebugging.
HouseCode=0 DataCode=0 ValidDecode=Good ;Dataistransmittedas-sowecanperform ;paritychecktoseeifdataiscorrupted. Fork=2toRXBitLen-1Step2 ;Validcodesare%1%0and%0%1. ;Theseevaluateas%1inXOR ;invalidcodesare%1%1and%0%0. ;Theseevaluateas%0inXOR ;Ifbad,thensetValidDecodeerrorflag IfRcvdBit(k)XORRcvdBit(k+1)=0Then ValidDecode=Bad HSerOut[“BadDecodeatk=“,Deck\2,| “Bitsare“,iBinRcvdBit(k),”“,| iBinRcvdBit(k+1),13] EndIf Next
Wenowcomparethereceivedbitsandtheircomplementstoverifythatthereceiveddataisuncorrupted.In reality,thischeckisredundant,astheTW523’scircuitalsomakesthiscomparison.But,we’lluseitasaway ofdemonstratinghowtomakethecomplementcomparison. Theheartofthecodeistheexclusiveor,orXOR,functionwhichhasthefollowinglogictable: Input1 1 0 0 1 1 0
Input2 1 0
Ifinput1equalsinput2,theoutputis0;ifinput1andinput2arecomplementsofeachother,theoutput is1.Hence,totesttwoadjacentbitstoverifythattheyarecomplements,weusethetestIfRcvdBit(k) XORRcvdBit(k+1)=0ThenValidDecode=Bad. Iftheyarecomplements,thentheXORtestreturns1,andthesentinelvariableValidDecoderemainsequal toGood.IfValidDecodeequalsBad,thenanappropriateerrormessageisemitted.
IfValidDecode=GoodThen ;WeevaluateinLSBorder. Fork=0to3 HouseCode=HouseCode+| RcvdBit(2+k*2)*PowerTable(k) Next Fork=0to4 DataCode=DataCode+| RcvdBit(10+k*2)*PowerTable(k) Next
Wenowhaveknowngoodbits,andcomputethehousecodeanddatacodevalues,baseduponLSBfirstdata transmission.
;IfDataCode<16thenitisaunitcode IfDataCode<16Then ;HSerOut[StrHouseTable(HouseCode)\1,”-”,| DecUnitTable(DataCode)\2,”“] UnitVal=UnitTable(DataCode) EndIf
ByevaluatingthedataasLSBfirst,wecanusethe0…15and16…31divisionbetweenunitcodesandfunctioncodes.Thisdivisionisreplacedbyanodd/evenseparationwhenthedatacodeisevaluatedMSBfirst.
484
X-10HomeAutomation
Return
;nowevaluatedatacode. IfDataCode>=16Then HSerOut[StrHouseTable(HouseCode)\1,”-”,| DecUnitVal\2,”“] HSerOut[StrKeyName((DataCode-16)*13)\13,13] GoSubWriteToLCD UnitVal=99;99=FcnOnly,noUnitCode. EndIf EndIf
Wesendthereceiveddataouttheserialport,formattingitintoahousecode–unitcodeandfunctionname form.Displayingaunitcodeof99identifies“allcall”transmissions. Finally,weupdatetheLCD. WriteToLCD ;--------- ;NowputthesameinfototheLCD. LCDWriteRegSel\Clk,LCDNib,[ScrRAM+LineOFf(LineNo)] LCDWriteRegSel\Clk,LCDNib,[DecLineNo,”“,| StrHouseTable(HouseCode)\1,”-”,| DecUnitVal\2,”“,StrKeyName((DataCode-16)*13)\13] ;Addalinenumber LineNo=(LineNo+1) IfLineNo=5Then LineNo=1 EndIf Return
Wewritethedecodeddatatothenextavailableline,recyclingto line1afterfourlinesarewritten. Figure20-17showstheLCDdisplaywhenreceivingcommands sentbyProgram20-2. Thefollowingisarepresentativesampleoftheserialoutputof Program20-07whenreceivingcommandssentbyProgram20-2. TransmittingProgram20-02Output L-16 L-16 L-16 L-16 L-16 L-16 M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-ALL M-01 M-01 M-01 M-01
Pre-SetDim0 Status=Off ExtendedData Status=On Pre-setDim1 StatusRqst AllUnitsOff AllLghtsOn On Off Dim Bright AllLghtsOff ExtendedCode HailRequest HailAcknldge Pre-SetDim0 Status=Off ExtendedData Status=On Pre-setDim1 StatusRqst AllUnitsOff AllLghtsOn On Off
Figure 20-17: LCD output displaying Program20-7results.
ReceivingProgram20-07Output L-16Pre-SetDim0 L-16Pre-SetDim1 L-16ExtDta-Analg L-16Status=On L-16Status=Off L-16StatusRqst M-99AllUnitsOff M-99AllLghtsOn M-99On M-99Off M-99Dim M-99Bright M-99AllLghtsOff M-99ExtendedCode M-99HailRequest M-99HailAcknldge M-99Pre-SetDim0 M-99Pre-SetDim1 M-99ExtDta-Analg M-99Status=On M-99Status=Off M-99StatusRqst M-01AllUnitsOff M-01AllLghtsOn M-01On M-01Off
485
Chapter20 RangeProblems DuringthecourseofexperimentingwithtwoTW523’s,Idiscoveredthathighqualitypowerstrips,identifiedas“filtered”or“protected”containinterferencereducingfiltercomponentsthatattenuatethe120KHz burstsandthereforereducethepossiblerange.Formaximumrange,plugboththeTW523andanyreceiving modulesdirectlyintothewallsocketanddon’tuseapowerstrip. AsecondrangeproblemoftenobservedwithX-10isduetothewaypowerisdistributedinsidearesidence. Figure20-18showsatypicalUSresidentialwiringarrangement.UnitsAandBareX-10receivers.The TW523isononelegofthepowerdistributionline,anditssignalscancrossovertotheotherlegonlyby passingthroughappliancesthatareconnectedtothe240Vline,thatis,tobothhotcircuits.Inmanycases, theseapplianceswillleakenough120KHzenergythrough,evenwhenturnedoff,topermitdecodingwith modulesconnectedoneither120Vleg.Myhousehadinsufficientleakagebetweenthetwopowerlines towork.IfyouexperiencethisproblemyoucanpurchaseanX-10signalbridgethatcouplesthe120KHz burstsignalsbetweenbothsidesofyourhousewiring.
A
120V
Signal Bridge Neutral Safety_Ground Safety_Ground Neutral
240V
120V
TW523
Hot
B
Hot
Figure20-18:X-10Powerdistributionissues.
References [20-1]
Rye,Dave,TechnicalNote,TheX-10POWERHOUSEPowerLineInterfaceModel#PL513and Two-WayPowerLineInterfaceModel#TW523,Rev.2.4,X-10Powerhouse(undated).Availablefor downloadathttp://www.x10.com/support/support_manuals.htm. [20-2] Davidson,Ken,TheX-10TW523Two-WayPowerLineInterface,CircuitCellarInk,No.5,September/ October1988.Availablefordownloadathttp://www.circuitcellar.com/library/print/hcs-pdf/5-Davidson. pdf. [20-3] Davidson,Ken,Power-LineBasedComputerControl,CircuitCellarInk,No.3,May/June1988.Availablefordownloadathttp://www.circuitcellar.com/library/print/hcs-pdf/3-Davidson.pdf. [20-4] Moews,PaulandMoews,David,TheX-10Spy;MakingX-10SignalsVisible,CircuitCellarInk,No. 63,October1995.Availablefordownloadathttp://www.circuitcellar.com/library/print/hcs-pdf/63moews.pdf.
486
21
CHAPTER
DigitalPotentiometers andControllableFilter Digitalpotentiometers(usuallycalleda“pot”inelectronicsspeak)areasolid-statereplacementformechanicallyadjustablevariableresistorshistoricallyusedforvolume,balanceandtonecontrolsinconsumer electronics,amongmanyotherapplications.Insteadofrespondingtoshaftrotation,digitalpotschangetheir value—inmicroseconds—baseduponareceivedcommandmessage. Digitalpotsareofferedinavarietyofcontrolinterfaces,including1-wire,contactclosure(up/downsteps), parallel,increment/decrement,SPI(3-wire)andothers.Someevenincludenonvolatilememorytoretain theirlastsettingwhenpowerisremoved.We’lllookatMicrochip’sMCP41xxx/42xxxfamilyofdigitalpots, withanSPIinterface.Othermanufacturers,suchasMaxim(includingitsDallasSemiconductordivision), havewiderproductranges,andyoushouldreviewtheirofferingsifyouthinkdigitalpotentiometersmaybe usefulinyourparticularproject. First,let’sclearuptheterminology.Thedevicewearetalkingaboutisknownasapotentiometer,avariable resistor,arheostatoravolumecontrol,amongmanyotherterms.Inreality,thesetermscanbeboileddown intotwopossibleconnectionarrangements,asshowninFigure21-1.Thepotentiometerarrangementuses allthreeconnectionsandisusuallyconfiguredasavariablevoltagedivider.Thevariableresistororrheostat arrangementusestwoconnections(thewiper—thevariableconnectingpiece—isconnectedtooneendofthe fixedwinding,buttotheexternalcircuitonly twoconnectionsareseen)andoperatesasa variableresistance.We’llusetheterm“pots” asthegenericnameforthesedevices,even thoughtheymaybeconnected,incertain applications,asvariableresistors. Onemajordifferencebetweenmechanical anddigitalpotsisresolution.Mechanical potsvarycontinuouslywithshaftrotation, orinthecaseofsomewirewounddesigns, haveverysmalljumpsinvaluewithrotation.Digitalpots,incontrast,aremore accuratelythoughofasastringofresistors withanelectronicswitch,asillustrated inFigure21-2.Consequently,theirvalue movesinsteps.TheMCP42xxx/41xxx deviceshave256steps.Rxisresidual resistance,andRwcanbethoughtofasthe resistanceofthe“wiper”connection.For Figure 21-1: Potentiometer versus variable resistor (Rheostat) connection. Microchip’sMCP41xxx/42xxxdevices, 487
Chapter21 theparasiticresistancefromterminalAincludes oneresistancestepaswell,thatis,thewiperwill neverconnectdirectlytoterminalA. FortheMCP41xxx/42xxxdevices,theresistance betweenterminalsA,Bandthewiperandthe commandstepDn(neglectingparasiticresistance Rx)is: Dn + RW 256 256 − Dn = RAB + RW 256
RBW = RAB
RAW
where: Dnisthecommandstep,withpossiblevalues0…255. RBWistheresistancebetweenterminalsB andthewiper RAWistheresistancebetweenterminalsA andthewiper RABistheresistancebetweenterminalsA andB. TheMCP41xxx/42xxxfamilyconsistsofsixdevices,withthedeviceIDidentifyingthenumber ofsections(1or2)andthenominalresistance(in Figure21-2:Conceptualmodelofdigitalpotentiometer. Kohm,010,050or100).
DeviceID MCP41010 MCP41050 MCP41100 MCP42010 MCP42050 MCP42100
Numberof Independent Sections 1 1 1 2 2 2
ResistanceRAB 10Kohm 50Kohm 100Kohm 10Kohm 50Kohm 100Kohm
Singledevices,typeMCP41xxx,haveonepotentiometer.Dualdevices,typeMCP42xxx,havetwoindependentpotentiometers,identifiedasP0andP1,withcommoncontrollogicandpowersupply. Let’slookatthegoodandbadpointsofdigitalversusmechanicalpots. ComparisonPoint Lifetime
Digital Essentiallyinfinite.
Mechanical Limitedbynumberofshaftrotationsand construction.Rangesfromafewhundred cyclestohundredsofthousandsofcycles.
(Continued)
488
DigitalPotentiometersandControllableFilter ComparisonPoint Reliability;environmental
Resistancerangesavailable Powerhandling Speedofresponse Remotecontrolability
Digital Excellentwhenoperatedwithin specifications;hermeticallysealed. Limited;veryhighandverylow valuesnotavailable. Verylimited;dissipationlimitedtoa fewmilliwatts;maximumpermitted currenttypically1mA. Excellent;microsecondorfaster. Excellent,smallpackagewithdirect microprocessorconnection.
Mechanical Good,butcanbecomenoisyand someconstructiontypescanbecome contaminatedwhenoperatedinharsh environments. Widerangeofvaluesavailablefrom1ohm to10megohms. Widerangeavailable,includingpower rheostatsratedintotheKilowattrange. Limitedbymechanicalconsiderations. Canbemotordriven,butlargevolume results. Highlinearity(0.1%)available,butata premiumprice.
Linearity
Verygood,wellunder1%.
VoltageRating
Can’texceedthesupplyvoltages (VDDandVSS)ofthedevice.
Limitedonlybytheinsulationused.
FrequencyResponse
Lessthan1MHzfor10K;lessthan 145KHzfor100Kdevices.
Limitedbystraycapacitanceand inductance;caneasilyexceed10MHzfor carbonorconductiveplasticdevices.
DistortionandIntermodulation
Notspecified;butRwisanonlinear functionofappliedvoltage.
Essentiallyzero.
Shockandvibrationresistance
Excellent.
TemperatureCoefficient
Approx.±800PPM/ºC.
Resolution
Typically100,256,512or1024 steps.
TaperAvailable NominalResistanceAccuracy
Linear. Typically±20–30%.
Moderate;mayrequireshaftlocksto preventinadvertentrotation. Canbeasgoodas±100PPM/ºCin premiumunits. Theoreticallyunlimitedinmostdesigns,but inpracticelimitedbyfrictionandbacklash. Wirewoundsingleturnpotshavejumpsas thewipermovesfromwiretowire. Linear,log,reverselog. Typically±10–25%.
Now,it’stimetolookatsomecode. We’veusedthethree-wire,orSPI,protocoltoreadtheDS1302real-timeclockin Chapter12,sowewon’trepeattheintroductorymaterialappearinginthatchapter.
GettingStartedwithan MCP41010 Ourinitialtestconfigurationusesa MCP41010,asinglesection10Kdevice, connectedasillustratedinFigure21-3. Program21-1exercisesthepotentiometer byrunningitthroughallpossible256 states. Figure21-3:ConnectinganMCP41010.
489
Chapter21 Program21-1 ;Program21-1 ;ControlaMCP41010 ;Digitalpotentiometer ;Constants ;----------Clk Dta CSel
Con Con Con
A0 A1 A2
Cmd_NOP Cmd_Write Cmd_ShutDn
Con Con Con
%00000000 %00010011 %00100011
;Variablesw ;----------i Var
Byte
;Clock ;Data ;ChipSelect
;loopvar
;Initialization ;-------------OutputCSel LowCSel Main End
Fori=0to255 LowCSel ShiftOutDta,Clk,MSBPre,[Cmd_Write\8,i\8] HighCSel Next GoToMain
SimilartotheDS1302real-timeclock,thecommandsyntaxfortheMCP42xxx/41xxxchipsisacommand byte,followedbyaninstructionbyte. ThekeystatementinProgram21-1isShiftOutDta,Clk,MSBPre,[Cmd_Write\8,i\8].Itsendstwo sequentialbytestotheMCP41010;theconstantCmd_Write,followedbythestepinstruction,i. Thepossiblecommandbytesareillustratedbelow. Bit7 X
Bit6 X
Bit5 C1
MCP42xxx/41xxxCommandByte Bit4 Bit3 C0 X
Bit2 X
Bit1 P1
Bit0 P0
Xis“don’tcare”andmaybeeithera0or1. BitsC1andC0selectthecommandtobeexecuted,whileP1andP0selectthepotentiometertowhichthe commandistobeapplied. C1 0
C0 0
0
1
1
0
1
1
CommandSelectionBits Command CommandSummary None Nocommandexecuted. Writethedatacontainedintheinstructionbytetothe WriteData potentiometer(s)selectedbytheselectionbits. Potentiometer(s)selectedbytheselectionbitsenter Shutdown shutdownmode.Databitsforthismodeare“don’t care.” None Nocommandexecuted.
490
DigitalPotentiometersandControllableFilter PotentiometerSelectionBits P0 PotentiometerSelections Dummycode;neitherpotentiometeris 0 affected. 1 CommandexecutedonP0. 0 CommandexecutedonP1. 1 CommandexecutedonbothP0andP1.
P1 0 0 1 1
Sinceweareusingasinglesectiondevice,thepotentiometerselectionbitsP0andP1are“don’tcare.”We’ll setthemto%11. WhendealingwithanMCP41xxxdevice,wehaveonlytwousefulcommands;writeastepvalueandshut down,andathirddummycommand“donothing”thatwe’lllaterseeisnecessarywhenwedaisychain multipleMCP42xxxdevices: Cmd_NOP Cmd_Write Cmd_ShutDn
Con Con Con
%00000000 %00010011 %00100011
Wehaveaccordinglydefinedthethreepossiblecommandbytesasconstants. Let’stakeaquicklookatwhatthesecommandbytesdo. Cmd_NOP—A“nooperation”ordummycommand.Whenreceived,thedevicetakesnoaction.Allpreviousvaluesareretainedwithoutchange. Cmd_Write—Instructsthedevicetosetthetapsettingtotheimmediatelyfollowingbytevalue. Cmd_ShutDn—Instructsthedevicetoentershutdownmode.AsillustratedinFigure21-2,uponashutdown instruction,terminalAisdisconnectedfromtheresistivedividerstringandthewiperconnectionisconnecteddirectlytoterminalB. OnefinalpointregardingouruseoftheShiftOutstatementconcernsselectingthepropermodeconstant. AswesawinChapter12,theDS1302’sreadandwriteprotocolisLSBfirst,andbitsamplebeforetheclock pulse.HenceweusethemodeLSBPREoritsaliasLSBFIRST.TheMCP42xxx/41xxx’sdatasheet(Section 5.8)tellsusthatdataissentMSBfirstandthatthedatashouldbesetbeforetheclockpulse.Hence,thecorrectmodeforaShiftOutstatementisMSBPRE.Ifyoudon’tunderstandwhythisisthecase,comparethe datatransferdiagramsfortheDS1302andtheMCP42xxx/41xxxdevicesfromtheirrespectivedatasheets. AfinalreminderofSPIfunctionalityisthatdatamaybewrittenonlywhentheMCP42xxx/41xxx’schip selectpinishigh.Thecommandanddatathenbecomesactivewhenthechipselectpindropslow. Thedatabytesetsthewiperatthepositiondefinedbythebytevalue.Let’sseehowthatworksinpractice. SupposewesendthecommandbyteCmd_Writefollowedbytheinstructionbyte,Dn,123.Whenthechip selectlinegoeshigh,thepotwipergoestoposition123.SincethenominalresistanceRABforaMCP41010 chipis10Kohm,wecancalculatetheresultingnominalresistancebetweenthewiperandterminalsAandB: Dn 123 + RW = 10 × 103 + 52 = 4, 857Ω 256 256 256 − Dn 256 − 123 = RAB + RW = 10 × 103 + 52 = 5, 247Ω 256 256
RBW = RAB
RAW We’veusedtheword“nominal”asthe10KohmRABvaluemaybeaslowas8Kohmorashighas12Kohm andremainwithinspecification.Thegoodnewsisthatwearelessoftenconcernedwiththeprecisevalues RAB,RAWorRBWthanwearewiththeaccuracyoftherelativesteps.AndinthisregardtheMCP42xxx/41xxx devicesareexcellent,withatypicalrelativeaccuracyerrorof±0.25LSB. 491
Chapter21 OurcircuitshowninFigure21-3connectsVDDtoterminalA,ground(VSS)toterminalBandusesthewiper astheoutputconnection.SinceVDDis5V,thisgivesanunloadedcurrentthroughtheresistorstringRABof 0.5mA,wellwithinitspowerandcurrentrating. Ifweattachthewipertoahighimpedancedevice,suchasadigital voltmeter,oranoscilloscopeprobe,thevoltageoutputatthewiper willbedirectlyproportionaltotheinstructionword,withoutregard forerrorinthenominalRABresistancevalue.Figure21-4shows theequivalentcircuit.Wecancalculatethevoltagemeasuredbythe DVMbygoingthroughthecompletecircuitequationsorwecan applysomecommonsensesimplificationrules: First,RWandR4,theresistanceoftheDVMareinseries.RWis 52ohms,whichisnegligiblecomparedwiththeDVM’s10M ohmimpedance.Hence,we’llignoreRW. Figure 21-4: Equivalent Circuit Voltage
Second,R1cannotexceedabout10Kohm.R1isinparallelwith Divider. R4,10Mohm.SinceR4is1,000timeslargerthanR1,wecan ignorethecurrentthroughR4.
Hence,thecircuitreducestosimplyR1inserieswithR2,withtheoutputvoltagemeasuredatthemidpoint. Thisisaclassicvoltagedividerandtheoutputvoltageis: R1 Vout = Vin R 1 + R2 Inourcircuit,VINisVDDandwenotethatR1/(R1+R2)issimplytheratioofRB/(RA+RB).Afterabitofalgebra,wefindthat: D Vout = Vin n 256 Hence,theoutputvoltageisDnmultipliedbyaconstantfactor,Vin/256,orforVin5.0volts,19.531mV/step. Ifweworkthroughadetailedcircuitanalysisoftheeffectofthesetwoshortcuts,itturnsouttheerrorisless than10microvolts,quiteacceptableconsideringothersourcesoferror. Main End
Fori=0to255 LowCSel ShiftOutDta,Clk,MSBPre,[Cmd_Write\8,i\8] HighCSel Next GoToMain
Thecodewillthusgenerateavoltageoutputthatgoesfrom 0Vtojustunder5V,instepsof19.5mV.Figure21-5shows theresultisasexpected,witheachsteptakingabout560µs. GrossdeviationfromlinearityintheMCP41010output willshowupasbendsorkinksinthewaveform,andnone arevisible.Bytheway,ifFigure21-5remindsyouofa digital-to-analogconverteroutput,youarequitecorrect;as configuredinFigure21-3,theMCP41010isavoltage-output DAC. Figure21-5:LinearvoltagesweepoutputCh1: N/ACh2:wiper.
492
DigitalPotentiometersandControllableFilter
RS-232ControlofanMCP41010 Program21-1givesusconfidenceincontrollingaMCP41010,butitdoesn’treallydomuch.Let’strysomethingabitmorecomplex—commandinganMCP41010bytheRS-232serialport.Ourcommandsyntaxis simple: Command Snnn(orsnnn) S?(ors?) X(orx)
Function Setthepotentiometertovaluennn Respondbysendingthecurrentsettingvalue Shutdownthepotentiometer
Program21-2 ;Program21-2 ;ControlaMCP41010 ;Digitalpotentiometer ;RS-232Command ;Constants ;----------Clk Con A0 Dta Con A1 CSel Con A2 ArraySize Con 6 MultiplierByteTable100,10,1
;Clock ;Data ;ChipSelect ;sizeofinstring
Cmd_NOP Cmd_Write Cmd_ShutDn
Con Con Con
%00000000 %00010011 %00100011
;Nooperation ;writevalue ;executeshutdown
;Variables ;----------i j InStr WorkStr Setting Temp CmdByte
Var Var Var Var Var Var Var
Byte ;loopvar Byte ;incrementcounter Byte(ArraySize) Byte(ArraySize) Byte ;PotSetting Word ;tempinstringvalue Byte ;commandsenttopot
;Initialization ;-------------EnableHSerial SetHSerialH19200 HSerOut[“Set/ReadDigitalPotentiometer”,13] Setting=0 ;initializeat0level OutputCSel LowCSel GoSubWriteSetting Main ;----------- ;Reminduserofcommands GoSubSendPrompt InStr=““ ;keyon10,not13.Assumessending***CR&LF*** ;Otherwise,inputterminateson13,andthe ;10appearsasleading ;characterinthenextstring. HSerIn[StrInStr\ArraySize\10] ;testforSettingcommand If(InStr(0)=“S”)OR(InStr(0)=“s”)Then GoSubDispatcher ;seewhattypeofScommand EndIf
493
Chapter21 ;TestforShutdowncommand If(InStr(0)=“X”)OR(InStr(0)=“x”)Then Setting=$00 ;dummyvalue CmdByte=Cmd_ShutDn ;shutitdown GoSubWriteSetting ;sendtothepot EndIf GoToMain SendPrompt ;sendpromptstring ;------------- HSerOut[“S?toReadValueSxxxtoSetValue;Xforshutdown”,13] Return WriteSetting ;writetodigitalpot ;------------- LowCSel ;enablewriting ShiftOutDta,Clk,MSBPre,[CmdByte\8,Setting\8] HighCSel ;disablewriting ;Respondtouserwithmessage ;Normalcommand IfCmdByte=Cmd_WriteThen HSerOut[“Setto“,DEC4Setting,13,13] EndIf ;Shutdowncommand IfCmdByte=Cmd_ShutDnThen HSerOut[“ShutdownExecuted”,13,13] EndIf Return Dispatcher ;gethereonlyiffirstcharis“S”or“s” ;------------ ;Nowlookatthesecondcharacter ;If?thenreportcurrentsetting IfInStr(1)=“?”Then GoSubReportSetting EndIf ;Ifnot?andifanumericvalue,itmustbeacommand If(InStr(1)>=“0”)AND(InStr(1)<=“9”)Then GoSubGetSetting EndIf Return ReportSetting ;outputthecurrentsetting ;----------- HSerOut[“CurrentSetting“,DEC4Setting,13] Return GetSetting ;parsetheRS-232inputintonumericaldata ;----------- ;andsendittothedigitalpot ;rightsetdatainWorkStrsowantall0’sinunusedplaces WorkStr=“000000” j=ArraySize-1 i=ArraySize-1 ;putonlythenumbersintoWorkStr,rightset ;readtheinputstringrtolkeepingonlydigits0...9 ;putthesedigitsrightsetintoWorkStr While(i>0) If(InStr(i)>=“0”)AND(InStr(i)<=“9”)Then Then WorkStr(j)=InStr(i) j=j-1 EndIf i=i-1 WEnd ;converttonumeric.ValueofdigitisitsASCII-“0”
494
DigitalPotentiometersandControllableFilter Return
Temp=0 Fori=(ArraySize-1)to(ArraySize-3)Step-1 Temp=Temp+Multiplier(i-3)*(WorkStr(i)-”0”) Next ;Ifoutofrange,setitto255 IfTemp>255Then GoSubErrorMsg Temp=255 EndIf ;Writethevaluetothepot Setting=Temp CmdByte=Cmd_Write GoSubWriteSetting
ErrorMsg ;---------- HSerOut[“Error!Setvalueto255”,13] Return End
AlmostallthenewcodeinProgram21-2relatestoactinguponthereceivedRS-232commands.Let’sfirst examinethemainprogramloopcode. Main ;----------- GoSubSendPrompt InStr=““ HSerIn[StrInStr\ArraySize\10] If(InStr(0)=“S”)OR(InStr(0)=“s”)Then GoSubDispatcher ;seewhattypeofScommand EndIf If(InStr(0)=“X”)OR(InStr(0)=“x”)Then Setting=$00 ;dummyvalue CmdByte=Cmd_ShutDn ;shutitdown GoSubWriteSetting ;sendtothepot EndIf GoToMain
Aftersendingthepromptmessage,wecleartheinputstring,InStr,bysettingittoallblanks.(InStris abytearrayoflengthArraySize,declaredintheVariablessectionofProgram21-2.)Wethenreadthe RS-232inputintoInStr,terminatingthereadwheneither(a)ArraySizenumberofcharactershasbeen received,or(b)thelinefeedcharacter(decimalvalue10)hasbeenreceived. Aftertheinputlineisfinished,wethencheckthefirstlettertoseewhatactionistobetaken.IfthefirstcharacterofInStrisan“S”or“s,”theactionistosetthepotentiometervalue,sowebranchexecutiontothe subroutineDispatcher.Ifthefirstcharacteris“X”or“x,”wesetthecommandbytetotheshutdowncode andsendittotheMCP41010viatheWriteSettingsubroutine. Ifneitherthesettingnortheshutdowncommandhasbeenreceived,nocommandissenttotheMCP41010. ThesubroutineDispatchersimplydetermineswhetherthe“S”commandisforinformation(S?)orisa commandthatachangedvalueshouldbewrittentotheMCP41010(Snnnwherenisadigit0...9). Dispatcher ;gethereonlyiffirstcharis“S”or“s” ;------------ ;Nowlookatthesecondcharacter ;If?thenreportcurrentsetting IfInStr(1)=“?”Then GoSubReportSetting EndIf ;Ifnot?andifanumericvalue,itmustbeacommand If(InStr(1)>=“0”)AND(InStr(1)<=“9”)Then
495
Chapter21 EndIf Return
GoSubGetSetting
Wedifferentiatebetweenthetwosimplybylookingatthesecondreceivedcharacter.Ifitisa“?”thesubroutineReportSettingrespondswiththecurrentsettingvalue.Ifitisacharacterintherange“0”...”9,” thenweconverttheinputstringtoanumericalvalueinthesubroutineGetSetting. GetSetting ;parsetheRS-232inputintonumericaldata ;----------- ;andsendittothedigitalpot ;rightsetdatainWorkStrsowantall0’sinunusedplaces WorkStr=“000000” j=ArraySize-1 i=ArraySize-1 ;putonlythenumbersintoWorkStr,rightset ;readtheinputstringrtolkeepingonlydigits0...9 ;putthesedigitsrightsetintoWorkStr While(i>0) If(InStr(i)>=“0”)AND(InStr(i)<=“9”)Then Then WorkStr(j)=InStr(i) j=j-1 EndIf i=i-1 WEnd
PossibleinputstringstosettheMCP41010tothevalue5are“S5,”“S05”and“S005.”Anyofthesearelegitimateinputsshouldgivethecorrectsetting.Thefirststepinaccomplishingthistaskistoplacethedigits inInStrfollowingthe“S”intoanewbytearray,WorkStr,right-justified,withallotherdigitsinWorkStrbeingzeros.Thus,S5,S05andS005allyieldaWorkStrvalueof000005.Torightjustify,wesimply readInStronebyteatatime,right-to-left,placingthereadbyteintoWorkStr,startingwiththerightmost position.AssoonaswecometoacharacterinInStrthatisnot“0”...“9,”westop. Next,weconverttherightjustifiedcharacterstringinWorkStrintoanumericalvalue.
Temp=0 Fori=(ArraySize-1)to(ArraySize-3)Step-1 Temp=Temp+Multiplier(i-3)*(WorkStr(i)-”0”) Next
WerememberthatthenumericalvaluesoftheASCIIcharacters“0”...”9”areindirectsequence,48...57. Hence,toconvertanumericalcharactertoitsnumericvalue,wesimplysubtract48.Tobeevenclearer, MBasicletsususethecharacter“0”inamathematicalexpressionandevaluatesitasitsnumericalvalue, 48.Hence,toconvertanindividualdigitcharactertoitsnumericalvalue,wesimplysubtract“0”fromit. SinceWorkStrhastherightjustifiedstringvalue,andallunusedelementsaresetto“0”allwehavetodo toconverttothenumericalvalueismultiplytherightmostdigitvalueby1,thenextby10andthethirdby 100andsumthetotal.ThisisefficientlyaccomplishedwithaForiloop.(Weconstructedthebytetable Multiplierearlieras100,10,0.) YoumaywonderwhywemadeWorkStrsixelements,whenthreewouldhavebeensufficient.ThesubroutineGetSettingiscodethatIusefrequently,sometimestoreadlongerinputstrings,soratherthanmodify itforeachapplication,Iemployitintact.
;Ifoutofrange,setitto255 IfTemp>255Then GoSubErrorMsg Temp=255 EndIf ;Writethevaluetothepot Setting=Temp CmdByte=Cmd_Write
496
DigitalPotentiometersandControllableFilter GoSubWriteSetting Return
NextGetSettingtrapsforvaluesabovethemaximumsettingof255andsetsthevalue,inthiscase,to 255.(Youmayinsteadchangethecodetorejectthesettingandsendanerrormessage.)Lastly,GetSetting sendsthesettingvaluetotheMCP41010throughasubroutinecalltoWriteSetting. WriteSetting ;writetodigitalpot ;------------- LowCSel ;enablewriting ShiftOutDta,Clk,MSBPre,[CmdByte\8,Setting\8] HighCSel ;disablewriting ;Respondtouserwithmessage ;Normalcommand IfCmdByte=Cmd_WriteThen HSerOut[“Setto“,DEC4Setting,13,13] EndIf ;Shutdowncommand IfCmdByte=Cmd_ShutDnThen HSerOut[“ShutdownExecuted”,13,13] EndIf Return
ThesubroutineWriteSettingimplementsthesamefunctionalitywesawinProgram21-1,addingonlythe reportinginformationsenttotheserialport. Here’satypicalcommandinteractionwithProgram21-2.SinceProgram21-2doesnotechobackthesent characters,toseewhatyouaresendingyoumustenable“localecho”inyourterminalprogram.Forclarity, I’veshowninboldthecommandsIsenttoProgram21-2,whilenormalcharactersshowtheresponseby Program21-2.CommentsI’veaddedafterwardareindicatedbythe←symbol. Set/ReadDigitalPotentiometer S?toReadValueSxxxtoSetValue;Xforshutdown S? CurrentSetting0 S?toReadValueSxxxtoSetValue;Xforshutdown s123 Setto123 S?toReadValueSxxxtoSetValue;Xforshutdown s? CurrentSetting123 S?toReadValueSxxxtoSetValue;Xforshutdown S999 Error!Setvalueto255 Setto255
←whatisthecurrentsetting?
←setthepotto123withlowercases123
←whatisthecurrentsetting?
←trysettingtoillegalvalue999
S?toReadValueSxxxtoSetValue;Xforshutdown S? CurrentSetting255 S?toReadValueSxxxtoSetValue;Xforshutdown S5 Setto5
←whatisthecurrentsetting
←trythreealternatewaysofsettingto5 ←S5isacceptedcorrectly
S?toReadValueSxxxtoSetValue;Xforshutdown S05 Setto5
←S05isacceptedcorrectly
←S005isalsoacceptedcorrectly
S?toReadValueSxxxtoSetValue;Xforshutdown S005 Setto5
497
Chapter21 S?toReadValueSxxxtoSetValue;Xforshutdown X ShutdownExecuted S?toReadValueSxxxtoSetValue;Xforshutdown s? CurrentSetting0 S?toReadValueSxxxtoSetValue;Xforshutdown s123 Setto123
←shutdowncommand
←shutdownreadsas0
←exitshutdownbysettingtoanything
S?toReadValueSxxxtoSetValue;Xforshutdown
TheremainderofthesubroutinesinProgram21-2willnotbefurtheranalyzed.
DaisyChainingMultipleMCP42010Devices Let’sseehowweextendourcontroltomultipledual-potdevices,suchastheMCP42010,connectedas showninFigure21-6.OurexampleusestwoMCP42010’swiththedataconnectionsinseries,buttheconceptcanbeextendedindefinitely. We’llstartwithaverysimpleprogramtotestourabilitytowritedatatomultipleMCP42010devices.We’ll writeanupwardsteppedlinearoutputintobothpots0and1ofU1andadownwardsteppedlinearoutput intobothpots0and1ofU2.
Figure21-6:TwoMCP42010deviceswithdaisy-chaineddataconnection.
Program21-3 ;Program21-3 ;ControltwoMCP42010 ;Digitalpotentiometerintandem ;Constants ;----------Clk Dta
Con Con
A0 A1
;Clock ;Data
498
DigitalPotentiometersandControllableFilter CSel
Con
A2
;ChipSelect
Cmd_None Cmd_WriteData Cmd_ShutDown Cmd_None1
Con Con Con Con
%00000000 %00010000 %00100000 %00110000
Cmd_Dummy Cmd_P0 Cmd_P1 Cmd_Both
Con Con Con Con
%00000000 %00000001 %00000010 %00000011
;Variables ;----------i Temp U1_Cmd Var U2_Cmd Var U1_InstVar U2_InstVar
Var Var Byte Byte Byte Byte
Byte ;loopvar Byte ;CommandforU1 ;InstuctionforU2 ;CommandforU1 ;InstructionforU2
;Initialization ;-------------OutputCSel LowCSel Main End
U1_Cmd=Cmd_WriteData+Cmd_Both U2_Cmd=Cmd_WriteData+Cmd_Both Fori=0to255 U1_Inst=i U2_Inst=255-i LowCSel ;Push2ndchipdatafirst ShiftOutDta,Clk,MSBPre,[U2_Cmd\8,U2_Inst\8| ,U1_Cmd\8,U1_Inst\8] HighCSel Next GoToMain
Withtheexceptionofhowwewritedatatotwo chips,Program12-3requiresnoelaboration. TheMCP42xxxseriesdevices(butnotthe MCP41xxxseries)have“shiftin”and“shift out”pins.Shiftin(SI),aswe’veseen,isthe datainputtothedevice.Whatthenis“shift out”(SO)andhowmightitbeused?Shiftout simplyrepeatstheinputdata,butdelayed,or shifted,by16bits.Let’slookatthisinmore detailinconjunctionwithFigure21-7. UpontakingtheCSlinelow,theinternal16bitbufferinbothU1andU2iscleared,that is,setto0s.Wethensendthecommandbyte andinstructionbyteforU2toU1.Aseachbit ofU2’scommandandinstructionbytesare clockedintoU1’sSIpin,thebitsareplaced intoU1’sbufferandthebitspreviouslyin
Figure21-7:Daisy-chainedMCP42010s.
499
Chapter21 U1’sbufferareemittedfromU1’sSOpin.Sincetheseareall0’s,U2receives160bits.(LikewiseU2emits 160bitsfromitsSOpinaswell,butsincewehavenoU3device,thesebitsremainunused.However,more MCP42xxxdevicesmaybedaisychainedfromU2.) Afterthefirst16bitsaresent,U1’sbufferholdsU2’sinstructions,andU2’sbufferisfilledwithzeros.Next, stillkeepingtheCSlinelow,wesendU1’sinstructionstoU1.Asthe16bitsofU1’sinstructionsarriveat U1’sSIpin,thebitsheldinitsbuffer(U2’sinstructionsthatwejustsent)areshiftedoutofU1’sSOpininto U2’sSIpin,andconsequentlyarereadintoU2’sbuffer. AftersendingthelastbitofU1’sinstructions,wetaketheCSlinehigh.Atthispoint,U1’sbuffercontains U1’sinformationandU2’sbuffercontainsU2’sinformation. TakingtheCSlinehighlatchestheinformationintheirrespectivebuffersintoU1andU2andeachdevice takestheactionscorrespondingtothereceivedcommandbyteandinstructionbyte. Thus,whenwedaisychainthedevicestogether,wesendthedatainreverseofthedeviceconnections;informationforthelastdeviceissentfirstandinformationforthefirstdeviceissentlast.Abitofreflectionand studyofFigure21-7shouldmakethelogicobvious.Toverifythisoperation,let’slookatthedatagoinginto U1’sSIpinandthedataoutofU1’sSOpin.Figure21-8showsfourbytesofdataintoU1’sSIpin.Figure21-9 showsthefirsttwobytesoutputfromU1’sSOpinarezeros,followedbytwobytesofnonzeroinformation. (Youcan’tdirectlycomparethedatabitsbetweenFigures21-8and21-9astheyweretakenatdifferenttimes.)
Figure 21-8: Input Data to U1’s SI Pin; Ch1: Clock;Ch2:SIPinData.
Figure21-9:OutputDatafromU1’sSOPin;Ch1: Clock;Ch2:SOPinData.
Microchip’sSI/SOdesignmakeitpossibleto individuallyaddressmultipleSPIdevices,without requiringeachonetohaveauniqueaddress(aswe sawinChapter12for1-wirechips),usingnomore thanthreewiresforcommunications,regardlessofthe numberofdevicesbeingcontrolled.
Figure21-10:TwoMCP42010DevicesinDaisy Chain;Ch1:U2,P1Wiper;Ch2:U1P1Wiper.
500
DigitalPotentiometersandControllableFilter Fori=0to255 U1_Inst=i U2_Inst=255-i LowCSel ShiftOutDta,Clk,MSBPre,[U2_Cmd\8,U2_Inst\8,U1_Cmd\8,U1_Inst\8] HighCSel Next
Aswe’vejustseen,whenwewritedatatoU1andU2withtheabovestatement,wefirstsendU2’scommand andinstructionbytes,followedbyU1’scommandandinstructionbytes.We’vesetU1tolinearlyrampup (i)andU2(255-i)tolinearlyrampdown,andFigure21-10matchesourexpectations.
RS-232CommandofMultipleDaisyChainedMCP42010Devices Let’snowmergeourtwoMCP42010daisychainwithanexpandedversionofProgram21-2’sRS-232controltogiveusindependentcontrolofallfourpots. OurcommandsyntaxisexpandedfromthatofProgram21-4.First,weidentifyeachofthefourpotswithan IDletter: IDLetter Aora Borb Corc Dord
PotUnit U1,P0 U1,P1 U2,P0 U2,P1
CommandsareoftheformIDLetterfollowedbyavalueor“X”orastand-alone“?”forstatus. Command Qnnn(orqnnn) QX(orqx)
Function SetpotentiometerQtovaluennn ShutdownpotentiometerQ Respondbysendingthecurrentsettingvalueofall potentiometervalues
?
WhereQiseitherA,B,CorD.Forexample,tosetpotentiometerCtovalue123,thecommandisC123. Program21-4 ;Program21-4 ;ControltwoMCP42010 ;Digitalpotentiometers ;Constants ;----------Clk Dta CSel
Con Con Con
A0 A1 A2
;Clock ;Data ;ChipSelect
ArraySize
Con
6
;sizeofinstring
Cmd_None Cmd_WriteData Cmd_ShutDown Cmd_None1
Con Con Con Con
%00000000 %00010000 %00100000 %00110000
Cmd_Dummy Cmd_P0 Cmd_P1 Cmd_Both
Con Con Con Con
%00000000 %00000001 %00000010 %00000011
MultiplierByteTable100,10,1 ;Variables ;-----------
501
Chapter21 i j Temp BadData
Var Var Var Var
Byte Byte Word Byte
;loopvar ;loopvar
U1_Cmd U2_Cmd U1_Inst U2_Inst
Var Var Var Var
Byte Byte Byte Byte
;CommandforU1 ;InstuctionforU2 ;CommandforU1 ;InstructionforU2
A_Val B_Val C_Val D_Val
Var Var Var Var
Word Word Word Word
;UnitAvalue ;UnitBvalue ;UnitCvalue ;UnitDvalue
InStr WorkStr
Var Var
Byte(ArraySize) Byte(ArraySize)
;Isdatavalid?
Initialization ;------------- Clear ;variablestozero OutputCSel LowCsel EnableHSerial SetHSerialH19200 HSerOut[“Set/ReadQuadDigitalPotentiometer”,13] ;Initializeallfoursectionsto0 U1_Cmd=Cmd_WriteData+Cmd_Both U1_Inst=0 U2_Cmd=Cmd_WriteData+Cmd_Both U2_Inst=0 GoSubWriteSetting GoSubReportSetting Main ;-------- ;Reminduserofcommands GoSubSendPrompt InStr=““ ;keyon10,not13.Assumessending***CR&LF*** ;Otherwise,inputterminateson13, ;andthe10appearsasleading ;characterinthenextstring. HSerIn[StrInStr\ArraySize\10] GoSubDispatcher ;seewhatwasreceived GoToMain Dispatcher ;Lookatinputstringand ;-------------- ;actaccordingly ;setuppseudo-Casestatement If (InStr(0)=“A”)OR(Instr(0)=“a”)Then GoSubGetSetting ;getnumericalvalue IfBadData=1Then;unknowninfo GoSubUnknownMsg ELSEIFBadData=0 ;goodnumericaldata U1_Cmd=Cmd_WriteData+Cmd_P0 A_Val=Temp U1_Inst=A_Val GoSubU2Null ;write&setnulls ElseIfBadData=2 ;shutdown U1_Cmd=Cmd_ShutDown+Cmd_P0 ;don’tcareaboutinstructionword A_Val=999 GoSubU2Null ;write&setnulls EndIf
502
DigitalPotentiometersandControllableFilter Return U2Null ;---- Return
EndIf If(InStr(0)=“B”)OR(Instr(0)=“b”)Then GoSubGetSetting ;getnumericalvalue IfBadData=1Then;unknown GoSubUnknownMsg ELSEIfBadData=0 ;goodnumericaldata U1_Cmd=Cmd_WriteData+Cmd_P1 B_Val=Temp U1_Inst=B_Val GoSubU2Null ElseIfBadData=2 ;shutdown U1_Cmd=Cmd_ShutDown+Cmd_P1 ;don’tcareaboutinstructionword B_Val=999 GoSubU2Null EndIf EndIf If(InStr(0)=“C”)OR(InStr(0)=“c”)Then GoSubGetSetting ;getnumericalvalue IfBadData=1Then;unknwon GoSubUnknownMsg ELSEIfBadData=0 ;numericaldata C_Val=Temp U2_Cmd=Cmd_WriteData+Cmd_P0 U2_Inst=C_Val GoSubU1Null ElseIfBadData=2 ;shutdown U2_Cmd=Cmd_ShutDown+Cmd_P0 ;don’tcareaboutinstructionword C_Val=999 GoSubU1Null EndIf EndIf If(InStr(0)=“D”)OR(InStr=“d”)Then GoSubGetSetting ;getnumericalvalue IfBadData=1Then GoSubUnknownMsg ELSEIfBadData=0 ;numericaldata D_Val=Temp U2_Cmd=Cmd_WriteData+Cmd_P1 U2_Inst=D_Val GoSubU1Null ElseIfBadData=2 ;shutdown U2_Cmd=Cmd_ShutDown+Cmd_P1 ;don’tcareaboutinstructionword D_Val=999 GoSubU1Null EndIf EndIf IfInStr(0)=“?”Then;statusquerry GoSubReportSetting EndIf
;Shortenupdispatcher U2_Cmd=Cmd_None U2_Inst=Cmd_Dummy GoSubWriteSetting GoSubReportSetting
U1Null ;Shortenupdispacther ;------
503
Chapter21 U1_Cmd=Cmd_None U1_Inst=Cmd_Dummy GoSubWriteSetting GoSubReportSetting Return WriteSetting ;Writestopots.Assumes ; U1_Cmd,U2_Cmd,U1_Inst& ;-------------- ;U2_Insthavebeensetbeforecalling LowCSel ;Noteorder-pushlastchipinfofirst ShiftOutDta,Clk,MSBPre,[U2_Cmd\8,U2_Inst\8,| U1_Cmd\8,U1_Inst\8] HighCSel Return SendPrompt ;sendpromptstring ;------------- HSerOut[13,”Annn,Bnnn,Cnnn&Dnnntoset;?”,| “forvalues;Ax,Bx,Cx&Dxtoshutdown”,13] Return ErrorMsg ;senderrormessage ;-----------wherevalue>255 HSerOut[“Error!Setvalueto255”,13] Return UnknownMsg ;unknowncommandmessage ;---------- HSerOut[“Unknowncommand”,13] Return ReportSetting ;Writesallfourvalues ;------------- HSerOut[“CurrentSettings:”,13] HSerOut[“UnitA(U1-P0):“,DecA_Val\3,| “UnitB(U1-P1):“,DecB_Val\3,13] HSerOut[“UnitC(U2-P0):“,DecC_Val\3,| “UnitD(U2-P1):“,DecD_Val\3,13] HSerOut[“999=Shutdown”,13] Return GetSetting ;parsetheRS-232inputintonumericaldata ;----------- ;andsendittothedigitalpot ;rightsetsdatainWorkStrsowant0’sinunusedplaces ;Isitashutdowncommand? If(InStr(1)=“X”)OR(InStr(1)=“x”)Then BadData=2 ;Shutdown GoToBailOut EndIf ;Isitgoodnumericaldata? If(InStr(1)<“0”)OR(InStr(1)>“9”)Then BadData=1 ;notnumericaldata GoToBailOut EndIf
BadData=0 WorkStr=“000000” j=ArraySize-1 i=ArraySize-1 ;putonlythenumbersintoWorkStr,rightset ;readtheinputstringrtolkeepingonlydigits0...9 ;putthesedigitsrightsetintoWorkStr While(i>0) If(InStr(i)>=“0”)AND(InStr(i)<=“9”)Then Then WorkStr(j)=InStr(i) j=j-1
504
DigitalPotentiometersandControllableFilter Return
EndIf i=i-1 WEnd ;converttonumericalvalue.ValueASCII-“0” Temp=0 Fori=(ArraySize-1)to(ArraySize-3)Step-1 Temp=Temp+Multiplier(i-3)*(WorkStr(i)-”0”) Next ;Ifoutofrange,setitto255 IfTemp>255Then GoSubErrorMsg Temp=255 EndIf BailOut
End
Program21-4trackstheearlierprogramsandfurtherdiscussionisn’tnecessary.Hereisasampleinteraction withProgram21-4.Toseethetransmittedcharacters,localechomustbeturnedoninyourterminalprogram. Asbefore,forclarity,I’veshowninboldthecommandsIsenttoProgram21-2,whilethenormalcharacters showtheresponsebyProgram21-2.CommentsI’veaddedafterwardareindicatedbythe←symbol. Annn,Bnnn,Cnnn&Dnnntoset;?forvalues;Ax,Bx,Cx&Dxtoshutdown a123 CurrentSettings: UnitA(U1-P0):123UnitB(U1-P1):000 UnitC(U2-P0):000UnitD(U2-P1):000 999=Shutdown Annn,Bnnn,Cnnn&Dnnntoset;?forvalues;Ax,Bx,Cx&Dxtoshutdown b123 CurrentSettings: UnitA(U1-P0):123UnitB(U1-P1):123 UnitC(U2-P0):000UnitD(U2-P1):000 999=Shutdown Annn,Bnnn,Cnnn&Dnnntoset;?forvalues;Ax,Bx,Cx&Dxtoshutdown c111 CurrentSettings: UnitA(U1-P0):123UnitB(U1-P1):123 UnitC(U2-P0):111UnitD(U2-P1):000 999=Shutdown Annn,Bnnn,Cnnn&Dnnntoset;?forvalues;Ax,Bx,Cx&Dxtoshutdown d222 CurrentSettings: UnitA(U1-P0):123UnitB(U1-P1):123 UnitC(U2-P0):111UnitD(U2-P1):222 999=Shutdown Annn,Bnnn,Cnnn&Dnnntoset;?forvalues;Ax,Bx,Cx&Dxtoshutdown ? CurrentSettings: UnitA(U1-P0):123UnitB(U1-P1):123 UnitC(U2-P0):111UnitD(U2-P1):222 999=Shutdown
505
←SetU1,P0to123
←SetU1,P1to123
←SetU2,P0to123
←SetU2,P1to123
←Querystatus
Chapter21 Annn,Bnnn,Cnnn&Dnnntoset;?forvalues;Ax,Bx,Cx&Dxtoshutdown ax CurrentSettings: UnitA(U1-P0):999UnitB(U1-P1):123 UnitC(U2-P0):111UnitD(U2-P1):222 999=Shutdown Annn,Bnnn,Cnnn&Dnnntoset;?forvalues;Ax,Bx,Cx&Dxtoshutdown bx CurrentSettings: UnitA(U1-P0):999UnitB(U1-P1):999 UnitC(U2-P0):111UnitD(U2-P1):222 999=Shutdown Annn,Bnnn,Cnnn&Dnnntoset;?forvalues;Ax,Bx,Cx&Dxtoshutdown Cx CurrentSettings: UnitA(U1-P0):999UnitB(U1-P1):999 UnitC(U2-P0):999UnitD(U2-P1):222 999=Shutdown Annn,Bnnn,Cnnn&Dnnntoset;?forvalues;Ax,Bx,Cx&Dxtoshutdown Dx CurrentSettings: UnitA(U1-P0):999UnitB(U1-P1):999 UnitC(U2-P0):999UnitD(U2-P1):999 999=Shutdown
←ShutdownPotA ←noteA’svalueis999
←ShutdownPotB ←noteB’svalueis999
←ShutdownPotC ←noteC’svalueis999
←ShutdownPotD ←noteD’svalueis999
Annn,Bnnn,Cnnn&Dnnntoset;?forvalues;Ax,Bx,Cx&Dxtoshutdown
LogarithmicResponseforAudioVolumeControl ShouldweuseanMCP41010tocontrolthevolumelevelonanaudioamplifier,wewillquicklyfindthat manystepchangesproducenoperceptiblechangesinvolumelevelbutafewstepchangesattheextreme bottomendofthesteprangeyieldsignificant 10 volumechanges.Thisphenomenonresults fromhumanhearing’slogarithmic,notlinear, 0 responsetosoundpressurelevel.
Beforewegofurther,abriefrefresherondecibelsmaybehelpful.Thedecibel(abbreviated dB)isaratiorelationshipbetweentwopower levels,P1andP2,suchthat:
-10 Output (dB)
Topreventtheusefulvolumecontrolrangefrom beingbuncheduparoundafewdegreesshaft rotation,mechanicalpotentiometersareavailablewithanonlinearor“tapered”response.For volumecontrols,an“audiotaper”or“logtaper” potprovidesperceivedvolumelevelsthatchange directlyproportionaltoshaftrotation.Ifwedo nothingspecial,theMCP42xxx/41xxxshowsthis undesiredbunching,asillustratedinFigure21-11.
-20
-30
-40
-50 0
50
100
150
200
250
MCP42XXX/41XXX Step
Figure21-11:DecibelresponseofMCP42xxx/41xxx.
506
300
DigitalPotentiometersandControllableFilter
P dB = 10 log10 1 P2
Log10meanthelogarithm,base10.IfP1>P2,dBispositive;ifP1<P2,dBisnegative.Thisfollowsfrom thenatureoflogarithms.P1andP2maybeinkilowatts,watts,milliwatts,microwatts,oranyotherpower unit,aslongasbothareinthesameunits. Insteadofmeasuringtwopowerlevelsandtakingtheirratio,wemaymeasurethevoltagesassociatedwith thetwopowers,usingaformulacommonlystatedas: V dB = 20 log10 1 V2 V1andV2arethemeasuredvoltages.Sincepowerisproportionaltothesquareofthevoltage,themultiplier goesfrom10to20.Thereisasubtletyhere,though.Thefundamentaldefinitionofthedecibelisaratio oftwopowers.Hence,thepowerratioformulaisalwayscorrect,butwhenwecomputedecibelsfromtwo voltagemeasurements,thereisanimplicitassumptionthatbothvoltagesareacrossidenticalimpedances.In practice,theidenticalimpedancerequirementisoftenignored.Manytimesignoranceisbliss,butoccasionallyitwillcauseyoutrouble,sobecarefulwhenusingdBcalculationsbasedonvoltages. Mostauthoritiesaccept1dBastheminimumdifferencethatisperceptibleasachangeinvolumelevel. ChangeinSoundLevel(dB)
PerceivedDifference Attheedgeofperceptiblechange; probablyimperceptibletomost Shouldbeperceptiblebymostlisteners Clearlyperceptiblebylisteners Twice(orhalf)asloud Fourtimes(orone-fourth)asloud
1 3 6 10 20
Wewillconstruct,inProgram21-5,a“dBlinear”arrangement,wheretheMCP41010’sprovidesquantized outputvaluesthatchange1dBperlevelstep. OnefinalpointbeforewelookatProgram21-5.We’veonlyconnectedDClevelstothedigitalpotsinour earlierwork.Nowthatweareapplyingaudio,weneedtowatchtheappliedvoltagelevels.TheMCP42xxx/ 41xxx’spotentiometerconnectionscannotbeoperatedwithavoltagebelowVSSoraboveVDD.Normalaudio signalsareACwaveformsandconsequentlyhavecomponentsthatareaboveVSSandbelowVSS,withanaverage voltageof0.Hence,wemustbiastheaudiosignalsothatits averagevoltageisbetweenVSSandVDDandsothatthepeak excursionsdonotexceedVDDordropbelowVSS.Togive maximumheadroomfortheaudiosignal,we’lluseabias voltageofVDD/2.Figure21-12showsthedifferencebetween anormalaudiosignal(Channel2)withapproximatelyequal excursionsaboveandbelowzerovoltsandasignalbiased upwardbyapproximately2.5V(Channel1).Eventhough theaudiosignalhaspeak-to-peakamplitudeofapproximately4V,thebiasedsignalneverexceedsVDD,nordropsbelow VSS,asitsmaximumisapproximately4.5VanditsminiFigure 21-12: Normal and DC Biased 1000 Hz mumisapproximately0.5V.Itthusmeetsthemaximumand SineWaveSignals;Ch1:SignalBiasedatApprox. minimumvoltagerequirementsoftheMCP41010.Thepure 2.5V;Ch2:UnbiasedSignal. 507
Chapter21 ACsignal,incontrasthasaminimumvoltageof–2V,whichviolatestheMCP41010’sVSS(0V)minimum specification. Figure21-13showshowtoconnectanaudiosignaltoanMCP41010.Insomecases,thesignalmaybeproperlybiasedfromitssource,inwhichcasewemaydirectlyconnecttothedigitalpot.If,however,thesignalis ACcoupledandhencerequiresbias,thesecondcircuitshowninFigure21-13maybeused.Thiscircuituses blockingcapacitorsC1andC2tokeeptheDCbiasawayfromtheaudioinputandoutput.R1andR2,with C3formalowimpedanceVDD/2biassource.R3preventsthebiassourcefromappreciablyloadingtheaudio source.SincenoDCcurrentflowsinMCP41010,R3maybeincreasedinvalueifnecessary.
Figure21-13:Connectinganaudiosignaltoadigitalpot.
Wecan’treallymakethelinearresistancestepsofanMCP41010intologarithm-valuedresistors,butwecan approximateitbyonlypermittingcertainstepvaluestobeused.We’llselectthevaluessothatwehave31 steps,eachstepverycloseto1dBfromitsneighboringsteps.Sincethepurposeofthisprogramistoillustrate thelogconcept,we’lluseaminimalistapproach.(Program21-5usesthedualMCP42010configurationof Figure21-6,butitwillworkwithsingleMCP41010equallywell,astheextrainstructionsareignored.) Program21-5 ;Program21-5 ;ControltwoMCP42010 ;Digitalpotentiometer ;withlogsteps ;Constants ;----------Clk Dta CSel
Con Con Con
A0 A1 A2
;Clock ;Data ;ChipSelect
Cmd_None Cmd_WriteData Cmd_ShutDown Cmd_None1
Con Con Con Con
%00000000 %00010000 %00100000 %00110000
Cmd_Dummy Cmd_P0 Cmd_P1 Cmd_Both
Con Con Con Con
%00000000 %00000001 %00000010 %00000011
;0...-30dBsteps LogStepsByteTable251,224,200,178,158,141,126,112,| 100,89,79,71,63,56,50,45,40,|
508
DigitalPotentiometersandControllableFilter 35,32,28,25,22,20,18,16,13,11,10,9,8,7 ;Variables ;----------i Temp U1_Cmd U2_Cmd U1_Inst U2_Inst
Var Var Var Var Var Var
Byte Byte Byte Byte Byte Byte
;loopvar ;CommandforU1 ;InstuctionforU2 ;CommandforU1 ;InstructionforU2
;Initialization ;-------------OutputCSel LowCSel Main End
U1_Cmd=Cmd_WriteData+Cmd_Both U2_Cmd=Cmd_WriteData+Cmd_Both Fori=0to30 U1_Inst=LogSteps(i) U2_Inst=LogSteps(30-i) LowCSel ;Push2ndchipdatafirst ShiftOutDta,Clk,MSBPre,[U2_Cmd\8,U2_Inst\8,| U1_Cmd\8,U1_Inst\8] HighCSel Next GoToMain
We’llconcentrateonthenewpartsofProgram21-4.Theconceptissimple;wesetupabytetablecontainingtheMCP41010stepvaluescorrespondingto1dBincrementsandindexintothebytetabletoobtain thevaluestoloadintotheMCP41010.Aswe’llseeshortly,ifweextendthetabletomorethanabout31 positions,thepositionscorrespondingtoMCP41010stepsbelow8deviateincreasinglyfromourdesired one-position-every-1dBgoal. LogStepsByteTable251,224,200,178,158,141,126,112,| 100,89,79,71,63,56,50,45,40,| 35,32,28,25,22,20,18,16,13,11,10,9,8,7
Howdidwegeneratethisbytetable?ChangingtheMCP41010’sstepcommandchangesthevoltageatthe wiper,sothattellsustousethevoltage-ratio-to-dBformula.Sincewewanta1dBstep,weknowtheratio betweenthecurrentstepandthenext(orprior)stepis: 20 log10
V1 = 1dB V2
Dividebothsidesby20 V 1 log10 1 = V2 20 Nowexponentiatebothsides
10
log10
V1 V2
= 10 0.05
Since10log(x)=x:
V1 = 10 0.05 V2 509
Chapter21 Withapocketcalculator,orExcel,wefindthat100.05is(tosixplaces)1.122018.Hence,wewantthevoltage outputattheMCP41010’swipertoincreaseinstepsof1.122018:1(ordecreaseinstepsof1/1.122018when wearegoingdown).WeknowthatthevoltageatthewiperwiththeinputatpinAandpinBgroundedis directlyproportionaltothestepnumber.Hence,thestepnumbersinourbytetablemustchangeintheratio 1.122018:1aswell. WhenweconstructatableinExcelwiththeseratios(eachtheoreticalstepis1.122018timesthepriorstep, andtheintegerstepisthetheoreticalsteproundedto0places)weseeaproblematoneendofthetable, wherethestepbetween1and2causesa4dBincrease.TheMCP41010onlyhasintegerstepsandconsequentlyourdesireduniformstepgoalisnotachievable. DBStep
TheoreticalStep
IntegerStep
1
1.122018
1
2
1.258925
1
3
1.412538
1
4
1.584893
1
5
1.778279
2
6
1.995262
2
7
2.238721
2
8
2.511886
3
Aswemoveupinsteps,weseethatwecanbecomeveryclosetomatchingthetheoreticalstepwiththe MCP41010’sintegersteps.Thecompletespreadsheetcalculationgivesus48possiblesteps,ofwhichwe acceptthe31nonshadedasbeingacceptablycloseto1dBperincrement.Figure21-14illustratestheincreasingerroraswetrytoachievemorethanabout30dBrangewithoneMCP41010. Possible1-12dB
Possible13-24dB
Possible25-36dB
Possible37-48dB
dB
Step
Int.
dB
Step
Int.
dB
Step
Int.
dB
Step
Int.
1
1.122018
1
13
4.466836
4
25
17.78279
18
37
70.79458
71
2
1.258925
1
14
5.011872
5
26
19.95262
20
38
79.43282
79
3
1.412538
1
15
5.623413
6
27
22.38721
22
39
89.12509
89
4
1.584893
2
16
6.309573
6
28
25.11886
25
40
100
100
5
1.778279
2
17
7.079458
7
29
28.18383
28
41
112.2018
112
6
1.995262
2
18
7.943282
8
30
31.62278
32
42
125.8925
126
7
2.238721
2
19
8.912509
9
31
35.48134
35
43
141.2538
141
8
2.511886
3
20
10
10
32
39.81072
40
44
158.4893
158
9
2.818383
3
21
11.22018
11
33
44.66836
45
45
177.8279
178
10
3.162278
3
22
12.58925
13
34
50.11872
50
46
199.5262
200
11
3.548134
4
23
14.12538
14
35
56.23413
56
47
223.8721
224
12
3.981072
4
24
15.84893
16
36
63.09573
63
48
251.1886
251
OursimpledemonstrationprogramjustwritestheuniformdBstepsintothepotinaloop.
Fori=0to30 U1_Inst=LogSteps(i) U2_Inst=LogSteps(30-i) LowCSel ;Push2ndchipdatafirst ShiftOutDta,Clk,MSBPre,[U2_Cmd\8,U2_Inst\8,| U1_Cmd\8,U1_Inst\8] HighCSel Next
510
DigitalPotentiometersandControllableFilter 10
0 Estimated Error MCP4x010 Digital Pot Log Steps
0
Output (dB)
Actual Attenuation (dB)
-10
-20
-10
-30
-20
-40
-50
-30 50
-40
-30
-20
-10
0
0
5
10
15
20
25
30
dB Quantized Step
Theoretical Attenuation (dB)
Figure21-15:LineardBresponseofProgram21-5.
Figure21-14:LineardBresponseerror.
Amoreusefulprogram,ofcourse,mightacceptRS-232 commands,orperhapsread“up”and“down”volumecontrol buttons,orarotaryencoder,orrespondtoasignalfroman infraredremotecontrol. Aslongaswestayintherange0…30dB,theresponseis quitecloseto1dBperindexstep,asshowninFigure21-15. Theoutputstepsclearlyshowtheirlogarithmparentage,as seeninFigure21-16.(SeetheIdeasforModificationstoProgramsandCircuitssectionofthischapterforanideaonhow toextendthelineardBrangeofadigitalpot.)
ElectronicallyTunableLow-PassFilter UsingMCP42010
Figure 21-16: dB Stepped Output; Ch1: dB DecreasingSteps;Ch2:dBIncreasingSteps.
Weshouldn’tlimitourthinkingbyenvisioningdigitalpotsstrictlyascomputercontrollablevolumecontrols.Rather,theyhavemanyapplications,andwe’lllookattheirusetocontrolanactivelow-passfilter. ThisdesignisbasedonMicrochip’sApplicationNoteAN737[21-2],whichshouldbereadformoredetail. (SomeolderversionsofAN737’sFigure2schematicinterchangetheAandBpinsinbothpotsectionsand thecircuitwon’tworkasshown.ThiserrorwascorrectedwithAN737releaseD.) We’llassumeyouhavepassingfamiliarity withactivefiltersandoperationalamplifiers.Ifnot,thereferencesectionofthis chapteridentifiesseveralexcellentinformationsourcesforbothsubjects. Figure21-17showsourconceptualfilter design.ItisasecondorderButterworth low-passfilter,implementedwithSallenKeytopology.(Ifthesetermsmeannothing toyou,pickupacopyofreference[21-6]. It’sbyfarandawaythemostreadablebook onfilterdesignyou’lleverfind.) Figure21-17:Simplifiedvariablelow-passfilterdesign. 511
Chapter21 ByadjustingthedigitalpotentiometersP0andP1,wemaychange thefilter’scut-offfrequencyfrom100Hzto10KHz,afactorof 100:1.We’llconcentrateontherange100Hzto1KHzinour work.Figure21-18showsthetheoreticalfrequencyresponseof ourfilterwhenP0andP1aresetforcut-offfrequenciesof100 Hz,200Hz,300Hzand1KHz.(Thecut-offfrequencyforaButterworthfilteristhefrequencyatwhichtheresponseis–3dB.) Figure21-19showsthedetailedcircuitlayoutandPICconnections.Notethatwe’vemadeonemajorchangetotheAN737 design;usinganMCP4201010KpotinsteadofaMCP42100 100K.SincetheRCelementsmaybeproportionallyscaled,we havecompensatedfortheeffective“divideby10”ofthe10K versus100KpotsbymultiplyingC1andC2’svaluesbyafactor of10,from0.047µFto0.47µFandfrom0.018µFto0.18µF, respectively.
V(out)
0dB
-20dB
-40dB
-60dB 10Hz
100Hz
1KHz
10KHz
Figure 21-18: Second-order Butterworth low-passFilterwith100Hz,200Hz,300 Hzand1KHzcut-offs.
Figure21-19:Detaileddiagram— variablelow-passfilter.
512
DigitalPotentiometersandControllableFilter ApplicationNoteAN737providestheMCP42010settingsforvariouscut-offfrequencies: Cut-offFrequency(Hz) 100 200 300 1000 2000 3000 10000
P0Code 82 41 26 8 4 3 1
P1Code 238 119 79 24 12 8 2
SincewehavescaledC1andC2toexactlyoffsetthedifferencebetweenAN737’sMCP42100100Kvalues, wemayusethesecodesettingswithoutchange. Program21-6cyclesthroughfourcut-offfrequencies,100Hz,200Hz,300Hzand1KHz,witheachfrequencybeingactivefor10seconds.Thecurrentcut-offfrequencyvalueissenttotheserialoutputportwhereit canbeobservedonaPCrunningaterminalprogram.Duringthetimeeachcut-offfrequencyisactive,we maymeasurethefrequencyresponsewithsignalgeneratorandvoltmeter.Sinceittakeslongertosetupthe signalgeneratortoanewfrequencythantoactuallytakeareading,it’smoreefficienttomeasureallfour responsecurvesatacommontestfrequency,andthenmovetothenexttestfrequency. Program21-6 ;Program21-6 ;ControlaMCP42010-based ;tunablelow-passfilterbased ;onMicrochipAN737 ;Constants ;----------Clk Dta CSel
Con Con Con
A0 A1 A2
;Clock ;Data ;ChipSelect
;DefinecommandsfortheMCP42010 Cmd_None Con Cmd_WriteData Con Cmd_ShutDown Con Cmd_None1 Con
%00000000 %00010000 %00100000 %00110000
Cmd_Dummy Cmd_P0 Cmd_P1 Cmd_Both
%00000000 %00000001 %00000010 %00000011
Con Con Con Con
;Forfilterresponsemeasurements,setthesignal ;sourcetodesiredfrequencyandtakedataasthe ;filterstepsthroughfourcut-offfrequencies CutOffWordTable 100,200,300,1000 PP0 ByteTable 82,41,26,8 PP1 ByteTable 238,119,79,24 ;Variablesw ;----------i U10_CmdVar U10_Inst U11_CmdVar U11_Inst
Var Var Var
Byte Byte Byte Byte Byte
;loopvar ;CommandforU1 ;CommandforU1 ;CommandforU1 ;CommandforU1
;Initialization ;-------------OutputCSel
513
Chapter21 LowCsel EnableHSerial SetHSerialH19200 HSerOut[“OK”,13]
;wewillwritethefrequencytoport ;soweknowtowritedownresponsedata
SetHSerialH19200 U10_Cmd=Cmd_WriteData+Cmd_P0 U11_Cmd=Cmd_WriteData+Cmd_P1 Main End
;settoWriteP0 ;settoWriteP1
Fori=0to3 ;stepthroughthe4frequencies U10_Inst=PP0(i) ;gettheresistancestepforP0 U11_Inst=PP1(i) ;likewiseforP1
LowCSel ;WriteP0 ShiftOutDta,Clk,MSBPre,[U10_Cmd\8,U10_Inst\8] HighCSel
LowCSel ;WriteP1 ShiftOutDta,Clk,MSBPre,[U11_Cmd\8,U11_Inst\8] HighCSel ;Updateoutput HSerOut[“Cutoff:“,DecCutOff(i),”Hz“,13] Pause10000 ;10secondstotakedata Next ;foreasierreading HSerOut[13,13] GoToMain
We’veseeneverypartofthisprogrambefore,inoneformoranother. CutOff PP0 PP1
WordTable ByteTable ByteTable
100,200,300,1000 82,41,26,8 238,119,79,24
Thecut-offfrequencyandtheassociatedP0andP1settingsareheldinthreebytetables.
Fori=0to3 ;stepthroughthe4frequencies U10_Inst=PP0(i) ;gettheresistancestepforP0 U11_Inst=PP1(i) ;likewiseforP1
LowCSel ;WriteP0 ShiftOutDta,Clk,MSBPre,[U10_Cmd\8,U10_Inst\8] HighCSel
Next
LowCSel ;WriteP1 ShiftOutDta,Clk,MSBPre,[U11_Cmd\8,U11_Inst\8] HighCSel ;Updateoutput HSerOut[“Cutoff:“,DecCutOff(i),”Hz“,13] Pause10000 ;10secondstotakedata
WiththeFori=0to3loop,westepthroughthefourcut-offfrequencies,loadtheassociatedP0andP1 valuesintotheMCP41010andmakethemactive.Theloopthenpausesfor10secondssothatwemaymeasuretheoutputvoltageateachofseveraltestfrequenciestoplottheresponsecurve. Figure21-20showsthemeasureddatatracksthepredictedresponsereasonablywell.SinceIbuiltthecircuit ona2840DevelopmentBoard,withjumperwireconnections,straycouplingandnoiselimitstheultimate rejectionofthefilteroncewemovepastabout55–60dBofstopbandloss.Thetestsignalhadapeak-topeakvalueof4.0V(plusa2.5Vbias,requiredbytheMCP42010),sowith60dBattenuation,wemust measurea4.0millivoltsignal,notalwayseasyinthepresenceof60HzhumanddigitalnoisefromthePIC. Realdesignsonprintedcircuitboardsrequireattentiontolayoutandpowersupplydecouplingtoavoidthese 514
DigitalPotentiometersandControllableFilter problems.Wherewemixdigitalandlowlevel analogsignalsonthesamePCB,evengreater attentiontodesigndetailsisnecessary.
IdeasforModificationstoPrograms andCircuits •
•
Onepossiblewaytoexpandthedynamic rangeofadBsteppingdigitalpotistocascadetwoofthem,alongthelinesshownin Figure21-21.Inthisarrangement,P0provides0…30dBattenuation,duringwhich intervalP1issetfor0dBattenuation.For attenuationgreaterthan30dB,P0remains at30db,butP1nowstartsanindependent 0…30dBattenuationrange,thusgivinga total0…60dBrange.Whathappenswhen youtrythisconnectionwithP0andP1both Figure21-20:Measuredresponseofprogrammablelow-pass 10Kdevices?Sinceoneofourunderlying filter. assumptionsisthatthewiperalwaysseesa highimpedanceload,mightP1beloadingdownP0? Howmightthisbecorrected?DoyouexpectadifferentresultifP1isa100Kpotinsteadofa10K?Isthis 10:1increaseinimpedanceenough?Supposeinstead P0worksintoanoperationalamplifierbufferwith essentiallyinfiniteimpedance,andtheoutputofthe bufferampdrivesP1.Doesthisprovidetheexpected result? OneoftheproblemswenotedinChapter16relatedto usingafixedfrequencylow-passfilterwithavariFigure21-21:HypotheticalExtendeddBrangevia ablefrequencyDACoutput.Howmightyouadaptthe cascadeddigitalpots. digitallytunablelow-passfilterandsoftwaredesignto trackthefrequencyoutputoftheDDSgeneratordescribedinChapter16?
References [21-1]
MCP41xxx/42xxxSingle/DualDigitalPotentiometerwithSPIInterface,MicrochipTechnology,Inc. DocumentNo.DS11195C(2003). [21-2] Baker,BonnieC.,UsingDigitalPotentiometerstoDesignLowPassAdjustableFilters,AN737,MicrochipTechnology,Inc.,DocumentNo.DS00737(2001). [21-3] MCP601/2/3/42.7Vto5.5VSingleSupplyCMOSOpAmps,MicrochipTechnology,Inc.,DocumentNo. DS21314E(2003). [21-4] Frederiksen,ThomasM.,IntuitiveICOpAmps—FromBasicstoUsefulApplications,NationalSemiconductorTechnologySeries,SantaClara,CA.,(1984).Aclassictutorialonoperationalamplifiers,but unfortunatelyoutofprint. [21-5] Jung,WalterG.,ICOp-AmpCookbook,3rdEd.,PrenticeHallPTR,(1986).Abitdated,butstillausefulintroductiontoopamps. [21-6] Lancaster,Don,ActiveFilterCookbook,2ndEd.,Newnes,divisionofElsevierScience,Woburn,MA, (1995).Aclassicintroductiontoactivefilters,inprintsincethefirsteditionin1975. 515
Chapter21 [21-7]
Franco,Sergio,DesignwithOperationalAmplifiersandAnalogIntegratedCircuits,McGraw-HillScience/Engineering/Math,NewYork,(2001).Expensive,butanexcellentbook. [21-8] Baker,BonnieC.,ComparingDigitalPotentiometerstoMechanicalPotentiometers,AN219(Preliminary),MicrochipTechnology,Inc.,DocumentNo.DS000219A(2000) [21-9] Baker,BonnieC.,OptimizingDigitalPotentiometerCircuitstoReduceAbsoluteandTemperature Variations,AN691,MicrochipTechnology,Inc.,DocumentNo.DS00691A(2001) [21-10] AudioGainControlUsingDigitalPotentiometers,AN1828,DallasSemiconductorDivisionofMaxim IntegratedProducts,Inc.,(2002). [21-11] MicrochipmakesavailablefreeitsfilterdesignsoftwareFilterLab,currentatrelease2.0,athttp://www. microchip.com/1010/pline/tools/analog/software/flab/10626/index.htm.Thisisanexcellentelementary filterdesignprogramandiswellworthdownloading.
516
22
CHAPTER
Infrared RemoteControls AccordingtoInternetlore,theaveragehouseholdhasbetweenfiveandsevenremotecontrols.Beforestartingthischapter,Icollectedaboxfulltotest—oneZenith,twoNakamichis,twoMitsubishis,oneSamsung, oneToshiba,oneHitachi,andtwoRadioShackuniversalremotecontrols—justbygoingthroughourhouse. Twobelongtoequipmentlongsincescrappedasuneconomicaltorepair,buttherestareinmoreorless commonuse. Althoughthefirst“cordless”TVremotecontrolsusedultrasonictechnology(andwithout electronicsintheremote,noless,employingmechanicallystrokedtuningforks)when inexpensiveLEDsbecameavailable,digital infraredtransmissionbecamethenorm.(Low powerradioisusedforgaragedooropeners, automobileremotelocksandthelike.) WithaninexpensiveIRreceivermodule connectedtoaPIC,it’seasytodecodemost remotecontrols.Oncedecoded,wethen mayusethetechniqueswe’veseeninother Figure22-1:SimulateddrivetoIRLEDforoneburst—38KHz Chapterstocontrolavarietyofdevices.We mightusearelaytoturnalightoffandon,or carrier. wemighttranslatevolumeup/downbuttonsto adjustaudiolevelsthroughaSPI-controlled MCP42010digitalpotentiometer. FindingdefinitiveinformationonIRremote controlsisn’teasy;theconsumerelectronic manufacturersholdtheinformationclosely. I’vepiecedtogetherthischapterfromresearch publishedontheInternetbyinspiredhackers, supplementedwithmeasurementsoftheassortmentofremotecontrolsavailabletome. First,let’slookatthelowestlevelofthe transmissionandreception—andatthislevel, allremotesworkalike.Whenyoupushabut- Figure 22-2: IR receiver smoothes carrier cycles into clean ton,theremotegeneratesaparticulardigital waveform; upper waveform: raw IR; lower waveform: IR controlsequenceandtransmitsitasmultiple receiveroutput.
517
Chapter22 burstsofIRlight.Eachindividualburstconsistsofafewdozenrapidon/offcycles,asillustratedinFigure22-1.AnIRreceiverdetectstheseburstsandsmoothesouttheindividualon/offcarriercycles,thereby reconstitutingtheoriginaldigitalsequence,asshowninFigure22-2. ThefrequencyofeachIRon/offcyclewithinaburstisthecarrierfrequency,andvariesfrommanufacturer tomanufacturer.Thelowestcarrierfrequencycommonlyusedis32.75KHz,andthehighestis56.8KHz, butbyfarthemostcommoncarrierfrequencyis38KHz.IRreceiversarefrequencyselectiveandtoachieve reasonablerange,youmustmatchthereceiverfrequencytotheremote’scarrierfrequency.(Afewbroadbandreceivermodulesareavailable,suchasVishaySemiconductor’sTSOP1100model.)We’lltalkmore aboutIRreceiversshortly. TheIRreceiveralsotranslatesbetweenlightlevelandPIC-compatiblelogiclevel—itsoutputiseitherat logic1orlogic0.ReceiversaredesignedsothatwhennoIRlightisdetected,thereceiver’soutputislogic 1;andislogic0whenIRlightisdetected.Thismayseembackwardsatfirst,butinfactwe’llfinditvery convenienttoforgetaboutwhetheralightoutputcausesa1ora0andinsteadconcentrateonthereceiver’s logicoutputvalues.
CommonEncodingStandards How,then,arethereceiver’s1sand0sareorganizedintousefulinformation?Herewemustdelveintosome detailedmanufacturer-specificinformation.Threecommonlyusedmethodsofencodingthe1sand0sinto usefulinformationare: PhilipsRC-5Code—isa14-bitbiphase(Manchester)encodedsystem,witha36KHzcarrier.ThedocumentationforthissystemispubliclyavailableinaPhilipsSemiconductorApplicationNote.Because we’regoingtoconcentrateonothersystems,wewon’tfurtherdiscusstheRC-5code.(Philipsrecently introducedRC-6,anexpandedversionofRC-5,toprovideforadditionaldatalength.) Sony—(SerialInfraredRemoteControlSystem,SIRCS)—Originallya12-bitcode,butlaterexpandedto 15-bitand20-bitversions.ThedataistransmittedLSBfirst,usingpulsewidthcoding: SIRCSProtocol IROutput
IRReceiverModuleOutput
600µs 600µs Data0 600µs
600µs Data0
1200µs Data1
1200µs Data1
LEDcarrieron=shade
SIRCSusesa40KHzcarrierfrequency,and,asreflectedabove,0and1aredistinguishedbydifferentcarrier-onintervals.Wewon’tfurtherconcernourselveswithSIRCS. REC-80—Isa32-bit“spacewidth”modulatedcode,andis,insomesense,aninverseofSIRCS.InSIRCS, thecarrier-offperiodisconstantandthecarrier-onperiodhastwovalues,anarrowpulsefor0anda widepulsefor1.REC-80hasaconstantcarrier-onperiodandhastwooff-periods,anarrowpulsefor0 andawidepulsefor1.
518
InfraredRemoteControls TypicalREC-80Protocol IROutput 800µs
800µs
IRReceiverModuleOutput
1200µs Data0
800µs
1800µs Data1
800µs
800µs
1200µs Data0
800µs
800µs
1800µs Data1
800µs
LEDcarrieron=shade
ThesketchoftheIRreceiveroutputsuggestsourdecodingstrategyforREC-80signals;measurethelogic highpulsedurationoutofthereceiverandclassifyitaswideornarrow.We’llsee,however,thatinpracticethenarrowpulsestendtobemuchshorterthan1200µsandthewidepulsesaresomewhatshorterthan 1800µs,due,inpartatleast,totheIRreceiver’sresponsetime.(Somesourcessuggestthedata0“no-carrier”periodistwicethe“carrier-on”time,andthedata1“no-carrier”periodisthreetimesthe“carrier-on” time.NoneoftheremotecontrolsignalsImeasuredcameclosetothis1:2:3ratio.) Alongstartsignalissentbeforethedatabits: TypicalRCS-80StartSignal IROutput Idle
9.5ms 4.25ms StartPulse LEDcarrieron=shade
IRReceiverModuleOutput Data
Data
Idle
9.5ms 4.25ms StartPulse
Data
Data
ThenormalREC-80protocolhas32databits,intheory,organizedas: Byte3 DeviceCode LSB
MSB
TypicalREC-80DataOrganizationSendingOrder Byte2 Byte1 D.C.CheckByte FunctionCode LSB MSB LSB MSB
Byte0 F.C.CheckByte LSB
MSB
ThecheckbytesarelogicalNOTcopiesoftheassociateddatabytes.(ThelogicalNOToperationconverts1s to0sand0sto1s.)Again,however,youshouldbepreparedfordiscrepanciesbetweenthistypicalorganizationandthewaymanufacturersactuallyimplementtheirremotecontrols.Some,forexample,mightincrease thepossiblenumberofdevicecodesandfunctioncodesbydroppingthecheckbytes,therebyyielding16-bit devicecodesandfunctioncodes. Mostremotecontrolssendthecodeforakeypressseveraltimes,withthethoughtthatatleastoneofthe repeatedmessageswillbecorrectlyreceived.Repeatedreceptionsofthesamecommandmayleadtoa differenterror,however.Forexample,thepower-on/power-offcodeistypicallyassignedtoone“power”button.Howthenisthereceivertodistinguishbetweenreceivingtwocorrectcopiesofacodetheuserintends tobeasinglepower-oncommandfromapower-onfollowedbyapower-offcommand?Somemanufactures employa“togglebit”todistinguishbetweenthesetwocases;sequentialpressesofakeywillalternate betweentwocodesdifferinginthetogglebit.Thus,twosuccessivecopiesofacommandreceiveddueto normalmessagerepetitionwillbeidentical;twosuccessivecopiesofacommandreceivedduetotheuser pressingthecommandtwicewilldifferbythevalueofthetogglebit.NoneoftheremotecontrolsIworked withimplementedtogglebits,however. 519
Chapter22
IRReceiver Althoughit’spossibletodecodeanIRcontrolsignalwithnothingmorethanaphotodiodeorphototransistor,toworkwellthesedevicesrequiresignificantancillarycircuitry.Ratherthanreinventthemousetrap, we’lluseaninexpensiveIRreceivermodule.Togiveyouanideaofthecomplexityofthesedevices,Figure 22-3providesahigh-levelblockdiagramofatypicalIRreceiver,aVishayTSOP12xxseriesdevice.
Figure22-3:Blockdiagram— typicalIRreceivermodule.
Let’sseehowtheseindividualmoduleswork,atleastatahighlevel.Thephotodiodeismostoftenemployed withacurrent-to-voltagepre-amplifier.LightphotonshitthePNsemiconductorjunctioninthephotodiodeandgiverisetosmallcurrentsbydisplacingelectrons.Thecurrent-to-voltagepre-amplifierprovidesa voltageoutputproportionaltothephotoelectriccurrent.Topreventthephotodiodefrombeingsaturatedby ambientlight,someintegratedreceivers,suchastheTSOPdevices,includeanopticalfiltertorejectvisible lightbutpassinfrared. Theblocklabeled“AGC”representstheautomaticgaincontrolfunctionwithinthemodule.Thesignallevel receivedbythephotodiodechangesdrasticallyasyouorienttheremoteatdifferinganglestothereceiving diode,orchangedistancebetweentheremotecontrolandthereceivingdiode.TheAGCamplifierincreases itsgainwhentheinputsignalisweakanddecreasesitsgainwhentheinputsignalisstrong,therebystabilizingitsoutputatalevelroughlyindependentofthereceivedsignallevel. AftertheAGCamplifier,theincomingcarriersignalisbandpassfiltered.Thisisaveryimportantstepin reducinginterferencefromotherlightsources,suchasroomlighting,orstraysunlight.Afterall,theIR receivermustdifferentiateaweak IRemitterfromaseaofbackground illumination,andthisisthejobof thebandpassfilter.(Eventhoughthe opticalfilterhelps,manylightsources, suchassunlight,havestronginfrared components.)Byselectivelyfiltering onthecarrierfrequency,thebandpass filterrejectsotherlightsources,suchas sunlight,thatareeitherunmodulated, orfluorescentlighting,whichismodulatedwitha120Hzcarrierfromthe ACmainspower.Thebandpassfilter isresponsiblefortheneedtomatch thereceiverfrequencytothecarrier Figure22-4:InputIRpulsesyieldinvertedlogicleveloutput. frequencyoftheremotecontrol. 520
InfraredRemoteControls Theoutputofthebandpassfilterisenvelopedetectedanddrivesthelogicleveloutputstage.Asillustrates, theconventionisthatIRreceiversinvertthesenseofthereceivedsignal;no-IRcausesalogicalhighand IR-receivedcausesalogicallow. Intheremainderofthischapter,whenwerefertohighandlow,or positivepulsesandnegativepulses,itiswithrespecttotheoutputoftheIRreceiver, nottheactualIRilluminationoftheremotecontrolunit. Inwritingthischapter,ItestedtwoSharpElectronicsGP1U5receivermodules,andseveralVishay TSOP12xxintegratedreceivers,withsimilarresults.TheGP1U5moduleshaverecentlybeenreplacedby GP1UD26/27/28seriesdevices,whicharephysicallysmallerbuthavesimilarperformancecharacteristics. I’vealsoseendatasheetsleadingmetobelievethatSharp’sGP1U5moduleshavebeenclonedandstillmay beavailableifyousearchdiligently.Vishay’sTSOPseriesofIRreceiversisavailablefrommanyelectronic partssuppliers,andcostaround$1insmallquantities. YoushouldmatchtheIRreceiver’sresponsefrequency(thebandpassfiltercenterfrequencyinFigure22-3) tothecarrierfrequencyofyourremotecontrol,within10%orso.Operatingoutsidethisrange,suchasdecodinga32.75KHzsignalwitha38KHzreceiver—orviceversa—significantlyreducesrange.Ifyoudon’t knowthecarrierfrequencyofyourremotecontrol,it’seasyenoughtomeasureitwithaphototransistor usingthecircuitshowninFigure22-5.Theresultingwaveform,whentheQSE114phototransistorisilluminatedbyaMitsubishiremotecontrol,isshowninFigure22-6.Measuringthetimeintervalbetweenpeaks yieldsacalculatedcarrierfrequencyof37.88KHz,sothenominalcarrierfrequencyis38KHz.Youmay wonderwhythephototransistoroutputisn’tthenicesquarewaveweexpectfromtheory.TheQSE114is anIRphotoreceptor,withariseandfalltimeof8µs,soweseeoneproblemimmediately;a38KHzsquare wavehasanon-timeof13µs,sowewouldexpecttoseeaseverelydistortedoutputwaveformtobeginwith. Andwewon’tseeeventhatspeedfromaQSE114whenoperatingwithasimpleresistivecollectorload. But,tomeasurethecarrierfrequency,allweneedareconsistentreferencepointsonthewaveform.
Figure22-5:Simplecircuitformeasuring IRcarrierfrequency.
Figure 22-6: Measuring the carrier frequency of a remote control Ch1: collector of QSE114 phototransistor;Ch2:unused.
Onefinalnoteandthenontosomecode.Althoughthebandpassfilterreducesstraylightinterference, itcan’tsolveasecondmajorproblem—backgroundlightingsaturatingthephotodiodeandthecurrentto-voltagepreamplifier,sincethephotodiodeismoreorlesssensitivetovisibleaswellasinfraredlight frequencies.YoumaysignificantlyimprovedecodingrangebyaddingadarkredplasticIRfilteroverthe lensoftheIRreceiver.Ifyoucan’tfindthecorrectIRfiltermaterial,experiment,assomecommonplastics
521
Chapter22 areopaquetovisiblelightbuttransmitIR.Afullyexposedpieceofdevelopedcolornegativefilmmayalso workasanIRfilter.Vishay’sTSOP-seriesintegratedIRreceivershaveabuilt-inIRfilter,whichisanother reasontopreferthemtoSharp’sGP-seriesmodules.
CharacterizingWide/NarrowPulse Intervals RememberthatwehavedecidedtoworkonlywithREC80protocol,andthathigh/lowreferencesarewithrespect totheIRreceiveroutput.ConnecttheIRreceivermodule tothePICasillustratedinFigure22-7.Let’slookatthe outputoftheIRreceiverwhenitreceivesaremotecontrol signal.Figure22-8showsidle,thenastartpulse,followed by32wideornarrowdatapulses,withareturntoidle. Wemightmeasurethepulsewidthwiththeoscilloscope, byexpandingthesweepspeed,withtheresultsillustrated inFigure22-9.But,sinceourultimateobjectiveinvolves readingtheremotecontrolviaaPIC,let’susethePICto measurethereceivedpulsewidths. ThestartpulseweseeinFigure22-8consistsofabout10ms low(IR-on),followedbya4.2mshigh(IR-off).Sincewe keyonhighs,we’llregardthestartpulseasanominal4.2 Figure22-7:ConnectinganIRreceivermoduleto thePIC. mshighpulseprecedingtheactualdata.
Figure22-8:IRreceiveroutput,REC-80signal; Ch1:IRoutputCh2:unused.
Figure22-9:Expandedviewofdatapulses;Ch1: IRoutput;Ch2:unused.
Program22-1 ;Program22-1 ;IRdecoderoutput;toPinB0. ;Measurepositivepulse;widthand ;formhistogramanddumptoserialforanalysis ;Variables ;----------Width WidthArray i j
Var Var Var Var
Word Byte(100) Word Byte
;Readpulsewidth ;Datatobehistorgrammed ;counter ;counter
522
InfraredRemoteControls ;Initialization ;-------------Clear InputB0 ;IRReceivertopinB0 EnableHSerial SetHSerialH115200 Main ;-------- ;Inidleconditionreceiverishigh IfPortB.Bit0=1Then GoToMain EndIf ;presskeysquicklyinfrontofreceiver Fori=0to999 ;take1Ksamples ;measurepositivepulsewidth;actuallyno-IR-output ;butweareinverted,soitmakessenseto ;consideritapositivegoingpulse ;withvariablewidth ;PulsIninunitsof1.4us=>18units=25.2us PulsInB0,1,Width ;saveinbinsof25.2uSec j=Width/18 Ifj>99Then j=99 EndIf ;increasecounter WidthArray(j)=WidthArray(j)+1 Next ;dumphistogramcountersforlateranalysis Forj=0to99 HSerOut[“Width”,9,Dec(j*252)/10,9,DecWidthArray(j),13] Next Pause100 End
OurobjectivewithProgram22-1istomeasureaselectionofremotecontrolsandseeifwemightidentifythe widththresholdtodistinguishawide(logic1)pulsefromanarrow(logic0)pulse.Wedothisbymeasuring 1000pulses,generatedwhenyourapidlypressarandomselectionofremotecontrolkeyswhiletheprogramis samplingdata.Theprogramthencategorizesthemeasuredwidthsintohistogram-typewidthbins. Main ;-------- ;Inidleconditionreceiverishigh IfPortB.Bit0=1Then GoToMain EndIf
WeknowthattheIRreceiver’sidleconditionishigh,sowereadB0untilwedetectalow,indicatingdatais startingtoarrive.Actually,you’llseethatthereissufficientrandominterferencefromflorescentlightingto causeperiodiclowconditions,soit’sagoodideatoloadtheprogramintothePIC,gettheremotecontrolin positionandthenresetthePICasyoubegintopressrandombuttons.(We’llseehowtoreducefalsestartsin Program22-2.)
Fori=0to999 ;take1Ksamples PulsInB0,1,Width
ThekeytoreadingtheIRreceiverisMBasic’sPulsInprocedure.PulsInmeasurestheinputpulse durationinunitsteps.Theunitstepdurationcorrespondstoseveninstructioncycledurations,whereone instructioncycleis4/Fosc. OscillatorFrequency 20MHz 16MHz 10MHz
InstructionCycleLength 200ns 250ns 400ns
PulsInUnitStepSize 1.4µs 1.75µs 2.8µs
523
TimeoutBaseValue 91.75ms 114.7ms 183.5ms
Chapter22 PulseInisinvokedwithseveralparameters: PulseInPin,State{TimeoutLabel,TimeoutMultiple,}Var
Pin—Aconstantorvariablethatdefinesthepintobemeasured.PulsInautomaticallyplacesthepininto inputmode.Figure22-7showswe’veconnectedtheIRreceivertoB0. State—PulseIncanmeasureeitherthepositivewidthornegativewidth,i.e.,thewidthofthelogic1signalor thewidthofthelogic0signal.Stateisavariableorconstantthatdefineswhichwidthistobemeasured. IfState=1,westartmeasuringwhenB0goesfrom0to1andstopmeasuringwhenB0goesfrom1 to0,i.e.,wemeasurethepositivewidth.Conversely,ifState=0,wemeasurethewidthofthe0level interval.Sincewewishtomeasurethepositivewidth,wesetState=1.(Don’tgetconfused;thevariableperiodinREC-80isthetimebetweenLEDcarrierbursts;butsincetheIRreceiverisinverting,by measuringpositiveintervals,weare,infact,measuringtheintervalbetweenIRlightbursts.) {TimeoutLabel,TimeoutMultiple}—PulseInchecksforthetransitiondefinedbyState,either0→1or 1→0.Ifnosuchtransitionhasbeenreceivedafter65,535unitstepintervals,PulsIntimesout,and executionpassestothenextMBasicstatement.Optionallyitispossibletoextendthetimeoutperiodin stepsof65,535unitstepintervalsviatheTimeoutMultiplevalue.Avalueof2,forexample,yields atimeoutperiodof2x65,535,or131,070unitstepintervals.AssumingourPIChasa20MHzclock, eachunitstepis1.4µs,sothebasictimeoutintervalis65,535×1.4µsor91.75ms.Uponpassageof thistimewithoutaninputpulse,executionwillpasstoTimeoutLabel.Ifoundthatitisnotpossibleto setTimeoutMultiplewithoutalsosupplyingaTimeoutLabel,andviceversaandthatanyattempt touseonlyoneofthetwooptionsproducedacompilererror.We’llusetheseoptionalparametersin laterprograms,butnotinProgram22-1. Var—Holdsthewidthofthemeasuredpulse,inunitstepintervals.Varisa32-bitresult,whichcallsfora longvariableifyouwishtomeasurethemaximuminterval.Inourcase,weknowthatthepulselength isunderafewthousandmicroseconds,sowewilluseawordvariableforVar.
Next
;saveinbinsof25.2uSec j=Width/18 Ifj>99Then j=99 EndIf WidthArray(j)=WidthArray(j)+1
Nowthatwehavemeasuredthepositivepulsewidth,wewishtostoreitsvalue.OurPICdoesn’thaveenough memorytostore1,000wordvariables,and,inanyeventthatisn’tnecessary,orevendesirable.Instead,we categorizeeachmeasuredwidthintooneof100“widthbins,”eachbinbeingabout25µswide.(Witha20 MHzclock,Widthismeasuredinunitintervalsof1.4µsduration,and18suchunitscorrespondto25.2µs.) Wedothisbydividingthemeasuredwidthby18toyieldthehistogram“binnumber”jandthenincrementingWidthArray(j)by1.(Wetrapforj>99,asweonlyhaveallocated100binsforthedata.)Afterwehave taken1,000samples,WidthArray(j)holdsthenumberofwidthmeasurementsfallingwithineachbinvalue. Forexample,WidthArray(20)holdsthenumberofpulseswithmeasuredwidthsbetween500and524µs. Instatistics,thisistermeda“histogram.”(Byusingabytearraytoholdbincounts,weassume,implicitly,that notmorethan255widthmeasurementswillbelongtoanyindividualbin.That’sareasonablysafeassumption for1,000totalmeasurementswithapproximatelyhalfexpectedtobewideandhalftobenarrowandwithan expectedspreadofpulseduration.) Executionspeedisaconcerninthisprogram,andevenmoresoinlaterprogramsinthischapter.Wewish ourprogramtonotmissanypositivepulses,sowemustbeeconomicalwiththetimeavailablebeforewe expectthenextpositivepulsetostart.FortheREC-80code,weknowthespacebetweenpulses(theIR-on time)runsbetween600and800µs.That’senoughtime,assumingthePICisrunningwitha20MHzclock, toperformthecomputationswerequire.But,wemustbecarefultonotburdenourprogramwithlengthy computationsduringthisinter-pulseinterval,lestthenextpositivepulsebemissed. 524
InfraredRemoteControls
;dumphistogramcountersforlateranalysis Forj=0to99 HSerOut[“Widthunits“,9,Decj*18,9,”Widthus“,9,| Dec(j*252)/10,9,DecWidthArray(j),13] Next Pause100
Afterwehavetaken1,000samplesthehistogramresultsaresentbyserialinterfacewherewecapturethem withaterminalprogram.Toconvertthebinnumbertomicroseconds,wemultiplyby25.2.Toavoidfloating pointconversion,weinsteadmultiplyby252anddivideby10.But,fordecodingitdoesn’tmatterwhether weusemicrosecondsorunitintervals,aslongasweareconsistentinsettingtheboundarythresholds. Here’sapartialsampleoftheoutputfromaMitsubishiremotecontrol: Widthunits Widthunits Widthunits Widthunits Widthunits Widthunits Widthunits Widthunits Widthunits Widthunits
576 594 612 630 648 666 684 702 720 738
*
*
*
Widthunits Widthunits Widthunits Widthunits Widthunits Widthunits Widthunits Widthunits Widthunits
1494 1512 1530 1548 1566 1584 1602 1620 1638
Widthµs806 Widthµs831 Widthµs856 Widthµs882 Widthµs907 Widthµs932 Widthµs957 Widthµs982 Widthµs1008 Widthµs1033
0 10 0 70 82 104 151 5 5 0
Widthµs2091 Widthµs2116 Widthµs2142 Widthµs2167 Widthµs2192 Widthµs2217 Widthµs2242 Widthµs2268 Widthµs2293
0 8 7 80 204 0 3 4 0
Thedisplayedwidthvalueisthelowerboundofthebin,for example,width907µsmeansbetween907and932µs.We caneitheranalyzethedatabyinspectionoftheoutput,orwe canplotit.Figure22-10showsthehistogramsforsixREC80remotecontrolunits.Thedatashowsthatwecansafely Figure 22-10: Wide and narrow pulse setournarrow/wideboundsas: distributions–6remotecontrolunits. PulseCategory Narrow Wide Start
MinimumLength Units(1.4µs) Microseconds 250 350µs 1004 1450µs 2714 3800µs
MaximumLength Units(1.4µs) Microseconds 786 1100µs 1607 2250µs 3429 4800µs
Onefinalpoint,oscilloscopemeasurementsforeachremotecontrolshowedareasonablyconsistentstart pulseofabout4500µs.
525
Chapter22 Program22-2 OK,enoughpreparatorywork.Let’slookatdecodingarealremotecontrol.First,though,let’sworkthrough ourdecodingalgorithminpseudo-code. Searching: Checkinputpin.Ifhigh(idle)continuechecking Ifinputpinislow,itmightbethelead-intoastartpulse UsingPulsIncheckforavalidstartpulse~4.2ms IfnovalidstartpulsegobacktoSearching Assumesweknowthenumberofdatapulsestoreceive=BitLength Fori=0toBitLength-1 Readthepulselength Storethepulselengthinarray(bitlength)Warray Next NowAnalyzeWarraytocategorizeeachmeasurementas AWide(W),aNarrow(N)oranUnknown(x)pulselength populateastringarrayTempArray()withW,Norx basedonthepulsewidthwindows. UseTempArraytodeterminevalidityofdata;can’thaveany Xvaluesifvalid. Substitute1forW,0forNinabit-by-bitassemblyofthe Decodedvalue. Writeoutputtoserialport
Tokeepthingssimple,we’llstartwithanolderMitsubishiTV/VCRremotecontrolwitha16-bitcode. Mitsubishiusesa32.75KHzcarrierfrequency,sotheparticularIRreceiverweuseisoneoptimizedforthat carrierfrequency.(InreadingProgram22-2,rememberthe|characterisalinecontinuation.) Program22-2 ;Program22-2 ;toPinB0.ValuesforMitsubishiremotecontrol16-bitwidth ;Mitsubishiisspecialcasebecauseitis16-bits ;anduses32.75KHzcarrier,notthemorecommon38KHz ;Constants ;-------------;thevaluesareinunitintervalsof1.4uswhichassumes ;a20MHzclock. Wmin Con 1036 ;1450uswidepulseminwidth WMax Con 1714 ;2400uswidepulsemaxwidth NMin Con 250 ;350usnarrowpulseminwidth NMax Con 786 ;1100usnNarrowPulsemaxwidth ;Variables ;----------CodeValue CodeValueR TempArray i WArray GoodFlag
Var Var Var Var Var Var
Word Word Byte(16) Byte Word(16) Byte
;Holdsthe16-bitdecodedvalue ;Reversedbitswithinbyte ;HoldsW/N/xstringarray ;Counter ;Holdsmeasuredpulsewidths ;If1,gooddata
;Initialization ;-------------Clear InputB0 ;DecodertoB0 EnableHSerial SetHSerialH115200
526
InfraredRemoteControls HSerOut[“P22-2”,13,13] Main ;----- ;UnlikwREC-80spec,Mitsubishiusesnolongstartpulse ;Allwegetis16databits ;Waitforastartpulse i=0 ASM { WaitForInput bankselPortB btfsc PortB,0 GoTo WaitForInput NOP } ;pulseisfollowedby16databits.Capture ;thewidthstoWArray Loop PulsInB0,1,Main,1,WArray(i) ASM { bankseli incf i&0x7F,f bankselPortB } Ifi<16ThenLoop ;GoToMain GoSubCalculateCode GoSubGenerateValue GoSubDumpRawData IfGoodFlag=1Then HSerOut[“Good:“,StrTempArray\16,”MSB:“,| iHexCodeValue] HSerOut[“LSB:“,iHexCodeValueR,13] ELSE ;Uncommentlinebelowifwantseebaddata HSerOut[“Error:“,StrTempArray\16,”LSB:“,| iHexCodeValue,13] EndIf GoToMain CalculateCode ;----------- ;Scanthemeasuredwitharrayandclassifyeachas ;N(narrow),W(wide)orx(outsideWandNwindows) Fori=0to15 TempArray(i)=“x” If(WArray(i)>WMin)AND(WArray(i)<WMax)Then TempArray(i)=“W” EndIf If(WArray(i)>NMin)AND(WArray(i)<NMax)Then TempArray(i)=“N” EndIf Next Return GenerateValue ;----------- ;Nowcalculatethe16-bitWordequaltothereceiveddata CodeValue=0 ;Setto0ifwehavebaddata GoodFlag=1 Fori=0to15
527
Chapter22 Return
CodeValue.Bit0=%0;overwriteifW ;NowconvertW/N/xtonumbers IfTempArray(i)=“W”Then CodeValue.Bit0=%1 EndIf IfTempArray(i)=“x”Then GoodFlag=0 EndIf ;NoneedtocheckNorx,pre-populatedwith0s ;readassumingsentMSBfirst.Thismaynot ;bethecase,butforourpurposeorderdoesn’t ;matterasweonlylookforuniquevalues ;Datagoesinatright,movetolefteveryentry ;Don’tshiftonlastbitasnomoretobeadded Ifi<>15Then CodeValue=CodeValue<<1 EndIf Next CodeValueR.Byte0=CodeValue.Byte0REV8 CodeValueR.Byte1=CodeValue.Byte1REV8
DumpRawData ;--------- Fori=0to15 HSerOut[Deci,9,DecWArray(i),13] Next Return End
There’ssomethingdifferentherethaninourpseudo-code; thereisnocodetocheckforavalidstartpulse.That’sbecauseMitsubishiusesadifferentapproach,asseeninFigure 22-11.Thesignalgoesdirectlyfromidletodata,without theprolongedstartpulseseeninFigure22-8.(It’sentirely possible,ofcourse,thatthethreewidepulsesimmediately afteridleareapreambleandthattheremaining13bitsare data.That’soneofthedifficultiesofreverse-engineering aprotocolwithonlyalimitedsampleofdevicestotest. Regardless,wewilldecodetheseasiftheyarevaliddata bits,andtheirstatusisimmaterialtothetechniqueweusein Program22-2.) Main ;----- WaitForInput
bankselPortB btfsc GoTo NOP
Figure22-11:Lead-intoMitsubishi16-bitdata; Ch1:IRreceiveroutput;Ch2:notused.
PortB,0 WaitForInput
Sincethereisnostartbit,wejumptocapturingthenext16positivepulsewidthsafterthefirsttimetheinput pingoeslow.InMBasic,ourwaitforinputroutinecouldbewrittenas: WaitHere IfPortB.Bit0=1ThenGoToWaitHere EndIf
TheproblemwithapureMBasicsolutionisthatitsexecutiontimeismarginal,giventhatthelowtimeisa fewhundredmicroseconds.Accordingly,weuseasimpleassemblerroutinethatreadsPortBandchecksthe statusofbit0(B0)throughthebtfscoperation.IfB0isset(B0=1)thenextinstruction,GoToWaitForInputisexecutedinanendlessloop.IfB0isclear(B0=0),theGoToWaitForInputinstructionis
528
InfraredRemoteControls skipped,anull(NOP)operationisexecutedandcodeexecutionreturnstoMBasic.Theassemblertestand branchcodeexecutesinlessthan1µswitha20MHzclock. Wethenreadthedurationofthenext16highpulsesusingPulsIn.Themostdirectwaytocodethisis:
Fori=0to15 PulsInB0,1,WArray(i) Next
Thisconstruction,however,hasanexecutionspeedproblem.ItturnsoutthatthecombinationoftheFor… Nextloopoverhead(162µs)andPulsIn’sreleasetime(166µs)followingtheinputpulsefallingedgetotal approximately328µs,assuminga20MHzclock.Sincetheremotecontrolinter-pulsedwellintervalcanbe asshortas305µs,wemustsavetimesomeplace.WecouldwriteourownalternativePulsInprocedure, perhapsusingtimer1,butbeforeintroducingthatcomplexity,wefirsttryansubstitutefortheFor…Next loop.BymixingabitofassemblerwiththeMBasiccodeweshavetheloopoverheadfrom162µsto73µs, foratotalexecutiontimeof249µs,wellwithinour305µsdwellinterval.
Loop
PulsInB0,1,Main,1,WArray(i) ASM { bankseli incf i&0x7F,f bankselPortB } Ifi<16ThenLoop
OurassemblerroutinefollowsthatdiscussedinChapter14andistheequivalentofi=i+1whereiisabyte variable,exceptitexecutesinunder1µs.Wethencapturethenextpulsewidthintheword-lengtharray Warray(i).Ifwehavereadfewerthan16pulses,theif…thentestrecyclestoPulsIntoreadthenext inputpulse.Theif…thentestinMBasicexecutesinabout70µs,sothecombinedassemblerincrementand if…thentestexecutesinlessthanhalfthetimeofthefor…nextcodeitreplaces. Aftera250mspausetoavoidreadingduplicatedpulsesequences,wecallthesubroutineCalculateCode toclassifyeachofthe16measuredpulsewidthsaswide,narroworunknown. CalculateCode ;----------- ;Scanthemeasuredwitharrayandclassifyeachas ;N(narrow),W(wide)orx(outsideWandNwindows) Fori=0to15 TempArray(i)=“x” If(WArray(i)>WMin)AND(WArray(i)<WMax)Then TempArray(i)=“W” EndIf If(WArray(i)>NMin)AND(WArray(i)<NMax)Then TempArray(i)=“N” EndIf Next Return
Sincewewishtodisplaytheoutputdatafordebugging,we’llusethestringarrayTempArrayfortwo purposes.First,wewilluseittoholdthestatusofeachpulse,W,Norx,forwide,narroworunknown, respectively.Thisarrayislatersenttotheserialportfordisplay.Second,we’lluseittohelpcomputethe numericalvalueofthereceived16bits. UsingaFori…Nextloop,wefirstassignTempArray(i)thevalue“x”,orunknown.Then,wetestthe pulselengthstoredinthecorrespondingWarray(i)toseeifitwithinournarroworwidewindowsandwe assignanappropriateletter—“N”or“W”—toTempArray(i)ifitaverifiablenarroworwidepulse.Ifit isn’twithineitherthewideornarrowwindows,theclassificationstaysas“x”.
529
Chapter22 AftercompletingCalculateCode,atypicalTempArraylookslikethefollowing:WWWNWNWNNNNWNWNNif ithasnoerrors,or,perhaps,WWWxWNWNNxNWNxNNifitcontainspulsesoutsidetheWorNwidthlimits.(Of course,theWsandNschange,dependingonthekeysequencepressed.) SubroutineGenrateValuethencalculatesthewordvalueofthe16receivedbits. GenerateValue ;----------- CodeValue=0 GoodFlag=1 Fori=0to15 CodeValue.Bit0=%0;overwriteifW IfTempArray(i)=“W”Then CodeValue.Bit0=%1 EndIf IfTempArray(i)=“x”Then GoodFlag=0 EndIf Ifi<>15Then CodeValue=CodeValue<<1 EndIf Next CodeValueR.Byte0=CodeValue.Byte0REV8 CodeValueR.Byte1=CodeValue.Byte1REV8 Return
Thereturnedwordvalue,assumingthedataissentMSB-first,isinCodeValue.However,sincewedon’t knowifMitsubishisendsitsdatainLSBorMSBorder,we’llalsocalculateanddisplaytheLSB-firstvalue, tobeheldinCodeValueR.We’lljudgewhichisthecorrectorderbasedonhowthesevalueschangeaswe pressdifferentkeysontheremote. OurapproachistoloopthroughthestringarrayTempArrayand,baseduponthevalueofthecharacter, addeithera%0ora%1atthelastbitinCodeValue.Aftereachpassthroughtheloop,weshiftthebitsin CodeValueoneplacetotheleftwiththeshift-left(<<)operator.Any“x”characterinTempArray,setsthe GoodFlagto0,indicatingthereceiveddataiscorrupt.Notethatsincetheshift-leftgetsusreadyforthe nextbit,wewon’texecuteitforthelastbit,astherearenofurtherbitstoadd.Hencewetestfori=15and, whentrue,omittheshift-left. Finally,wesetthetwobytesofCodeValueRequaltoCodeValue,butwithreversedbitorder.
IfGoodFlag=1Then HSerOut[“Good:“,StrTempArray\16,”MSB:“,| iHexCodeValue] HSerOut[“LSB:“,iHexCodeValueR,13] ELSE ;Uncommentlinebelowifwantseebaddata ;HSerOut[“Error:“,StrTempArray\16,”MSB:“,| iHexCodeValue,13] EndIf
Theremainderofthemainprogramloopdisplaysthereceiveddata.Ifyouwishtoseecorruptdataaswell asgooddata,uncommenttheHserOutstatementintheELSEportionoftheIfconditional.Subroutine DumpRawDataprovidestheindividualmeasuredpulsedurations. Here’stheoutputforsomesamplekeypresses.(Tosavespace,I’vesuppressedtherawpulselengthoutput data.)ThisparticularremotecontrolhasaslideswitchtoselectbetweenTVandVCR,sowe’llexercise bothoptions.I’veaddedtheModeandKeycommentstoProgram22-2’soutputandI’vedeletedduplicates, whereeachoftherepeatedmessagesautomaticallysentbytheremotecontrollerarecorrectlydecodedand separatelyreported.
530
InfraredRemoteControls
Good:WWWNWNWNNWNWNNNNMSB:$EA50LSB:$570A Good:WWWNWNWNNWNNWNNNMSB:$EA48LSB:$5712 Good:WWWNNNWNNWNNNWNNMSB:$E244LSB:$4722 Good:WWWNNNWNNWNWNWNNMSB:$E254LSB:$472A Good:WWWNWNWNWNNWNNNNMSB:$EA90LSB:$5709 Good:WWWNWNWNNNNNNNNNMSB:$EA00LSB:$5700 Good:WWWNWNWNNNNWNNNNMSB:$EA10LSB:$5708 Good:WWWNWNWNNNNNWNNNMSB:$EA08LSB:$5710 Good:WWWNWNWNNNNWWNNNMSB:$EA18LSB:$5718 Good:WWWNWNWNNNNNNWNNMSB:$EA04LSB:$5720 Good:WWWNWNWNNNNWNWNNMSB:$EA14LSB:$5728 Good:WWWNWNWNNNNNWWNNMSB:$EA0CLSB:$5730 Good:WWWNWNWNNNNWWWNNMSB:$EA1CLSB:$5738 Good:WWWNWNWNWNNNNNNNMSB:$EA80LSB:$5701 Good:WWWNNNWNNWNWNNNNMSB:$E250LSB:$470A Good:WWWNNNWNNWNNWNNNMSB:$E248LSB:$4712 Good:WWWNNNWNNWNNNWNNMSB:$E244LSB:$4722 Good:WWWNNNWNNWNWNWNNMSB:$E254LSB:$472A Good:WWWNNNWNWNNWNNNNMSB:$E290LSB:$4709 Good:WWWNNNWNNNNNNNNNMSB:$E200LSB:$4700 Good:WWWNNNWNNNNWNNNNMSB:$E210LSB:$4708 Good:WWWNNNWNNNNNWNNNMSB:$E208LSB:$4710 Good:WWWNNNWNNNNWWNNNMSB:$E218LSB:$4718 Good:WWWNNNWNNNNNNWNNMSB:$E204LSB:$4720 Good:WWWNNNWNNNNWNWNNMSB:$E214LSB:$4728 Good:WWWNNNWNNNNNWWNNMSB:$E20CLSB:$4730 Good:WWWNNNWNNNNWWWNNMSB:$E21CLSB:$4738 Good:WWWNNNWNWNNNNNNNMSB:$E280LSB:$4701
Comments Mode Key VCR Ch+ VCR ChVCR Vol+ VCR VolVCR 0 VCR 1 VCR 2 VCR 3 VCR 4 VCR 5 VCR 6 VCR 7 VCR 8 VCR 9 TV Ch+ TV ChTV Vol+ TV VolTV 0 TV 1 TV 2 TV 3 TV 4 TV 5 TV 6 TV 7 TV 8 TV 9
Beforedecidingthemostlikelycorrectbitorder,weshouldunderstandthatitreallydoesn’tmatterinmost caseswhetherwehaveitrightornot.Ifwewishtousethedecodedremotecontroltoincreaseordecrease somevaluebasedontheTV/Channel+orTV/Channel–key,itmattersnotwhetherweincreaseupondecoding$E250or$470A.Allweareconcernedwithismatchingauniquevalue,andthatvaluecanbethe theoreticallycorrectbitorder,oritsreverse;bothvaluesareuniqueandeitherservesourpurpose.However, asanexercise,let’sseeifwecandeterminethecorrectorder. Beforewedecidethebitorder,itappearsthatthehighbyteisadevicecode,where$E2/$47precedescontrolmessagestotheTV,and$EA/$57precedesmessagestotheVCR.Ifso,thelowbytemakessenseasa keycodeindependentofthedeviceaddress.Forexample,thelowbytevalue$90/$09alwaysrepresentsthe digit0key,regardlessofwhetherthecommandisdirectedattheTVortheVCR.(Thedualvaluesseparated bya/indicatebothMSB-firstandLSB-firstvalues.) TochoosebetweenLSB-firstandMSB-firstbitorder,however,ismoredifficult.Examiningthevaluessent whenthe0…9keysarepressed,wenotethatLSB-firstorderhasfewerlargevaluejumpsthanMSB-first order(theMSB-firstordervaluesassociatedwiththe9and0keysparticularlystandoutasunusual).Onbalance,it’slikelythedataissentLSBfirst. Finally,wealsoobservethat,atleastforthesamplesshownabove,allkeycodesstartwiththreeconsecutive Ws(1’s)andallendwithtwoconsecutiveN’s(0’s).It’sareasonableguess—logical,butstillaguess—that theseconsecutivecharactersrepresentmessagestartandmessageendsentinels.Ifso,thevariablemessage contentwouldbe11bitsandourviewofLSB-firstdataordermightchange.
531
Chapter22
DecodingaREC-80Controller Let’snowlookatreadingatrueREC-80compatiblecontroller.Program22-3buildsuponProgram22-2,so we’llconcentrateonthedifferences. Program22-3 ;Program22-3 ;IRdecoderoutput ;toPinB0.ValuesforGeneric ;remotecontrol32-bitwidth ;Constants ;------------- ;unitduration@20MHzclock Smin Con 2500 ;3500usstartpulseminimum Smax Con 3572 ;5000usstartpulsemaximum Wmin Con 964 ;1350usWidepulseminwidth WMax Con 1393 ;1950usWidepulsemaxwidth NMin Con 214 ;300us Narrowpulseminwidth NMax Con 571 ;800us NarrowPulsemaxwidth MLen Con 32 ;Numberofdatabits ;Variables ;----------CodeValue Temp TempArray i WArray GoodFlag
Var Var Var Var Var Var
Long Long Byte(MLen) Byte Word(MLen) Byte
;holdsdecoded32bitsLSBorder ;decodedbitsMSBorder ;HoldsN/W/Xstrings ;Counter ;Holdspulsewidthmeasurements ;If1,gooddata
;Initialization ;-------------Clear ;Zeroize InputB0 ;OutputofIRReceivertoB0 EnableHSerial SetHSerialH115200 HSerOut[“P22-3”,13,13] Main
i=0 ;Wefirstwaitforstartpulse PulsInB0,1,Main,1,WArray(0) ;Isitavalidstartpulse? IfWarray(0)<SminThen GoToMain EndIf IfWarray(0)>SmaxThen GoToMain EndIf ;ValidstartpulseisfollowedbyMLendatapulses Loop PulsInB0,1,Main,1,WArray(i) ASM { bankseli incf i&0x7F,f bankselPortB } Ifi<MLenThenLoop GoSubCalculateCode GoSubGenerateValue
532
InfraredRemoteControls
IfGoodFlag=1Then GoSubErrorCheck IfGoodFlag=1Then HSerOut[“Good:“,StrTempArray\MLen,| “MSB:“,iHexTemp] HSerOut[“LSB:“,iHexCodeValue,13] EndIf ELSE ;Uncommentlinebelowifwantbaddataoutput ;HSerOut[“Error:“,StrTempArray\MLen,| “MSB:“,iHexTemp,13] EndIf GoToMain CalculateCode ;----------- ;Scanthyemeasuredwidtharrayandclassifyeach ;asN(narrow),W(wide)orX(outsideNandWwindows) Fori=0to(MLen-1) TempArray(i)=“x”;pre-loadwithbadflag If(WArray(i)>WMin)AND(WArray(i)<WMax)Then TempArray(i)=“W” EndIf If(WArray(i)>NMin)AND(WArray(i)<NMax)Then TempArray(i)=“N” EndIf Next Return GenerateValue ;----------- ;Nowcalculatethelong=tothereceived32-bits Temp=0 ;Setto0ifgetbaddata GoodFlag=1 ;NowconvertW/N/xtovalues Fori=0to(MLen-1) Temp.Bit0=%0 IfTempArray(i)=“W”Then Temp.Bit0=%1 EndIf IfTempArray(i)=“x”Then GoodFlag=0 EndIf ;NoneedtocheckNorx,sincepre-populatedwith0s ;readassumingsentMSBfirst.Thismaynot ;bethecase,butforourpurposeorderdoesn’t ;matterasweonlylookforuniquevalues ;Datainatright,movetolefteveryentryw/new ;datatofollow.Skipattheend Ifi<>(MLen-1)Then Temp=Temp<<1 EndIf Next ;SomeinforsaysdatasentLSBfirst ;byteorderisOK,butbitsarereversed CodeValue.Byte3=Temp.Byte3REV8 CodeValue.Byte2=Temp.Byte2REV8 CodeValue.Byte1=Temp.Byte1REV8 CodeValue.Byte0=Temp.Byte0REV8 Return ErrorCheck ;checkNOTbytes ;-------- If(CodeValue.Byte3+CodeValue.Byte2)<>$FFThen GoodFlag=0 HSerOut[“BadCheckByte3”,13] EndIf
533
Chapter22 Return End
If(CodeValue.Byte1+CodeValue.Byte0)<>$FFThen GoodFlag=0 ;HSerOut[“BadCheckByte1”,13] EndIf
First,wemakethecodemoreflexibleandmaintainablebydefiningthebitlengthwithaconstant: MLen
Con
32
And,sincethedatalengthis32bits,not16,we’vechangedthevariablesCodeValueandTemptobetype long,notword.Finally,inanattempttocoverawiderangeofremotecontrollers,weexpandedthewide andnarrowwindowconstantstomatchFigure22-10. WenotedthatMitsubishi’s16-bitprotocolhasnostartpulse,butREC-80compatibleremotecontrolshavea startpulse.We’llaccordinglymodifythestartconditionsforProgram22-3.
;Wefirstwaitforstartpulse PulsInB0,1,Main,1,WArray(0) ;Isitavalidstartpulse? IfWarray(0)<SminThen GoToMain EndIf IfWarray(0)>SmaxThen GoToMain EndIf
WestartbymeasuringthepositivepulsewidthusingPulsIn,storingthevalueinWarray(0).Unlikein Program22-2,however,wenowdefinetheTimeoutMultipleandTimeoutLabel.We’llsettheTimeoutMultipleas1,anduseMainastheTimeoutLabel.Thus,ifapositivepulseisn’treceivedwithin1.4 µs×65,535(91.7ms)programexecutionjumpsbacktoMain,wherePulsInisagainexecuted.Consequently,weareinacontinualloop,waitingforapositivepulsetoarrive.Whenapositivepulsearrives,we saveitsvalueinWarray(0)andcheckitagainstthewindowwe’vedefinedforthestartpulse,Sminand Smax.Ifwehavereceivedavalidstartpulse,executioncontinuesandwereadthewidthofthenext32data bitsintoWarray,startingwithWarray(0).IfthepossiblestartpulseisoutsidetheSmin…Smaxwindow, programexecutionreturnstoMainandweagainwaitforapossiblestartpulse. ImeasuredtheREC-80inter-pulsedwelltimeat600µssowehavesufficienttimetoperformthesecomparisonsinMBasic.Infact,wecoulduseafor…nextlooptoreadthepulsewidths.However,sinceourmixed assembler/MBasiccodeworks,we’llstickwithit. Afterthethisstartrelatedcode,theremainingportionofthemainprogramsegmenthasonlyasmallchange relatedtoerrorchecking,whichwe’llgettoshortly.ThetwosubroutinesCalculateCodeandGenerateValueareidenticalwiththeirnamesakesinProgram22-2,saveforsubstitutingMlenforthehardcoded bitlength.Consequently,we’lllimitouranalysistotheerrorcheckingsubroutine,ErrorCheck. AswenotedinourdiscussionofREC-80codeformat,dataissentintheform Byte3 DeviceCode LSB
MSB
TypicalREC-80DataOrganizationSendingOrder Byte2 Byte1 D.C.CheckByte FunctionCode LSB MSB LSB MSB
Byte0 F.C.CheckByte LSB
MSB
AnREC-80checkbyteisformedbytakingthelogicalNOToftheassociateddatabyte—thatis,1’sare changedto0’sandviceversa.Consequently.ifwelookatthedatabyteanditsassociatedcheckbyte,for everycorrespondingbitposition,onebytehasa%0andtheotherbytehasa%1.Thus,ifweaddthedatabyte anditscheckbyte,wealwaysget%11111111or$FF. 534
InfraredRemoteControls We’llaccordinglyimplementafurthererrorcheckbyseeingifCodeValue.Byte3+CodeValue.Byte2 =$FFandifCodeValue.Byte1+CodeValue.Byte0=$FF.ThenewsubroutineErrorCheck performsthisaction,anduponanerrortheGoodFlagiscleared,indicatingcorrupteddataandabrieferror messageisemittedovertheserialport.ToavoidorderofprecedenceproblemswithsomeMBasicversions,I’veusedparenthesestoforcetheCodeVal.Byte3+CodeValue.Byte2andCodeVal.Byte1+ CodeVal.Byte0expressionstobeevaluatedbeforethe<>comparison. ErrorCheck ;checkNOTbytes ;-------- If(CodeValue.Byte3+CodeValue.Byte2)<>$FFThen GoodFlag=0 HSerOut[“BadCheckByte3”,13] EndIf If(CodeValue.Byte1+CodeValue.Byte0)<>$FFThen GoodFlag=0 ;HSerOut[“BadCheckByte1”,13] EndIf Return
Let’slookattheoutputofProgram22-3.BoldfaceindicatesannotationsI’veaddedtotheoutput.I’vealso addedleadingzerostotheHitachiMSBvalues. NakamichiRM-2CDPRemoteControl P22-3 Good:WWWNNWWNNNNWWNNWWNWNNNWWNWNWWWNNMSB:$E619A35CLSB:$6798C53A Good:WWWNNWWNNNNWWNNWWWNWNNWWNNWNWWNNMSB:$E619D32CLSB:$6798CB34 Good:WWWNNWWNNNNWWNNWNWWWNNWWWNNNWWNNMSB:$E619738CLSB:$6798CE31 Good:WWWNNWWNNNNWWNNWWWWWNNWWNNNNWWNNMSB:$E619F30CLSB:$6798CF30 Good:WWWNNWWNNNNWWNNWNNNNWNWWWWWWNWNNMSB:$E6190BF4LSB:$6798D02F Good:WWWNNWWNNNNWWNNWWNNNWNWWNWWWNWNNMSB:$E6198B74LSB:$6798D12E Good:WWWNNWWNNNNWWNNWNWNNWNWWWNWWNWNNMSB:$E6194BB4LSB:$6798D22D Good:WWWNNWWNNNNWWNNWWWNNWNWWNNWWNWNNMSB:$E619CB34LSB:$6798D32C Good:WWWNNWWNNNNWWNNWNNWNWNWWWWNWNWNNMSB:$E6192BD4LSB:$6798D42B Good:WWWNNWWNNNNWWNNWWNWNWNWWNWNWNWNNMSB:$E619AB54LSB:$6798D52A Good:WWWNNWWNNNNWWNNWNWWNWNWWWNNWNWNNMSB:$E6196B94LSB:$6798D629 Good:WWWNNWWNNNNWWNNWWWWNWNWWNNNWNWNNMSB:$E619EB14LSB:$6798D728 NakamichiRM-4TARemoteControl P22-3 Good:WWWNNWWNNNNWWNNWWNWNNNWWNWNWWWNNMSB:$E619A35CLSB:$6798C53A Good:WWWNNWWNNNNWWNNWWWNWNNWWNNWNWWNNMSB:$E619D32CLSB:$6798CB34 Good:WWWNNWWNNNNWWNNWWWWNNNWWNNNWWWNNMSB:$E619E31CLSB:$6798C738 Good:WWWNNWWNNNNWWNNWWNNNNNWWNWWWWWNNMSB:$E619837CLSB:$6798C13E Good:WWWNNWWNNNNWWNNWNNNWNNWWWWWNWWNNMSB:$E61913ECLSB:$6798C837 Good:WWWNNWWNNNNWWNNWNWNNNNWWWNWWWWNNMSB:$E61943BCLSB:$6798C23D
Key Stop Pause 0 1 2 3 4 5 6 7 8 9 Key Stop Pause >> << >| |<
ToshibaSE-R0108RemoteControlVCR/DVD Key P22-3 Good:WNWNNNWNNWNWWWNWNWNNWNNNWNWWNWWWMSB:$A25D48B7LSB:$45BA12ED Pwr Good:WNWNNNWNNWNWWWNWNNNNNWWWWWWWWNNNMSB:$A25D07F8LSB:$45BAE01F VCR/DVD Good:WNWNNNWNNWNWWWNWNWNWNNNNWNWNWWWWMSB:$A25D50AFLSB:$45BA0AF5 0 Good:WNWNNNWNNWNWWWNWWNNNNNNNNWWWWWWWMSB:$A25D807FLSB:$45BA01FE 1 Good:WNWNNNWNNWNWWWNWNWNNNNNNWNWWWWWWMSB:$A25D40BFLSB:$45BA02FD 2 Good:WNWNNNWNNWNWWWNWWWNNNNNNNNWWWWWWMSB:$A25DC03FLSB:$45BA03FC 3 Good:WNWNNNWNNWNWWWNWNNWNNNNNWWNWWWWWMSB:$A25D20DFLSB:$45BA04FB 4 Good:WNWNNNWNNWNWWWNWWNWNNNNNNWNWWWWWMSB:$A25DA05FLSB:$45BA05FA 5 Good:WNWNNNWNNWNWWWNWNWWNNNNNWNNWWWWWMSB:$A25D609FLSB:$45BA06F9 6 Good:WNWNNNWNNWNWWWNWWWWNNNNNNNNWWWWWMSB:$A25DE01FLSB:$45BA07F8 7 Good:WNWNNNWNNWNWWWNWNNNWNNNNWWWNWWWWMSB:$A25D10EFLSB:$45BA08F7 8
535
Chapter22 Good:WNWNNNWNNWNWWWNWWNNWNNNNNWWNWWWWMSB:$A25D906FLSB:$45BA09F6 Good:WNWNNNWNNWNWWWNWNNWNWNNNWWNWNWWWMSB:$A25D28D7LSB:$45BA14EB Good:WNWNNNWNNWNWWWNWWWNNWNNNNNWWNWWWMSB:$A25DC837LSB:$45BA13EC Good:WNWNNNWNNWNWWWNWWNNWWNNNNWWNNWWWMSB:$A25D9867LSB:$45BA19E6 Good:WNWNNNWNNWNWWWNWNNNNNNNNWWWWWWWWMSB:$A25D00FFLSB:$45BA00FF Hitachi“RemoteController” P22-3 Good:NNNNNWWNWWWWWNNWWWWNWNNNNNNWNWWWMSB:$06F9E817LSB:$609F17E8 Good:NNNNNWWNWWWWWNNWNWWNWNNNWNNWNWWWMSB:$06F96897LSB:$609F16E9 Good:NNNNNWWNWWWWWNNWWNNWWNNNNWWNNWWWMSB:$06F99867LSB:$609F19E6 Good:NNNNNWWNWWWWWNNWNNNWWNNNWWWNNWWWMSB:$06F918E7LSB:$609F18E7 Good:NNNNNWWNWWWWWNNWNNWNWNNNWWNWNWWWMSB:$06F928D7LSB:$609F14EB Good:WNNNNWWNNWWWWNNWNNWNWNNNWWNWNWWWMSB:$867928D7LSB:$619E14EB Good:NNNNNWWNWWWWWNNWWNNWNNNNNWWNWWWWMSB:$06F9906FLSB:$609F09F6 Good:NNNNNWWNWWWWWNNWNWNWNNNNWNWNWWWWMSB:$06F950AFLSB:$609F0AF5 Good:NNNNNWWNWWWWWNNWWWNWNNNNNNWNWWWWMSB:$06F9D02FLSB:$609F0BF4 Good:NNNNNWWNWWWWWNNWNWNWWNNNWNWNNWWWMSB:$06F958A7LSB:$609F1AE5
9 Stop >> << Pause Key Pwr VTR/TV Ch+ ChPlay Rec+Play >> << Stop Pause
Noneofthesedatareadscausedacheckbyteerror.And,that’snotunexpected,asthefactthatwe’vereceived32sequentialcorrectwidthbitsprovidesahighprobabilitythatthebitsarecorrect.Mylimitedtest showedno16-bitdeviceanddatacodes,andnotogglebits. IfwechecktheMSB-firstandLSB-firstvaluesagainstthekeyfunctions,theLSB-firstvaluesmakemore sense,sothesemanufactureshavefaithfullyfollowedtheREC-80protocol.And,theyseemtohavemade logicalkeyassignmentsaswell. NumericKey 0 1 2 3 4 5 6 7 8 9
ToshibaKeyCode $0A $01 $02 $03 $04 $05 $06 $07 $08 $09
NakamichiKeyCode $CE $CF $D0 $D1 $D2 $D3 $D4 $D5 $D6 $D7
Figure22-12:Controllingfour LEDswithanIRremotecontrol.
536
InfraredRemoteControls Toshibaencodesthekeyvaluedirectly(key0isassignedvalue10,or$0A),whileNakamichi’scodestrack thekeyvalueaswell,butwithanoffsetof$CE. Let’susethedecodedoutputtoactuallydosomething.We’llonlyturnLEDsonandoff,butthetechniques we’vedevelopedinotherchapterspermityoutoextendtheconceptsinProgram22-4tocontrolotherdevices.Forexample,youmightemitSPIcontrolsignalstoanMCP42010digitalpotentiometerandhavethe outputofastereoaudiosignalincreaseordecreasein1dBstepsinresponsetotheVol+andVol–buttons. I’vewrittenProgram22-4tofunctionwithaHitachicontroller,chieflybecauseitbelongstoano-longerfunctionalVCRandisn’tneededelsewhereinmyhouse.Ofcourse,youmaysubstituteanyothercodes. And,toshowthatbitorderisn’timportantif—asisusuallythecase—weareonlylookinguniquekeycodes, I’veintentionallywrittenProgram22-4withMSB-firstbitorder. PressingthePlay,Stop,PauseorPowerbuttonscausesanLEDconnectedtothePICtolatchonoroff.Each keypressreversesthestatus.Figure22-12showstheLEDconnection. Program22-4 ;Program22-4 ;IRdecoderoutput ;toPinB0.ValuesforGeneric ;remotecontrol32-bitwidth ;Constants ;------------- ;unitduration@20MHzclock Smin Con 2500 ;3500usstartpulseminimum Smax Con 3572 ;5000usstartpulsemaximum Wmin Con 964 ;1350usWidepulseminwidth WMax Con 1393 ;1950usWidepulsemaxwidth NMin Con 214 ;300us Narrowpulseminwidth NMax Con 571 ;800us NarrowPulsemaxwidth MLen Con 32 ;Numberofdatabits PowerPin Con B4 ;LEDonPowerPin StopPin Con B5 ;LEDonStopPin PausePin Con B6 ;LEDonPausePin PlayPin Con B7 ;LEDonPlayPin ;DecodeHitachiinMSBorder Power Con $06F9E817 StopD Con $06F9D02F PauseP Con $06F958A7 Play Con $06F928D7
;Powerbutton ;Stopbutton ;Pausebutton ;Playbutton
;Variables ;----------CodeValue TempArray i WArray GoodFlag FcnStr
;holdsdecoded32bits ;holdsmeasuredwidths ;counter ;fordisplay ;If1,gooddata
Var Var Var Var Var Var
Long Byte(MLen) Byte Word(MLen) Byte Byte(6)
;Initialization ;-------------Clear InputB0 ;HaveLEDsonB4...B7pins Fori=B4toB7 Lowi Next EnableHSerial SetHSerialH115200 HSerOut[“P22-4”,13,13] Main ;------
537
Chapter22
i=0 ;Wefirstwaitforstartpulse PulsInB0,1,Main,1,WArray(0) ;Isitavalidstartpulse? IfWarray(0)<SminThen GoToMain EndIf IfWarray(0)>SmaxThen GoToMain EndIf ;Validstartpulsefollowedby32datapulses Loop PulsInB0,1,Main,1,WArray(i) ASM { bankseli incf i&0x7F,f bankselPortB } Ifi<MLenThenLoop GoSubCalculateCode GoSubGenerateValue IfGoodFlag=1Then GoSubErrorCheck EndIf IfGoodFlag=1Then Pause100 ;gotvalidcodethistime FcnStr=“Unkwn“ ;Nowwetogglepinsbasedonreceivedcodes IfCodeValue=PowerThen TogglePowerPin FcnStr=“PWR“ EndIf IfCodeValue=StopDThen ToggleStopPin FcnStr=“Stop“ EndIf IfCodeValue=PausePThen TogglePausePin FcnStr=“Pause“ EndIf IfCodeValue=PlayThen FcnStr=“Play“ TogglePlayPin EndIf HSerOut[StrFcnStr\6,StrTempArray\MLen,| “MSB:“,iHexCodeValue,13] ELSE ;Removecommentsifyouwanttoseebaddata ;HSerOut[“Error:“,StrTempArray\MLen,| “Value:“,iHexCodeValue,13] EndIf
GoToMain
CalculateCode ;----------- ;Scanthemeasuredwidtharrayandclassifyeachas ;N(narrow),W(wide)orX(outsideNorWwindow) Fori=0to(MLen-1) TempArray(i)=“x” If(WArray(i)>WMin)AND(WArray(i)<WMax)Then TempArray(i)=“W” EndIf
538
InfraredRemoteControls Return
Next
If(WArray(i)>NMin)AND(WArray(i)<NMax)Then TempArray(i)=“N” EndIf
GenerateValue ;----------- ;NowcalculatetheLong=tothe32bits CodeValue=0 ;setto0ifwegetbaddata GoodFlag=1 ;NowconvertW/N/Xtovalues Fori=0to(MLen-1) CodeValue.Bit0=%0 IfTempArray(i)=“W”Then CodeValue.Bit0=%1 EndIf IfTempArray(i)=“x”Then GoodFlag=0 ;ifdon’twantbaddata EndIf ;debugcouldbailouthere ;NoneedtocheckNorx,pre-populatedwith0s ;readassumingsentMSBfirst.Thismaynot ;bethecase,butforourpurposeorderdoesn’t ;matterasweonlylookforuniquevalues ;Datagoesinatright,movetoleft ;everyentryexceptlastone Ifi<>(MLen-1)Then CodeValue=CodeValue<<1 EndIf Next Return ErrorCheck ;checkNOTbytes ;-------- If(CodeValue.Byte3+CodeValue.Byte2)<>$FFThen GoodFlag=0 HSerOut[“BadCheckByte3”,13] EndIf If(CodeValue.Byte1+CodeValue.Byte0)<>$FFThen GoodFlag=0 HSerOut[“BadCheckByte1”,13] EndIf Return End
SinceProgram22-4duplicatesmuchofProgram22-3,we’llconcentrateonthedifferences. PowerPin StopPin PausePin PlayPin
Con Con Con Con
B4 B5 B6 B7
;LEDonPowerPin ;LEDonStopPin ;LEDonPausePin ;LEDonPlayPin
;DecodeHitachiinMSBorder Power Con $06F9E817 StopD Con $06F9D02F PauseP Con $06F958A7 Play Con $06F928D7
;Powerbutton ;Stopbutton ;Pausebutton ;Playbutton
We’veaddedseveralnewconstantdefinitions.We’vealiasedthepinsB4…B7tomoreunderstandablenames, anddefinedthefourMSB-orderkeyvalueswediscoveredintheoutputofProgram22-3.
IfGoodFlag=1Then GoSubErrorCheck EndIf IfGoodFlag=1Then Pause100 ;gotvalidcodethistime FcnStr=“Unkwn“ ;Nowwetogglepinsbasedonreceivedcodes IfCodeValue=PowerThen
539
Chapter22
ELSE
EndIf
EndIf
TogglePowerPin FcnStr=“PWR“
IfCodeValue=StopDThen ToggleStopPin FcnStr=“Stop“ EndIf IfCodeValue=PausePThen TogglePausePin FcnStr=“Pause“ EndIf IfCodeValue=PlayThen FcnStr=“Play“ TogglePlayPin EndIf HSerOut[StrFcnStr\6,StrTempArray\MLen,| “MSB:“,iHexCodeValue,13] ;Removecommentsifyouwanttoseebaddata ;HSerOut[“Error:“,StrTempArray\MLen,| “Value:“,iHexCodeValue,13]
Theindividualpin-set/clearcodeisnotcomplex.Ifwehavereceivedavalid32-bitremotecontrolsignal, wetestitsvalueagainstthefour“action”values.Ifanactionvalueisreceived,wetogglethecorresponding outputpin,anddefineanoutputmessagestringwiththenameoffunction.Toavoidinterpretingthebuilt-in automaticrepeatasrepeatedindividualbuttonpresses,we’veaddedaPause100delaystatementaftera successfuldecode. WehaveslightlysimplifiedtheserialoutputroutinetoomittheLSB-firstordervalue,butaddedthefunction identifyingstring.Here’sasampleoutputfromProgram22-4: P22-4 PWRNNNNNWWNWWWWWNNWWWWNWNNNNNNWNWWWMSB:$6F9E817 PWRNNNNNWWNWWWWWNNWWWWNWNNNNNNWNWWWMSB:$6F9E817 PlayNNNNNWWNWWWWWNNWNNWNWNNNWWNWNWWWMSB:$6F928D7 PlayNNNNNWWNWWWWWNNWNNWNWNNNWWNWNWWWMSB:$6F928D7 StopNNNNNWWNWWWWWNNWWWNWNNNNNNWNWWWWMSB:$6F9D02F StopNNNNNWWNWWWWWNNWWWNWNNNNNNWNWWWWMSB:$6F9D02F PauseNNNNNWWNWWWWWNNWNWNWWNNNWNWNNWWWMSB:$6F958A7 PauseNNNNNWWNWWWWWNNWNWNWWNNNWNWNNWWWMSB:$6F958A7 UnkwnNNNNNWWNWWWWWNNWWNNWNNNNNWWNWWWWMSB:$6F9906F UnkwnNNNNNWWNWWWWWNNWNWNWNNNNWNWNWWWWMSB:$6F950AF UnkwnNNNNNWWNWWWWWNNWNWWNWNNNWNNWNWWWMSB:$6F96897 UnkwnNNNNNWWNWWWWWNNWWNNWWNNNNWWNNWWWMSB:$6F99867 UnkwnNNNNNWWNWWWWWNNWNNNWWNNNWWWNNWWWMSB:$6F918E7 PlayNNNNNWWNWWWWWNNWNNWNWNNNWWNWNWWWMSB:$6F928D7 PlayNNNNNWWNWWWWWNNWNNWNWNNNWWNWNWWWMSB:$6F928D7
Thefourfunctionoutputpinsareinitializedlow,sothefirsttimeafunctionkeyisdecoded,theassociated LEDilluminates.Thenexttime,itisextinguished.Togglingcontinueswithadditionalkeypresses.Receipt ofacodeotherthanoneassociatedwiththefourdefinedkeystriggersan“unkwn”messageandthestatusof thefourLEDpinsisunchanged. ItestedabreadboardversionofFigure22-11withbothaSharpGP1U58xIRreceivermoduleandaVishay TSOP1238integratedIRreceivermodule.Bothmodulesaretunedto38KHz.Ifoundreliabledecodingat 30feetwiththeGP1U58xreceiverandat36feetwiththeTSOP1238receiver.ItestedtheGP1U58xwithoutanIRfilter,buttheTSOP1238hasanintegratedIRfilter.
540
InfraredRemoteControls Finally,ofcoursetheserialoutputdataisintendedtohelpdeveloping,debuggingandtestingtheprogram.It maybeomittedifunnecessary.
IdeasforModificationstoProgramsandCircuits •
• •
ModifyProgram22-4tocontrolanMCP42010digitalpotentiometerusingthecircuitryandconcepts developedinChapter21.WitheachpressoftheVol+buttontheMCP42010shouldstepup1dB;with eachpressoftheVol-buttontheMCP42010shouldstepdown1dB.Aftereachstepchange,storethe currentpositioninEEPROM.Uponprograminitiation,readtheoldpositionfromEEPROMandsetthe MCP42010’svaluetothestoredposition. Whatelsemightyouwishtocontrolremotely?Howwouldyougoaboutit? Chapter22concentratesonreceivingremotecontrolsignals.But,it’snotdifficulttotransmitanREC80signalwithaPIC.Asastartingpoint,developasimple“repeater”orrangeextender.Afteracorrect signalisreceived—onethatpassesthecheckbytetest—replaythesignaltoanIRdiode.Here’sa pseudo-codeoutlineofhowthismightbeaccomplished: Sendastartpulse: LED-onfor9.5ms, LED-offfor4.5ms StepthroughthearrayTempArray(i) SendLED-onfor800uS IfTempArray(i)=W,pausefor1600uS IfTempArray(i)=N,pausefor600uS
•
Goingbeyondrepeatingareceivedremotecontrol,usetheRS-232porttogenerateselectedtransmitted controlcodes.Forexample,areceived+mightgenerateaVol+IRcommand;a–mightgenerateaVol- IRcommand.
References [22-1]
MicrochipTechnologies,Inc.,DecodingInfraredRemoteControlsUsingaPIC16C5XMicrocontroller, AN657,DocumentNo.DS00657A(1997). [22-2] Sonmez,MehmetZ.,InfraredLearner(RemoteControl),CypressMicroSystemsApplicationNote AN2092,Rev.A(2002). [22-3] Archer(RadioShack),TechnicalDataforCatalogNo.276-137,(undated).Briefdatasheetonthe SharpGP1U52XIRdecodermodules. [22-4] VishaySemiconductors,TSOP1100WideBandIRReceiverModuleforRemoteControlSystems,Doc. No.82262,Rev1.3(2003). [22-5] VishaySemiconductors,TSOP12..IRReceiverModulesforRemoteControlSystems,Doc.No.82013, Rev11(2003). [22-6] VishaySemiconductors,TSOP48..IRReceiverModulesforRemoteControlSystems,Doc.No.82013, Rev11(2003). [22-7] SharpElectronicsComponentsGroup,GP1UD26XKSeries/GP1UD27XKSeriesGP1UD28XKSeries/ GP1UD28YKSeriesEnergySavingTypeLowDissipationCurrentIRDetectingUnitforRemote Control,(undated). [22-8] AnexcellentstartingpointforIRremotecontrolInternetresearchishttp://www.epanorama.net/links/irremote.html.Inadditiontoabriefexplanationoftheunderlyingtechnology,thissitehasdozensof usefulcross-linkstoothersiteswithusefulIRinformation. [22-9] InnotechSystems,Inc.,APrimeronRemoteControlTechnology,(undated). [22-10] Seerden,Paul,UsingthePhilips87LPC76xmicrocontrollerasaremotecontroltransmitter,AN10210, PhilipsSemiconductors(2003).
541
CHAPTER
23
ACPowerControl We’velearnedmanytechniquesforswitchingDCcircuits;highsideswitching,lowsideswitching,motor driversandPWMcircuitstomentionafew.Weevenbrieflylookedatswitchinglowvoltage,lowcurrentAC withabidirectionalopticallycoupledFETinChapter3.Thischapterexplorescontrolling120VACpower lineloadswithaPIC.We’llusea200wattincandescentlampload,butthetechniquesofthischaptercanbe extendedtokilowattlevelpowerswitching. Beforewegoanyfurther,pleasestopandreadandunderstandthefollowingwarningstatement. DANGER! Thecircuitsdescribedinthischapterinvolveworkingwith120VACmainspower. SHOULD YOU COME INTO CONTACT WITH ENERGIZED CONDUCTORS, YOU MAY RECEIVE A DANGEROUSSHOCK,WITHTHEPOSSIBILITYOFSERIOUSINJURYORDEATHBYELECTROCUTION. Ifyouarenotexperiencedworkingwith120Vpowersources,pleasedonotbuildtheprojects describedinthischapter. Ifyoudobuildtheseprojects,youmustobserveprudentsafetyprecautions: (a) Do not under any circumstances work on an energized circuit. Unplug the 120 V portionofthecircuitfromthepowerlinebeforeworkingonthecircuit.Beforetouching anycircuitrydoublechecktoverifythatthepowerlineisdisconnected. (b)Donotleaveyourbreadboardcircuitunattended.Ifyouarenotpresent,unplugthe circuitfromthepowerline. (c)Usea3-wire(groundedplug)connectionandwiring. (d)Thedesignshowsa6Afuseandisintendedfordemonstrationusewithuptoa200wattload.Donotincreasethefusesizeoroperatewithagreaterpowerload. (e)Donotmakeconnectionsbetweenyourdevelopmentboardandthepowercontrol boardexceptasshowninthischapter. (f)Usegoodconstructionandwiringpracticewhenyoubuildthepowercontrolboard. UNDERNOCIRCUMSTANCESINSTALLTHESEPARTSONYOURDEVELOPMENTBOARD.
Ifyouhaveanydoubtaboutyourabilitytosafelyworkon120Vcircuitry,readthischapterbutdon’tbuild theassociatedcircuitry. CAUTIONUSINGANOSCILLOSCOPEWITHACPOWERCIRCUITS! ThischapterincludesmanyoscilloscoperecordsofbothACvoltageandcurrent.Undernocircumstances shouldyouuseaPCsoundcardoscilloscopetomeasureAClinevoltages.Thealmostinevitableresult willbeadestroyedsoundcardanddamagetotherestofthecomputercircuitry.
542
ACPowerControl Even if you have a laboratory oscilloscope, you must take care to ensure your oscilloscope is properlygroundedandthatyoudonotinadvertentlyallowthegroundconnectoronthescope probetocontactanenergizedconductor. Finally,youmaybetemptedtoobservecurrentwaveformsusingasmallseriesresistorasacurrent shunt.Don’tdoit.Unlessyouknowexactlywhatyouaredoing,youmaydamageyouroscilloscope andexposeyourselftodangerousrisk.Allofthecurrentmeasurementsinthischapterweretaken withaTektronixTCP202clip-oncurrentprobe,whichisolatestheoscilloscopefromtheACline.
IntroductiontoTriacs Becausetheymaybeunfamiliartomanyelectronicsexperimenters,we’llfirstgothrough“Triacs101.” OurprincipalACpowercontroldeviceinthischapteristhetriac.Theacronym“TRIAC”isformedfromthe wordstriode(three-element)ACsemiconductorswitch.AlthoughtherulesofEnglishusagesaythatacronymsaretobewritteninallcapitalletters,GeneralElectric’ssourcematerialandlaterusagefavorstreating triacasanormalword,writteninlowercaseandcapitalizedonlywhererequiredbysentencestructure.And, sinceGEinventedthetriac,we’llfollowitsusage. Thetriacisamemberofthethyristorfamily,alongwiththeprogrammable unijunctiontransistor(PUT),thebidirectionaldiodethyristor(diac)and,most notably,thesiliconcontrolledrectifier(SCR).Thecommonfeatureamongall membersofthethyristorfamilyisthattheyhavetwostablestates;conducting andnonconducting.Mostthyristorsrequirecurrentinjectionorcurrentremoval fromagateconnectiontobecomeconducting.Thyristorconstructionprovides inherentinternalpositivefeedback;onceathyristorstartsconducting,itstays conducting.Conductioncontinuesaftergatecurrentisremoveduntilthecurrent throughthedevicereducesbelowsomecriticalvalue(the“holdingcurrent”)for acertainminimumtime.Likewise,anonconducting thyristorstaysnonconductinguntilatriggerevent occurs.(Afewuncommonmembersofthethyristor familycanbeturnedofbygateactionundercertain conditions.)
Figure 23-1: Schematic symbolforatriac.
Let’slookattheparticularscionofthethyristorfamilywe’llbeusing,thetriac.Figure23-1showsthe schematicsymbolforatriac.Ithasthreeterminals, thegateandtwootherterminals,identifiedas“main terminal1”and“mainterminal2”orMT1andMT2, respectively.SomeEuropeanmanufacturersidentify thesetwoterminalsas“A1”and“A2”standingfor anode1andanode2.Byconvention,polarityfor voltagereferenceisalwayswithrespecttoMT1. Thus,ifwesaythegateis“positive”itmeansthe gateispositivewithrespecttoMT1. Thegateinitiatesaone-wayaction;abriefgatepulse turnsthetriacon.Onceturnedon,thegatecannotturnitoff.Rather,thecurrentthroughthetriac mustdropbelowsomecriticallevelforaspecified minimumtimeinorderforthetriactocommutate, Figure23-2:Triactriggeringoptions. 543
Chapter23 orturnoff.Sincethe60HzACpowermainsdroptozero120timesasecond,thetriacisself-commutating undermostcircumstances.We’lllookattheturnoffcharacteristicsofthetriaclater,asitmaybeimpossible, withoutancillarycomponents,toturnoffsometypesoftriacswhenconnectedtocertaininductiveloads. AvariantofFigure23-2appearsinalmosteverytriacreference,sowe’llnotbreaktradition.Byconvention, wemapthegateandMT2polaritiesonanX-Yaxis.TheY-axisistheMT2polaritywhiletheX-axisisthe gatepolarity.Thefourpossiblegate/MT2polaritycombinationsthusfallintofourquadrants,identifiedby RomannumeralsI,II,IIIandIV.Figure23-2’squadrantassignmentsaresummarizedasfollows. Gate TerminalMT2
+ –
– Quad.II Quad.III
+ Quad.I QuadIV
Sincebothpositiveandnegativegatedrivecanbeusedtoturnonatriac,whyclassifythegate/MT2relationship?First,notalltriacscanbetriggeredinallfourquadrants;somedevicesarenotQ-IVtriggerable. And,eventhosedevicesthatarefour-quadranttriggerablemaynothaveidenticalgatedriverequirementsin eachquadrant.OurdesignusesQ-I/Q-IIItriggering,whichworkswithalltriacs. Let’stakeaquicklookatthekeyparametersfoundinatriac’sdatasheet.We’llpayparticularattentionto STMicroelectronic’sBTA12-600BWtriacusedinthischapter’scircuits. Gatecurrentandvoltagerequirements—Thecurrentrequiredtotriggerconduction,IGTandthevoltage acrossthegate,VGT,atthiscurrentlevel.TheBTA12-600BWhasamaximumrequiredIGTof50mA andVGTof1.3V.ThelowertheIGT,theeasieritistofirethetriac.Sometriacsaredesignedtointerface directlywithlogicgatesandcanbetriggeredwithacurrentofafewmilliamperes.TheBTA12-600TW, forexample,hasanIGTof5mA.Wewillavoidsensitivetriacs,asthetradeoffforincreasedgatesensitivityresultsinworseperformanceelsewhere.And,aswe’llseelater,wewillnotdrivethegatedirectly fromaPIC,solowgatecurrentdriveisnotanissueinourdesign. TheBTA12-600BWisratedfortriggeringonlyinQuadrantsI-II-IIIandnotforQuadrantIV.The“B” version,BTA12-600B,isratedforallfourquadrants.(We’llexplainthedifferencebetweentheBW “snubberless”triacandtheB“standard”triaclaterinthischapter.) Latchingcurrent—istheminimumcurrentthatthetriacmustcarryinordertolatchintoconductingmode oncethegatedriveisremoved.ItssymbolisIL.IfthetriaccarrieslessthanILcurrentattheinstantthe gatedriveisremoved,thetriacwillreverttoitshighimpedance,nonconductingstate.ILfortheBTA12600BWisspecifiedas70mA. Holdingcurrent—istheminimumcurrentthetriacmustcarryatalltimesinordertostayinconducting mode.ItssymbolisIH.WhentheinstantaneouscurrentdropsbelowIH,andnogatedriveisapplied, thetriacrevertstoitshighimpedance,nonconductingstate.IHfortheBTA12-600BWisspecifiedas 50mA.Thereversiontononconductingstateis,ofcourse,whatallowsustocontrolACcurrentwitha triac;thecurrentdropstozero120timesasecondwith60Hzpowerandifnogatedriveisappliedduringzerocrossing,thetriacturnsoff. dV/dt—Withcertaintypesofloadstriacscanrefusetoturnoff.Iftherateofchangeofvoltageacrossthe triacexceedsitsmaximumdV/dtrating,thetriacwillretriggerandwillnotcommute.TheBTA12600BW’sdV/dtratingis1000V/µs,significantlyhigherthantheBTA12-600B’s400V/µs.Thisisan areawherethesensitivegatetriacisatanenormousdisadvantage;theBTA12-600TW—whichrequires only5mAtriggeringcurrent—hasamaximumdV/dtratingofonly20V/µs.We’llexplorethisdifferenceinmoredetailwhenwediscusssnubberlessversusstandardtriacs.
544
ACPowerControl dI/dt—InadditiontoretriggeringcausedbyhighdV/dt,triacsaresubjecttoretriggeringduetohighrateof changeincurrent,dI/dt,aphenomenarelatedtostoredchargeinthetriac’sjunctioncapacitance.The BTA12-600BW’sdI/dtratingis12A/mswithoutasnubber.Furthermore,thereisinteractionbetween dV/dtanddI/dt.We’llexplorethisinmoredetailwhenwediscusssnubberlessversusstandardtriacs. Maximumcurrent—ThemaximumRMSon-statecurrentisIT(RMS)andthemaximumnonrepetitivepeak currentisITSM.We’llseethatevenforanincandescentlampload,thepeakturn-oncurrentcanbemany timesgreaterthanthesteadystatecurrent.TheBTA12-600BWisratedat12Asteadystateoncurrent and120Anonrepetitivepeakcurrent. VDRM—Therepetitivepeakoff-statevoltage,i.e.,thevoltagethatmaybeappliedacrossthetriacwhenitisin theoffstatebeforeun-triggeredconductionoccurs.ApplyingmorethanVDRMcausesthetriactotoggle intoconduction;thetriacisnotnecessarilydamaged,butunexpectedapplicationofvoltagetotheload willoccur. Maximumgatecurrent—isthemaximumcurrentthatmaybeappliedtothegate,IGM.TheBTA12600BW’sIGMis4A. VT—istheon-statevoltageacrossthetriac.FortheBTA12-600BW,themaximumVTis1.55V. Package—Triacsgenerateheatwhenswitchinghighcurrents,soproperheatsinkingisimportant.Intheoff state,thecurrentthroughthetriacisnegligible—typicallyafewmicroamperes—andnothermalload ispresented.Whenintheonstate,thetriachasavoltagedropofVT.SupposeweuseaBTA12-600BW toswitch12Aandthetriacisusedasasimpleswitch;offoron,withnopowercontrolimplemented. Whenon,thetriacwilldissipateapproximately12A*1.55V=18.6watts.Thethermalresistanceof aBTA12-600BW,junctiontocase,orRTH(j-c),is2.3°C/watt.Themaximumoperatingjunctiontemperature,Tj,is125°C.Let’sseewhatsizeheatsinkisrequired.We’llassumetheambienttemperatureis 35°C,andthatwewishtokeepthejunctiontemperaturebelow100°C. AswelearnedinChapter3,temperatureandheatflowcanbemodeledanalogouslytoelectricalcurrent andresistance.Ifthetriacdissipates18.6watts,thetemperaturerisejunction-to-caseis18.6watts×2.3°C/ watt,or43°C.Inorderforthejunctiontemperatureisnottoexceed100°C,thecasetemperaturemustnot exceed100°–43°,or57°C.Iftheambienttemperatureis35°C,therequiredheatsinkthermalresistance canbecalculatedas(57°C–35°C)/18.6watts,or1.2°C/watt.Meetingthisobjectiverequiresaserious heatsink,likelywithforcedaircooling.We’llkeeptheloaddownto1.7Aorless,wherealmostanysmall heatsinkwillsuffice.(Repeatingthesecalculations,wecandeterminethatthetotaltriacdissipationis2.6 watts,correspondingtoajunctiontemperatureriseof71°Cforasmallheatsinkwithathermalresistance of25°C/watt.) Youmayhavenoticedourthermalcalculationdonotincludeamicasheetorotherelectricalinsulator betweentheheatsinkandthetriac.Anexternalinsulatorisn’tnecessarybecausetheBTA12-600BWhas aninsulatingceramicpadencapsulatedinitsTO-220package.(TheBTBseriesdevicesdonothavean internalinsulator.)
SnubberlessversusStandard;dV/dtanddI/dtIssues Inconcept,atriacisconstructedfromtwothyristorsinreverseparallelformedontoonepieceofsilicon. Withoutbecomingoverlyinvolvedinsemiconductorphysics,itispossiblethatatthemomentoftriacturnoff,unrecombinedchargecarriersfromonethyristorcauseinducedgatechargeintheotherthyristorand thusfalselytriggerconduction,aconditionknownas“commutationfailure.”PhilipsSemiconductor’sFacts Sheet13[23-25]explainsthecommutationproblemasfollows: Theprobabilityofanydevicefailingcommutationisdependentupontherateofriseofreversevoltage (dV/dt)andtherateofdecreaseofconductioncurrent(dI/dt).ThehigherthedI/dtthemoreunrecombinedchargecarriersareleftattheinstantofturn-off.ThehigherthedV/dtthemoreprobableitisthat 545
Chapter23 someofthesecarrierswillactasgatecurrent.Thusthecommutationcapabilityofanydeviceisusually specifiedintermsoftheturn-offdI/dtandthere-applieddV/dtitcanwithstandatanyparticularjunctiontemperature. dI/dt CalculatingdI/dtissimpleenough,assumingwearedealingwithalinearload,thatis,onecomposedof resistive,inductiveandcapacitiveelementsonly.AssumethattheRMScurrentthroughthetriacandloadis I.Theinstantaneoustriaccurrentimustbe: i = 2 I sin(2 πft + φ) where: istheRMScurrentthroughthetriacandload(thesquarerootof2multiplierisnecessarysinceIis statedinRMSamperes.) Fisthelinefrequency,60HzinNorthAmerica. tisthetime,measuredfromsomearbitrarystartingpoint φisthephaseshiftresultingfromanonresistiveload. Fromintroductorycalculus,weknowthederivative,di/dt,ofthisexpressionis: di = 2 I × 2 πf × cos(2 πft ) dt We’reinterestedinthemaximummagnitudeofdi/dt,sowecansetthecos(2πft)termto1,ascos(x)isalwaysintherange–1…1.Substitutingnumericalvaluesfora60Hzsupplyfrequency,wefindthemaximum di/dtis: di = 533I A/secor0.53I A/ms dt maximum
TheBTA12-600BW’sdI/dtratingis12A/ms.ThisvaluecorrespondstoanRMScurrentof22.6A,wellover thedevicescontinuousratingof12ARMS.Hence,weneedonlybeconcernedwithexceedingthisdevice’s dI/dtratingwithloadsthathaveshort-termcurrentsurges,suchasincandescentlampsormotorsatstartup. Youmaybethinking“iftheloadisinductive,doesn’tthevoltagefromthecollapsingfieldinduceacurrent inthetriacthatmustbeconsidered?”Theanswerisno,becausethetriacwillcommuteonlyatessentially zerocurrentandsinceaninductor’sstoredmagneticenergyisproportionaltothesquareofthecurrent,there isnostoredfieldwhenthereiszerocurrent.Hencethereisnoappreciablemagneticfieldtocollapseatthe instantthetriacswitchesoff. dV/dt ThedV/dtratingrelatestotherateofvoltagechangeacrossthetriacattheinstantofcommutation.Ifthe triacisoperatingintoaresistiveload,wemayusetheapproachweusedtodeterminedI/dttocalculatedV/ dt.Theinstantaneousvoltagevacrossthetriacis: v = 2V sin(2 πft ) where: VistheRMSvoltageacrossthetriac(thesquarerootof2multiplierisnecessarysinceVisstatedin RMSvolts.) Fisthelinefrequency,60HzinNorthAmerica. tisthetime,measuredfromsomearbitrarystartingpoint.(Nophaseangleφisrequired;weassumethe phasereferenceis0withrespecttothevoltage.) 546
ACPowerControl Likewise,dV/dtforaresistiveload,60Hzpowerat120VRMSis: dV = 2V × 2 πf × cos(2 πt ) dt ThequantitydV/dtisevaluatedatthetimewhenthecurrentiszero;foraresistiveload,thecurrentzero coincideswithvoltagezero—thatis,at0,180,360degrees,andsoon.Hence,themagnitudeofcos(2πt)is1 andthenumericalvalueofdV/dtis: dV = 2 × 120 × 2 × π × 60 × 1 = 64 × 103 V/sor0.064V/µs dt
TheBTA12-600BW’sdV/dtratingis1000V/µs, 10,000timesmorethanourcalculatedvaluefora resistiveload.Wecansafelyconcludethatweare unlikelytohaveadV/dtproblemwithaBTA12600BWwhileswitchinga120Vresistiveload.
But,supposewehaveaninductiveload,sucha motor.Thecurrentandvoltagethroughthetriac andtheloadarenolongerinphase,asillustrated inFigure23-3.Atthetimethetriacsnapsintononconductivemode,thevoltageacrossthetriacis,in theworstcase(foraphaseangleof90°between VandI)thepeaklinevoltage,170V.And,the Figure23-3:dV/dtissuesintriacturnoffofinductiveload. triac’sswitchingspeedmaybeontheorderofa fewmicrosecondsorless.Hence,dV/dtcaneasily reachhundredsofvolts/microsecond.Theactual dV/dtdependsontheload,strayinductanceand capacitanceandthetriac’sparameters. AcommonsolutiontodV/dtproblemsistoadd anRC-snubbernetworkacrossthetriac,asshown inFigure23-4.TheRCnetworkslowstherateof changeinappliedvoltageandthusdropsthedV/dt belowthetriac’srating.References[23-18]and [23-21]shouldbeconsultedfordetailsonsnubber design.
Figure23-4:Typicalsnubbercircuitforinductiveloads.
Manynewtriacs,however,arebuiltwithsuchahighdV/dtratingthatitisunlikelythatanexternalsnubber networkwillprovenecessaryevenwithhighlyinductiveloads.WecanseethisbycomparingthedV/dtratingsofthemembersoftheBTA12-600triacfamily: TriacVariant BTA12-600TW BTA12-600SW BTA12-600CW BTA12-600BW BTA12-600C BTA12-600B
Description 5mALogicLevel 10mALogicLevel 35mASnubberless 50mASnubberless 25mAStandard 50mAStandard
GateDrive(mA) 5 10 35 50 QI-II-III25/Q-IV50 QI-II-III50/Q-IV:100
547
MaximumdV/dt(V/µs) 20 40 500 1000 200 400
Chapter23 ThedirectcorrelationbetweenthegatesensitivityandtherateddV/dtisobvious;asthedeviceismademore sensitivetopermitlowergatecurrent,itbecomesmoresensitivetofalsegatetriggeringcausedbydV/dt factors.Moreimportantly,thedevicewe’vechosen,theBTA12-600BWis50timeslesssensitivetodV/dt concernsthanitslogiclevelsisterdevice.(AllBTA12-600devicesareratedfor600volts/12Acontinuous operation.)Thus,withalmostallloads,evenhighlyinductiveloads,thesnubberlessdevicewillproperly commutewithoutanexternalsnubbercircuit.
TriggeringaTriac Totriggerthetriacwemustinjectcurrentintothegate.InthecaseoftheBTA12-600BW,theminimumgate triggercurrentis50mA,andthepeakratedgatecurrentis4A,durationnottoexceed20µs. Howdowegoaboutcontrollingthetriac’sgate?WemightconnectitdirectlytothePIC,throughanauxiliarydrivertransistorandletthePICinjectcurrentintothegate.Thisisaverybadideaforexperimenting,as forittoworkonesideofthePIC’spowersupplymustbeconnectedtothehotpowerlineconductor.Don’t doit!TheresultcouldbetodestroynotonlyyourPICandtheICD,butyourcomputeraswell.We’llleave thatapproachtoexperiencedengineerswiththecorrectequipmenttodoitsafelyandwhereitisnecessary towringeverylastcentoutofthedesign.We’llisolatethetriacandthepowerlinefromthePIC,theICD andyourcomputerwithanopto-isolatortriactriggerdevice. Figure23-5showstheschematicsymbolforthetwotypesofdeviceswe’lluse.Bothareinexpensive,small devices,packagedina6-pinDIPformat.Theyaresimilartotheopticalisolatorsthatweconsideredin Chapters3and4,excepttheoutputdeviceisnotatransistor,butasmalltriac.WhentheLEDilluminates, thecoupledtriacswitchestoaconductivestate.PhotonsfromtheLEDsubstituteforphysicalgatecurrent. Byitself,thetriacintheopto-isolatorcan’tcarryenoughcurrenttooperate muchofaload,butit’smorethanadequatetotriggeralargertriac,suchasour BTA12-600BWdevice.We’llusetwoopto-triacdevices;aVishayK3011Panda FairchildMOC3032M.Manysimilardevicesareavailablefromothermanufacturersandthere’snothingparticularlycriticalaboutthesetwodevices. K3011P—isa“randomphase”device,withatypicalLEDcurrentof10mAand acorrespondingforwardvoltageof1.5V.Thetriacportionofthedeviceis ratedat100mAcontinuous,1.5Apeakandwillwithstand250V. MOC3032M—Isazerocrossingtriggerdevice,withatypicalLEDcurrentof10 Figure 23-5: Optically mAandatypicalcorrespondingforwardvoltageof1.25V.Thetriacportion triggeredtriactypes. ofthedeviceisratedapeakcurrentof1A,andwillwithstand400V. Thedifferencebetweena“randomphase”and a“zerocrossing”deviceisthatarandomphase opto-triacmaybetriggeredatanytimeduringthe voltagecycle.Azerocrossingdevicehasadditionalcircuitrythatinhibitsthetriacfrombeing triggered,exceptwhentheACvoltageisatazero crossing.Whenweexaminephaseandcyclecontrol,we’llseewhyweneedbothtypeofdevices. Figure23-6showshowweuseanopto-triacto triggerourmainpowercontroltriac.Althoughthe figureshowsazerocrossingopto-triac,thesame configurationisusedfortherandomphasedevice. Figure23-6:TypicalisolatedtriactriggeringfromPIC. It’snecessarytolimittheopto-triac’soutputcur548
ACPowerControl rentwithaseriesresistor,R1inFigure 23-6.ThemaximumpermittedpeakcurrentoftheMOC3032Mis1.0A,sowe cancalculateR3’svalue: 2 × 120V = 170Ω 1A Sincethetriggeringgatecurrentisonly 50mA,thiswillgiveusmorethan enoughgatedrive.R3shouldbea1-watt resistor.Thenearest5%standardvalue is180ohms,whichshouldbeused.The worst-caseinstantaneouspowerdissipatedbyR3is160watts(triacfiredat90 degrees)buttheturn-ontimeofatypical triacis5µsorless,atwhichtimethe drivingvoltageisremoved—itssourceis thepotentialdifferencebetweenMT1and MT2,whichdropsto1.5Vafterthetriac fires.Hence,theworst-casetimeaveraged powerdissipationofR3,assuming120 pulses/sec,is0.1W.Toavoidhotspots andpossibleresistorfailure,however,R3 Figure23-7:Possibletriacconnectionarrangements. shouldbeatleasta1-wattratedresistor. R3 =
Figure23-7isasimplifiedviewofthefourpossiblewaystoconnectthetriacwiththeloadandtriggerdrive. IpreferFigure23-7’sCircuit“D”fortworeasons: • Asamatterofsafety,circuitsAandBareunacceptable.Contrarytogoodsafetypractice,whenthetriac isoff,bothsidesoftheloadremainconnectedtothehotsideofthe120Vsupplymains.Aswitch,such asthetriac,whenoffshouldisolatetheloadfromthehotsideofthemainssupplyandnotexposethe usertoasourceofunexpectedvoltage. • CircuitsCandDusethetriac,whenoff,toisolatetheloadfromthehotsideofthemainssupplyand thusdonotsufferthesamesafetyproblemascircuitsAandB.CircuitCtriggersthetriacinquadrants IIandIV,however,andisthusincompatiblewiththeBTA12-600BWsnubberlesstriacthatcannotbe triggeredinquadrantIV.ItwouldworkwiththestandardmemberoftheBTA12-600family,however.
PhaseandCycleControl Wecanusethetriacinatleastthreecontrolconfigurations: • Off/oncontrol,similartoaswitchorrelay; • Phasecontrol,whereweturnthepoweronpartwaythroughanACcycle; • Cycle-control,whereweturnthepoweroffandonforanintegernumberofwholeACcycles. Off-oncontroliseasytounderstand;thetriacreplacesaswitchorarelay.Thepowertotheloadiseitheron orofffora“long”time.“Long”inthiscontextmeansformorethanafewcyclesofAC. Phasecontrolisthemostcommoncontrolmechanismassociatedwithtriacs.Tocontrolvoltagetotheload, wedelayfiringthetriac.For60Hzpower,onehalf-cycleoccupies8.333ms,soifwetriggerthetriac4.167 msafterthestartofacycle,weturnthetriaconhalfwayintothehalf-cycle,orat90degreeswithrespectto thefullcycle.Figures23-8,23-9and23-10illustratetriggeringthetriacat45degrees,90degreesand135 549
Chapter23
Figure23-9:Triggerat90degrees.
Figure23-8:Triggerat45degrees.
degrees,respectively.Ineachfigure,thebottomplot showstheinputwaveformandtheupperplotshows theoutputvoltageorcurrentintoaresistiveload.(We triggerboththepositiveandnegativehalf-cyclesat thesamephasedelayafterthezerocrossings.) Bychangingthetriggeringpoint,wechangethe voltageorpowerdeliveredtotheload.It’simportant tounderstand,however,thatthedeliveredvoltage andpowerisnotlinearlyrelatedtothefiringpoint phase.Figure23-11showshowtheRMSandaverage voltagesvarywithrespecttothefiringanglefora120 Figure23-10:Triggerat135degrees. Vsource.TheRMSvaluegovernspower-relatedapplications,suchasincandescentlamps,orresistiveheaters.Theaveragevaluerelatestodevicesthatfunction onaverageorpeakvoltagelevels;suchasanunregulatedDCpowersupply,ormostinexpensiveanalogand digitalvoltmeters.ThesemetersmaybecalibratedintermsofRMSvoltage,butactuallyrespondtoaverage voltage,computingRMSbymultiplyingtheaveragevoltagetimesaconstant.Socalled“trueRMS”meters areavailablethatmeasuretherealRMSofthewaveform. Powerintoaconstantresistance(andaincandescentlampisnotaconstantresistance)isproportionaltothe squareoftheRMSvoltage,sohalf-powercorrespondstonothalfRMSvoltage,butrather70.7%ofRMS voltage.Figure23-12isanormalizedversionofFigure23-11,anditaddsthenormalizedpowerdeliveredto aconstantresistanceload. Figure23-12showstwoimportantpoints:First,toobtainalmostcompleteloadpowercontrol,weneedonly controlthefiringangleovertherangeofabout20…160degreesandsecond,evenintherange20…160 degrees,powerversusfiringangleisnotparticularlylinear.Ifourobjectiveistoadjustpowertotheload,it requiresalook-uptableorothermechanismtotranslatethedesiredpowerleveltothefiringpointangle. CycleControlinvolvessendinggroupsofwholecyclesofvoltagetotheload,asillustratedinFigure23-13. Theadvantageofsendingwholecyclesisthatallpowerswitchingisatzerocrossingsandhencelittle,if any,radiofrequencyinterferenceisgenerated.Inaddition,itpermitssofterstartofloads,suchasincandescentlamps,withlowcoldresistance.Cyclecontrolshouldnotbeusedwithunequalpositiveandnegative half-cycles,asshowninFigure23-14,sinceitintroducesaDCcomponentintothepowerline.ADCcomponentcandamagetransformersandotherdevicesconnectedtothepowermains.Cyclecontrolisn’tusable withincandescentlamps,astheresultingflickerishighlyobjectionable. 550
ACPowerControl
Figure23-11:ChangeinaverageandRMSvoltageversus triggerangle.
Figure23-12:NormalizedchangeinaverageandRMS voltageandpowerversustriggerangle.
Figure23-14:CycleswitchingwithDCcomponent.
Figure23-13:50%powercontrolbysendingalternate cycles.
PowerControlBoard Figure23-15showsthepowercontrolboardanditsinterfacewiththeModel2840PICprototypeboard. Undernocircumstancesshouldyoubuildthepowercontrolboardusingaplug-in,solderlessprototype board.Solderlessprototypeboardsaredesignedtoworkwithlowcurrent,lowvoltagecircuits,andmustnot beusedforhighpower,highvoltageprojectssuchaswearedealingwithhere.I’lldiscussthe“Manhattanstyle”constructionthatIusedtobuildmyexperimentalpowercontrolboardlaterinthissection.Let’sfirst gothroughthecircuitdesign.
PowerControlBoard—Design T1isa120Vto10Vstep-downtransformer.IusedaStancorSW-210,butthisisanoncriticalpart.Any smalltransformerwithasecondaryvoltagebetween5and15voltsRMSshouldwork.Thesecondarydraws lessthan2mAcurrent,soaphysicallysmalltransformerisperfectlyadequate.(TheSW-210isratedat10 Vat110mA.AHammondmodel164D10isasuitablesubstitute.)T1’ssecondaryprovidesazero-crossing referencetothePIC.
551
Chapter23
Figure23-15:PowercontrolboardandconnectiontoPIC.
Thepowercontrolboardalsoprovidesmountingfortheopto-triaccoupler,andthetriac.Iconstructedmy powercontrolboardwithasocketfortheopticalcouplersoIcouldswitchbetweenrandomphaseandzero crossingmodels.ImountedbothaBTA12-600BWsnubberlesstriacanditsnormalsibling,aBTA12-600B triac,tothepowercontrolboardsothatIcouldexperimentwithbothversions.Iusedastandard0.1”spacing3-pinheaderjacktoconnectthetriacpinstotherestofthepowercontrolboard,permittingmetounplug onetriacandconnecttheotherinamatterofseconds,after,ofcourse,unpluggingthepowercontrolboard fromtheACmainssupply.Ifyouarenotinterestedinexperimentingwithbothtriacs,justinstallaBTA12600BWmodel. R3,thepeakopto-coupleroutputcurrentlimitingresistorshouldbeatleasta1-wattrateddevice.Although theaveragepowerdissipatedbyR3issmall,thepeakpoweris160watts,whichmaycauselocalizedheating ofaphysicallysmallresistor,therebyleadingtofailure. Iincludeda6Afuseinmypowercontrolboardasanadditionalsafetymeasure.Thesuggestedsnubberis intendedforexperimentationandisnotnecessarywiththerecommendedBTA12-600BWsnubberlesstriac. Ifyoudoexperimentwithasnubber,C1mustberatedforACservice,withaminimumofa600Vratingas wellasratedforthecalculatedcurrent.Ametallizedpolyestercapacitorisoftenusedinthisapplication. Thiscircuitisnotintendedforanypurposeotherthaneducatingthereader.Itomitsmanythingsnecessary forunattended,longtermoperation,suchasasmallerprotectivefuseforT1,andradiofrequencyinterferencesuppressionfiltersonboththeinputandoutputpowerconnections.
552
ACPowerControl PowerControlBoard—Construction Figures23-16and23-17showmyprototypeboard.Iused“Manhattanstyle”construction,asdescribedin Reference[23-24]butwithonemajorchange.SincetheACmainsconnectionsandtheloadconnectionsuse largewire,thesupergluenormallyusedtoattachpadstothePCBsubstratedoesn’tprovideadequatemechanicalstrength.Iusedquicksettingepoxyinstead.Ialsoattachedtheincomingpowerlinetothesubstrate withasmallclamp.Ishouldhavealsoclampedtheoutputcableaswell.Boththeinputandoutputcableare fromanoldcomputerpowercord.Theoutputcableisapproximately10incheslongandhasattachedtoit astandardACconnectioncablejack,obtainableatanygoodhardwarestore,whichpermitsyoutoplugina lamporotherload.
Figure23-17:Powercontrolboard,view2.
Figure23-16:Powercontrolboard,view1.
Theopto-triacsocketismountedonanupsidedown(solder-sideup)RadioShackprototypeboardmodel 276-159.(Youonlyneedone-halfofthe276-159board.)Iattachedthe276-159boardwithfour6-32pan headmachinescrewsandnuts,butyoucouldepoxyittothePCBsubstrate. Theconnectionsbetweenthepowercontrolboardandthe2840DevelopmentBoardaremadethroughfour 18-inchlongjumperwires.Thejumpersaresolderedtopadsonthepowercontrolboardwiththeotherend strippedforinsertionintothe2840DevelopmentBoardboard. TheBTA12-600BWandBTA12-600Btriacsaremountedwith6-32panheadmachinescrewsandsmall heatsinks.AWakefield231-137PABorsimilarheatsink isadequateforthemaximumrecommendedoperation powerlevelof200watts.SincetheBTA12-600BWand BTA12-600Bhaveinternalinsulators,separatemica orotherinsulatorisnotrequired.Mosttriacsdonot haveinternalinsulators,soifyousubstituteadifferent device,youmayneedtoinsulatethetriaccasefromthe heatsinkandPCBsubstrate. Foratestload,Iuseapairof100wattincandescent lamps,screwedintoporcelainsocketsmountedona smallwoodbase,asseeninFigure23-18.Itwouldbe justaseasy,ofcourse,touseastandardtablelamp.
Figure23-18:Lamploadfortriactest.
PostConstructionCheckout Afterconstruction,useyourohmmetertocheckyourwiringinaccordancewiththefollowingtable.Before connectingyourohmmeter,againverifythatthepowercontrolboardisnotconnectedtotheACmains powersupply!
553
Chapter23 MeasureBetween Green–WhiteConductorsonInputandOutput. Green–BlackConductorsonInputandOutput. WhiteConductortoBlackConductoronInput. WhiteConductoronInputtoWhiteConductoron Output. BlackConductoronInputtoBlackConductoron Output. T1secondarytoGreen,BlackandWhite conductorsonbothinputandoutputside. OptoLEDconnectionstoGreen,BlackandWhite conductorsonbothinputandoutputside
ShouldRead >1Megforbothmeasurements.Shouldbean opencircuit. >1Megforbothmeasurements.Shouldbean opencircuit. Approx.1000ohms(dependsonT1asyouare measuringT1’sprimary.) <1ohm.(Shouldbedirectionconnectionbetween thesetwopoints.) >100K(Measuringacrosstriac;shouldbe essentiallyanopencircuit.) >1Meg.Shouldbeanopencircuit. >1Meg.Shouldbeanopencircuit.
Next,performano-conductiontest.Plugthetestloadintothepowercontrolboard’soutputsocket.Ifyou areusingalamp,makesurethelamp’sswitchison.Positionthepowercontrolboardwhereitwillnotbe disturbedandwhereyouwillnotaccidentallycomeincontactwithit.Thenplugthepowercontrolboard’s inputpowerconnectionintotheACmainssocket.Nothingshouldhappen;thetestloadshouldremainunpowered.Afterthistest,disconnectthepowercontrolboardfromtheACpowermains.
Componentson2840PrototypeBoard ResistorR2andLEDD1ontheprototypeboardareinserieswiththeLEDcontainedwithintheopto-triac coupler.D1providesavisualcheckoftriactriggerpulses,whileR2limitsthecurrentthroughtheLEDsto approximately15mA. Inordertoknowwhentotriggerthetriac,thePICmustknowwhenoneAChalfcycleendsandthenextone begins.WeuseanMCP601op-amprunningopenloopasalimitertoproduceasquarewavezerocrossing outputthatfollowsthe60HzlinebyfeedingitsinputwiththesecondaryofT1.Figure23-19showsthe inputandoutputtothelimiter.TheMCP601isn’taparticularlyfastop-ampandoverdrivingitasalimiter furtherslowsitsresponse.Figures23-20and23-21showariseandfalltimeofaround3.6µs,butthisis perfectlyacceptableforourpurpose,asat60Hz,3.6µsrepresentslessthan0.1degree.
Figure23-20:MCP601LimiterOutputRiseTime; Ch1:T1Secondary;Ch2:MCP601Output.
Figure 23-19: Limiter Input/Output Ch1: T1 Secondary;Ch2:MCP601Output.
554
ACPowerControl Microchip’sspecificationsfortheMCP601statethatitis permissibletodrivetheinputpinsbeyondVDD/VSS,solong asthecurrentdrawndoesnotexceed2mA.R1,a24K resistor,limitsthepeakcurrentintoU1to2mA.(T1’s secondarymeasuresatapproximately48Vpeak-to-peak. Smalltransformerswithhighresistancewindingsoftenhave highunloadedsecondaryvoltages.)WhenconnectingT1’s secondary,it’sdesirable,butnotnecessary,tohaveU1’s outputbehighwhenthehotsideoftheAClineispositive. Thecircuitsandsoftwareinthischapterworkwitheitherthis phase,orthereversephase,butalloscilloscopeillustrations aretakenwithanin-phaseconnection.Theminusinputpin Figure23-21:MCP601LimiterOutputFallTime; andtheothersideofT1’ssecondaryismaintainedat+2.5V Ch1:T1Secondary;Ch2:MCP601Output. DCbyaTexasInstrumentsTLE2426“railsplitter”IC.Ifa TLE2426isnotavailable,aresistivevoltagedividercouldbesubstituted,comprisedoftwo470ohmresistorsinseries,with470µFbypasscapacitorfromthecommonpointofthetworesistorstoground.
Programs Program23-1 We’llstartwithasimpleobjective;toblinkthelightbulbloadoffandoninasequence—onfor5seconds andofffor15seconds.ForProgram23-1,youshouldinstalltheMOC3032Mzero-crossingopto-triac.With thepowercontrolboardunplugged,connectthetransformersecondaryjumpersandtheopto-triac’sLED pinsasshowninFigure23-15.Placethepowercontrolboardinasafelocation,whereyouwillnotaccidentallytouchanyexposedwiringandwhereitnotbeknockedoffyourworkbench.Connectthelamploadto theoutputsocket.Then,connectthepowerboardtotheACpowermainsandrunProgram23-1. ;Program23-1 ;Off/Oncontrolwithoptodriver ;Constants ;---------OnTime OffTime OptoPin
Con Con Con
5000 ;ontime(seconds) 15000 ;offTime(seconds) C0 ;pinwithoptooutput
Main HighOptoPin PauseOnTime LowOptoPin PauseOffTime GoToMain End
RunningProgram23-1shouldflashthelampinaccordancewiththeOnTimeandOffTimeconstantvalues. TheprogramtakesOptoPin(C0)highfor5seconds,whichtriggerstheopto-triac,inturntriggeringthe maintriac,completingthecircuitbetweentheACmainsandthetestload.WhenOptoPingoeslow,the opto-triacisnolongertriggered,themaintriaccommutesatthenextcurrentzerocrossingandthetestload isdisconnectedfromtheACmains. Figure23-22showstherelationshipbetweentheLEDtriggercurrentandtheloadcurrentwhenweusea zero-crossingcontroller.TwopointsinFigure23-22deservefurtherdiscussion.First,pinC0goeshighseveralmillisecondsbeforetheACcurrentcommences.SinceProgram23-1appliespowertotheLEDwithout referencetotheACzerocrossingtime,weseethezerocrossingcircuitryintheMOC3032Matwork;al555
Chapter23 thoughtheLEDispowered,theMOC3032Monlytriggersat azerocrossing.Second,notethelargeinitialcurrentinrush. Channel2inFigure23-22is2A/division.Thepeakcurrent drawofthe200wattbulbsisapproximately13A.Afterabout fivecycles,thelampfilamentshavereachedsteadystatetemperatureandthecurrentdrawisstabilizedatapeak-to-peak currentof4.4A,correspondingtoanRMScurrentof1.7A,as expectedfora200wattload. Imeasuredthecoldresistanceofthetwo100wattincandescentbulbsinparallelas5.33ohms.Thisimpliesthatwitha zero-impedanceACsourcewemightseeapeakcurrentof 32Aifthetriacfiresexactlyatthepeakvoltagepointinthe ACcycle.(Thiscan’thappen,ofcourse,solongasweusea zero-crossingtriggerdevice.)Now,theACmainswiringin myworkshopisn’tzeroresistanceasthecircuitbreaker,the ACwiring,theplug,thesocket,thelinecordandthetriac allhavesomeresistance.And,perhapsmoreimportantly,the filamentina100-wattincandescentlampheatsupquickly anditsresistanceincreasedseveralfoldbythetimethefirst ACwaveformpeakarrives.Basedonapeakcurrentof13A, thelampresistance(bothlampsinparallel)increasedto13 ohmsbythetimethepeakvoltageoccurred,a2.5:1increase in4.1ms.(Youcanusethisinformationtodeterminethat after4.1msthefilament’stemperatureis650°Kandthat itssteady-statetemperatureisabout2500°K.The“official” colortemperatureofa100wattincandescentbulbisaround 2850°K,soourmeasurementtechniquelikelyneedsabit morecarethanwecasuallygiveithere.)
Figure 23-22: 200 Watt Incandescent Lamp Turn-On / Zero Crossing Ch1: Trigger to Triac; Ch2:CurrentThroughLoad.
Figure23-23:200WattIncandescentLampTurnOn/RandomPhaseTriggerCh1:TriggertoTriac; Now,disconnectthepowercontrolboardfromtheACmains Ch2:CurrentThroughLoad.
supply,removetheMOC3032MandinstalltheK3011P randomphaseopto-triac.ReconnectthepowerandrunProgram23-1again.Theresultsareidentical,atleast asfarasthenakedeyeperceivesthelampillumination.Howeverwhenweexaminethestart-uptransient weseequiteadifferencefromthezerocrossingcase.Figure23-23showsthecurrentbeginssimultaneously withLEDtrigger,andthatthepeakinrushcurrentis18.3A,nearly50%abovethezero-crossingcase.Note thatFigures23-22and23havedifferentverticalscales.)Sincethetriacistriggeredatarandomphasepoint, wearealmostguaranteedthattheturn-onwillbeanonzerovoltagepoint.Intheworstcase,turn-oncoincideswiththeAClinepeak,170V,andtheinstantaneouscurrenthasatheoreticalmaximumvalueof32A, aswecalculatedabove,withlimitingtoalesservalueduetotheresistancesmentionedearlier.Thehigher inrushcurrentwithrandomphasestartingismorestressfultoboththefilamentsandtherestoftheACcircuitry,includingthetriac.Thefastcurrentrisealsomaygiverisetoradiofrequencyinterference. Program23-2 Next,let’strycyclecontrollingtheload.Program23-2triggersthetriacforadefinednumberofwhole cyclesandthenidlesforanotherdefinednumberofcycles,andrepeatsthison/offratioindefinitely. First,disconnectthepowercontrolboardfromtheACmainsandreinstalltheMOC3032Mzero-crossing opto-triac.Then,reconnectthepowerboardtotheACpowermainsandrunProgram23-2. 556
ACPowerControl ;Program23-2 ;WholeCycleControl ;Constants ;---------HTab OptoPin GateDur
Con Con Con
9 C0 500
;horizontaltab ;pinwithoptooutput
;Cyclebasemustbeamultipleof4toavoid ;DCintheoutput CycleBase Con 8 ;numberofhalf-cyclesinbase ;Variables ;----------------PinStat Counter DutyCycle HalfCycOn HalfCycOff
Var Var Var Var Var
Bit Byte Byte Byte Byte
;Pinstatus ;numberofhalf-cycles ;percentcycleson ;numbercycleson ;numbercyclesoff
;Initialization ;---------------LowOptoPin OutputOptoPin Counter=0 DutyCycle=50;0...100 HalfCycOn=(CycleBase*DutyCycle)/100 HalfCycOff=CycleBase-HalfCycOn Main Repeat UntilPortB.Bit4<>PinStat IfCounter<=HalfCycOnThen PulsOutOptoPin,GateDur EndIf IfCounter>=(HalfCycOn+HalfCycOff)Then Counter=0 EndIf PinStat=PortB.Bit4 Counter=Counter+1 GoToMain End
Westartbydefiningthe“cyclebase,”thatis,thenumberofhalf-cyclesoverwhichtheoff/oncycleisrepeated.I’vesettheconstantCycleBaseto8,representingfourfullACcycles. CycleBase
Con
8
;numberofhalf-cyclesinbase
DutyCycle HalfCycOn HalfCycOff
Var Var Var
Byte Byte Byte
;percentcycleson ;numbercycleson ;numbercyclesoff
Wethendeclarethreevariables,DutyCycle,HalfCycOnandHalfCycoff.DutyCycleholdsthepercentageof“on”cyclesinCycleBase,whileHalfCycOnandHalfCycOffholdthenumberofhalf-cycles“on” and“off,”respectively. DutyCycle=50;0...100 HalfCycOn=(CycleBase*DutyCycle)/100 HalfCycOff=CycleBase-HalfCycOn
557
Chapter23 IntheInitializationsection,I’vesetDutyCycleat50%.Thismeansfourhalf-cycleson,followedby fourhalf-cycleson,thenfourhalf-cycleson,etc.HalfCycOniscomputedas4andHalfCycOffiscomputedas4.Forfourcycles,theonlylegitimatedutycyclevaluesare0,25%,50%,75%and100%. Let’snowlookatthemainprogramsegment. Main
Repeat UntilPortB.Bit4<>PinStat
AsreflectedinFigure23-15,theoutputoftheMCP601limiterisconnectedtoB4.Themainprogramcode monitorsthestatusofB4untilitchangesstate,whichrepresentsavoltagezerocrossingintheACmains supply.(Zerocrossingsoccureveryhalfcycle;whichisthereasonwecastthestructureintermsofhalfcycles,notfullcycles.)
IfCounter<=HalfCycOnThen PulsOutOptoPin,GateDur EndIf
Ifthenumberofzerocrossingsislessthantherequirednumberofon-cycles,Program23-2pulsestheoptotriactoturnthemaintriaconforthejuststartedhalf-cycle.
IfCounter>=(HalfCycOn+HalfCycOff)Then Counter=0 EndIf
Figure23-24:CycleControl50%DutyCycle;Ch1: TriggertoTriac;Ch2:CurrentThroughLoad.
Figure23-25:CycleControlwithIntentionalDC;Ch1: TriggertoTriac;Ch2:CurrentThroughLoad.
Figure23-26:CycleControlWithRandomPhase Opto DC; Ch1: Trigger to Triac; Ch2: Current ThroughLoad.
558
ACPowerControl Ifwehavereachedtheendofourcycleduration,thenresetCounter.
PinStat=PortB.Bit4 Counter=Counter+1
Finally,ateachzerocrossing,refreshthestatusofB4andincrementthebytevariableCounter. GoToMain
Figure23-24showstheresult.Twofullcyclesofcurrentflow,followedbytwocyclesofnocurrent.Ifthe loadisanincandescentlamp,bytheway,thisoff/oncyclecausesaveryannoyingflicker.Ofcourse,ifwe werecontrollingadifferenttypeofload,suchasawaterheater,flickerisnotanissue. It’simportantthatwekeepthesamenumberofpositiveandnegativehalf-cyclesineachonandoffperiodto preventDCcurrentfromflowing.Figure23-25showstheeffectofsettingCycleBase=10,andDutyCycle=50.Weseetwopositivehalf-cyclesandthreenegativehalf-cycles.ThenetaverageDCcomponent ofthiswaveformis148mA. Now,disconnectthepowercontrolboardfromtheACmainssupply,removetheMOC3032Mandinstall theK3011Prandomphaseopto-triac.ReconnectthepowerandrunProgram23-2again,butredefining CycleBaseas16insteadof8.KeepDutyCycleas50.Figure23-26isidenticalwithFigure23-24;since Program23-2onlyfiresthetriacatazerocrossing,thereisnodifferenceinresultbetweentriggeringwith arandomphaseopto-triacorazero-crossingopto-triac.OnedifferencebetweenFigures23-24and23-26is thattheeighthalf-cycleoff-periodallowsthefilamenttocoolmorethanthefourhalf-cycleperiodinFigure 23-24.Hence,weseeasmallinrushcurrentincreaseforthefirsttwocyclesinFigure23-26. Program23-3 Program23-3demonstratesphasecontrol.KeeptheK3011Prandomphaseopto-triacinplaceforProgram23-3. ;Program23-3 ;Phase ;Constants ;---------HTab OptoPin ZeroPin GateDur usPerDeg OffsetCorr
Con Con Con Con Con Con
9 C0 B4 500 46 225
;horizontaltab ;pinwithoptooutput ;inputpin ;durationinmicroseconds ;46usecperdegree ;delayinusofprogramloop
Bit Byte Word
;Pinstatus ;phasedelayindegrees0...180 ;delaytofire
;Variables ;----------------PinStat Degrees TDelay
Var Var Var
;Initialization ;---------------LowOptoPin OutputOptoPin ;Degreesmust>=5and<=175degrees Degrees=175 TDelay=Degrees*usPerDeg IfTDelay>OffsetCorrThen TDelay=TDelay-OffsetCorr EndIf Main
Repeat UntilPortB.Bit4<>PinStat
559
Chapter23 PauseusTDelay PulsOutOptoPin,GateDur PinStat=PortB.Bit4 GoToMain End
Westartbydefiningseveralconstants: GateDurCon usPerDeg OffsetCorr
500 Con Con
46 225
;durationinmicroseconds ;46usecperdegree ;delayinusofprogramloop
GateDuristhelengthofthegatedrivepulse,inmicroseconds.Fortheparticularopto-triacandtriacthatwe use,500µsprovidesmorethanadequategatedriveduration.IfGateDuristoolong,sothatyoutriggerlate
intothecycle,it’spossiblethatgatedrivewillstillbeappliedwhenthenextcyclestartsandthetriacwill unexpectedlylatchintoconduction.500µscorrespondstoapproximately11degreesat60Hz,soweexpect troublefortriggeringdelayedby169degreesormore.TheconstantusPerDegisthedurationofonedegree ofphaseat60Hz,expressedinmicroseconds.(Onecycleof60Hzis16.667ms,and16.667ms/360degreesyields46.1µs/degree.)TheconstantOffsetCorristhelengthoftimeittakesforMBasictoexecute theRepeat…UntilstatementloopinProgram23-3.Thisvaluemustbeconsideredtocorrectlydetermine thefiringpointand225µsisbasedona20MHzclock,measuredasdescribedlaterinthissection. DegreesVar TDelay Var
Byte Word
;phasedelayindegrees0...180 ;delaytofire
Wewishtodefinethefiringpointindegrees,butthePICknowsonlytimeinmicroseconds.Thevariable Degreesholdsthedesiredfiringangle,whileTDelayholdsthetimedelayinmicrosecondsbetweenthe zerocrossingtimeandthefiringtime. ;Degreesmust>=5and<=175degrees Degrees=175 TDelay=Degrees*usPerDeg IfTDelay>OffsetCorrThen TDelay=TDelay-OffsetCorr EndIf
IntheInitializationsection,wehardcodethephaseanglebysettingDegree=175.(We’lltry severalvaluestoseethedifferenceandinProgram23-4,weenternewvaluesthroughtheserialport.)We thencomputethetimeinmicrosecondsbetweenzerocrossingandthedesiredfiringpointbythestatement TDelay=Degrees*usPerDeg.WethenmustsubtracttheoverheaddelayassociatedwithMBasic’s functionbythestatementTDelay=TDelay–OffsetCorr.SinceTDelaycan’tbenegative,before makingtheoverheadcorrection,wetestitsvaluebeforesubtractingtheoverheadconstant. Main Repeat UntilPortB.Bit4<>PinStat PauseusTDelay PulsOutOptoPin,GateDur PinStat=PortB.Bit4 GoToMain
WeuseProgram23-2’sapproachtodetectingzerocrossings;continuouslyreadandtestpinB4’sstatusin theRepeat…Untilloop.B4changesstateonlyatazerovoltagecrossing.Uponazerocrossing,wewait TDelaymicrosecondsandthenfirethetriacforGateDurmicroseconds.Wethenrepeatthewait/delay/fire processendlessly. TodeterminethecorrectvalueofOffsetCor,wemeasurethetimebetweenazerocrossingandthetime OptoPingoeshigh,withDegreessetto0,asshowninFigure23-27.
560
ACPowerControl Figures23-28through23-31showthetriggerpulsesandresultingcurrentwaveformsforfiringanglesof45, 90,135and175degreesrespectively.
Figure 23-27: Measuring Overhead Delay in Repeat…Until Loop; Ch1: OptoPin Ch2: MCP601ZeroCrossingDetectorOutput.
Figure 23-28: Current through Load, Program 23-3@45DegreesCh1:DrivetoOptoLED;Ch2: LoadCurrent.
Figure 23-29: Current through Load, Program 23-3@90DegreesCh1:DrivetoOptoLED;Ch2: LoadCurrent.
Figure23-30:CurrentthroughLoad,Program233@135DegreesCh1:DrivetoOptoLED;Ch2: LoadCurrent.
Figure23-31:CurrentthroughLoad,Program 23-3@175DegreesCh1:DrivetoOptoLED; Ch2:LoadCurrent.
561
Chapter23 Program23-4 Program23-4demonstratesphasecontrol,butwiththefiringphaseanglebeingenteredthroughtheRS-232 serialport.KeeptheK3011Prandomphaseopto-triacinplaceforProgram23-4. ;Program23-4 ;Phasecontrollerwith ;serialinputcommand ;Constants ;---------HTab OptoPin ZeroPin GateDur usPerDeg OffsetCorr
Con Con Con Con Con Con
9 C0 B4 200 46 225
;horizontaltab ;pinwithoptooutput ;inputpin ;durationinmicroseconds ;46usecperdegree ;delayinusofprogramloop
MaxStrSize Con MaxDeg Con MinDeg Con ;Variables ;-----------------
12 177 5
;stringlength ;maximumphaseangle ;minimumphaseangle
PinStat Degrees TDelay i j InStr InByte DecNum OldDeg
Bit ;Pinstatus Byte ;phasedelayindegrees0...180 Word ;delaytofire Byte ;counter Byte ;counter Byte(MaxStrSize) ;inputstring Byte ;inputbyte Word ;outputofstringtodecimal Byte ;olddegrees
Var Var Var Var Var Var Var Var Var
;Initialization ;---------------EnableHSerial SetHSerialH115200 LowOptoPin OutputOptoPin ;Degreesmust>=5and<=175degrees Degrees=45 OldDeg=Degrees GoSubSetDelay i=0 j=0 Main HSerStat3,CheckInput ReturnFromCI Repeat UntilPortB.Bit4<>PinStat PauseusTDelay PulsOutOptoPin,GateDur PinStat=PortB.Bit4 GoToMain CheckInput ;--------- HSerIn[InByte] ;Echoback HSerOut[StrInByte\1] InStr(j)=InByte
562
ACPowerControl j=j+1 Ifj=(MaxStrSize-1)Then j=0 EndIf IfInByte=13Then Ifj>0Then j=j-1;getridofCR EndIf GoSubCRReceived EndIf HSerStat3,CheckInput GoToReturnFromCI CRReceived ;-------------- Ifj>0Then GoSubStrToDecimal EndIf j=0 Return StrToDecimal ;------------ i=0 DecNum=0 While(InStr(i)>=“0”)AND(InStr(i)<=“9”) DecNum=DecNum*10 DecNum=DecNum+InStr(i)-“0” i=i+1 WEND Degrees=DecNum GoSubSetDelay Return SetDelay ;--------- If(Degrees>=MinDeg)AND(Degrees<=MaxDeg)Then TDelay=Degrees*usPerDeg Return End
IfTDelay>OffsetCorrThen TDelay=TDelay-OffsetCorr EndIf HSerOut[“Was:“,DecOldDeg,HTab,”Now“,| DecDegrees,13] OldDeg=Degrees EndIf;validdegrees
TheonlychangesbetweenPrograms23-3and23-4relatetoenteringandparsingtheuserinputdata. Main HSerStat3,CheckInput ReturnFromCI Repeat UntilPortB.Bit4<>PinStat PauseusTDelay PulsOutOptoPin,GateDur PinStat=PortB.Bit4 GoToMain
Program23-4usescodeandtechniquesdevelopedinChapter9andusedelsewhereinthisbook,sowe’llnot spendagreatdealoftimeanalyzingthecode. Notethatwe’veaddedthestatements: HSerStat3,CheckInput ReturnFromCI
563
Chapter23 Atthetopofthemainprogramloop,aswelearnedinChapter9,weusetheundocumentedfunctionHSerStattoseeifanycharactershavebeenreceivedinthehardwareserialinputbuffer.Ifoneormore charactershavebeenreceived,programexecutionjumpstoCheckInput. ThecodeatCheckInput,CRReceivedandStrToDecimaltracktheidenticallynamedroutinesfoundin Programs9-2A,9-2Band9-3andwillnotbefurtheranalyzedhere. Afteravalidnumberstringhasbeenreceived,terminatedwithacarriagereturn,subroutineStrToDecimal convertsittoabinarynumberandstorestheresultingvalueinthevariableDegrees.SubroutineStrToDecimalthencallssubroutineSetDelay,wherethevariableDegreesisfurthervalidatedandusedtoset thetriacfiringangle. SetDelay ;--------- If(Degrees>=MinDeg)AND(Degrees<=MaxDeg)Then TDelay=Degrees*usPerDeg Return
IfTDelay>OffsetCorrThen TDelay=TDelay-OffsetCorr EndIf HSerOut[“Was:“,DecOldDeg,HTab,”Now“,| DecDegrees,13] OldDeg=Degrees EndIf;validdegrees
First,weverifythatDegreesiswithinthemaximumandminimumrangedefinedbythetwoconstants MaxDegandMinDeg,respectively.Ifvalid,anewTDelayvalueiscomputedandaconfirmingmessageis senttotheuserovertheserialport.ThenewTDelayisimplementedatthenextzerocrossing. Here’sasampleuserinteractionwithProgram23-4(I’veaddedcommentstotheright): 45 Was:5 Now45 90 Was:45 Now90 177 Was:90 Now177 95 Was:177 Now95 22 Was:95 Now22 111 Was:22 Now111 80
←userenteredvalueof45degrees
←userenteredvalueof90degrees
←userenteredvalueof177degrees,greaterthanMaxDeg ←nochangeactuallytookplace,however ←userenteredvalueof95degrees
←userenteredvalueof22degrees
←userenteredvalueof111degrees
←userenteredvalueof80degrees
Was:111 Now80
IdeasforModificationstoProgramsandCircuits •
TheuserinputinProgram23-4isintermsofphaseangle.Formostapplications,however,auser wishestheinputvaluetotracksomecontrolledparameter.Forexample,forincandescentlampdimming itwouldbemoreusefultoenter10or20brightnesssteps,witheachsteproughlycorrespondingto equalchangesinlightoutputintensity.Howwouldyoudothis?Antungstenfilamentincandescentlamp luminosityisnonlinear,withtherelationshipgivenbythefollowingformula:
V L1 = L0 1 V
3.5
0
564
ACPowerControl
• • • •
•
where: L1istheoutputinlumensatappliedvoltageV1 L0istheoutputinlumensattheratedvoltage,V2 Thereasontheexponentis3.5,not4asmightbeexpectedfromtheStephan-Boltzmanlaw,isthatthe resistanceofthetungstenfilamentchangesdrasticallywithtemperatureandhencethecurrentdrawn bythelampisafunctionofvoltage.Thepower(andthusthefilamenttemperature)thusdoesnotvary exactlywiththesquareoftheappliedvoltage. Howmightyoucontrolinrushcurrent?Mightthisbedonebyrampinguptheappliedvoltage,suchas startingata175degreetriggerangleandreducingit,say5degreeseveryfullcycleuntilfullvoltageis reached. Program23-4hasnofull-onorfull-offsettings.Modifyittoshutthedowngatedrivetothetriaccompletelyiftheenteredphaseangleis176degreesorgreater,andtoapplyfullpoweriftheenteredphase angleislessthan5degrees. Forwhattypeofloadsmightcyclecontrolbesuitable?Forwhatloadsisarandomphaseloadsuitable? Howmighttheuserinterfacebeexpandedtobemoreuser-friendly?Whichparametersdoesauserneed tocontrol?Woulditbeusefultostorepre-programmedsequences,suchasramp-upandrampdown sequences,powerlevelsandthelike?TheseshouldbestorableinEEPROMtopreservecontentswhen powerisremovedfromthePIC.Howwouldyougoaboutaddinguser-programmablesequences? Itispossibletocombinethetriaccircuitryofthischapterwiththeinfraredremotecontroldecoderof Chapter22andremotecontrollampsorotherACloads.Howwouldyoucombinetheseconcepts?You couldalsocombinetriaccircuitrywithtemperaturesensingdevices,asweusedinChapter12,tocontrolaheater.Whatsafetymeasuresshouldbeincludedtopreventasoftwareorhardwareproblemfrom becomingafireorothersafetyhazard?
References [23-1]
TeccorElectronics,FundamentalCharacteristicsofThyristors,AN1001(2004).Availablefordownloadathttp://www.teccor.com/web/menuitems/downloads/appnotes.htm. [23-2] TeccorElectronics,PhaseControlUsingThyristors,AN1003(2002).Availablefordownloadathttp:// www.teccor.com/web/menuitems/downloads/appnotes.htm. [23-3] TeccorElectronics,ThyristorsUsedasACStaticSwitchesandRelays,AN1007(2004).Availablefor downloadathttp://www.teccor.com/web/menuitems/downloads/appnotes.htm. [23-4] TeccorElectronics,MiscellaneousDesignTipsandFactss,AN1009(2004).Availablefordownloadat http://www.teccor.com/web/menuitems/downloads/appnotes.htm. [23-5] TeccorElectronics,TriggeringandGateCharacteristicsofThyristors,ThyristorDesignGuide(Undated).Availablefordownloadhttp://www.teccor.com/web/menuitems/downloads/appnotes.htm. [23-6] Grimm,WilliamG.,UsingPICMicrocontrollerstoControlTriacs,AvorexDesigns(May2003),availablefordownloadathttp://www.avorex.com. [23-7] MicrochipTechnology,Inc.,PICDIMLampDimmerforthePIC12C508,PICREF-4,DocumentNo. DS40171A(1997). [23-8] VishaySemiconductors,Optocoupler,PhototriacOutput,250VVDRM,K3010P/K3010PGSeries,Rev. 1.5(Dec.2003).Availablefordownloadathttp://www.vishay.com. [23-9] FairchildSemiconductorCorp.,6-PinDIPZero-CrossOptoisolatorsTRIACDriverOutput(250/400 VoltPeak),MOC3031M,MOC3032M,MOC3033M,MOC3041M,MOC3042M,MOC3043M,DocumentNo.DS300256,(2001).Availablefordownloadathttp://www.fairchildsemi.com. [23-10] STMicroelectronics,BTA/BTB12andT12Series,Snubberless,LogicLevelandStandard12ATRIACS, Ed.6A,(2002).Availablefordownloadathttp://www.st.com/.
565
Chapter23 [23-11]
FairchildSemiconductorCorp.,ApplicationNoteAN-3003ApplicationsofNonZeroCrossingTRIACDriversFeaturingtheMOC3011,Rev.4.06,(2001).Availablefordownloadathttp://www.fairchildsemi.com. [23-12] FairchildSemiconductorCorp.,ApplicationNoteAN-3004ApplicationsofZeroVoltageCrossingOpticallyIsolatedTRIACDriver,Rev.4.06,(2001).Availablefordownloadathttp://www.fairchildsemi.com. [23-13] Cox,Doug,InterfacingtoACPowerLines,ApplicationNoteAN521,MicrochipTechnology,Inc., DocumentNo.DS00512C(1997). [23-14] Parekh,Rakesh,ACInductionMotorFundamentals,AN887,MicrochipTechnology,Inc.,Document No.DS00887A(2003). [23-15] Durbecq,X.,ControlbyaTRIACforanInductiveLoad:HowtoSelectaSuitableCircuit,Application NoteAN308/0289,SGS-ThomsonMicroelectronics,(1995).Availablefordownloadathttp://www. st.com/stonline/books/pdf/docs/3566.pdf. [23-16] Ochoa,Alfredo,Lara,Alex&Gonzalez,Gabriel,MomentarySolidStateSwitchforSplitPhase Motors,ApplicationNoteAND8007/D,ONSemiconductor,(1999).Availablefordownloadingat http://www.onsemi.com. [23-17] Zilog,Inc.,DigitalInstantWaterHeater,ApplicationNote,AN007101-0301,DocumentNo. AP96Z8X0701.Availablefordownloadathttp://www.zilog.com/docs/z8/appnotes/dig_ins_wh.pdf. [23-18] Templeton,George,RCSnubberNetworksforThyristorPowerControlandTransientSuppression, AN1048/D,Rev.2,ONSemiconductor,(1999).Availablefordownloadingathttp://www.onsemi.com. [23-19] Ochoa,Alfredo,Lara,Alex&Gonzalez,Gabriel,HighResolutionDigitalDimmer,ApplicationNote AND8011/D,Rev0,ONSemiconductor,(1999).Availablefordownloadingathttp://www.onsemi.com. [23-20] Ochoa,Alfredo,Lara,Alex&Gonzalez,Gabriel,SolidStateControlforBi-DirectionalMotors, ApplicationNoteAND8017/D,Rev0,ONSemiconductor,(2000).Availablefordownloadingathttp:// www.onsemi.com. [23-21] Castagnet,T.,NewTriacs:IstheSnubberCircuitNecessary?,ApplicationNoteAN437/0899,STMicroelectronics(1999).Availablefordownloadathttp://www.st.com/. [23-22] Edmunds,Llew,HeatsinkCharacteristics,ApplicationNoteAN-1057,InternationalRectifier,Inc. (undated).Availablefordownloadathttp://www.irf.com/technical-info/appnotes/an-1057.pdf. [23-23] PhilipsSemiconductors,Thyristors&Triacs—TenGoldenRulesforSuccessinYourApplication, DocumentNo.939775000812(1996).Availablefordownloadathttp://www.semiconductors.philips. com/acrobat/various/SC03_TECHN_PUBS_1.pdf. [23-24] Adams,Chuck,ManhattanBuildingTechniques(undated).Availablefordownloadathttp://www.qsl. net/k7qo/manhattan.pdf.Afollowuparticle,AdvancedManhattanBuilding,isavailablefordownloadingathttp://www.qsl.net/k7qo/advmanart.pdf. [23-25] PhilipsSemiconductors,FS013Understandinghigh-commutationtriacs,documentordernumber: 939775006504(October1999).
566
24
CHAPTER
DCMotorControl Inearlierchapters,welearnedhowtocontrolbothbipolarandunipolarsteppermotors.It’stimenowtolook atamucholdermotortype,thepermanentmagnetDCmotor.SimplyturningaDCmotoroffandonwitha PICisnotconceptuallydifferentthancontrollinganyinductiveloadandthetechniquesofChapter3maybe used.We’lllookatamorechallengingaspectofDCmotorcontrol;apulse-widthmodulatedvariablespeed motorwithtachometerfeedback.Motorssuitableforthetechniquesinthischapterarepermanentmagnet brush-typeDCmotors.BrushlessandotherspecializedDCmotorswillnotnecessarilyfunctionwiththis chapter’scircuits. Beforetacklingthischapter,onesmallconfessionisinorder.Whentacklinganewsubject,whetherinaformal classroomsettingorathome,attheoutsetmostofusareabitpuzzled.Then,atsomemagicmoment,itall comestogetherandlearningbecomesapleasure.Inmyundergraduateelectricalengineeringdays,Ihadtwo classeswherethatgestaltmomentneverarrived.Onewasrotatingmachineryclass(motorsandgenerators)and thesecondwascontrolsystems.Afterthefinalexaminboth,Isaidtomyself,“IsurehopeIneverhavetowork withthisstuffforreal.”As,bynowyoumightsuspect,thischapterdealswithmotors,generatorsandcontrol theory.We’lldipourtoesintothepooloflearning,butwe’redefinitelystickingtotheshallowend.
IntroductiontoControlTheory We’regoingtocontrolasmallDCpermanentmagnetmotorwithabuilt-intachometer.Theparticularmotor Iusedisaspindledrivemotor,removedfromanold5-1/4"floppydrive.It’sabout1"indiameterand2-1/2" longandisratedatamaximumof12V,correspondingtoabout6700RPM.(Basedonthepulleydiameters, themotorranat2025RPMwhenoperatingthediskspindle.)Mostimportantly,ithasabuilt-intachometer. ThisparticularmotorhasanACtachometer,whichislesscommoninnewermotors.But,alongtheway we’llseehowthecircuitryandprogramlogicmightbemodifiedtoworkwithothertachometertypes.Ifyou don’thaveanoldfloppydriveinyourjunkbox,youmayfindamotor/tachometerinascrapVCR,orfroma surpluselectronicsdealer. ControllingaDCmotorisaclassicalapplicationforananalogservoloop.(Indeed,DCmotorspeedcontrol withelectromechanicalgovernorspredateselectronics.)Thefloppydriveusedananalogfeedbackloopto controlthespindlemotor,andformanyapplicationsthisremainsanexcellent,inexpensivesolutionfor smallmotors.But,we’regoingtodothingsdifferently,andimplementaPIC-baseddigitalsolution. Althoughourexperimentsuseamotorunattachedtoanyload,usuallywecontrolasystem,notanisolated elementinasystemsuchasamotor.Thesystemmayconsistofsomethingassimpleasafanblade,oras complexasaroboticarm.Thefeedbackthatourcontrolhardwareandsoftwareusescomesfromthesystem, butnotnecessarilythemotor.Forexample,tocontrolcoolingairflowoveraheatsink,wemightusethe temperatureofthesemiconductorsmountedontheheatsinkasourfeedbacksignal,nottheRPMspeedof themotorattachedtothefanblades.Sometimes,ofcourse,themotorspeediswhatwewishtocontrol,such asthefloppyspindledrive.(Thisisn’tquiterightisit?Whatwewishtocontrolistherotationalspeedofthe 567
Chapter24 floppydisk,notthemotor.But,sincethemotorconnectstothediskbyapulleyandbeltarrangementwith afixeddiameterratio,controllingthemotorspeedisalmostasgoodasdirectlycontrollingthefloppydisk spindleandit’smuchsimplermechanically.) Sincewe’vethrowntheterms“feedback”and“controlsystem”ontothetable,let’sdefinethem.Figure24-1is rightoutofControlSystems101;wehaveaninput(thetargetpulsewidth),asummingpoint(thecirclewith the“X”),acontrolmechanism(thealgorithm,drive circuitryandmotor)and,finally,thefeedbacksignal, anRPM-proportionaloutputfromthetachometer.Together,theseelementsconstituteacontrolsystem. Feedback—isasampleproportionaltotheoutput tobecontrolled.Itdoesn’thavetobelinearly Figure24-1:Controlsystemformotorandtachometer. proportional,butit’shelpfulifitis.Inourmotor controlprogram,thefeedbackvalueisthewidthofthetachometerpulse,inmicroseconds.Sincethe tachometeroutputfrequencyisproportionaltomotorspeed,thefeedbackvalueislinearlyproportional tothereciprocalofmotorspeed. Controlinput(target)—isthevaluethatthefeedbacksignalwouldbe,iftheoutputperfectlymatchedour objective.Inourmotorcontrolprogram,thetargetisthewidthofthetachometerpulsethatisoutput whenthemotorisrunningatexactlythedesiredspeed.(SincetheuserinputsspeedinRPM,wemathematicallytransformRPMintothetargetpulsewidth.) Summingpoint—comparesthefeedbacksignalwiththetargetandoutputstheerror(targetminusfeedback).Theoutputofthesummingpointistheerrorsignal.Inourcase,thesummingpointisalineof MBasiccodewherewesubtractthemeasuredpulsewidthfromthetargetpulsewidth.Thisdifferenceis theerrorsignal. Algorithmandcontrolmechanism—consistsofsoftwareandhardwarethatcontrolthemotor’sspeedina waysoastoreducetheerrorsignaltozero.We’lltrytwodifferenthardwarearrangementsandseveral softwarealgorithms.Allsharethecommonfeature,however,thatthealgorithmandcontrolmechanism worksuchthattheerrorsignaldrivestheoutputinadirectionoppositetheerror;iftheerrorsignal showsthespeedistoohigh,thecontrolmechanismchanges“something”inawaythatwillreducethe motor’sspeedandviceversa.(Thedirectionofchangeshouldbeobvious;ifthemotorisrunningtoo fastandourcontrolsystemtakesthatasanindicationthatitshouldrunevenfaster,wehavearunaway system,notonethatcontrolsthemotorinanymeaningfulfashion.) Thecontrolloopprocessmaybeclearerifweplaceitintopseudo-code: DefinetargetRPM CalculatetargetpulsewidthcorrespondingtoRPM Main Measuremotorspeed(tachometeroutputpulsewidth) Error=TargetWidth–MeasuredWidth MotorVoltage=MotorVoltage+Function(Error) GoToMain
Function(Error)isthemechanism(algorithmandhardwarecombined)thattakestheerrorsignaland
makessomeadjustmenttothevoltageappliedtothemotor.(Don’tworryaboutthealgebraicsignoftheerrorvalue;we’llmakeitallcomeoutintherightdirectionintheadjustmentfunction.) Withthispseudo-codeinmind,let’slookatthethreepartsofouralgorithm:
MeasureMotorSpeed(TachometerOutputPulseWidth) Ifwearetocontrolthespeedofamotor,wemusthavesomewayofmeasuringthatspeed.Awealthapproachestomeasuringmotorspeedhavebeendevised,butfourseemdominant: 568
DCMotorControl •
DCtachometer—outputsaDCvoltageproportionaltothemotorspeed.ADCtachometerisaminiature generatoronthesameshaftasthemotor. • ACtachometer—outputsanACvoltagewithbothitsvoltageandfrequencyproportionaltothemotor speed.AnACtachometerisaminiaturealternatoronthesameshaftasthemotor. • Opticalormagneticsensors—producepulses(rangingfromonetoseveralthousand)foreachshaftrevolution. • Sensorless—Systemsnotemployingtachometersorsensorsthatinsteadsensethemotor’sbackelectromagneticforce—whichisproportionaltomotorspeed.Theseareknownassensorlesssystems. Theoldesttechnology,butstillwidelyused,istheDCtachometer,whilethenewestsystemsuseoptical shaftencoders,with2048ormore positionspershaftrevolution.These permitnotonlyprecisespeedcontrol,butalsoshaftpositioning. Figure24-2showshowwemight conditionaDCoranACtachometer’soutputtobePICcompatible. IfourmotorhasaDCtachometer output,wereadthevoltagewith thePIC’sA/Dconverter.Wemust, however,filterthecommutatornoise withanRClow-passfilter,and useavoltagedividertoscalethe maximumoutputvoltagetoavalue consistentwiththereferencevoltage weusewiththePIC. IfourmotorhasanACtachometer, recallthatboththevoltageand frequencyareproportionaltomotor speed.Hence,wehavetwooptions; rectifyandfilterthetachometer outputyieldingaDCoutputproportionaltomotorsimilartothatfroma DCtachometer;ormeasuretachometeroutputfrequency.Ifwewish tomeasurethefrequency,wemust “squareup”thesinusoidaltachometeroutput,convertingittoasquare wavecompatiblewiththePIC’s digitalinput.We’lllookatthecircuit Figure24-2:Analogtachometerconditioningcircuits. ofFigure24-2(c)laterinthischapter. Idecidedtomeasurethetachometer’sfrequency.Intheory,thetachometer’soutputfrequencyshouldbea morelinearmeasureofshaftrotationspeedthantheDCrectifiedoutput.Italsoavoidsotherproblemswith thecircuitinFigure24-2(b),suchasfilteringtherectifiedtachometeroutputtoremovetheACcomponent, butstillhavingtheaverageDCvaluequicklyrespondtochangingmotorspeed.Asweshallsee,however, measuringfrequencyisnotwithoutitsproblems.(We’llmeasureperiod,thereciprocaloffrequency,but we’llgenerallyspeakaboutthetachometer’sfrequency,notperiod.) 569
Chapter24 DeterminingtheTachometerConstant IfwearegoingtosetspeedinRPM,butbaseourcontrolmechanismonthetachometeroutputfrequency, wemustknowtherelationshipbetweentachometeroutputandmotorRPM.Sincewedon’thaveamanufacturer’sdatasheetonthemotor,we’lldetermineitbyexperiment—spinthemotorataknownspeedand measurethetachometeroutput.IdidthisbyapplyingaseriesofDCvoltagesbetweenabout3.5Vand12V tothemotor,measuringthecorrespondingRPMwithaGeneralRadioGR1531ABStrobotac.(Themotor speedwouldnotstayconstant,sotheRPMvaluesare“eyeballaverages.”)Ifyoudon’thaveaStrobotac handy,youcanuseafluorescentlamp.Markalineonthemotorshaftandat3600RPM,thelinewillappear tostandstill.At7200RPM,youwillseetwolinesstandingstill.(Ifyourpowerlinefrequencyis50Hz,the correspondingvaluesare3000and6000RPM,ofcourse.)Or,youcanspintheshaftofanun-poweredmotorataknownspeed,usingadrillpressormillingmachine,andmeasurethetachometeroutput. SinceIhaddecidedthatIwouldusethetachometeroutputfrequencyasthespeedmeasuringmechanism,I wasonlyconcernedwiththeoutputfrequency.Here’sthedataIcollected: RPM
TachometerOutput Frequency(Hz)
ShaftSpeed(Rev/Sec)
TachometerOutput Cycles/Rev
CalculatedPoles
390
52.5
6.5
8.08
16.15385
1050
149.3
17.5
8.53
17.06286
1960
262.5
32.7
8.04
16.07143
2720
368.5
45.3
8.13
16.25735
3520
471.7
58.7
8.04
16.08068
4300
589.6
71.7
8.23
16.45395
5100
702.2
85.0
8.26
16.52235
5950
809.1
99.2
8.16
16.31798
Average
8.18
Basedonthisdata,wecanbeconfidentthatthetachometerisa16-poledevice,andhencethetachometer constantis8cycles/rev.WedeterminethisfromtherelationshipbetweenACgenerator(ormotor)poles, frequencyandRPM,whichis: NP F= 120 where:
FistheoutputfrequencyinHz NistherotationalspeedinRPM Pisthenumberofpoles.
Solvingforthenumberofpoles: P=
120 F N
Pmustbeaninteger;youcan’thaveafractionofapoleinamotororgenerator.Hence,Pmustbe16,and thetachometerconstantis8cycles/rev.
ConvertingtheSinusoidalTachometerOutputtoaDigitalLogicLevelSignal MBasic’sfunctionPulsInmeasuresthedurationofalogic-levelsignal(optionallystartingwitheither the0to1transitionorthe1to0transition)andreturnsitslengthinunittimestepperiods,whereoneunit timestepcorrespondstosevenmachineinstructioncycles.Ifyoudon’trecallthedetailsofPulsIn,review 570
DCMotorControl Chapter22wherewemeasureinfraredpulsedurationfromremotecontrolunits.Asaquickreminder, PulsIn’ssyntaxis: PulseInPin,State{TimeoutLabel,TimeoutMultiple,}Var
Wecan’tfeedthesinusoidaloutputofthetachometerintoaPIC’spinandexpectPulsIntoworkreliably. First,evenatmodestspeedthetachometer’svoltageoutputfarexceedsthePIC’ssafelimit.But,supposewe canlimitvoltageexcursionstoasafevaluethroughaseriesresistoranda5.1VZenerdiode.Evenso,we haveanotherproblem.InChapter4welearnedthatthePICreadstransitionsbetweenlogic0andlogic1at differentvoltages,dependingonwhethertheinputpinisTTLcompatible,orCMOScompatibleorSchmitt triggertype.Inanycase,thetransitionpointisatleast1.5Vorthereaboutsataminimum.Hence,thepulse widthwewouldmeasurewoulddependuponboththeamplitudeofthetachometeroutputaswellasits frequency.Ifyoudoubtthis,supposethetachometeroutputhasapeakvalueof1.4V.Theperiodwon’t bemeasuredatall,sincethegatewillnotchangelogicstate.Ifthepeakvalueis1.6Vandiftheinputpin isaTTLcompatibleonewith1.5Vthreshold,thelogical1durationwillbeonlybethelengthoftimethe instantaneousvoltageexceeds1.5V. Theusualsolutionistofeedthesinusoidalsignaltoa“squarer,”oralimiter—acircuitthatconvertsasine waveintoasquarewave.Iftheinstantaneousoutputofthetachometerispositive,thesquareroutputslogic 1;ifitisnegative,thesquareroutputslogic0.Therecommendeddevicetouseasasquarerisacomparator. Acomparator“compares”thevoltagedifferencebetweenitsplusandminusinputs.Ifthevoltageonthe plusinputexceedsthevoltageontheminusinput,thecomparatoroutputsalogic1;ifthereverseistrue,it outputsalogic0.We’regoingtouseaninexpensiveMCP601generalpurposeop-ampoperatingopenloop instead,recognizingthatitsperformancewillbeinferiortoatruecomparatorinoutputslewrateandthatthe logic0tologic1transitionwillnotnecessarilyoccurascloseto0Vasitwillwithatruecomparator. Figure24-3showsthesquarercircuitofFigure24-2(c)asenteredintoaSPICEmodeling program.TheACtachometerismodeledasa perfectsinewavesource,withaseriesresistanceof200ohms.I’vesetitfor300Hz,with 14Vpeak-to-peakoutput,correspondingto 2250RPM.(TheLTSpicesimulatorrequires youtousetheone-sidedpeakvoltageasthe amplitudespecificationforasinesource; henceFigure24-3shows7V.) Figure24-3:ACtachometerconditioner. Anop-ampoperatedopenloop,i.e.,without feedback,exhibitsbehaviorsimilartoacomparator;ifthevoltageontheplusinputexceedsthatonthe minusinput(plusanyoffsetvoltage),theoutputisdriventothepositiverailandviceversa.We’vegrounded MCP601’sinvertinginputinFigure24-3soweexpectitsoutputtogoto+5Vassoonasthetachometer’s instantaneousvoltageexceedsafewmillivoltspositive.TheMCP601’sinputpinsarelimitedtoVDD+0.3V andVSS–0.3V,sowe’veaddedR2,D1andD2tolimitmaximumvoltageexcursiononediodedrop(around 700mV)positiveornegativewithrespecttoground.WelikelycouldomitD1andD2,astheMCP601has internalout-of-rangeprotectivecircuitrysolongastheinputcurrentdoesnotexceed2mA,whichisassured bythe10Kseriesresistor. Figure24-4showsthesimulatedtachometerinputandMCP601outputvoltages,whileFigure24-5shows resultsfromtherealcircuitoperatingat1750RPM.Thereislittledifferencebetweensimulationandmeasuredresults.
571
Chapter24
Figure24-5:Measuredresults.
Figure24-4:Simulationresults.
UsingMBasic’sPulsInfunctiontomeasurethedurationofthepositivegoingoutputoftheMCP601gives usavalueproportionaltothemotorRPM.
Error=TargetWidth–MeasuredWidth Thispartofourrealcodelooksalotlikeourpseudo-code.Wecalculatetheerrorbetweenthedesiredpulse widthandthemeasuredpulsewidth. Let’slookathowwecalculatethedesiredpulsewidth.Weconventionallyworkwithmotorspeedinrevolutionsperminute,orRPM.Westartwiththerelationshipbetweenfrequency,theshaftspeedandthenumber ofpolesinthetachometer: NP 120 SinceP=16,andsinceperiodisthereciprocaloffrequency,werearrangethisequation: F=
1 120 = F 16 N Wemeasureonlythepositivegoinghalf-cyclewidth,orone-halftheperiod.And,beginningwithversion 5.3.0.0,MBasic’sPulsInfunctionreturnsthewidthinunitsteps,notmicroseconds.Inordertosimplify ourcomputations,we’llworkinmicrosecondsandconverttounitstepslater.Hence: 60 × 10 6 16 N Let’sseehowthisworks.IfourtargetRPMis1750wecalculatethepulsewidthweexpectPulsInto measure: Periodµs =
Periodµs =
60000000 = 2143µs 16 × 1750
Fora20MHzclock,PulsIndeterminesthewidthinunitsof1.4µssteps.2143µscorrespondsto1531unit steps.
TheControlAlgorithm Wenowhaveameasuredpulsewidth,andthetargetpulsewidth,andthecalculatederrorbetweenthetwo. 572
DCMotorControl Nowthatwehaveit,whatdowedowiththeerrorvalue? Tokeepthingssimple,we’llconsiderfourpossiblecontrolalgorithms. Bang-bang—Thesimplestpossiblecontroltechniqueistoapplyfullvoltagewhenthemotorisrunning slowandcutthevoltagetozerowhenthemotorisrunningfast.Thisapproachisoftencalled“bangbang”control,asthecontrolparametersarealwayshardagainstthestops.Bang-bangcontrolsimplifies theelectronicsdesign—novariablevoltagemotorcontrolisrequired.Rather,allweneedisasimple on-offswitch.Itscorrespondingdrawback,ofcourse,isthatthemotor’sspeedisalwayseithertoofast ortooslow.We’llseehowabang-bangalgorithmworksinProgram24-4.Lestyouhaveanydoubtof theefficacyofbang-bangcontrols,untilrecentlytheUnitedStatesAirForce’slaser-guidedbombsused bang-bangcontrolledsteeringvanes.(PavewayIIIwasthefirsttouseproportionalcontrol.) Proportional(P)—Thenextstepupfrombang-bangcontrolistousethemagnitudeoftheerrorsignaltodrive thecorrectionamount.Ifthemotorisveryslow,thenweincreasethedrivevoltagealargeamount;ifthe motorisjustalittleslow,weincreasethedrivevoltageasmalleramount.Thismeans,ofcourse,thatthe controllermustsupplythemotorfromavariablevoltagesource.We’lluseproportionalcontrolinPrograms24-5and24-6whereoursourceofvariablevoltageisthePIC’shardwarepulsewidthmodulation module.Aproportional-onlycontrolcanonlyapproach,butneverexactlymatchthesetpoint,asthecloser wegettomatchingit,thesmallertheerrorandthesmallerthecorrespondingcorrection.Althoughthe residualerrormaybequitesmall,aproportionalsystemcannotreduceittozero. ProportionalandIntegral(PI)andProportionalandDerivative(PD)—Wecanmodifythealgorithmto considernotonlytheerror,butalsotheintegraloftheerror,orthederivativeoftheerror.Wecanthink ofaPIcontrolleraslookingatnotonlytheinstantaneouserror,butalsoahistoryofrecenterrors.API controllercanreducethesteadystateerrortozero.Wecouldalsolookatthederivativeoftheerrorsignal,thatis,howhastheerrorchangedovertime.PDsystemshavemanyimplementationproblems—for example,differentiationaddshighfrequencynoisetotheestimate,notagoodthingatall.Consequently,PDcontrollersareseldomused. Proportional,IntegralandDerivative(PID)—Ifweadjust thecontrolvariablebasedon themagnitudeoftheerror,as wellasitshistoryanditsrateof change,wehaveaPIDcontroller.PIDcontrollersarethemost flexibleandareverywidely used.Indeed,about90%ofindustrialcontrolsystemsarePID.
MotorControlPrograms WewillnotlookatPI,PDorPID algorithmsfurtherastheyarebeyond anintroductorybooksuchasthis one.Now,let’sseehowweimplementDCmotorcontrol.
Figure24-6:Simplemotorconnection.
573
Chapter24 Program24-1 We’llstartbytestingourabilitytoturnthemotoroffandon.Figure24-6showsourcircuit,whichshouldbe familiarfromChapter3. ;Program24-1 ;MotorOff/On ;Constants MtrPin Con C2 ;Initialize OutputMtrPin Main HighMtrPin Pause1000 LowMtrPin Pause2000 GoToMain
Program24-1turnsthemotoronforonesecond,andthenturnsitofffortwosecondsinanendlessrepeated cycle.WhenC2istakenhigh,the2N7000MOSFETisturnedon,whichmakesitssource-drainpathlook likealowvalueresistorthuscompletingthemotorcircuit.Sincethemotorwindingsareinductive,D3is necessarytoclampthevoltagespikewhenQ1turnsoff.Ifyoudon’tunderstandhowthiscircuitworks, pleasereviewChapter3. We’veselectedpinC2purposefully;aswe’llseeinProgram24-2the16F876/877/AfamilyhavetwohardwarePWMmodules,oneconnectedtopinC2andtheothertopinC1.ByusingC2forouroperationaltest, weavoidhavingtorewirewhenusingPWMtechniques. Figure24-6showsthemotor’spositiveterminalconnectedtothepositiveendofthemotorpowersupply. ManyDCmotorsarenotpolaritysensitive,andcheerfullyrotateinonedirectionwithonepolarityandin thereversedirectionwhenpolarityisreversed.AfewDCmotors,however,aremechanicallyconstructedto functionbestwhilerotatinginonedirection.(Usually,thisisrelatedtothebrushandcommutatorconstruction.)Ifyourmotorhaspolaritymarkings,youshouldfollowthemunlessyouknowthatitmaysafelybe operatedwithreversedpolarity. Program24-2 Now,let’svarythemotor’sspeedthroughpulsewidthmodulation.WekeepthesameconnectionarrangementasusedinProgram24-1. ;Program24-2 ;MotorPWMOpenLoop ;Constants PWMC2 PWMPrd
Con Con
0 2048
;Variables DutyCyc
Var
Word
;Initialize Main ForDutyCyc=0toPWMPrdStep25 HPWMPWMC2,PWMPrd,DutyCyc Pause1000 Next GoToMain
Westudieddigital-to-analogconversionviapulsewidthmodulationinChapter16,sowewon’tgothrough aground-upreviewofthetheorybehindPWM,butinsteadwewillrecaptheitsfundamentalconcept.Let’s 574
DCMotorControl lookatthreedigitalwaveforms,A,BandC.Eachwaveformrepeatsaftertheeightintervalsshowninthe illustration. A
+12 0
AverageVoltage 1.5V
B
+12 0
6.0V
C
+12 0
10.5V 0
Timemarkers
1
2
3
4
5
6
7
Supposeweapplythesewaveformstoamotorandplaceanaveragereadingvoltmeteracrossthemotor windings.WaveformAwillshow1.5V,waveformBwillshow6VandwaveformCwillshow10.5V.Our 12Vmotorwillturnslowly,ifatall,whenwaveformAisapplied,itwillturnreasonablyfastforwaveform BanditwillrunnearlyatmaximumspeedforwaveformC.Thisassumes,ofcourse,thateachtimeperiod isrelativelyshort,typicallyafewhundredmicrosecondsorless. MBasicsupportshardwarePWMthroughthefunctionHPWM,withsyntax: HPWMCCPx,Period,Duty CCPx—identifiesthePWMgeneratortouse.The16F876/876A/877/877Adevices,forexample,havetwo hardwarePWMgenerators,onehardwiredtopinC1andtheotherhardwiredtopinC2.CCPxmaybeacon-
stantoravariable,andhastwopermissiblevalues,0and1: CCPxvalue 0 1
PWMGeneratorUsed CCPModule1 CCPModule2
PinConnection C2 C1
Insomeprintings,MBasic’sUser’sGuidereversestheCCPxvaluesrequiredtoselecttheCCPmodules. PeriodandDuty—Theseparametersareinter-related,sowe’lllookatthemtogether.We’llusewaveformBtoillustratetheterminologyusedinHPWM. ←Duty→ B
+12 0 ←Period→
Timemarkers(us)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Theperiodmightmoreclearlybereferredtoasthe“repetitionperiod,”i.e.,thetimebetweensuccessive repetitionsoftheoutputwaveform,measuredfromleadingedgetoleadingedge.Intheexample,theperiodis 8µs.Dutyisthetimethattheoutputwaveformisatlogicalhigh,4µsintheexample.Acommonlyusedterm is“dutycycle,”whichistheratioofhightolowperiods.Intheexample,thedutycycleis4µs/8µsor0.50.The valueisoftenexpressedasapercentage,soourexamplehasadutycycleof50%.(Occasionallydutycycleis usedtoexpressthepercentageoftimelow,nothigh,sowatchthecontextinwhichthetermisused.) Let’slookinmoredetailhowwegoaboutsettingperiodandduty. First,thePICsfundamentaltimeunitisclockcycles.Iusea20MHzresonatorinmydevelopmentboards (BasicMicroshipstheboardswitha10MHzresonator.)Thus,myclockperiodis50ns(thestock10MHz resonatorclockperiodis100ns): 575
Chapter24
TOSC =
1 1 = = 50 × 10 −9 seconds fOSC 20 × 10 6
SupposewewishthePWMperiodtobe100µs.Wecalculatethenumberofclockcycles,N,requiredfor100µs:
N=
100 × 10 −6 = 2000 50 × 10 −9
TosetthePWMperiodto100µs,weinvokeHPWMwithperiod=2000. Second,periodmaynotexceed16383.Valuesgreaterthan16383causethePWMoutputtofreezeandno compiletimeerrormessageisreturned.Witha20MHzclock,thiscorrespondstoamaximumperiodof 16383x50ns,or819.15µs. Dutyiscalculatedthesamewayandhasthesamelimits.Supposewewishtogenerateour100µsperiod
PWMwaveformwithadutycycleof25%,correspondingtoanontimeof25µs.Wecancalculatethe requireddutybyrepeatingthecalculationforN,butwith25µsinthenumerator,orwecansimplymultiply periodby25%,ineithercaseyieldingduty=500. Unfortunately,thissummaryofperiodanddutyisnotquitecorrect.Asweexpectahighlevellanguage todo,MBasichidessomeofthecomplexityofthePWMmodulesinitsHPWMfunction.Thisresultsina confusingnotecaptioned“ImportantNotes”intheUser’sGuidethatattemptstoexplainhowdutycanbe a10-bitvariable(0…1023)andyetaccept14bitvalues(0…16383).Let’suntanglethisconcept.I’lltryto keepitassimpleaspossible,butnotanysimpler.(ConsultSections8.3ofthe16F87xDataSheetand14.5 oftheMidrangeReferenceManualformoredetail.) Insidethe16F87x’sPWMmodule,theperiodisdeterminedbyacombinationofan8-bitvalueheldinregisterPR2,andtheprescalerdividevaluefortimer2.Theformularelatingperiodtothesetwovaluesis: PWMPeriod=(PR2+1)*4*Tosc*(Timer2prescalevalue)
Timer2’sprescalevalueiseither1,4or16,dependingonhowtheprescalercontrolbitsT2CKPS1and T2CKPS0aresetinitsassociatedcontrolregisterT2CON.
ThepositivedurationofthePWMoutputissetbyadifferentmechanism,anditsformulais: PWMDuty(High)=(CCPRxL:CCPRxCON<5:4>)*(Timer2prescalevalue)
Theterm(CCPRxL:CCPRxCON<5:4>)representsa10-bitvaluecomprisedofan8-bitregister(CCPRxLandtwo bits(bitsno.5and4)fromasecondregister,CCPRxCON.)Wesee,however,thattimer2’sprescalervalue affectsthehightimeaswellastheperiod. Withoutspendingmoretimeonthisthanabsolutelynecessary,weshouldseethefollowing: • Periodmustmoveinstepsof4Tosc,16Toscor64Tosc,dependinguponwhethertimer2’sprescaleris setfor1,4or16. • Theperioddeterminingvariableisheldinan8-bitregister,whichmeanswehaveonly256possible periodsforeachofthethreepossibleprescalervalues,or768possibleperiodstotal. • ThedurationofthehighoutputissettableinstepsofTosc,4Toscor16Tosc,dependinguponwhether timer2’sprescalerissetfor1,4or16. • Thedutyisalwayssettablewithfourtimestheprecisionoftheperiod. Yet,HPWMletsusdefinebothperiodanddutyintermsofTosc,notsomemultipleofTosc.Or,doesit? Whatactuallyhappensis,yes,youentervaluesforperiodanddutyintermsofmultiplesofTosc.However, thefunctionHPWMcanonlydothatwhichthehardwarepermits.So,thevaluesyouenterforperiodand dutyareconvertedtobecompatiblewiththehardwarePWMmodule,asshowninthefollowingtable.
576
DCMotorControl PeriodValue HPWM period 0…1023 1024…4095 4096…16383
Timer2 Prescaler 1 4 16
Step(Tosc) 4 16 64
Step(ns)forFosc= 20MHz 200 800 3200
DutyValue Step(ns)forFosc= Step(Tosc) 20MHz 1 50 4 200 16 800
Suppose,forexample,wewishtogenerateaPWMwaveformwithaperiodof500ns,andthatweareusing a20MHzoscillator.Wecalculatethatperiodshouldbe10: 500 ns N= = 10 50 ns Let’smakethedutycycle40%,or200ns.Wehaveperiod =10andduty=4,soweinvokethehardwarePWMmoduleconnectedtopinC2withHPWM0,10,4.Wethenlookat theoutputonpinC2withanoscilloscopeandgetasurprise. Weexpecttoseea500nsperiod,with200nsatlogic1 and300nsatlogic0.Figure24-7reveals,however,thatthe periodisabout600ns,not500ns,andthatalthoughtheduty matchesourexpected200ns,thelongerperiodreducesthe dutycycleto33.3%. Howdidthishappen?Forperiodbetween0…1023,HPWM loadsthe8-bitPWMregisterbyfirstintegerdividingperiod Figure24-7:OutputforHPWM0,10,4. by4.Hence,ifwetrydifferentvaluesofperiod,weseethe outputstepsinunitsoffour: period 0 1 2 3 4 5 6 7 8 9 10 11 12
ExpectedPeriod(ns) 0 50 100 150 200 250 300 350 400 450 500 550 600
ActualPeriod(ns) 200 200 200 200 400 400 400 400 600 600 600 600 800
Ifwetrydifferentvaluesofduty,say3insteadof4,soourfunctioncallisHPWM0,10,3,weseethatthe dutyportionofthewaveformdoesreduceby50ns. Assummarizedintheearliertable,weseestepbreaksat1024and4096,wheretheperiodstepsize increasesfrom200nsandbecomes800nsand3200ns,respectively.And,sincedutystepsizeisalways one-fourththeperiodstep,thedutystepincreasesfrom50nsto200nsand800nsatthesebreakpoints.
577
Chapter24 ThepointtorememberisthatalthoughHPWMletsusenterperiodanddutyintermsoftheoscillatorclock period,infactbothperiod(always)andduty(ifperiod>1023)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| (TachWid<MaxPeriod)Then Avg=Avg+TachWid k=k+1 EndIf Pause10 Next;j
Avg=Avg/k Freq=1000000.0/(2.0*ToFloat(Avg)*1.4) RPM=7.5*Freq ;basedon16poletachometer RealDC=100.0fmul(FloatDutyCycfdivFloatPWMPrd) PctGood=100.0fmul(FloatkfdivFloatAvgNumber) HSerOut[“RPM:“,RealRPM\1,HTAB,”DutyCycle| %:”,HTab,Real4RealDC\2,| HTab,”FreqHz:“,Real6Freq\1,HTab,| “Good%:”,HTab,Real4PctGood\1,HTab,| “Periodus:”,HTab,DecAvg,13] Next GoToMain
WestartwithaFor/Nextlooptovarythedutycycleandrampupthemotorspeed. Main
ForDutyCyc=MinDutyCycto(PWMPrd-DCStep)StepDCStep HPWMPWMC2,PWMPrd,DutyCyc
580
DCMotorControl There’snopointsteppingatdutycyclessolowthatthemotordoesn’tmove.Hence,westartatMinDutyCyc,whichformymotoris368,correspondingtoabout2.2Vaverageacrossthemotor.WesettheHPWM parametersasdiscussedearlier. There’sanimportantpointabouthardware-basedPWMformotorcontrolthatmakesitessentialformotor control;itisa“setandforget”feature.ThismeanswecansetthehardwarePWMtooutputacertainvalue andthenexecuteothersoftwarefunctions,suchasmeasuringthemotor’sspeedandcalculatingthespeed errorandacorrectionfactorwhilethemotorcontinuestorun.Wecan’tdothiswithMBasic’ssoftwarePWM procedure,asprogramexecutionstayswithPWMuntilthestatementisfinished.
Avg=0 k=0 Forj=1toAvgNumber PulsInTachPin,Hi2Low,TachWid If(TachWid>MinPeriod)AND| (TachWid<MaxPeriod)Then Avg=Avg+TachWid k=k+1 EndIf Pause10 Next;j
Next,wereadthetachometerpulsewidthAvgNumber(200)timesandaddgoodpulsewidthvaluestoAvg. (We’lllaterdivideitbythenumberofvalidcountstogettheaveragepulsewidth.)We’vepredefinedthe constantHi2LowtomakePulsInreadthepositivepulsewidth.
Figure 24-11: Clean Tachometer Pulse Ch1: OutputofMCP601;Ch2:unused.
Figure 24-12: Dirty Tachometer Pulse Ch1: OutputofMCP601;Ch2:unused.
WhenIdevelopedProgram24-3,Ifoundsometachometeroutputpulseswereveryclean,suchastheone seeninFigure24-11.However,particularlyatlowerspeeds,somepulseshadmultiplespurioustransitionsatboththeleadingandtrailingedge,asillustratedinFigure24-12.Thespuriouspulsesareenoughto triggerPulsInandgiveerroneouspulsewidthreadings.Hence,wetestthemeasuredpulsewidthagainst minimum(MinPeriod,definedas200units)andmaximumexpectedvalues(MaxPeriod,definedas8000 units).SinceI’musinga20MHzresonatorinmy2840DevelopmentBoard,onePulsInunitis1.4µs.If themeasuredpulseiswithinthewindow,weassumeitisvalidandadditsvaluetoAvg,incrementingthe “goodpulse”counter,k. Avg=Avg/k Freq=1000000.0/(2.0*ToFloat(Avg)*1.4) RPM=7.5*Freq ;basedon16poletachometer RealDC=100.0fmul(FloatDutyCycfdivFloatPWMPrd) PctGood=100.0fmul(FloatkfdivFloatAvgNumber)
581
Chapter24
Next GoToMain
HSerOut[“RPM:“,RealRPM\1,HTAB,”DutyCycle| %:”,HTab,Real4RealDC\2,| HTab,”FreqHz:“,Real6Freq\1,HTab,| “Good%:”,HTab,Real4PctGood\1,HTab,| “Periodus:”,HTab,DecAvg,13]
Afterwe’vereadthetachometerAvgNumbertimes,wethencomputeseveralstatistics. First,wecomputetheaveragepulsewidth(inunits)AvgbydividingthesumofthePulsInvalues(heldin thevariableAvg)bythenumberoflegitimatereadingsk.Tosaveavariable,westoretheaverageinAvg. FreqisthefrequencyinHzofthetachometeroutput,whichwecomputebytakingthereciprocalofthe
pulseduration.Sincewemeasureonlyonesideofthepulseduration(thepositivepulse),wemustmultiply themeasuredaverageduration,Avg,bytwo.Toconvertthedurationfromunitstomicrosecondswemultiply Avgby1.4andtoconvertfrommicrosecondstoHz,wemustcompute1000000.0/microseconds. Next,wecomputethemotorspeedRPM.Aswediscoveredearlier,a16-polemotorproduceseightcomplete cyclesperrevolution.Hence,themotorspeedinrev/secisFreq/8.Toconverttothemoreconventional rev/min,wemultiplyrev/secby60.Thus,RPM=60*Freq/8,or,combiningtheconstants60and8, RPM=7.5*Freq. Lastly,wecomputethedutycyclestatedinpercentforthecurrentdutyvalue,thepercentageofvalidpulse widthsofthoseread,andthefrequencycorrespondingtotheaveragetachometerpulsewidth. Here’sasampleofProgram24-3’soutput. RPM:3629.5 RPM:3649.2 RPM:3684.4 RPM:3709.9 RPM:3725.4 RPM:3767.3 RPM:3788.6
DutyCycle%: DutyCycle%: DutyCycle%: DutyCycle%: DutyCycle%: DutyCycle%: DutyCycle%:
57.81 58.20 58.59 58.98 59.37 59.76 60.15
FreqHz:483.9 FreqHz:486.5 FreqHz:491.2 FreqHz:494.6 FreqHz:496.7 FreqHz:502.3 FreqHz:505.1
Good%: 100.0 Good%: 100.0 Good%: 99.4 Good%: 99.4 Good%: 100.0 Good%: 100.0 Good%: 97.9
WidthUnits: WidthUnits: WidthUnits: WidthUnits: WidthUnits: WidthUnits: WidthUnits:
738 734 727 722 719 711 707
Let’sseewhatthedatashowswhenplotted.Figure24-13showsthatwhenrunningwithoutloadourmotor’s speedisquitelinear.(Remember,tachometeroutputfrequencyislinearlyproportionaltoshaftspeed.). Program24-4 We’venowdemonstratedhowtovarythemotor speedthroughchangingthePWMdutycycleand howtomeasurethemotor’sspeed.It’stimetoput theseelementstogetherandregulatethemotor’s speed.Program24-4implementsasimplebangbangcontrolloop.
Figure24-13:Openloopmotorspeedversusdutycycle.
582
DCMotorControl ;Program24-3 ;MotorPWMversusTachFrequency ;Bang-Bangcontrol ;Constants ;------------TachPin Low2Hi Hi2Low MinPeriod MaxPeriod MotorPin RPM
Con Con Con Con Con Con Con
C5 1 0 20 8000 C2 1750
;inputpinforperiodmeasurement ;forPulsIndirection ;forPulsIndirection ;minimumunitsforvalidpulse ;maximumunitsforvalidpulse ;2N7000drivenfrompinC2 ;TargetRPM
;TheACtachometerproduces8Hzperrevolution ;ToconvertRPMtoperiod,usethefollowing ;formula ;Variables ;------------TachWid Var Target Var
Word Word
;Pulsewidthinusec ;targetpulsewidth
;Initialize ;------------;Spinmotorupforabittoavoid ;startproblems ;Assumes1.4us/unitoutputfromPulsIn ;TheACtachometerproduces8Hzperrevolution ;ToconvertRPMtounitsteps,usethefollowing ;formula Target=2678600/RPM OutputMotorPin HighMotorPin Pause100
Main ;Wehavetokeepthisloopasfastaspossible ;Measureuntilwegetagooddatapoint Repeat PulsInTachPin,Hi2Low,TachWid Until(TachWid>MinPeriod)AND(TachWid<MaxPeriod) ;IfTachWid>Targetthemotorisrunningtooslowly ;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(TachWid<MaxPeriod)
Wedon’twantbadtachometerreadingstocauseerroneousspeedcommands,sowecontinuereadingthe tachometeruntilwegetavaluethat’swithintheacceptablerange. IfTachWid>TargetThen 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(TachWid<MaxPeriod) ;Erroris+ifslow,-iffast ErrorVal=Target-TachWid ;Havetoreducegaintoavoidsaturation DutyCyc=DutyCyc-ErrorVal/Gain ;Watchforboundaryconditions IfDutyCyc>PWMPrdThen DutyCyc=PWMPrd-10 EndIf IfDutyCyc<MinDutyCycThen DutyCyc=MinDutyCyc EndIf Ifk<1000Then HSerOut[SDecErrorVal,13] k=k+1 EndIf GoToMain
Attheoutset,weseeanewstatementGain=100000/RPM.We’llseehowthisisusedshortly.Otherwise,the variableandconstantdeclarationsandinitializationfollowthepatternsetwithearlierprogramsinthischapter. Main
HPWMPWMC2,PWMPrd,DutyCyc
WesetDutyCycatthetopofourmainprogramloop.
Repeat PulsInTachPin,Hi2Low,TachWid Until(TachWid>MinPeriod)AND(TachWid<MaxPeriod)
Next,weusethetechniquedevelopedforProgram24-4tomeasurethetachometerpulsewidth,discarding baddata.
;Erroris+ifslow,-iffast ErrorVal=Target-TachWid
Wenowhavearrivedatthemagicmomentwhenwecancalculatetheerror;itissimplythedifferencebetweenTargetandTachWid,thatis,thetargetpulsewidthminusthemeasuredpulsewidth.Thesignofthe errorispositiveifthemotorisslowandnegativeifitisfast. WenowmakesomeadjustmenttoDutyCyctoadjustthemotorspeed.Wecan’tgetareliablecorrected DutyCycbysimplysubtractingErrorValfromthecurrentDutyCychowever.Whynot?Ourpulseperiod parameter,PWMPrd,is2048.Hence,themaximumDutyCycis2048andtheminimumDutyCycis0.Supposeourmotorisspinningat1000RPM,sothecorrespondingDutyCycisaround400.For1000RPM, TachWidwillbe3750(µs).Wenowcommandittogoto5000RPM.For5000RPM,Targetis750,so ErrorValis750–3750,or–3000.OurfirstcorrectedDutyCycwillthusbe400–(-3000)or3400,which exceedsthemaximumDutyCycvalueof2048.Wecouldjustclipout-of-rangevaluesandnotpermitsetting DutyCyctovaluesgreaterthanPWMPrdorlessthan0.We’lldothatasasafetymeasure,butitturnsoutthat abetterstrategyistodivideErrorValbyavalue.Thisisthemathematicalequivalentofreducingthegain inthefeedbackloop.Hence,wemakethefollowingadjustmentinDutyCyc:
DutyCyc=DutyCyc-ErrorVal/Gain
586
DCMotorControl And,asmentionedearlier,I’veselectedthedivisorGaintobeafunctionofourtargetRPM: Gain=100000/RPM
Let’sfinishlookingattherestofthecodeandthenwe’llexamineourchoiceofGaininmoredetail.
;Watchforboundaryconditions IfDutyCyc>PWMPrdThen DutyCyc=PWMPrd-10 EndIf IfDutyCyc<MinDutyCycThen DutyCyc=MinDutyCyc EndIf
EvenafterwereducethecorrectionthroughdividingbyGain,it’sstillpossibletogenerateanout-of-bounds DutyCyc,sowetrapforanypossibleerrorandsetDutyCyctoanappropriatevalue. Ifk<1000Then HSerOut[SDecErrorVal,13] k=k+1 EndIf GoToMain
Finally,tohelpusunderstandandadjustProgram24-5,wewritethefirst1000ErrorValvaluestothe serialport. Let’sseewhathappensifwechangeGain.We’llfirstuseaseriesofconstantvalues,intheprogression Gain=2,4,8,…,64,andseewhathappensatstartupwithatargetspeedof2000RPM.We’lljudge performancebylookingatthefirst1000errorvaluesemittedovertheserialport.Agoodalgorithmshould reducetheerrortonearlyzero,inapredictablefashion,reasonablyquicklyafterstartup. Figure24-17showsveryinterestingresults;ifGain=2,theerrorneverreducestozero,butoscillateson eithersideofzero.Ourfeedbackloopisunder-damped,andunstable.Othergainvaluesyieldoscillating errors,particularlyatstartup,butgraduallytheerrordecreases.Althoughitmaybedifficulttojudgefrom Figure24-17,settingGain=64yieldedquitesatisfactoryresults. ButwhathappenswhenwesetGain=64andtrydifferenttargetspeeds?Isthisauniversalconstant—at leastforourmotorandourloadcondition?Figure24-18suggeststheanswerisno.Weseesignificantovershootforslowspeedsandaslow,over-dampedresponseforhighspeeds.Itlookslike64isa“magic”gain valueonlyforspeedsof2000to4000RPM.
Figure24-17:Start-uperrorat2000RPMversusgain.
Figure 24-18: Start-up error with gain = 64 versus targetmotorspeed.
587
Chapter24 Ourconclusionisthatgainshouldnotbeaconstant,butrathershouldvarywithRPM,beingsmallerwith highRPMandlargerforslowspeeds.Aftersomeadditionalexperimentation,Ifoundareasonablewayto setgainisGain=100000/RPM.(SincewedividetheerrorbythevalueGain,theeffectofthisequationistoincreasetheloopgainforhigherspeeds.)Figure24-19showsbetterperformanceovertherange 1500RPM–5500RPMthanwithanysinglefixedgainvalue. Whataboutstaticspeederror?Figure24-20showsoursimpleproportionalgainmodificationoutperforms fixedgainversionswhenconsideredoverthefullrangeofspeedvariation. 7
Steady State Speed Error versus Motor Speed Different Control Strategies
6
Speed Error (Percent from Target)
5 4 3 2
Gain = 64 Variable Gain
1 0 -1 -2 -3 -4
Gain = 4
-5
1000
2000
3000
4000
5000
6000
Target Motor Speed (RPM)
Figure 24-20: Proportional control static speed error versuschangesingain.
Finally,howdoesthemoresophisticatedproportional controlcomparewiththebang-bangcontrollerforstatic speedaccuracy?Figure24-21showsthebang-bang approachmorethanholdsitsownifthetargetspeedis between2000and4000RPM,buttheoverallwinneris theproportionalalgorithm,withvariablegain. Theperformancedataandalgorithmstructureis,of course,highlydependentuponthespecificmotorand theload.Don’tlookupontheseprogramsasthesolutiontoallmotorcontrolproblems,butratherusethese ideasasadeparturepointforyourownwork.Agreat dealofcontrolsystemtheoryisdevotedtocalculating loopresponseanddeterminingtherequiredloopgain andtimeconstantstoproducethedesiredresponse. We’llleavethesedetailsforafuturebook. Program24-6
Bang-Bang 15
Speed Error (Percent from Target)
Figure24-19:Start-uperrorwithvariablegain.
Steady State Speed Error versus Motor Speed Different Control Strategies
10
Proportional Gain = 64 5
Proportional Variable Gain 0
-5
Proprtional Gain = 4
1000
2000
3000
4000
5000
6000
Target Motor Speed (RPM)
Figure 24-21: Overall static speed control error comparison.
We’veminedaboutalltheorepossiblewithoutamathematicaltreatmentofcontrolloops,soourlastprogramwilllookatproportionalcontrolusingthealgorithm ofProgram24-5,butwiththeoptiontoreversemotordirection.We’lluseaSN754410H-bridgeasthemotordrive,connectedasshowninFigure24-22.
588
DCMotorControl
Figure24-22:Reversingmotorcontrolcircuit.
Figure24-23:ConceptualviewofH-Bridge.
589
Chapter24 Figure24-23providesaconceptualoverviewofan“H”bridge.Bysettingonecontrolpinhighandtheother low,currentflowsthroughthemotorinonedirection.Ifthetwocontrolpinsreversestate,currentflows throughthemotorinthereversedirection. ToimplementourreversiblePWMcontrolledcircuit,we’lltieonecontrolpintooneofthehardwarePWM modulesandthesecondpintotheotherPWMmodule.Inonedirection,we’llsetonePICoutputpintolow andtheothertoprovidePWMoutput.Toreversedirection,weturnoffthefirstPWMmodule,resetitsassociatedpintobeastandardI/Opinanddropitlow.WethenactivatethesecondPWMmodule.Atnotime arebothPWMmodulesoperating. SinceProgram24-6duplicatesmuchofProgram24-5,we’llonlyanalyzeitsreversingelement. ;Program24-6 ;MotorPWMwithperiodmotorcontrol ;UsesSN754410Hbridge,socanreverse ;OnebridgeinputisonC1andtheotherisonC2 ;HencewhenC1isPWM,C2mustbelowandviceversa ;Constants ;------------PWMC2 PWMC1 PPC2 PPC1 PWMPrd MinDutyCyc TachPin Low2Hi Hi2Low MinPeriod MaxPeriod
Con Con Con Con Con Con Con Con Con Con Con
0 1 C2 C1 2048 512 C5 1 0 250 11000
ForwardCon Reversed
0 Con
;directionflagvalues 1
;SetoutputforPinC2 ;OutputforPinC1 ;aliasforeasiernamerecognition ditto ;For20MHz,PRF=102.5usec ;HavetoincreaseduetoDarlingtondrop ;PulsInpin ;ConstantforPulsIndirection ;ConstantforPulsIndirection ;Minimumperiodtobevalid ;Maxperiodtobevalid
;UsehardwireconstantRPM-inrealprogramreadit ;viaswitchesorRS-232command RPM Con 1750 ;TargetRPM ;TheACtachometerproduces8Hzperrevolution ;ToconvertRPMtoperiod,usethefollowing ;formula.Periodisinmicroseconds ;Thisalsoshouldbeunderusercommand Target Con 60000000/(RPM*2*8) ;Variables ;------------DutyCyc TachWid ErrorVal K Gain Direction OldDirection PWMPin
Var Var Var Var Var Var Var Var
;Initialize ;------------DutyCyc=MinDutyCyc EnableHSerial SetHSerialH115200 k=0
Word Word SWord Word Byte Byte Byte Byte
;usec
;DutycycleforHPWM ;Measuredtachometerwidthinusec ;Errorbetweendesiredandmeasured ;Counterweuseforvariousthings ;Actually1/gain ;Whichdirectiontorotate ;Priordirectionstopifchanges ;WhichPWMpintouseforPWM
;ApproximationtovarygainwithRPM Gain=100000/RPM
590
DCMotorControl ;setdirection Direction=Forward OldDirection=99 GoSubSetDirection ;Mayneedmoreelaboratestartupmechanism Main HPWMPWMPin,PWMPrd,DutyCyc ;Wehavetokeepthisloopasfastaspossible ;Measureuntilwegetagooddatapoint Repeat PulsInTachPin,Hi2Low,TachWid Until(TachWid>MinPeriod)AND(TachWid<MaxPeriod) ;Erroris+ifslow,-iffast ErrorVal=Target-TachWid ;Havetoreducegaintoavoidsaturation DutyCyc=DutyCyc-ErrorVal/Gain ;Watchforboundaryconditions IfDutyCyc>PWMPrdThen DutyCyc=PWMPrd-10 EndIf IfDutyCyc<MinDutyCycThen DutyCyc=MinDutyCyc EndIf ;Uncommenttoseestartuperror ;Ifk<1000Then ; HSerOut[SDecErrorVal,13] ; k=k+1 ;EndIf ;Thiscausesreversaleveryfewminutes ;Inrealprogramuseakeyboardorswitchcommand k=k+1 Ifk=0Then Direction=Forward GoSubSetDirection EndIf Ifk=$7FFFThen Direction=Reversed GoSubSetDirection EndIf GoToMain SetDirection ;lfwehaveachangeindirection,thenwefirst ;stopthemotorwithregenerativebraking ;SincetachisACwecan’tdeterminedirectionfromit ;FirstflagforbadDirectionvalue If(Direction=Forward)OR(Direction=Reversed)Then IfOldDirection<>DirectionThen ;StopHPWMbyresettingcontrolregisters ;Weclearbothanddroplowtostopthemotor ;NextapplicationofHPWMre-initializes CCP1Con=$0 CCP2Con=$0 LowPPC1 LowPPC2 ;Giveittimetostop Pause400 OldDirection=Direction EndIf
591
Chapter24 Return
EndIf
;SetthePWMpintofunctionandtheotherpinlow IfDirection=ForwardThen PWMPin=PWMC2 OutputPPC1 LowPPC1 EndIf ;Likewise.Ifother,leaveitthesame IfDirection=ReversedThen PWMPin=PWMC1 OutputPPC2 LowPPC2 EndIf
End
Inordertocauseaperiodicreversal,I’veaddedasimplecounterroutine.
;Thiscausesreversaleveryfewminutes
;Inrealprogramuseakeyboardorswitchcommand k=k+1 Ifk=0Then Direction=Forward GoSubSetDirection EndIf Ifk=$7FFFThen Direction=Reversed GoSubSetDirection EndIf
Everytimethetachometerissuccessfullyread,thecounterkincrements.Whenk=32767,thedirection reverses.Sincekcontinuestoincrement,iteventuallyrollsoverbackto0afteranadditional32678steps anddirectionreversesagain.ThevariableDirectionissettooneoftwopredefinedconstants,Forward orReversedandthatvalueisusedbysubroutineSetDirectiontoconfigurethePWMmodulesandpins thatimplementthedirectionchange. SetDirection If(Direction=Forward)OR(Direction=Reversed)Then IfOldDirection<>DirectionThen ;StopHPWMbyresettingcontrolregisters ;Weclearbothanddroplowtostopthemotor ;NextapplicationofHPWMre-initializes CCP1Con=$0 CCP2Con=$0 LowPPC1 LowPPC2 ;Giveittimetostop Pause400 OldDirection=Direction EndIf
Uponbeingcalled,subroutineSetDirectionverifiesthatDirectioncontainsavalidvalue,eitherForwardorReversed.Ifnot,controljumpstotheendofsubroutineandnooperationalcodeisexecuted. Ifthedirectionbeingsetisnotthesameasthecurrentdirection,westopthemotorandswitchofftheactive PWMmodule.First,wedisconnectbothPWMmodulesbyclearingtheircontrolregisters.Then,westop themotorbyapplyingdynamicbraking;bysettingbothcontrolpinstotheSN754410low,bothsidesofthe motorareconnectedtoground.Inthiscondition,themotoractsasageneratorintoalowimpedanceload andrapidlycomestoastop.Lastly,wesavethecurrentdirectioninOldDirection.
;SetthePWMpintofunctionandtheotherpinlow IfDirection=ForwardThen PWMPin=PWMC2 OutputPPC1 LowPPC1
592
DCMotorControl Return
EndIf
EndIf ;Likewise.Ifother,leaveitthesame IfDirection=ReversedThen PWMPin=PWMC1 OutputPPC2 LowPPC2 EndIf
ReversingdirectionrequiresusswitchPWMmodules.Toaccommodatethis,we’vechangedtheHPWM callbyreplacingthepreviousconstantthatidentifiedwhichPWMmodulewastobeactivewithavariable PWMPin.
HPWMPWMPin,PWMPrd,DutyCyc
Tosetadirection,weassignPWMPintooneoftwoconstants,PWMC2orPWMC1,whichwehavepredefined tocorrespondtothevaluesHPWMneedstomakethePWMmoduleattachedtopinC2orC1,respectively, active.Wemaketheotherpinanoutputandsetitlow,thusgroundingtheothersideofthemotorthroughthe H-bridge.Figures24-24and24-25illustratethereversalcycle.
Figure24-24:ClockwiseRotationCh1:Inputto SN7544102A;Ch2:InputtoSN7544101A.
Figure24-25:Counter-ClockwiseRotationCh1: InputtoSN7544102A;Ch2:InputtoSN7544101A.
TheSN754410H-bridgeisconstructedwithDarlingtontransistorsinboththehighsideandlowside switches.Itthushasagreatervoltagedropthanour2N7000circuit,andthedropappearsinboththehigh andlowsidemotorconnections.Hence,foragivendutycycle,lessvoltageappearsacrossthemotor.Inour application,theincreasedvoltagedropisnotofmajorconcern,butitmightbeforlargermotors.Fortunately,awidevarietyofH-bridgecircuitsareavailable,includingthosewithlessvoltagedropandhighercurrent ratingsthantheSN754410.
IdeasforModificationstoCircuitsandPrograms •
•
I’venotedtheproblemsmeasuringthetachometeroutputperiodatlowspeeds.Tryimplementingthe fullwaverectifiercircuitofFigure24-2(b).ThePIC’sA/Dconvertercanthenreadtheoutputofthe rectifier.HowshouldthevaluesofRandCinFigure24-2(b)beselected?Whatchangesarenecessary totheprogramlogicandcodetosubstituteanA/Dreadingfortheperiod?HowwilltheA/Dandthe programcodehandletherippleoutofthetachometerfilter?HowdoestheRCfiltertimeconstantaffect speedcontrolstabilityandtimeresponse? Ifweinsteadkeepthefrequencymeasuringapproach,willasimplelow-passfilteronthetachometeroutputimprovethemeasurementaccuracybyreducingnoise?(Ifoundthatevenasimplefilter comprisinga0.033µFcapacitoracrossthetachometerterminalssignificantlyimprovedlowspeed measurements,enablingstableresultsforaslowas400RPM.) 593
Chapter24 • •
IfyouhaveamotorwithaDCtachometer,howwouldyoumodifytheprogramcodeandlogic? Ifwewishtoaddanintegraltermtoourerrorcorrection,wemustintegratetheerror.Onepossibilityis touseasimplenumericalsummingapproach,usingacircularbuffertechnique,usingtheapproachwe developedinChapter11whenwesmoothedtheA/Dreadingsofthedigitalvoltmeterproject.Strictly speaking,however,numericalintegrationofthistypeassumesthatallsamplesoccuratequaltimeintervals.Thiswillnotbethecaseiftheperiodmeasurementsoccuratdifferingintervalsduetodiscarding badreadings.IsthisacasewheretherectificationandA/Dconversionapproachworksbetter?Additionally,thecircularbufferdiscardsoldvaluesatsomepoint.Thisisactuallygoodforouralgorithm.How manyreadingsshouldbesummedinthebuffer?Howshouldtheintegralandproportionalreadingsbe individuallyweighted?
References [24-1]
Bishop,RobertH.,ed.,TheMechatronicsHandbook,CRCPressLLC,(2002) Palmer,Mark,UsingtheCCPModule(s),MicrochipTechnology,Inc.,ApplicationNoteAN594,Rev. B,DocumentDS00594B(1997) [24-3] Rylee,Mike,Low-CostBidirectionalBrushedDCMotorControlUsingthePIC16F684,Microchip Technology,Inc.,ApplicationNoteAN893,Rev.A,DocumentDS00893A(2003) [24-4] Bucella,Tim,ServoControlofaDC-BrushMotor,MicrochipTechnology,Inc.,ApplicationNote AN532,RevC,DocumentDS00532C(1997) [24-5] Duane,Brett,SwitchModeBatteryEliminatorBasedonaPIC16C72A,MicrochipTechnology,Inc., ApplicationNoteAN701,RevA,DocumentDS00701A(1999) [24-6] Lepkowski,Jim,MotorControlSensorFeedbackCircuits,MicrochipTechnology,Inc.,Application NoteAN894,RevA,DocumentDS00894A(2003) [24-7] Sax,Herbert,HowtoDriveDCMotorswithSmartPowerICs,STMicroelectronics,ApplicationNote AN380(December2003) [24-8] Trump,Bruce,DCMotorSpeedController:ControlaDCMotorwithoutTachometerFeedback,BurrBrownApplicationBulletinAB-152(October1999) [24-9] Trump,Bruce,Motorcontrolleroperateswithouttachometerfeedback,EDN,December9,1999,pages 170-171. [24-10] Regan,Tim,ADMOS3A,55V,H-Bridge:TheLMD18200,NationalSemiconductor,ApplicationNote AN-694(2002).
[24-2]
594
25
CHAPTER
BarCodeReader Fewthingsaremoreubiquitousthanbarcodes.Indeed,they’vebecomebackgroundnoiseandoureyesglide overabarcodeswithoutactuallyseeingit.Afteryoubuildabarcodereader,you’llseldomignoreoneagain. Mybarcodereaderisbasedaroundaninexpensivenew-old-stockHewlettPackard(nowAgilentTechnologies)wand,butsimilarwandsmanufacturedbyHPandothersuppliersarewidelyavailableforafew dollarsfromelectronicssurplusdealersoroneBay.We’lllearnabitaboutbarcodesingeneralanddevelop programstoreadtwobarcodes,the“3of9”codeandthe“UniversalProductCode,revisionA,”orUPC-A, thecodeusedtoidentifyretailmerchandise.
BarCodes“101” Themoderneraofbarcodesstartedwiththegroceryindustry’sdesiretostandardizeproductnumbersinthe late1960s.Afterconsideringproposalsfromtheleadingcomputermanufacturers,IBMwonacontractto designacodingsystemtoimplementthegroceryindustry’snumberingsystem,proposingwhatwenowknow asUPC-A,orUniversalProductCode,versionA.AlthoughthefirstUPC-Ascanningsystemwentintoservice in1974,itwascertainlynotthefirstbarcode.Indeed,thefirstUnitedStatesbarcodepatentwasgrantedin 1952,andthefirstpracticaluseofbarcodeswasinthelate1960’stoidentifyrailroadboxcars.UPC-A,andits derivatives,however,arefarandawaythemostcommonbarcodetodayandhaveworldwideusage.
Code3of9 Let’sstartwithasimplebarcodeknownvariouslyas“Code39”and“Code3of9.”Tokeepusspeakinga commonlanguage,let’sdefineafewterms. Bars—arethedarkpartofthecode. Character—isaletterordigitorspecialsymbol(suchas*or$). Element—genericreferencetoeitheraspaceor abar. Module—isthewidthofnarrowestelement (eitheraspaceorabar)inthecode QuietZone—isspaceoneitherendofthebar codetoisolatethebarcodefromitssurroundings. Spaces—arethelighterpartofthecode. Figures25-1and25-2illustratethecomponents ofCode3of9characters.Figure25-1showsa singlecharacter,thenumber0,comprisedoffive Figure 25-1: Character Figure 25-2: Character “0” barsandfourspaces.Belowthebarisahuman “0”(zero)inCode3of9. (zero) in Code 3 of 9 with readablerepresentationofthedigit.Figure25-2 RequiredStart/StopSymbols. 595
Chapter25 showstheminimumlegitimateCode3of9sequence;thestartcharacter“*”followedbyoneormoreuser character(s),concludingwiththestopcharacter“*.”Thebarcodeisisolatedfromitssurroundingsbyaquietzoneatboththeleftandrighthandsides.Code3of9alsorequiresaspacebetweeneachcharacter(we’ll seethatinter-characterspacesarebuiltintotheUPC-Acode).Finally,althoughtheexactratiomaynotbe obvious,Figures25-1and25-2clearlyhavetwoelementwidths,whichwe’llcall“wide”and“narrow.” Nominally,wideelementsarethreetimesthewidthofnarrowelements,althoughahigh-densityversionof thecodereducesthisratioto2.2:1. HowthenarecharactersmappedintovaryingbarwidthsandlocationsinCode3of9?Herearetherules: 1. Wideelementsarethreetimesthewidthofnarrowelements 2. Allcharactersstartandendwithabarandarecomprisedoffivebarsandfourspaces. 3. Allcharactershavetwowidebarsandonewidespace.Allotherelementsarenarrow. 4. Allbarcodesmuststartandstopwiththestart/stopsymbol,theasterisk“*.” 5. Anarrowspaceinter-characterseparatorappearsaftereachcharacter(except,ofcoursethestopsymbol). 6. Wideelementsarebinary1sandnarrowelementsarebinary0s.Whethertheelementisabaroraspace doesnotaffectitsbinaryvalue. 7. Anynumberofcharactersmaybeinasinglebarcode,althoughpracticallengthconsiderationslimitit to6-10charactersinmostcircumstances. Weseesourceoftheterm“3of9,”aseachcharacterhasnineelements,ofwhichthreearewide.Ifweconsider thenarrowestelementashavingawidthofoneunit,thewidthofacompletecharacteris15units,consistingof threeelementsofwidththreeandsixelementsofwidthone,totaling15units.Themoduluswidthofacharacteristhus15.Ifweconsidertheinter-characterspaceaspartofthecharacter,itsmodulusbecomes16. Thebarvalueandspacevalueareseparatelyevaluatedaccordingtothefollowingtable.(Wewon’tgointo whythewideandnarrowelementsareplacedwheretheyare;weareinterestedinreadingthecodesowe willtakeitsstructureasgiven.) SpaceValue BarValue Binary
DecValue
1
2
4
7
8
11
13
14
Decimal
0001
0010
0100
0111
1000
1011
1101
1110
Binary
+
/
$
00000
0
10001
17
K
A
1
% U
01001
9
L
B
2
V
11000
24
M
C
3
W
00101
5
N
D
4
X
10100
20
O
E
5
Y
01100
12
P
F
6
Z
00011
3
Q
G
7
-
10010
18
R
H
8
.
01010
10
S
I
9
00110
6
T
J
0
SPACE
*
Let’sseehowaparticularbarvalueisdecoded.ConsiderthecharactershowninFigure25-1,whichhasthe followingstructure: 1 1
2 2
3 3
4
5 4
6
7
8 5
596
9
10 6
11
12 7
13
14 8
15 9
BarCodeReader I’veaddedthemodulusnumbers(1…15)andelementnumbers(1…9).Wedecodethebarandspacevalues (MSBfirstorder)as: Bars Spaces
Width Binary Width Binary
N 0
N 0 N 0
W 1 W 1
W 1 N 0
N 0 N 0
DecimalValue 6 4
Welookforacharacterwithbarvalue6andspacevalue4andsee thatitisthenumber0. Code3of9iswidelyusedasaninternalstandardforwarehousing andinventorycontrolandithasbeenadoptedbytheUnitedStates militaryforitsLOGMARSlogisticsmanagementprogram.
UPC-A Let’snowturntoUPC-A,asillustratedinFigure25-3.Thefigure doesn’tshowaquietzone,butoneisnormallyusedwithUPC-A. TheUPC-Acodeis12digitslong,withthedigitsdividedintofour categories: NumberSystemCharacter—isadigitassignedaccordingtothe followingscheme: Digit 0 1 2 3 4 5 6 7 8 9
Figure 25-3: Structure of UPC-A bar code.
Meaning Manufactureridentificationnumbers. Reserved. Randomweightitemsmarkedatthestore(articleswherethepricevariesbytheweight;forexamplemeat.The codeisproducedinthestoreandattachedtothearticle.) NationalDrugCode(NDC)andNationalHealthRelatedItemsCode(HRI). In-storemarkingwithoutformat(UPCCodewhichcanbeusedwithoutformatlimits). UPCCoupon. Manufactureridentificationnumbers. Manufactureridentificationnumbers. Reserved. Reserved.
ManufacturerIDNumber—isafive-digitnumberuniquelyidentifyingthemanufacturer.(TheUniform CodeCouncil,Inc.assignsmanufacturerIDnumbers.) ItemNumber—isafive-digitnumberuniquelyidentifyingthemanufacturer’sproduct.(Onceyouhavea manufacturerIDnumber,youassignyourownitemnumbers.) CheckDigit—isadigitformedfromthepreceding11digitstohelpensuredataintegrity.(We’lllatersee howthecheckdigitiscalculated.) Theelementstructureisdividedintoleftandrightparts,separatedbythe“centerguardpattern.”Atboththe leftandrightextremesareguardpatterns.ItshouldbeobviousfromFigure25-3thatelementshavevarying widths.Specifically,elementshaveawidthof1,2,3or4units.(We’lllearnmoreaboutthedetailedstructureoftheUPC-Acodewhenwewriteprogramstoreadit.) TheUPC-Arulesare: 1. Itmustbeexactly12digits,assignedassummarizedabove.Onlydigits0…9arepermittedcharacters.
597
Chapter25 2. Barcodesstartandfinishwithaguardpatternof101. 3. Thecodeisdividedintoleftandrighthalveswithacenterguardpatternof01010. 4. Elementare1,2,3or4unitswide.Eachcharacterhasfourelements,twobarsandtwospaces.Thetotal characterwidthissevenunits. 5. Theelementstructuremapsintoa7-bitcode,withspacesrepresentingbinary0sandbarsbinary1s.The elementwidthencodesthenumberof1sor0s.Aspaceofthreeunitswidth,therefore,representsthe binarysequence000,whileabarofwidthtwounitsrepresentsthebinarysequence11. 6. Charactersintheleftsidestartwithaspaceelement;charactersontherightsidestartwithabar element. 7. Codevaluesareconstructedtoyielduniquevalueswhetherreadleft-to-rightorright-to-left. 8. Thecharacterstructureisself-separating.Hencenointer-characterseparatorneedbeadded. Let’sseehowtheserulesgointocharacterdecoding.Aswesee,digitstotheleftofcenterarecodeddifferentlythanthosetotherightofcenter.Infact,thebitvaluesintheleftandrightimplementationare complementary—1sand0sareinterchanged.Thetableincludesthecorrespondingvaluesforbothforward (left-to-right)andreverse(right-to-left)directions.
LeftofCenter
Forward
Reverse
Value
Value
1
13
88
1
25
76
1
1
19
100
1
0
1
61
94
0
1
1
35
98
0
0
0
1
49
70
0
1
1
1
1
47
122
1
1
0
1
1
59
110
1
1
0
1
1
1
55
118
0
0
0
1
0
1
1
11
104
Forward
Reverse
Digit
6
5
4
3
2
1
0
Value
Value
0
1
1
1
0
0
1
0
114
39
1
1
1
0
0
1
1
0
102
51
2
1
1
0
1
1
0
0
108
27
3
1
0
0
0
0
1
0
66
33
4
1
0
1
1
1
0
0
92
29
5
1
0
0
1
1
1
0
78
57
6
1
0
1
0
0
0
0
80
5
7
1
0
0
0
1
0
0
68
17
8
1
0
0
1
0
0
0
72
9
9
1
1
1
0
1
0
0
116
23
Digit
6
5
4
3
2
1
0
0
0
0
0
1
1
0
1
0
0
1
1
0
0
2
0
0
1
0
0
3
0
1
1
1
4
0
1
0
0
5
0
1
1
6
0
1
7
0
1
8
0
9
RightofCenter
Let’smanuallydecodetwoUPC-Adigits.We’lldecodetwodigitstoillustrateUPC-A’sself-spacingfeature.
598
BarCodeReader (Eachleftsidecharacterendsinabarandstartswithaspace;whileeachrightsidecharacterendsinaspace andstartswithabar.Hencewealwayshaveaspacebetweenoncecharacteranditsadjacentneighbor.) We’llassumethecharactersarefromthelefthalfandthatwereadthemleft-to-right. Character1 1
2
3
4
1
5 2
Character2 6
7
1
3
4
1
2
3 2
4 3
5
6
7
4
I’veaddedmodulusnumbers(1…7)andelementnumbers(1…4)forbothcharacters. Character
1
2
ElementNo. 1 2 3 4 1 2 3 4
Type Space Bar Space Bar Space Bar Space Bar
Width 3 2 1 1 1 2 1 3
Binary 000 11 0 1 0 11 0 111
Let’sassemblethebinaryelements.
Character1:000+11+0+1=0001101,ordecimal13. Character2:0+11+0+111=0110111,ordecimal55.
Wechecktheencodingtableanddiscoverthat13correspondsto0and55correspondsto8.Hencethetwo digitsare08. Ifyoureadthecharactersright-to-left,thevaluesare:
Character1:1+0+11+000=1011000,ordecimal88. Character2:111+0+11+0=1110110,ordecimal118.
Readingthe“reversevalue”entryinthetablewediscoverthat88decodesas0and118decodesas8,yieldingthesamevaluesasourinitialleft-to-rightreading.
BarCodeWand HowthendowegetblackandwhitebarsonpaperintoaPIC?We’llusethesimplestpossiblescanner,a barcodewandreader.Toreadyouswipethewandacrossthebarcode.There’salotofblackmagicthat goesintoawand,soI’llassumeyouwilluseanalreadybuildcommercialwand.Irecentlypurchasedtwo unusedHewlettPackardA000-serieswandsfor$5.00eachfrom anelectronicssurplushouseandsimilarwandsfromHPandother manufacturersarewidelyavailableinthesurplusmarket. MyHPwandisshowninFigure25-4.Itcamewithathree-footcable terminatedwitha6-pinDINplug.(ThematingpaneljackisaMouserElectronicspartno.16PJ224.)AlthoughIwasabletofindHP’s datasheet[25-4]fortheA000-serieswands,myDINplughadsix pins,notfiveasthedatasheetshows.Sinceyoumayhaveasimilar problem,I’llgothoughhowIidentifiedthecorrectpinconnection. Figure25-4:Barcodescanningwand.
599
Chapter25 ManywandsofthiserausedHP’sspecializedLEDsensorandsupportchip,HBCC-0500andfollowedHP’s recommendedcircuitdesignshownintheassociateddatasheet.[25-3]Thewandhasthreeconnections; +5V(red),ground(black)andanopencollectoroutput(white).Afourthconnectionistheshieldforthe cable,whichisnormallyconnectedtotheDINplug’sshell.ThewiringcolorcodecomesfromHP’sdata sheet.Usingasharpboxcutter,Icarefullylengthwiseslittheinsulationofthecableforseveralinchesnear theplug,givingmeaccesstotheindividualconductors.Sureenough,theymatchedHP’scolorcode,red, blackandwhite,andacableshield.Usingasharpstraightpin,Ithenpiercedeachwire’sinsulationoneata timeandmeasuredtheresistancebetweenthewireandeachofthesixpinsoftheDINplug.Afterdeterminingwhichpinconnectstoeachwire,Icarefullypushedthewirebackintothecablesheathandrepairedthe slitwithtransparenttape.It’sagoodthingthatIcheckedtheconnections,asHP’sdatasheetdidnotmatch mywand’swiring.Figure25-5showshowIconnectedthewandtomyPIC,andFigure25-6showstheconnectorconnectionformywand.
Figure25-5:Scanningwandconnection. Function +5V Output Ground Shield
Figure25-6:WandPlugConnection.
WireColor Red White Black ShieldWrapping
MyWand 1 3 4 Shell
HPA000DataSheet 1 2 3 Shell
Incidentally,Ifirstmeasuredtheresistancebetweeneachpairofpins.IwasreasonablysurethatIidentified thecorrectpinconnectionsfromtheresistancemeasurements,butIdidn’twanttoapplypowerincorrectly anddestroythewand.Hence,theprocessdescribedabove. HPmanufacturedwandsinthreeresolutions,andwithbothvisibleredandinfraredlightsources,andwith andwithoutapower-onswitch.I’mprettysuremywandisa“medium”resolutionmodel,capableofresolvingelements0.0075incheswidth,sincebothlowandhighresolutionmodelswerenonstandardproducts. I’vefounditreliableinreadingCode3of9barcodesprintedwith14-pointtypeusingabarcodefontfrom IDAutomation.com.
600
BarCodeReader Sowhathappenswhenyouscanabarcode?First,wireupyourwandasshowninFigure25-5andconnect youroscilloscopetothewand’soutputconnection.(Don’tforgetthe4.7kpull-upresistor.)Youshouldsee redlightemanatingfromthewand’stip,assumingyoudon’thaveaninfrared-typewand. HPsays“anon-reflectingblackbarresultsinalogichigh(1)leveloutput,whileareflectingwhitespace willcausealogiclow(0)outputlevel.Theinitialstatewillbeindeterminate.However,ifnobarcodeis scannedafterashortperiod(typicallylessthan1second),thewandwillassumealogiclowstate.”Ifwe scantheCode3of9examplewelookedatearlier,theoutputwillbe:
Figure25-7showshowthisworksinpracticewhenscanningtheCode3of9barcodefor*8.*Theentire scantookabout40msandshows15barsand14spaces,29elementsintotal.Thisiscorrect,aseachCode3 of9charactercontainsnineelementsplusainter-characterspace,foratotaloftenelements.Thus,forthree characters,*8*weshouldsee2×10+9=29elements.Thetrailing*,ofcourse,doesn’thaveanexplicit spaceafteritandonlycomprisesnineelements.Weshouldseefivebarsforeachcharacter,or15barstotal, whichmatchestheoscilloscoperesultaswell.Figure25-8showsthatthemodule1lengthofthescanis about1msandtheratiobetweennarrowandwideelementsiscloserto2.5:1thanthetheoretical3:1.
Figure25-7:WandoutputscanningCode3of 9barcode“*8*.
Figure 25-8: Expanded view of Code 3 of 9 scan.
Figure25-9showstheresultofscanningaUPC-Abarcode. Thisscantookabout70msandshows30bars.Howmany barsshouldwesee?Eachdigithasfourelements,ofwhich twoarebars.Sincewehave12digits,that’s24bars.Theleft andrightguardshavetwobarseach,foratotaloffourbars. Thecenterguardhastwobars.Weexpect,therefore,tosee 30barsandinthat’sexactlywhattheoscilloscopeshows. Figures25-10and25-11expandtheUPC-Ascan.Barsof widthoneandtwoandspacesofwidthoneandthreecanbe seeninFigure25-9,whileFigure25-10showsonebarof widthfour.Evenwherethebarsandspacesareobviouslyof thesamenominalwidth,themeasuredwidthshowsvariation.Oursoftwarewillhavetoallowforimperfectbarcode Figure 25-9: Wand output scanning UPC-A barcode. printingandnonuniformscanning. 601
Chapter25
Figures25-10:Expandedviewofwandoutput scanningUPC-Abarcode.
Figure 25-11: Expanded view of wand output scanningUPC-Abarcode.
Programs Nowthatwehaveahighlevelunderstandingofbarcodesandwands,let’slookatsomecode. We’llstartwithanexperiment—canweuseMBasictoreadthewand,orareweforcedtocodetime-critical elementsinassembler? We’llstartwithasimpleapproach,countingthenumberoftransitionsreportedwhenscanningabarcode.A transitioniseitheralow-to-highresultingfromthewandgoingfromaspacetoabar,orthehigh-to-lowthat occurswhenthewandpassesfromabartoaspace.We’lluseaninterruptdriventechniquetocounttransitions.InChapter6,Programs6-3and6-4,weusedtheinterruptonPortBchangefunctiontoreadarotary encoder,whileChapter10coversinterruptsgenerically.IftheoperationofMBasic’sRBintfunctionisn’t cleartoyou,pleasereviewChapters6and10. Program25-1 ;Program25-1 ;Countthenumberoftransitions ;whenscanabarcode ;Constants ;---------VideoIn
Con
B4
;Variables ;---------NoEdges OldValue i Dummy
Var Var Var Var
Byte Byte Byte Byte
;Initialization ;-------------NoEdges=0 OldValue=0 EnableHSerial SetHSerialH115200 HSerOut[“P25-1”,13] Pause100 InputVideoIn SetPullupsPU_on OnInterruptRbInt,CountEdges EnableRbInt Main
602
BarCodeReader ;--- Fori=0to255 Next IfOldValue<>NoEdgesThen HSerOut[DecNoEdges,13] OldValue=NoEdges EndIf GoToMain Disable CountEdges ;-------- NoEdges=NoEdges+1 Dummy=PortB Resume End
Aspartoftheinitializationcode,wedefinetheinterrupt,RbInt,defineitshandler,CountEdgesandfinally enabletheinterrupt. OnInterruptRbInt,CountEdges EnableRbInt
TheRbIntiscalledeverytimepinsB4,B5,B6orB7changestate,whetherfromhigh-to-loworlow-to-high. InputVideoIn SetPullupsPU_on
We’vepreviouslyaliasedVideoInasB4,thepintowhichthewandoutputisconnected.Sinceachange onanyofB4,B5,B6andB7willcauseaninterrupt,weenablethePIC’sinternalweakpullupresistorsto ensurethattheunusedpinsB5,B6andB7willremainhighandnotcausespuriousinterrupts. ThemainprogramloopexecutesatimekillingForiNextloop. Main ;--- Fori=0to255 Next IfOldValue<>NoEdgesThen HSerOut[DecNoEdges,13] OldValue=NoEdges EndIf GoToMain
Attheconclusionofeachloopcycle,ifadifferentnumberofedgecrossingsisheldinthevariableNoEdges fromthepriorvalueheldinOldValue,Program25-1sendsthenumberofedgescountedoutontheserialport. Disable CountEdges ;-------- NoEdges=NoEdges+1 Dummy=PortB Resume
Theinterruptprocedure,whencalled,incrementsthevariableNoEdgesbyone.(Don’tforgettoaddthe commandDisablebeforetheinterrupthandlertopreventmultiplecallstotheinterruptprocedure.)The statementDummy=PortBisnecessarybecauseMicrochip’sPICdesigndoesnotcleartheportmismatch (themismatchcausestheinterrupttobeissued)unlessPortBisread.Withoutthisdummyreadstatement, theinterruptcontinuestoberepeated,eventhoughnochangeinPortBhasoccurred. WhenIattemptedtoreadaUPC-Abarcode,Program25-1reportedthefollowing: P25-1 2 4 6 8
603
Chapter25 Weshouldhaveseen60transitions(twotransitionsforeachbar;30barsinaUPC-Abarcode)noteight. Betweenthelatencyininterruptsandexecutionspeed,MBasicisn’tfastenough. Program25-2 Let’stryanassemblerinterruptversionofProgram25-1tocounttransitions. ;Program25-2 ;Countthenumberoftransitions ;whenscanabarcode ;Constants ;---------VideoIn Zero
Con Con
B4 0
;Variables ;---------NoEdges OldCount i
Var Var Var
Byte Byte Word
;Initialization ;-------------NoEdges=0 OldCount=99 EnableHSerial SetHSerialH115200 HSerOut[“P25-2”,13] Pause1000 InputB4 InputB5 InputB6 InputB7 SetPullupsPU_on GoSubSetupRBint OutputC0 LowC0 ;NotereASM-InMBasicISRASMisexecuteduponaninterrupt. ;MBasicisresponsibleforcontextsavings,andRTIE. ;The“&0x7F”ISnecessarytotrimoff ;thevariabletypebitsaddedbytheMBasiccompilertothe;underlyingvariable address. ;============================================================= israsm ;============================================================= { ;testforsourceofinterrupt,andonlyhandle ;RBIEinterruptinthisroutine ;entryfromMBasicisinBank0 ;------------------------------------------------------ btfss IntCon,RBIF ;dowehavea GoTo EndProc ;RBINTinterrupt. ;Ifnotjumptoend ;--------followingcodeexecutedonlyifvalidRBINT ClrRBIF movf PortB,f bcf IntCon,RBIF BankSelNoEdges Incf NoEdges&0x7F,f;NoEdges=NoEdges+1 EndProc BankSelZero
604
BarCodeReader } Main ;--- Fori=0to$200 Pause10 Next IfOldCount<>NoEdgesThen HSerOut[DecNoEdges,9,Dec(NoEdges-OldCount),13] OldCount=NoEdges EndIf NoEdges=0 OldCount=0 HSerOut[“Ready”,13] GoToMain SetupRBint ;setuptheRBintinterrrupt ;-------- gie=1 ;globalinterruptenable(INTCON,bit7) rbie=1 ;setRBint Return
Program25-2tracksProgram25-1’sconcept,butsubstitutesanassemblerinterrupt.We’vecoveredMBasic’sISRASMfunctioninChapters13and14.Ifyouhaven’talreadyreadtheseChapters,youmightwishto dosobeforereviewingProgram25-2.Let’slookatthedifferencesbetweenPrograms25-1and25-2. SetupRBint ;setuptheRBintinterrrupt ;-------- gie=1 ;globalinterruptenable(INTCON,bit7) rbie=1 ;setRBint
Sinceweareusinganassembler-basedinterruptroutine,wehavetoenabletheinterrupt.Delvinginto Microchip’sPIC16F87xdatasheet,Section12.10,wefindthattheinterruptonPortBchangeinterruptis knownastheRBIEinterruptinassembler.RBIEisoneoffourmembersoftheGIE,orgeneralinterruptenable,family.So,toenabletheinterruptonPortBchange,wemustenablebothRBIEandGIEbysettingboth to%1.WecandothisinMBasicbecauseMBasicduplicatesmanyassembleridentifiersandletsusreadand writetotheminMBasicstatements. israsm {
btfss IntCon,RBIF GoTo EndProc
;dowehavea ;RBINTinterrupt. ;Ifnotjumptoend ;--------followingcodeexecutedonlyifvalidRBINT
Manyeventscantriggeraninterrupt,includingsendingorreceivinginformationovertheserialportwith MBasic’sHSerOutorHSerInfunctions.BeforeexecutingcodethatrespondstotheRBIE,weaccordingly verifythatwehavereceivedaninterruptgeneratedbyaPortBchange,notsomeotherinterrupt.ThisissimplyaccomplishedbycheckingtheRBIFbitintheIntConregister.(The“F”inRBIFindicatesit’sa“flag” bitassociatedwiththePortBinterrupt;the“E”inRBIEindicatesit’san“enable”bit.)IfRBIFisnotset,then theinterruptisfromsomeothercauseandweimmediatelyjumptotheendoftheinterrupthandlerviathe GoToEndProcstatement. ClrRBIF movf PortB,f bcf IntCon,RBIF BankSelNoEdges Incf NoEdges&0x7F,f;NoEdges=NoEdges+1 EndProc BankSelZero }
TheabovecodefragmentisexecutedonlywhenthereisavalidinterruptonPortBchange.First,weread PortBtoitselfbyexecutingmovfPortB,f.Thismightseemameaninglessexercise,butaswelearnedin 605
Chapter25 Program25-1,wemustreadPortBtoresettheinternalcomparisonstorage.(ThePICcomparesthecurrent valueofPortBbits4…7againstastoredcopy;untilweupdatethestoredcopythemismatchthatcausedthe interruptcontinues.)Next,weresettheinterruptflagbyclearingtheRBIFbit. BeforeupdatingNoEdges,weexecuteaBankSeltoensureweareinthecorrectRAMbank.Lastly,we updatetheNoEdgesvariable.IncrementingNoEdgesby1throughtheincfoperatorisequivalenttoexecutingtheMBasicstatementNoEdges=NoEdges+1. Here’stheoutputfromProgram25-2whenIscannedthreeCode3of9barcodes;*8*,*12*and*123*. Ready 32 Ready 42 Ready 52
32 42 52
WhatshouldbetheoutputfromProgram25-2?ThenumberofelementsinaCode3of9barcode,aswe learnedearlier,is10N-1,whereNisthenumberofcharacters.Hence,thebarcode*8*shouldhave29 elements.And,anadditionaltransitionoccurswhenthewandpassesoverthelastbarandentersthequiet zone,sowe’veaccountedfor30transitions.Whataboutthelasttwo?Afterscanning,Iliftedthewandaway fromthepaper.Thewandthusgoestoblack,foranothertransition.Then,afterabriefperiodofblack,the wandrevertstowhiteidle,yetanothertransition.Hence,weshouldsee32transitions,matchingtheoutput ofProgram25-2.Likewise,wecalculate42and52transitionsfor*12*and*123*barcodes.We’llhaveto payattentiontotheseextraneoustransitionswhenwemeasureelementwidths. Program25-3 Beforewefullydecodeabarcode,wemusthaveanalgorithmtomeasureelementwidths.And,itmakes sensetodevelopandverifythealgorithminasimplestand-aloneprogrambeforewegoontomoreelaborate programs.Hence,inProgram25-3,we’llmeasurethewidthofupto80barcodeelementsanddumpthe widthmeasurementstotheserialport. Asshouldbeobviousbynow,whenwemeasurethe“width”ofabarcodeelementtheresultisinmicroseconds,notinchesormillimeters.Wemeasurethetimeittakestomovethewandfromoneedgeofanelement totheoppositeedge.Ifthewandmovesatamoreorlessconstantspeedacrossthebarcode—areasonable assumptionsincethedistancetraversedissosmall—thephysicalwidthoftheprintedelementisdirectly proportionaltothetransittime.Wewilltriggeranelementwidthmeasurementeverytimethewand’soutput statuschangesstate,justaswedidtocountthenumberoftransitions. Let’sconsiderhowapossiblealgorithmmightwork.We’llkeeptrackofthenumberofelementsreadina bytevariablekandwe’llmeasurethewidthofeachelementintimeunits,storingtheresultinabytearray Data(k).We’llsetaside80bytesforData()anddefinethecorrespondingmaximumvaluefork,79,as kmax.Tomeasureelementduration,we’llusetimer1,a16-bittimerthatcountsupfrom0000to65535. (We’lldiscussourchoiceoftimer1later.)Eachtransitionoccurswhenthewand’soutputchangesstate, therebytriggeringachangeonPortBstateinterrupt. Transition
k
RBINTERRUPT Initializek=0
Low-to-High(spacetobar)Transition 1 1 ResetTimer1to0
0
2 StartTimer0
0
3 ClearRBIF DosomethingelseuntilnextRBINTERRUPT
606
specialcaseatstartup
BarCodeReader RBINTERRUPT High-to-Low(bartospace)Transition 2 1 StopTimer1
0
2 CopyTimer1valuetoData(k)
0
3 ResetTimer1to0
0
4 RestartTimer1
0
5 k=k+1
1
6 ClearRBIF
1
DosomethingelseuntilnextRBINTERRUPT RBINTERRUPT Low-to-High(spacetobar)Transition 3 1 StopTimer1
1
2 CopyTimer1valuetoData(k)
1
3 ResetTimer1to0
1
4 RestartTimer1
1
5 k=k+1
2
6 ClearRBIF
2
DosomethingelseuntilnextRBINTERRUPT RBINTERRUPT High-to-Low(bartospace)Transition 4 1 StopTimer1
2
2 CopyTimer1valuetoData(k)
2
3 ResetTimer1to0
2
4 RestartTimer1
2
5 k=k+1
3
6 ClearRBIF DosomethingelseuntilnextRBINTERRUPT Repeatuntil
A Timer1overflowOR B k>kmax
SpecialCase–Timer1Overflow 1 DisableChangeonPortBinterrupt 2 Setendofcollectionsentinelvariable
Leavingasidethespecialcasesofthefirstandlastelements,thealgorithmisn’tcomplex;witheverytransitionwestoptimer1andcopyitsvalueintoData(k).Wethenresettimer1to0,restartitandincrement k.WeknowwearefinishedwheneitherwerunoutofroominData(k),orwereachthequietzone,as evidencedbyaverywidespacevalue. Ourchoiceofatimerisanimportantcomponentofthisapproach.FromFigures25-7,25-9and25-10,itlooks asifthenarrowestelementwemustmeasurerunsaround1000µs,andthewidestelementabout4000µs.We’ll allowa2:1safetymargintoaccountforfasterorslowerwandmovementsorlargerandsmallerprintedbar
607
Chapter25 codes,soourtargetistocorrectlymeasurea500µselementaswellasan8000µselement,representinga 16:1dynamicrange.And,sincewewillbeworkinginbytelengthintegerarithmetic,wewouldliketohave the500µselementcorrespondtoacountofatleast10or12.Thissuggestsatargetcounter“tick”interval around50µs.A500µswideelementcorrespondsto10“ticks”andan8000µswideelementcorresponds to160“ticks.”Bothvaluesfitintoabytevariableandgivereasonableresolutionwhenitcomestodeciding elementlengths. AswelearnedinChapter15,timer1isa16-bittimerwithanoptionalprescaler(1:1,1:2,1:4and1:8).My PICusesa20MHzoscillator,soiftimer1isinternallyclocked,anditsprescalersetfor1:1,itoperatesat Fosc/4andadvancesonecountevery200ns.Timer1isa16-bitcounter,soitshighbyteincrementsone countevery256*200ns,oronceevery51.2µs,almostexactlyourtarget50µsgoal.So,we’llmeasureelementwidthusingTimer1.Byte1,orTimer1Hinassembler. Program25-3implementsthisalgorithm. ;Program25-3--DiagnosticandDevelopmentProgram ;Readanddumpbarwidthsforupto80bars/spaces STACK=10 ;Constants ;---------VideoIn ASize AStart HTab Zero
Con Con Con Con Con
B4 80 $A0 9 0
;PinforWandconnection ;sizeofarray ;startofarrayBank1 ;Horizontaltabchar ;forbankseluse
;Variables ;---------Initial i k Temp
Var Var Var Var
Byte Byte Byte Byte
;sentinelfor1sttimeafterreset ;counter ;counter ;holdspeekvalue
Initialization ;------------- EnableHSerial SetHSerialH115200 HSerOut[“P25-3”,13] ;PortBasinputs&turnpullupontoassurestates TRISB=$FF SetPullupsPU_on GoSubSetupRBint ;setupRBInterrupt GoSubSetUpTimer1 ;setupTimer1(nointerrupts) GoSubClearArray ;fillarraywithzeros k=0 ;startwithindex=0 Initial=0 ;primeforbeingfirstbar ; ;=========================================================== israsm ;============================================================ { ;testforsourceofinterrupt,and ;onlyhandleRBIEinterruptinthisroutine ;---------------------------------------- btfss IntCon,RBIF ;Isthisa GoTo EndProc ;RBINTinterrupt. ;Ifnotjumptoend ;--------followingcodeexecutedonlyifvalidRBINT
608
BarCodeReader ClrRBIF ;cleartheRBinterruptflag movf PortB,f ;readtoselftoresetcomparevalue bcf IntCon,RBIF btfss Initial&0x7F,0;testtoseeifthisis1stpass GoTo FirstPass Call Stop_n_Copy ;copyTmr1Htoarray Call ResetTimer1 GoTo UpDateK FirstPass ;ifleadingedge,onlystartthetimer ;------ Call ResetTimer1 ;startthetimer bsf Initial&0x7F,0;setthesentinel bcf Pir1,Tmr1IF ;clearthe(forendofscan) GoTo EndProc ;nomoretodo-we’reoutofhere! ResetTimer1 ;setsTimer1=0andstartsitrunning ;------------ BankSelZero ;allinbank0 clrf Tmr1H ;clearthetimer clrf Tmr1L bsf T1Con,Tmr1on ;Turntimer1on Return Stop_n_Copy ;stoptimer1copyhighbytetomemindexk ;----------- BankSelZero ;allinbank0 bcf T1Con,Tmr1On ;turntimeroff movlw AStart ;getstartingaddressintow BankSelk addwf k&0x7F,w ;w=i+startingaddress movwf FSR ;FSRholdstheaddresstobeaccessed movf Tmr1H,w ;getthelowbyteoftimer movwf INDF ;movedataintomemoryatAStart+i Return UpDateK;k=k+1 ;------ BankSelZero incf k&0x7F,f movf k&0x7F,w ;k=k+1.kcan’texceedASize-1 sublw ASize ;testtoseeifk=Asize btfsc STATUS,Z ;checkforequal clrf k&0x7F ;ifk=ASizeTHENk=0 EndProc BankSelZero } Main ;---
;Timewastingloop.Initialsetto1 ;byfirstscaninterruptsoweuseittoknow ;scanisinprogress Repeat UntilInitial>0 ;lightscaninprogressLED HighC0 Repeat ;interruptworksduringpause ;wedon’tuseinterruptperse,butweusetheIF ;toindicatescanintooverrunwhitespace UntilTmr1IF=%1 ;Timetoliftthescanwandwithouttriggeringasecond rbie=0 ;scan.Disblestherbieinterrupt rbif=0 ;cleartheinterruptflagaswell Pause500
609
Chapter25 rbie=1 LowC0 GoSubReadArray GoSubClearArray k=0 Initial=0 GoToMain
;scanfinished ;dumpscanstoHSerOut ;resettozeros
SetupRBint ;setuptheRBintinterrrupt ;-------- gie=1 globalinterruptenable rbie=1 ;setRBint Return SetUpTimer1 ;setupTimer1 ;--------- t1oscen=0 ;disabletimer1osc tmr1cs=0 ;setforinternalclock t1ckps1=0 ;prescalersetfor1:1 t1ckps0=0 ;prescalersecondbitfor1:1 Return ClearArray ;putszerosintoarray ;-------------- Fori=0to(ASize-1) ASM { movlw AStart ;getstartingaddressintow BankSel i addwf i&0x7F,w ;w=i+startingaddress movwf FSR ;FSR=addresstobeaccessed BankSel i ; movlw 0x00 ;w=0 movwf INDF ;movedatatoaddressAStart+i BankSel Zero ;exitcondition } Next Return ReadArray ;readarraytoserialport ;---------- HSerOut[13,13] ;Scanmemoryanddumpthewidthvaluesout Fori=0to(ASize-1) PEEK(AStart+i),Temp HSerOut[“i:“,Deci,HTab,”Width:“,DecTemp,13] Pause10 Next Return End
Asusual,we’llexamineonlythenewaspectsofProgram25-3. Beforewemayusetimer1,wemustfirstinitializeit.WedothisinsubroutineSetUpTimer1,whichdirectlyfollowswhatwelearnedinChapter15. SetUpTimer1 ;setupTimer1 ;--------- t1oscen=0 ;disabletimer1osc tmr1cs=0 ;setforinternalclock t1ckps1=0 ;prescalersetfor1:1 t1ckps0=0 ;prescalersecondbitfor1:1 Return
Timer1hasanoptionalexternaloscillator,whichwedisable,insteadselectingtheinternalclock.Clearing bothprescalerbitsto0setstheprescaleratioat1:1. 610
BarCodeReader Beforeouranalysisprogressesfurther,weshouldconsiderourdatastructureandmemoryallocation.To simplifyourassemblerroutine,weneed80contiguousbytesofvariablespace.We’llusethe80contiguous bytesofRAMstartingataddress$A0inbank1.ThedefaultmemorymodelusedinMBasicversion5.3.0.0 reservesallRAMinbank0forinternaluseandbeginsallocatinguservariablesataddress$A0inbank1, whichwouldconflictwithourneedfor80freebytesofRAM.ToforceMBasictoreservespaceinbank0 forMBasicvariables,therebyfreeingupbank1forouruse,weaddthecompilerinstructionSTACK=10. Thisfreesup28bytesofbank0RAMspace,whichMBasichasavailableuseforuser-definedvariables.Alternatively,wecouldinstallourarrayinbank2,beginningataddress$120andpermitMBasictousebank1 memoryforuservariables. WemaywishtoexaminetheASMcodegeneratedbyMBasictoverifyourvariablebankassignments. ThesetechniquesarediscussedinChapters13,14and15.Additionally,MBasicdoesnotprovideawayfor ustodeclaretheMBasicbytearrayvariableData(80)andhavethatarraybeginataddress$A0(orany otheraddress)andrunfor80contiguousbytesinasinglebank.Hence,wewillusePEEKtoreadthearray fromMBasic. ToseehowwewritetothefictitiousarrayData(k)inassembler,we’llexaminehowthesubroutineClearArraywriteszerostoall80positions.(WecoulddothiscompletelyinMBasicviathePOKEfunction,but we’lldoitinassemblerasawayoftestingourabilitytowritetoanarray-typedatastructure.) ClearArray ;putszerosintoarray ;-------------- Fori=0to(ASize-1) ASM { movlw AStart BankSel i addwf i&0x7F,w movwf FSR BankSel i movlw 0x00 movwf INDF BankSel Zero } Next Return
;getstartingaddressintow ;w=i+startingaddress ;FSR=addresstobeaccessed ; ;w=0 ;movedatatoaddressAStart+i ;exitcondition
We’vepreviouslydefinedtheconstantsAsizeasthearraysize,80,Astartasthearraystartingaddress, $A0andZeroas0.We’llmixassemblerandBASIChereaswell,showingtheflexibilitythatmakesMBasic souseful.ThisletsuswraptheassemblermemorywriteprocedureinsideaMBasicFor…Nextloop. Ourclearingalgorithmusesindirectmemoryaddressingviathetwospecialregisters,FSRandINDF.The FSRregisterholdstheaddressofthememorytobeaccessed.TheFSRregisteris8bitswideandthusallowsustoaddressmemorylocations$0…$FF,thatis,allmemorylocationsinBanks0and1,includingthe $A0…$EFrangeweusetoholdthewidthdata.ToaddressBanks2and3,wesettheIRPbitto1.(Wemay assumetheIRPbitissetto0whenMBasichandsofftoourASMcode.) TheactualaccessismadetotheINDFregister.Forexample,supposewewishtoclearthefileataddress $A0.First,weloadFSRwiththevalue$A0.TosettheRAMmemoryataddress$A0to0,weexecutethe clearfileinstructionclrf,withitsoperandasINDF.HencetheinstructionclrfINDFclearsthefileatthe addresscontainedinFSR:IRP,$A0inthisexample. Withthisunderstanding,thefirstfourlinesoftheassemblerprocedureshouldbeclear:
movlw BankSel addwf movwf
AStart i i&0x7F,w FSR
611
;getstartingaddressintow ;w=i+startingaddress ;FSR=addresstobeaccessed
Chapter25 Weloadthestartingaddress,Astart,intothewregisterandthenaddthecurrentvalueoftheloopcounter itothestartingaddress.ThesumAstart+iisthenmovedtoFSR.Asigoesfrom0toAsize-1,FSR indexesfrom$A0through$EF.
BankSel movlw movwf BankSel
I 0x00 INDF Zero
; ;w=0 ;movedatatoaddressAStart+i ;exitcondition
Theremainderofourassemblerroutineloadsa0intoINDF.But,aswelearned,INDFactuallyaccessesthe filewiththeaddresspreviouslyloadedinFSR. Theassemblerroutineisthefunctionalequivalentof:
Fori=0to(ASize-1) Data(i)=0 Next
WhereData(i)isthefictitious80-elementbytearraystartingat$A0. Let’sgothroughthemainprogramloop. Main ;---
Repeat UntilInitial>0
TheRepeatUntilloopisatimewastingdummyactivityuntilthestartofascan.Wecouldbeupdating anLCDdisplayorconductingotheractivities.SincethechangeonPortBinterruptisservicedbyanisrasm procedure,thelatencyisafewmicrosecondsatmost;unlikethecasewithapureMBasicinterruptservice routinecalledonlyinbetweenMBasicstatements. TheisrasmprocedurecommunicatesthatawandscanhasstartedbysettingthesentinelvariableInitial to%1.Uponthestartofascan,executionpassestoasecondRepeat…Untilloop.
HighC0 Repeat UntilTmr1IF=%1
BeforeenteringthesecondRepeat…UntilloopweilluminateanLEDconnectedtopinC0toinformthe userthatascanhasstarted. TheexitconditionfromthissecondRepeat…Untilloopisabittrickier.Timer1doesnotautomatically resetanduponrolloveritsetsthetimer1interruptflagbitTmr1IF.Althoughwedonotenablethetimer1 interrupt,nonetheless,wecanstillusetheTmr1IFbittodeterminewhentimer1hasrolledover.And,of course,timer1rollsoverwhenitattemptstomeasurethewidthofthequietzoneaftermeasuringthelast validbar.TheTmr1IFbitthereforesignalsend-of-scan,uponwhichoccurrencethesecondRepeat…Untilloopconditionfailsandexecutioncontinueswiththerestoftheprogram.
rbie=0 rbif=0 Pause500 rbie=1 LowC0
ThescanhasendedandwewishtodisablefurtherchangeonPortBinterruptsuntilwehavecompleted analyzingthecurrentinformation.Disablingthechange-on-PortBinterruptsimmediatelyuponentryinto thequietzonealsoblocksthefalsewand-liftandwand-timeouttransitions.Mywandrequiredabout500ms delaytoavoidfalsepenlifttransitions.Youmayneedtolengthenthisdelayslightlytomatchyourwant.HP specifiesthisperiodas“approximatelyonesecond.”
GoSubReadArray GoSubClearArray
612
BarCodeReader ThesubroutineReadArraydumpsthewidthmeasurementstotheserialport,andsubroutineClearArray, aswe’vejustseen,zerosoutthemeasurementarray. k=0 Initial=0 GoToMain
Finally,weresetthearrayindexkandthestart-of-scansentinel,Initial. Let’snowdelveintotheinterrupthandlercode. israsm ;============================================================ { ;testforsourceofinterrupt,and ;onlyhandleRBIEinterruptinthisroutine ;---------------------------------------- btfss IntCon,RBIF ;Isthisa GoTo EndProc ;RBINTinterrupt. ;Ifnotjumptoend ;--------followingcodeexecutedonlyifvalidRBINT
WeusedidenticalcodeinProgram25-2totestfortheinterruptsource,andwewon’trepeattheanalysis. ClrRBIF movf bcf btfss GoTo Call Call GoTo
;cleartheRBinterruptflag PortB,f;readtoselftoresetcomparevalue IntCon,RBIF Initial&0x7F,0 FirstPass
;testtoseeifthisis1stpass
Stop_n_Copy ResetTimer1 UpDateK
;copyTmr1Htoarray
AfterverifyingthatwehaveachangeonPortBinterrupt,weconductthePortBreadandcleartheinterrupt flag,RBIF,justaswedidinProgram25-2. Next,wedetermineifthisinterruptrepresentstheleadingedgeofthefirstbarbyexaminingthevalueofthe sentinelvariableInitial.IfInitial.Bit0=0,indicatingthefirstpass,weexecutethecodeatFirstPassthatresetstimer1,setsInitial.Bit0to%1,indicatinginitializationisfinishedandclearsTmr1IF. (Wecouldhavemadethevariablekperformdoubleduty,butusingaseparatevariableInitialclarifies ouraction.Ifweweretousekasasentinelforthefirstpass,wetestfork=0.) Ifitisnotthefirstpassthroughtheinterruptserviceroutine,thenweexecutetwoassemblersubroutine calls;firsttoStop_n_CopyandsecondtoResetTimer1.Afterthesetwosubroutinecalls,executionjumps toUpDateK. FirstPass ;------ Call bsf bcf GoTo
;ifleadingedge,onlystartthetimer ResetTimer1 Initial&0x7F,0 Pir1,Tmr1IF EndProc
;startthetimer ;setthesentinel ;clearthe(forendofscan) ;nomoretodo-we’reoutofhere!
Aspreviouslystated,thecodeatFirstPassstartstimer1,setsthesentinelvariableInitialandclears theTmr1IFflagbit. ResetTimer1 ;------------ BankSel clrf clrf bsf Return
;setsTimer1=0andstartsitrunning Zero ;allinbank0 Tmr1H ;clearthetimer Tmr1L T1Con,Tmr1on ;Turntimer1on
SubroutineResetTimer1clearsboththehighandlowbytesoftimer1andturnsthetimerbackonbysettingthetimer1controlregisterbitTmr1on.
613
Chapter25 Stop_n_Copy ;----------- BankSelZero bcf movlw BankSel addwf movwf movf movwf Return
;stoptimer1copyhighbytetomemindexk T1Con,Tmr1On AStart k k&0x7F,w FSR
;allinbank0 ;turntimeroff ;getstartingaddressintow
Tmr1H,w INDF
;getthelowbyteoftimer ;movedataintomemoryatAStart+i
;w=i+startingaddress ;FSRholdstheaddresstobeaccessed
SubroutineStop_n_Copyfirststopstimer1byclearingthetimer1controlregisterbitTmr1on.Wethen copythehighbyteoftimer1,Tmr1H,intothememoryarrayusingthesamecodeanalyzedinsubroutine ClearArray. UpDateK;k=k+1 ;------ BankSel incf movf sublw btfsc clrf EndProc BankSelZero }
Zero k&0x7F,f k&0x7F,w ASize STATUS,Z k&0x7F
;k=k+1.kcan’texceedASize-1 ;testtoseeifk=Asize ;checkforequal ;ifk=ASizeTHENk=0
Lastly,weincrementthearrayaddressindexkandtestitssize.Ifk=Asize,weresetktozero.This causesanyadditionalscannedelementstowraparoundthestartofthearray.Alternatively,wecouldendthe scanbyforcingasetofTmr1IF.Weendtheisrasmprocedurebysettingthebankto0,asrequiredbefore returningtoMBasic. Notethatwedonotpreloadthecountertocompensatefortheexecutiontimeofthesetupcode.Sincewe measurewidthsin51.6µsincrements,ignoringcodeexecutiontimeofamicrosecondortwointroduces negligibleerror. ThelastpieceofcodetoexamineisthesubroutineReadArray. ReadArray ;readarraytoserialport ;---------- HSerOut[13,13] ;Scanmemoryanddumpthewidthvaluesout Fori=0to(ASize-1) PEEK(AStart+i),Temp HSerOut[“i:“,Deci,HTab,”Width:“,DecTemp,13] Pause10 Next Return
WereadthedataarrayusingMBasic’sPeekprocedureandwritethewidths. Let’sseetheresultsofascan.We’llscantheCode3of9barcode*9*andseetheresults.(Tosavespace, I’vereformattedtheoutputintofourcolumns.)
614
BarCodeReader 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
Width:14 Width:32 Width:10 Width:12 Width:27 Width:10 Width:25 Width:10 Width:8 Width:9 Width:8 Width:10 Width:25 Width:27 Width:9 Width:9 Width:25 Width:10 Width:8 Width:9
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
Width:8 Width:24 Width:9 Width:9 Width:24 Width:9 Width:24 Width:10 Width:8 Width:24 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0
i:40 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 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
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 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 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0 Width:0
Weseetwothingsimmediately.First,ourtimer1choicelookscorrect.Thesmallestbarwidthis8,not unexpectedsincethebarcodeIscannedwasprintedwitha14-pointfont,butwithinouracceptablerange. Second,wesee30elements.Becauseweincrementtheindexvariablekaftereachscaniscompleted,only k-1widthsarevalid,soweshoulddiscardData(29). Let’smanuallydecodethisdata.SincewescannedaCode3of9barcode,eachcharacterhasamodulusof width15,plusoneforthetrailinginter-characterspaceinthecaseofallcharacterssavethelast.Thus,the totalmodulusofthisthree-characterbarcodeis16+16+15,or47.Wesumtherawwidthvaluesandfind theirsumis422“ticks”whereatickis51.6µs.Thus,themoduluscalculatedinticksis422/47,or8.98. Nextweclassifythecalculatedmodulusvaluesaseithernarroworwide.Thenwerankeachelementasa baroraspace,baseduponthefactthatthefirstelementisabar.Lastly,wecalculatethebinaryvaluesassociatedwiththebarsandspaces. Tick Width
Modulus
k
Width
Class
Type
Bar
BinaryValue
0
14
1.56
N
B
0
1
32
3.56
W
S
2
10
1.11
N
B
3
12
1.34
N
S
4
27
3.01
W
B
5
10
1.11
N
S
6
25
2.78
W
B
7
10
1.11
N
S
8
8
0.89
N
B
9
9
1.00
N
S
10
8
0.89
N
B
11
10
1.11
N
S
12
25
2.78
W
B
13
27
3.01
W
S
Space 1
0 0 1 0 1 0 0 Inter-characterspace 0 0 1 1
(Continued)
615
Chapter25 Tick Width
Modulus
k
Width
Class
Type
Bar
BinaryValue
14
9
1.00
N
B
0
15
9
1.00
N
S
16
25
2.78
W
B
17
10
1.11
N
S
18
8
0.89
N
B
19
9
1.00
N
S
20
8
0.89
N
B
21
24
2.67
W
S
22
9
1.00
N
B
23
9
1.00
N
S
24
24
2.67
W
B
25
9
1.00
N
S
26
24
2.67
W
B
27
10
1.11
N
S
28
8
0.89
N
B
SumofTicks
422
ModulusUnits
47
ModulusTicks
8.98
Space 0
1 0 0 Inter-characterspace 0 1 0 0 1 0 1 0 0
Theresultis: Bars CharacterNumber 1 2 3
Binary 00110 01010 00110
Spaces Decimal 6 10 6
Binary 1000 0100 1000
Decimal 8 4 8
CheckingtheCode3of9valuetablewefindthatcharactersoneandthreedecodeasa“*”andcharacter twodecodesasthedigit“9,”asexpected. Program25-4 Tosavespace,thetextofProgram25-4isnotlistedbutisavailableontheassociatedCD-ROM. Nowthatwe’veestablishedthefunctionalityofourinterruptdrivenmeasurementalgorithm,anddeveloped amanualprocessfordecodingtheresultingmeasurementsProgram25-4assemblesitallintoaprogramthat willreadaCode3of9barcodeofupto8characters(includingtheleadingandtrailing“*”characters). MuchofProgram25-4isliftedwithoutchangefromProgram25-3,sowe’lllookonlyatthenewcomponents. ThemainprogramloopsubstitutesacalltoGoSubDecodeDataforProgram25-3’scalltoReadArray. TheinterruptserviceroutineisunchangedfromProgram25-3. Let’slookatsubroutineDecodeData.WhenDecodeDataiscalled,thescaniscompleted,widthdatais storedinmemorystartingataddress$A0andkholdsthelastindex.ThesubroutineDecodeDataimplementsthedataslicingalgorithmwemanuallyperformedearlier. 616
BarCodeReader DecodeData ;decodethereaddata ;------------- Sum=0 ;sumholdsrunningtotal Ifk>0Then 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(k<29)Then GoToNothingFound EndIf
Next,wechecktoseeifthebarcodeissmallerthanthesmallestpossibleCode3of9result,whichis*n* resultingink=29.Ifk<29,thescanisinvalidandexecutionjumpstotheendofthesubroutine.
IfDataDebug=1Then HSerOut[Deci,”Valid”,HTab,”Thsld:“,DecTemp,13] Fori=0to(k-1) PEEK(AStart+i),Temp HSerOut[“i:“,Deci,HTab,”Value:“,| DecTemp,HTab] IfTemp>ThsldThen HSerOut[“W”,13] Else HSerOut[“N”,13] EndIf Pause10 Next EndIf
Again,asadebuggingandprogramverificationaid,weoptionallycansendintermediatevaluestotheserial port.
617
Chapter25
Star=Good ;Checkfor*infirstposition j=0 ;firstcharacter GoSubFillWorkArray GoSubCalculateValues If(SpaceV=8)AND(BarV=6)Then Else Star=Bad EndIf
;Checkfor*inlastposition j=((i/ElLen)-1) GoSubFillWorkArray GoSubCalculateValues If(SpaceV=8)AND(BarV=6)Then Else Star=Bad EndIf
Asanerrorcheck,weverifythatthefirstandlastcharactersdecodeas“*.”(We’llgothroughtheCalculateValuesubroutinelaterintheanalysis;fornowit’senoughtosayitreturnsthebarandspacenumerical valuesinthetwovariablesBarVandSpaceVwhicharethenverifiedagainsttheexpectedvaluesof6and8, respectively.)
;Ifgoodorbadsendmessage IfStar=BadThen GoSubBadScan Else GoSubGoodScan EndIf
Dependinguponthevalueofthefirstandlastcharacters,weexecutea“goodscan”subroutineGoodScanor a“badscan”subroutine,BadScan.
;ifwanttogetmoreinformation IfDataDebug=1Then GoSubDumpChars EndIf
Again,wehavetheoptiontodumpmoreinternalvaluesforprogramdevelopmentanddebugging. ;loopthroughcharacteratatime HSerOut[“Decodedas:“] Forj=0to((i/Ellen)-1) GoSubFillWorkArray ;get9widths GoSubCalculateValues ;calculateBarVandSpaceV ;getthecharcorrespondingtoBarVandSpaceV GoSubGetChar HSerOut[Temp] Next;j HSerOut[13] NothingFound Return
Lastly,themainprogramloopoutputsthedecodedbarcode,onecharacteratatime.Individualcharacters aredecodedinthethreesubroutinesFillWorkArray,CalculateValuesandGetChar.Thedecoded characterisreturnedinthebytevariableTemp. Let’slookatthesethreesubroutines. ;Filltheworkarray.Assumesjissetbeforecalling ;jisthecharacternumber FillWorkArray ;-------------- Fork=0to(ElLen-1) PEEK(AStart+10*j+k),Temp IfTemp>ThsldThen 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,SpaceVmustbe<=14 ;andBarV<=24butitwillconfuseourerrordatadump Return
AswelearnedwhenmanuallyevaluatingCode3of9barcodes,thebarandspacevaluesareinterleaved. SubroutineCalculateValuesde-interleavesthebarandspacevaluesandcalculatesthenumericalvalue ofeach.Thereareundoubtedlymoreelegantwaystoaccomplishthis,butCalculateValuesusesa straightforwardmethod;multiplyeachbarandeachspaceelement’svaluebyitsbinaryweighting,summing theresultsinseparatebarandspacevaluevariables,BarVandSpaceV,respectively. 619
Chapter25 ThelastcomponentofdecodingthebarcodescanisassociatingtheBarVandSpaceVvalueswithspecific characters,atasksubroutineGetCharaccomplishes.Ifmemorywerenotalimit,wemightdefineapseudo two-dimensionalbytearray,suchasCharacter(BarV,SpaceV)andpopulateitwiththedecodedcharactermatrix.But,memoryisaconcern,sowe’lluseamoreparsimoniousapproach.Wedefinefourbyte arrays,eachholdingallthecharactersassociatedwithoneparticularspacevalue: BC4Str BC8Str BC1Str BC2Str
ByteTable“???7?40??29?6????18?5???3” ByteTable“???-?X*??V?Z????U.?Y???W” ByteTable“???Q?NT??LS?P????KR?O???M” ByteTable“???G?DJ??BI?F????AH?E???C”
ThebytetableBC4StrholdsthecharactersforSpaceV=4,BC8StrforSpaceV=8andsoforth. GetCharreturnsthedecodedcharacterinthebytevariableTemp. ;CallwithSpaceVandBarVset.ReturnsinTemp GetChar;getstheassociatedcharacter ;-------- Temp=“?” ;overwriteifdecoded
WesetTemp=”?”sothatifwedonotdecodeavalidCode3of9character,Tempindicatesanerror.(Code3 of9doesnotcontainthe“?”symbol.)
IfSpaceV=4Then Temp=BC4Str(BarV) EndIf IfSpaceV=8Then Temp=BC8Str(BarV) EndIf IfSpaceV=1Then Temp=BC1Str(BarV) EndIf IfSpaceV=2Then Temp=BC2Str(BarV) EndIf
ThefourIf…ThenstatementsslogthroughthefourmainpossiblevaluesofSpaceVandsetTempbasedon indexingBarVelementsintotheassociatedbytetable. Return
;Forafewspecialcharacters,wecheckwithnestedIFs IfBarV=0Then IfSpaceV=7Then Temp=“%” EndIf IfSpaceV=11Then Temp=“+” EndIf IfSpaceV=13Then Temp=“/” EndIf IfSpaceV=14Then Temp=“$” EndIf EndIf
Ahandfulofspecialsymbolsdon’tjustifyafullbytetable,sowedecodethembyamultipleIf…Thenstatements.AllfourofthesespecialsymbolsareassociatedwithBarV=0,soweneedtestonlytheassociated SpaceV. Theremainingnewsubroutines,BadScanandGoodScan,provideuserfeedback.Agoodscanproduces oneshortbeeponthespeakerbutabadscanproducesadoublebeep.Inaddition,acorrespondinggood/bad messageissentovertheserialport. 620
BarCodeReader BadScan ;goodscan-beepandmessage ;-------- HSerOut[“BadScan”,13] SoundSpkrPin,[BeepLen\BeepHz] PauseBeepLen/250 SoundSpkrPin,[BeepLen\BeepHz] Return GoodScan ;doublebeepandmessage ;---------- HSerOut[“GoodScan”,13] SoundSpkrPin,[BeepLen\BeepHz] Return
Let’slookatsometypicaloutputofProgram25-4. ThefirstsampleisrunwithDataDebug=0tosuppressinternalvariableoutput.(Tosavespace,I’vereformattedtheoutputintothreecolumns.) GoodScan Decodedas:*0* BadScan Decodedas:*1? BadScan Decodedas:*1? GoodScan Decodedas:*12* GoodScan Decodedas:*23* GoodScan Decodedas:*123* GoodScan Decodedas:*098*
BadScan Decodedas:*1234? BadScan Decodedas:?5678* GoodScan Decodedas:*5678* GoodScan Decodedas:*12345* BadScan Decodedas:?09875* GoodScan Decodedas:*09875* BadScan Decodedas:*???456?
BadScan Decodedas:*???456? GoodScan Decodedas:*123456*
WithDataDebug=1,additionalinformationisprovided.(Tosavespace,I’vereformattedtheoutputinto threecolumns.) TotalBars/Spaces:49 Modulus:18 Threshold:36 i:0 Value:30 N i:1 Value:63 W i:2 Value:27 N i:3 Value:22 N i:4 Value:53 W i:5 Value:24 N i:6 Value:49 W i:7 Value:20N i:8 Value:18 N i:9 Value:18 N i:10 Value:45 W i:11 Value:18 N i:12 Value:18 N i:13 Value:43 W i:14 Value:17 N i:15 Value:15 N
i:19 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
Value:18 N Value:16 N Value:17 N Value:43 W Value:18 N Value:17 N Value:17 N Value:43 W Value:44 W Value:17 N Value:16 N Value:17 N Value:17 N Value:44 W Value:20 N Value:45 W Value:20 N Value:46 W Value:50 W Value:20 N
621
i:41 Value:54 W i:35 Value:18 N i:36 Value:20 N i:37 Value:20 N i:38 Value:21 N i:39 Value:18 N i:40 Value:21 N i:41 Value:54 W i:42 Value:27 N i:43 Value:21 N i:44 Value:59 W i:45 Value:28 N i:46 Value:65 W i:47 Value:26 N i:48 Value:29 N GoodScan 0 Space8 Bar6 1 Space4 Bar17 2 Space4 Bar9 3 Space4 Bar24 4 Space8 Bar6 Decodedas:*123*
Chapter25 Asyoumayhavenotedfromourbytetabledefinitions,Program25-4decodestheextendedCode3of9 valuesforlettersA…Zaswellasnumbers. Program25-5 Nowwe’llturntoreadingaUPC-Abarcode.We’llreusemuchofProgram25-4,butwe’llimprovetheslicinganddecodingalgorithms,andmakeafewotherchangestoreflectthedifferentstructureofUPC-A. Tosavespace,thetextofProgram25-5isnotlistedbutisavailableontheassociatedCD-ROM. Asusual,we’llconcentrateonthedifferencesbetweenProgram25-5andProgram25-4.UntilthesubroutineCharacterize,thedifferencesaretrivialtononexistent. OnemajordifferenceinsubroutineCharacterizeisthatProgram25-5decodesandanalyzesthe12UPCAdigitsoneatatimethroughouttheentiresubroutine.Program25-4considersindividualcharactersonly towardstheendofitscorrespondingsubroutineCharacterize. Characterize ;readarrayandgroupandcharacterize ;------------ ;Assumescanisgood;anyerrormakesitbad ScanStatus=Good ;Scanthedatabasedonnumberofcharacters k=k-1;incrementatendisonetoomany ;AgoodUPC-Awillhavek=58aftersubtraction ;represening0...58(59total)elements Ifk<>59Then ScanStatus.Bit0=%1 EndIf
AUPC-AcodeismorestructuredthantheCode3of9decodedinProgram25-4.AvalidUPC-Abarcode willhaveexactly59elements,sowecancheckforonepossibleerrorconditionbyverifyingthatwescanned exactly59elements.Ifnot,wesetScanStatus.Bit0to%1.ScanStatus.Bit0isabit-mappederrorflag thatwe’llusetoprovideabadscandiagnosis.
Position=0 m=0;indexfordigitarray
;stepthroughthewidtharray,onecharacteratatime ;acharisstart/stop/center&the12digits Forj=0to(NoChars-1) Sum=0 ;ChIndexholdsnoofelementsforeachcharacter. ;Getthesumofthebarandspacewidthsforall ;elementsinthecharacter Forn=0to(ChIndex(j)-1) PEEK(AStart+Position+n),Temp Sum=Sum+Temp Next;n
TheForj…Nextloopcontainsthecharacter-by-characteranalysisthatdistinguishesProgram25-5from Program25-4.Theloopvariablejrepresentsthecharacternumber. AUPC-Abarcodehas12numericalcharacters,plusthestart,stopandcentersymbols.Forsimplicity, we’llalsotreatthesespecialsymbolsascharacters,thusgivingus15characterstoconsider.Theconstant NoCharsissetto15andthebytetableChIndexholdsthenumberofbarsandspacesineachsymbol: ChIndexByteTable3,4,4,4,4,4,4,5,4,4,4,4,4,4,3. WhendecodingCode3of9barcodes,wecalculatedthemodulusandthresholdvaluesbaseduponallelementsofthebarcode.Program25-5insteadcalculatesthemodulusandthresholdforeachcharacter.This improvesthethresholddecision,asvariationsinwandspeedaresmallerconsideredoverashorterspan.
;ElIndex=numberofelementsineachcharacter. ;Numbersareformedfrom7elements. ;Modulusistheaverageelementwidth Modulus=Sum/ElIndex(j)
622
BarCodeReader Aswelearnedearlier,eachUPC-Anumericalcharacterisconstructedfromsevenelementallengths,while thestartandstopcharactersarelengththreeandthecentercharacterislengthfive.Theelementallength valuesareheldinthebytetableElIndex:ElIndexByteTable3,7,7,7,7,7,7,5,7,7,7,7,7,7,3. Whencomputingthemodulusofeachindividualcharacter,wedividethesumofthecharacterswidthbythe elementallength:Modulus=Sum/ElIndex(j).
;Dumpdataifinterested IfDataDebug=1Then HSerOut[DecPosition,HTab,Decj,HTab,| DecSum,HTab,DecModulus,13] EndIf
Asinearlierprograms,weincorporateanoptionaldebugginganddevelopmentdataoutput.
;IfChIndex=4,it’sadigit3&5areseparators IfChIndex(j)=4Then GoSubGetDigitValue EndIf
Thestart,stopandcentercharactersdonothaveanumericalvalue,sotheyarenotevaluated—justthe12 numericalcharactersaresettothesubroutineGetDigitValueforevaluation.We’llstudyGetDigitValue later.Fornow,allweneedtoknowisthatitsetsthevariableDValuetothenumericalvalueofcharacter j.DValueisnotthecharacterrepresentedbytheparticularbar/spacecombination;ratheritisthenumericalvalueofthebar/spacecombinationcomputedusingtheruleswelearnedearlierforUPC-Avaluation. GetDigitValuealsodeterminesthecharacterrepresentedbybar/spacecombinationandstoresitinthe 12-elementbytearrayDigits().
;Determinedirectionbylookingatfirstdigit. ;Assumeitisforwardscan.Ifitisintheset ;RevKey,thenitisareversescan. If(j=1)Then Dir=FwdScan Forn=0to9 IfDValue=RevKey(n)Then Dir=RevScan EndIf Next;n EndIf
UPC-A’sinventorsdesignedittobescannedfromeitherleft-to-rightorright-to-left.Indeed,thelefthalfdigits neednotbescannedinthesamedirectionastherighthalfdigits.We’llimplementdirectionlessscanningin Program25-5.Todistinguishthescandirection,wetestthevalueofthefirstnumericalcharacterscanned.The forwardandreversevaluesinthedecodingtable,reproducedbelow,establishthedirectionofthescan.
LeftofCenter
Forward
Reverse
Value
Value
1
13
88
0
1
25
76
1
1
19
100
1
0
1
61
94
0
1
1
35
98
0
0
0
1
49
70
0
1
1
1
1
47
122
1
1
0
1
1
59
110
1
1
0
1
1
1
55
118
0
0
1
0
1
1
11
104
Digit
6
5
4
3
2
1
0
0
0
0
0
1
1
0
1
0
0
1
1
0
2
0
0
1
0
0
3
0
1
1
1
4
0
1
0
0
5
0
1
1
6
0
1
7
0
1
8
0
9
0
623
Chapter25
RightofCenter
Forward
Reverse
Value
Value
0
114
39
1
0
102
51
0
0
108
27
0
1
0
66
33
1
1
0
0
92
29
0
1
1
1
0
78
57
0
1
0
0
0
0
80
5
0
0
0
1
0
0
68
17
1
0
0
1
0
0
0
72
9
1
1
1
0
1
0
0
116
23
Digit
6
5
4
3
2
1
0
0
1
1
1
0
0
1
1
1
1
0
0
1
2
1
1
0
1
1
3
1
0
0
0
4
1
0
1
5
1
0
6
1
7
1
8 9
WetestwhetherDValueisinthereversesetbycomparingittothevaluesheldinthebytetableRevKey: RevKeyByteTable39,51,27,33,29,57,5,17,9,23.Wecomparethefirstdigitonlyagainstrightof-centerreversevaluesbecauseit’sphysicallyimpossibletoscanhalfaUPC-Abarcodeinonedirection andhalfintheotherinacontinuousscanwithahand-heldwand.Hence,thechoicesareleft-to-rightand right-to-leftforthefull12digits.Basedontheresult,wesetthescandirectionflagDirtoeitherFwdScan orRevScan.
;Dumpdataifinterested IfDataDebug=1Then Forn=0to(ChIndex(j)-1) PEEK(AStart+Position+n),Temp ;weaddModulus/2forrounding, ;sinceintegerdivisionissmallest ;integer CWidth=(Temp+Modulus/2)/Modulus HSerOut[Dec(Position+n),HTab,| DecTemp,HTab,DecCWidth,13] Next;n HSerOut[13] EndIf
Asinearlierprograms,weincorporateanoptionaldebugginganddevelopmentdataoutput.
;Positionisthestartingpointintothewidtharray Position=Position+ChIndex(j) Next;j
ThelaststepincyclingthroughthebarcodeonecharacteratatimeistoupdatethevariablePosition whichholdsthenextoffsetintotheRAMmemoryblockfrom$A0to$EFholdingthescanwidths.
;Ifthescanwasright-to-leftthenreversedigits IfDir=RevScanThen GoSubReverseArray EndIf
ThearrayDigits(),computedinsubroutineGetDigitValueholdstheASCIIcharacterscorresponding tothe12UPC-Adigits,heldintheorderoffirstscannedtolastscanned.Ifwescannedleft-to-right,the digitsarecorrectlyheldinDigits().Ifwescannedright-to-left,however,it’snecessarytoreversethedigit order,whichweaccomplishthroughacalltosubroutineReverseArray.
;writethedigits Forn=0to(MaxDigits-1) HSerOut[Digits(n)] ;Checktoseeifanydigitsarebad IfDigits(n)=“?”Then ScanStatus.Bit1=%1 EndIf Next;n HSerOut[13]
624
BarCodeReader Wenowdisplaythedigitsbywritingthemtotheserialport.Thedigitswillbeinthecorrectorder,regardlessofthedirectionwescanned.Ifanycharacterimproperlydecodes,itscharacterissetasa“?”soweuse thepresence“?”charactertodetectforabadscan,settingtheeffortflagScanStatus.Bit1to%1toreflect adigiterror.
GoSubComputeCheckDigit ;UseCheckDigitforerror.Baddigitcomesoutas“?” IfCheckDigit<>(Digits(MaxDigits-1)-”0”) Then ScanStatus.Bit2=%1 EndIf
Thefinalerrorcheckistocomputethecheckdigitbaseduponthefirst11scanneddigitsandcomparethe computedvaluetothescannedcheckdigit.Ifthecomputedandscannedcheckdigitsdonotmatch,wehave anothertypeoferrorandweaccordinglysetScanStatus.Bit2to%1. Return
;reportscanstatuswithbeeps IfScanStatus=GoodThen GoSubGoodScan Else GoSubBadScan EndIf
Lastly,weexecuteeithertheGoodScanorBadScansubroutine,basedupontheerrorflagScanStatus. ScanStatuswillonlyequalGood(aconstantwedefinedas0)ifnoneofitsindividualerrorconditionbits havebeenset. Now,let’sfinishupwiththesubroutinescalledbyCharacterize. SubroutineGetDigitValueiscalledwithj,AStartandModulusdefined.Thevariablejisthecharacter number,AStartisthememoryblockstartingaddress,$A0inourcase,andModulusistheaveragewidth ofthenarrowestelementinthisparticularblockoffourbars/spaces. GetDigitValue ;----------- DValue=0 Forn=0toChIndex(j)-1 PEEK(AStart+Position+n),Temp CWidth=(Temp+Modulus/2)/Modulus Next;n
WereadChIndex(j)charactersfromthewidthmemoryblockandcalculatetheirwidthinmodulusunits. Sinceweuseintegerdivision,toobtaintheequivalentofaroundingoperation,weaddonehalfofthedivisortothedividend. Anexampledemonstrateswhythisisnecessary.SupposeModulus=10andthebarwidth,heldinTemp, is9.ItmaybeobvioustousthatTemprepresentsabarofwidth1,butinintegerdivision9/10=0.Biasing TempupwardsbyonehalfModuluscausestheresulttoberoundedupward.Aseriesofnumericalexamples illustratesthebenefitsofroundingupward
Temp 13 14 15 16 17
Modulus 10 10 10 10 10
IfCWidth=(Temp/ Modulus) 1 1 1 1 1
625
Temp+Modulus/2 18 19 20 21 22
IfCwidth= (Temp+Modulus/2)/ Modulus 1 1 2 2 2
Chapter25 Havingcomputedthewidthoftheelementinmodules,wenowconvertthistoanumber. Fori=1toCWidth Next
DValue.Bit0=n.Bit0 DValue=DValue<<1
Rememberthatleftofcenterdigitsalwaysstartwithaspace,whilerightofcenterdigitsstartwithabar;that spacesarebinaryzerosandbarsarebinary1sandthatthewidthofthebarorspaceisthenumberof1sor 0s. Accordingly,wesettheDValue.Bit0to%1or%0,dependingonwhethertheelementisaspaceorabar andrepeat;shiftingDValue’sbitsoneplacetotherightforeveryunitwidth.Leftofcentercharactersstart withaspaceandalternate,sowhennisevenweareworkingwithaspace;whenitisoddwehaveabar. (Thefirstelementiselementnumber0)Thus,n.Bit0is%0forspacesand%1forbars,whichisexactlythe valuewewishtoshiftintoDValue.Bit0. Notsofast,yousay.Usingn.Bit0tosetthedecodedbitisvalidfordigitstotheleftofcenterbutis backwardsfordigitstotherightofcenterthatstartwithspaces.That’scertainlycorrect.However,ifyou carefullyexaminetheUPC-Acodechart,theonlydifferencebetweenleft-of-centerandright-of-center encodingisthatthe1sand0sarereversed,i.e.,right-of-centercodesarethecomplementsofleft-of-center codes.Hence,ignoringbitinversionaswetraversethecenterstillproducescorrectdecodevalues. Thismaybeclearerifwetakeanexample.Supposethedigit0appearsinbothleftandrighthalvesofthecode. We’llcallthesecharacters0Land0R.IfwefollowtheUPC-Astandardstrictly,wedecode0Las%0001101, or13and0Ras%1110010,or114.However,byignoringthestartingelementinversion,wedecode0R as%0001101,or13.WhetherwefollowtheUPC-Astandardexactly,orignoretheelementinversion,the characterdecodesidentically.Shouldthisshortcutoffendyoursensibilities,itwouldnotbedifficultmodify subroutineGetDigitValuetoinverttheelementbitvalue,baseduponthecharacternumber.
DValue=DValue>>1 ;makeupforlastexcessshift
Sinceweshiftaftereachelement,thefinalelementcausesanextraleftshift,whichwereversewithasingle rightshiftaftertheelementloop.
IfDataDebug=1Then HSerOut[DecDValue,HTab,iBinDValue,HTab,| “Digit:“,DigitMap(DValue),13] EndIf
Again,wehaveanoptionaldatadumpforprogramdebugginganddevelopment. Return
;storethedecodeddigits Digits(m)=DigitMap(Dvalue) m=m+1 Ifm=MaxDigitsthen m=0 EndIf
Finally,decodethedigitintoitscorrespondingcharacter,usingthebytetableDigitMap. DigitMap
ByteTable
“?????6???8?9?0??”,|;0 “?7?2???9?1?2?4??”,|;10 “?3?4???0???????6”,|;20 “?5?1???8?5?7?3??”,|;30 “??3?7?5?8???1?5?”,|;40 “6???????0???4?3?”,|;50 “??4?2?1?9???2???”,|;60 “??0?9?8???6?????”;70
626
BarCodeReader Wecanrecastthisdatainamorehumanreadableformat: Code
Value
Code
Value
Code
Value
Code
5
6
33
3
66
3
98
Value 4
9
8
35
4
68
7
100
2
11
9
39
0
70
5
102
1
13
0
47
6
72
8
104
9
17
7
49
5
76
1
108
2
19
2
51
1
78
5
110
7
23
9
55
8
80
6
114
0
25
1
57
5
88
0
116
9
27
2
59
7
92
4
118
8
29
4
61
3
94
3
122
6
AllotherpossiblevaluesinDigitMaparefilledwiththeerrorcharacter,“?” Animportanterror-checkingfeatureinUPC-Aisthecheckdigit.Thecheckdigitisthelastdigitanditis calculatedwiththefollowingalgorithm,appliedtothefirst11digits: a. Sumtheodddigitsandmultiplythesumbythree b. Sumtheevendigitsandmultiplythesumbyone c. Addthetwovaluescalculatedinsteps(a)and(b).Subtractthisvaluefromthesmallestmultipleof 10thatexceedsthissum.Theresultisthecheckdigit. SupposetheUPC-Ais639785321767.Thecheckdigitisshownas7.Let’scalculateitandseeif7iscorrect. Category Odd Even SumofProducts
Digits 6+9+8+3+1+6 3+7+5+2+7
Sum 33 24
Multiplier 3 1
Product 99 24 123
Thesmallestmultipleof10thatexceeds123is130.Hence,thecheckdigitis:130-123=7.Thismatches thevalueofthecheckdigitinthebarcode. ;Callwiththe12valuesheldinDigits ComputeCheckDigit ;--------------- Sum=0 ;applychecktofirst11digits Fori=0to(MaxDigits-2) ;oddhasmultiplierof3.Butodd/evenis ;basedon1stdigitbeingDigitNo.1,i.e.,odd. ;Sincewestartfrom0,mustreverseodd/even Ifi.Bit0=%0Then Sum=Sum+(Digits(i)-”0”)*3 Else Sum=Sum+(Digits(i)-”0”) EndIf IfDataDebug=1Then HSerOut[Deci,HTab,DecSum,13] EndIf Next;i ;Checkdigitisno.tomakesum=multipleof10 CheckDigit=10-(Sum//10) CheckDigit=CheckDigit//10
ThesubroutineComputeCheckDigitimplementsthisalgorithm.However,insteadoflookingforthe smallestevenmultipleof10thatexceedsthesum,wetakeadvantageoftherulesofbase10arithmeticto
627
Chapter25 simplifythecomputation.Theoperation(Sum//10)istheremainderafterwedividethesumby10;in ourexample123//10=3.Subtractingthisfrom10yieldsthecheckdigit,10-3=7.However,ifSum//10= 0,theresultofthissubtractionis10,not0.Hence,wedoanotherremaindercalculationtoforceachecksum of10intothecorrect0value. Return
IfDataDebug=1Then HSerOut[“Sum:“,DecSum,HTab,”CheckDigit:“,| DecCheckDigit,13] EndIf
Again,wecanoptionallyseeintermediatechecksumcalculations. BadScan;goodscan-beepandmessage ;-------- ;HSerOut[“BadScan-ErrorCode:“,iBinScanStatus,13] SoundSpkrPin,[BeepLen\BeepHz] PauseBeepLen/250 SoundSpkrPin,[BeepLen\BeepHz] Forn=0to2 IfScanStatus.Bit0=%1Then HSerOut[StrErrMsg(n*16)\16,13] EndIf ScanStatus=ScanStatus>>1 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 IfWPM<MinWPMThen WPM=MinWPM EndIf IfWPM>MaxWPMThen WPM=MaxWPM EndIf ELtime=1200/WPM;FromPARIS=50Elements=1Word DotTime=(ElTime*Weight)/50 GoToAfterSelector ;Selectordetermineswhichvariableisupdatedby ;thevalueencoder. UpDateSelector ;------------ Selector=Selector+Counter IfSelector<MinSelThen
645
Chapter26 Return
Selector=MinSel EndIf IfSelector>MaxSelThen Selector=MaxSel EndIf
;Weightdeterminesthedotlength.Keepdashlengthdetermined ;byWPM,butallowdotlengthtovaryiftheoperatorwantsto ;changeit. UpDateWeight ;----------- Weight=Weight+Counter IfWeight<MinWeightThen Weight=MinWeight EndIf IfWeight>MaxWeightThen 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 IfWPM<MinWPMThen WPM=MinWPM EndIf IfWPM>MaxWPMThen 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 MIndex=MIndex+1 EndIf
We’veinitializedMindexto0inProgram26-4’sInitializationsectionandfilledBarrelArywith thespacecharacter.AccordinglyweincrementMindexuntilitreaches19.(Asourusualpractice,we’ve definedthelengthofBarrelAryintermsofaconstantBarrelSize,whichissetto20.Hence,thelast validarrayindexisBarrelSize-1.)WhenMindex=BarrelSize-1,wehavefilledall20positionsofthe Line1withinformationandwethenaddnewcharactersattherighthandendshifttheoldercharactersleft byoneplacetoaccommodatethenewletter.HencetheabovecodeincrementsMindexonlyuntilitreaches 19,atwhichpointitfreezesat19. ;Shiftallcharstothelefttomakeroomfornewones ;thatcomeinattheend. 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<MinWPM.Weonlyneedto ;initializetodefaultsoncewhenprogramming;in ;operation,changedvaluesarewrittentoeeprom ;automaticallyandFirstPassisnotnecessary
658
SendingMorseCode IfParam(WPM)<Param(WPM+MinOff)Then GoSubFirstPass EndIf Return
ReadingparametersfromEEPROMiscomplicatedsincewemustdistinguishbetweendevelopingthe program,wherethestart-upsequenceisinvokedbyMBasic’sprogrammerandwherethestart-upsequence resultsfromnormalpoweron/offsequence.Atprogramtime,MBasicfillsall256EEPROMcellswiththe value$FF,overwritingtheirpriorcontent.Hence,ifwesimplyreadEEPROMtogetstoredparameters,our codewillfailatprogrammingtime,eventhoughitmightworkperfectlyonceprogrammed.Wedetectfor launch-after-programmingbytestingthevalueofParam(WPM).SinceParamisanarrayoftypeSByte,the $FFvaluewillbeinterpretedas–1.ThetestforParam(WPM)<Param(WPM+MinOff)willthereforebe trueonlyforthefirstrunafterprogramming.Inthiscase,Program26-4executessubroutineFirstPass. ;FirstpassiscalledonlywhenEEPROMiszeroizedduringProgramming ;Itprovidesdefaultparameters FirstPass ;------ Param(WPM)=20 Param(Wt)=50 Param(Hand)=Normal GoSubSaveParams Return
SubroutineFirstPasssubstitutesdefaultvaluesandsavesthosevaluestoEEPROM.Atthispoint,poweringthePICoffandbackon,orpressingthe2840DevelopmentBoard’sresetbuttonwillcorrectlyreadthe EEPROMstoredvalues.
IdeasforChangestoProgramsandCircuits •
• •
•
Thealgorithmwe’veusedinPrograms26-2through26-4looksatthestatusoftheoppositepaddlelever beginninghalfwaythroughthecurrentelement.Iftheoppositecontactisclosedatanytimeduringthe secondhalf,theoppositeelementwillbeautomaticallysentwhenthecurrentelementiscompleted. Thisisknownas“ModeB”keyinginhamradioterminology.“ModeA”keyingworksdifferently.Ifthe paddlecontactisreleased,sendingstopsaftercompletionofthecurrentcharacter.Selectionbetween ModesAandBisamatterofpersonalpreference.HowwouldyoumodifyProgram26-4toaddaMode A/Bselector?Whereshouldbemodestatusbedisplayed? Anothermodeis“bugemulation”wherethekeyeremulatesamechanicalsemi-automatickey.Dotsare automaticallysentaslongasthedotleverispressed,buttheoperatormustmakedashesmanually;pressingandholdingthedashlevergivesacontinuousoutput.HowwouldyouaddthistoProgram26-4? Avaluablekeyerfeatureismessagerecordingandplayback.SinceProgram26-4decodestheletteror prosigncorrespondingtotheoperator’stransmission,howwouldyougoaboutsavingthemessagein EEPROMandallowingtheoperatortoeraseorsendthemessage?The256bytesofEEPROM,less whateverisreservedforparametersaving,mightbedividedinto4to8messages,ofperhaps40to80 characterslength.(Notallmemoriesneedidenticallength.)It’salsodesirabletobeableto“chain” memorymessages,sothatmessage1canlinkto,forexample,message3.Howwouldyoudothis? Whatchangestotheuserinterfacewouldbeappropriate? Witha20MHzclock,thelowestsidetonefrequencythatcanbegeneratedbyonePWMmoduleis around1.2KHz.Sidetonefrequencyisanothermatterofpersonalpreference,butIlikeasidetoneof 400Hzto500Hz.Sincea16F876AhastwoPWMgenerators,howmightweproducea400Hzsidetone,whenneithergeneratorwillgobelow1200Hz?Supposeweconnectonesideofthespeakerto onePWMgeneratorandtheothersidetothesecondPWMgenerator.And,supposeonePWMoutputs 10.000KHzandthesecondoutputs10.400KHz.Thespeakerwillreproducethesum(20.400KHz)
659
Chapter26 anddifference(400Hz)betweenthesetwofrequencies.Thesumfrequencywillbeabovethenormal hearingrange,butthedifferenceproducesourdesiredsidetonefrequency.Thiswill,ofcourse,require ustogateoneorbothofthePWMgeneratorstogiveoff/oncontrol,butwe’veseenhowthatisaccomplished.Sincesidetonefrequencyisapersonalpreferenceitem,itshouldbeuserselectable.Ideally,the usershouldbeabletoselectsidetonefrequencyandvolume.(ReviewChapters21and17foranideaon howasmallaudioamplifierwithPIC-controlledvolumelevelmightbeaddedtotheProgram26-4and itsassociatedcircuit.)
References [26-1]
AmericanRadioRelayLeague,TheARRLHandbookforRadioCommunications,81stEd.,Newington, CT.(2004)Nowinits81stedition,theARRLhandbookisthestartingpointreferenceforallthings amateurradio. [26-2] Adams,Chuck,IambicKeying101—Part1,http://www.n9vv.com/k7qo-a-b-keying.html.(April2002).
660
27
CHAPTER
AMorseCodeReader We’veseeninChapter26howaPICcanhelpsendMorsecode.Now,it’stimetoputaPICtoworkreading Morse.And,evenifyou’renotinterestedinreceivingMorsewithaPIC,readthischapteranywaytolearna bitaboutphaselockedloopsandanadaptivealgorithmtoaccountfortimingvariationsinhandsending.
SendingandReceivingMorse Wewon’trepeattheMorsecodeintroductorymaterialpresentedinChapters17and26.But,let’sconsiderbriefly howMorsecodeissentandreceived.InChapter26,welearnedthatamateurradiooperatorsuseoff/ontransmitterkeyingtosendMorse;adotoradashrepresentstransmitteron;spacesaretransmitterofftime.Intheamateur radiofraternity,thison/offmodulationschemeisknownasCW,or“continuouswave”transmission.Inthecomputeranddatacommunicationsworld,on/offmodulationiscalledOOK(on-offkeying)orASK(amplitudeshift keying).We’veseenOOKbefore—inChapter22tobeprecise,asit’spartoftheinfraredremotecontrolcommunicationsprotocol.And,ofcourse,there’snothinglimitingustosendingMorsebyOOK;wecoulduseanyof manymodulationprotocols,suchasfrequencyshiftkeying(dotsanddashesarerepresentedbyonefrequency; spacesbyasecondfrequency)orphaseshiftkeyingormanyothermodulationtechniques.Asapracticalmatter, however,we’llconcernourselveswithOOK,asthat’swhatisusedinpractice. SinceOOKimpliesturningatransmitteronandoff,todetectthesignalwerequireareceiver.And,since Morseisusedmostwidelyintheamateurradioshortwavefrequencies(amateuroperatorshaveaccessto anumberoffrequencybandsbetween1.8and30MHz;seereference[27-2]formoredetails),we’llneed ashortwavereceiver.We’llassumeyoualreadyhaveareceiver,andifnotreference[27-3]mayhelpyou selectone.SinceMorseistraditionallyreceivedasanon-offaudiotone,thereceivermustconverttheon-off signaltoanon-offaudiotone.Thisisdonethrougha“beatfrequencyoscillator”orBFObuiltintothereceiver.OlderreceivershadaswitchlabeledBFOon/off,whileneweronessimplifythingsbyautomatically selectingthepropercircuitrywheneithertheCWorsinglesidebandmodeisengaged.(Singlesideband,or SSBasit’susuallycalled,isamethodofvoicetransmissionthatalsorequiresaBFO;areceiverineither CWorSSBmodewillreceiveMorse.) We’llassumethatyouhaveasuitablereceiverandthatyounowhavethesoundsofMorsecodeechoingout ofthespeaker.HowthentoconverttheaudiotonetoalogiclevelsignalthatourPICwillrecognize?We’ll buildacircuitcalled,logicallyenough,a“tonedetector”thatconvertsthepresenceorabsenceofanaudio tonetoalogiclevelsignal.Therearemanywaystobuildatonedetector;ourdesignemploysanExarXR2211phaselockedloop. Figure27-1isanoverviewofourXR-2211circuit.TheXR-2211isthereceivinghalf(demodulator)ofa modemdevice;itreceivesfrequencyshiftkeyeddatasignalsandtranslatesthetwotonesintologiclevel outputsignals.(Modemstandsformodulator-demodulator;theXR-2211performsthedemodulationhalf ofthemodemfunction,itscompanionchip,theXR-2206performsthemodulationfunction.)Anauxiliary functionbuiltintotheXR-2211,however,istonedetectiontodeterminewhetherthemodemiscurrently receivingasignal,andthat’sthepartwe’lluseinourMorsedecodercircuit. 661
Chapter27
Figure27-1:XR-2211phase lockedloopintegratedcircuit.
Don’tlettheapparentcomplexityoftheXR-2211scareyouoff; we’veseenitsunderlyingprinciplebefore.Beforewediginto thedetailsoftheXR-2211,let’sstartatthebeginning—whatis aphaselockedloop,orPLL?Figure27-2showsaconceptual PLLarrangement;aninputsignal(atfrequencyFINPUT),aphase detector,aphasedetectoroutputconditioningcircuitandavoltage-controlledoscillatororVCOwithoutputfrequencyFVCO.The VCO’sfrequencyrangeincludesFINPUT. Let’sstartwiththephasedetector,whichwemayconsiderasabalancedfrequencymixer;itsoutputisthesumanddifferenceofthe twoinputsignals,FINPUTandFVCOinFigure27-2,i.e.,(FINPUT+FVCO) Figure27-2:Conceptualphaselockloop. and(FINPUT-FVCO).Let’sconcentrateonthedifferencesignal, (FINPUT-FVCO).ThisdifferencesignalrepresentstheerrorbetweentheinputsignalandtheVCO.Thisdifference signalthenisconditioned—andpossiblylevelshifted—andfedintotheVCO.Thecontrolsignaloutputthe conditioningsystemthendrivestheVCOfrequencyFVCOtomatchtheinputfrequencyFINPUT.Ifthissoundsfamiliar—it’sbecauseit’spreciselythesamecontrollooparrangementwesawinChapter24wherewemeasured themotorspeed,compareditwiththetargetfrequency(theerror)andincreasedordecreasedthemotorvoltage todrivetheerrortozero.Herewemeasurethedifference(theerror)betweentheinputsignal(ourtarget)and theVCOandweeitherincreaseordecreasethecontrolvoltagetodrivetheerrortozero. HowthendoweuseaPLLtodeterminewhenanaudiotoneispresentornot?Let’sconsiderwhathappens whennosignalispresent,whichmeanstheinputisnoise.FINPUTcanbethoughofasacollectionofrandomfrequencycomponentsthatquicklycomeandgo.TheVCOtriestosynchronizetotheinputnoise,but itsabilitytotrackquicklyvaryingnoiseislimitedbytheconditioningstagethatincludesalow-passfilter element.(Remembertheoutputofthephasedetectoralsoincludesan(FINPUT+FVCO)component?Ataminimum,wemustattenuatethiscomponentwithalow-passfilter,butwe’llseethatothercriteriadictatedesign 662
AMorseCodeReader ofthelow-passfilter.)Hence,theoutputofthephasedetectorisarandomtimevaryingsignal,which,ifthe inputistruerandomnoise,willhaveanaveragevalueofzero. Now,supposeatoneispresentandtheVCOlockstoit.Thefeedbackmechanismworks,FVCOmatches FINPUTinbothfrequencyandphaseandtheoutputofthephasedetectoris…zero. Waitaminute,yousay,boththelockedandunlockedconditionsarezero?Howdowedistinguishalockedzerofrom anunlockedzero?Itturnsoutthatwithrealphasedetectors,wedon’thavequitesuchadifficulttask.Supposeour phasedetectorresponseisthatshowninFigure27-3,which mayimplementedfromanXORlogicgate.Iftheinput signalisnoiseandiftheloopfilterkeepstheVCOfrom trackingthenoise,thenthephaserelationshipbetweenthe inputsignalandtheVCOwillberandom,uniformlyvaryingfrom–180to+180degrees.Inputtinguniformrandom phasesfrom–180to+180degreestothephasedetector ofFigure27-3resultsinarandomoutput,butonewith anaveragevalueofVcc/2.(Thelowpassloopfiltercan Figure27-3:XOR-typephasedetectorresponse. bethoughtofasanelectronicaveragingcircuit.Youcan computetheoutputmathematicallyorgraphicallyfromFigure27-3,oryoucansimplynotethatitsoutput ispositiveforanyphasedifferenceexcept0.)Now,supposewehaveatoneinputandtheVCOislockedin frequencyandphasetotheinputsignal.Inthiscase,thephaseerrorisconstantat0degrees,andtheoutput ofthephasedetectoris0V.Thus,thephasedetectorofFigure27-3allowsustoeasilydistinguishbetween noise(averageoutputVcc/2)andlockedtoasignal(averageoutput0).Avoltagecomparatorwithoneinput onthelowpassfilteredphasedetectoroutputvoltageandtheotherinputbiasedatVcc/4willthustoggleits outputbetweenlockandno-lockconditions.Inkeepingwiththeintroductorylevelofthisbook,wewon’t considerothertypesofphasedetectors,buttheconceptwe’veillustratedinFigure27-3appliestomanyof them;theaverageoutputvoltageisdifferentforrandomphasenoisecomparedwiththelockedcondition.
ToneDetectorCircuit Figure27-4showsthefinishedtonedetectorcircuit.Let’stakeaquickpassthroughhowitworksbeforewe zeroinonsettingthecomponentvalues.
Figure27-4:Tonedecodercircuit.
663
Chapter27 TheaudioinputsignaliscoupledtotheXR-2211’sinternalpreamplifierthrougha0.1µFblockingcapacitor(pin2).Thepreamplifierisusedasalimitersotheincomingsinewavesignalisconvertedtoasquare wave,withthe10mVbeingtheminimumsignallevelfortheonsetoflimiting.Thepreamp’soutputfeeds twophasedetectors,oneforloopcontrol(outputonpin11)anda“quadrature”phasedetector(outputonpin 3)fortonedetection.TheinternalVCOisconnectedtobothphasedetectors.TheVCO’scenter(unlocked) frequencyissetbythetimeconstantofC0andR0. Theoutputoftheloopphasedetector(pin11)containsboththesumanddifferencefrequenciesoftheinput andtheVCO,asinourearlierdiscussion.WeseethisinFigure27-5whenwelookattheloopphasedetectoroutputwithatoneburstinput.Whennosignalispresent,thephasedetectoroutputisdominatedbythe VCOfrequencywhich,whichidlesisatthecenterfrequency,800Hz;whenthetoneispresent,theoutput isdominatedby(F1+F2)component,at1600Hzinthiscase,assoonasthePLLlocksup.(Wecanseethe FINPUT–FVCOcomponentonlyafterlow-passfilteringouttheFINPUT+FVCOcomponent.)Anexpandedlookat thephasedetectoroutput,asseeninFigure27-6,showsimmediatechangeinthephasedetectoroutputas soonastheinputtoneburstisapplied.
Figure27-5:Ch1:800Hztoneburstinput;Ch2: phasedetectoroutput(pin11).
Figure27-6:Expandedviewofphasedetector output; Ch1: 800 Hz tone burst input; Ch2: phasedetectoroutput(pin11).
ThesumcomponentisattenuatedbyC1andthedifferencecomponentFINPUT-FVCO(theerrorsignal)isappliedasacorrectingcurrenttotheVCOcontrolportthroughR1(VCOinputonpin12).(TheXR-2211’s variablefrequencyoscillatoriscurrentcontrolled,notvoltagecontrolled,soweshouldcallitaCCO,nota VCO,butwe’llcontinuereferringtoitasaVCO.) WhentheVCOissynchronizedwiththeinputsignal,theoutputofthequadraturephasedetectorisdrivento Vcc;whentheVCOisunsynchronizeditisclosetoground.RDandCDprovidefilteringforthequadrature phasedetectoroutput.Figure27-7showsthequadraturephasedetectoroutputrespondingtoatoneburstinput. Theoutputofthequadraturephasedetectorisconnectedtotheminusinputofacomparatorwiththeplusinput connectedtoaninternalvoltagereferencethatisapproximatelyatVcc/2(internalreferencevoltageoutputat pin10).Thecomparatorhasbothanormalandacomplementaryoutput.Thus,whenaninputtoneispresent, thenormaloutput(pin6)ishighwhenthePLLisinlockandlowwhenunlocked.Thecomplementaryoutput (pin5)islowwheninlockandhighwhenunlocked.Figure27-8showhowthecomparatorcleansuptheripple onthequadraturephasedetectoroutput.Themultipletransitionsonthetrailingedgeofthecomparatoroutput areadirectconsequenceoftherelativelygentletransitiontimeinthetrailingedgeofthequadraturedetector outputseeninFigure27-7,combinedwiththeresidual800Hzrippleintheoutput.
664
AMorseCodeReader
Figure27-7:Quadraturephasedetectoroutput; Ch1:800Hztoneburstinput;Ch2:quadrature phasedetectoroutput(pin3).
Figure27-8:Outputofquadraturecomparator; Ch1:toneburstinput;Ch2:quadraturecomparator invertedoutput(pin5).
Thelockdetectorcomparatorisofopencollectordesign andhencerequiresapull-upresistor.R2/D1pullsup thecomparatoroutputandprovides,throughLEDD1, avisualindicationoftonedetection.TheRCnetwork comprisedofR3andC2providesasmallamountoflow passfilteringtoreduceedgeglitchesfromthecomparatoroutput.Figure27-9showstheeffectoftheRCfilter whendecodingoff-the-airsignalsmixedwithnoise. Althoughnotnearlyaseffectiveasamultipolelow-pass filter,theRCnetworkknockstheworstedgesoffthe Figure27-9:RCnetworkeffect;Ch1:outputof spurioustransitions. quadraturecomparator(pin5);Ch2:PICinput followingRCfilter.
ThedesignparametersIusedare: Parameter CenterFrequency TrackingBandwidth
Value 800Hz ±100Hz
Thecenterfrequencyissomewhatamatterofpersonalpreference.MostMorseoperatorsliketolistentoa toneinthe800–1000Hzrange.Althoughmypersonalpreferenceisfora400Hzbeatnote,ourdesigngoes withthetraditional800Hzfrequency.Mychoiceofa±100Hzlockbandwidthisbaseduponexperience; thenarrowerthebandwidththelongerittakesforthetonedetectortolockupandrelease.For60WPM Morse,thedotlengthis20ms,usingtheformulawederivedinChapter26.Toreducedistortion,wewill requirethetonedecodertolockupinlessthan25%oftheshortestelementduration,or5ms.Sincethelock timeisapproximately1/totalbandwidth,tomeetthisobjectivethetotalbandwidthmustnotbelessthan 1/.005,or200Hztotal,or±100Hz. DesigningthecircuitrequiresustocalculatevaluesforC0,C1,Cd,R0,R1andRd,aswellassomeancillarycomponents.AlthoughtheXR-2211’sdatasheetcoversthesecalculations,Ifoundaninconsistencyor twothatinitiallyleadmetoincorrectvaluesforseveralcomponents.Let’sgothroughthecalculations.You maywishtohavetheXR-2211datasheetinfrontofyou.
665
Chapter27 Step1—C0andR0 C0andR0determinetheVCO’scenterfrequency.(Wenormallywritecomponentreferenceswithouta subscript,i.e.,C0,notC0.However,forconsistencywiththeXR-2211’sdatasheet,we’llusesubscripted componentvaluesinthissection.)Althoughwe’vesaidthecenterfrequencyofourdesignis800Hz,inrealitythecenterfrequencyf0isthe“geometricmean”oftheupperandlowercutofffrequencies,900Hzand 700Hz,respectively:
f0 =
fL fU = 700 × 900 = 793.7 Hz
wherefLandfUaretheloweranduppercutofffrequencies. Sinceourfilterisrelativelynarrowbandwithrespecttothecenterfrequency,thegeometricmeanisalmost thesameasthearithmeticalmean,andwe’llusef0=800Hzforconvenience.Thissimplificationintroduces lessthan1%errorincomponentvalues. TheXR-2211datasheetprovidesthefollowingrelationshipamongf0,R0andC0: 1 1 f0 = and R0 = R0C0 f0 C0 Where10K<R0<100Kand200pF<C0<10µF BasedupontheXR-2211’sdatasheet’sFigure7,we’llpickC0as0.1µF.C0shouldbeahighqualityMylar orpolyestercapacitor.WenowcancalculateR0: 1 1 = = 12500 f0C0 800 × 0.1 × 10 −6 TopermitustoadjustthecenterfrequencytocompensateforC0’stolerance,we’lluseaseriescombination ofa10Kfixedresistoranda3Kpotentiometer.
R0 =
Step2—R1 R2definesthebandwidth.ThecorrectequationrelatingR2andbandwidthis: Rf R2 = 1 0 ∆f Where∆fistheone-sidedbandwidth—thatis,100Hz.(Thedesignexampleatpage16oftheXR2211’s datasheetconfusessingle-sidedanddouble-sidedbandwidthvaluesandintroducesanextrafactorof2into thenumeratorofthisequation.) Rf 12500 × 800 R2 = 1 0 = = 100 K ∆f 100 Basedonmeasureddata,IfoundthatthecalculatedR2wastoohighandthat82Kprovidedexactlythedesired±100Hzbandwidth.We’lldiscusshowtoverifyperformanceofyourcompletedcircuitlater.
Step3—C1 C1ispartofthecontrolloopfeedbackcircuit’slow-passfilter.Ithasthreepurposes:firsttoattenuatethe (FINPUT+FVCO)componentfromthephasedetector;secondtoaveragethe(FINPUT–FVCO)componentoutof thephasedetectorandthirdtogovernthestepresponseofthecontrolloop.Chapter24,Figures24-17,18 and19showwhatmayhappentoamotorcontrolloopinresponsetoanabruptchangeincontrolledorreferencevalues;theloopmayundershoot,overshootoroscillate.ThesamephenomenaoccurinourPLLloop. Incontrolsystemlanguage,thereactionofthelooptoachangeiscalled“damping.”Aloopthatundershoots
666
AMorseCodeReader isover-damped,whileonethatoscillatesmaybeunder-damped.We’llskipthemathbehindit,simplyfollowingExar’srecommendationtosizeC1foradampingfactorof0.5,wheretherelationshipbetweenC1and thedampingfactoris: 1250 ⋅ C0 C1 = R1 ⋅ζ 2 Whereζisthedampingfactor. C1 =
1250 ⋅ C0 1250 × 0.1 × 10 −6 = = 5 × 10 −9 = 5nF R1 ⋅ ζ 2 100000 × 0.52
Iuseda5nF(5000pF)MylarcapacitorforC1.
Step4—RDandCD ExarrecommendsRDbesetat470K,andCDsizedusingthefollowingequation: 16 CD > ∆f CDisinµF. CD >
16 16 = = 0.075µF ∆f 200
(There’sanotherinconsistencyintheXR-2211datasheetinthisequation;itappearsthat∆fhererefersto thedouble-sidedbandwidth.) InadditiontothelockuptimeofthePLL,whichwesetthroughR1andC1,CDsetsthelockuptimeofthe tonedetectorcomparator.Thus,forthetonedetectoroutputtoreflecttonecapturetwoeventsmustoccur: (a)themainPLLloop(comprisingthephasedetectorwithPin12asitsoutput)mustlockupand(b)the tonedetectphasedetectoroutputtracksthelockupofthemainPLLloopandCDchargessufficientlysothat thevoltageatPin3exceedstheinternalreferencevoltageandthelockdetectorcomparatorchangesstate. Hence,wewishtomakeCDassmallasfeasible,consistentwiththeminimumvaluewe’vecalculated.Iset CDat0.1µF.C0shouldbeaMylarorothertemperaturestablecapacitor. ThefinalcomponentswemustdetermineareR2,R3andC2.R2isthepull-upresistorfortheopencollector lockdetectioncomparator.WealsouseR2tolimitthecurrentthroughthelockdetectionLED,D1.Exar ratesthecomparatoroutputtosinkamaximumof5mA,soweusethetechniquediscussedinChapter3to determinethatR2shouldbeapproximately700ohms.We’llusetheneareststandard5%value,680ohms. Aswe’llseelaterinthischapter,undersomeconditions,particularlyiftheinputtoneisatoneedgeofthe lockrange,thecomparatoroutputhassomefalsetransitions.R3/C2partiallyde-glitchthecomparatoroutput. Sincewe’vedesignedthePLLforaresponsetimeof5ms,we’lllikewisesetthetimeconstantofR3/C2for 5ms.Pickingaconvenientvalueof0.1µFforC2,wedetermineR3shouldbe20K.
AdjustingtheCircuit Afterconstruction,it’snecessarytoadjustRPtocentertheVCO.YoumayalsohavetochangeR1toobtain thedesignbandwidth.SincetheVCOisnotbroughtouttoapin,wemustuseanindirectmethodtoadjustRP.Whilemonitoringtheoutputofthetonedetectorcomparator(pin5)varytheinputfrequencyand notetheupperandlowerdropoutfrequenciesortheupperandlowerpull-infrequencies.(Thedrop-out frequencyismeasuredbystartingwithafrequencyinthepassbandandthenobservingwhentonedetector dropsout.Thepull-infrequencyismeasuredbystartingatafrequencyout-of-lockandthenadjustingthe frequencyuntilthetonedetectorshowslock.)
667
Chapter27 AdjustRPuntiltheupperorlowerfrequencies(eitherpull-inordrop-out)arecenteredon800Hz.Thedifferencebetweentheupperandlowerpull-infrequenciesshouldbeapproximately200Hz.Ifyoucan’tadjust RPtocentertheupperandlowerfrequenciesto800Hz,changeR0;reduceittoincreasethecenterfrequency orincreaseittodecreasethecenterfrequency. Ifthebandwidth(upperpull-infrequencyminusthelowerpull-infrequency)issignificantlylessthan200 Hz,thenyouwillneedtoadjustR1.Iwouldn’tadjustR1unlessthebandwidthwasmorethan50Hzwideror narrowerthanthe200Hztarget.Toincreasethebandwidth,reduceR1;todecreasethebandwidth,increase R1.Youmayseeinteractionbetweenbandwidthandcenterfrequencyadjustments,sokeepadjustingthe centerfrequencyandbandwidthdeterminingcomponentsuntilthecenterfrequencyandbandwidthmeet yourrequirements.
Programs Program27-0 We’llstartoutcautiously;collectingsomestatisticson Morsecodeassentonthehambandsandasreceivedbyour tonedecodercircuit.Figure27-10showshowtheXR-2211 tonedecoderconnectstothePICforPrograms27-1and272.Thestatisticswe’reconcernedwitharethedotanddash lengthsfortypicalamateuroperatorsentMorseandwe’ll usethesetodevelopanappropriatedecodingalgorithm.We can’t,ofcourse,useexactlythesameapproachwedidin Chapter26,wherewedistinguishunambiguouslybetween Figure27-10:Connectionsforprograms27-0,–1 dotsanddashesbywhetherthedotordashpaddleleveris and–2. pressed.Instead,wehavetomeasurethelengthofthereceivedcodeelementsanddecidewhicharedotsandwhicharedashes,basedsolelyupontheirrelativelengths. RecallfromChapter26therecommendedelementandspacinglengthsforperfectMorse: Element Dot Dash Inter-ElementSpace Inter-letterSpace Inter-WordSpace
RelativeLength 1 3 1 3 7
Whycollectthesestatistics,youmightask?Afterall,weknowthedot/dashratiois1:3andthespaceratios arealsowelldefined.Ifeveryonesentcomputer-generatedcode,withperfectelementlengthswecouldskip collectingstatisticsandproceeddirectlytocodingourprogram.However,hamssendMorsewithavariety oftechnologies,rangingfromup/downtelegraphkeysthatwouldhavebeenathomeinanCivilWarera telegrapher’sofficetocomputerprogramsthatgenerateperfectcode.Themajorityofhamslikelyusean electronickeyer,similarinconcepttotheonewedevelopedinChapter26,whichensuresconsistentdot/ dashratios,butevenso,theoperatorisresponsibleformanuallyinsertingletterandwordspaces.And,not alloperatorsareequallyproficientintheirabilitytooperatetheirchoseninstruments;otherwiseitwouldnot havebeennecessaryfortheamateurradiocommunitytocoinaspecialcodesignalQLF,or“nowtrysendingwithyourleftfoot”todescribethoseattemptingMorsewithunacceptableresults. Program27-0measurestonepulselengthsandoutputsthemeasurementsovertheserialinterfaceforpostcollectionanalysis.
668
AMorseCodeReader ;Program27-0 ;collectstatsontypicalMorsesending ;Constants ;---------;Setmaxandminwidthinmilliseconds MinWidth Con 15 ;lessisnoise MaxWidth Con 360 ;moreisinterference CPinIn Con C0 ;constantforinputpin ;Variables ;--------PWidth VPinIn
Var Var
Word PortC.Bit0
;widthinmilliseconds ;variableforinputpin
;Initialization ;--------------EnableHSerial SetHSerialH115200 HSerOut[“P27-0”,13] InputCPinIn PWidth=0 Main ;==== IfVPinIn=%0Then WhileVPinIn=%0 PWidth=PWidth+1 PauseuS790 WEND EndIf If(PWidth>=MinWidth)AND(PWidth<=MaxWidth)Then HSerOut[DecPWidth,13] EndIf PWidth=0 GoToMain End
Unlessweneedaspecialfeatureofaparticularpin,suchasB0’sinterrupt-on-changefeatureorwemusthave ourpinsinsequence,suchasfordatatransfertoorfromanLCD,ourchoiceofaninputpinis,toalarge extent,arbitrary.Here,however,wepickpinC0toconnecttotheXR-2211tonedecoderbecausetheC-seriesinputpinshaveCMOSlevelSchmitt-triggerinputsandthusoffermoreimmunitytonoiseorglitchesin thetonedecoder’soutputthantheTTL-levelB-seriesinputpins.Ifyoucan’trecallthedifferencebetweena CMOSlevelSchmitt-triggerinputpinandaTTL-levelinputpin,youmaywishtorereadChapter4. Asusual,wedefineconstantsandvariables,inthatorder. ;Constants ;---------;Setmaxandminwidthinmilliseconds MinWidth Con 15 ;lessisnoise MaxWidth Con 360 ;moreisinterference CPinIn Con C0 ;constantforinputpin
Ifyou’veevertunedaroundashortwaveband,particularlyinthesummer,you’venoticedstaticcrashes, clicksandpops.Thesenoiseburstsareusuallyquiteshort—afewmillisecondslong—butthetonedecoder canmomentarilylockontotheseburstsandreadafalsecharacter.Hence,we’lldiscardanytoneduration measuredlessthanMinWidth,whichI’vesetto15ms.Likewise,wedon’twantasteadysignaltobemeasured,sowe’lldiscarddurationsexceedingMaxWidth,whichI’vesetto360ms.I’vebasedbothMinWidth andMaxWidthonexpectedvaluesforreasonablecodespeeds.RecallfromChapter26thatadotlengthis givenby: 1200 WDOT = WPM 669
Chapter27 WhereWPMisthecodespeedinwordsperminuteandWDOTisthedotdurationinmilliseconds.Fora maximumexpectedcodespeedof60WPM,WDOTis20ms,soI’vesetMinWidthabitbelowthisvalue.If wesettheslowestspeedweareinterestedinmeasuringat10WPM,thedotlengthis120msandaproperly proportioneddashwillbe360ms.Hence,I’vesetMaxWidthat360ms. I’vealsodefinedtheconstantCPinInasaliasforC0. ;Variables ;--------PWidth Var VPinIn Var
Word PortC.Bit0
;widthinmilliseconds ;variableforinputpin
Program27-0onlyhastwovariables;onetoholdthemeasuredpulsewidth,PWidth,andonetocheckthe statusoftheinputpin,VPinIn.Mynamingconventionadded“C”forconstanttoPinIntoyieldtheconstantCPinInand“V”forvariabletoyieldthevariableVpinIn. TheobjectiveinProgram27-0istoreadthewidthofthetonepulse,toverifythatitiswithintheacceptable rangeandifsowriteitswidthtotheserialport. Main ;====
IfVPinIn=%0Then WhileVPinIn=%0 PWidth=PWidth+1 PauseuS790 WEND EndIf
WeuseaIf…ThentesttomonitorthestatusofthepinconnectedtotheXR-2211tonedetectoroutput.Ifthe inputpingoeslow,theXR-2211hasdetectedaninputtoneandwemeasurethedurationofthelowbytiminghowlongtheinputpinstayslow. WhenIdevelopedProgram27-0underMBasic5.2.1.1,IcouldnotuseitsPulsIntimingfunctionto measureMorsewidthbecauseitsmaximumreturnedvalue,65535µs,wasn’tlongenoughtomeasureslow Morse.(Version5.3.0.0remediesthatproblem,buttoshowanalternative,we’llkeepthetimingapproach Idevelopedtousewithversion5.2.1.1.)Howthentomeasureapulsevalueouttoseveralhundredmilliseconds?Wecouldwriteanassemblerinterruptroutinethatusesthe16F87x’sinternal16-bittimer1to generateatickeverymillisecondthatupdatesawordvariable“tickholder.”Thepulsewidthmeasurement loopwouldthenzerothetickholderuponentranceandreaditsvalueuponexit.We’lluseasimplertechnique;addinga“donothing”Pauseusstatementtothemeasurementloopsothateverypassthroughthe loopexecutesinexactly1ms.ByincrementingPWidtheverypassthroughtheWhile…Wendloop,PWidth automaticallymeasuresthedurationinmilliseconds.ThisisthesameapproachweusedinChapter26to addaspecificdelaywhengeneratingMorsecode,andthetechniquewediscussedthereforcalibratingthe PauseusstatementcanbeusedforProgram27-0. Ofcourse,there’snothingrequiringustomeasurethetonepulsewidthinmillisecondsaspartofdecode theincomingcharacters;wecoulddeletethePauseusstatementandmeasurethedurationin“loopcycles,” whereoneloopcycleishoweverlongittakestheWhile…Wendlooptocompleteonepass.Afterall,wedistinguishdotsfromdashesbytheirrelativelengths,notbysomeabsoluteduration.Ifadotis345loopcycles indurationandthenextelementmeasures1050loopcycles,it’smostlikelyadash,regardlessofhowlong aloopcycleisintermsofmillisecondsormicroseconds.However,inProgram27-3,wewilldisplaythe decodedMorsesignal’sestimatedcodespeedinWPM.Forthiswerequirethepulsewidthtobedetermined inmilliseconds.Hence,we’lluseProgram27-0asanopportunitytowriteanddebugamillisecondmeasuringroutine.
670
AMorseCodeReader If(PWidth>=MinWidth)AND(PWidth<=MaxWidth)Then HSerOut[DecPWidth,13] EndIf PWidth=0 GoToMain
Aftertheincomingcodeelementends,wethentestthemeasuredwithtoensureitisvalidand,ifvalid,write themeasureddurationtotheserialport. Let’stunearoundthehambands,findastationsendingMorseandadjustthereceiverdialuntilthedetection LEDpulsesinsynchronizationwiththeincomingaudio.YoumayfindthatnoisetriggerstheLEDequally wellwiththereceivedsignal.Ifso,youshouldreducetheaudioleveltotheXR-2211untilwithnoMorse codesignalpresent(butwithbackgroundnoise),theLEDremainsoffanddoesnotflash.Oursimplified circuitisquitesensitivetonoiseandaudiooverload,soit’simportantthatyoufollowthisstepinadjusting theinputsignallevel.Then,youshouldseeanoutputsimilartothefollowing: 118 309 22 15 31 61 196 62 206 68 60 137 169 176 40 64 156
Itappearsthatdotsarearound60-70msanddashesarearound150-200msbutweseequiteafewvalues farremovedfromtheseranges.Let’slookatsomesampledataIrecordedwithProgram27-0.Figure27-11 isasampleofgoodsoundingMorse;itwaspleasanttolistentowithgoodelementlengthandspacing. Thedatashowsadash/dotratioquiteclosetotheideal3:1value.Figure27-12isfromtheotherendofthe qualityspectrum;poorqualitysendingwithdashlengthsallovertheplace.Icouldcopyitbyear,butitwas fatiguingtolistento.Theoperator’sdotswerequiteconsistentinlength,buthisdashdurationvariedmore that2:1,withtheaveragedash/dotratiobeing4.3:1.Thisoperatorusedamechanicalsemi-automatickey (colloquiallyknownasa“bug”)withavibratingspringtoautomaticallycreatedotsbutwithmanuallysent dashes.Figure27-13showssimilardatafromfivestations,expressedintermsofaverageelementlength inordertoplacestationssendingatdifferentspeedsintoacomparableformat.Thisdata,althoughlimited, confirmswhatmanyyearsofhamradiooperationhadtaughtme;there’sahugevariationinqualityof Morsetransmission.Wethereforepreferanalgorithmthatrobustlydifferentiatesdotsfromdashesanddeals withvaryingspacelengths.Weshallsee,however,thatevenarelativelysimpleaveragingtechniqueworks reasonablywellwithawidevarietyofMorsereception. Whatwedesireisathresholdvalue;elementslongerthanthethresholdaredashesandshorterelementsare dots.Ofcourse,thethresholdmustbeadaptive;changingbetweenoperatorsandalsotrackingduringany singletransmissiontoadjustforchangedspeeds.Figure27-11and12showtheresultsoftwoofmanypossiblethresholdmethodologies: 671
Chapter27 Figure27-11:Element lengthdistribution;high qualityMorse.
Figure27-12:Element lengthdistribution;poor qualityMorse.
672
AMorseCodeReader Figure27-13:Normalized elementlengthdistribution.
• •
Averageallelementsandsetthethresholdattheaverage.Ifthenumberofdotsequalsthenumberof dashesandifthedash/dotratiois3:1,thisestablishesthethresholdexactlywheredesired,halfway betweenthedotanddashlengths. Categorizetheelementsas“long”and“short”andfindtheaverageofthelongelementsandtheaverage oftheshortelementsandsetthethresholdhalfwaybetweenthetwoaverages.
Program27-1 LookingatmoredatathanshowninFigures27-11and12,Ideterminedthatasimplearithmeticalaverageof theelementlengthsprovidesareasonablethresholdvalueandcanbeexecutedinMBasicsignificantlyfaster thancomputingindividualdot/dashmeans.Program27-1teststhisthresholdapproach. ;Program27-1 ;AverageThreshold ;Constants ;---------;Setmaxandminwidthinmilliseconds MinWidth Con 15 ;lessisnoise MaxWidth Con 360 ;moreisinterference TimeMult Con 3 ;timeoutmultiple CPinIn Con C0 ;constantforinputpin ArySize Con 32 ;averagearraysize DefaultWPM Con 20 ;startingWPM ;Variables ;--------PWidth VPinIn wArray i k WPM
Var Var Var Var Var Var
Byte PortC.Bit0 Word(ArySize) Byte Byte Byte
;widthinmilliseconds ;variableforinputpin ;holdswidths ;counter ;counterforwArray ;codespeedWPM
673
Chapter27 Threshold Var Sum Var ElLen Var ;Initialization ;-------------EnableHSerial SetHSerialH115200 HSerOut[“P27-1”,13] InputC0 PWidth=0
Word Word Byte
;dot/dashthresholdinms ;sumofdata ;elementlengthinms
Threshold=100 Fori=0to(ArySize-1) wArray(i)=Threshold Next k=0 Sum=Threshold*ArySize Main ;==== IfVPinIn=%0Then WhileVPinIn=%0 PWidth=PWidth+1 PauseuS790 WEND EndIf If(PWidth>=MinWidth)AND(PWidth<=MaxWidth)Then wArray(k)=PWidth GoSubUpDateThreshold GoSubUpDateWPM HSerOut[“Width:“,DecPWidth,9,”Thld:“,| DecThreshold,9,”WPM:“,DecWPM,13] EndIf PWidth=0 GoToMain ;RecalulatetheWPMandElLengthvalues UpDateWPM ;----------- ;Thresholdisavgofdot&dash32samples ;soitis=2dotlengths ElLen=Threshold/2 WPM=1200/ElLen Return ;updatethresholdbasedoncurrentvalueofdot/dashaverages UpDateThreshold ;------------- ;wArrayisacicularbufferandweusethe ;techniqueofChapter11tosimplifyaverages Sum=Sum+wArray(k) k=k+1 Ifk=ArySizeThen k=0 EndIf Threshold=Sum/ArySize Sum=Sum-wArray(k) HSerOut[“k:“,Deck,9,”Sum:“,DecSum,13] Return End
We’vedefinedseveralnewconstantsandvariablestoholdtheinformationweneedtocalculatethetone duration: ArySizeCon
32
;averagearraysize
wArray Var Threshold
Word(ArySize) ;holdsaveragewidths Var Word ;dot/dashthresholdinms
674
AMorseCodeReader Sum ElLen
Var Var
Word Byte
;sumofdata ;elementlengthinms
We’llcollecttonedurationmeasurementsina32-elementwordlengtharray,wArray.We’llthencompute themeanvalueofwArrayandusethatasthethreshold,holdingtheresultinthevariableThreshold.The variableSumholdsthecurrentsumofall32measuredvalues. Threshold=100 Fori=0to(ArySize-1) wArray(i)=Threshold Next k=0 Sum=Threshold*ArySize
WepreloadWarrayandSumwithdefaultvaluestosecurebetterresultswhenreceivingthefirst32elements. Main ;====
IfVPinIn=%0Then WhileVPinIn=%0 PWidth=PWidth+1 PauseuS790 WEND EndIf
Programs27-1sharesacommontimingstructurewithProgram27-0andnofurtherdiscussionisrequired. If(PWidth>=MinWidth)AND(PWidth<=MaxWidth)Then wArray(k)=PWidth GoSubUpDateThreshold GoSubUpDateWPM HSerOut[“Width:“,DecPWidth,9,”Thld:“,| DecThreshold,9,”WPM:“,DecWPM,13] EndIf PWidth=0 GoToMain
Ifthemeasuredtonedurationisavalidvalue,westoreitinwArray(k)andcallsubroutinesUpDateThresholdtocalculatethecurrentthresholdvariableThresholdandUpDateWPMtocomputethe correspondingcodespeedvariableWPM.Thesevaluesarethenwrittentotheserialport. ;updatethresholdbasedoncurrentvalueofdot/dashaverages UpDateThreshold ;------------- ;wArrayisacicularbufferandweusethe ;techniqueofChapter11tosimplifyaverages Sum=Sum+wArray(k) k=k+1 Ifk=ArySizeThen k=0 EndIf Threshold=Sum/ArySize Sum=Sum-wArray(k) HSerOut[“k:“,Deck,9,”Sum:“,DecSum,13] Return
InChapter11welearnedanefficientmethodofcomputingthearithmeticalaverage.Thebruteforcemethod ofcomputinganarithmeticalaverageofwArrayistosumall32valuesanddividethesumresultby32each timewetakeanewmeasurement.Thuseachcomputationrequires32additionsandonedivision.Using thetechniquedescribedinChapter11,westructurewArrayasacircularbuffer,inotherwords,itholdsthe last32valueswiththemostrecentvalueoverwritingtheoldestvalue.Wealsosavethesumofthereadings inthevariableSum.Tocomputethecurrentaverageofall32values,weupdatethesum,re-computethe averageandthensubtracttheoldestvaluefromthesum.Thenumberofrequiredadd/subtractoperationsis reducedfrom32additionstooneadditionandonesubtraction.Bothrequireonedivision.Ifthisbriefexplanationisn’tadequate,checkChapter11forathoroughanalysisofthealgorithm. 675
Chapter27 ;RecalulatetheWPMandElLengthvalues UpDateWPM ;----------- ;Thresholdisavgofdot&dash32samples ;soitis=2dotlengths ElLen=Threshold/2 WPM=1200/ElLen Return
Theremainingsubroutinecomputestheestimatedcodespeedinwordsperminute.ThiscomputationassumesthatThresholdiscomputedastwodotlengths,which,aswesawearlier,isitselfbaseduponthe assumptionthatthelast32elementscompriseequalnumbersofdotsanddashesandthatthedash/dot durationis3:1.Neitheroftheseassumptionsislikelytobecompletelyvalid,soweshouldusethecomputed codespeedasonlyanestimatedvalue. Here’sasampleofProgram27-1’soutput.Thisdatawastakenaftertheprogramhadbeenrunningforafew momentswithmyreceivertunedtoanacceptablequalityMorsesignal. Width:164 Thld:121 WPM:20 k:27 Sum:3869 Width:193 Thld:124 WPM:19 k:28 Sum:3832 Width:63Thld:122 WPM:19 k:29 Sum:3932 Width:200 Thld:126 WPM:19 k:30 Sum:3900 Width:68Thld:125 WPM:19 k:31 Sum:3949 Width:149 Thld:126 WPM:19 k:0 Sum:3937 Width:71Thld:125 WPM:19 k:1 Sum:3837 Width:71Thld:125 WPM:19 k:2 Sum:3722
Basedonthislimitedsample,itlookslikeourthresholdcalculationdoeswhatisrequired.Noneofthemeasurementsshorterthanthethresholdvalueseemtoberealdashesandnonethatarelongerthanthethreshold seemtoberealdots. Program27-2 Nowthatwehaveconfidenceinourthresholdalgorithm,let’smergeProgram27-1withtheMorsecode decodingelementsofProgram26-4.We’lloutputthedecodedMorsetotheserialportandusethesameconnectionsareforProgram27-1. ;Program27-2 ;DecodeMorseandsendtoserialport ;AssumesPLLanalog-to-digitaldecoder ;istiedtopinCpinIn ;Constants ;---------;Setmaxandminwidthinmilliseconds MinWidth Con 15 ;lessisnoise MaxWidth Con 500 ;moreisinterference TimeMult Con 3 ;timeoutmultiple CPinIn Con C0 ;constantforinputpin ArySize Con 32 ;averagearraysize Dot Dash Nil MorseLen
Con Con Con Con
-1 1 0 8
;forArrayMorse ;inarrayofsendelements ;isclassedasdot/dashornothing ;lenarrayholdingdots/dash/nil
676
AMorseCodeReader EndYes Con 0 ;wasacharactersent?Yes EndNo Con 1 ;no.Usedtoterminatespaces WordRatio Con 3 ;letterspaces=wordspace IdleTime Con 510 ;ussforidleloopexecution LSpace Con 850 ;letterspacemultipler ;LetterSpace=(Threshold*;LSpace)/IdleTime ;Decodeholdsthetreeformofthedecodedcharacter 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___” ;TreeWholdsthetreeweightings TreeW ByteTable$40,$20,$10,$8,$4,$2,$1 ;Variables ;--------PWidth VPinIn wArray i j k WPM Threshold Sum Morse IdleCount LetterSpace
Var Var Var Var Var Var Var Var Var Var Var Var
m EndLetter EndWord Temp TempStr WordSpace
Var Var Var Var Var Var
Word ;widthinmilliseconds PortC.Bit0 ;variableforinputpin Word(ArySize) ;holdswidths Byte ;counter Byte ;Counterforweight Byte ;counterforwArray Byte ;codespeedWPM Word ;dot/dashthresholdinms Word ;sumofdata SByte(MorseLen);holdselements Word ;counter--idleperiod Word ;passesthroughidle ;toequalaletterspace Byte ;counterforMorse(m) Byte ;isletterfinished? Byte ;iswordfinished? Byte ;valueofMorsechar Byte ;Character Byte ;numberofwordspaces
Initialization ;--------------- ;Changeasdesiredbutnottooslow EnableHSerial SetHSerialH115200 HSerOut[“P27-2”,13] InputCPinIn ;forPLLinput PWidth=0 ;pulsewidth
;Threshold=2dotlengthsforperfectcode Threshold=120 ;correspondsto20wpm ;Initializedvalue LetterSpace=(Threshold*LSpace)/IdleTime ;Holdsmeasuredlengthsofdot/dashpulses Fori=0to(ArySize-1) wArray(i)=Threshold Next ;holdsdot/dashdecisionedvalues Fori=0to(MorseLen-1) Morse(i)=Nil Next ;zeroloop/timercounters IdleCount=0 WordSpace=0 k=0
677
Chapter27 Sum=Threshold*ArySize m=0 ;OutputC1;useforidletimemeasurement ;uncommentifneedtocalibrateloop Main ;==== ;Waitforadot/dashoninputpin ;Ifitoccurs,measurethelength.Setloopfor ;1msandcountnumberoftimesthroughtheloop IfVPinIn=%0Then WhileVPinIn=%0 ;1msfor20MHzPIC PWidth=PWidth+1 ;Don’tmodifyunlesschange PauseuS790 ;thePauseuSconstant! WEND EndIf ;Checkforbadpulsewidths If(PWidth<=MaxWidth)AND(PWidth>MinWidth)Then wArray(k)=PWidth ;ClassifyasdotordashandsaveinPWidth ;SameasforProgramsinChapter26. IfPWidth>ThresholdThen Morse(m)=Dash Else Morse(m)=Dot EndIf m=m+1;readyfornextdot/dash Ifm=MorseLenThen m=0 EndIf GoSubUpDateThreshold ;updatethreshold ;Zerospacecounterssincewehavea ;validdot/dash IdleCount=0 WordSpace=0 EndLetter=EndYes ;maybeendofletter? EndIf PWidth=0 ;clearfornextpulse ;Howmanypassesthroughinidledowehave? ;LetterSpaceisbasedontimetoexecutethisloop. ;Ifidletime=Letterspacewehaveanendof ;letterandpossiblyanendofword IdleCount=IdleCount+1 If(IdleCount>=LetterSpace)Then GoSubSpacing EndIf ;Followingtomeasureidletimewith‘scopeonC1 ;Uncommentifneedtocalibratelooptime ;bsf PortC,1 ;NOP ;NOP ;NOP ;bcfPortC,1 GoToMain ;RecalulatetheWPMandElTimegthvalues UpDateWPM ;----------- ;Thresholdisavgofdot&dash32samples ;soitis=2dotlengths WPM=600/Threshold LetterSpace=(Threshold*LSpace)/IdleTime Return ;updatebasedoncurrentvalueofdot/dashaverages ;Thisassumes#dots~#dashes.Usuallytrue
678
AMorseCodeReader ;Calledeveryletterspace UpDateThreshold ;------------- ;wArrayisacicularbufferandweusethe ;techniqueofChapter11tosimplifyaverages Sum=Sum+wArray(k) k=k+1 Ifk=ArySizeThen k=0 ;wraparoundfork EndIf ;newaverage Threshold=Sum/ArySize ;mustsubtractoldestaveragefromsum,and ;oldestaverageisk+1. Sum=Sum-wArray(k) Return ;SubroutineSpacingiscalledwhenwehavealetterspace ;Spacingcheckstoseeifthisisaletterspaceora ;wordspace. Spacing ;------- IdleCount=0 ;resetwhenthistrips WordSpace=WordSpace+1;timesSpacingcalled ;weupdateatendoffullletter Return
GoSubUpDateWPM
;getnewWPMaswell
;IfSpacingiscalledenough,mustbeawordspace ;Ifitisawordspace,weoutputaspacechar ;Followingexecutedonlyifendofword ;--notendofletter IfWordSpace=WordRatioThen WordSpace=0 IfEndWord=EndYesThen ;UseEndWordtopreventmultiplespaces EndWord=EndNo;sentonespacenomore TempStr=““;haveaMorsecharacter HSerOut[““] EndIf EndIf ;Followingexecutedifendofletter ;andnotendofword ;TheconversionroutinefollowsprograminChapter26 IfEndLetter=EndYesThen Temp=128 ;binarytreemidvalue ;goup/downtreebasedondot/dash Forj=0to(MorseLen-1) Temp=Temp+Morse(j)*TreeW(j) Morse(j)=Nil ;clearfornextletter Next ;haveindex--getcorrespondingcharacter TempStr=DeCode(Temp) ;Senditout HSerOut[TempStr] ;Readyfornextdotordash m=0 ;Letterdone?WordDone? EndLetter=EndNo EndWord=EndYes EndIf
End
679
Chapter27 SinceagreatdealofthenutsandboltsinProgram27-2duplicatesProgram26-4,we’llconcentrateonthe differences.Let’slookatthemainprogramloop: Main ;==== IfVPinIn=%0Then WhileVPinIn=%0 ;takes1msfor20MHzPIC PWidth=PWidth+1;Don’tmodifyunlesschange PauseuS790 ;thePauseuSconstant! WEND EndIf
Themeasurementroutineisidenticalwithourearliercodeandneedsnofurtheranalysis.
;Checkforbadpulsewidths If(PWidth<=MaxWidth)AND(PWidth>MinWidth)Then wArray(k)=PWidth ;ClassifyasdotordashandsaveinPWidth ;SameasforProgramsinChapter26. IfPWidth>ThresholdThen Morse(m)=Dash Else Morse(m)=Dot EndIf
Todetermineifatonepulseisadotoradash,wecompareitwiththecurrentThreshold.Iflonger,it’sa dash;ifshorter,it’sadot.We’vedefinedtheconstantsDashandDotas1and–1,respectivelysowemay usethesamenumericalbinarytreeevaluationalgorithmusedinProgram26-4.(And,ofcourse,we’vealso definedtheconstantNilas0asrepresentingneitheradotnoradash.) Thisprogramstructureignorestheinter-elementspace.Immediatelyafterwehaveclassifiedanelementas adotoradash,themainprogramloopisreadytoclassifythenextreceivedelement.Wedonotattemptto measurethespacebetweenelementsanddetermineifthespaceisapproximatelyonedotduration.Ignoringinter-elementspacehelpsproperlydecodeill-sentMorseandsimplifiesourprogrammingtask.Itdoes, however,introduceapotentialproblemwithfalsecharacterscausedbyglitchesontheXR-2211outputpin, orbynoisebursts.
m=m+1;readyfornextdot/dash Ifm=MorseLenThen m=0 EndIf
Afterclassifyingthetonepulse,weupdatethearraycountermthatweusetoindexintothearrayMorse() thatholdsthenumericalDash,DotandNilvalues.
EndIf
GoSubUpDateThreshold ;updatethreshold ;Zerospacecounters--validdot/dash IdleCount=0 WordSpace=0 EndLetter=EndYes ;maybeletterend?
WerecalculateThresholdbasedonthemostrecentelementlengththroughasubroutinecalltoUpdateThreshold.WeuseIdleCountinthesamewayit’susedinProgram26-4;itmeasureshowmanytimes themainloopisexecutedwhennotoneinputisdetected.Accordingly,wezeroIdleCountwheneverwe haveavalidtoneinput.Likewise,WordSpaceworksthesamewayinProgram27-2asitdoesinProgram 26-4;itdetermineswhetherawordspacehasoccurredbymeasuringhowmanyinte-elementspaceshave occurred.WordSpaceaccordinglymustbesettozeroaftereachtoneinputmeasurement.EndLetteralso tracksitsProgram26-4functionality;itletsusemitonlyoneletterspaceregardlessofhowlongthemain loopremainsidle. PWidth=0 ;clearfornextpulse ;Howmanypassesthroughinidledowehave? ;LetterSpaceisbasedon
680
AMorseCodeReader ;timetoexecutethisloop.Ifidletime=Letterspace ;wehaveanendofletterandpossiblyanendofword IdleCount=IdleCount+1 If(IdleCount>=LetterSpace)Then GoSubSpacing EndIf
Totimethe“keyup”spaceintervals,weusethetechniquedevelopedinChapter26;wemeasurethetime ittakestoexecutethemainprogramloopandcomputehowmanytimestheprogramloopmustexecuteto equaloneinter-letterspace.ThisvalueisheldinthevariableLetterSpace.(We’llseehowLetterSpace iscalculatedwhenwelookatsubroutineUpDateWPM.)Whenthemainloophasidledwithouteitheradotor dashhavingbeenreceivedlongenoughforoneletterspacetopass,subroutineSpacingiscalled. ;Followingformeasuringidletimewith‘scopeonC1 ;Uncommentifneedtocalibratelooptime ;bsf PortC,1 ;NOP ;NOP ;NOP ;bcfPortC,1 GoToMain
AsinProgram26-4,wemeasurethetimeittakesforthemain programlooptoexecuteinidleoncetoobtainacalibration factorthatwethendefineastheconstantIdleTime.To makethismeasurement,weuncommentthefivelinesofcode shownabove,alongwiththelineinInitializationthat makesC1anoutputpin: ;OutputC1;useforidletimemeasurement ;uncommentifneedtocalibrateloop
WethenconnectanoscilloscopetoPinC1andmeasurethe timebetweenthebriefpositivepulses,asseeninFigure2714.Usingthecalibratedcursorfeatureofmyoscilloscope,I Figure27-14:Measuringtheidleexecutiontime determinedthattheidletimewas510µs.Hence,Iaddedthe formainprogramloop,program27-2. followingdeclarationtotheConstantssection: IdleTime
Con
510
;usforidleloopexecution
Ifyoudon’thaveanoscilloscope,youmayusetheexecutiontimingmonitordevelopedinChapter14. SubroutineUpDateThresholdisidenticalwiththeProgram27-1version,sowe’llnotdiscussitfurther. ;RecalulatetheWPMandElTimegthvalues UpDateWPM ;----------- ;Thresholdisavgofdot&dash32samples ;soitis=2dotlengths WPM=600/Threshold LetterSpace=(Threshold*LSpace)/IdleTime Return
SubroutineUpDateWPMiscalledafterThresholdisupdated.SinceThresholdisequal—giventhecaveats wementionedearlier—totwodotlengths,wecalculatethecorrespondingcodespeedbyWPM=600/ Threshold. Finally,wecalculateanewvalueforLetterSpace,basedonthenewThreshold.Whenwehavemade LetterSpacepassesthroughthemainloopwhileinidle,subroutineSpacingiscalled. ThevalueofThresholdrepresentstwodotlengths,measuredinmilliseconds.IdleTimeisthenumber ofmicrosecondsittakestoexecuteonepassthroughthemainprogramloopwhenidling.Ifwewishedto callsubroutineSpacingexactlyat3dotlengthsofidletime(notagoodidea,bytheway),wewouldset 681
Chapter27 LetterSpace=1.5*1000*Threshold/IdleTime.Thefactor1000convertsThresholdin millisecondstoThresholdinmicroseconds.
Asusual,we’llwishtoaddabitofasafetymarginandconsiderthataletterspaceoccursatabout1.7dot lengths.Thiscouldbedoneby:LetterSpace=(1.7/2)*1000*Threshold/IdleTime.Or,we cansimplifyitinto:
LetterSpace=(Threshold*LSpace)/IdleTime
WhereintheConstantssection,wedefinedLSpaceas850: LSpace
Con
850
Thevalue1.7isbasedonsubjectivefactorsandexperimentingwithdifferentvalues.Settingtheinter-letter timetotwodotlengthscausedasurprisinglylargeerrorrateonmanytransmissions.Likewise,valuesless than1.5causedtoomanycasesofnotproperlydistinguishingletterspacesfrominter-elementspaces. SubroutineSpacingisquitesimilar—butnotidentical—tosubroutineSpacinginProgram26-4.Let’sgo throughit,concentratingonthedifferences.First,wemustrememberthatSpacingiscalledafteranidle timeequalto1.7dotspaces,andthatSpacingiscalledthereafterevery1.7dotspacessolongasthemain programloopremainsidle,i.e.,theXR-2211doesnotdetectatoneinput. Spacing ;------- IdleCount=0 ;rest-calledwhenthistrips WordSpace=WordSpace+1;timesSpacingcalled ;weupdateatendoffullletter
GoSubUpDateWPM
;getnewWPMaswell
AswiththeProgram26-4versionofSpacing,wedeterminewhetheraletterspaceintervalhasoccurredby countinghowmanytimesSpacinghasbeencalled,usingthevariableWordSpace. IfWordSpace=WordRatioThen WordSpace=0 IfEndWord=EndYesThen ;UseEndWordtopreventmultiplespaces EndWord=EndNo;sentonespacenomore TempStr=““;haveaMorsecharacter HSerOut[““] EndIf
EndIf
IfSpacinghasbeencalledenoughtimesthatWordSpace=WordRatio,weknowanendofwordhas occurredandweshouldemitablankspace.We’vedefinedWordRatioas3intheConstantssection: WordRatio
Con
3
SinceweincrementWordSpacebeforemakingthecomparison,andsinceWordSpaceisresettozeroafter eachdotordash,wedeemawordspacetohaveoccurredafterSpacingiscalledthreetimes,correspondingto5.1dotspaces.(Wedon’thavethesamenonuniformprobleminProgram27-2seeninProgram26-4 resultingfromtheextradotspacethekeyerautomaticallyinsertsaftereachdotordash.)Thisvalueseemsto workwellinpractice. Inordertopreventwordspacesfrombeingendlesslyemittedwhilethemainprogramloopidles,weuse variableEndWordasasentineltodetectmultiplepasses.Afteraletterspaceissent,EndWordissetto EndNo.NofurtherletterspacecharacterswillbeemitteduntilEndWordisresettoEndYes,whichoccurs wheneitheradotoradashisreceived. ;Followingcodeexecutedonlyifendofletter ;andnotendofword ;TheconversionroutinefollowsprograminChapter26 IfEndLetter=EndYesThen
682
AMorseCodeReader EndIf Return
Temp=128 ;binarytreemidvalue ;goup/downtreebasedondot/dash Forj=0to(MorseLen-1) Temp=Temp+Morse(j)*TreeW(j) Morse(j)=Nil;clearfornextletter Next ;Havenumericalindex--getcorrespondingcharacter TempStr=DeCode(Temp) ;Senditout HSerOut[TempStr] ;Readyfornextdotordash m=0 ;Letterdone?WordDone? EndLetter=EndNo EndWord=EndYes
TheremainderofSpacingfollowscloselytheversionweexaminedinChapter26.Tounderstandouralgorithm,startwiththeMorsealphabet. 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’ssupposeforthemomentthatSpacinghasbeencalled,butinsufficientidletimehasoccurredto constituteawordspace.Hence,wehaveanend-of-characterspaceandthusarereadytoconvertthevalues inMorse()toacharacteranddisplayitontheLCD.Atthispoint,wehavethecharacter’sdot/dash/nil sequenceloadedintothearrayMorse,andwehavedeterminedthatavalidend-of-characterspacehasbeen received.
683
Chapter27 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,asshowninFigure 27-15weseeaninterestingrelationship.Figure27-15’s structureisknownasa“binarytree”incomputerscience terms.(Thetreeisupsidedown,withthestemintheair andthebranchesdownward.)Ateachnode(element), wemakeadecisionbaseduponthenextelement; goalongthedotbranchorthedashbranchuntil thenextelementhasanilvalue.Wehavethen decodedtheletter. Wemightimplementabinarytreethrougha seriesofIf…Thenstatements.Let’sseehowthat mightworktodecode“C.”
Figure27-15:Morsecodebinarytree.
IfMorse(0)=DashThen IfMorse(1)=DotThen IfMorse(2)=DashThen IfMorse(3)=DotThen IfMorse(4)=NilThen Character=“C” EndIf EndIf Endif EndIf EndIf
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. Westartbynotingthesimilarityofabinarytreetoabinarynumber.Ifwesaythestartingpoint(root)value is128;thateverylayerdownrepresentsonebinaryshifttotherightandthatadotrepresentssubtractionand adashrepresentsaddition,wecanmapeachMorsecharacterintoauniquenumberbetween0…255. Let’sseehowthisworksfor“C.”
+128
0 Dash 1 64 +64
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.Wethencanindexintoabytetablethathasthe letter“C”atits168thpositionandquicklyretrievethecorrectdecodedcharacter.
684
AMorseCodeReader ThisweightedbinarytreeconversionforA…Z,0…9andcommonpunctuationmarksandprosignsisasfollows. 1 64
2 32
FirstElementisaDot 3 4 5 6 7 16 8 4 2 1
Ch Wt
5
4
H
1 64
2 32
FirstElementisaDash 3 4 5 6 7 16 8 4 2 1 6
8 4
S
136 =
16 SN
V
D
144 148
22
X
24 3
160 C
32 F
2
184
T
192
50
7
60
E
176 Y
48 ?
168
K
40
U
152
N
28
I
L
200 ,
72
R
G
80 AR
W J
216
M
224
86
8
96
O
228 240
104
9
244
112
0
252
120 1
206 208
Q
84 .
196
Z
64
P
140
20 SK
A
132
B
12
Ch Wt
124
Ifthenextelementisadot,moveupwardonelevel;ifitisadash,movedownwardonelevel
685
Chapter27 Basedonthisapproach,calculatingthebinarytreevalueforMorse()issimple;wemultiplyeachelement valuebythatlevel’sweightandsumthetotal: IfEndLetter=EndYesThen ;haveendofletter Temp=128 Forj=0to(MorseLen-1) Temp=Temp+Morse(j)*TreeW(j) Morse(j)=Nil;clearfornext
Next
NotethatweearlierdefinedthelevelweightingsinthebytearrayTreeW: TreeW ByteTable$40,$20,$10,$8,$4,$2,$1
ThevaluesinTreeWarestatedinhex,where$40correspondstodecimal64,andsoforth.Youshouldalso noteourearlierchoiceof1,–1and0fordash,dotandnilvalueswasnotaccidental.
EndIf Return
;Havenumericalindex--nowgetcorrespondingcharacter TempStr=DeCode(Temp) ;Senditout HSerOut[TempStr] ;Readyfornextdotordash m=0 ;Letterdone?WordDone? EndLetter=EndNo EndWord=EndYes
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___”
Theonlyremainingstepistosendthedecodedcharacteroutovertheserialport,whichweaccomplishwith theHSerOut[TempStr]statement.Towrapup,wesetthesentinelvariablesEndLetterandEndWord toreflectthefactthatwe’vejustcompletedaword.Likewise,were-initializembysettingitto0sothatit’s readyforthestartofthenextletter. HowdoesitworkwithtypicalMorse?Prettywell,thankyou.Here’sasnippetofsomeoff-the-airdecoding: KZ4VMBDEKO1COKATVIFGILESIHAVENTBEENONTENMETERSINALONPTIME HOWHASTHATBANDBEENDOINGLATELY,DOYOUKNOW?BK
Theextractstartswithanexchangeofcallsigns(stationKZ4VMZthisisstationKO1C)andendswitha “BK”whichmeans“I’mturningthetransmissionbacktoyouforaquickresponsetomyquestion.”The decodingisn’tperfect,butit’squiteacceptable,allthingsbeingconsidered.
Program27-3 Let’snowtakethestructureofProgram27-2andaddanLCDdisplay.Figure27-16showshowweaddthe LCDtoourearliercircuit.Inordertosavespace,wehaveomittedlistingProgram27-3.Acopyisavailable intheaccompanyingCD-ROM. Program27-3largelyduplicatesProgram27-2,withtheaddedcoderelatingtotheLCDdisplayfunctions. We’llaccordinglystudyonlythenewmaterial. Figure27-17showsatypicaldisplayfromProgram27-3.WeusethesameDisplayTechmodel204A,20x4 LCDdiscussedinChapter26,andadisplayarrangementsimilartoProgram26-4.Thetoplinedisplays
686
AMorseCodeReader
Figure27-16:ConfigurationforProgram27-3.
Figure27-17:Program27-3display.
thereceivedtext,whichisaddedleft-to-rightuntilthe20thcharacterisreceived,atwhichpointitrevertsto scrollingmode.Thebottomlineshowstheestimatedcodespeedinwordsperminute. We’veaddedseveralconstantsandvariablesrelatedtothedisplay: RegSel Clk BarrelSize
Con Con Con
B5 B4 20
;LCDcontrol ;LCDcontrol ;lengthofbarrelarrayfordisplay
;IndexintoLCDllinesfora4x20display LineOffByteTable$0,$0,$40,$14,$54 LCDNib Var PortB.Nib0 ;LCDdatatransferport LineNo Var Byte ;LCDLinenumber ;(assumes20x4display) BarrelAry Var Byte(BarrelSize) ;forLCD Mindex Var Byte ;forbarrelcounter
RegSel,ClkandLCDNibdefinethepinsusedtocommunicatewiththeLCD,whilethebytetableLineOff providesthestartingmemoryaddressesforlines1through4.DecodedMorsecharactersareheldinthebyte arrayBarrelAry().Ineachcase,weusedidenticalconstantandvariableidentifiersaswedidinProgram 26-4.
Let’slookatfragmentsofthesubroutineSpacingtoseetheLCDdisplaychanges:
IfWordSpace=WordRatioThen WordSpace=0 IfEndWord=EndYesThen ;UseEndWordtopreventmultiplespaces EndWord=EndNo ;sentonespace- TempStr=““ ;haveMorsecharacter HSerOut[““] GoSubShowChar
TheonlyadditiontotheabovecodesegmentisthesubroutinecallGoSubShowChar.
IfEndLetter=EndYesThen Temp=128 ;binarytreemidvalue Forj=0to(MorseLen-1) ;goup/downtree Temp=Temp+Morse(j)*TreeW(j) Morse(j)=Nil;clrnextletter
687
Chapter27
Next ;nowgetcorrespondingcharacter TempStr=DeCode(Temp) ;Senditout HSerOut[StrTempStr\1] GoSubShowChar ;Readyfornextdotordash
Likewise,wehaveaddedGoSubShowChartothemaindecodingfunctioninsubroutineSpacing.Note thatwehaveretainedtheserialoutputfunctionalityinProgram27-3. Let’slookatsubroutineShowChar.Whenitiscalled,thecurrentcharactertobedisplayedisheldinthe bytevariableTempStr. ;PutsentcharontoLCD ShowChar ;-------- ;Holdthedecodedcharactersinalength20array ;InsertnextcharacteratMindexposition BarrelAry(Mindex)=TempStr LineNo=1 ;displayonline1
WeinsertthecharactertobedisplayedinthenextopenpositioninarrayBarrelAry.ThevariableMIndex holdsthenextopenpositionindex.WealsosetLineNo=1toprovidethecorrectoffsetwhenweindex intoLineOff. ;Codetakesabout7.5ms ;PositionLCDcursor&writethecharacterarray LCDWriteRegSel\Clk,LCDNib,[ScrRAM+LineOff(LineNo),| StrBarrelAry\BarrelSize]
Wewriteall20charactersinBarrelAryatoncetothetoplineoftheLCD,unlikeinProgram26-4where wewritethelettersoneatatime.ItturnsoutthatProgram27-3strugglestokeeptheLCDupdatedwhenthe incomingcodespeedisfasterthanabout30WPMorso.Writingall20charactersofBarrelAryatonce savesseveralmillisecondsandimprovestheLCDupdateperformance. ;Westartatleftsideofscreen,writecharstoright. ;Whenreachlastposition,addcharsatright ;andshiftallpriorcharsonepositiontotheleft. ;HenceweonlyincreaseMindexifitislessthan19. ;Onceithits19wekeepitthere. IfMIndex<(BarrelSize-1)Then MIndex=MIndex+1 EndIf
We’veinitializedMindexto0inProgram27-3’sInitializationsectionandfilledBarrelArywith thespacecharacter.AccordinglyweincrementMindexuntilitreaches19.(Asourusualpractice,we’ve definedthelengthofBarrelAryintermsofaconstantBarrelSize,whichissetto20.Hence,thelast validarrayindexisBarrelSize-1.)WhenMindex=BarrelSize-1,wehavefilledall20positionsofthe Line1withinformationandwethenaddnewcharactersattherighthandendshifttheoldercharactersleft byoneplacetoaccommodatethenewletter.HencetheabovecodeincrementsMindexonlyuntilitreaches 19,atwhichpointitfreezesat19. ;Shiftallchars1positiontothelefttomakeroom ;fornewonesthatcomeinattheend. ;Followingcodetakes8ms IfMIndex>=(BarrelSize-1)Then Forkk=0to(BarrelSize-2) BarrelAry(kk)=BarrelAry(kk+1) Next EndIf
Theabovecodemoveseverycharacteronepositiontotheleft,overwritingBarrelAry(0). ;LineNo=4 ;LCDWriteRegSel\Clk,LCDNib,[ScrRAM+LineOFf(LineNo)] Return
688
AMorseCodeReader Finally,wepositionthecursorbacktothestartofline4,readyforanupdatedcodespeeddisplay. We’vealsoaddedasubroutinecalltoUpDateStatusattheendofsubroutineSpacing:
GoSubUpDateWPM GoSubUpDateStatus
SubroutineUpDateStatusdisplaysthenewlycalculatedcodespeedatline4oftheLCD. ;Updatesthestatusline UpDateStatus ;---------- LineNo=4 LCDWriteRegSel\Clk,LCDNib,[ScrRAM+LineOFf(LineNo)] LCDWriteRegSel\Clk,LCDNib,[DECWPM\2,”WPM“] Return
SincetheremainderofProgram27-3duplicatesProgram27-2,nofurtheranalysisisnecessary.
IdeasforChangestoProgramsandCircuits •
• •
•
Inadditiontodisplayingthecurrentestimatedcodespeed,itwouldbeinterestingtodisplaythe dash/dotratioasameasureofthequalityofcodebeingsent.Howmightthisbedone?Sincewehave distinguishedbetweendotsanddashesinourmainloop,wecouldestablishtwonewwordarrays; sayDotAryandDashAry,eachoflength16.EachdotordashlengthwouldbestoredinDotAryorDashAryinadditiontoWArray,andthearithmeticalaverageofbotharrays(sayDotAvgand DashAvg)calculatedusingthesamerunningsumtechniqueemployedtodetermineThreshold.Every timethespeeddisplayisupdated,computethedash/dotratioasDashAvg/DotAvg.Ofcourse,itwill eitherbenecessarytoperformthiscomputationinfloatingpoint,oraddkeepitanintegercalculation, butmultiplyDashAvgby10toobtainonedecimalpointofaccuracy,i.e.,(DashAvg*10)/DotAvg.Beforethevalueisdisplayed,adecimalpointcanbeaddedatanappropriatepoint. Howmightthedot/dashdecisionthresholdalgorithmbeimprovedupon?Isthereaalgorithmthatwill accuratelycomputetheseparatearithmeticalaverageofeachpartofabi-modaldataset? Ioriginallyplannedtousethetopthreelinesofthe20x4displayforreceivedcode,witha60-characterscrollingdisplay.However,thetimerequiredtoupdatethreelinesdidn’tpermitaccuratedecoding highspeedMorse.Howmightweexpandthememoryandpreservescrolling?Supposeweupdatethe displayonlyatwordbreaks,whereadditionaltimeisavailablebeforethenextcodeelementisreceived. Thisproducesasomewhatjerkydisplay,ofcourse.Woulditmakesensetoimplementbothasmooth scrolling60-characterdisplay,switchingtoaword-baseddisplaywhenthereceivedcodespeedexceeds acertainvalue?Or,shouldcertaintimesensitiveroutinesberecodedinmixedassemblerandMBasic? Toreducetheeffectoftonedecoderoutputglitches,ourcircuitaddsanRCfilter,comprisedofR3and C2.Wouldanactivelow-passfilter,implementedaroundanMCP601op-ampyieldabetterresult? Wouldavariablecut-offlow-passfilteroffermoreimprovement,wherethecutofffrequencycould beadjustedbythePIC,baseduponthespeedofthereceivedsignal?Cantheprogrammablelow-pass filterdiscussedinChapter21beusedforthispurpose?Shouldanyofthefiltercomponentvaluesinthe XR-2211beadjustedforbetterperformanceatlowtomoderatecodespeeds?Ifso,howmightthesebe placedunderPICcontrol?
References [27-1]
EXARCorporation,XR-2211FSKDemodulator/ToneDecoder,rev.3.01(June1997).Availablefor downloadingathttp://www.exar.com(requiresfreeregistrationtoaccessdatasheets.) [27-2] AmericanRadioRelayLeague,TheARRLHandbookforRadioCommunications,81stEd.,Newington, CT.(2004)Nowinits81stedition,theARRLhandbookisthestartingpointreferenceforallthings amateurradio.
689
Chapter27 [27-3]
Osterman,Fred,ShortwaveReceiversPast&PresentCommunicationsReceivers1942-1997,3rded., UniversalRadioResearch,ColumbusOH(April1998).Thiscompendiumcoversalmosteverymodel shortwavereceivermanufacturedbetween1942and1997,andisavaluablereferenceforanewentrant toshortwaveradiothatwishestopurchaseaneworusedreceiver. [27-4] Helms,HarryL.,ShortwaveListeningGuidebook:TheCompleteGuidetoHearingtheWorld,2nded., UniversalRadioResearch,ColumbusOH,(August1993).Goodintroductiontooverallshortwave listening,althoughabitdated.
690
28
CHAPTER
WeatherStation andDataLogger Nowthatwe’velearnedhowtoreadanalogvoltages,tostoredatainanexternalEEPROM,toreaddigital temperaturesensorsandtowriteaninteractiveserialprogram,let’sassemblethesedisparateconceptsintoa dataloggingmini-weatherstation. We’llmeasuretemperature,relativehumidityandbarometricpressureandsavethedatatoexternalEEPROMforlaterextraction.Inordertokeeptheprogramtomanageablelength,we’llnotimplementthefull interactiveserialfunctions,butwhatyou’velearnedinChapter9willletyouaddit,shouldyousodesire. And,ofcourse,youmightdecidetoaddanLCDdisplayandadditionaltemperaturesensorsandhaveaselfcontainedindoor/outdoorweatherstation.
SensorSelection We’velimitedourweatherstationsensorsuitetothethreecommonestelements:relativehumidity,barometricpressureandtemperature.Foreachelement,wehaveawideselectionofsensortypes,buttokeepthings simple,we’lllimitoursensorselectiontointegratedmodules.We’llfirstreviewourchoiceofsensors,next seehowtheyconnecttothePICandfinallywritethecodetomakeitwork.
Humidity Aswelearnedinintroductoryscienceclasses,airisamixtureofgasesincluding,mostimportantlyoxygen andnitrogen,butalsowatervapor.Relativehumidityisdefinedastheratioofactualvaporpressureofwater tothesaturationvaporpressure,i.e.,themaximumamountofwatervaportheaircanholdbeforeitprecipitatesoutasliquidwaterdropletsormist.Relativehumidityiscustomarilyexpressedasapercentage,from 0to100%.Sincethesaturationcarryingcapacityofairisproportionaltotemperature,thesameabsolute quantityofwatervaporresultsindifferingrelativehumidityasthetemperaturechanges. Almostallinexpensiverelativehumiditysensorsrelyuponabsorptionofwaterbyamaterialthatchanges propertiesinresponsetotheabsorption.Afewsensorsareconstructedfrommaterialthatchangesresistance whenexposedtowatervapor,butthemostpopularrelativehumiditysensortodayreliesuponchangesindielectricconstant.Whenthecorrectmaterialisbetweenthetwoconductingplates,theresultisasensorwith acapacitanceproportionaltorelativehumidity.Bymeasuringthesensor’scapacitance,wemaydetermine therelativehumiditywithsurprisinglygoodaccuracy,typicallywithin±2%. Humirel’sHS-1100sensor,forexample,hasanominalcapacitanceof180pFat55%relativehumidity,and variesapproximately0.34pFpereach1%changeinrelativehumidity.(Thevariationisnotquitelinear,and Humirelprovidesafour-termpolynomialequationtofitcapacitancetorelativehumidity.)It’spossibleto measurecapacitancewithaPICbyseveraltechniques,suchasmeasuringthechargingtimeofanRCnetworkwithaknownresistance;orbymeasuringthefrequencyofanoscillatorwherethesensor’scapacitance isoneofthefrequencydeterminingelements.Fromthemeasuredcapacitancewemaycalculatetherelative humidityaftergoingthroughafewmathematicalmanipulations. 691
Chapter28 Tosimplifyourproject,however,we’lluseapre-builtrelativehumiditymodulefromHumirel,theHM1500.ThismodulecombinesacapacitiverelativehumiditysensorwithothercircuitrytoyieldaDCvoltage outputproportionaltorelativehumidity.Withoutcorrection,ourhumidityreadingwillbewithin±3%over therange30%…80%andwithin±5%overthefulloperatingrangeof10%…95%relativehumidity.Ifincreasedaccuracyisdesired,Humirelprovidesanequationtocorrectfornonlinearityandtemperature.We’ll keepthingssimple,andusetheuncorrectedlinearequation: Vout = 25.68 RH + 1079
VoutistheoutputvoltageinmillivoltsfromtheHM-1500
RHistherelativehumidityinpercent
SincewewishtodetermineRH,knowingVout,wesolveforRHand(restatinginvolts,notmillivolts)find: V −1.087 RH = out 0.02568 TheHM-1500’soutputvoltagerangesfrom1.3Vat10%RHto3.55Vat95%RH. TheHM-1500isabitexpensiveat$30eachinsinglelots,comparedwiththebareHS-1101sensorat$12.50 sothisisacasewherewepayforconvenience.AnalternativetotheHM-1500wouldbeoneofHoneywell’s HIH-3610seriesintegratedsensormodules,whichareslightlylessexpensiveat$22eachinsinglelots.The HIH-3610alsohasaDCvoltageoutputproportionaltorelativehumidityandshouldbesubstitutableforthe HM-1500withonlyaminorchangetothevoltage-to-relativehumidityequation. We’llreadtheHM-1500’soutputwitha16F87x’sA/Dconverter.Aquickback-of-theenvelopeerrorbudget showsthatthe16F87x’s10-bitA/Dresolutionismorethanadequateforthistask;thesensoraccuracyis ±2%,and,aswelearnedinChapter11,agoodreferencevoltageyieldsanexpectederrorof±8mVorso overtherange0…4.096V.Thesensoroutputrangeisapproximately2.2V,soweestimatethemeasurement erroroverthesensoroutputrangeis8mV/2.2V,orapproximately0.4%.Thisisaboutfivetimesbetterthan thesensorerror,sowe’llconsideritacceptable.
BarometricPressure Barometricpressureisthepressureexertedbytheatmosphereabovethesensor.Themeasuredpressureisa functionofboththeweatherconditionsandtheelevationofthesensorabove(orbelow)sealevel.Forhistoricalreasons,barometricpressurehaslongbeenexpressedininchesofmercury,astheoriginalbarometers measuredairpressureagainstacolumnofmercury.Atsealevel,thestandardbarometricpressureis29.92 inches.Themostcommonlyusedmetricunitofairpressureisthehectopascal(hPa),butitsoldername,the millibar,isstillinwidespreaduse.We’llusethetermmillibar.(Thepreferredmetrictermforpressuremeasurementisthekilopascal,orKPa,as“hecto”(×100)multipliersarenonstandard.)Therelationshipamong inchesofmercury,millibars,kilopascalsandpoundspersquareinchis: PSI KPa InchesHg mbars
PSI 1 0.1450 0.4912 0.0145
KPa 6.8948 1 3.3864 0.1000
InchesHg 2.0360 0.2953 1 0.0295
mbars 68.9476 10.000 33.8639 1
Toconvert,forexample,30.00inchesHgtombar,multiplyby33.8639,yielding1015.9mbar.(Ifwewere concernedwithhighprecisionmeasurements,wewouldlearnthatmanometer-typeunits,suchasinchesHg, orinchesofwaterarenotwelldefined;forexample,theydependonthedensityofthemercury,thetemperature,thelocalgravity,etc.Butatourlevelofprecision,don’tworry.) 692
WeatherStationandDataLogger Theautomotiveindustryisthelargestconsumerofpressuresensors,usedinelectronicenginecontrol, amongotherthings,andwe’lltakeadvantageofthecostbenefitsoftheassociatedvolumeproduction.FreescaleSemiconductor,Inc.,arecentspin-offofMotorolasensorbusiness,isaleadingproducerofpressure sensors,sowe’lllookattheirproductsindetail.Freescale’spressuresensorsusepiezoelectrictechnology; athinflexiblesilicondiaphragmisionimplantedwithamaterialthatchangesresistancewhenpressureis applied,thusformingastraingauge.Whencurrentispassedthroughthestraingauge,avoltageproportional todiaphragmdeflection(andhencethepressuredifferentialbetweenthetwosidesofthediaphragm)results. Ifonesideofthediaphragmisinavacuum,thedeflectionisproportionaltotheabsolutepressureonthe exposedside. Asmightbeexpected,therawoutputofthestraingaugerequirescalibrationandsignalconditioningto compensatefortemperatureeffectsandtoamplifytherelativelysmallvoltageversuspressurechange. Fortunately,Freescaleoffersmanypressuresensorswithintegratedsignalconditioningandcalibration.The particularsensorwe’lluseisaMPX6115A6U,whichcostsabout$17.50insinglelots.Thisdeviceisan 8-pinsurfacemount,smalloutlinepackage,butcaneasilybemountedtoaSurfboard61033-connection surfacemountadapter,asonlypins2,3and4oftheMPX6115A6Uareused.Thesmalloutlinepackagepin spacingis0.1"soit’squitemanageablewithoutspecialsurfacemounttoolsorprocedures.TheSurfboard 6103adapterplugsdirectlyintoastandard0.1”breadboard,suchasBasicMicro’s2840developmentboard. TheMPX6115A6Uoperatesoverarangeof15kPato115kPa,or150mbarto1150mbar.Freescalestates therelationshipbetweenoutputvoltageandpressureas: Vout = VS ( 0.009 P − 0.095) ± Error
Voutistheoutputinvolts
VSisthesourcesupplyvoltageinvolts
PisthepressureinkPa
SolvingforPinmillibars,andignoringtheerrorcomponentfornow,wefind: Pmbar =
Vout + 0.095VS 0.090VS
Overthecalibratedrangeof150mbarto1150mbar,thevoltageoutput,assumingVSis5.000V,rangesfrom 4.700V(1150mbar)to0.200V(150mbar).Thequestionthenbecomes“overwhatrangemightweexpect normalbarometricpressuretovary?” Itappearsthatthelowestbarometricpressureeverrecorded(inatyphoon)was25.68inchesHg(869.63 mbar),andthehighestpressure(sealevelequivalent)was32.01inchesHg(1083.8mbar),recordedinSiberia,correctedforastationelevationof263meters. Beforegoingfurther,wemusttakeabriefdetour.Byconvention,barometricpressureisadjustedor“reduced”tosealevelequivalent,sodatamaybecomparedwithoutknowledgeofthestationelevationabove meansealevel.However,we’llbemeasuringabsolutepressure,whichincludeselevationeffects.TheabsolutepressureinDenver,Colorado,atanelevationofapproximately5300feetAMSL,willbelowerthanin thebasementworkshopinmyhouseinsuburbanWashingtonDCwithanelevationof320feetAMSL.The barometricpressureadjustmentfactorforelevationcanbedeterminedtherelationshipbetweenelevationand airpressurechange,whichisapproximately:
P Z = 62900 log10 0 P
693
Chapter28 Where:
ZistheelevationinfeetAMSL P0isthesealevelpressure PisthepressureatelevationZ
SinceweknowZandP0wesolveforP: P0 P= Z 62900 10 Todevelopanelevationcorrection,we’llusethestandardatmospheresealevelpressure,29.92inchesHg. WethencalculatePforthealtitudeandsubtractfrom29.92inchesHgtoobtaintheelevationcorrection. (Thisisasimplifiedcorrectionmethodology,butisacceptableforourpurposes.)I’vetabulatedasampleof elevationcorrectionsbelow. Elevation(feetAMSL)
inHgoffset
0
0.00
100
0.11
200
0.22
320
0.35
500
0.54
1000
1.08
2000
2.11
5000
5.00
5300
5.28
10000
9.17
Theelevationcorrectionisaddedtotheabsolutepressure.Forexample,ifmyMPX6115A6Uhasanoutput voltageof4.025Vandthepowersupplyvoltageis5.000V,what’sthesealevelcorrectedbarometricpressure? V + 0.095VS 1. Calculatepressureinmbarusingequation Pmbar = out .Theresultis1000.0mbar. 0.090VS 2. Calculatethepressureininchesofmercurybymultiplyingmbarby0.02953.Theresultis29.53inchesHg. 3. Addtheelevationcorrection.Mygroundelevationis320feet,sothecorrectionis0.35inchesHg, resultinginacorrectedvalueof29.53+0.35,or29.87inchesHg. Withthisunderstanding,wecannowestimatethevoltageoutputrangeofourpressuresensor.Basedonthe weatherrecordsmentionedearlier,themaximumabsolutepressureexpectedisveryunlikelytoexceed32 inchesHg.(Weatherrecordsarekeptbasedonelevation-correctedreadings,sowecan’tbe100%sureof thisstatement.)Theminimumabsolutepressureisdependentupontheobservingaltitude.We’llarbitrarily setthisat5000feet,andassumethecorrectedpressureis26inchesHg,correspondingtoanabsolutepressureof21inchesHg.Convertingthesevaluestombarandcalculatingtheexpectedsensoroutput,wefind themaximumexpectedvoltageis4.401Vandtheminimumexpectedvoltageis2.725V,arangeof1.649V frommaximumtominimum. Let’sseehowthesevaluesfitwithour10-bitA/Dconverter.First,wenoticethattheprecision4.096VreferenceusedinChapter11’sdesignnolongerworks,asweneedtomeasureupto4.401V.(Assumingwedon’t scaletheMPX6115A’soutput,ofcourse.)Let’sassume,forouranalysis,thatwewillusea4.6Vreference. And,let’sassumeforsimplicityofdesignwesettheA/D’sVref-toground.(Wecouldimproveresolution about2:1ifwesetVref-to,say2.5V,butatthecostofadditionalcircuitry.)Eachofthe1024voltagestepsis 694
WeatherStationandDataLogger thus4.5mVandthe1.649Voutputrangeencodesinto367steps.Sincethisvoltagerangecorrespondsto 11inchesHg,eachA/Dstepis0.03inchesHg.TheA/Derror,includingerrorsinthevoltagereferenceand analogcircuitrytoscalethevoltagereferenceto4.6V,correspondstoabout0.06inchesHg. Howdoesthiserrorbudgetrelatetotheoverallsensoraccuracy?FreescaleratesitsMPX6115Asensoras ±1.5%ofVFSSoverthefullpressureandtemperaturerange.VFSSisthefull-scale(maximumratedpressure) voltageoutput,nominally4.75V,sotheerrorvoltageis±71.25mV.Theerrorisnot“1.5%ofthepressure reading.”Rather,everyvoltagereadingissubjecttoanerrorof±71.25mV.Iftheactualabsolutepressure is32inchesHg,correspondingtoanominal4.401V,theactualvoltageoutputcouldbeaslowas4.3298V (correspondingto31.53inchesHg)orashighas4.4723V(32.46inchesHg).Thisconstanterrorvoltage correspondstoanerrorof±0.47inchesHg,regardlessofthepressure.Consideringtheinherentsensorerror, ourA/Derrorbudgetof±0.06inchesHglooksacceptable.
Temperature WeusedMaxim’sDS18B20one-wiretemperaturesensorsinChapter12,butwe’llreconsiderthatdecision forthischapter.Sinceboththehumidityandbarometricpressuresensorsareanalog,wecouldstaywithan “allanalog”sensorsuiteanduseananalogtemperaturesensor,suchasNationalSemiconductor’sLM34C, withanoutputof10.0mV/°F.WithanA/Dresolutionofabout4.5mV/step,wecouldreadtemperaturewith aresolutionof0.45°F/0.25°C.However,additionalcircuitryisrequiredtosensetemperaturesbelow32°F. Instead,we’lluseMaxim’sI2C-protocolDS1624temperaturesensor/EEPROM.TheDS1624combinesa temperaturesensorwitharesolutionof0.03125°Cwith256bytesofserialEEPROM.(No,that’snot256 Kbytesofmemory;it’s256bytes.)Wewon’tusetheEEPROM. WeexploredI2CcommunicationswithexternalEEPROMserialmemorychipsinChapter18,sowe’llconcentrateonthedifferencesbetweentheDS1624andthe24-seriesmemorychips. First,wenotethepinconnectionsdiffersignificantlyfromthoseofgeneric24-seriesdevices: PinName
DS16248-pinDIP PinNumber
SDA
1
SCL NC VSS A2 A1 A0 VDD
2 3 4 5 6 7 8
FunctionandComments SerialData.Thisisanopendrainpinandmusthaveapull-upresistor.10Kisa suitablevalueforStandardSpeeddatatransfer. SerialClock. Noconnection.TheDS1624doesnothaveaWriteProtectpin. Ground. ChipaddressbitA2. ChipaddressbitA1. ChipaddressbitA0. Pluspowersupply;+5Vinourbreadboarddesigns.
TheDS1624doesnothaveawriteprotectpin. Let’slookataDS1624controlbyteasusedwithMBasic’sI2CoutandI2Cinprocedures.(Ifyoudon’t recallthenuancesofMBasic’sI2CoutandI2Cinprocedures,now’sagoodtimetoreviewChapter18.) It’scomprisedofthreeelements:
Bit7 1
DeviceFamilyCode Bit6 Bit5 0 0
DS1624ControlByte ChipAddressingInformation Bit4 Bit3 Bit2 Bit1 1 A2 A1 A0
695
8/16Bit Bit0 0
Chapter28 Recallthatthefamilycodefor24-seriesEEPROMsis$Aor%1010;theDS1624’sfamilycodeis$9or %1001.TheDS1624usesallthreechipaddressbitsforchipaddressing;therearenoblockbitsorunusedbits. Thecontrolbyte’sbit0determineswhethertheEEPROMaddressinformationsentimmediatelyfollowing thecontrolbyteisasingle8-bitbyte(256possibleaddresses)ora16-bitword(65536possibleaddresses). Ifbit0is0,theaddressissentasan8-bitbyte;ifbit0is1,theaddressissentasa16-bitword.TheDS1624 requiresan8-bitvaluetoimmediatelyfollowthecontrolbyte,sowemustsetBit0to%0. Aswith24-seriesEEPROMdevices,thecontrolbytedefinitionintheDS1624’sdatasheetreferstobit0as the“read/write”orR/Wbit,andsaysthatthatitdeterminesthedirectionofdatatransfer;if0,themaster sendsandif1,theslavesends.However,MBasic,forreasonsofcompatibilitywithotherversionsofPIC BASIC,automaticallyinsertsthecorrectR/Wbitandinsteadusesbit0ofthecontrolbyteforaddresslength information.It’seasytogetconfused,soattentiontodetailiscritical. PerhapsthemostconfusingdifferencebetweentheDS1624and24-seriesEEPROMisthatwhensending datafromthemasterPICtotheslaveI2Cdevice,aDS1624requiresacommandbytethatimmediatelyfollowsthecontrolbyteandprecedesanydatabyte: Device 24-SeriesEEPROM DS1624
1stByte ControlByte ControlByte
2ndByte AddressByte CommandByte
3rdByte AddressByteif16-bit DataByte
4thByte DataByte
Thecommandbytehasfivelegitimatevalues: CommandByte $17 $AC $AA $EE $22
Action Accessthe256-byteEEPROMmemory.Afterthiscommandbyte,thenextbyteisthememory addresstobeaccessed. Accesstheconfigurationregister,eithertoreadstoredvaluesorsetvalues. Readthelasttemperatureresult.TwobytesarereturnedbytheDS1624. Startatemperatureconversion.Ifincontinuousmode,$EEinitiatescontinuousoperation.No datavaluefollowsa$EE. Stoptemperatureconversion.Ifincontinuousmode,$22haltscontinuousoperationuntila$EE isreceived.Nodatavaluefollowsa$22
Theconfigurationregisterisasinglebyte,withonlytwooptions: Bit7 Done
Bit6 1
Bit5 0
Bit4 0
Bit3 1
Bit2 0
Bit1 1
Bit0 1-shot
Done—IfDone=%1,thecommandedtemperatureconversioniscomplete;ifDone=%0,theconversionis stillinprogress. 1-Shot—TheDS1624operatesintwomodes;continuousandone-shot.Incontinuousmode(1-Shot=%0) theDS1624continuouslymakestemperatureconversions;assoonasoneiscompleted,thenextone starts.Inone-shotmode(1-Shot=%1),temperatureconversionsaremadeonlywhencommandedbythe $EEcommandbyte.IftheDS1624isincontinuousmode,however,acommandbyte$22willterminate continuousmodeuntila$EEcommandisreceived. Theconfigurationregisterisnonvolatile,soitsvalueisretainedwhenpowerisremoved.Thefactoryconfigurationiscontinuousmode. Usingthecommandbytemaybeclearerwithsamplecodetostartaconversion,readthetemperatureresult andstopconversions: TCtrl ReadT StartC
Con Con Con
%10011110 $AA $EE
;controlword&addresscombined ;readtemperature ;starttemperatureconversion
696
WeatherStationandDataLogger StopC
Con
$22
;stoptempconversion
RawTemp
Var
Word
;holdsbinarytemperatureoutput
;StartConversion I2COutMDta,MClk,ErrorWMsg,MCtrlB,StartC,[StartC] ;waitforconversiontocomplete Pause1000 ;Readthetemperature I2CinMDta,MClk,ErrorRMsg,MCtrlB,ReadT,| [RawTemp.Byte1,RawTemp.Byte0] ;stopconversiontosavepower I2COutMDta,MClk,ErrorWMsg,MCtrlB,StopC,[StopC]
Forthepurposeofthiscodefragment,assumewe’vedefinedthedataandclockpinsasMDataandMDlock, respectively,andthattwoerrorroutineshavebeendefined,ErrorWMsgforwriteerrorsandErrorRMsgfor readerrors. InChapter18,whenwritingtoaserialEEPROM,ourI2Coutcommandwas
I2COutDta,Clk,ErrorMsg,RCtrl,i+iStart,[Ti]
Wherei+iStartisthememoryaddressandTiisabytevaluebeingwrittentotheaddress. TosendacommandbytetotheDS1624,wesimplysubstitutethecommandbytefortheaddress: I2COutMDta,MClk,ErrorWMsg,MCtrlB,StartC,[StartC]
And,sinceI2Coutrequiresavaluebesent,weresendthecommandbyteasadummyvalue. Ratherthanrepeatedlyreadtheconfigurationregistertodeterminewhenthetemperatureconversioniscomplete,wewaitonesecond,themaximumconversiontime,forittobecompleted. Pause1000 ;Readthetemperature I2CinMDta,MClk,ErrorRMsg,MCtrlB,ReadT,| [RawTemp.Byte1,RawTemp.Byte0]
TheI2CinprocedureworksthesamewasastheI2Cout;wesubstitutethecommandbytefortheaddress byteandthenreadthetwo-bytetemperaturedata. I2COutMDta,MClk,ErrorWMsg,MCtrlB,StopC,[StopC]
Tostopconversions,wesendthe$22commandbyteasasubstitutefortheaddressbyteinanI2Coutprocedure,againusingthestopconversionconstantasadummydatavaluetosatisfyI2Cout’srequirementofat leastonedataelement. Thelastdifferencewe’llconcernourselveswithisthereturnedtemperaturedata.TheDS1624’sdistant cousin,theDS18B20,returnsa12-bittemperaturevalue,rightjustifiedintwosuccessivebytesthat,in Chapter12,wereadasawordlengthresult.TheDS1624returnsa13-bittemperaturevalue,leftjustified (shownfor+25.0625°C): 128 B15 0
64 B14 0
32 B13 0
Byte1 16 8 B12 B11 1 1
4 B10 0
2 B9 0
1 B8 1
.5 B7 0
.25 B6 0
.125 B5 0
Byte0 .0625 .03125 B4 B3 1 0
X B2 0
X B1 0
X B0 0
Thevalueiscalculatedas:
16+8+1+0.0625=25.0625
Thereasonthedataisleftjustifiedisthatitpermitsus—byreadingbyte1only—togetthetemperature directlyindegreesCelsius,withoutanymanipulation.Formanypurposes,aone-degreestepisadequate. However,wewishtousethefull13-bitresolutionoftheDS1624,sowemustdealwiththeleftjustified data.OneofmanywaystosimplifytheresultistoshiftthedatainByte0threeplacestotherightandtreat theresultingByte0valueasrepresenting0.03125°Csteps. 697
Chapter28
RawTemp.Byte0=RawTemp.Byte0>>3
Afterthisshift,oursamplevaluelookslike: B15 0
B14 0
B13 0
Byte1=25 B12 B11 1 1
B10 0
B9 0
B8 1
B7 0
B6 0
B5 0
Byte0=2 B4 B3 0 0
B2 0
B1 1
B0 0
Thevalueofbyte0is2,sothefractionalpartofthetemperatureis2*0.03125°C,or0.0625°C.Byte1, holdingtheintegervalue,remains25,sotheresultingtemperatureis25.0625°C,exactlyasitshouldbe. WecancomputethetemperatureasRawTemp.Byte1+0.03125*RawTemp.Byte0.We’llseehowthis workswithMBasic’sfloating-pointlibrarywhenweexaminethecodelaterinthischapter. AswiththeDS18B20,theDS1624uses“a16-bitsign-extendedtwo’scomplementnumber”whenreporting temperaturesbelow0°C.We’llusetheroutinesdevelopedinChapter12toconvertnegativereadingsandto convertCelsiustoFahrenheit.
ConnectingtheSensorsandMemory Ourweatherstationisthemostcomplexcircuitwe’veyetbuilt,sowe’llapproachourcircuitanalysisin modules.
VoltageReference OuranalysisoftheMPX6115 pressuresensorshowsthatwe needtomeasureupto4.4Vto readthedesignedmaximumair pressure.We’llusethesame precision4.096Vreference,a LinearTechnologiesLT1634CCZ-4.096deviceasourmaster voltagereference.Wehavetwo options:toscaletheMPX6115’s Figure28-1:VoltagereferenceandVDDscalingsection. outputdowntoamaximum valuebelow4.096V,ortoscale thereferencevoltage,VREF+,uptoabout4.6V.We’llchoosetoscalethereferencevoltageup,asit’sthe simpleroption.InChapter11,weusedanMCP601op-ampunitygainbuffertoprovidealowimpedance 4.096VreferencetothePIC;herewewilladdtworesistorstochangetheMCP601fromunitygaintoagain ofapproximately1.127,givingusareferencevoltageof4.616V.Figure28-1showstheresultingcircuit. Weanalyzethevoltagescalingcircuitbyemployingabasicop-amprule;inaclosedloopnegativefeedback amplifier,suchasthatinFigure28-1,thevoltagesattheinverting(–)andnoninverting(+)inputstotheop ampareidentical.Sincethenoninvertingvoltageis+4.096V,theinvertinginputmustalsobe+4.096V.But, theinvertinginputisconnectedtoavoltagedividercomprisingR2andR3.Hence,thevoltageattheoutput oftheop-ampmustbegreaterthan4.096V.Thegainoftheop-ampcircuitissimplythevoltagedivision ratiooftheresistivevoltagedividernetwork: R 2 + R3 R3 WhereAVistheresultingDCgain. AV =
698
WeatherStationandDataLogger Tobeabletomeasure4.401VfromtheMPX6115,weneedsomethinggreaterattheVREF+inputtothePIC’s A/Dconverter.Thereferencevoltagecan’tgettooclosetothe+5Vsupply,orelsewerunintoproblems withtheMCP601.(TheMCP601isarail-to-railoutputdevice,butevenso,it’sagoodideatomaintain somemarginbetweenoutputandsupplyvoltage.)Ifwesplitthedifferencebetweenthe+5Vsupplyandthe maximumvoltagetobemeasured,wearriveatabout4.7V,soweneed(R2+R3)/R3tobeabout1.147. AnyerrorinR2andR3directlytranslatesintoavoltagereferenceerror.TheLTC1634is±0.05%,soideally R2andR3haveatleastthisgoodatolerance.Precisionresistorsof0.05%orbettertoleranceareavailable, buttheyarenotinexpensiveandarenotoff-the-shelfitemsatmostsupplyhouses.Even0.1%toleranceresistorsarenotcommonlystocked.(MouserElectronicsisonesupplier;0.1%resistorsarepricedabout$1.00 eachinsinglelotquantities.0.01%resistorsrunabout$6.00eachinsinglelotquantities.)So,whattodo? Forexperimentation,we’lluse1%toleranceresistorsandaccepttheresults.(Icheatedabithere;Iused1% resistors,butmeasuredthevoltagereferenceoutputwitha5.5digitdigitalvoltmeter.Theprogramusesthe measuredvalue,notthecalculatedreferencevalue.)And,Ididn’thavethe1%resistorcombinationsnecessaryforavoltagegainof1.147,soIusedwhatIhad,100Kand12.7K1%resistors,yieldingatheoretical gainof1.127,foranoutputof4.616V.Imeasuredtheactualoutputvoltageat4.6235V,about0.16%in errorfromthetheoreticalvalue. It’snotagoodideatosubstitute5%carbonfilmresistors,withthethoughtthatyoucaneitherhand-selecta pairthatmatchthedesiredvalue,orsimplymeasuretheoutputvoltageanduseitinthecalculations.Metal filmprecisionresistorshaveamuchbettertemperaturecoefficientthancarbonfilmresistorsandarealso morestableovertime. TheremainingpartofFigure28-1isa1:2voltagedividerformeasuringthe+5Vsupply.Wemustmeasure thesupplyvoltagebecausetheMPX6115output-voltage-versus-pressureequationhasinitatermforthe supplyvoltage.Alookatthedatasheetforthe7805regulatorusedinthe2840developmentboardwillconvinceyouthatthe7805wasdesignedforcostandreliability,notprecision.Again,weshoulduseatleast1% resistorsforthevoltagedivider.Ihadseveral12.7Kohm1%resistors,soIusedapairforR4andR5.These valuesarenotparticularlycriticalandalmostanytwoequalvalueresistorsupto15Kohmorsocouldbe used.Infact,R4andR5neednotbe equalinvalueifyoualterthescaling constantintheprogram.
SensorSuite Thethreesensorsconnectasshown inFigure28-2. Don’tforgettoconfiguretheaddress pinsontheDS1624.I’vearbitrarily setthemallhigh(becauseit’seasy torunjumpersfrompin8to7to6to 5)sotheDS1624’saddressis%111 or$7.Ifyouchangetheaddress jumpers,you’llhavetomakeacorrespondingchangeintheprogram constantdefinitionsection. Figure28-2:Sensorsuite.
699
Chapter28 Real-TimeClockandSerialEEPROM Figure28-3showtheconnectionfortheDS1302 real-timeclockandtheAT24C512512kbitserial EEPROM. Forarefresheronthesedevices,reviewChapters12 (real-timeclock)and18(AT24C512).Bothdevice connectionsdirectlyduplicatethedesignsinthose chapters,saveforchangestopinconnectionstothe PIC. I’vesettheAT24C512’saddresspinsto%00,or$0. Althoughit’snotdirectlyobviousfromtheseparate drawings,theclockanddatalinesoftheAT24C512 areparalleledwiththoseoftheDS1624temperature sensor.Thetwodevicesareselectivelyaddressed throughdifferencesintheircontrolbytedevicefamilybits,aswellastheiraddresses.
CombinedSchematic
Figure28-3:Real-timeclockandserialEEPROM.
Thecombinedschematic,Figure28-4integrates thethreeindividualelementsweseparatelyreviewed.(Don’tforgettoconnecttheRS-232port.)I’veuseda 16F877Ainthisdesign,buta16F877wouldworkjustaswell,aswoulda16F876or16F876A.
InitialTests There’salottowireuponasmallplugboard,andit’seasytomakeamistake,sowe’llfirstwriteseveral simpleprogramstoverifythattheindividualelementsofourcircuitareproperlyconnectedandfunctioning. Firstwe’llverifytheA/Dcomponentsofthecircuitareworking.Program28-1AreadsVDD/2andthehumidityandbarometricpressuresensors,andreportstheoutputsinrawA/Dunits,incomputedvoltsandin computedfinalvalues,i.e.,relativehumidityinpercentandbarometricpressureininchesHgandmbar. Program28-1A ;Program28-1A ;ReadVdd,Vpres&Vhumid ;anddumpthevaluesouton ;serialport.Convertrawto ;engineeringunits. ;Constants ;-----------------;KeepsREpinsdigital,VrefonAN3 ;andrestofANpinsinputs ADSetup Con $83 ;seeChapter11 VddPin Con A0 ;Vdd/2 VrhPin Con A1 ;Relativehumiditypin Clk Con 2 ;A/Dconversionclock VbarPin Con A2 ;Barometricpin Vref fCon 4.6235;MeasuredVref ElevCor fCon 0.35 ;altitudecorrectionfor320ft mBarToInHg fCon 0.02953;millibarstoinchesHg ;Variables ;------------------
700
WeatherStationandDataLogger
Figure28-4:Combinedschematic. RawVolts Vstep Vdd Vrh VHg InHg mBars Rhum i
Var Var Var Var Var Var Var Var Var
Word Float Float Float Float Float Float Float Byte
;Readvoltage ;voltsperA/Dstep ;actualVdd ;OutputofRHsensor ;OutputofBarometricsensor ;InchesofMercurypressure ;OutputinBars(kPa/10) ;Relativehumidity ;delaycounter
;Initialization ;----------------- EnableHSerial SetHSerialH38400 ;serialoutput HSerOut[“P28-1A”,13] HSerOut[“V/Step:“,RealVStep,13] Vstep=Vref/1024.0 ;can’tcomputeasconstant Main
GoSubReadVdd HSerOut[“Vdd:“,RealVdd\3,”Raw:“,DecRawVolts,13] GoSubReadVrh HSerOut[“Vrh:“,RealVrh\3,”Raw:“,DecRawVolts,13] HSerOut[“RH:“,RealRhum\1,”%”,13] GoSubReadVbar HSerOut[“Vbar:“,RealVHg\3,”Raw:“,DecRawVolts,13]
701
Chapter28 HSerOut[“Pressure:“,RealmBars\1,”millibars”,13] HSerOut[“Pressure:“,RealInHg\2,”inHg”,13] Pause6000 GoToMain ReadVdd;ReadsVDDandreturnsitinVDD ;------- ADinVddPin,Clk,ADSetup,RawVolts Vdd=2.0*VStep*ToFloatRawVolts Return ReadVrh;ReadsRHvoltageandreturnsitinVrh ;------- ADinVrhPin,Clk,ADSetup,RawVolts Vrh=VStep*ToFloatRawVolts Rhum=(Vrh-1.079)/0.02568 Return ReadVbar;ReadsRHvoltageandreturnsitinVrh ;------- ADinVbarPin,Clk,ADSetup,RawVolts VHg=VStep*ToFloatRawVolts mBars=((VHg+0.095*Vdd)/(0.009*Vdd))*10.0 InHg=(mBars*mBarToInHg)+ElevCor Return End
Let’sfirstexaminetheconstantsthatsetuptheA/Dconversion.(IfyouneedarefresherinA/Dconversion, reviewChapter11.) ;Constants ;-----------------;KeepsREpinsdigital,VrefonAN3 ;andrestofANpinsinputs ADSetupCon $83 ;seeChapter11 VddPin Con A0 ;Vdd/2 VrhPin Con A1 ;Relativehumiditypin Clk Con 2 ;A/Dconversionclock VbarPinCon A2 ;Barometricpin
WehavethreeanalogvoltagestoreadandwewishtouseanexternalVREF+withVREF-atground.And,we wishour10-bitoutputtoberightjustified,sinceweintendtouseall10bits.Theserequirements,asreflectedinthetablebelow,extractedfromChapter11,aremetwithanA/Dsetupvalueof$83.Thisconstant whenusedwithMBasic’sADinproceduresetspinsA0,A1andA2toanaloginput,pinA3toVREF+andsets VREF-togroundandright-justifiesthereturned10-bitvalue.Wealsoaliasthethreeanaloginputpinstomore usefulnames. Hexfor Hexfor Left Just.
Right Just.
03
83
Ports(AN=Analog--RA/RE=RegisterA/E(Digital) AN7 RE2 D
AN6 RE1 D
AN5 RE0 D
AN4 RA5 A
AN3 RA3 Vref+
AN2 RA2 A
AN1 RA1 A
VoltRefs AN0 RA0 A
Vref+
Vref–
Chan/ Refs
RA3
Vss
4/1
Shadedcellsapplyonlyto16F877and16F877A.
Wesettheconversionclockvalueto2,representingTosc/32,sinceour16F877Ausesa20MHzresonator andTosc/32istheonlypermittedconversionclockvalueforthatclockspeed.Ifthismaterialisunfamiliar, pleasereviewChapter11. Vref ElevCorfCon mBarToInHg
fCon 0.35 fCon
4.6235 ;MeasuredVref ;altitudecorrectionfor320ft 0.02953;millibarstoinchesHg
702
WeatherStationandDataLogger Next,wedefinethreefloatingpointconstants: VrefisthemeasuredreferencevoltageatpinA3,4.616Vnominal.Ifyoucan’tmeasurethereferencevoltagewithadigitalvoltmeterwith0.25%accuracyorbetter,justsetVreftothenominalvalue4.616,or whatevervalueitshouldhave,basedonyourselectionofR2andR3inFigure28-1. ElevCoristhebarometeradjustmenttocorrecttosealevelreadingsmadeatanelevationof320feet,based upontheelevationofmyworkshop.ElevCorisininchesHgandisderivedasdiscussedearlierinthis chapter. MBartoInHgistheconstantthattranslatespressureinmillibars(hPa)toinchesHg.Itisfromthetable presentedearlierinthischapter. (We’lldealwiththevariableassignmentsasweusethemineachroutine.) ;Initialization ;----------------- SetHSerialH38400 ;serialoutput HSerOut[“P28-1A”,13] HSerOut[“V/Step:“,RealVStep,13] Vstep=Vref/1024.0 ;can’tcomputeasconstant
Inadditiontosettinguptheserialoutputportintheinitializationsection,wealsocalculateonetermthatis unchangedthroughoutourcalculations;howmanyvoltseachofthe1024A/Doutputstepsrepresents.We definethisparameterasavariableVstepandcalculateitsvalueduringinitialization.Vstepis4.5151mV.(Of course,wecouldhaveinsteadusedapocketcalculatortodeterminethatVstepis0.0045151andthendefineditasaconstantVstepfCon0.0045151.It’sbetterprogrammingpractice,though,touseconstants todefinefundamentalvaluesandletthecompilercalculatederivativevalues.Thismakesprogrammaintenanceeasier.) Main GoSubReadVdd HSerOut[“Vdd:“,RealVdd\3,”Raw:“,DecRawVolts,13] GoSubReadVrh HSerOut[“Vrh:“,RealVrh\3,”Raw:“,DecRawVolts,13] HSerOut[“RH:“,RealRhum\1,”%”,13] GoSubReadVbar HSerOut[“Vbar:“,RealVHg\3,”Raw:“,DecRawVolts,13] HSerOut[“Pressure:“,RealmBars\1,”millibars”,13] HSerOut[“Pressure:“,RealInHg\2,”inHg”,13] Pause6000 GoToMain
Themainprogramloopconsistsofaseriesofcallstosubroutineswheretheheavyliftingisperformed. Aftereachsubroutinecall,wewritethevaluesofthecorrespondingvariablestotheserialportwhereweuse thedatatodebugtheprogramandtoverifythateachsensorisproperlyfunctioning. ReadVdd;ReadsVDDandreturnsitinVDD ;------- ADinVddPin,Clk,ADSetup,RawVolts Vdd=2.0*VStep*ToFloatRawVolts Return
WeuseMBasic’sADinproceduretoreadthevoltageonpinVddPin(A0).Theresultingwordvalueis returnedinthevariableRawVolts.WethenconvertRawVolts(whichisinA/Dunits,0…1023)toan actualvoltagebyfirstconvertingRawVoltstoafloatingpointnumberwiththeToFloatoperatorandthen multiplyingitbythevoltageperA/Dstepvalue,VStep,wecalculatedintheinitializationroutine.Finally, sincewesenseVDDthrougha2:1voltagedividercomprisedofR4andR5,wemultiplyby2.0toyieldthe trueVDD.
703
Chapter28 ReadVrh;ReadsRHvoltageandreturnsitinVrh ;------- ADinVrhPin,Clk,ADSetup,RawVolts Vrh=VStep*ToFloatRawVolts Rhum=(Vrh-1.079)/0.02568 Return
WeuseasimilarapproachtoreadtheHM-1500humiditysensoroutputvoltage.AfterreadingtheA/Dcount inRawVolts,weconvertittofloatingpointvoltagebythesameprocessemployedinReadVdd.Wethen usetheequationdevelopedearlierinthischaptertoconvertthemeasuredoutputvoltagetoarelativehumiditypercentage. Vout −1.087 0.02568 TheMBasicstatementRhum=(Vrh-1.079)/0.02568implementstheconversionequation,with theresultantrelativehumiditypercentagestoredasafloatingpointvalueinRhum. RH =
ReadVbar;ReadsRHvoltageandreturnsitinVrh ;------- ADinVbarPin,Clk,ADSetup,RawVolts VHg=VStep*ToFloatRawVolts mBars=((VHg+0.095*Vdd)/| (0.009*Vdd))*10.0 InHg=(mBars*mBarToInHg)+ElevCor Return
Likewise,wereadthevoltageoutputfromtheMPX6115pressuresensorandconvertittoafloatingpoint value,storedinVHg.Wethenconvertthemeasuredoutputvoltagetoanabsolutepressureusingtheequation developedearlierinthischapter. Vout + 0.095VS 0.090VS TheMBasicstatementmBars=((VHg+0.095*Vdd)/(0.009*Vdd))*10.0implements thisequationandstorestheresultingpressureinmbarinthevariablembars.(NotethattheMBasicstatementactuallycalculatesthepressureinkPaandthenmultipliesitby10.0toyieldaresultinhPaormbar. Thisisthefunctionalequivalentoftheequation,ofcourse.) Pmbar =
TheremainingstepstoachieveasealevelcorrectedpressureininchesHgrequireustoconvertfrommbar toinchesHgandaddtheelevationcorrection.WeaccomplishthiswiththeMBasicstatementInHg= (mBars*mBarToInHg)+ElevCor. I’vedecidedtokeepthepressureinmbarsuncorrected.Youmightwishtocorrectitaswell. Here’sasampleoutputfromProgram28-1A: Vdd:4.966Raw:550 Vrh:2.027Raw:449 RH:36.9% Vbar:3.901Raw:864 Pressure:978.2millibars Pressure:29.26inHg Vdd:4.966Raw:550 Vrh:2.027Raw:449 RH:36.9% Vbar:3.887Raw:861 Pressure:975.2millibars Pressure:29.17inHg
704
WeatherStationandDataLogger Vdd:4.957Raw:549 Vrh:2.018Raw:447 RH:36.5% Vbar:3.910Raw:866 Pressure:981.8millibars Pressure:29.37inHg
Asexpected,weseethe±1countjitterintherawoutputwhenreadingVddandVrh.Thebarometricsensor outputbouncesaroundmorethan±1count,however.Thisislikelyacombinationofstraysignalsbeing coupledinthebreadboardandsomerealvariation. Program28-1B Nowthatwehavethesensorsuiteinstalledandfunctioning,wecanverifythattheAT24C512serialEEPROMmemorychipisworking. ;Program18-1Btoread/write ;selectivelyto512Kbit24C512SerialEEPROM ;I2Ccommunications;Demonstraterandomread/write ;Constants ;--------Clk Con Dta Con RCtrl Con DisplayCon Adr0 Con
B6 ;clockisonA0 B7 ;dataonA1 ;havetoaddthepageselecttoCtrl ;16-bitaddressword,soendsin1 %10100001 ;controlwordstartingpoint 0;setto0toblockwritingvaluestoserialport 0;Addressof24C512A0=A1=0 ;hasfull64Kwriteaddressspace
;Variables ;---------CtrlB i j ShouldBe
Var Var Var Var
Byte Word Byte Byte
;controlbyte ;index ;bytevalueto/from25FC512 ;calculatedreadvalue
;Initialization ;-------------;Communicatewithoutsideworldviaserial EnableHSerial SetHSerialH38400 ;Demonstraterandomaccessbyteatatime ;24C512isorganizedastwo32bytepages. ;Upto4chipsareaddressedinthecontrolbyte HSerOut[13,”IntoWrite”,13] Pause50 Fori=$0000to$FFFF CtrlB=RCtrl+Adr0 ;TowritesomethingdistinctivetoRAM ;wewritetheindexplustheoffset j=i.LowByte+i.HighByte ;Writetoaddressedmemory I2COutDta,Clk,ErrorMsg,CtrlB,i,[j] Pause5;neededforwritetime IfDisplay>0Then HSerOut[“Writei:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf If(i//256)=0Then HSerOut[“Writei:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput
705
Chapter28 EndIf Next j=0 Pause50 HSerOut[“EndofWrite”,13] Pause50 ;Nowreaditback Fori=$0000to$FFFE ;Setupthecontrolbyteinthesameway CtrlB=RCtrl+Adr0 ShouldBe=i.LowByte+i.HighByte I2CInDta,Clk,ErrorMsg,CtrlB,i,[j] IfDisplay>0Then HSerOut[“Readi:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf If(i//256)=0Then HSerOut[“Readi:“,Deci,”Data:“,Decj,13] Pause25 ;neededifwriteoutput EndIf Ifj<>ShouldBeThen HSerOut[“Readi:“,Deci,”Data:“,Decj] HSerOut[“<--Error!”,13] Pause25 EndIf Next HSerOut[“EndofRead”,13] Pause50 ;GoToMain End ErrorMsg HSerOut[“Error!”] End
Program28-1BisadirectcloneofProgram18-2B,changedonlytoreflectdifferentdataandclockpins,so wewillnotreanalyzeit.Ifyoudon’tunderstandthelogicorcodeofProgram28-1B,pleasereviewProgram 18-2BandtherelatedtextinChapter18. TheoutputofProgram28-1Bisshownbelow,withrepetitivepiecessuppressed. IntoWrite Writei:0Data:0 Writei:256Data:1 Writei:512Data:2 Writei:768Data:3 Writei:1024Data:4 … Writei:65024Data:254 Writei:65280Data:255 EndofWrite Readi:0Data:0 Readi:256Data:1 Readi:512Data:2 … Readi:64768Data:253 Readi:65024Data:254 Readi:65280Data:255 EndofRead
706
WeatherStationandDataLogger ThereshouldbenoerrormessagesgeneratedwhenrunningProgram28-1B. Program28-1C ;Program28-1CtotestreadingaDS1624EEPROM/Thermometer ;I2Ccommunications.InparallelwithanAT24C512512kbitEEPROM ;Constants ;--------Clk Con Dta Con TCtrl AccMem Con AccConfCon ReadT StartC Con StopC
B6 ;clockisonA0 B7 ;dataonA1 ;havetoaddthepageselecttoCtrl ;8-bitaddressword,soendsin0 Con %10011110 ;controlword&addresscombined $17 ;accessmemory $AC ;accessconfiguration Con $AA;readtemperature $EE;starttemperatureconversion Con $22 ;stoptempconversion
;Variables ;---------CtrlB RawTempVar PlusFlag Centigrade Fahrenheit
Var Word Var Var Var
Byte ;index Byte Float Float
;controlbyte ;plus/minusflag ;FloatingpointCtemp ;FloatingpointFtemp
;Initialization ;-------------;Communicatewithoutsideworldviaserial SetHSerialH38400 RawTemp=0 Main
CtrlB=TCtrl ;starttemperatureconversion I2COutDta,Clk,ErrorMsg,CtrlB,StartC,[StartC] Pause1000 I2CInDta,Clk,ErrorMsg,CtrlB,ReadT,| [RawTemp.Byte1,RawTemp.Byte0] ;dataisleftjustified RawTemp.Byte0=RawTemp.Byte0>>3 ;stopconversiontosavepower I2COutDta,Clk,ErrorMsg,CtrlB,StopC,[StopC] PlusFlag=1 IfRawTemp.HighBit=1Then ;checkfor<0C ;Subtractfrom0toreadbelow0value RawTemp=$0000-RawTemp PlusFlag=0 EndIf ;ReturnedvalueisinCentigradestepsof0.03125DegC. ;ThisdiffersfromtheDS18B20weusedinChapter12! Centigrade=(ToFloatRawTemp.Byte0)*0.03125 Centigrade=Centigrade+ToFloatRawTemp.Byte1 IfPlusFlag=0Then ;belowzero,multiplyby-1 Centigrade=-Centigrade EndIf
;StandardconversionformulatogettoFfromC. Fahrenheit=(Centigrade*1.8)+32.0 ;convertF HSerOut[“Temp:“,RealCentigrade\2,”C“,| RealFahrenheit\2,”F”,13] Pause5000 GoToMain ErrorMsg
707
Chapter28 End
HSerOut[“Error!”]
Asusual,westartbydefiningconstantsthatwe’llusetocommunicatewiththeDS1624 ;Constants ;--------Clk Dta TCtrl AccMem AccConf ReadT StartC StopC
Con Con Con Con Con Con Con Con
B6 ;clockisonA0 B7 ;dataonA1 %10011110 ;controlword&addresscombined $17 ;accessmemory $AC ;accessconfiguration $AA ;readtemperature $EE ;starttemperatureconversion $22 ;stoptempconversion
Althoughwewon’tusetheminthischapter,we’vedefinedallfivepossiblecommandbytes.WealsoconstructtheI2Cin/I2Coutcontrolbyte,followingthemethodologydevelopedearlierinthischapter: Element FamilyCode Address(PinsA0/A1/A2at+5V) 8/16BitSelection(8-bit)
Value %1001 %111 %0
Thecontrolbyteisthus%10011110. Let’slookatreadingtheDS1624. Main
CtrlB=TCtrl I2COutDta,Clk,ErrorMsg,CtrlB,StartC,[StartC]
Aswelearnedearlier,theDS1624protocoliscontrolbyte:commandbyte:optionaldatabyte.I2Cout transmitsthissequenceifwesubstitutethecommandbytefortheaddressbyte.I2Coutrequiresadatabyte, soweusethecommandbyteasadummydataelement.TheStartC($EE)commandbytestartsatemperatureconversion.
Pause1000
RatherthanpolltheDS1624todeterminewhenthetemperatureconversioniscompleted,we’lljustwaitone second.Iftimeiscritical,it’spossibletopolltheDS1624anddeterminewhentheconversioniscompleted. (Thetypicalconversiontimeis400ms,butthemaximumtimeis1000ms.)
I2CInDta,Clk,ErrorMsg,CtrlB,ReadT,| [RawTemp.Byte1,RawTemp.Byte0]
Weusethesameapproachwhenreadingthereturnedtemperaturevalue;substitutethecommandbytefor theaddressbyteintheI2Cinprocedure.Toreadthetemperaturedata,thecommandbyteisReadT($AA). Sincethereturnedtemperatureisintwobytes,wereadeachseparately.TheorderisMSBfirst,soweread RawTemp.Byte1,followedbyRawTemp.Byte0.
RawTemp.Byte0=RawTemp.Byte0>>3
AswelearnedwhenstudyingtheDS1624,the13-bitdataisreturnedleftjustified.Tomakeiteasierto handle,werightjustifyRawTemp.Byte0byshiftingitscontentsthreebitstotherightusingMBasic’sshift rightoperator.
I2COutDta,Clk,ErrorMsg,CtrlB,StopC,[StopC]
Afterreadingthedata,westopfurtherconversionswiththeStopC($22)commandbyte.
PlusFlag=1 IfRawTemp.HighBit=1Then ;checkfor<0C ;Subtractfrom0toreadbelow0value RawTemp=$0000-RawTemp PlusFlag=0 EndIf
708
WeatherStationandDataLogger Afterreadingthe13-bitrawtemperatureinformationandright-justifying,wenowchecktoseeifitrepresentsabelowzeroCelsiusvalue.Wherethetemperatureisbelowzero,thedatais“two’scomplemented.” Wecheckforthisbylookingatthehighorderbitofthereturneddata,whichwillbea1onlyifthedatais belowzero.Ifthetemperatureisbelowzero,weremovethecomplementbysubtractingthereturnedvalue from$0000andsettheplusflagto0. ThiscodefragmentisidenticalwiththetechniqueweusedinChapter12toreadtheDS18B20one-wire temperaturesensor,whereitisexplainedinmoredetail.
;ReturnedvalueisinCentigradestepsof0.03125DegC. ;ThisdiffersfromtheDS18B20weusedinChapter12! Centigrade=(ToFloatRawTemp.Byte0)*0.03125 Centigrade=Centigrade+ToFloatRawTemp.Byte1 IfPlusFlag=0Then ;belowzero,multiplyby-1 Centigrade=-Centigrade EndIf
WenextconvertthereturnedvaluetoanactualCelsiustemperature.RawTemp.Byte1holdsthetemperature inintegerdegrees,whileRawTemp.Byte0holdsthefractionalpartofthetemperature,inincrementsof 0.03125°C.WeconverttoafloatingpointtemperatureindegreesCelsiusbymultiplyingRawTemp.Byte1 by1.000andmultiplyingRawTemp.Byte0by0.03125andsummingthetwoproducts.TheresultingtemperaturevalueisheldinthefloatingpointvariableCentigrade.
;StandardconversionformulatogettoFfromC. Fahrenheit=(Centigrade*1.8)+32.0 ;convertF HSerOut[“Temp:“,RealCentigrade\2,”C“,| RealFahrenheit\2,”F”,13] Pause5000 GoToMain
Lastly,weconverttheCelsiustemperaturetoFahrenheitandstoretheresultinthefloatingpointvariable Fahrenheit. SampleoutputfromProgram28-1Cappearsbelow.(TotesttheresponseoftheDS1624,Ibrieflyputmy fingeronit—inafewsecondsthereadingincreasedbyabout4°F.) Temp:22.59C72.66F Temp:22.65C72.78F Temp:24.28C75.70F Temp:24.90C76.83F Temp:24.75C76.54F Temp:24.09C75.36F Temp:23.68C74.63F Temp:23.46C74.24F Temp:23.31C73.96F Temp:23.21C73.79F Temp:23.15C73.68F
Program28-1D TheremainingelementtotestistheDS1302realtimeclock.Program28-1DexercisestheDS1302and outputsthedateandtimetotheserialport. ;Program28-1D.ReadsaDallas/MaximDS1302 ;Realtimeclock. ;Alsowritesthecurrenttimetotheclock ;Varibles ;--------------RTCCmd Var Temp Var i Var
Byte Byte Byte
;Commandbyte ;Temporaryvariable ;counter
709
Chapter28 TimeData OldSeconds
Var Var
Byte(7) Byte
;ss:mm:hh:dd:mm:yy ;lastreadseconds
;Forconvienencewealiasthetimearray Seconds Var TimeData(0) ;Seconds Minutes Var TimeData(1) ;Minutes Hours Var TimeData(2) ;Hours Date Var TimeData(3) ;DayofMonth Month Var TimeData(4) ;Month Day Var TimeData(5) ;DayofWeek Year Var TimeData(6) ;Year ;Constants ;-------------- Clk Con Dta Con Reset Con CtrlRegCon
B2 B3 B1
()areDIP8numbers ;Clockpin(7) ;Datapin(6) ;Resetpin(5)
%00111
;InitialloadofSecMinHrsDateMODayYR PreSetByteTable$00,$05,$10,$08,$01,$05,$04 ;TheseareinBCD,henceNovember(Month11) ;isenteredas$11,not11. ;Commandtoselectchargersettings ChargerCon %01000 ;1diode,2Kchargingresistance.See ;Figure5ofDS1320datasheet BatteryCon %10100101 ;ForDayandMonthnames,usethefollowing.Since ;Sun=1andJan=1weusenulatthebeginninginsteadof ;subtracting1. DayNameByteTable“NulSunMonTueWedThuFriSatSun” MoNameByteTable“NulJanFebMarAprMayJunJulAugSepOctNovDec” Initialization ;------------- EnableHSerial SetHSerialH38400 HSerOut[“Pgm28-01d”,13]
;Tosettheclockwefirstdisablewriteprotection. ;Thensendtheclocksetinformation,andthenrestore ;writeprotection.
GotoNoSet
NoSet
;SetthedateandtimefromthePresetbytetable Fori=0to6 Temp=Preset(i) RTCCmd=i GoSubPreSetData Next
;DS1320Writeprotectionbackon Temp=$80 RTCCmd=CtrlReg GoSubPreSetData
;DisableDS1302WriteProtectionby0inBit7 Temp=$00 RTCCmd=CtrlReg GoSubPreSetData ;skipifdataalreadyset
;SIncewehaveaSuperCapbackup,wewantchargerON Temp=Battery RTCCmd=Charger GoSubPreSetData
710
WeatherStationandDataLogger Loop ;--------- ;Readtheclockoutput.Checktheseconds. ;Ifchanged,writetime GoSubReadData ;Writeinform: ;13:10:4511/24/03Mon24-Nov-2003totheserialport ;Newseconds,sowriteoutput IfOldSeconds<>SecondsThen HSerOut[Dec2(BCD2BINHours)\2,”:”,| Dec2(BCD2BINMinutes)\2,”:”,Dec2(BCD2BINSeconds)\2] HSerOut[““,Dec2(BCD2BINMonth)\2,”/”,| Dec2(BCD2BINDate)\2,”/”,Dec2(BCD2BINYear)\2] HSerOut[““,StrDayName(Day*3)\3,”“] HSerOut[Dec2(BCD2BINDate)\2,”-”,| StrMoName(3*BCD2BINMonth)\3,”-20”,| Dec2(BCD2BINYear)\2,13] EndIf GoToLoop PreSetData ;RoutinetouploaddatatotheDS1302 ;---------- HighReset ;The%0\1,RTCCmd\5,%10\2resultsintheequivelentof ;sending10RTCCMD0.Eachelementissentinelementorder ;butbitreversed,asrequiredbytheDS1320. ShiftOutDta,Clk,LSBFIRST,[%0\1,RTCCmd\5,%10\2,Temp\8] LowReset Return ReadData ;--------- ;Resetpinmustbehighforread HighReset ;%10111111isBURSTSENDREGISTERcommand, ;sotimeis8bytes ;thelastbyteisthecontrolregister, ;whichwedon’treadoruse ShiftOutDta,Clk,LSBFirst,[%10111111\8] OldSeconds=Seconds ;Nowactuallyreadtheburstsenddata. ShiftInDta,Clk,LSBPRE,[Seconds\8,Minutes\8,| Hours\8,Date\8,Month\8,Day\8,Year\8] LowReset Return
Exceptforchangestopinassignments,Program28-1DduplicatesProgram12-4.SinceChapter12presents adetailedanalysisoftheDS1302realtimeclockandProgram12-4,wewon’tfurtherdiscussit. Program28-1Dwritesthetimeanddate,everysecond,totheserialport.Sampleoutputappearsbelow. 08:43:5701/19/04Mon19-Jan-2004 08:43:5801/19/04Mon19-Jan-2004 08:43:5901/19/04Mon19-Jan-2004 08:44:0001/19/04Mon19-Jan-2004 08:44:0101/19/04Mon19-Jan-2004 08:44:0201/19/04Mon19-Jan-2004 08:44:0301/19/04Mon19-Jan-2004
Program28-2 Programs28-1Athrough28-1Dverifythetemperature,humidityandbarometricpressuresensorsarecorrectlyfunctioning,thatwemaywritetoandreadfromtheexternalEEPROMserialmemoryandthatthe realtimeclockcanbesetandread.Wearenowreadytoassemblethesefourelementsintoaweatherstation anddatalogger.
711
Chapter28 Beforewedelveintothecode,let’srecapwhatweexpectthisprogramtoaccomplish: • Readtherealtimeclockandthethreeweathersensors.Outputthetime,date,temperature,relative humidityandbarometricpressuretotheserialport. • Periodicallysavethedate,time,temperature,relativehumidityandbarometricpressuretotheserial EEPROM. • Uponcommandfromtheuser,readthesaveddatafromEEPROMandsenditovertheserialport.(The commandistheletter“o”or“O”followedbyacarriagereturn.) SinceProgram28-2isbasedlargelyuponthesubroutinesofPrograms28-1Athrough28-1D,let’suse pseudo-codetoseehowthesesubroutinesfitintoourprogramstructure. Main
GoSubReadTime–ReadTimeconstructedfromPgm28-1D Isittimetooutputdata?IfnotgotoMain GoSubReadTemp–ReadTempconstructedfromPgm28-1C GoSubReadVbar–FromProgram28-1A GoSubReadVrh–FromProgram28-1A GoSubWriteTime–Writestime/datetoRS-232 GoSubWriteWxData -WriteweatherdatatoRS-232 GoSubPackTimeInfo–Compressdate/timetouselessmemory GoSubSavePackTime–SavetoEEPROMfromProgram28-1B GoSubPackReadings–Compressweatherdata GoSubSavePackData–SavetoEEPROMfromProgram28-1B
Readserialportforinputcommandtowritesaveddata (BasedonmenuprogramfromChapter9) Iffoundunpackandsenddatatoserialport (ReadroutinebasedonProgram28-1B) GoToMain
Program28-2isverylongandlargelyduplicatesthischapter’searlierprogram.Ratherthanfollowournormal structureoflistingtheprograminfull,followedbyasection-by-sectionanalysis,we’llskipthefulllisting.Program28-2,likeallotherprogramsinthisbook,isavailableinanelectroniccopyintheassociatedCD-ROM.If youneedalistingtofollowwhilereadingtheanalysis,youmayprintonefromtheprogramfile. Toavoidduplication,wewillnotanalyzethesubroutinesthatarederivedfromPrograms28-1Athrough28-1D. We’llstartwiththemainprogramloopandoverallprogramflow. Program28-2 Main HSerStat3,CheckInput
Comment Checktheserialinputtoseeiftheuserhas sentacommandtotheprogram.Ifdatais intheserialinputbuffer,executethecode atlabelCheckInput.HserStatisan undocumentedMBasicprocedurediscussed inChapter9andsummarizedlaterinthis chapter.
712
WeatherStationandDataLogger ReturnFromCI
LabelReturnFromCI.Executionreturnshere aftertheCheckInputcodeexecutes.Thisis awayoffakingaGoSub/ReturnwhereMBasic doesn’tallowaGoSub/Returnconstruction.
GoSubReadTime
ReadtheDS1302real-timeclock.
IfOldMins<>MinutesThen MinCount=MinCount+1 OldMins=Minutes EndIf
Keeptrackofhowmanyminuteshavepassed sincethelastwritetoEEPROMinMinCount. WedothisbycheckingtheDS1302’sminute value.Ifitisdifferentthantheminutevalue inthelastDS1302read,anewminutehas started.WethenincrementMinCount.
IfMinCount=MinsThen MinCount=0 ELSE GoToMain EndIf
Minsisaconstantthatdefinesthenumber ofminutesthatshouldelapsebetween EEPROMsaves.Iftheelapsedminutes,heldin MinCount,doesnotmatchMins,thenwe gobacktoMainandwaitforeitherauser inputtotheserialport,orforMinCountto equalMins.IfMinCount=Minsthenwe resetMinCountto0andgoontoexecutethe remainderofthecode. Thecurrentprogramstructurewritestothe serialportonlywhendataissaved,i.e.,the weatherdataissenttotheserialportonlyas frequentlyasthedataissavedtoEEPROM.
GoSubReadTemp GoSubReadVbar
ReadtheDS1624temperaturesensor. ReadtheMPX6115barometricpressure sensor.
GoSubReadVrh GoSubWriteTime
ReadtheHM1500relativehumiditysensor.
;GoSubWriteEngData
WriteEngDataisadebuggingand experimentationsubroutinethatwritesraw A/Dreadingsandvoltagevaluestotheserial port.I’vecommenteditout,butifyouhave problemswithoneormoresensors,remove thecommentsymbolandreruntheprogram.
GoSubWriteWxData
Writetheweatherinformationtotheserial report.
Writethedateandtimetotheserialport.
713
Chapter28 ;GoSubWxToOscope
GoSubPackTimeInfo
GoSubSavePackTime GoSubPackReadings
GoSubSavePackData RecordNo=RecordNo+1
Anotherdebuggingandanalysisaid.MBasic’s integrateddevelopmentenvironment includesagraphinganalysistool,underTools |Oscilloscope.Ifthecommentsymbolis removedsothesubroutineWxToOscopeis executed,therelativehumidity,temperature(F) andbarometricpressure(inHg)arewrittento theserialportinaformatcompatiblewiththe Oscilloscopeutility. Ifwesavethedate/timeinformationinthe formitisemittedbytheDS1302,itwould require6bytes.Wereformatthedataand bit-packitinto4bytesinthesubroutine PackTimeInfo. SubroutineSavePackTimesavesthebitpackeddate/timetoEEPROM. SubroutinePackReadingsreformatsand bit-packsthetemperature,barometricpressure andrelativehumidityreadingsinto4bytes. SubroutineSavePackDatasavesthebitpackedweatherdatatoEEPROM. RecordNoistheindexthatkeepstrackof howmanypackeddate/timeandweatherdata recordshavebeenwrittentoEEPROM.
IfRecordNo=$1FFEThen Recordno=$0 EndIf
TheEEPROM’scapacityis512kbits,or65,536 bytes.Thiscorrespondsto8192date/time/ weatherrecordsof8byteslength(0…8191). Wefoundproblemswritingtothelastbyteof EEPROMinChapter18,sowelimitourselves to8191records(0…8190.Sinceweincrease afterwriting,wejusttestfor8191andreset whenitisreached.Forconvenience,I’ve writtenthisinhexas$1FFE.
GoToMain
GobacktoMainanddoitalloveragain.
Let’slookatthesubroutineswehavenotseenelsewhere. We’llstartwiththeroutinestoreaduserinformationreceivedovertheserialport.Program28-2usesa strippeddownversionofthefullmenu/inputprogramwedevelopedinChapter9. First,considerthefirststatementinthemainprogramloop:HSerStat3,CheckInput HSerStatisanundocumentedMBasiccommandthatletsyoureadandmodifythestatusofboththe receiveandtransmithardwareserialbuffers.HserStatworkswithHSerInandHSerOutandassumesyou
714
WeatherStationandDataLogger haveinitializedthehardwareserialroutineswiththeEnableHSerialcompilerdirectiveandSetHSerial command.Itscommandsyntaxis:
HserStatexp,{label}
Expisavaluefrom0…6thatdeterminesthefunctiontobeexecuted. Command 0 1 2 3 4 5 6
Function Cleartheinputbuffer Cleartheoutputbuffer Clearboththeinputandoutputbuffers Iftheinputbufferhasdata,executeaGoTolabel Iftheinputbufferisempty,executeaGoTolabel Iftheoutputbufferhasdata,executeaGoTolabel Iftheoutputbufferisempty,executeaGoTolabel
ThestatementHSerStat3,CheckInputisexecutedeverymillisecondorso,aswereadthecurrenttime fromtheDS1302andloopbacktoMain,unlessitistimetoreadthesensorsandsavedatatotheEEPROM. SinceweinvokeHSerStatwithanargumentof3,ifthereisdatainthereceivebuffer,executionwilljump tothelabelCheckInput. CheckInputisnotatruesubroutine,asit’snotpossibletouseasubroutinecallwithHSerStat,butthe GoToReturnFromCIstatementletsitactssimilartoatruesubroutine,asthelabelReturnFromCIimmediatelyfollowstheHSerStatstatement. CheckInput ;------------- HSerIn[InByte] ;Echoback HSerOut[StrInByte\1] InStr(jj)=InByte jj=jj+1 Ifjj=(MaxStrSize-1)Then jj=0 EndIf IfInByte=13Then GoSubCRReceived EndIf HSerStat3,CheckInput GoToReturnFromCI
Onceweknowacharacteriswaitingintheserialinputbuffer,wethenreaditintothebytearrayInStr. Wecheckfortwopossibleconditions(a)thatthenumberofbytesreceivedexceedsthesizeofInStror(b) thatwehavereceivedanend-of-lineindicator(carriagereturn,withadecimalvalueof13).Ifthenumberof bytesreceivedreachesInStr’ssize,weresettheindexto0.Ifacarriagereturnisreceived,wethenexecute thesubroutineCRReceivedtoseeifthereceivedcharactersareavalidcommand.WeusetheHSerStat proceduretoloopbackthroughCheckInputuntilallcharactersinthebufferhavebeenread.Atthatpoint, HSerStat3,CheckInputnolongerexecutestheGoToCheckInput. SubroutineCRReceivedisfarmorecomplexthannecessaryifourgoalissimplytodetermineifthecharacter“o”or“O”hasbeenreceived.CRReceivedis,infact,partofthemenu/dataserialentryprogramwe developedinChapter9.Ratherthanmodifyit,we’llusethecompletesubroutine,sinceweknowitworks. CRReceived ;---------
715
Chapter28
Forjj=0to(MaxStrSize-1) If(InStr(jj)<““)OR(InStr(jj)>“z”)Then InStr(jj)=$0;non-printingchars EndIf ;Convertlowercasetouppercase If(InStr(jj)>=“a”)and(InStr(jj)<=“z”)Then InStr(jj)=InStr(jj)-$20 EndIf Next;jj
Hereweconvertanylowercaseletterstouppercase,simplifyingourcommandsyntax.
;howlongisthevalidpartofthestring? k=0 WhileInStr(k)>=““ k=k+1 WEND
Thebytevariablekholdsthelengthofthereceivedstring,excludingnonprintingcharactersthatarebelow thespacecharacterintheASCIIcollatingsequence.
Ifk>0Then k=InStr(0)-“?” Ifk>27Then k=1 EndIf BranchIndexArray(k),[BR_Unk,BR_Out] EndIf
AswelearnedinChapter9,ourapproachtoageneral-purposedispatcherisbasedonamenusystemthat looksatthefirstcharacteroftheuser’sresponseandindexesthatcharacterintoatabletodeterminewhich functionitshouldexecute.Permissiblefirstcharactervaluesare“?,”“@,”andtheletters“A”through“Z.” Weconvertthefirstcharacterintoanumericalvalue,rangingfrom0(“?”)to27(“Z”)bysubtracting“?” fromthereceivedcharacter.Ifthefirstcharacterisoutsidethatrange,weforceittobe1,correspondingto “@”whichwethenmaytreatas“unknowncommand”andissueanappropriateresponsetotheuser. IndexArray()isa28elementbytetablethatrelatesthefirstletterofpossiblecommandstoanindexvalue.WedefinedIndexArrayintheconstantssectionofProgram28-2,butwe’llrepeatithere.(I’veslightly modifiedIndexArray’sformattobetterfittheprintedpage.) ;?@ABCDEFGHIJKL IndexArrayByteTable0,0,0,0,0,0,0,0,0,0,0,0,0,0,| 0,0,1,0,0,0,0,0,0,0,0,0,0,0 ;MNOPQRSTUVWXYZ
Supposethefirstletterreceivedis“O.”Weconvertthislettertoitsordinalvaluevia“O”–“?”.The resultis16,whichisstoredink.We’vegivenIndexArray(16)thevalue1.HencethestatementBranch IndexArray(k),[BR_Unk,BR_Out]evaluatestoBranch1,[BR_Unk,BR_Out]andprogramexecutionjumpstothelabelBR_Out.Thismayseemoverlycomplex,anditisifallweneeddoisdetectthe letter“o”or“O.”But,asapartofacomplexuserinteractionsystem,aswedevelopedinChapter9,itisan efficientwayofadding,deletingorrearrangingthecommandsyntaxwithoutbeingforcedtomodifycode. Insteadallweneeddoischangeatableentryortwoandaddordeleteashortcorrespondingroutingfunction.
BR_Unk GoSubSub_Unk GoToEndCmd
Ifthefirstletterreceiveddoesnotcorrespondtoalegitimatecharacter,itsindexvalueinIndexArrayis0, whichcausesabranchtoBR_Unk,whichtheninformstheuserthathehasenteredanunknowncommand. Notealsothatifonlyacarriagereturnhasbeenreceived(k=0),BR_Outisstillexecuted.
BR_Out GoSubSub_Out
716
WeatherStationandDataLogger
GoToEndCmd
Ifthereceivedletteris“o”or“O,”executionwilljumptoBR_OutandsubroutineSub_Outiscalled. EndCmd HSerStat0 j=0 Return
Beforereturning,weclearthereceivedbufferwithaHSerStat0command. ThesubroutineSub_OutreadsallstoredvaluesfromtheEEPROMunpacksthedataandwritesthetime/ dateandweatherinformationtotheserialoutputport.Allofthesefunctionsareperformedbycallstofunctionalsubroutines,andwe’lldefertheiranalysisuntilafterwegothroughthedatapackingprocess. Sub_Out;DumpEEPROMtoserial ;----------- ForAdrConst=0to(RecordNo-1) HSerOut[DecAdrConst,9] ReadAdr=AdrConst*2*WriteInc GoSubReadPackTime GoSubUnpackTimeInfo GoSubWriteUnpackedTime ReadAdr=ReadAdr+WriteInc GoSubReadPackData GoSubUnPackReadings GoSubWriteUnpackedWxData Next Return
Dataisstoredinrecords,witheachrecordconsistingoftwofour-bytepackedvariables;thefirstholdingthe time/dateandthesecondholdingweatherdata.AdrConstisanindexforthenumberofsavedrecordsand hasamaximumvalueof8190.ReadAdristhebyteaddressfortheEEPROMread,i.e.,ReadAdrranges from0…65527fortheAT24C512. WriteInc(standingforWriteIncrement)isaconstantequaltofour,andisthenumberofbytesineachhalf ofarecord.ReadAdrthusincrementsinstepsoffour,withtwoincrementsforeachAdrConststep,forexample,AdrConst=0,ReadAdr=0and4;AdrConst=1,ReadAdr=4and8,andsoforth.When AdrConst=0,8,12…wewritethedate/timeinformation;whenitis4,12,16…wewritetheweather
information.Thisarrangementisreflectedinthefollowingdatamap: 24C512Address 65535 65528
Contents
RecordNo.
AdrConst
ReadAdr
Unused
Unused
Unused
Unused
Record8190
8190
65527 65524
PackedWxData
65523 65520
PackedTime
… 15 12
…
65524 65520 …
…
Record1
1
PackedWxData
11 8
PackedTime
7 4
PackedWxData
3 0
PackedTime
… 12 8 4
Record0
0 0
717
Chapter28 Let’snowturntohowwepackandunpackthetime/dateandweatherinformation. TheDS1302datastructureisaseven-byterecord,witheachbytecontainingatwo-digitBCDvalue.We don’tneedtheday-of-the-weekinformation,butwearestillleftwithsixBCDbytes,1byteperfield;hour: minute:secondandday/month/year.Lookingattheminimumnumberofbitsrequiredforeachfield,we seethatafullbyteiswasteful: Field Seconds Minutes Hours DayofMonth Months Years
Minimum/MaximumValue 0…59 0…59 0…23 1…31 1…12 01…00[2001…2100] Total
MinimumBitsRequired 6 6 5 5 4 6* 32
TheDS1302correctlycalculatesleapyearthrough2100,sowemightliketheyearfieldtorunthrough 2100.Unfortunately,thisrequires7bits,andpushesthetotalupto33bits.Tokeeptoa4-byterecordlength, we’llshave1bitofftheyearfieldandthuslimitourpotentialyearrangeto00…63.Theresultingpacked datamapisshownbelow. 3 1
3 0
2 9
2 8
2 7
2 6
2 5
2 4
2 3
2 2
2 1
2 0
1 9
1 8
1 7
1 6
1 5
1 4
1 3
1 2
1 1
1 0
0 9
0 8
0 7
0 6
0 5
0 4
0 3
0 2
6bits
4bits
5bits
5bits
6bits
6bits
Year
Month
DayofMonth
Hours
Minutes
Seconds
Byte3
Byte2
Byte1
0 1
0 0
Byte0
Packingtime/dateinformationintothefour-byterecordisatwo-stepprocess;firstweconverttheBCDvalueof eachofsixfieldvaluestostraightbinaryvalues.Then,weinserttherelevantbitsofthebinaryvaluesintothe time/daterecord.SinceatypelongvariableinMBasicisfourbytes,it’sconvenienttomaketherecordatype longvariable,PackedTime.SubroutinePackTimeInfobitpacksthesixtime/datefieldsintoPackedTime. PackLenByteTable$5,$5,$4,$4,$3,$0,$5 PackTimeInfo ;Putdate/timeinfoinbit-packedlong ;---------- PackedTime=0 k=0 Fori=0to6 Ifi<>5Then TempByte=BCD2BINTimeData(i) Forj=0toPackLen(i) k=k+1 PackedTime.Bit31=TempByte.Bit0 Ifk<>31Then PackedTime=PackedTime>>1 EndIf TempByte=TempByte>>1 Next;j EndIf Next;i Return
WestartbyclearingPackedTimebysettingitto0.Rememberthatthetimeanddateinformationisstored intheseven-elementbytearrayTimeData,inordersecondstoyearsandthatTimeData(5)isthedayof theweek,afieldwedonotwishtosave. ForeachTimeDataelement,exceptforTimeData(5),wefirstconvertfromitsnativeBCDformattoa binaryandholdthebinaryvalueinTempByte.WethencopyTempByte.Bit0toPackedTime.Bit31.We 718
WeatherStationandDataLogger nextshiftbothTempByteandPackedTime1bittotherightandrepeatthecopyuntilwehavecopiedall therequiredbitsofTempByteintoPackedTime.AfteroneelementofTimeDataisshiftedintoPackedTime,wegetthenextelement,convertitfromBCDtobinaryandrepeatthecopy/shiftprocess. Toseehowthisworksinmoredetail,let’slookatanexample.Supposethetimeis33seconds.Since TimeData(0)holdsthesecondsvalueinBCD,TimeData(0).Nib1=3andTimeData(0).Nib0= 3..Let’sseehowthisisconvertedtodecimalandshiftedintoPackedTime. AswelearnedinChapter7,BCDdataisorganizedasonedigit0…9ineachnibbleofabyte.Thus,TimeData(0),withavalueof33secondsholdsthefollowingbinarypattern: 7
0
6 5 Nibble1 Value=$3 1 1
TimeData(0) 4 3
0
0
2 1 Nibble0 Value=$3 1 1
0
0
AfterTempByte=BCD2BINTimeData(0),TempBytecontains: 7 0
6 0
5 1
TempByte 4 3 0 0
2 0
1 0
0 1
WenowstartshiftingTempByteintoPackedTime. Afterthefirstbitcopy,withthecopiedbitshownshaded:
31 1
30 0
29 0
7 0
6 0
5 1
TempByte 4 3 0 0
2 0
1 0
0 1
28 0
27 0
26 0
PackedTime 25 24 0 0
23 0
22 0
21 0
…
1 0
0 0
NowweshiftbothTempByteandPackedTimeonebittotherightandcopyTempByte.Bit0toPackedTime.Bit31again:
31 0
30 1
29 0
7 0
6 0
5 0
TempByte 4 3 1 0
2 0
1 0
0 0
28 0
27 0
26 0
PackedTime 25 24 0 0
23 0
22 0
21 0
7 0
6 0
5 0
TempByte 4 3 0 1
2 0
1 0
0 0
Andagain:
719
…
1 0
0 0
Chapter28 31 0
30 0
29 1
27 0
26 0
PackedTime 25 24 0 0
23 0
22 0
21 0
7 0
6 0
5 0
TempByte 4 3 0 0
2 0
1 0
0 1
28 0
27 0
26 1
PackedTime 25 24 0 0
23 0
22 0
21 0
28 0
…
1 0
0 0
…
1 0
0 0
Afterthesixthcopyandshift:
31 1
30 0
29 0
Unpackingthedataisjustthereverseofpackingit. UnPackTimeInfo ;Unpackdate/timeinfo ;-------------- Fori=6to0Step-1 Ifi<>5Then TempByte=0 Forj=0toPackLen(i) TempByte.Bit0=PackedTime.Bit31 PackedTime=PackedTime<<1 Ifj<>PackLen(i)Then TempByte=TempByte<<1 EndIf Next;j TimeData(i)=BIN2BCDTempByte EndIf Next;i Return
Notethatweworkinthereverseorder;startingwithyears—TimeData(6)—andworkdowntoseconds, TimeData(0).And,insteadofshiftingtotheright,weshifttotheleft.Lastly,sincewesavethedatainthe TimeDataarray,werestorethebinaryunpackedvaluetoBCDwithMBasic’sBIN2BCDoperator. Wetakeaslightlydifferentapproachwiththeweathersensordata,however.WecouldsavetherawA/D readingsforthehumidityandpressuresensors,foratotalof20bits,andsavethemostsignificant12bitsof the13-bittemperaturevalue(resultinginaresolutionof0.0625°C).Thesethreevaluescouldthenbebitpackedinto4bytesjustaswedidwiththetimedata.Thereisaslightproblemwiththisapproach,sincethe barometricpressurereadingmustbecalculatedusingknowledgeofVDD,whichwehavenoroomtosaveif westickwitha4-byterecordlength.WecouldassumeVDDis5.00V,andinfactthetypicalexcursionofVDD from5.00Vresultsinarelativelysmallerrorinthecalculatedbarometricpressure. Asanexerciseintryingadifferentapproach,we’llquantizethecalculatedtemperatureinto0.25°Fsteps,the barometerinto0.01inchesHgstepsandtherelativehumidityinto0.1%steps. Field Temperature(F) BarometricPressure(inHg) RelativeHumidity%
Steps 0.25°F 0.01inchesHg 0.1% Total
Minimum/MaximumValue -40…216 0…4096 0…1000
720
MinimumBitsRequired 10 12 10 32
WeatherStationandDataLogger Ourbitmapistherefore: 3 1
3 0
2 9
2 8
2 7
2 6
2 5
2 4
2 3
2 2
2 1
10bits Temperature°F Byte3
2 0
1 9
1 8
1 7
1 6
1 5
1 4
1 3
10bits RelativeHumidity% Byte2
1 2
1 1
1 0
0 9
0 8
0 7
0 6
0 5
0 4
0 3
0 2
0 1
0 0
12bits BarometricPressureinchesHg Byte0
Byte1
And,whileweareatit,you’llseeadifferentapproachtobitpacking.ThesubroutinePackReadingsquantizesthetemperature,humidityandbarometricpressureandbitpackstheirvaluesintoPackedDatainjust fourlinesofcode. PackReadings ;--------------- IntTemp=ToInt((Fahrenheit+40.0)*4.0) IntHum =ToInt(Rhum*10.0) IntBaro=ToInt(InHg*100.0) PackedData=4194304*IntTemp+4096*IntHum+IntBaro Return
Wedeclarethreewordvariables,IntTemp,IntHumandIntBarotoholdthequantizedvaluesofFahrenheittemperature,relativehumiditypercentageandbarometricpressureininchesHg,respectively.We quantizehumiditybymultiplyingby10andconvertingtoaninteger,andwequantizebarometricpressure bymultiplyingby100andconvertingtoaninteger.Thus,forexample,35.1%relativehumidityisconverted to351,and30.31inchesHgisconvertedto3031.Convertingbacksimplyrequiresustodivideby10or 100.351Isconvertedto35.1afterdividingby10,and3031isconvertedto30.31bydividingby100. Becausethetemperaturemaygobelowzero—andoursimplisticsystemcan’tdealwithnegativenumbers— wefirstbiasthetemperatureupby40degrees,thenmultiplyby4andfinallyconvertittoaninteger.The biasoffsetpermitsustoproperlyencodeanytemperaturebetween–40°Fand+216°F.Forexample,suppose thetemperatureis72.34degrees.Thisisquantizedinto4*(72.34+40),or449.Weconvertbackbyfirst subtracting160anddividingtheremainderby4.Theresultis72.25°F. WecouldusethebitshiftingapproachinPackTimeInfotoinsertthedesiredbitsfromthesethreeinteger valuesintothelongvariablePackedData.Instead,becausethereareonlythreevariablestoadd,wemultiplyeachbyitsbasevalueandaddtoPackedData. Multiplyingby4096isthefunctionalequivalentofshiftingleftby12bits.Likewise,multiplyingby 4194304isequivalenttoshiftingleftby22bits.Let’stakeanexample.WestartwithPackedData=0. 3 1
3 0
2 9
2 8
2 7
2 6
2 5
2 4
2 3
2 2
2 1
2 0
1 9
1 8
1 7
1 6
1 5
1 4
1 3
1 2
1 1
1 0
0 9
0 8
0 7
0 6
0 5
0 4
0 3
0 2
0 1
0 0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
10bits Temperature°F Byte3
10bits RelativeHumidity% Byte2
Byte1
12bits BarometricPressureinchesHg Byte0
We’llassumetherelativehumidityis35.1%,or351whenquantized. 15 0
14 0
13 0
12 0
11 0
10 0
9 0
IntHum=351 8 7 6 1 0 1
5 0
Computing351*4096yields1437696,or%101011111000000000000. InMBasic’sinternal32-bitnumericalcalculationstack,1437696is:
721
4 1
3 1
2 1
1 1
0 1
Chapter28 3 1
3 0
2 9
2 8
2 7
2 6
2 5
2 4
2 3
2 2
2 1
2 0
1 9
1 8
1 7
1 6
1 5
1 4
1 3
1 2
1 1
1 0
0 9
0 8
0 7
0 6
0 5
0 4
0 3
0 2
0 1
0 0
0
0
0
0
0
0
0
0
0
0
0
1
0
1
0
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
WhenweaddthisresulttoPackedData,weseethattherelativehumiditybitshavebeenplacedexactly wherewewantthem. 3 1
3 0
2 9
2 8
2 7
2 6
2 5
2 4
2 3
2 2
2 1
2 0
1 9
1 8
1 7
1 6
1 5
1 4
1 3
1 2
1 1
1 0
0 9
0 8
0 7
0 6
0 5
0 4
0 3
0 2
0 1
0 0
0
0
0
0
0
0
0
0
0
0
0
1
0
1
0
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
10bits Temperature°F Byte3
10bits RelativeHumidity% Byte2
Byte1
12bits BarometricPressureinchesHg Byte0
Unpackingtheweatherdataisthereverseprocess;butwithatwistortwo. UnPackReadings ;------------- IntBaro=PackedData//4096 InHg=(ToFloatIntBaro)/100.0 mbars=(InHg-ElevCor)/mBarToInHg IntTemp=PackedData/4194304 Fahrenheit=(ToFloat(IntTemp-160))/4.0 IntHum=(PackedData/4096)//1024 Rhum=(ToFloatIntHum)/10.0 Return
Rememberthatthe/operatorreturnstheintegerquotientand//returnstheintegerremainder.Ifthedivisor isoftheform2N,theremainderisthevalueresultingfrommaskingoffallthebitstotheleftoftheN-1th bit.HencethestatementIntBaro=PackedData//4096returnstherightmost12bits(bits0…11)of PackedData,since4096=212. Likewise,ifthedivisorisoftheform2N,thequotientisthevalueyougetbymaskingoffallbitstotheright oftheN-1thbitandrightjustifyingtheresult.Hence,thestatementIntTemp=PackedData/4194304 returnstheleftmost10bits(bits22...31)ofPackedDataandrightjustifiestheresultsince4194304=222. Only10bitsarereturnedbecausePackedDataisa32-bitvariable. Toextractthemiddle10bits,wejustcombinethedivisionandremainderoperators.First,weextractthe leftmost22bitswith(PackedData/4096),thereforeleavinguswiththetemperatureandhumidityright justifiedina32-bitbufferinMBasic’sinternalmathematicstack.Wethenextracttherightmost10bitsof thisresiduewiththeremainderoperator//1024.Weuse1024,or210,becausewewishtoextract10bits. Theremainderofthesubroutineconvertstheextractedintegervaluestofloatingpointnumbersbydividing bythequantizationconstantweusedinsubroutinePackReadings.InthecaseoftheFahrenheittemperature,wealsosubtractthebiasvalue. Wenowreturntosavingandreadingthepackeddata.BeforecallingSavePackTime,wehaveupdated RecordNotothenextvalue.UsingthetechniqueswelearnedinChapter18,wewritethefourbitsof PackedTimetotheserialEEPROM. SavePackTime ;---------- MCtrlB=MRCtrl+MAdr0 ;Writetoaddressedmemory MemAdr=RecordNo*2*WriteInc I2COutMDta,MClk,ErrorWMsg,MCtrlB,MemAdr,| [PackedTime.Byte3,PackedTime.Byte2,| PackedTime.Byte1,PackedTime.Byte0] Pause5 Return
722
WeatherStationandDataLogger Likewise,wesimplywritethefourbytesofPackedDatausingthesametechniques.Weadvancethebyte addressvariableMemAdrasdiscussedearlier. SavePackData ;---------- MCtrlB=MRCtrl+MAdr0 MemAdr=RecordNo*2*WriteInc+WriteInc I2COutMDta,MClk,ErrorWMsg,MCtrlB,MemAdr,| [PackedData.Byte3,PackedData.Byte2,| PackedData.Byte1,PackedData.Byte0] Pause5 Return
Theremainingnewpartsofthecodeinvolvewritingtheunpackeddate/timeandweatherinformationtothe serialport. WriteUnpackedWxData ;----------------- HSerOut[RealFahrenheit\2,”F”,9,| RealRhum\1,”%RH”,9,RealinHg\2,”inHg”,13,10] Return WriteUnpackedTime ;---------------- HSerOut[Dec2(BCD2BINHours)\2,”:”,| Dec2(BCD2BINMinutes)\2,”:”,Dec2(BCD2BINSeconds)\2,9] HSerOut[““,Dec2(BCD2BINMonth)\2,”/”,| Dec2(BCD2BINDate)\2,”/”,Dec2(BCD2BINYear)\2,9] Return
BoththesesubroutinesmimictheonesweusedtowritefromthefreshlyreaddatainPrograms28-2and124andneednofurtherexplanation. Program28-2alsoprovidesanoptionalspecialformatdataoutput,throughanoptionalcalltoWxToOscope subroutine. WxToOscope ;outputtoIDE’sOscilloscopeutility ;------------ TempLong=ToInt(Fahrenheit*10.0) j=0 GoSubOutputToScope TempLong=ToInt(inHg*10.0) j=1 GoSubOutputToScope TempLong=ToInt(RHum*10.0) j=2 GoSubOutputToScope Return OutputToScope ;------------- HSerOut[Chan1+j,TempLong.Byte0,TempLong.Byte1,| TempLong.Byte2,TempLong.Byte3] HSerOut[13] Return
MBasic’sintegrateddevelopmentenvironmentincludesautilityprogram,Oscilloscope,accessedfrom theToolsmenu.AlthoughOscilloscopeisundocumentedinMBasicUser’sGuide,itisdocumentedina downloadableApplicationNoteatBasicMicro’swebsite.DatawrittentotheOscilloscopeutilitymustbe anintegertypelong.Dataiswrittenfromtheserialport,andstartswitha“channelnumber,”whichranges from15to30andisfollowedbythe4bytesofthelongvariable,andendswithacarriagereturn(13).Receivedlinesnotstartingwithavalidchannelnumberareassumedtobetextmessagesandaredisplayedin Oscilloscope’smessagewindow.Oscilloscopeplotseachchannelwithadifferentcolor.
723
Chapter28 SinceOscilloscopeplotsonlyintegervalues,we’ll needtoscalethefloatingpointdata,aswellas convertingittointeger—otherwiseallwewouldsee areintegerstepsintemperature,relativehumidity andbarometricpressure.Toprovidebetterscales, therefore,we’llmultiplythetemperature(inFahrenheit)by10;multiplytherelativehumiditypercentage by10andthebarometricpressureby10.Thisallows ustoplotascaleof0…1000andseeallthreesensor outputsononescreen.Figure28-5showstheresult. Figures28-6and28-7showhowadjustingtheverticalscaleandoffsetallowyoutoexpandotherwise smallchangesintheoutputvalues.
Figures28-6:Expandedviewofbarometricpressure andrelativehumidity.
Figure 28-5: Temperature, relative humidity and barometricpressuredisplayedonoscilloscope.
Figure28-7:Expandedviewoftemperature.
BeforewewrapupthisverylongChapter,let’slookattheoutputformat.First,welettheprogramrunand outputthetime/dateandweatherdataonceeveryminute. 15:49:0501/18/04Sun18-Jan-2004 Temp73.17F22.87CRel.Hum.36.5%Barometer979.2mbar(uncor)29.26inHg(cor) 15:50:0001/18/04Sun18-Jan-2004 Temp73.06F22.81CRel.Hum.36.3%Barometer980.3mbar(uncor)29.29inHg(cor) 15:51:0001/18/04Sun18-Jan-2004 Temp72.94F22.75CRel.Hum.36.2%Barometer981.8mbar(uncor)29.34inHg(cor) 15:52:0001/18/04Sun18-Jan-2004 Temp72.89F22.71CRel.Hum.35.8%Barometer981.8mbar(uncor)29.34inHg(cor) 15:53:0001/18/04Sun18-Jan-2004 Temp72.83F22.68CRel.Hum.35.8%Barometer981.8mbar(uncor)29.34inHg(cor)
Now,wesendthecommandtooutputthesaveddata,an“o”or“O”followedbyacarriagereturn(enter). o 0 1 2 3 4
15:49:05 15:50:00 15:51:00 15:52:00 15:53:00
01/18/0473.00F 01/18/0473.00F 01/18/0472.75F 01/18/0472.75F 01/18/0472.75F
36.5%RH29.25inHg 36.2%RH29.28inHg 36.1%RH29.33inHg 35.7%RH29.33inHg 35.7%RH29.33inHg
724
WeatherStationandDataLogger Weseethedatamatchestherealtimedata,exceptforvariationsduetorounding. Anotherrealtimereportarrives. 15:54:0001/18/04Sun18-Jan-2004 Temp72.78F22.65CRel.Hum.36.0%Barometer983.9mbar(uncor)29.40inHg(cor)
Again,wesenda“o”anddumpthesaveddatatotheserialport. o 0 1 2 3 4 5
15:49:05 15:50:00 15:51:00 15:52:00 15:53:00 15:54:00
01/18/0473.00F 01/18/0473.00F 01/18/0472.75F 01/18/0472.75F 01/18/0472.75F 01/18/0472.75F
36.5%RH29.25inHg 36.2%RH29.28inHg 36.1%RH29.33inHg 35.7%RH29.33inHg 35.7%RH29.33inHg 36.0%RH29.39inHg
Ifwekeepthedatasaveintervalatoneminute,wehavecapacityfor8191minutes,or5.68days.Thattime, ofcourse,canbeextendedproportionallybylengtheningthetimebetweendatasaves.(We’llseeanapproachsuggestedintheIdeasforModificationstoProgramsandCircuitsthatmightdoublethedatasave capacity.) Let’sseehowthesaveddatalookswhenexaminedoverseveraldays.Figure28-8plotsabouttwodays worthofcompressed/decompresseddata.Thedatawastakeninmybasementworkshopandshowsthedrop intemperatureatnightwhenthecutbackthermostatdropsthefirstfloortemperature.Theriseinindoorrelativehumidityonthe18thisaresultoffreezingrainandhighoutdoorhumidity. Figure28-9comparestwodaysofthebarometricpressureIrecordedwiththeNationalWeatherService’s dataforDulles,VA,about10milesfrommyhouse.AsreflectedinFigure28-10,myMPX6115appearsto bebiasedlowbyabout0.17inchesHg.It’sasimplemattertoaddanadditional0.17inchesHgoffsettothe reportedvalues.Thebiasisnotuniform,ofcourse,soanevenbettercorrectionwouldbeonethatincludes bothinterceptandslopefactors,asshowninFigure28-11.Thecorrectedpressureformysensoris: PCORRECTED = 1.02959 PRAW − 0.60568 WherebothPCORRECTEDandPRAWareininchesMercury,andPRAWiscorrectedforaltitude.Thiscorrection equationisvalid,ofcourse,onlyformyMPX6115,and,evenwiththisunderstanding,itwouldbewiseto collectmorethantwoday’sdatabeforeacceptingthisequation.
Figure28-8:Recordedweatherdata.
Figure28-9:Barometricpressurecomparison.
725
Chapter28
Figure 28-10: Error plot; MPX6115 versus NWS data.
Figure28-11:LinearregressionfittocorrectMPX6115 reading.
Notethatthecorrectionsareappliedtoaveraged data.Figure28-12showsthereading-to-reading variationmakesanyindividualreadingsuspect.
•
•
•
•
30.2
30.1
Barometric Pressure (inches Mercury)
IdeasforModificationstoPrograms andCircuits
30.3
30.0
Program28-2usestime-basedcapture.Since 29.9 weknowthestarttimeandsinceeachcapture occursatconstantintervals,isitnecessaryto 29.8 savethetime/date?Instead,allweneedsaveis MPXA6115 Barometric Pressure Sensor 30 Minute Smoothed Data versus Raw Readings thestartdate/timeandthesaveinterval.From 29.7 thatinformation,wecanreconstructtheeach 29.6 sampledate/time,withouterror.Nothavingto 20 Jan 2004 21 Jan 2004 21 Jan 2004 22 Jan 2004 savethetime/datemeanswemaysavetwiceas 12 15 18 21 0 3 6 9 12 15 18 21 0 3 6 Hour manyweatherdatapoints.Whatadditionalcode doyouneedtoaddtoreconstructthetime/date? Figure28-12:Raw1-minuteand30-minutesmoothed averagevalues. Howwouldyoudealwiththedifferingmonth lengths?Howdoyoudealwithleapyear? Thealternativetotime-basedcaptureisevent-basedcapture.Forexample,savethetime/dateand weatherdataeverytimethetemperaturechangesmorethan1degreefromitspreviousvalue.How wouldyouchangeProgram28-2toimplementanevent-basedcapture?IfProgram28-2isevent-based, wenowmustsavethetime/dateinformation,asthesaveperiodswillnotbeatuniformintervals. Thereareapproximately31.6×106secondsinaleapyear.Itonlytakes25bits(225isapproximately 33.5×106)tocountsecondsfrom00:00:0001Jan.InsteadofbitpackingthetimeaswedoinProgram28-2,whichrequires32bits,howwouldyouimplementasecondscounter?Howwouldyousave theyearinformation?Howwouldyoudealwithextractinghours,minutes,days,andmonthsfroman elapsedsecondscounter?Howmightyoudealwithyearrollover? Aretherebetterwaysofsavingtheweatherinformation?Forexample,savingtherawA/Dreadings? HowmightyoumodifythebarometerA/DreadingtoreflectchangesinVDD?Woulditbepossibleto 726
WeatherStationandDataLogger
•
• •
• •
createafictitious10-bitA/DvaluethatassumesVDDis5.000VandyieldsthesamecomputedbarometricpressureastheactualA/DreadingwithacorrectionforVDD? Bitpackingisafirstordercompressiontechniqueandprovidesreasonablereturns,inourexample,for modestprogrammingdifficulty.Wouldmorecomputationallyintensivedatacompressionwork?For example,supposethetime/dateinformationwasdeltaencoded;insteadofrepeatingtheunchangedparts ofthedateandtimewitheveryrecord,wemightjustrecordchanges.Thefirstrecordcontainsthefull time/date,whilethenextrecordcontainsonlythechangedvaluesfromthepriorrecord,andsoforth. Wouldthesameapproachworkfortheweatherdata?Deltaencodingcanbequiteefficient,butitlikely forcesustovariablelengthrecords,eithervariablebytelength,orevenvariablebitlength.Howwould youstructureavariablelengthrecordstructurewithintheconfinesofaAT24C512serialEEPROM? Toprovideaninteractivemenudrivensystem,mergetheideasofProgram9-3withthoseofthischapter. AnLCDdisplaywould,ofcourse,makeauser-friendlierweatherstation.Whichparametersshouldbe reported?Toreducethereading-to-readingvariationinthebarometricpressureandrelativehumidity, shouldthesevaluesbeaveraged?Ifso,over whatperiod? Howwouldyouaddexternaltemperature andhumiditysensors?Howwouldyou expandthememory? Howwouldyougoaboutreadingthe MPX6115sensorwithimprovedresolution withoutahigherresolutionA/Dconverter? Itispossibletoderiveasecondvoltage fromthe4.096Vprecisionreference throughasecondop-amprunningwitha gainoflessthan1.00,andusethatasVREF–. Figure28-13isonepossiblecircuit.All resistorsshouldbe1%toleranceorbetter. IfVREF+is4.6085VandVREF–is3.5853V, towhatresolutionmaytheMPX6115be read?Whatisthemaximumandminimum absolutepressurerange? Figure28-13:Possibledual-voltagereferencesource.
References [28-1]
HoneywellInternational,Inc.,ThermosetPolymer-basedCapacitiveSensors,ApplicationSheet,(undated)availableathttp://www.honeywell.com/sensing. [28-2] Humirel,Inc.,TechnicalDataRelativeHumiditySensorHS1100/HS1101,DocumentHPC001,Rev.7, June2002,availableathttp://www.humirel.com/Humidity_temperature_sensors.php [28-3] Humirel,Inc.,TechnicalDataRelativeHumidityModuleHM1500,DocumentHPC009,RevH.,October2001,availableathttp://www.humirel.com/Humidity_temperature_sensors.php. [28-4] HoneywellInternational,Inc.,HumiditySensorHIH-3610Series,(undated),availableathttp://www. honeywell.com/sensing. [28-5] HoneywellInternational,Inc.,HumiditySensorHIHSeries,(undated),availableathttp://www.honeywell.com/sensing. [28-6] MotorolaSemiconductor,SensorDeviceDataBookDL200/D,Rev.5(Jan003),availableathttp://ewww.motorola.com/files/sensors/doc/data_lib/DL200.pdf.Thisdocumentcontainsthedatasheetforthe MPX6115Aseriespressuresensors,aswellasotherusefulinformation.
727
Chapter28 [28-7]
DallasSemiconductorCorp.divisionofMaximIntegratedProducts,Inc.,DS1624DigitalThermometer andMemory,(July20,1999)availableathttp://pdfserv.maxim-ic.com/en/ds/DS1624.pdf. [28-8] NationalSemiconductorCorp.,NationalSemiconductor’sTemperatureSensorHandbook,2ndEd. (undated). [28-9] BasicMicro,Inc.,ApplicationNote:Oscilloscope,(undated),availableathttp://www.basicmicro.com/ downloads/docs/oscope%20app%20note.pdf.
728
29
CHAPTER
Migratingfromv5.2.1.xto5.3.0.0 andtheUndocumentedMBasic Migratingfromv5.2.1.xto5.3.0.0 Inearly2005,BasicMicroplanstoreleaseMBasicversion5.3.0.0.I’vebeengivenaccesstoaprerelease versionof5.3.0.0andtheprintedprogramlistingsinthisbookarecompatiblewith5.3.0.0.TheCD-ROM containsboth5.2.1.1and5.3.0.0programversions. Version5.3.0.0fixesanumberofsmallbugsinearliereditions,butalsoaddsnewfunctionsandsignificantly modifiesthewaymanyexistingfunctionsoperate.I’veidentifiedmanyofthesechangesthroughoutthis bookandthischaptersummarizesthosediscussionsinonelocation. ADIN16—ADIN16isanewhardwarecommand.ADIN16readsa10-bitA/Dvalueenoughtimestocreatean averaged16-bitresult,therebyapproximatinga16-bitADconverterundercertainconditions(thoughnot perfectly).ADIN16’ssyntaxisidenticalwithADIN.Program11-1AprovidesanexampleofADIN16usage. MiddleMultrenamedFractionalMultiply—ThefunctionMiddleMulthasbeenrenamedFractionalMultiply. Changesinfloatingpointoperators—Thespecialoperatorsforfloatingpointarithmetic(FMUL,FDIV,and soon.)aredeletedandreplacedwithnormal+,–,/and*operators. • FADDisnow+ • FSUBisnow– • FMULisnow* • FDIVisnow/ • FNEGisreplacedbyprefixingthevariablewitha–sign Inaddition,TOINT,TOFLOATandFLOATTABLEarenewoperators: • FLOATisrenamedToFloat • INTisrenamedToInt • FloatTableisusedtodefineafloatingpointdatatablejustlikeByteTableisusedforbytelengthdatatables. It’snolongernecessarytoincludetheFLOATconversionoperatorwhendefiningconstants;insteadthenew operatorFConisusedtodefinefloatingpointconstants: v.5.2.1.1: FloatingConstant Con Float1.00 v.5.3.0.0: FloatingConstant FCon1.00 User-definedfunction—User-definedfunctionsarenowsupportwithbothparametersandareturnedvariable. MyFunction[var1,var2,var3...]{,returnval} ;Functioncode. return{returnval}
Tocallauser-definedfunctionuseGoSub:
GosubMyFunction[var1,var2,var3...]{,returnval}
729
Chapter29 Here’sasimpleexampleshowinghowtodefineanduseauser-definedfunction: EX FX GX HX QX
Var Var Var Var Var
Word Word Word Word Word
Clear Main EX=4 FX=5 HX=EX*FX ;HX=20 GX=0 ;GX=0 GoSubMyFunction[3,4],GX ;GX=20 GoSubMyFunction[30,40],GX ;GX=1200 GoSubMyFunction[128,256],GX;GX=32768 GoSubMyFunction[HX,16],QX ;QX=320&GX=320 GotoMain ;DefineFunctionPrototype ;------------------------MyFunction [EX,FX] GX=EX*FX ReturnGX
Severalpointsshouldbenoted: • Eitherplacethefunctiondefinitionattheendofthecode,or“jumparound”thefunctiondefinitionwitha GoTooperation,sothatthefunctioncodeisnotexecutedexceptasaconsequenceoftheGoSubstatement. • Variablesusedinthefunctiondefinitionarestillglobalvariables.Consequentlyanychangesmadeto anyvariableinthefunctionstillhaveglobalvisibilitytotherestofyourcode. • Aswithbuilt-infunctions,argumentsmaybevariablesorconstants. • Thelimitonthenumberofcommandargumentsisthesizeofthestackcommand.Thedefaultstack sizeis17,whichalsohappenstobethelargestpermittedstacksize. • ThereisnoerrorcheckingonthenumberofargumentsintheGoSubMyFunctionoperation.Ifyou usefewerargumentsthanthenumberinthefunctionprototypedefinition,theunusedargumentsareundefined(theycouldbeanyvalue);ifyouusemoreargumentsthaninthefunctionprototypedefinition, theextravaluesarejunked. PICparameterheader—Thestandardheaderisnolongeracceptedandmustbesetintheconfigurationbox. ;Versionsearlierthan5.3.0.0 CPU=16F876 MHZ=20 CONFIG16250
IfyouloadaBASfilecreatedinanearlierversion,MBasic5.3.0.0willalertyouandaskifitshouldautomaticallyconvertthefiletothenewversion.Answerthedialogbox“Yes”andyouwillbepresentedwith theprogramconfigurationdialogboxsothatyoucanconfirmthesetupconstants.Theprincipalchangein thedialogboxfromearlierversionsisthatthePIC’sclockfrequencymustbeenteredinHz,notMHz.A seriesofbuttonspredefinethecommonclockspeeds,forexample,pressingthe“20MHz”buttonenters 20000000intotheclockspeedbox.Or,youmayenteracustomspeeddirectly. ThenewheaderinformationisenteredasacommentlineatthetopoftheBASfile,butisnotdisplayedin MBasic’scodeeditor.TheheadermaybeseenifyouopenaBASfilewithatexteditor: ;%CONFIG%16F877A$1312d00$3f3a$0$0$0$0$0$0$0$0 $0$0$0$0$0$0$0$0
730
Migratingfromv5.2.1.xto5.3.0.0andtheUndocumentedMBasic 32-bitfunctionparameters—Earlierversionslimitedsomefunctionarguments,to16-bitvalues.Withversion5.3.0.0,allbuilt-infunctionargumentsmaynowbeupto32bits. Timingparameterchanges—Mosttimingparametersarenowinmicroseconds,notmilliseconds.This changeisrelatedtothe32bitargumentextension,andpermitsamaximumtimeintervalof232µs,or about4,295seconds.Specifically: • Sound—durationisinµsnotms. • Sound2—durationisinµsnotms. • SPMotor—delaytimeisinµsnotms. • DTMFOut—on-timeandoff-timein0.5µsintervalsnotms. • DTMFOut2—on-timeandoff-timeinµsnotms. • FreqOut—durationin0.5µsintervalsnotms. • Pause—notchanged–durationremainsinms. • Pauseus—accepts32-bitarguments • PulsIn—Resolutionisunitsteps,withaminimumof16steps.Eachunitstepis7machinecycles, or1.4µsfora20-MHzclock.(Thisintervalcorrespondstominimummeasurabledurationofabout 22µs.)Thereturnedvalueisthedurationinunitsteps,asa32-bitvalue.Thedefaulttimeoutisstill 65535.However,thetimeoutvalueisintermsofunitstepintervals,sothemaximumtimeoutis 65535*unitstepduration. • PulsOut—durationinµs;maximumvalueis232µs. • PWM—cyclescanbeupto232(dutyremains0…255). • RCTime—Resolutionisunitsteps,witheachstep17machinecycles,or3.4µsfora20MHzclock. (Theminimummeasurabledurationis1unitstep.)Thereturnedvalueisdurationinunitsteps,asa 32-bitvalue.Thedefaulttimeoutisstill65535.However,thetimeoutvalueisintermsofunitstep intervalssteps,sothemaximumtimeoutis65535*unitstepduration. • Sleep—maximum232seconds. • HPWM—remainslimitedbyhardware—nochangefrom5.2.1.1. Optionalhalf-stepmotoroperation—AnewcompilerdirectiveoptionallyswitchesSPMotortohalf-step mode.Sinceitisacompile-timeoption,youcan’tswitchbackandforthduringprogramexecution. ;Toswitchtohalfstepmodeaddthistoyourprogram. SPMOTOR_HALFcon0 ;canmakethisconstantanyvaluesinceitsimplyhastob ;defined. ;Whenusinghalfstepmodeonecycleequals8halfsteps.
NewLCDInitcommand—AshortcuttoLCDinitializationisaddedtoversion5.3.0.0:
LCDINITRegSel\Clk{\RdWrPin},LCDNib
LCDInitrunstheinitializationspecifiedbyHitachiforitsLCDcontrollers,whichhasbeenadoptedas thedefactoLCDcontrollerstandard.YounolongerneedtheLCDINIT1,LCDINIT2argumentsinthefirst LCDWRITEcommandifyouuseLCDInitfirst.Theolderinitializationtechniquecontinuestoworkinver-
sion5.3.0.0. EnableHSerialcompilerdirective—AnewEnableHSerialcompilerdirectiveisrequiredbeforeusing HSerInorHSerOut.OtherwiseHserOutandHSerInareunchanged. NewSerInandSerOutconstants—ThefunctionconstantsassociatedwithSerInandSerOuthavebeen replaced.(Theoldconstantsarenolongerrecognized.)
731
Chapter29 Sense Ltr N
Fcn Normal
I
Inverted
Mode Ltr Fcn Blank Normal O
Open(Bus mode)
DataBits Ltr Fcn 7 7data bits 8 8data bits
Parity Ltr N
Fcn None
E
Even
O
Odd
StopBits Ltr Fcn 1 1stopbit 2
Speed (withleading_)
_300 _600 2stopbits _1200 _2400 _4800 _7200 _9600 _12000 _14400 _16800
_19200 _21600 _24000 _26400 _28800 _31200 _33600 _36000 _38400 _57600
Youconstructtheappropriateconstantbyconcatenatingthesixelementsinthetable.Forexample,thebaudmodeconstantforinverted,8databits,noparity,1stopbit,standardmodeisI8N1_9600.(Normally,you willusethestandardoutputconfiguration,thatis,notopencollector,wheretheconfigurationcharacterisa blank,soinmostcasesyourconstantwillhavefiveelements,notsix.) Stacksizeandlocation—Version5.3.0.0handlesthestackdifferently,andbydefaultassignsallBank0 RAMtothestack.ThemainimplicationofthisisthatbydefaultnouservariablewillbeinBank0and henceanyassemblerreferencetovariablesmustdealwithbankselection.(Althoughnotitspurpose, thisenforcesgoodprogrammingpractice.)Alternatively,youmaymanuallydefinethestacktoasmaller sizetofreeupBank0RAM.ThesecondchangeisthatstacksizeisstatedintypeLong(4bytes), whereasin5.2.1.1stackisstatedintypeWord(2bytes). Tochangethestackallocation,usethestackcompilerdirective.Forexample,toallocate40bytesofstack space,usethefollowingcompilerdirective: STACK=10
NewFunctionGetTimer1—thefunctionGetTimer1readsthetimer1high(TMR1H)andlowbytes(TMR1L) andreturnsthevaluesinasinglewordvariable.(Thisfunctionisinversion5.2.1.1butisnotdocumented.) NewModesforShiftIn&ShiftOut—TheShiftInandShiftOutfunctionshaveeightnewmodeconstants:
HighSpeed (allnewin5.3.0.0)
SlowSpeed (allnewin5.3.0.0)
NormalSpeed {}indicatesbackwards compatibleforolderversions
ModeConstant FASTMSBPRE FASTLSBPRE FASTMSBPOST FASTLSPOST SLOWMSBPRE SLOWLSBPRE SLOWMSBPOST SLOWLSBPOST MSBPRE {MSBFIRST} LSBPRE {LSBFIRST} MSBPOST LSBPOST
BitOrder MSBfirst LSBfirst MSBfirst LSBfirst MSBfirst LSBfirst MSBfirst LSBfirst MSBfirst LSBfirst MSBfirst LSBfirst
732
Clock/Data Relationship Datavalidon leadingedge Datavalidonfalling edge Datavalidon leadingedge Datavalidon leadingedge Datavalidon leadingedge Datavalidon leadingedge
Speed (Machine Speed Cyles) (With20MHzclock)
25
200KHz (5µs/bit)
100
50KHz (20µs/bit)
50
100KHz (10µs/bit)
Migratingfromv5.2.1.xto5.3.0.0andtheUndocumentedMBasic Thesemodeconstantshavethesamebitorderandbittimingsequenceasthenon-“FAST”ornon-“SLOW” prefixedconstants,butwithdifferentoutputspeeds.Theoutputspeedisapproximately50,100and200KHz withSlow,NormalandFastmodesona20MHzPICbutproportionallyslowerwithslowerclocks. TwonewaliasconstantsassociatedwithShiftInandShiftOutaredefinedinversion5.3.0.0,MSBFIRST andLSBFIRST,whicharethesameasMSBPREandLSBPRE,respectively.Notethatthereisnoequivalent speed-upforone-wiresupport. Pre-definedmacrosinISRASM—Version5.3.0.0removestherestrictionpreventingMBasic-definedassemblermacrosinsideanISRASMblock. Newdefinitionof_MHZ—Theassemblerconstant_MHZwaschangedfromabyte-lengthrepresentation oftheprocessorclockinMHztoatypeLongdefiningtheclockfrequencyinHz.A20MHzclockassemblesas_MHZEQU20inversion.5.2.1.1.butas_MHZEQU20000000inv.5.3.0.0. Redefinedorderofprecedence—Version5.3.0.0’sorderofprecedenceisrevisedtomorecloselyalignwith otherlanguages. Order 1st(Highest) 2 3 4 5 6 7 8 9(Lowest)
MBasic5.3.0.0 DEC2BCD,BCD2DEC,TOINT,TOFLOAT,NOT,~,ABS, SIN,COS,-,DCD,NCD,SQR,RANDOM REV,DIG MAX,MIN *,**,*/,/,// +,<<,>> <,<=,=,>,>=,<> &,|,^ AND,OR,XOR
MBasic5.2.1.1 NOT,ABS,SIN,COS,–(NEG),DCD,NCD,SQR, Random,FNEG,INT,FLOAT,DEC2BCD,BCD2DEC <,<=,=,>,>=,<> AND,OR,XOR REV,DIG <<,>> MAX,MIN &,|,^,&,|,^ *,**,*/,/,//,FMUL,FDIV +,–,FSUB,FADD
Newassembler—Beginningwithversion5.3.0.0,MBasicnolongerusesMicrochip’sMPASMassembler andlinker,insteadusingGPASM.Asofthetimethischapteriswritten,theGPASMassemblerdoes notacceptcomputationsinbanksel.Hence,theconstructionbankselvariable&0x1FFfails;but bankselvariableworksandprovidescorrectbanking.Also,bankselvariable+1toreachthe upperbyte(wherevariableistypeword)alsofails.Likewisebanksel.0fails—theargumentcan’tbe adirectnumericalvalue—butwecandefinenewnamedconstantzerocon0andthenusebanksel zero. Newreservedwords—newreservedwordswithversion5.3.0.0include:
P0…P31 ADIN16 ToInt ToFloat GetTimer1
[ATOMpinnames] [newfunction] [renamedconversionoperator] [renamedconversionoperator] [undocumentedfunction]
UndocumentedMBasic Whilewritingthisbook,IfoundanumberoffeaturesthatarenotcoveredinthecurrentUser’sGuide. AlthoughI’vediscussedmostoftheseundocumentedfeaturesinearlierchapters,it’susefultohaveacentral repositoryofthe“UndocumentedMBasic.”BasicMicroisrewritingtheMBasicUser’sGuidetoinclude thismaterialaswellastoreflectversion5.3.0.0changes. ThepagereferencesinthischapteraretotheUser’sGuide,revision5.3,released2003.
733
Chapter29 Function
Page
Summary
SystemSetup— CompileOptimize Size/Speed
18
Feature—CompileOptimizeSize/Speed—AddedafterManualWritten
TheSystemSetupdialogboxdiscussiondoesnotreflectthecurrent compilerrelease,asitomitstheCompilerOptimizeSize/Speedselection.Figure29-1showsthenewoptimizationselectionboxatthe bottom.Youmayselectspeedorsizeoptimization. What’sthedifferencebetweenoptimizingforspeedorsize?Programcompiledwith“OptimizeforSpeed”runabout15–25%fasterthanthesame programcompiledwith“OptimizeforSize.”Forlargeprograms,“Optimize forSize”consumesroughly40%to50%lesstokenmemory.Theexact numbersdependonthemixofprogramstatementsused.Figures29-2and 29-3showspeedversusmemoryrequirementsfortwosampleprograms compiledwithversion5.2.1.1.Figure29-2isbaseduponaprogramwith repeatedcopiesofonesimplemathematicalcomputation—multiplyingtwo bytesandstoringtheproductinathirdbytenumber.Figure29-3isbased uponaprogramwithrepeatedinstancesof10mathematicaloperations, includingfloatingpoint,squarerootandtrigonometriccomputations.The dataisfroma16F877witha20MHzresonator. InreadingFigures29-2and29-3,don’tforgetthattherequiredprogram memoryisthesumofthetokenmemoryandthelibrarymemory.BroadFigure 29-1: Compiler optimization lyspeaking,therequiredlibrarymemoryisafunctionofhowmany differenttypesofMBasicfunctionsandoperationsyourprogramuses, optioninTools|SystemSetupDialog Box. whiletherequiredtokenmemoryisproportionaltothenumberofprogramstatements.“OptimizingforSize”tradesoffspeedandalargerlibrarysizeforsmallertokenmemory consumption.Thus,averyshortprogrammayactuallyconsumemorememoryaswellasrunslowerunder “CompileforSize”comparedwith“CompileforSpeed.”Largerprogramsusuallydon’tshowthisanomaly. Function
Page
Summary
LineContinuation Symbol|
42
Anundocumentedfeatureisthe“linecontinuationsymbol,”|
Theverticalbar|characterpermitslonglinestobecontinuedifitappearsbeforetheparagraphbreakwhen enteringprograms.Althoughusedinsomesampleprograms,itisneverformallydocumentedintheUser’s Guide.Anexampleofthelinecontinuationsymbolis:
HSerOut[“Thisisgoingtobeaverylongline“,Deci,| ”continuedintotwolines”,13] Function
Page
Summary
ArrayVariable Usage
48
Reminderthatarrayvariablesarenotcheckedforboundingerrors.
734
Migratingfromv5.2.1.xto5.3.0.0andtheUndocumentedMBasic
Figure 29-2: Memory versus speed for compiler optimization selection; simple program.
Figure 29-3: Memory versus speed for compiler optimization selection; complex program.
735
Chapter29 Indealingwithvariables,threecautionsshouldbekeptinmind: 1. Itispossibletoaddressavariableasanarray,evenwhereitisnotdeclaredasanarray,withoutany compilererror; 2. Thecompilerperformsnoboundschecking,soit’spossibletoindexintoanarrayoutsideitsdeclared dimension.(ThisalsoapplieswhenoutputtingastringwiththeStrmodifier;noboundscheckingis performed.) 3. It’spossibletouseanarrayasasinglevariable.Nowarningmessageof“missingsubscript”isissued. Thefollowingcodesampleshowserrors1and2,neitherofwhichresultsinacompilerorrun-timeerror.It alsoillustratespoint3,whichisnotnecessarilyanerror,butratheracompilerfeaturethatpermitsgreater flexibilityincertainprogrammingsituations.However,ifyoureallymeanttousethearrayasanarraybut simplymadeanerror,thecompilerwillnotflagtheambiguoususage. AA ZZ i Main
Var Var Var
Byte Byte(11) Byte
ZZ=99 Fori=0to20 ZZ(i)=i Next
;treatZZlikeassinglebytevariable ;indexingbeyondthedeclaredsizeofZZ
Fori=0to10 AA(i)=i Next GoToMain End
;treatingAAlikeanarray
AsyoushouldunderstandfromChapter14,overrunningthearrayboundariesresultsinaccessingregister filesnotreservedforthatarray.Itmayevencauseyourprogramtoaccessspecialpurposeregisterfiles, whichareassuredlynotintendedforgeneral-purposedatastorage.Ifyourprogramusesarrayvariablesand youexperiencestrangedataresults,orevenprogramfreezesorrestarts,agoodplacetolookfortroubleis withyourarrayindexing. Function
Pages
Summary
Command Modifiers
53–55
Omitsmanycommandmodifiers;alsocommandmodifiersmaybeused asstand-alonefunctions.
Chapter9providesanextensivediscussionoftheundocumentedcommandmodifiers,includingasample programtodemonstratehowthesameoutputappearswithdifferentformatting.Thefollowingtable,reproducedfromChapter9,summarizesthedocumentedandundocumentedcommandmodifiers. Modifier Family
Decimal (Dec) (and others)
Modifier Dec Dec1 Dec2 Dec3 Dec4
BaseValue
Output 123 3 23 123
123 123
736
Comments ThemodifierDecnwherenisanumber determinesthenumberofdigitstodisplay, startingfromtheright.Notethatspecifying moredigitsthanrequiredtodisplaythe numberdoesnotcauseblanksorleading zeros.Decwithoutan“n”displaysalldigits ofthenumber. Thissame“addn”todefinedisplayed digitsappliesto: Dec,sDec Hex,iHex,sHex,isHex Bin,iBin,sBin,isBin
Migratingfromv5.2.1.xto5.3.0.0andtheUndocumentedMBasic Modifier Family Decimal (Dec) andOthers
Real (floating point numbers)
Modifier Decx\2 Decx\3 Decx\4 Decx\5 Decx\6
BaseValue
SignedHex Indicated SignedHex Signed Binary Indicated Signed Binary
123 123 0123 00123 000123
x=123
Real
123.4559936523
Real1 Real2 Real3 Real4 Real4Var\1
3.4559936523 23.4559936523 123.4559936523 123.4559936523 123.4 123.45 123.455 123.4559 –123 123 7B –7B $7B $-7B
123.456
Real4Var\2 Real4Var\3 Real4Var\4 Signed Decimal
Output
sDec sHex
isHex
sBin
–123 +123 7B –7B 7B –7B 1111011 –1111011 1111011
1111011 –1111011 %1111011
isBin
Comments Leadingzeroscanbeaddedbyappending a\nmodifiertopadwithleadingzerosto nplaces. Thissame“\n”todefineleadingdigits appliesto: Dec,sDec Hex,iHex,sHex,isHex Bin,iBin,sBin,isBin Extradigitsareresolutionerror.Withoutany modifier,wegetthefull14characters. Usedwithoutanythingelse,Realnworks thesamewayasforDec.However,n appliesonlytodigitstotheleftofthe decimalpoint. Tosetthedigitsdisplayedontherightof thedecimalpoint,usethe/nsyntax.(Varis atypeLong)
Ifvalueis<0,–signappended;no+sign if>0. Ifvalueis<0,–signappended;no+sign if>0. Ifvalueis<0,–signappended;no+sign if>0.Minussignappearsafterthe$hex indicator. Ifvalueis<0,–signappended;no+sign if>0. Ifvalueis<0,–signappended;no+signif >0.Minussignappearsafterthe%binary indicator.
It’salsopossibletousethesemodifiersasfunctions.Forexample:
InStrVarByte(4) InValVarWord
InVal=1234 InStr=DecInVal
Aftertheoperation,InStrcontainsthestring“1234”withtheremainderofitslength(ifany)paddedwith0’s. Whenusingtherepeatoption,forexample,HSEROUT[Stri\30],nolengthcheckingisperformed.Ifi isonlytwocharacterslong,nonetheless,all30willbereturned.Thereturnedcharactersarefromregister filesstartingwiththebaseaddressofthevariableandcontinuesforthedesiredrepetitionnumberofbytes. Function
Page
Summary
PinVariables
57
ReversedsensefromBasicStampusage;extrareservedwords.
737
Chapter29 TheBasicStampcompatibilitycommandforinput/outputsettingDIRxxisreversedfromthatfoundinthe BasicStamp.IntheBasicStamptosetforoutput,forexample,DIR0=1,butinMBasictosetforoutput DIR0=0.(ThisreversalismentionedinanoteintheBasicStampcompatibilitysectionatpage237) TheUser’sGuidelistofreservedwords(pages241-252)impliesthatBasicStampcompatibilityhasbeen extended,asreservedwordsgofromINA/OUTA/DIRA/…INF/OUTF/DIRFandpinfunctionsstopatIN31/ OUT31/DIR31.However,theseadditionalpinsarenotimplementedintheIN/OUT/DIRfunctions. Function
Page
Summary
#Include
63
Undocumentedfeature
#IncludeisanundocumentedMBasicfeaturethatallowsyoutobreakupalargeprogramintomoreman-
ageablesectionsandthenreadthemintothemasterprogram,justasiftheyweretypedindirectly. Toincorporateincludefilesintothemasterprogram,thefollowingstructureisused: #Include“P-XX-Constants.inc”;Holdsconstantdefinitions #Include“P-XX-Vars.inc” ;Holdsvariabledeclarations
Youmustbecarefulwhenbreakingcodeinto#Includefiles—MBasicdepends,tosomeextent,onorderof entry,sotheorderandcontentsofthe#Includefilesisimportant.Considerthefollowingsequence: X X= ZZ
VarByte ZZ Con 5
Thiscodefragmentproducesanerror,aswhenthecompilerreachesthestatementX=ZZ,ZZhasnotyetbeen defined.(Theactualerrormessageis“unexpectedtokentype.”) Theproperorderrequiresthevariablesandconstantstobedeclaredbeforetheymaybeused. ZZ X
Con 5 VarByte
X=
ZZ
Further,ifthe#Includefilehassubroutines,itshouldnotbeexecuteduntiltheindividualsubroutinesare properlycalled. Function
Page
Summary
SinandCos Functions
73
Returnedvaluenotclear
MBasic’ssinandcosfunctionreturnasignedbytevalueintherange–127…127. Function
Page
Summary
BIN2BCDand BCD2DEC
73
Renamedfunctions
ThefunctionsidentifiedintheUser’sGuideasDEC2BCDandBCD2DEChavebeenrenamed:
DEC2BCDisBIN2BCD BCD2DECisBCD2BIN Function
Page
Summary
ToInt
75
Returnsfloor,notroundedvalue
738
Migratingfromv5.2.1.xto5.3.0.0andtheUndocumentedMBasic TheToIntfunction,whichconvertsfromfloatingpointtointegerisafloorfunction,anddoesnotround. Forexample,ToInt(1.99)=1andToInt(2.001)=2.Toforceroundingadd0.5beforeToInt conversion,e.g.,ToInt(x+0.5)yieldstheintegervalueofx,roundedtothenearestinteger. Function
Pages
Summary
I2CinandI2Cout
109-112
MissinginformationinUser’sGuide; problemswithI2Coutundercertainconditions
Thereisanimplicitrequirementthatthedatabeingreadorwrittenisinbyteform.Henceitispossibleto correctlywriteandreadindividualbytes,orarrayofbytes.However,typeword,long,etc.failtocorrectly readandwrite,butnoerrormessageisprovided. Caution—theControlWord,bit0iscorrectlydiscussedintheUser’sGuideasan8/16bitaddressflag. Don’tbeconfusedbydocumentationformemorychipsthatsayBit0ofthecontrolwordisR/W.MBasicautomaticallysetstheR/Wflagbit. Caution—Ifthedesignhasmultipleserialchipsinparallel,multiplebytewritesorreadsthatstraddleachip boundarywillfailwithouterrormessage. ThediscussionintheUser’sGuide,page113,statesthatthe24C04is“word(16-bit)addressing.”The 24C04isa512byte(4Kbit)device.Ituses8-bitaddressing,withthe9thbit(A8)beingsetasbit1inthe commandword.Thesamplecodecorrectlyshowsthecommandbyteendingwith0,thusindicatingan8-bit addressdevice. ThecodeintheUser’sGuide,pages114–115,putstwoaddressbitsintothecommandword(A8atbit1and A9atbit2).But,the24C04doesnotuseA9addressingbit. Function
Page
Summary
Random
150
Errorinsampleprogram
ThefirstUser’sGuide,page150,sampleprogramalwaysreturnsthesamevalue;51. ;FollowingsampleprogramfromUser’sGuidefails ;don’tuseit Tempvarword Main Temp=Random25 HSerOut[DECTemp,13] Pause1000 GotoMain
ThesecondsampleprogramintheUser’sGuide,page150,iscorrect: ;Thissampleprogramworkscorrectly Tempvarword temp=25 Main Temp=Randomtemp ;25istheseedvalue HSerOut[DECTemp,13] Pause1000 GotoMain
However,theoutputofthesampleprogramhas,atplaces,aprogressivepatternthatmaynotbesatisfactory forallrandomnumberrequirements.Followingarethefirstelevenresults—thenumbersapproximately doublewitheachoutput.
739
Chapter29 51 102 204 409 819 1638 3276 6553 13107 26214 52428
It’simportantthattheresultofRandombeawordlengthvariable.IfyoudeclareTempvarbyte,the outputrepeatsafteronlyfourcycles: 51 102 204 153 51 102 204 153 51 102 204 153
Ifyouneedabytelengthrandomvariable,keeptheresultofRandominawordlengthvariableandusethe lowerbyteasthebytelengthrandom,forexample,ByteRandomVar=Temp.LowByte. Function
Page
Summary
SerOut alsoHSerOut
175
Stringoutputdoesnotstopautomaticallyfor0
TheUser’sGuidestatesthatwhenoutputtingastring-formattedvariable,suchas[STRTempStr],the charactersofTempStrwillbeoutputteduntila$00byteisfound.NeitherSerOutnorHSerOutbehavethis way.Rather,whenoutputtingastring,theoutputgoesonfor255characters,and$00bytesaresentasnull characters.Toforcetheoutputtostopat$00,youmustaddanexplicit\$0end-of-linecommandasinthe followingexample: StrVarVarByte(20) i Var Byte Clear ;fillwithzeros SetHSerialH115200 StrVar=“Hello!” Main HSerOut[“NoEOL:“,9,StrStrVar,13] HSerOut[“W/EOL:“,9,StrStrVar\20\0,13] Pause1000 GotoMain
740
Migratingfromv5.2.1.xto5.3.0.0andtheUndocumentedMBasic Thefirstserialoutputlineresultsinthefollowingoutput:
NoEOL: Hello!<00><00><00><00><00><00><00><00>[continuedforseverallines]
Thesecondserialoutputlineresultsinthefollowingoutput:
W/EOL: Hello!
TheconstructionStrStrVar\20\0causesoutputtostopattheearlierof:(a)20characters;or(b)thefirst 0character. Function
Page
Summary
Sleep
186
Mustenablewatchdogtimeratcompiletime
InorderforSleeptowork,youmustenabletheWatchdogTimeratcompiletimeviatheIDE’sConfigurationdialogbox.Wheninsleepmode,anMBasicinterruptwillnotendthesleepperiod,aproductoftheway MBasicchecksforinterrupts.AnISRASMprocedurewillbeexecuted,however. Function
Pages
Summary
XinandXout
203–210
Correctcertainconstantsandaddexplanatorymaterial
Chapter20providesanextensivediscussionofX10interfacingincludingexamplesofXinandXout. ThecodeX_Units_On%10000ismisidentifiedintheUser’sGuide.Thereisnofunction“AllUnitsOn” inX10;thefunctionisactually“AllUnitsOff”andcorrespondsto%10000.Thislibraryconstantshouldbe renamed“X_Units_Off.” IntheUser’sGuide,page203,thedescriptionofparametersforXinsaysVAR“isavariable/constantusedto storetheresults…”SinceXinreadsfromtheinterfaceunit,ofcourse,thedatamayonlybestoredinavariable,andthereferencetoVARbeingaconstantshouldberemoved. ThetableforKeyCodes(User’sGuide,page208)ismislabeled“unit”insteadofKeyCode. ThereisnotableforHouseCodes,soI’vereproducedtheonefromChapter20: B3
B2
B1
B0
Decimal Value
HouseCode
0
1
1
0
6
X_A
0
1
1
1
14
X_B
0
1
0
0
2
X_C
0
1
0
1
10
X_D
1
0
0
0
1
X_E
1
0
0
1
9
X_F
1
0
1
0
5
X_G
1
0
1
1
13
X_H
1
1
1
0
7
X_I
1
1
1
1
15
X_J
1
1
0
0
3
X_K
1
1
0
1
11
X_L
0
0
0
0
0
X_M
0
0
0
1
8
X_N
0
0
1
0
4
X_O
0
0
1
1
12
X_P
741
Chapter29 AsdevelopedinChapter20,thebinaryvaluesshownforbothUnitandKeyCodesarereversedintheUser’s Guide.Forexample,X_1hasavalueofDecimal12,Hex$C.Thiscorrespondsto%01100.TheUser’s GuideshowsX_1=%00110,whichisdecimal6orhex$6. Thisconfusionarisesfrombitorder.OfficialX10literatureassumescodesaresentLSBfirst.SinceMBasic’sXoutandXinoperatorsappeartosendorreceivethebitsleft-to-right(MSBfirst)startingwiththe rightmost4(or5forunitsandkeycodes)bits,itisnecessarytoreversethebitorderfromthatshowninthe User’sGuide. Forexample,tosendthecodeforUnit1,thebitsmustbesentinthefollowingorder0-1-1-0-0.Ifthesebits areheldinaMBasicbytevariableandaresentleft-to-right,theMBasicbytevaluemustbedecimal12($C). Infact,thevalueoftheconstantX_1is$C.However,thebitvalueshownintheUser’sGuideis%00110. Thiscorrespondstodecimal6($6),nottheactualvalueofX_1. ThetripletbitrepetitionintervalinXoutappearstobehardcodedfor60Hz.Thismightcauseproblemsin areaswith50Hzpower,wherethreephasepowerisused. TheUser’sGuidedatapindescriptionisinerror.Thedatapinissetasanoutput,notinput.Nopull-upresistorisrequired. Function
Page
Summary
HSerInand HSerOut
214
Errorsinsamplecodeandaddedwarnings
Chapter9providesanextensivediscussionofserialinputandoutput,includingexamplesofHSerInusage. TheUser’sGuidesamplecodeis:
HSERIN1000,main,[temp]
Thecommandargumentsarereversed;thecorrectcodeshouldread:
HSERINmain,1000,[temp]
HserOutworksbytransferringthebytestobesenttoa47-byteoutputbuffer(assuming16F87x/87xA
devices)asquicklyaspossible.ThehardwareUSARTthensendsthebuffercontentswithminimalsupport fromMBasicthereafter.ExecutionispassedbacktothenextstatementafterHserOutassoonasthebuffer isloaded,notwhenthebufferisemptied,aswhatMBasicsupportisrequiredissuppliedviaaninterrupt handler.Itispossible,therefore,togetintotroublewiththefollowing: …othercode… HserOut[“Thisisaverylongstringmessage”] END ;endofprogram
TheEndstatementisexecutedbeforethe“Thisisaverylongstringmessage”hascompletedsending.The resultisprogramtermination,andatruncatedstringtransmission.ThefixistoaddaPausestatementbetweenHserOutandtheEndstatement. MBasic’sClearoperatorinteractswithSetHSerial. Thefollowingconstructionfails: SetHSerialH38400 Clear HSerOut[“P28-50”,13,13]
Thedesiredstringisnotemittedovertheserialport.Topreventthisproblem,theClearcommandmust precedeSetHSerial:
742
Migratingfromv5.2.1.xto5.3.0.0andtheUndocumentedMBasic Clear SetHSerialH38400 HSerOut[“P28-50”,13,13]
Theaboveconstructionworks. Function
Page
Summary
HSerStat
214
UndocumentedfunctionforHSerOutandHSerIn
Chapter9providessamplecodeusingtheundocumentedfunctionHSerStat.HSerStatisinvokedwith thefollowingsyntax: HSERSTATcmd{,label} CMDvalue 0 1 2 3 4 5 6
Function ClearInputbuffer(labelnotused) ClearOutputbuffer(labelnotused) Clearbothbuffers(labelnotused) IfDataavailableininputbuffergotolabel IfnoDataavailableininputbuffergotolabel IfDataiswaitingtobesentgotolabel IfnoDataiswaitingtobesentgotolabel
Function
Page
Summary
HPwm
215
PinsreversedinUser’sGuide;howtoturnHPWmoff;critical valuesforperiodanddutymaycauseerroneousoutput
TheCCPxpinidentificationsarereversedintheUser’sGuidewiththecorrectassignmentsfor16F87x/87xA devicesbeing: CCPxValue 0 1
Pin C2 C1
TheUser’sGuideomitshowtoturnoffthehardwarePWMmoduleandrestorethepinsC1orC2tonormal I/Ouse.Thismaybeaccomplishedbyclearingtheassociatedcontrolregisters:
CCP1Con=$0 CCP2Con=$0
;turnsoffthePWMgenerator1(PinC2) ;turnsoffthePWMgenerator2(PinC1)
WhenusingtheHPwmfunction,itisnotnecessarytofirstsetthedesiredpintoOutput. Function
Page
Summary
Interrupts
224
LatencyinMBasicinterrupts
Chapter10providesdetailedcoverageofinterruptsinMBasiccode.TheUser’sGuidedoesnotexplicitly statethatMBasicinterruptsonlyarecalledatthefollowingexecutionofeachMBasicstatement.Thus,the interruptpollingisnottrue“realtime”duetolatencyintheMBasicstatementexecution.Thisisseenatits worstifaPAUSEstatementisexecuted;theinterruptwillnotbeexecuteduntilafterthepausecompletes.
743
Chapter29 Function
Page
Summary
RBINT
225
NoteconcerningreadingPortBtoclearthemismatch
TheportmismatchthatcausestheRBINTtobeissuedisnotclearedunlessPortBisread.Usuallytheinterrupt handlerwillreadPortBaspartofitsnormalcodeandtheinterruptcausingconditionwillbereset.IftheinterrupthandlerdoesnotreadPortB—itmightjustcountinterruptcalls,forexample—theRBINTwillcontinueto beservicedandspuriousinterruptcallswilloccur.Inthiscase,addadummyPortBread,suchas: Dummy
Var
Byte
RBINTServiceRoutine …othercode Dummy=PortB Resume Function
Page
Summary
Macros
None
Undocumentedfeature
Chapter14coversMBasic’sundocumentedin-lineassemblermacrofeatures,aswellascertainfasteroperatingMBASCmacros.Thesemacrosarediscussed,andexamplesprovidedinChapter14. StandardName MacroName PinAssignmentFunctions High @High Low @Low Input @Input Output @Output TimingFunctions Pause @MSDelay Pauseus @USDelay AssemblerOnly GoTo @GoTo Return @Return BankSel @Bank Call @Call @RatedDelay
Thefollowingtableshowsthespeedincreasepossiblebyusingthesemacros.Thedataisbasedona 16F876Awitha20MHzresonator. Name High Low Input Output
StandardMBasic ExecutionSpeed(µs) 28.6 28.4 28.0 28.4
MBasicLibraryMacros Name ExecutionSpeed(µs) @High 0.8 @Low 0.8 @Input 0.6 @Output 0.6
Function
Page
Summary
ISRASM
None
Undocumentedfeature
MBasicsupportsassemblerhandlingofinterruptprocedures.Chapter15isdevotedtoISRASMprocedures, soforthischapter’spurposes,we’lljustnotethatISRASMisanundocumentedfeatureofMBasic. 744
A
APPENDIX
PartsList Suppliers Partsfortheexperimentsinthisbookareavailablefrommanysuppliers.Inthisappendix’sdetailedchapter-by-chaptercomponentsection,I’llidentifysourcesforcomponentsthatyoumighthavetroublefinding; otherwiseanyofthelargernewcomponentdealersshouldhaveeverythingyouneed.Incidentally,DigiKey andMouser,atleast,crosslinktheiron-linecatalogswithmanufacturerdatasheets. SuppliersthatI’vehadsuccesswithareasfollows:
NewComponents Short Name DigiKey
http://www.digikey.com
Mouser
http://www.mouser.com
Allied
https://www.alliedelec.com
Newark
http://www.newark.com
Arrow
http://www.arrow.com/
ArrowElectronics,Inc. 50MarcusDrive Melville,NewYork11747 631-847-2000.
JameCo
http://www.jameco.com
JamecoElectronics 1355ShorewayRoad Belmont,CA94002 800-831-4242.
URL
CompanyName/Address/ Telephone DigiKeyCorporation 701BrooksAveSouth ThiefRiverFalls,MN56701 800-344-4539 MouserElectronics,Inc. 1000NorthMainStreet Mansfield,Texas76063 800346-6873 AlliedElectronics,Inc. 7410PebbleDrive FortWorth,Texas76118 1-800-433-5700 NewarkInOne 4801N.Ravenswood Chicago,IL60640-4496 800-263-9275
745
Comments Verylargestock;new componentsonly.Inmost cases,samedayshipment; Servicechargeforordersunder $25.00. Largestock;newcomponents only;nominimumorder amount.;noservicecharge. Oldlinedistributor,verylarge stock;localbranchesinmany cities;$50minimumorder. Oldlinedistributor;verylarge stock;localbranchesinmany cities;Servicechargefororders under$25.00;Common ownershipwithFarnellinUK andcansupplyanyitemin FarnellcatalogtoUSpurchaers. Largestock,includingsome productshardtofindfrom otherdistributors;Local branchesinmanycities;$25 minimumorder. Mailorderonly;smallerstock thanabove;hassomenew closeoutordiscontinuedparts; Processingfeeforunder$20.
AppendixA Short Name SmartHome
URL http://www.smarthomeusa.com
CompanyName/Address/ Telephone SmartHomeSystems 127EastMainStreet,Smithtown, NY 888-843-9103
Comments X-10modulesonly.
Overstock,DiscontinuedandSurplusComponents Aswithanysourceofoverstocked,discontinuedandsurpluscomponents,stockvariesfrommomenttomoment.Hence,what’savailabletodaymaynotbetomorrowandviceversa. ShortName
URL
BGMicro
http://www.bgmicro.com/
AllElect
http://www.allcorp.com/
Debco
http://www.debcoelectronics. com/
Goldmine
http://www.goldmine-elec.com/
MPJones
http://www.mpja.com/
CompanyName/Address/ Telephone B.G.Micro 555N.5thSt.Suite#125 Garland,Texas75040 800-276-2206 ALLELECTRONICSCORP. P.O.Box567 VanNuys,CA91408-0567 888-826-5432 DebcoElectronicsInc. 4025EdwardsRoad Cincinnati,Ohio,USA,45209 800-423-4499 TheElectronicGoldmine POBox5408 Scottsdale,AZ85261 800-445-0697 MarlinP.Jones&Assoc.,Inc. P.O.Box530400 LakePark,Florida33403 800-652-6733
Comments UsefulsourceofLCDdisplays inadditiontogeneralparts andmodules. Electromechanicalaswellas electronicparts.
Carriessomehardto findlinearanddigital semiconductors.
CarriesLCDsalongwithother components.$10minimum orderand$6minimum shipping. AnothersourceforLCD displays;goodforpower suppliesaswell;minimum order$15.
GenericComponentsRequired Thechapter-by-chapterpartslistconcentratesonmajororspecialcomponents.Inaddition,youwillrequire whatcanbecalled“gardenvariety”components.Irecommendyouhaveonhand: Resistors—10each,¼watt,carbonfilmresistorsofvalue:100,220,470,680,1K,2.2K4.7K,6.8Kand 10Kohm.Resistorvaluesusedinmanyschematicsinthisbookmayvaryslightlyfromthesevalues,but oneofthesevaluescanbesubstitutedinalmostallinstances.Forexample,Ifrequentlyuse5.1Kpull-up resistorsbuta4.7Kworksjustaswellinthisapplication.Youmaywishtopurchasearesistorassortment,suchasJameco’s81832CL($27.95includingcabinet)or103165CL(resistorsonly$12.95). Capacitors—10each.01µFand0.1µFdisccapacitors,50voltrating.Youmaywishtopurchaseadisc capacitorassortment,suchasJameco’s81859CL($35.95includingcabinet)or130232CL(capacitors only$17.95). Semiconductors—youwillneedasmallquantity(atleast10each)ofafewinexpensivegeneralpurpose semiconductors,suchas:
746
PartsList NPNlowpowerswitchingtransistors—Iuse2N4401devices,inTO-92package.Youcanpurchase25 2N4401sfromDigiKey,PN2N4401-ND,for$2.97. PNPlowpowerswitchingtransistors—Iuse2N4403devicesinTO-92package.Youcanpurchase25 2N4403sfromDigiKey,PN2N4403D26ZCT-ND,for$2.97. N-ChannelLowPowerMOSFET—Iuse2N7000devicesinTO-92package.Youcanpurchase10 2N7000sfromDigiKey,PN2N7000FS-ND,for$2.16. Lowpowersiliconsignaldiodes—Iuse1N4148devicesinDO-35package.Youcanpurchase10 1N4148sfromDigiKey,PN1N4148MSCT-ND,for$0.53,or100for$4.20. PowerDiodes—Aclassic1N4001,50V,1Apowerdiodeisusedinafewcircuits.Youcanpurchase10 1N4001sfromDigiKey,PN1N4001MSCT-ND,for$0.43. SchottkyDiodes—aninexpensiveSchottkydiode,ratedat40V,1Aisthe1N5891.Youcanpurchase10 1N5891sfromDigiKey,PN1N5819IR-ND,for$2.31. LEDs—it’susefultohaveafewdifferentcolorLEDsonhand,green,redandyellow,forexample.The LEDsshouldberatedfor5to15mA.YoumaypreferthelargerT-1¾sizeLEDs,orsmallerT1devices.(Thenumberfollowingthe“T”isthediameteroftheLEDinunitsof1/8inch.TheLEDson the2840developmentboardandtheICDprogrammerboardareT1¾devices.)Iusuallypurchase LEDsfromoneofthesurplusdealers,butallnewcomponentdealerscarrythemaswell. OpAmp—TheoperationalamplifiersusedinthisbookaretypeMCP601fromMicrochipTechnologies. Theseamplifiersareoptimizedtooperatewithasingle+5Vsupply.MCP601sareavailablefrom DigiKey,PNMCP601-I/P-ND,for$0.68each. PICs—PICsarecarriedbyDigiKey,Mouser,Jamecoandothers.SomePICsarealsoavailablefromBasic Micro.Isuggestyouacquireandhaveonhandtwo16F877Aandtwo16F876Adevices.Whenordering thesedevices,carefullywatchthepackagetype—the2840DevelopmentBoardsworkonlywithDIP packageddevices,DigiKeypartnumbersPIC16F876A-I/SP-ND($7.05each)andPIC16F877A-I/P-ND ($7.70).Bothare20MHzparts. Resonators—IprefertorunmyPICswith20MHzresonators,typeZTT.TheseareavailablefromDigiKey, PNX909-ND,for$0.54each,or10for$4.50. ExtraBreadboard—Althoughthe2840DevelopmentBoardincludesa3"×1"(300contacts)solderless breadboard,it’snotbigenoughtoholdmanyofthecircuitsinthisbook,requiringyoutosplitthe circuitbetweenthe2840DevelopmentBoardandanauxiliarysolderlessboard.Irecommendatleasta 740contactauxiliarysolderlessboard,anda1500contactorlargerboardwillmakeprototypingwork easier. LCDDisplay—severaloftheprojectsinthisbookrequireanLCD.Irecommenda4-line,20charactersper linedisplay,oftencalleda20x4ora204model.Thesecanbeexpensivetopurchasenew,soyoumay wishtocheckthesurplusoutletsforsuitabledisplays.ConnectingtheLCDtoasolderlessdevelopmentboardrequiresatleast9pins,andinsomecases16pins.ThemostconvenientwayI’vefoundto connecttheLCDtoasolderlessboardiswitha16-pinribboncable,oneendterminatedina16-pinDIP plug,theotherendfreeforyoutosoldertothepadsontheLCD,DigikeypartnumbersC2PXG-1618ND(18”longfor$2.10each)orC2PXG-1606-ND(6”longfor$1.84each)aresuitable.(Thesecables are“valueadded”partsfromDigiKeyandareassembledonlywhenordered,sothestockcountwill show0whenyouorderone.) Unlessotherwisenoted,allcomponentsare“throughhole”type.Allpricesareasofthewritingofthistext, Spring2004,andarebaseduponsmallquantitypurchases.
747
AppendixA
SpecificComponents Inadditiontothegenericitemsdescribedabove,thislistingidentifiesotherspecificcomponentsrequiredfor eachchapter.
Chapter1
None.
Chapter2
None.
Chapter3 Qty 1
MfgNo MV5491A
Description TwocolorLED
CatalogNo MV5491A-ND
Supplier DigiKey
UnitPrice $0.51
Comments
1
G2RL-24DC-12
OmronRelay12Vcoil
Z147-ND
DigiKey
$4.03
Todemonstrate switchingofan inductiveload;needs external12Vsupply.
1
TIP31
NPNpowertransistor
497-2602-5-ND
DigiKey
$0.69
1
TIP120
NPNDarlingtonpower transistor
497-2539-5-ND
DigiKey
$0.74
1
IRF510
PowerN-channelMOSFET
IRF510-ND
DigiKey
$1.08
1
IPS021
IntelligentMOSFETlowside IPS021-ND powerswitch
DigiKey
$2.00
1
IRF9510
PowerP-channelMOSFET
DigiKey
$1.16
1
IPS511
IntelligentMOSFEThighside IPS511-ND powerswitch
DigiKey
$3.00
1
4N25
Opto-isolatorNPN
4N25FS-ND
DigiKey
$0.48
1
PS710A-1A
Opticallyisolatedbilateral powerMOSFETswitch
PS710A-1A-ND
DigiKey
$6.50
1
GF0401M
8-ohmspeaker,40mm diameter
GF0401M-ND
1
222202133471
470uf6.3Velectrolytic capacitorradialleads
4000PHCT-ND
IRF9510-ND
$2.49 DigiKey
Almostanyspeaker maybesubstituted.
$0.47
Chapter4 Qty 4
MfgNo EVQ-21409K
1
VEL16KEY
Description PanasonicSPSTnormally openpushbuttonswitch Velleman16key(4x4) keypad
CatalogNo P12223SCT-ND
Supplier DigiKey
UnitPrice Comments $0.33
SWT1067
BGMicro
$4.95
748
Canbeconnected via8-pinribbon connectorwithDIP8 plug.
PartsList Chapter5 Qty 1 1
1
MfgNo DMC-16202NYJLY-AKE-BG DMC-20481NYLY-ABE
Description OptrixLEDLCDDisplay 2x16w/LEDbacklight OptrixLEDLCDDisplay 4x20w/LEDbacklight
3386F-103
Bournes10Ktrimpot
CatalogNo 73-1032-ND
Supplier DigiKey
73-1094-ND
DigiKey
3386F-103-ND
DigiKey
UnitPrice Comments $16.90 Shoparoundfor surplusLCDmodules. $30.30 Use4x20asalternate to2x16;willuse 4x20displayforother chapters. $1.29
TheseLCDmodulesareexpensive.Itisn’tnecessarytopurchasebotha2×16anda4×20display;ifyou purchaseonlyone,buya4×20display.LCDdisplaysareoftenavailablefromsurplusdealersatamuch lowerpricethanquotedabove.Forexperimentation,itisn’tnecessarytouseabacklighteddisplay,soit’s possibletosavesomemoneywithanon-backlighteddisplay.
Chapter6 Qty 1
MfgNo CD10RL1CK
Description HexrotaryDIPswitch
288T232R161A2
1 2
CatalogNo CKN3045-ND
Supplier DigiKey
UnitPrice Comments $4.89 Alternativeis4single poleswitches. AsinChapter5.
CTSrotaryencoder16 positionw/detent
CT3002-ND
DigiKey
$2.58
LCD
Chapter7 Qty 4
MfgNo MAN4410A
Description Greencommonanode7segmentdisplay0.4”digit
CatalogNo MAN4410A-ND
Supplier DigiKey
1
ULN2003A
NPNDarlingtontransistor array SPSTswitches
296-1979-5-ND
DigiKey
Description Airpaxunipolarstepper motor5V,48steps/rev
CatalogNo
12VZenerdiode
1N5242DO35MSCT- DigiKey ND
4
UnitPrice Comments $0.98 Almostanycommon anodedisplaymaybe substituted. $0.64 AsinChapter4.
Chapter8 Qty 1
MfgNo AIRPAXLB82773- M1
1
ULN2003A
4
1N5242DO35
UnitPrice $4.29
Comments Almostanysmall5V unipolarsteppermay besubstituted AsinChapter7.
Chapter9
Supplier Jameco
None.
749
$0.21
AppendixA Chapter10 Qty
MfgNo
Description
CatalogNo
Supplier
UnitPrice Comments
1
SPSTswitches
AsinChapter4.
1
Rotaryencoder
AsinChapter6.
Chapter11 Qty
MfgNo LT1634CCZ-4.096
1 3
LDS-M514RI-RA LDS-M541RI-RA
3 1
3386F-203
Description LT1634CCZ-4.096voltage reference 7-SegmentDisplayLumex
CatalogNo LT1634CCZ- 4.096-ND 67-1512-ND
Supplier DigiKey
UnitPrice $3.88
DigiKey
$1.98
CapitalAdvanced Technologies331177-lead SurfaceMountto0.1”SIP (UseforbreadboardingLED displays) Bournes20Ktrimpot
33117CA-ND
DigiKey
$3.22
3386F-203-ND
DigiKey
$1.29
Comments
Inaddition,severalresistorsandcapacitorsotherthanthegenericstockvaluesarenecessary.Pleasereview theassociatedschematics.
Chapter12 Qty 2
MfgNo 18B20
Supplier DigiKey
UnitPrice Comments $5.04
DS1302
Description CatalogNo One-wiredigitaltemperature DS18B20-ND sensor Digitalrealtimeclock DS1302-ND
1 1
DigiKey
$3.31
ECS-.327-8-14
32.786KHzcrystal
DigiKey
$2.63
1
A0820-2R5474
0.47Fbackuppowerstorage 283-2497-ND capacitor
DigiKey
$2.40
X803-ND
Chapter13
None.
Chapter14
None.
Chapter15
None.
750
Shouldbea6pf crystal;thespecified unitis8pf.DigiKey doesnotstockthe 6pfversion.
PartsList Chapter16 Qty 1
MfgNo TLC7528CN
Description Dual8-bitmultiplyingDAC
CatalogNo 296-1871-5-ND
1
LTC1062
1
LC411CN
Switchedcapacitorlowpass LTC1062CN8-ND filter OpAmpJFETinputdualsupply LF411CN-ND
Supplier DigiKey
UnitPrice Comments $3.31
DigiKey
$6.13
DigiKey
$1.35
Inaddition,severalresistorsandcapacitorsotherthanthegenericstockvaluesarenecessary.Pleasereview theassociatedschematics.
Chapter17 Qty 1
MfgNo
Description TouchtonePad
1
MC145436A CM8870P1
1 1
Supplier
UnitPrice Comments Seenote1.
MotorolaDTMFdecoder
Debco
$4.29
Seenote2.
MitelDTMFDecoder
Debco
$1.79
Seenote2.
3.579545MhzCrystal Debco Colorburst(HC49) N/A Arrow
$0.99
3.58MHzcrystal CH1837A
CermetekMicroelectronics Telephonecouplermodule
CatalogNo
$18.67
1. ThetestcircuitusesatouchtonepadfromanoldWesternElectric500seriesdesktelephone.Ifyouareunabletofindasimilartouchtonepad,youmay useasecondPICandtheDTMFoutfunctiontogeneratetestsignals.Alternatively,itispossibletogeneratethetouchtonetestsignalsbytemporarily connectastandardtouchtonetelephonewithavoltagesourceandanaudiotransformer. 2. AtthetimeChapter17waswritten,boththeMotorolaMC145436AandMitelCM8870P1DTMFdecoderintegratedcircuitswereavailablefrom Debco.Atthetimethispartslistiscompiled,Debcoshowsshowbothasout-of-stock.TheMC145436Achipisofficiallydiscontinued,butmaystill beavailablefromothersuppliers.TheCM8870P1DTMFdecoderICisanalternativetotheMC145436Abutisnotpin-for-pininterchangeable.
Chapter18 Qty 1
MfgNo 24LC16B
Description 16KserialEEPROM
CatalogNo 24LC16B/P-ND
Supplier DigiKey
UnitPrice $0.63
2
24LC256
256KserialEEPROM
24LC256-I/P-ND
DigiKey
$2.25
1
24FC515
512KserialEEPROM
24FC515-I/P-ND
1
AT24C512
512KserialEEPROM
DigiKey
$6.19
1
74ACT843
9-bitlatch
AT24C512-10PI- 2.7-ND 512-74ACT843SP
Mouser
$2.55
1
CY7C128A-35PC
2KparallelRAM35ns
428-1045-ND
DigiKey
$4.95
Comments
$4.68
Chapter19 Qty
MfgNo
Description
CatalogNo
Supplier
UnitPrice Comments
1
SN754410
Quadhalfbridge
296-9911-5-ND
DigiKey
$1.88
1
10ohm5wpowerresistor
588-25J-10
Mouser
$1.37
2
seriescurrentlimitingresistor
Seenote2
1
Bipolarsteppermotor
Seenote3
1. Usedonlytodemonstratecleanmicrostepcurrent. 2. Resistorvalueanddissipationratingdependsuponmotorwindingresistance,voltageratingandsupplyvoltage. 3. TheunipolarmotorusedinChapter8maybeusedinbipolarmodeforChapter19.
751
Seenote1
AppendixA Chapter20 Qty 2
MfgNo TW523
Description X-10powerlinetransceiver
CatalogNo PSC-05
Supplier SmartHome
UnitPrice $19.95
1
PAM-02
Appliancecontrolmodule
PAM-02
SmartHome
$13.95
1
4x20LCD
AsinChapter5.
18B20temperaturesensor
AsinChapter12.
1
Comments Seenote1.
1. Twotransceiversarerequiredtosenddatafromonelocationandreceiveatasecondlocation.
Chapter21 Qty 1
MfgNo MCP41010
Description 10Kdigitalpotentiometer
CatalogNo MCP41010-I/P-ND
Supplier DigiKey
UnitPrice $1.68
DigiKey
$2.53
Comments
2
MCP42010
1
0.18µFcap
Dual10Kdigital MCP42010-I/P-ND potentiometer Metalizedpolyestercapacitor E1184-ND
DigiKey
$0.39
1
0.47µFcap
Metalizedpolyestercapacitor 495-1112-ND
DigiKey
$0.41
Supplier DigiKey
UnitPrice $0.55
Comments Seenote1.
Chapter22 Qty 1
MfgNo QSE114
Description Phototransistor
CatalogNo QSE114-ND
1
TSOP1100
VishayIRreceiver-broadband 782-TSOP1100
Mouser
$1.50
Seenote2.
1
TSOP1238
VishayIRreceiver-38KHz version
Mouser
$1.08
Seenote2.
782-TSOP1238
1. Onlynecessaryfordemonstration. 2. YoumayuseeitherabroadbandIRreceiver,suchasVishay’sTSOP1100,or,forbetterperformance,anarrowbandIRreceiver matchedtoyourremotecontrol.TheremotecontrolIusedhasa38KHzcarrier,andthenarrowbandreceiverisaTSOP1238.
Chapter23 Qty 1
MfgNo K3011P
Description Randomphaseopto-triac
CatalogNo 78-K3011P
Supplier Mouser
UnitPrice $0.53
1
MOC3032
Zerocrossingopto-triac
512-MOC3032M
Mouser
$1.24
1
BTA12-600BW
Snubberlesstriac-12A600V
511-BTA12-600BW Mouser
$0.96
1
SW210
546-164D10
Mouser
$8.44
1
TLE2426
Transformer-Hammond Transformersubstitutefor SW-210. Vcc/2railsplitter
296-1994-ND
DigiKey
$1.30
1
H312006
6A3AGfuse
5760-12006
Mouser
$0.39
1
441-R345A
3AGfuseholder
441-R345A
Mouser
$0.93
1. 2.
Comments
Seenote1.
Noncriticalitem.Weusethetransformertoprovideanisolated60Hzzerocrossingreference,soitdrawsnoappreciablesecondarycurrent. Thetransformersecondaryshouldbe10VRMSto30VRMS. Mechanicalpartsneededincludeapieceofunusedsinglesidedprintedcircuitboardapproximately6"×4",andACpowercord,plugand receptacle.Thelatteritemsmaybeobtainedatalocalhardwarestore.
752
PartsList Chapter24 Qty
MfgNo
1
SN754410
Description MotorwithACtachometer
CatalogNo
Supplier
UnitPrice
Comments Seenote1. AsinChapter19.
1. ThemotorusedinChapter24hasanACtachometerandwasremovedfromanoldfullheight5¼inchfloppydrive.Similardrivesare availablefromscrappedcomputersfortheasking.
Chapter25 Qty
MfgNo
1
Description
CatalogNo
Supplier
UnitPrice
Barcodewand
Comments Seenote1.
1. IpurchasedtheHPA200barcodewandreaderusedinChapter25fromGoldmineinJanuary2004,buttheirstockiscurrentlyexhausted.Similar barcodewandsareavailablefromothersurplushousesandfrequentlyappearoneBay.
Chapter26 Qty 1
MfgNo
Description 6Vbuzzer
CatalogNo 273-054
Supplier UnitPrice RadioShack $2.99
Comments Seenote1.
1
Speaker
AsinChapter3.
2
Rotaryencoder
AsinChapter6.
1
LCD
1
16F628
16F628
AsinChapter5. PIC16F628-20/P-ND
DigiKey
$3.88
Seenote2.
1. The6Vbuzzerisonlyusedforpreliminarytests. 2. Onlypreliminaryprogramsaredevelopedwiththe16F628.Programmingthe16F628requiresan0818DevelopmentBoard.
Chapter27 Qty 1
MfgNo XR2211
Description PLLdecoderIC
CatalogNo 34999
Supplier Jameco
UnitPrice $1.79
Comments Exar-Seenote1.
or
NJM2211
PLLdecoderIC
NJM2211D-ND
DigiKey
$0.93
Secondsourceof XR2211.
3
0.01µF
0.1µFmetalizedpolyester
B32529C103J
DigiKey
$0.19
1
4700pf
4700pfmetalizedpolyester
B32529C472J
DigiKey
$0.19
1
3386F-1-502
5Ktrimpot
3386F-502-ND
$1.29
Substitutefor5000 pfinFig27-4.See note2. Substitutefor3Kin Fig27-4.Seenote2.
1. Chapter27wasdevelopedwithanXR2211device;asecond,lowerprice,replacementistheNJM2211manufacturedbyJRC, butithasnotbeentestedwithChapter27’scircuitry. 2. A4700pF(0.0047µF)metalizedpolyestercapacitormaybeusedinplaceofthe5000pFshowninFigure27-4. Likewise,a5Ktrimpotmaybeusedinplaceofthe3KtrimpotshowninFigure27-4.
753
AppendixA Chapter28 Qty 1
MfgNo HM1500
Description Humiditysensor
CatalogNo HM1500-ND
Supplier DigiKey
UnitPrice $30.50
Comments
1
MPX6115A6U
Pressuresensor
MPXA6115A6U-ND
DigiKey
$17.57
1
6103
Surfboardadapter
6103CA-ND
DigiKey
$1.48
1
LT1634CCZ-4.096
3
12.7K1%1/4wresistor
12.7KXBK-ND
$0.54
Seenote1.
1
100K1%1/4wresistor
100KXBK-ND
$0.54
Seenote1.
DS1624-ND
$9.04
AsinChapter11.
1
DS1624
Temperaturesensor
1
DS1302
realtimeclock
AsinChapter12.
1
32KHzcrystal
AsinChapter12.
1
0.47Faerogelbackupcapacitor
AsinChapter12.
512kserialEEPROM
AsinChapter18.
1
AT24C512
1. Priceisforminimumpurchasequantity,5units.
754
B
APPENDIX
FunctionIndex ThefollowingindexidentifiesprogramsinwhichtheindicatedMBasicfunctionisusedatleastonce.I’ve omittedcommonfunctions,suchasIf…Then,For…Next,astheyareusedinalmosteveryprogram. BIN2BCD&BCD2BIN Program07-3 Program12-5;Program12-6 Program28-2 FloatingPointMath Program06-03;InterruptVersion;Program06-04; Program08-03; Program10-1;Program10-1A;Program10-1B;Program10-2;Program10-5; Program10-6; Program11-1;Program11-2; Program12-2;Program12-3;Program12-5;Program12-6; Program14-01-B;Program14-01-C;Program14-01;Program14-01A;Program14-100;Program14-101;Program14-102; Program14-103;Program14-104;Program14-105;Program14-106;Program14-107;Program14-108;Program14-109; Program14-110;Program14-111;Program14-112;Program14-113;Program14-114;Program14-115;Program14-116; Program14-118;Program14-119-A; Program14-119-B;Program14-4; Program15-01-A;Program15-01;Program15-02; Program16-1;Program16-2; Program18-3; Program20-05; Program24-2A;Program24-3;Program25-2; Program25-3;Program25-4;Program25-5; Program26-03;Program26-04; Program28-1A;Program28-1C;Program28-2;
755
AppendixB ADin Program4-01;Program4-02;Program4-05 Program06-01;Program06-02;Program06-04 Program07-3 Program09-1f Program11-1;Program11-2 Program12-5 Program19-03 Program20-05;Program20-06 Program21-2Program21-4Program21-6 Program25-3;Program25-4;Program25-5 Program28-1A;Program28-1C;Program28-2 Branch Program06-01;Program06-02;Program06-03-InterruptVersion;Program06-03 Program06-04 Program09-3 Program10-2 Program16-3 Program17-2;Program17-3z Program26-03;Program26-04 Program28-2 Button Program04-04 DTMFOut Program16-3 FreqOut Program16-3 I2Cin/I2Cout Program18-1;Program18-2;Program18-2A;Program18-2B;Program18-3 Program28-1B;Program28-1C;Program28-2 ISRASM Program15-01-A;Program15-01;Program15-02 Program16-2 Program19-03 Program25-2;Program25-3;Program25-4;Program25-5
756
FunctionIndex LCDRead/LCDWrite Program5-01;Program5-02;Program5-03;Program5-04;Program5-05 Program06-04 Program27-3 Program26-04 OWin/OWout Program12-1;Program12-2;Program12-3;Program12-5;Program12-6 Program20-05 PulseIn Program22-1;Program22-2;Program22-3;Program22-4; Program24-3;Program24-4;Program24-5;Program24-6 PulsOut Program16-3 Program18-4;Program18-5 Program23-2;Program23-3;Program23-4 PWM Program16-3 ReadDM Program06-04 Serin/SerOut Program09-1A;Program09-1B;Program09-1c;Program09-1d;Program09-1E;Program09-1f; Program09-1g ShiftIn/ShiftOut Program12-0;Program12-4;Program12-5;Program12-6 Program21-1;Program21-2;Program21-3;Program21-4;Program21-5;Program21-6 Program28-1D;Program28-2 Sound Program16-3 Program25-4;Program25-5 SPMotor Program08-01
757
AppendixB Xin/Xout Program20-01Program20-02;Program20-03;Program20-04;Program20-05;Program20-06 SetHSerial/HSerin/HSerOut Program06-01;Program06-02;Program06-03-InterruptVersion;Program06-03 Program09-2A;Program09-2B;Program09-3 Program10-2;Program10-3;Program10-5 Program11-1 Program12-1;Program12-2;Program12-3;Program12-4;Program12-5;Program12-6 Program14-01-B;Program14-01-C;Program14-01;Program14-01A;Program14-100;Program14-101; Program14-102;Program14-103;Program14-104;Program14-105;Program14-106;Program14-107; Program14-108;Program14-109;Program14-110;Program14-111;Program14-112;Program14-113; Program14-114;Program14-115;Program14-116;Program14-118;Program14-119-A; Program14-119-B;Program14-4 Program17-1;Program17-2;Program17-3z Program18-1;Program18-2;Program18-2A;Program18-2B;Program18-3;Program18-4;Program18-5 Program19-03 Program20-02;Program20-03;Program20-05;Program20-06;Program20-07 Program21-2;Program21-4;Program21-6 Program22-1;Program22-2;Program22-3;Program22-4 Program23-2;Program23-3;Program23-4 Program24-1;Program24-2;Program24-2A;Program24-3;Program24-5;Program24-6 Program25-1;Program25-2;Program25-3;Program25-4;Program25-5 Program27-0;Program27-1;Program27-2;Program27-3 Program28-1A;Program28-1B;Program28-1C;Program28-1D;Program28-2 HSerStat Program09-2A;Program09-3 Program23-4 Program28-2 HPWM Program19-01;Program19-02 Program24-2;Program24-2A;Program24-3;Program24-5;Program24-6 Program26-02;Program26-03;Program26-04 SetPullups Program25-1;Program25-2;Program25-3;Program25-4;Program25-5
758
FunctionIndex InterruptsHandledinMBasic Program06-03-InterruptVersion;Program06-04 Program10-1;Program10-1A;Program10-1B;Program10-2;Program10-4;Program10-5 Program10-6 Program17-3z Program25-1 Program26-03;Program26-04 SetHSerial/HSerOut/HSerIn Program06-01;Program06-02;Program06-03-InterruptVersion;Program06-03; Program09-2A;Program09-2B;Program09-3; Program10-2;Program10-3;Program10-5; Program11-1; Program12-1;Program12-2;Program12-3;Program12-4;Program12-5;Program12-6; Program14-01-B;Program14-01-C;Program14-01;Program14-01A;Program14-100; Program14-101;Program14-102;Program14-103;Program14-104;Program14-105;Program14-106;Program14-107; Program14-108;Program14-109;Program14-110;Program14-111;Program14-112;Program14-113;Program14-114; Program14-115;Program14-116;Program14-118;Program14-119-A;Program14-119-B;Program14-4; Program17-1;Program17-2;Program17-3z; Program18-1;Program18-2;Program18-2A;Program18-2B;Program18-3;Program18-4; Program18-5; Program19-03; Program20-02;Program20-03;Program20-05;Program20-06;Program20-07; Program21-2;Program21-4;Program21-6; Program22-1;Program22-2;Program22-3;Program22-4; Program23-2;Program23-3;Program23-4; Program24-1;Program24-2;Program24-2A;Program24-3;Program24-5;Program24-6; Program25-1;Program25-2;Program25-3;Program25-4;Program25-5; Program27-0;Program27-1;Program27-2;Program27-3; Program28-1A;Program28-1B;Program28-1C;Program28-1D;Program28-2;
759
AbouttheAuthor JackR.Smith Fornearly30years,Mr.Smithworkedintheareaofmixedlegal-technicaltelecommunications;bringingbothelectricalengineeringandlegal backgroundtobearonproblems.Involvedwithfirstexperimentalcellular radiosystemsintheUnitedStates,hesubsequentlyworkedwithstart-up cellularandpersonalcommunicationssystemradiooperatorsintheUnitedStates,EuropeandAsia.Heisaco-founderofthetelecommunications consultingcompanyTeleworXandhasshapeditsradiopropagationand networkdesignsoftware. HereceivedaBSEEDegreefromWayneStateUniversity,DetroitMIin1968,andaJurisDoctordegree, alsofromWayneStateUniversity,in1976.Heisalongtimeamateurradiooperator,holdingthecallsign K8ZOAandisactiveondigitalmodes.
760
Index NumbersandSymbols #Include738 $00bytes740 //returnstheintegerremainder722 /operatorreturnstheintegerquotient 722 1-wire231,389 bytesaretransmittedandreceived fromlowestaddresstohighest address235 CRC(cyclicreduncancycode)235 familycode234 familynumber235 globaladdress238 globaladdressing237 MBasiccurrentlysupportsonlythe initial14kb/sspeed1-wire protocol234 permissiblemodevalues234 presencepulse232 reset238 serialnumber234,235 1-wirebus240 selectivelyread240 24LC16B392,393 24LC256389 2840developmentboard8,151,154, 202,212,217 howthePCistobeconnectedtothe 159 2840prototypeboard554 2N7000142 7-segmentLEDdrivercircuit218 7805699
A A/Dreading720 A/Dstep695 A/Dunits703 absolutepressure693,704 accuracy212 activefilters511 activelow-passfilter511 ACpower opticallycoupledFET542 warningstatement542 addlw434 addressbyte708
addresspins699 ADIN218,729 ADin703,756 ADIN16218,729,733 AllUnitsOff741 analog-to-digital337 analog-to-digitalconversion211,335, 702 8-bitA/Dconversion214 analog-to-digitalconverter(ADC)6, 211,336,408 accuracy212 ADIN216 clockconstantselection215 internalRCoscillator216 errors212 differentiallinearityerror212 errorsinthereferencevoltages213 gainerror213 integrallinearityerror212 internal213 noise213 offseterror213 quantizationerror213 settlingtime213 sourceimpedance213 inputfunction ADIN216,218 ADIN16216,218 inputpinconstantselection216 internalselectionswitches214 selectinternalorexternalnegative referencevoltage214 selectinternalorexternalpositive referencevoltage214 whichofseveralpossiblepins connectstotheA/Dconverter module214 LT1634CCZ-4.096voltagereference 213 MCP601op-amp213 minimumtimetoconvert215 acquisitiontime,TACQ215,216 analog-to-digitalconversiontime, TAD215,216 offsetvoltage213 resolution212 quantizationerror212
761
result214 leftjustified214 right-justified214 signaltonoiseratio337 twovoltagereferences212 negativereference212 analogvoltages702 ArrayVariableUsage734 ASK(amplitudeshiftkeying)661 assemblercode _@RateDelayMacro294 decfsz295 delayfunction294 GoTo295 NOP295 bankselection291 ASM293 _@bank293 BankSel293 illegallabel293 MPASMassembler293 usagechangedslightlybeginning withMBasicversion5.3.0.0 293 usageinMBasicbeforeversion 5.3.0.0293 version5.3.0.0GPASMassembler293 determinewhichbankMBasichas placedavariable291 STACKcommand292 stacksizeisspecifiedinincrements of4bytes292 variableassignmentprocedure292 pageselection294 longcalls294 longjumps294 wordvariable303 highbyte303 lowbyte303 assemblerinstructions ADDLW267 ADDWF267 field266 b266 d266 f266 k266
Index PC266 PD266 TO266 W266 x266 movlw260 movwf261,264 rotate RRF267 RRL267 SUBLW267 SUBWF267 assemblerinterruptserviceroutine317 advantagesoverMBasic317 interrupts317 accommodatingmultipleinterrupts 327 cleartheinterruptflag ASM{…}construction321 in-lineassemblermacros321 INTCON321 INTE321 INTF321,325 contextrestoration322 contextsaving322 contextswitching322 controlbit “enable”bit318 disabled318 enabled318 higherlevelinterruptcontrolbits 319 onededicatedcontrolbit318 controlregister INTCON319 devicecontrol318 enable325 enableanddisableinterrupts320 _@bcf320 _@bsf320 ASM{…}assemblercodetoset orclearenablebits320 Banksel326 banksel327 bcf320 bsf320,326 cannotenableordisabletheinterruptusingMBasic’sEnableand Disablefunctions320 decfsz326 Ext_H2L320 GoTo326 in-lineassemblertosetorclear enableandsetupbits320 Intcon.bit4320 Inte320 IntEdg320 ISRASM320,331 OnInterrupt320 Option_Reg320 SetExtInt320 SetTmr0320
setorclearthesetupandenable bitsfromMBasic320 usingMBasiccommands320 enableglobalandperipheralinterrupts332 external(RB0)325,332 btfsc332 globalinterrupts(GIE)318,334 globalinterruptenablebit318, 319,325,326 Intcon321 Inte321 interruptevent321 flagbit322 FSR322 HSerIn322 HSerOut322 interruptvector322 latency321 PCLath322 RCIE322 Status322 TXIE322 W322 interruptflag332 intf333 interruptflagisclearedatprocessor reset321 INTF323 Intfbit326 ISRASM318,321,322 automaticallyperformscontext switching322 latency331 reentrant322 OnInterrupt317 Option_Reg321 peripheralfamilyinterruptenable bit319 peripheralinterrupts325 peripheralinterrupts(PEIE)318 peripheralinterruptbit(PEIE)325 peripheralinterruptenable(PIE) registers319 PIE1319 PIE1bit0319 PIE2319 peripheralinterruptfamily318 peripheralinterruptregisters(PIR) 319 PIR1319 PIR1bit0319 PIR2319 PIEandPIRregisters registeraddressesalign319 statusbit statusflag318 timers1and2332 firetheirinterruptssimultaneously334 intheorderestablishedbythe test/jumpstatements334
762
membersoftheperipheralinterruptfamily332 timer1319,327,331,332,333 banksel334 btfsc332 enablebit319 interruptflag319 maketimer1reset334 Tmr1IF333 timer2328,331,332,333 banksel333 btfsc332 interruptflag333 PIR1333 postscaler333 prescaler333 shuttimer2downbyclearingthe Tmr2On333 T2Con333 Tmr2333 Tmr2If333 Tmr2On333 turntimer2on333 ISRASM317,323,325,326,327, 332,333,334 @bank322 banksel322,323 disableinterrupts331,332 End326 mayplacetheISRASMcodeanywhere326 ISRASMcode322 assemblerlanguageprogramming260 address261 banking264 2-bitbankaddress264 7-bitopcoderelativeaddress264 assemblermacro,BankSel264 Banksel264 bankaddressbits264 destinationcode264 fileaddresses264 macro264 advantages264 BankSel264 opcode264,265 mov264 movwf264 specialfunctionregisterbitsRB1 andRP0264 statusregister264 comparingMBasic,assemblerand machineinstructions260 definition260 filelocation261 opcodes267 ADDLW267 ADDWF268 ANDWF269 ANDfunction268,269 “maskoff”bits268 ANDfunctiontruthtable268
Index logicalAND268 testmultiplebitstoseeifallare zero269 BCF269 BSF269 BTFSC270 BTFSS270 CALL271 label271 CLRF271 CLRW271 CLRWDT271 COMF272 DECF272 DECFSZ272 GOTO273 INCF273 INCFSZ273 IORLW274 IORWF274 MOVF275 MOVLW275 MOVWF276 NOP276 ORfunctiontruthtable274,275 RETFIE276 RETLW276 assemblerequivalentofMBasic’s ByteTable276 look-uptable276 RETURN277 RLF277 RRF277 SLEEP278 SUBLW278 SUBWF278 SWAPF279 XORLW279 XORWF279 PIC’sinstructionset260 specialpurposeregister Statusregister266 !Borrow267 !PD266 !TO266 CCarry/!Borrow267 DCDigitcarry/!Borrow267 IRP266 Z266 stepwisesubstitution413 storageregister(file)261 value261 assemblerterminology address261 file261 literal261 move260,261 opcode261 movlw261 movwf261 register261 workingregisteriscalledw261
AT24C512700 AT24C512serialEEPROM705 automaticallyconvertthefiletothenew version730 automaticscaling3-digitdigitalvoltmeter218 7-segmentLEDdrivercircuit218
B banksel733 Bank0RAM732 barometricpressure691,692 barometricpressureadjustmentfactor 693 barcodes595 bars595,601,618,619,626 value596 barvalue596,597 bytetable620 character595 complementary598 leftsidecharacter599 rightsidecharacter599 checkdigit597,627,628 calculatedwiththefollowingalgorithm627 code39595 code3of9595,596,597,600,601, 606,614,615,616,617,619, 622 computethecheckdigit625 EAN-13630,631 checkdigitcomputationchanges 631 left-of-centerdigits630 oddparity630 paritycomputations630 element595,596,597,601,606,607 centerguard601 centerguardpattern597,598 elementallengths623 centercharacter623 startandstopcharacters623 elementlength617 guardpatterns597 leftandrightparts597 elementduration bank0611 bank1611 bank2611 clrf611 compilerinstruction611 STACK=10611 donotpreloadthecounter614 FSR611,612 INDF611,612 indirectmemoryaddressing611 interrupts disable612 IRP611 israsm612 PEEK611
763
POKE611 timer1606,607,608,610,612 prescaler608,610 Timer1.Byte1608 Timer1H608 timer1interruptflag612 Tmr1IF612 elementwidths606,619 measurethewidthofabarcode element606 threearewide596 widthof1,2,3or4units597 integerdivision625 inter-characterspace596 modulus596 interrupt617 interrupts BankSel606 GIE605 HSerIn605 HSerOut605 incf606 interruptonPortB605 RBIE605 RBIF605,606 interrupthandlercode613 interruptflag613 isram614 RBIF613 Tmr1H614 Tmr1IF613,614 Tmr1on614 timer1613,614 itemnumber597 left-of-center626 manufacturerIDnumber597 UniformCodeCouncil597 MBasicversion5.3.0.0 memorymodel611 module595 modulus597,615,617,622,623, 625 moduluswidth596,619 numbersystemcharacter597 quietzone595,596,597,612 RAMmemory624 right-of-center626 rounding625 rules596 scandirection623 directionlessscanning623 left-to-right623,624 right-to-left623,624,628 spaces595,601,618,619,626 value596 spacevalue596,597 startcharacter596 stopcharacter596 timer1615 transition interrupt602,603 Disable603
Index enable603 portmismatch603 RBint602 RbInt603 UniversalProductCode,revisionA (UPC-A)595,596,597,598, 601,603,622,623,624,626, 627,630,631 EAN-13630 start,stopandcentersymbols622 wand595,599,601,602,606,607, 612,624 HBCC-0500600 howIidentifiedthecorrectpinconnection599 wand-lift612 wand-timeout612 wandrevertstowhiteidle606 weakpullupresistors603 bargraphdisplay80 BasicStamp18 backwardscompatibilitywiththe18 BasicStampcompatibility738 baudmodeconstant732 BCD2BIN719 BCD2DEC738 BCD2DECisBCD2BIN738 BIN2BCD720 Bin2BCD116,117 BIN2BCD&BCD2BIN755 BIN2BCDandBCD2DEC738 binarycodeddecimal(BCD)116,117, 718,719,720 packedBCD117 binarycodeddecimal(BCD)tobinary 719 binaryweightedtree633 bitorder742 bolt-inassemblerfunctions295 ASM297 routines296 Stack=10compilerdirective297 usinganin-linemacroor_@macro 297 stepwiserefinement295 bolt-inreplacements281 Branch756 BSR453 BSRSystemX10453 buffers176 Butterworthlow-passfilter511 Button756 bytelengthrandom740
C capacitance691 Capture16L2H207 Capture4L2H207 capturemode203 capturefunctionisexecutedindependently207 captureinterruptflag207
timer1203 usingthecaptureinterrupt203 carriagereturn445,715,716 CCP1203,208 CCP1Con578,743 CCP1INT203 CCP1Int208,210 CCP2203,208 CCP2Con578,743 CCP2INT203 CCP2Int208 CCPR1203 CCPR2203 CCPRxCON576 CCPRxL576 CCPRxL:CCPRxCON576 CCPmodule208 centralprocessingunit(CPU)1 clamp574 clampingdiode35 clampingdiodeshouldbeafast switchingdevice,suchasa Schottkydiode35 clampdiode110 Clear742 clearfunction mustprecedeSetHSerial158 clock(SCL)390 clockfrequencymustbeenteredinHz, notMHz730 CMOScompatible571 commandbyte708 commandbytes708 commoncathodedisplays108 CompareSpecial210 comparemode203,208 CCP1Int210 CompareSpecial210 SetCompare208,210 timer1203 timer2203 compilerdirective731,732 CompilerOptimizeSize/Speed734 compilervs.interpreter25 complementarymetaloxidesemiconductor(CMOS)configuration 28 ComTest152 Configurationdialogbox741 constants16 continuationsymbol15 controlbyte708 conversionclock702 cosinefunction421,425 cosinetransitioncurrentwaveform424 counters194 CRC(cyclicredundancycode)234 CTS163 CTSandreceiveddata163 CY7C128A415
D 764
Darlingtontransistor39,110,135 turnofftime40 data(SDA)390 datalogger691 datamemory1,2,261 banks261 files261 opcode’sdestinationbit262 registers261 registerfiles general-purposeregisters261,262, 263 accesses263 specialfunctionregister261,262 CCP1CON263 INTCON263 SSPSTAT263 unimplementedaddress261 workingorWregister262 dataRAM6 DCE(datacommunicationsequipment) 159 DCcircuits542 highsideswitching542 lowsideswitching542 PWM542 DCmotor567 comparator571 MCP601572 op-amp571 tachometer571 controlalgorithm572 bang-bang573,582,584,585 dynamicchanges585 speedchangecommands585 staticspeedcontrol585 proportional,integralandderivative (PID)573 PIDcontroller573 proportional(P)573 bang-bang573 hardwarepulsewidthmodulation573 residualerror573 proportionalandintegral(PI)and proportionalandderivative (PD)573 derivativeoftheerror573 error573 integraloftheerror573 PDcontrollers573 PDsystems573 PIcontroller573 controlsystem568 algorithmandcontrolmechanism 568 errorsignal568 controlinput(target)568 controlloop568 feedback568 tachometer568 summingpoint568
Index comparesfeedbacksignalwith target568 error(targetminusfeedback)568 errorsignal568 convertingthesinusoidaltachometer outputtoadigitallogiclevel signal570 MBasic PulsIn570,571 PulsIn’ssyntax571 unittimestep570 dutycycle575 feedback567,568 MBasic PulsIn572 sinusoidalsignal limiter571 squarer571 comparator571 squarercircuit571 tachometer571 tachometeroutputfrequency period569 DCmotorcontrolprograms573 bang-bangcontrolloop582 commutator574 hardwarepulsewidthmodulation (PWM)575,576,581 dutycycle575,576,582 HPWM575,576 MBasic’ssoftwarePWMprocedure 581 PWMoutput durationofthehighoutput576 formula576 PWMperiod576 repetitionperiod575 setandforget581 hardwarePWMmodules574,576, 577,578 associatedcontrolregister578 CCP1Con578 CCP2Con578 dutycycle577,580 howtoturnitoff578 HPWM577,578,581 oscillatorclockperiod578 period577 PR2576 formularelatingperiodtothese twovalues576 prescalerdividevaluefortimer 2576 formularelatingperiodtothese twovalues576 prescalecontrolbits T2CKPS0576 T2CKPS1576 T2CON576 timer2576 prescale576 tachometer579,581,582
PulsIn581,582 spuriouspulses PulsIn581,582 spurioustransition581 DCmotorspeed ACtachometer569 conditionaDCoranACtachometer’s outputtobePICcompatible 569 DCtachometer569 commutatornoise569 lowpassfilter569 dutycycle584 dynamicbraking592 error572 oscillatingerrors587 staticspeederror588 gaininthefeedbackloop586 oscillatingerrors587 opticalormagneticsensors569 over-damped587 overshoot587 proportionalcontrol588 hardwarePWMmodules590 reversiblePWMcontrolledcircuit 590 SN754410588,592,593 PWMmodule593 sensorlesssystems569 systemsnotemployingtachometers 569 tachometeroutputfrequency569, 570 determiningthetachometerconstant570 GR1531ABStrobotac570 relationshipbetweenACgenerator (ormotor)poles,frequencyand RPM570 Strobotac584 unitsteps572 DCpermanentmagnetmotor567 ACtachometer567 brush-type567 built-intachometer567 pulse-widthmodulated(PWM)variablespeed567 tachometerfeedback567 Dec736 DEC2BCD738 DEC2BCDisBIN2BCD738 decfsz434 decodingvariablelengthcodes633 defaultstacksizeis17730 detenttorque121 developmentboards13 cautioninconnectingdevicestothe +5VregulatedsupplyinBasic Micro’sdevelopmentboards 71 in-circuitprogramming14 models0818and284023
765
model0818for8-and18-pinDIP13 model2840for28-and40-pinDIP 13 dialtone371 dielectricconstant691 digital-to-analog337 digital-to-analogconversion(DAC) 335,336,338,339,340,341, 342,348,349,352,353,574 alternativeanalogoutputsolutions Pauseus357 pulsewidthmodulation(PWM) 352 PulsOut355,357 Sound355,356 invokes356 Branch357 digitizeatimevariantsignal337 directdigitalsynthesis(DDS)335, 338 jumptable348,352 arbitrarywaveform352 literal348 retlw348,352 outputfrequency342 phaseaccumulator342,345,347, 348 phaseadvance349 phasestep342,348 phasestepinterval347 relationshipamongstthevarious parameters342 samplespersecond342 samplerate348 erroranalysis337 errorsources ACerrorsinthelow-passfilter337 errorsinthelow-passfilter337 linearityerror337 outputbufferamplifiererror337 quantizationerror337 referencevoltageerror337 formuladevelopedinChapter11for calculatingtheADCstepsize appliestoaDAC335 GoTo357 integerconversion344 floatingpoint344 phaseaccumulator344 interrupts348 GIE348 ISRASM348,349 bitclear348 bitset348 PEIE348 timer2347,348 constants347 postscaler347 timer2isenabled348 low-passfilter338,356 10KHzlow-pass340 multiplefeedbackdesign340
Index 1KHzlow-pass339 Bessel338 Butterworth338 activeRClow-passfilter340 Cauer(elliptical)338 Chebyshev338 linearphase338 LT1634CCZ-4.096voltagereference 336 LTC1062339,340,349,356 ButterworthactiveRClow-pass filter340 outputs340 ratiopin339 LTC1062switchedcapacitorlowpassfilter338 multiplefeedbackactiveRCfilter 338 Nyquist’ssamplingrate338 Nyquist’ssamplingtheorem337 highestfrequencythatmaybegeneratedwithouterrorisone-half thesamplingrate337 programmableattenuator336 pulsewidthmodulation(PWM)352, 353,356 quantizationerror336 relationshipbetweenPWMand FreqOut355 resolution336 signal-to-noiseratio(SNR)337 Nyquistsamplingrange337 relationshipbetweenthemaximum signaltonoiseratioandthe numberofbitsinthesample 337 SNRdb337 spectrumanalysisplots349 TLC7528339 chipselectpin339 currentmode339 current-to-voltageconverter339 DACA/Bpin339 voltagemode339 writeenablepin339 TLC7528parallelloadingdual8-bit 336,337 quantizationnoise337 digitalinput53 currentthatflowsinoroutofaninput pinisduetoleakage57 hardwaredebouncing58 integratedcircuitdebouncers58 simplecircuit58 inputpinsrepresentahighinput impedance57 internalpull-upresistors57 RB0…RB757 pull-upresistors57,58 readingakeypad63 matrixswitches63 programtotestkeypadreading64
pull-down63 sealingcurrent58 softwaredebouncing60 switch58 built-inswitchdebounceprocedure Button60 illustrateshowButtonmaybe used61 debouncetheswitch58 mechanicalswitchoperates,the samecontactbounce58 softwaredebouncing60 switchbounce58 wettingcurrent58 digitalpotentiometers487 activelow-passfilter511 audiotaper506 Butterworthfilter512 Butterworthlow-passfilter511 Sallen-Key511 commandinganMCP41010bythe RS-232serialport493 converttheinputstringtoanumericalvalue496 linefeed495 commandbytes491 dummycommand491 setthetapsetting491 shutdownmode491 commandselectionbits490 controlinterfaces487 1-wire487 three-wire(SPI)487,489,491 MCP41xxx/42xxxfamily487 Microchip’sSI/SOdesign500 cut-offfrequency512 decibel506,507 changeinsoundlevel(dB)507 perceiveddifference507 powerratioformula507 minimumdifferencethatisperceptibleasachangeinvolume 507 DS1302489,490,491 LSBfirst491 LSBFIRST491 LSBPRE491 goodandbadpointsofdigitalversus mechanical488 taperedresponse506 logtaper506 MCP41010489,490,491,492,493, 495,496,497,506,507,508, 509,510 1dBstep509 accuracyoftherelativesteps491 blockingcapacitors508 bytetable509,510 connectanaudiosignal508 converttheinputstringtoanumericalvalue496 digital-to-analogconverter492
766
linearity492 linefeed495 maximumandminimumvoltage requirements507 multipledual-potdevices498 relativeaccuracyerror491 rightjustify496 toconvertanumericalcharacterto itsnumericvalue496 voltage-outputdigital-to-analog converter492 volumelevel506 MCP41xxx488,491,499 MCP41xxx/42xxxdevices487,488 residualresistance487 resistancebetweenterminalsA,B andthewiper488 resistanceofthe“wiper”connection487 MCP42010498,501,512,513 SPI517 MCP42100513 MCP42xxx488,499,500 commandbyte499 CS499,500 datainreverseofthedeviceconnections500 instructionbyte499 shiftin(SI)pins499 shiftout(SO)pins499 MCP42xxx/41xxx490,491,506, 507 cannotbeoperatedwithavoltage belowVSSoraboveVDD507 chipselectpin491 data beforetheclockpulse491 MSBfirst491 Microchip’sSI/SO500 multipledual-potdevices498 outputvoltageisDnmultipliedbya constantfactor492 potentiometer487 potentiometerselectionbits491 rheostat487 statement ShiftOut491 MSBPRE491 taperedresponse506 variableresistance487 variableresistor487 variablevoltagedivider487 voltagedivider492 volumecontrol487 digitalsignallevels53 inputlogiclevelspecifications54 inputvoltageagainsttheoutputvalue 54 logicalhigh53 logicallow53 RC3/RC4Schmitt54 Schmitttriggerinputs54
Index correctlyreadaninputsignalinthe presenceoflargenoisevoltages 57 hysteresis56 noiserejection56 specialSchmitttriggerinputs54 thresholdvoltage53 TTL54 TTLlevel53 undefinedregion53 VIH--Theminimumvoltageonan inputpinthatwillbereadasa logicalhigh53 VIL--Themaximumvoltageonan inputpinthatwillbereadasa logicallow53 diodethyristor(diac)543 directdigitalsynthesis(DDS)338, 340,341,342,345,348,349 clockjitter345 definition340 externaldigital-to-analogconversion (DAC)338 FREQOUT338 FreqOut356 hardwarePWM339 minimumfrequencystep348 numericallycontrolledoscillator340 phaseadvance341 pulsewidthmodulated(PWM)338 PULSOUT338 PWMprocedure338 doesnotusethePIC’shardware PWM339 SOUND338 Disable100,210 DS12B20235 DS1302709,718 DS1302real-timeclock243,244,246, 247,248,249,250,251,252, 256,257 accuracy244 aliased247 binarycodeddecimal(BCD)247, 252 BCD2BIN252 chargercontrolregister250 commandbyte251 clock/calendarburstread251 ShiftIn251 ShiftOut251 commandbytestructure247 exchangedatawith247 bytesofdata247 commandbyte247 HserOut252 initialize247 internalcharger247 LSB-firstbitorder249 LSBFIRST249 ShiftIn249 ShiftOut249
LSBPRE257 ShiftIn257 ShiftOut257 masterwriteprotectbit248 registerstructure246 clockburstregister246 controlregister246 date(dayofmonth)246 dayofweek246 hours246 minutes246 month246 seconds246 tricklechargercontrol246 year246 resetline244 resetpin251 reversecurrentisolationdiodes250 risingedge244 serialclockeddata258 fallingedgeoftheclockpulse255 leastsignificantbitfirst258 MCP41010digitalpotentiometer 258 mostsignificantbitfirst258 risingedgeoftheclockpulse255 risingorfallingclockandbitorder 258 ShiftIn258 ShiftOut258 ShiftOut/ShiftIn258 validonthefallingedge258 validontherisingedge258 ShiftIn251 ShiftOut249,251,257 modes249 FASTLSBPRE249 FASTLSPOST249 FASTMSBPOST249 FASTMSBPRE249 LSBPOST249 LSBPRE{LSBFIRST}249 MSBPOST249 MSBPRE{MSBFIRST}249 SLOWLSBPOST249 SLOWLSBPRE249 SLOWMSBPOST249 SLOWMSBPRE249 supercapacitors251 leakagecurrent251 three-wireserialconnection243 ShiftIn243 ShiftOut243 tricklechargercontrolbits(TCS)250 writingdata257 ShiftIn257 DS1624700,708,709 DS18B20709 DS18B20temperaturesensor231,232, 235,236,237,238,239,240, 242,252,470 18B20234
767
accuracy236 command237 converttemperature237,238 copyscratchpad237 readpowersupply237 readscratchpad237 recallEEPROM237 writescratchpad237 commandvalues237 configurationregister236 high(TH)temperaturealarm237 low(TL)temperaturealarm237 converttemperaturecommand238 convertthefloatingpointCelsiustemperaturetoFahrenheit239 globaladdress238 increasedresolutionmeanslonger conversiontime236 one-wireprotocol231 “presence”pulse232 64-bitserialnumber233 addressedeitherindividuallyor globally233 masterwritestotheslave233 “issuingatimeslot”233 “timeslot”coding233 permissiblemodevalues234 resetpulse232 serialnumber234 scratchpadmemory238 scratchpadmemorycontents237 selectivelyaddress242 selectiveaddressversion242 universaladdressversion242 signbit238 variableresolution236 DS18S20231 DTE(dataterminalequipment)159 DTMFOut731,756 DTMFOut2731 dual-tonemulti-frequency(DTMF)360 ASCIIcollatingsequence383 inter-office360 dutycycle423,424 dynamicbraking592
E EEPROMmemory3,101,102,103, 389,393,394,398,403,407, 408,695,715,717 24AA16390 24FC515394,401 24LC16B390,393,394,395,396, 399 blockselectbitsdonotchange from000duringthemulti-byte I2Cout395 cannotspanablockboundary395 chipaddressbits394 chipaddresspins390 24LC515399 addressbankselection401
Index bankselection399 controlbyte401 I2Cout401 nonconfigurablechipselect399 AT24C256393 AT24C512393,401,403,406,407, 408 I2Cout407 linear64Kbyteaddressspace401 clock(SCL)390 controlbyte392 familytype392 10-bitcontrolsequence393 read/write(R/W)bit393 Bit0ofthecontrolbyteforaddresslengthinformation393 MBASICautomaticallyinserts thecorrectR/Wbit393 data(SDA)390 extendPIC’sinternalRAMbyswappingdatabetweenRAMand EEPROM403 external691 GroupA392 InterICbus(I2C)392,393,403 I2Csupportfunctions392 I2Cin392,395,408 I2Cout392,395,408 MBasic Randomfunction407 multipleserialEEPROM 24LC256396,398 chipaddress396,397 chipboundaries398 controlbyte398 I2Cin398 I2Cout398 memoryisorganized397 nodelayisrequiredafterreadingthe EEPROM395 parallelingmultipleserialmemory chips395 serialEEPROM389,408 chipaddressbits393 standardidentificationsystemfor genericserialEEPROMchips 390 SRAM408 staticRAM409 timetowritetomemory394 writethestringstoEEPROM101 writingtoEEPROM101 WriteDM101,102 EEPROMread717 EIA/TIARS-232E151 EnableHSerial87,157,176,731 end-of-linecharacter166 end-of-linecommand740 EPROM3 EPROMandEEPROM3 onetimeprogrammable(OTP)3 Epson/Seiko’sSED127867
Equ267 explicitend-of-linedefinition167 externalEEPROM691,695,711 externalmemory 24LC16B392 24LC256389 InterICbus(I2C)389 24LC256389 parallelaccessmemory408
F FADD729 familycode234 CRC(cyclicredundancycode)234 FASTLSBPRE732 FASTLSPOST732 FASTMSBPOST732 FASTMSBPRE732 fastswitching--soundfromaPIC50 drivingthespeakerdirectlyfroma PIC50 emitterfollowertodrivethe3.2ohm speaker51 self-containedsounder,suchasthe Sonalert50 FDIV729 flashmemory3 FLOAT729 FloatingPointMath755 FLOATTABLE729 floorfunction739 flowcontrol160,164 FMUL729 FNEG729 Fouriertransform(FFT)408 FractionalMultiply729 FreescaleSemiconductor,Inc.693 FreqOut731,756 FSUB729 functionarguments731 functionargumentsmaynowbeupto 32bits731
G GetTimer1733 globaladdressing237 globalvariables730 GoSub730 GoTo434,730 GPASM413,432,733 Graycode94
H half-stepmode731 hardwarepulsewidthmodulation (PWM)420,423 hardwarePWMmodule’speriod423 hardwareserialinput/outputcode module87 EnableHSerial87 HserOut87 SetHSerial87
768
Harvardarchitecturemodel2,261 high-sidedigitswitches109 highpowerbipolarlowsideswitching39 whyVCE(SAT)issopoor39 highpowerMOSFETlowsideswitching40 highsideswitching42 smallPNPswitch42 intelligentpowerMOSFETswitch41 IPS02141 turn-onandturn-offspeeds41 highsidedigitselectionswitch108 highsidesegmentdrivers108 highsideswitching31,42 addingan2N4401NPNtransistorto controlthebaseofQ142 centralprobleminhighsideswitchingwithaPNPtransistorora positiveMOSFET(PMOS)42 highpowerhighsideswitching43 auxiliaryn-channelgatecontrol device43 integratedhighsideMOSFET switch43 IPS51143 determinethestatusofthe IPS511wewouldimplement thefollowingpseudo-code45 statuspin43 smallPNPswitch42 calculatethebaseresistor42 highvoltageprogramming(HVP)23 HitachiHD44780controller/driver chip67 HM-1500692 holdingtorque121 hookswitch371 HouseCodes741 howtoturnoffthehardwarePWM module743 HPWM424,576,581,731,758 HPwm743 HSerIn151,155,158,159,175,176, 210,714,731 buffers176 HSerIn/HserOut157 HSerInandHSerOut742 HSerOut158,175,176,210,617,714, 731 buffers176 HserOut87,151,252,742 HSerStat158,159,175,176,714,715, 717,743,758 undocumentedcommand158,714 humiditysensors691 HWPM352 hybrid371 HyperTerminal87 Hyperterminal152
I
Index I2Cin389,697,708 I2Cin/I2Coutcontrolbyte708 I2Cin/I2Cout756 I2Cout389,697,708 I2Cdevice696 in-circuitprogramming14 in-lineassembler281 incrementalencoders92 inductiveload567 inductivetimeconstant128 InitLCD90 InitLCD174 InitLCD274 inputsignal194 inputswitches86 positionencoders91 relativeencoder95 readingarelativeencoder95 changefromearlierversionsof MBasic97 rotaryencoders91 absoluteencoders91 codeoutput94 differencebetweenhexadecimal andGraycode94 Graycode94 straighthexadecimalbinarycode 94 construction92 mechanicalencoders92 opticalencoders92 quadratureencoder93 quadraturesensor93 relativeencoders91,92 incrementalencoders92 shaftencoders91 InStr168 instructionwordlength3 INT729 INTASM733 integerdivision625 integerquotient722 integerremainder722 intelligentpowerMOSFETswitch41 internalpull-upresistors57 internalRCoscillator216 interrupt99,317 MBasicwillnotbreakexecutionofa statementtoserviceaninterrupt 100 RBINTtypeinterrupt100 turnoffadditionalinterrupts100 Interrupts743 InterruptsHandledinMBasic759 interrupthandler99,104 “enable”theRBINTinterrupt100 Disable100 EnableRBINT100 OnInterrupt100 Resume100 turnoffadditionalinterrupts100 interruptserviceroutine(ISR)207,
210,317 InterICbus(I2C)389 fastmode389 high-speedmode389 I2Csupportfunctions392 I2Cin392 I2Cout392 usesitsinternaladdresscounter 392 standardmode389 I2Cin389 I2Cout389 IPS02141 IPS51143 determinethestatusoftheIPS511we wouldimplementthefollowing pseudo-code45 statuspin43 IRfilter521,522 IRreceiver517,518,519,520,521, 522,523,524,526 burst524 carrierfrequency518 commonencodingstandards518 PhilipsRC-5Code518 biphase(Manchester)518 REC-80518,522,524,525,532, 534 checkbyte534 databyte534 dataorganizationsendingorder 534 errorchecking534 histogram525 inter-pulsedwelltime534 protocol519 PulsIn534 spacewidthmodulated518 startpulse534 Sony(SerialInfraredRemoteControlSystem,SIRCS)518 LSBfirst518 pulsewidthcoding518 typicalREC-80dataorganization sendingorder519 checkbytes519 devicecodes519 functioncodes519 datapulse522 detectsthesebursts518 GP-series522 GP1U5521 GP1U58x540 GP1UD26/27/28521 idlecondition523 IRfilter521 MBasic orderofprecedenceproblems535 PulseIn524 PulsIn523,524 unitsteps523 Mitsubishi534
769
startpulse534 photodiode520 phototransistor520 refertohighandlow,orpositive pulsesandnegativepulses,itis withrespecttotheoutputofthe IRreceiver521 startpulse522 startsignal519 TSOP-series522 TSOP1238540 TSOP12xx520,521 automaticgaincontrol(AGC)520 bandpassfilter520,521 opticalfilter520 photodiode520 unitintervals525 unitstepintervals524 histogram524,525 IRremotecontrol517 burstsofIRlight518 carrierfrequency521 ifyoudon’tknow,easytomeasure it521 MCP42010 SPI537 photoreceptor521 phototransistor521 power-on/power-offcode519 QSE114521 togglebit519 widththreshold523 histogram523 isolatedswitching31,45,62 opticallyisolatedMOSFET49 PS710A-1AisahighpowerMOSFEToptoisolator49 switchinghighcurrentsinmicrosecondtimes49 undesiredtransientsandoscillations49 opticalcoupler62 opticalisolatedNPNswitch48 lowpoweroptoisolator48 opticalcouplers48 optoisolators48 readaswitchclosurethatcannothave acommongroundwithyour PICcircuit62 relayswitching46 contactbounce48 goodthingsaboutrelays46 minimumcontactload48 notsogoodthingsaboutrelays46 operatetime47 pull-intime47 Reedrelays47 forcontactbounce47 turnson47 turnofftime47 releasetime47,48 snubbingdiode46
Index testthecontactclosureandoperate/releasetime46 voltagespikeevenasmallinductive loadgenerates46 switchedthrougharelay62 ISP-PRO8,10,11,14,23 universaladapter11 ISP-PROprogrammer10 ISRASM741,744,756 interrupt345 israsm614
K KeyCodes741
L latency208,743 LatencyinMBasicinterrupts743 LCD/configurationswitch88 continuationcharacter90 duplexingtheswitchandLCD89 InitLCD90 samepinstoreadfourswitchcontacts andoutputdatatoanLCD module88 LCDINIT73 newinversion5.3.0.073 LCDInit74,731 LCDINIT1731 LCDINIT2731 LCDRead/LCDWrite757 LCDWRITE731 LCDWrite73,75 LCDinitialization481,731 LCDmodules67 40×4display74 backlighting68 electroluminescent68 LED68 muchlongerlivedthanelectroluminescentdevices,withtypical expectedlifetimeswellover 50,000hours69 twomajordisadvantages68 reflective68 connectiontoPIC69 4-bit(nibble)transfermode71 calculatetheLEDcurrentlimiting resistor’svalue71 displaycontrast70 enable(E)pin71 read/write(R/W)pin71 registerselectpin70 crystaltechnology68 filmsupertwistednematic(FSTN) 68 supertwistednematic(STN)68 twistednematic(TN)68 customcharacters80 bargraphdisplay80 charactergeneratormemory (CGRAM)80,81,84
createcustomcharacters81 writethesecustomcharactersinto CGRAM82 flashingthetextoffandon78 fontselection79 extendedfontset79 writetheextendedcharacter79 initializationconstants74 CLEAR74 HOME74 SCR74 TWOLINE74 initializationmessagewithLCDWrite 73 initializeanLCDusingtheolder method73 InitLCD174 InitLCD274 LCDINIT73 newinversion5.3.0.073 LCDWrite73,75 LCDdisplaysizes67 charactersize68 dotmatrixsize68 numbersofcharacters67 LCDenvironmentalconsiderations 69 extendedtemperatureLCDs69,70 memorylayoutfor16×2and20×2 displays74 Off79 physicalconnectionsbetweenthePIC andtheLCDmodule73 SCR79 SCRBLK79 SCRCUR79 SCRCURBLK79 ScrLeft75,77 ScrRAM77 ScrRight75,77 selectinganLCDmodule67 vacuumfluorescentdisplay(VFD)69 writingatadefinedlocation77 LED32 calculatetheseriescurrentlimiting resistor32 connecttwoLEDstoonepin33 constantvoltagedrop32 MV5491Atwo-pindualLED33 producefourstatesina2-pindual LED33 theseriescurrentlimitingresistor wheretheLEDisonwhenthe PICdrivingpinishigh33 LEDdisplays107 alphanumericmultisegment107 dotmatrix107 seven-segmentLEDdisplays107 Bin2BCD116,117 binarycodeddecimal(BCD)116, 117 packedBCD117
770
commonanode108 highsidedigitselectionswitch 108 individuallowsidedigitselectors 108 commoncathode108 highsidesegmentdrivers108 lowsidedigitselector108 high-sidedigitswitches109 high-sidedrivers108 low-sidedrivers108 mapthedesireddigitstothesegments112 mountingstyle107 onereasontoprefercommonanode displays108 TRISA112 TRISB112 leftjustified708 lengthchecking737 librarymemory734 LinearTechnologyLT1634CCZ-4.096 precisionsource220 LiquidCrystalDisplays67 literal434 logicalhigh53 logicallow53 low-passfilter511 low-sidedrivers108 2N7000142 lowsidedigitselector108 lowsidedigitselectors108 lowsideswitching31,36 basetoemitterjunctionvoltage,VBE 37 determinecasetemperature36 hFEorDCcurrentgain37 highpowerbipolarlowsideswitching39 simplelowsideswitch36 switchingspeed37 storedchargeeffect37 turn-offdelay37 lowvoltagedevice7 lowvoltageprogramming(LVP)22,23 LSB-first540 LSBFIRST733 LSBPOST732 LSBPRE733 LSBPRE{LSBFIRST}732 LSBfirst742 LT1634-CCZ-4.096698 LT1634CCZ-4.096voltagereference 213,336 LVPprogrammingpinselection22
M “modulus”operatorusesthe//symbol 84 machine comparingMBasic,assemblerand machineinstructions260
Index macro264 advantages264 Macros744 macros281 assemblermacrosversusASMcompilerdirective289 “trimoff”theseexcesscompiler bits 290 logicalAND290 7-bitregisteraddress289 extractthe7-bitregisteraddress fromthe16-bitcompiler-generatedversion290 warningmessages289 InvalidRAMlocation289 registerinoperandnotinbank 0289 definition281 ISRASM294 beforeversion5.3.0.0294 librarymacros addresstrimming290 _@clrf290 _@opcode290 ASM290 MBasic729 “modulus”operatorusesthe//symbol84 //orremainderfunction435 //orremainderoperator342 MODor“modulus”function342 remainderdivision345 1-wireprotocol MBasiccurrentlysupportsonly theinitial14kb/sspeed1-wire protocol234 OWIn234 OWOut234 addingassemblercode281 ASMdirective282,287 ASM282 assembleropcodemacro282 opcode282 definition281 interrupthandler282 ISRASM282 librarymacro281,285 @Bank285 @Call285 @GoTo285 @High285,286 @Input285,286 @Low285,286 @MSDelay285 @Output285,286 @RatedDelay285 @Return285 @TblJmp285 @USDelay285 addresstrimming290 undocumentedfeature281
macro @Call287 @MSDelay287 @TblJmp287 @USDelay287 macronameisusuallyformed byaddinga“@”prefixtothe MBasicnormalname285 measurestatementexecutionspeed 282 ADin702,703 assemblerlanguage281 ASM284 Call284 GoSub284 latency283 prescaler283 timer1283,284 StartTime284 StopTime284 assemblermodule StartTime284 bcf284 clrf284 return284 t1con284 timer1284 tmr1h284 tmr1l284 turntimer1on284 StopTime284 bcf284 stoptimer1284 t1con284 timer1284 assembleropcodes281 BankSel413 bankselectionbits287 BasicStamp18 backwardscompatibilitywiththe 18 BIN2BCD720 Branchinstruction184 Branchlabel184 built-inwaveformoutputfunctions 352 FreqOut352 PulsOut352 PWM352 Sound352 CCP423 clearfunction mustprecedeSetHSerial158 cleartosend(CTS)161 comparingMBasic,assemblerand machineinstructions260 compiledlanguageoraninterpreted language?25 compilervs.interpreter25 counters194 countersection inputsignal194
771
threepossiblesources194 defaultistoreserve100%ofbank0 memoryforitsinternalstack 292 defaultstacksetting334 differentwayswecanassignapinto anoutputandtomakeitsvalue 019 Disable210 DTMFOut387 DTMFOut2387 enabletheinterrupts332 flagclearing332 FREQOUTprocedure338,352,353 fromversion5.3.0.0.onwards156 SerIn156 SerOut156 fromversion5.3.0.0onward, MBasic’sSPMotorcanbecommandedtooperateineitherfull steporhalfstepmodes138 fromversion5.3.0.0onward,wemay defineafloatingpointconstant directly205 hardwareflowcontrol161 SerIn161 SerOut161 hardwarehandshaking160 hardwarePWM575 howMBasichandlespinsandports 17 HPWM423,639 HSerIn151,210,714 HSerOut210,714 HserOut151 HSerStat714,715,717 undocumentedMBasiccommand 714 HWPM352 I2Cin389,695 I2Cout389,695,708 I2Creadprocedure395 I2Cin395 I2Cout395 in-lineassemblermacros281 assembleropcodes281 in-linemacrosfortheassembler mathematicaloperations299 high299 low299 inputs/outputsmodifiers17 Bin169 Dec169 Decn169 Hex169 iBin169 iHex169 isBin169,170 isHex169,170 Real170 Realn170 sBin169,170
Index sDec169,170 sHex169,170 undocumentedportionsofinput/ outputmodifiers169 inputandreaditsvalue20 InStr Branch184 convertthislettertoanordinaldigit 183 interrupts187,188 capture203 Capture16L2H207 Capture4L2H207 capturefunctionisexecuted independently207 captureinterruptflag207 SetCapture205,207 CCP1Int208 CCP2Int208 compare203,208 CCP1Int210 CompareSpecial210 SetCompare208,210 definition187 Disable193,202 Enable191,193 enable188,190 EnableExtInt190 EXTINT189 SetExtInt190 ExtInt190,192 Disable191 interruptrequestscollide202 interruptserviceroutine(ISR)187, 190,191,193,194,207,210 internalstacktooverflow191 lagtimebetweentheinterruptactionandstart-of-execution191 latency191,208 Resume190,191 SerIn187 significantrestriction187 timer1208 writtenpurelyinMBasic187 MBasicIdentifier188 Microchipacronym188 interruptflag188 OnInterrupt190,206,210,317 optionsfortheinterrupt190 programwithaninterrupt188 disable188 enabletheinterrupt188 linktheinterruptsourcewiththe nameoftheassociatedinterrupt serviceroutine188 RBINT192,193,194 Resume193 rotaryencoder192 switchbounce192 usingthecaptureinterrupt203 INxx,OUTxxandDIRxx18 ISRASM605
libraryconstants208 CompareInt208 CompareOff208 CompareSetHigh208 CompareSetLow208 CompareSpecial208 librarymodeconstants206 Capture16L2H206 Capture1H2L206 Capture1L2H206 Capture4L2H206 CaptureOff206 LVPcheckboxinMBasic’sconfigurationsetupdialogbox23 LVPprogrammingpinselection22 MBasicisanoptimizingcompiler andwillnotallocatestoragefor variablesthatareunusedwithin MBasiccode325 Clear325 modifiers undocumentedfeature172 maybeusedasfunctionsto convertanumericalvaluetoits stringrepresentation172 numericalinputvariables173 automaticbuffer173 indicatedinput173 caseconversion173 nonnumericalcharacters173 Real173 signedvalue173 terminationofinput173 ONBORbrownoutresetcommand 387 orderofprecedenceproblems535 Oscilloscope723 utilityprogram723 undocumented723 outputmodifiers169 OWin470 Owout470 parsinginputstrings178 convertanumericalstringofthe formnnnntoabinarynumber 178 convertastringoftheformwe mightusetorepresentadateor time,hh:mm:ssordd/mm/yyto threeseparatenumbers.178 PEEK611 pins17 designatorAN021 pinsthroughasequentialnumberingsystem18 pinaddresses20 input20 low20 output20 pinarchitectures28 pinassignmentswehavediscussed tothispointareruntimealter-
772
able21 pinvariables20 programtime21 12F629exampleofpinsconfiguredatprogramtime21 testingforapinvaluecondition21 POKE611 ports17 file17 GPIO(generalpurposeinput/output)17 lettersfromA…Eidentifyports17 register17 treatedinternallybythePIC’sCPU, andbyMBasic,asbyte(8-bit) variables17 variable17 portorapinasanaddressorasa variable19 predefinedbaudmodeconstants156 preselector207 proceduresforserialcommunications 156 hardware(USART)-based157 Clear158 EnableHSerial157 goodandbadpointsof158 HSerIn157,158,159,175 HSerIn/HserOut157 HSerOut157,158,175 HSerStat158,159,175 interactionbetweenClearand SetHSerial158 receiveinput157 SerIn158 SetHSerial157 syntaxforHSerIn158 syntaxforSetHSerial157 universalsynchronous/asynchronousreceiver/transmitter (USART)157 USARTtransmitoutput157 software-based flowcontrol157,160 goodandbadpointsof158 parityerror157 SerDetect157 SerIn156,157,159,160 SerOut156,157,159,160 syntaxforSerIn156 syntaxforSerOut157 Timeout157 programtime21 12F629exampleofpinsconfigured atprogramtime21 configurationdialogfor12F629 –oscillatorconfiguration22 Pu_Off23 Pu_On23 PulsIn572,581 unitsteps572 PULSOUT338
Index PulsOut355,412,415 PWM581 PWMprocedure338,339,352,353 HWPM339 RBint602 ReadFunction214 ADIN214 ADIN16214 registeraddress287 remainder84 requesttosend(RTS)161 ReversePolishNotation25 revisedbaudmodeconstants156 SerIn151,156 SerOut151,156 SetPullUps23,57 SetTmr1206 SIN344 SOUND338 Sound355,356 standardmodifier/expressionrules 392 stringoutput doesnotcheckthelength170 undocumented170 Terminal162 timers187,194 comparator195 counter195 definition187,194 howtoget“shortcount”195 inputsignal194 interruptcondition195 interruptsource195 post-scalers187 postscaler195,196 prescaler187,194,196 timer0187,195 TMR0195 timer1187,195,196,197,201, 202,209,210 clocksource202 measuretheexecutiontimeof variousMBasicstatements196 preload202 preloadislostwitheveryrollover andmustbere-enteredafter everyinterrupt202 preselectordivisionratio197 requiredpreloadvalue202 settingtimer1’scounterdivision ratio202 setuptimer1197 Tmr1H195,202 Tmr1Int202 Tmr1L195,202 timer2187,195,198,209 16possiblepostscaleratios199 comparator200 errorsinmodelibraryconstants 199 interrupt,Tmr2Int200
interruptinterval200 interruptserviceroutine(ISR) 200 maximuminterruptperiod200 modelibraryconstants199 setupfunction199 TMR2195 turncounteron/off195 timersandinterruptsworktogether 198 ToFloat703 undocumentednumericalmodifiers 173 USARTtransmitoutput157 variables287 arrays289 mayoccupymorethanonebank, butwithinthearraynovariable willbesplitacrossbanks289 bits/nibindex288 compiler287 baseaddress288 compilerassignsthevariablea 16-bitidentifier288 willnotsplitamulti-bytetype variableacrossdifferentbanks 289 compilercontrolbits288 multi-bytetype288 thewayMBasicpassesvariable informationontotheassembler 287 GPASM287 MPASM287 variableaddress optionsinusingMBasicvariable addressesinassemblercode 290 versionspriorto5.3.0.0323,398 I2CinandI2Coutprocessesfreeze whenaddressingmemory 65535398 ISRASMprocedures322 MPASMassembler323 necessarytoobtaina9-bitregisteraddressforbanksel323 version05.2.1.1208 version5.2.1.1349 version5.3.0.0445,572 ADIN16216 GPASMassembler323 memorymodel611 version5.3.0.0friendly349 version5.3.0.0onward432 GPASM432 willnotbreakexecutionofastatementtoserviceaninterrupt 100 Xin453,454 Xout453,454 MBasic8768,10,11 2840developmentboard8
773
ISP-PRO8 MBasiccode AByte=0298 AByte=Abyte+1300 AByte=AByte-1301 decf301 Statusbit302 AByte=AByte-Constant304 subwf304 AByte=BByte+CByte302 addwf302 AByte=Constant299 AWord=0 298 AWord=AWord+1300 btfsc300 Status300 Status300 AWord=AWord-1301 btfsc302 movf302 AWord=AWord-Constant305 subwf305 AWord=BWord+CWord303 @bank303 addwf303 btfsc303 incf303 Status303 AWord=Constant299 ByteTable311 alternativetoMBasic’sByteTable 311 Call312 call311 computedGoTo311 GoTo312 retlw311 ByteVariableArrayReadandWrite 313 fileselectionregister313 FSR313,314 FSR/indf313 INDF314 indf313 indirectfileregister313 indirectmemoryaddressing313 IRP313,314 keywordconflictbetweentheassembleroperatorHIGHand MBasic’sHighfunction314 movlw314 RP1:RP0313 Status<7>313 Division(Special)307 @GoTo308 decfsz308 RRF307 Status307 For…NextLoop310 @GoTo310 btfsc310
Index movf310 movlw310 Status310 Remainder(Special)306 remainderoperation,//306 Set/ClearPortBit308 @bank309 bfc308 bfs308 MBasiccommand High308 low308 Output309 Set/ClearPortBitandSettoOutput 309 bcf309 bsf309 TRIS309 TRISA309 TRISB309 SwapAByteandBByte305 Swap305 MBasiccompiler10 certainthingsareomittedintheschematics17 choiceofPIC MBasic87617 substitutea16F876or876A 17 constants16 continuationsymbol15 developmentboard11 developmentboards13 in-circuitprogramming14 model0818for8-and18-pinDIP PICs13 model2840for28-and40-pin DIP13 highvoltageprogramming(HVP)23 ISP-PROprogrammer10 lowvoltageprogramming(LVP)22, 23 MBasicProfessional10 noteonserialports11 professionalversion10 programmingstyle15 prototypeboards13 in-circuitprogramming14 model08/18prototypeboard13 model28/40prototypeboard13 diagramof14 software10 standardassumptions16 standardprogramLayout15 standardversioncompiler10 subroutinenames16 verb-noun16 taxonomyofMBasicfunctionsand procedures11,12,13 updatedMBasiccompiler(version 5.3.0.0)10 variables16
adjective-noun16 indexorcountingvariables16 MBasiccompilersoftware10 MBasicfunction755 MBasicinterrupt741 MBasicProfessional10 MBasicversion5.3.0.0729 MCP41010digitalpotentiometer258 MCP601698,699 MCP601op-amp213 MCP601op-ampbuffers220 measurecapacitancewithaPIC691 memoryandvoltagedesignators4 MFsignaling361 Microchip’sGeneralPurposePIC2 24LC16B390 instructionwordlength3 linename2 base-line(12-bit)2 high-end(16-bit)2 mid-range(14-bit)2 programcounter436 MicrochipTechnology,Inc.1 literal267,434 microstep425 microstepping bitshifting rotateleftthroughcarryflag(RLF) 435 MiddleMult729 milli-Newton-meters129 modem159 modifiersasfunctions737 Morsecode375,377,633,641,652, 654,655,656,661,668,671, 684,687 amateurradio661 ASK(amplitudeshiftkeying)661 binarytree654,656 binaryweighted656 bytetable656 continuouswavetransmission(CW) 634,661 dash/dot637 dashes633,634,637,639,640,641, 651,652,653,654,655,656 dashbranch654 dashduration647 decodingvariablelengthcodes633 binaryweightedtree633 dot/dash652 dot/dashratio633,635,668 theoreticallyperfectdot/dashratio 635 dots633,634,635,637,639,640, 647,651,652,653,654,655, 656 dotbranch654 dotduration647 EEPROM651,658,659 Atprogramtime,MBASICfillsall 256EEPROMcellswiththe
774
value$FF,overwritingtheir priorcontent659 currentvaluesofspeed,weightand handsavedtoEEPROM658 readatprogramlaunch658 elementspersecond(EPS)isrelated tothespeedinwordsperminute(WPM)636 encoder646,648,649 end-of-charactersignal652 end-of-characterspace653,654 functionandvalueencoders646 functionencoder648 functionselection642 howMorsecodeissentandreceived 661 HPWM639 iambic637,639 iambicpaddle633 inter-elementspace653 interrupt641 keyer633,635,639,649,668,682 keyers635 keydown635 levelweighting656 mapeachMorsecharacterintoa uniquenumber655 millisecondsperelement636 Morsecharacters634 Morsecode controlloop over-damped667 nil656 OOK(on-offkeying)661 paddle633,635,639,646,647,651, 653 Pauseus640 pro-signs634 proceduresignals,AR,SKandSN 634 prosigns655 pull-upresistors635 PWMhardwaremodule637,639 RBINT647 readingMorsecode661 adaptivealgorithm661 amateurradio661 arithmeticalaverage673 arithmeticalmean666 ASK(amplitudeshiftkeying)661 bandwidth668 interactionwithcenterfrequency 668 bandwidthandcenterfrequency interaction668 beatfrequencyoscillator(BFO) 661 binarynumber684 binarytree684 bytetable684 centerfrequency665,666,668 interactionwithbandwidth668
Index circularbuffer675 complementaryoutput664 computestheestimatedcodespeed 676 controlloop666 damping666 dampingfactor667 oscillate666,667 overshoot666 under-damped667 undershoot666 controlsignal662 dash682 dash/dotratio671 dashes668,670,671,680,681, 683,686 dashbranch684 demodulation661 demodulator661 designparameters centerfrequency665 trackingbandwidth665 dots668,670,671,680,681,682, 683,686 dotbranch684 dotlength665,681 double-sidedbandwidth667 doublesidedbandwidth666 drop-outfrequency668 easurethetimeittakesforthemain programlooptoexecutein idle681 elementlengthdistribution672 end-of-characterspace683 endofword682 error662 errorsignal664 frequencyshiftkeyeddatasignals 661 geometricmean666 HSerOut686 inter-elementspace680 inter-lettertime682 letterspaceinterval682 lock667 lockbandwidth665 lockdetector665 lockrange667 lockup667 lockuptime667 lockuptimeofthetonedetector comparator667 loopcontrol664 loopphasedetector664 MBASIC5.2.1.1670 PulsIn670 MBasic5.3.0.0remediesproblem 670 normaloutput664 numericalbinarytree680 one-sidedbandwidth666 OOK(on-offkeying)661
out-of-lock667 Pauseus670 phasedetector662,663,664 phaselockedloop(PLL)661,662, 666,667 inlock664 locks664 unlocked664 pull-infrequency667,668 pull-upresistor667 quadraturephasedetector664 receiver661 Schmitt-trigger669 scrolling687 singlesidebandmode(SSB)661 singlesidedbandwidth666 stepresponse666 thresholdvalue;elementslonger thanthethresholdaredashes andshorterelementsaredots 671 timer1670 tonedecoder665,669 tonedetection661,664 tonedetector661,663,667 XR-2211661,662,664,665, 666,667,668,669,670,671, 680,682 tonedetectphasedetector667 trackingbandwidth665 TTL-level669 upperandlowerdropoutfrequencies667 upperandlowerpull-infrequencies667 voltage-controlledoscillator(VCO) 662,663,664,666 adjustRPtocenter667 weightedbinarytree685 wordspace682,683 XORlogicgate663 recommendedelementandspacing lengths668 rotaryencoder641,642,647,657 interrupt-driven641 scrolling657 sidetone635,639,647 spaces633,634,652 speed636,642,650,658 speed,weightandselector646 squarecursor658 standardword“PARIS”636 valueencoder648 valueselection642 variablelengthcode634,652 weight635,641,642,648,650,658 weightedbinarytreeconversion655 weighting635 wordsperminute636 wordspace652,653,654 Motorola693 movf434
775
movlw434 movwf434 MPASMassemblerandlinker733 MPX6115699,725 MPX6115A6U693 MSBFIRST733 MSBPOST732 MSBPRE733 MSBPRE{MSBFIRST}732 MSBfirst742
N NationalElectricalManufacturersAssociation(NEMA)124 Newdefinitionof_MHZ733 Newreservedwords733 nibble368 nominalcapacitance691 noerrorchecking730 Nyquistsamplingrate211,345
O offsetvoltage213 one-wireprotocol231 64-bitserialnumber233 addressedeitherindividuallyor globally233 bytesaretransmittedandreceived fromlowestaddresstohighest address235 CRC(cyclicredundancycode)235 familycode234 familynumber235 globaladdressing237 OWIn231,234,238 OWOut231,234 parasiticpowering233 permissiblemodevalues234 reset238 resetpulse232 serialnumber234,235 OnInterrupt100,210 OOK(on-offkeying)661 openloop120 opensystemsinterconnection(OSI) referencemodel151 operationalamplifiers511 opticallycoupledFET542 opticallyisolatedMOSFET49 PS710A-1AisahighpowerMOSFEToptoisolator49 switchinghighcurrentsinmicrosecondtimes49 undesiredtransientsandoscillations49 opticalcoupler62 opticalcouplers48 opticaltachometers92 OptimizeforSize734 OptimizeforSpeed734 OptimizingforSize734 optionaldatabyte708
Index optoisolators48 lowpoweroptoisolator48 orderofentry738 orderofprecedence733 orderofprecedencerulesforarithmetic 433 oscillatingerrors587 OSIstack151 outputbuffer742 OWIn234,238 OWin/OWout757 OWOut234
P P0…P31733 packedvariables717 parallelaccessmemory408 CY7C128A409,410,415 ‘843latch415 74ACT574409 74ACT843 9-bitlatch409 latchenable(LE)pin409 addressinputs409 bidirectionalI/Opins409 highimpedancestate409 controlpins409 chipenable(CE)409 outputenable(OE)409 writeenable(WE)409 Fouriertransform(FFT)408 SRAM408,409,410,413,416 tri-state416 staticRAM409 parametersandareturnedvariable729 parameterMdelay136 parasiticpowering233 parsinginputstrings178 Pause731 Pauseus357,731 peripherals2 phaseaccumulator348 phaseadvance349 phaseandcyclecontrol549 phaselockedloops661 photo-diode48 photodiode520 phototransistor48,520,521 PIC’sinstructionset260 PICmicromicrocontrollers1 “CCP”hardwaremodule203 16C781338 16C782338 absolutemaximumratingsfor 16F87XPICs29,30 currentthatflowsinoroutofaninput pinisduetoleakage57 datamemory261 fastswitching--soundfromaPIC50 highsideswitching31 howdoIpickone?7 inputpin
CMOScompatible571 Schmitttriggertype571 TTLcompatible571 inputpinsrepresentahighinput impedance57 interrupt317 isolatedswitching31,45 opticalisolatedNPNswitch48 relayswitching46 goodthingsaboutrelays46 notsogoodthingsaboutrelays 46 Reedrelays47 testthecontactclosureandoperate/releasetime46 ISP-PRO23 LED32 calculatetheseriescurrentlimiting resistor32 connecttwoLEDstoonepin33 constantvoltagedrop32 MV5491Atwo-pindualLED33 producefourstatesina2-pindual LED33 theseriescurrentlimitingresistor wheretheLEDisonwhenthe PICdrivingpinishigh33 whenthePICdrivingpinislow32 lowsideswitching31,36 basetoemitterjunctionvoltage, VBE37 determinecasetemperature36 hFEorDCcurrentgain37 simplelowsideswitch36 switchingspeed37 storedchargeeffect37 turn-offdelay37 lowvoltagedevice7 mainelementsinsideaPIC1 centralprocessingunit1 datamemory1,2 peripherals2 programmemory1,2,3 EPROMandEEPROM3 extendedvoltage3 flashmemory3 memoryandvoltagedesignators4 partiallistofpackagedesignators4 read-only3 standardvoltage3 temperaturerangedesignators4 maximumsafeparametersapplyto the16F87xseries29 physicalconnectionsbetweenthePIC andtheLCDmodule73 PICSsupportedbyMBasic4 PICswithamultipartidentifier2 casestyle2 familynumber2 maximumclockfrequency2
776
programmemorytype2 silicondielayoutrevisionsuffix2 temperaturerange2 programmemory261 pull-upresistors23 internalpull-upresistors23 smallN-ChannelMOSFETswitch 37 differencebetweentheMOSFET andNPNbipolartransistor38 highpowerMOSFETlowSide switching40 highpowerMOSFETlowside switching40 MOSFETs,gatecharge39 relationshipbetweenRDS(ON)and thegatevoltag38 speed7 stateofinputpinsRB4…RB7change 99 switchinginductiveloads34 calculatetheinductivespikelevel anddecaytimeanalytically,but it’smucheasiertouseaSPICE simulationprogram35 clampingdiodeshouldbeafast switchingdevice,suchasa Schottkydiode35 peakvoltagespikeandcurrent decaytimesinteractforthe circuit35 switchingspeed37 Zenerdiode35 terminalsoftware152 timers7 USART7 weakpull-upresistorsforPortB23 PicoElectronics453 PICSsupportedbyMBasic4,5,6 piezoelectric693 pinarchitectures28 complementarymetaloxidesemiconductor(CMOS)configuration 28 RA4isdifferent;itisconfiguredasan opendrainMOSFET29 pinsavingtechniques86 reada16-stateswitch86 readaconfigurationswitch86 PinVariables737 portmismatch744 positionencoders91 potentiometer487 power-on/power-offcode519 powercontrolboard551,552 2840prototypeboard554 limiter554 MCP601554,555 opto-triac554 TLE2426555 TLE2426railsplitter555 zerocrossing554
Index BTA12-600B552 BTA12-600BWsnubberlesstriac552 construction553 BTA12-600B553 BTA12-600BW553 heatsinks553 Wakefield231-137PAB553 postconstructioncheckout553 no-conductiontest554 design551 K3011P559 gatedriveduration560 opto-triac559,560 randomphase559 zero-crossing559 triac560 triggerpulses561 zerocrossing559,560 zerovoltage560 Manhattan-styleconstruction551 Manhattanstyleconstruction553 MOC3032M559 opto-coupler552 opto-triac553 opto-triaccoupler552 RadioShackprototypeboardmodel 276-159553 snubber552 triac552 Pre-definedmacrosinINTASM733 prescaler608 preselector207 pressuresensor704 pressuresensors693 programmableunijunctiontransistor (PUT)543 programmingstyle15 programconfigurationdialogbox730 programcounter265,436 programinstruction265 programmemory1,2,3,6,261,265, 734 call GoSub265 EEPROM3 EPROM3 EPROMandEEPROM3 onetimeprogrammable(OTP)3 extendedvoltage3 flashmemory3 interruptvectors266 jumpexecution265 memoryandvoltagedesignators4 opcodes jumpopcodes call265 GoTo266 goto265 pages265 partiallistofpackagedesignators4 PCLATHregister265 PCLregister265
programcounter265 programinstruction265 read-only3 resetvectors266 stackmemory266 calloperations266 interruptoperations266 standardvoltage3 temperaturerangedesignators4 programwords6 pseudo-code23,24 definetheproblem24 documenttheproblemandthesolution24 programmodularly,proceedingfrom thetopdown24 thinkfirst,codelater24 writinggoodcodeintoonerule24 Pu_Off23 Pu_On23 pull-down63 pull-upresistors23 internalpull-upresistors23 PulseIn757 pulsewidthmodulation(PWM)352, 354,355,357,420,424,574 1-bitDAC352 dutycycle424 FREQOUT352 FreqOut355 linearityproblems353 RClow-passfilter353 PulsIn581,731 PulsOut731,757 PWM731,757 PWMmodule593
Q quadratureencoder98 quantizationerror212,213,336 quantizedvalue721
R RAMmemory389 parallelstaticRAM(SRAM)389 Random739,740 randomnumber739 RBINT744 RBINTtypeinterrupt100 RCTime731 RCfilter354 calculatingvalues355 RCnetwork -3dBfrequency355 read/write(R/W)bit393 ReadDM757 Real737 real-timeclock700 real-timeclockandserialEEPROM 700 realtimeclock709,711,712 receiveddata163
777
records717 Redefinedorderofprecedence733 registereddataaccessarrangement (DAA)372 relativeencoder95 quadratureencoder98 readingarelativeencoder95 changefromearlierversionsof MBasic97 relativehumidity691,692,704 relativehumiditymodule692 remainder84 remainderoperator722 remotecontrols517 Hitachi536,537 checkbyte536 deviceanddatacodes536 LSB-first536 MSB-first536,537 REC-80536 togglebits536 infraredtransmission517 IRreceivermodule517 LSB-first540 Mitsubishi526,528,534 bitorder531 LSB-first530,531,536 LSBorMSBorder530 MSB-first530,531,536 btfsc528 carrierfrequency526 deviceanddatacodes536 devicecode531 executionspeedproblem529 HserOut530 keycode531 messageend531 messagestart531 PulsIn529 timer1529 REC-80536 shift-left(<<)530 startpulse528 togglebits536 Nakamichi535,537 checkbyte536 deviceanddatacodes536 keycode536 LSB-first536 MSB-first536 REC-80536 togglebits536 QSE114521 Toshiba535,537 checkbyte536 deviceanddatacodes536 keycode536 LSB-first536 MSB-first536 REC-80536 togglebits536 repeatoption737
Index resetpulse232 resolution212 Resume100 ReversePolishNotation25 rheostat487 right-justifies702 rightjustified702 rightjustifying709 risingedge244 rotaryencoders91,192 absoluteencoders91 codeoutput94 differencebetweenhexadecimal andGraycode94 Graycode94 straighthexadecimalbinarycode 94 construction92 mechanicalencoders92 opticalencoders92 incrementalencoders92 quadratureencoders93 quadraturesensor93 relativeencoders91 rotor121,124 RS-232serialinterface151,154,159 2840developmentboard154 carrierdetect(DCD)154 cleartosend154 datasetready154 dataterminalready154 receivedata(RX)154 requesttosend154 ringindicator154 signalground154 transmitdata(TX)154 busmode156 carriagereturn152 codevalue152 clockskew155 connecttoyourPC151 ComTest152 terminalsoftware152 comport152 databits152 endoflinecharacter(s)152 handshaking152 Hyperterminal152 parity152 stopbits152 Terminal152 controlsignals Assert/Negate153 Asserted/Unasserted153 converttheRS-232levelstologic levelscompatiblewithourPIC 153 databits evenparity155 oddparity155 parity155 paritybit155
datasignals Marking153 Spacing153 EIA/TIARS-232E151 flowcontrol160 HSerIn151,155 HserOut151 inversionbetweenRS-232andlogic 153 levelconverters153 relationshipbetweenthe±15VRS232levelsandthe0/+5Vlogic employedbyPICs153 SP232ACN153 linefeed codevalue152 maximumpermittederrorbetween thesendingandreceivingdata rates155 physicallayer151 serialtransmission154 asynchronous154 synchronization155 synchronous154 SerIn151,155 syntaxforSerIn156 SerOut151 SP232ACNdatasheet154 SP232ACNlevelconverters153 standardpinconnections154 start(space)bit154 stop(mark)bit154 Strmodifier166 parameters166 Teletype153 USB-to-serialadapter151 RTS/CTShandshaking163
S salientpoles124 Sallen-Key511 samplerate428 Samsung’sKS006667 Schmitttriggerinputs54 correctlyreadaninputsignalinthe presenceoflargenoisevoltages 57 specialSchmitttriggerinputs54 Schmitttriggertype571 scratchpadmemory238 ScrLeft75,77 ScrRAM77 ScrRight75 sensorsuite699 serial151 serialEEPROM389,408,697,700, 712,722 serialinputbuffer715 serialperipheralinterface(SPI)231 1-wire231 “presence”pulse232 resetpulse232
778
DS1302realtimeclock231 DS18B20temperaturesensor231 one-wireprotocol231 OWIn231 OWOut231 three-wire231 serialports,noteon11 serialterminalprogram87 HyperTerminal87 Terminal87 SerIn151,155,156,158,159,163, 164,165,176,731 doesn’tmeanthatwecansenda stringofcharactersat57600 bits/secandexpectthemtobe correctlyreceived165 flowcontrol164,165 I/Omodifier165 readastringofmultiplecharacters 164 syntaxforSerIn156 Serin/SerOut757 SerInandHSerIn differencesbetween176 SerInandSerOutconstants731 SerOut151,156,159,163,164,731 SerOutalsoHSerOut740 SetCapture207 SetCompare208,210 SetHSerial87,157,176 setthedesiredbaudrate176 SetHSerial/HSerin/HSerOut758 SetHSerial/HSerOut/HSerIn759 SetPullUps23,57 SetPullups758 SetTmr1206 seven-segmentLEDdisplays107 shaftencoders91 SherlineProducts,Inc.93 ShiftIn733 ShiftIn/ShiftOut757 ShiftOut733 ShiftOut/ShiftIn258 risingorfallingclockandbitorder 258 ShiftOut/ShiftIn--risingorfalling clockandbitorder258 SignalSystemNo.7361 siliconcontrolledrectifier(SCR)543 simplecircuit58 SinandCos738 Sleep731,741 SLOWLSBPOST732 SLOWLSBPRE732 SLOWMSBPOST732 SLOWMSBPRE732 smallN-ChannelMOSFETswitch37 differencebetweentheMOSFETand NPNbipolartransistor38 highpowerMOSFETlowside switching40 MOSFETs,gatecharge39
Index relationshipbetweenRDS(ON)and thegatevoltage38 SMBus54 SN754410147,148,588,592,593 superiorratings147 SN754410H-bridge132,147 snubber35 snubbingdiode35,46,110 softwaredebouncing60 Sound731,757 Sound2731 SP232ACNlevelconverters153 specialpurposeswitching50 spectrumanalysisplots349 speed7 speedorsizeoptimization734 speedversusmemoryrequirements734 SPI(3-wire)389 SPMotor135,138,141,147,731,757 whenstopped138 SpMotor133 SRAM409 STACK732 stack732 stackcommand730 stackcompilerdirective732 Stacksizeandlocation732 stacksizeisstatedintypeLong732 standardbarometricpressure692 standardheader730 standardprogramlayout15 start(space)bit154 staticRAM409 statictorque121 stator121,124 steppermotors120,418,428,567 “bolt-in”MBasic-to-assembler429 advantages120 AssemblerInterruptServiceRoutine (ISR)447 assemblerroutines429 compilercontrolbits433 forcethecompilertoallocatespace 433 GPASM447 stepwiserefinement429 banksel432,433 benefitsanddrawbacksofunipolar andbipolarconnections123 bipolar122,133,147,418,440,567 advantageofbipolarmotors133 conceptualviewofcontrollinga bipolarmotor131 H-bridge418 rotor418 SN754410H-bridge132,147 stator418 two-phase122 bitsetfile bcf435,437 bsf437 btfsc437
bitshifting434 carryflag438 maskoffbitsbythebitwiseAND operator435 modulus435 rotateleftthroughcarryflag(RLF) 434 rotaterightthroughcarryflag (RRF)434 rotatethroughcarry435,438 moreproperlynamed“re-circulation”435 Status435 carriagereturn445 carriagereturn/linefeedcombination445 CCP423 clockspeedvalueisconvertedintoa constant445 cosine438 cosinefunction421,425 cosinetransitioncurrentwaveform 424 Darlingtontransistor135 detenttorque121 digital-to-analogconverter419 disadvantages120 dutycycle423,424,425,437 fourphase123 fullstepmode418,421 GPASM432,447 banksel432 halfstepmode418 hardwarePWM439 hardwarePWMmodule438 hardwarePWMmodule’speriod423 highvoltagespike138 holdingtorque121 HPWMmodule424 HserOut446 HWPMmodule428 identifyingsteppermotors124 improvethecurrentreleasetimeby addingZenerdiodesinreverse series142 inductivecurrentrise135 initializationstring445 interrupt440 ISRASM440 interruptserviceroutine(ISR)447, 448 16-bitcomparison449 addwf448 bitpattern fullstep448 halfstep448 decf448 incf448,449 ISRASM445 pageboundaries448 retlw448 ISRASM446,447
779
L/Rdrive418 L/Rtimeconstant419,439 maskliteral438 MBasic //operatoristhemodulusorremainderfunction435 hardwarepulsewidthmodulation (PWM) HPWM423 HPWM423 dutycycle423 period423 Pauseus438 MBasicvariables accessawordvariable447 BankSel447 bankselection447 baseaddress447 Clear444 compilercontrol447 highorderbyteisatthebaseaddressplusone447 instructions BankSel447 incf447 microstepping418,419,420 fullstep419 microsteps418,425,426,434 pauseus432 MPASM432 NationalElectricalManufacturers Association(NEMA)124 openloop120 operationmodes129 compile-timeoption138 fullstep130 fullwave131 half-step130,131 nonuniformtorque131 halfstep131 routines138 wave130,131,133 parameterMdelay136 period425 PF35-48unipolar422 programs133 currentreleaseimprovementaZenerdiodemakesoverusingthe ULN2003A’sinternalclamping diode134 improvethecurrentrisetime136 SPMotor134,135 SpMotor133 programcounter436 PWMmodules423,428 dutycycle437 readingastepperspecificationsheet 126 ambienttemperaturerange--operatingandtemperaturerise129 drivemode126 excitationmode126
Index holdingtorque129 milli-Newton-meters129 ounce-inches129 mass129 rotorinertia129 startingpulserate,maxandslewing pulseratemax129 stepsperrevolution126 stepangle126 stepangletolerance126 voltageandwindingresistance126 windinginductance127 inductivetimeconstant128 registers addlw434 AND438 btfsc436 call436 CCP1CON437 CCPR1L437,438 decfsz434 GoTo434,436 HPWM437 incf436 jumptable436,437 movf434 movlw434 movwf434,436 PCL436 PCLATH436 retlw436 rotationdirection135 rotor121,124,418 salientpoles124 samplerate428 Schottkyvoltageclampdiodes148 selectaseriesresistanceandvoltage 136 SN754410147,148 superiorratings147 SN754410bipolardrivercircuit419, 420,421,422,428,440 enablepins419,420 enablevoltage428 pulsewidthmodulation(PWM) modules420,422 dutycycle420 SN754410quadhalf-Hbridgedevice 147 SPMotor138,141,147 SPMOTOR_HalfCON0138 SpMotor133 whenstopped138 STACK433 statictorque121 stator121,124,418 stepperpatterninasubroutine143 therelationshipbetweenR1,V1and Imotor136 timer1440,445,446,449 HSerIn interrupt447
interrupt445,446,447 PIR1447 tmr1if447,448 preload446,448 two-phase122 typesofsteppermotors123 canstack123 hybrid123,124 industry-standardcasesizes124 rotor124 stator124 permanentmagnet123 tincan123 variablereluctance124 ULN2003A135,138 ULN2003ADarlingtontransistor driver133 unipolar122,123,129,133,418, 440,567 centertaps123 fourphase123 L/Rtimeconstantofthebipolar connectedwindingistwicethat oftheunipolarconnection148 unipolarstepper133 windinginductanceincreases148 variableconstantcurrent419 wavemode418 stepwiserefinement295 stepwisesubstitution413 stop(mark)bit154 straight-throughcable159 straighthexadecimalbinarycode94 Strmodifier166 explicitend-of-linedefinition167 lengthtotheStrmodifier167 parameters166 subroutinenames16 verb-noun16 supercapacitors251 leakagecurrent251 Surfboard6103693 switchingspeed37 turn-onandturn-offspeeds41 switchbounce58,192 built-inswitchdebounceprocedure Button60 SystemSetupdialogbox734
T tachometer582 constant570 determiningthetachometerconstant 570 feedback568 taxonomyofMBasicfunctionsand procedures11,12 Teletype152,153 temperature691,695 temperature,humidityandbarometric pressure711 temperatureconversion697
780
Terminal152,162 thresholdvoltage53 thyristorfamily543 diodethyristor(diac)543 holdingcurrent543 programmableunijunctiontransistor (PUT)543 siliconcontrolledrectifier(SCR)543 triac543 time/date717 timers7,187,194 definition194 timer0187 timer1187,208,209,210 timer2187,209 prescale331 timingparameters731 TOFLOAT729 ToFloat217,703,733 togglebit519 TOINT729 ToInt729,733,738,739 tokenmemory734 Touch-Tone360,363,364,367,371, 372,373,387 ASCIIcollatingsequence383 ASCIIcollationorder385 CH1837A374,375,376,377,387 latency376 off-hook377 OffHookpins375 RIpins375,376 connectingacommonWestern Electric/LucentTouch-Tone dialtofunctionasastand-alone Touch-Tonegenerator361 digitreceiver371 DS18B20temperaturesensor387 dual-tonemulti-frequency(DTMF) 360 inter-office360 DV(digitvalid)362 four-wire371 generatingTouch-Tonesignals361 DTMFout361 DTMFOut2361 hybrid371 LM386374 MBasic DTMFOut387 DTMFOut2387 ONBORbrownoutresetcommand 387 MC145436A374 MFsignaling361 Morsecode375,377,382,385,386 “pro-sign”Morsecharacters383 di-bitencoding383,385 durationofdots,dashesandspaces aredefined382 Morsecodesending382 Morsecodespeed376
Index standardword376 wordsperminute376 variablelengthcode382 X10receivingmodules381 X10transceiver381 overviewofthetraditionalsingle-partytelephoneconnection370 answeringacall371 dialtone371 FCCestablishedsetofrules372 hookswitch371 hybrid372 off-hook372 on-hook371,372 originatingacall371 ringingvoltage371,372 subscriberloop371 characteristicimpedance372 nominalcharacteristicimpedance372 protectedfromover-voltageand over-current372 transmitlimit373 registereddataaccessarrangement (DAA)372 CH1837A372 CH1840372 MC145436A372 MC154436A372 MH88422372 XE0068372 ringingvoltage376 SignalSystemNo.7361 timer1375 interruptserviceroutine375 prescaler375 Touch-TonedecoderIC361 MC145436361 bytetable364 MC145436A361,363,367 DVpin364 maximumpermittedsignallevel 363 readtheMC145436A363 MCP145436A362 output362 MT8870361 nibble368 two-wiretofour-wireconverter371 triac544,545,547,549,558,560 anode1(A1)543 anode2(A2)543 BTA12-600B544 dV/dt544 standardtriac544 BTA12-600BW544 dV/dt544 quadrantsI-II-III544 quadrantIV544 snubberlesstriac544 BTA12-600TW dV/dt544
commutate543 commutation546 commutationfailure545 commute546 cyclecontrolling556 DCcomponent559 dI/dt545,546 BTA12-600BW545,546 commute546 linearload546 loadisinductive546 snubberless545 standard545 storedcharge545 unrecombinedchargecarriers545 di/dt546 dV/dt544,545,546,547 BTA12-600548 BTA12-600BW547,548 resistiveload547 commute544 falsegatetriggering548 gatecurrent546 gatesensitivity548 inductiveload547 inductiveloads548 resistiveload546 snubber548 snubberless544,548 snubbernetwork547 standard544 dv/dt547 numericalvalueofdv/dt547 resistiveload547 dV/dtanddI/dtissues545 four-quadranttriggerable544 gate543,544 gatecurrent544 IGT544 gatedriverequirements544 positiveandnegativegatedrive 544 voltageacrossthegate544 VGT544 gate/MT2relationship544 heatsinking545 BTA12-600BW545 junctiontemperature545 junctiontocaseRTH(j-c)545 thermalresistance545 VT545 holdingcurrentIH544 introduction543 K3011P556,562 inrushcurrent556 opto-triac562 randomphase556 start-uptransient556 zero-crossing556 latchingcurrentIL544 mainterminal1(MT1)543 mainterminal2(MT2)543,544
781
maximumcurrent545 BTA12-600BW545 maximumnonrepetitivepeakcurrentITSM545 maximumRMS-onstatecurrent IT(RMS)545 maximumgatecurrentIGM545 BTA12-600BW545 MCP601558 opto-triac558 zerocrossing558 MOC3032M555,556 coldresistance556 colortemperature556 initialcurrentinrush556 opto-triac555,556 relationshipbetweentheLEDtriggercurrentandtheloadcurrent whenweuseazero-crossing controller555 zero-crossing556 on-statevoltageVT545 BTA12-600BW545 phaseandcyclecontrol549 cycle-control549 cyclecontrol550 DCcomponent550 radiofrequencyinterference550 softerstart550 off-oncontrol549 off/oncontrol549 phasecontrol549 averagevalue550 firingangle550 powerversusfiringangle550 RMS550 RMSandaveragevoltagesvary withrespecttothefiringangle 550 triggeringpoint550 trueRMSmeters550 phasecontrol562 powercontrolboard552 Q-I/Q-III544 Q-IVtriggerable544 quadrants544 quadrantsIIandIV549 BTA12-600BW549 self-commutating544 snubberlessversusstandard545 thyristors545 trigger554 triggeringatriac548 BTA12-600549 BTA12-600BW548 snubberless549 differencebetweenzerocrossing andrandomphase548 gate548 gatecurrent549 MT1549 MT2549
Index K3011P548 randomphasedevice548 MOC3032M548 zerocrossingtriggerdevice548 opticalisolators548 opto-isolator548 opto-triac548 quadrantsIIandIV549 quadrantIV549 randomphaseopto-triac548 zerocrossingdevice548 VDRM545 waystoconnectthetriacwiththe loadandtriggerdrive549 TRISA112 TRISB112 TTLcompatible571 TTLlevel53 turn-offdelay37 two’scomplemented709
U ULN2003A135,138 ULN2003ADarlingtontransistordriver 133 ULN2003ANPNDarlingtonarray 109,110 undefinedregion53 undocumentedcommandmodifiers736 UndocumentedMBasic733 UnitandKeyCodes742 universaladapter11 UniversalProductCode,revisionA (UPC-A)595 universalsynchronous/asynchronous receiver/transmitter(USART) 157 updatedMBasiccompiler(version 5.3.0.0)10 USART7,742 USARTtransmitoutput157 user-definedfunction730 User-definedfunctions729
V vaporpressure691 variables16 adjective-noun16 indexorcountingvariables16 variableresistance487 variableresistor487 variablevoltagedivider487 version05.2.1.1 SetCompare errorthatreversesthebyteorder 208 verticalbar|character734 VIH--Theminimumvoltageonan inputpinthatwillbereadasa logicalhigh53 VIL--Themaximumvoltageonan inputpinthatwillbereadasa
logicallow53 voltage-controlledoscillator(VCO) voltage-controlledoscillator(VCO) lockandno-lockconditions663 voltagedivider699 voltagescaling698 volumecontrol487 vonNeumann’sarchitecture2
W WaitStrmodifier168,169 nonmatchingcharacters168 warningstatement542 watervapor691 weatherstation691 7805699 addresspins699 bit-packed720 externalEEPROM711 MPX6115698 packingtime/dateinformationinto thefour-byterecord718 quantizedvalue721 realtimeclock711,712 sensorsuite691,699 AT24C512serialEEPROM705 barometricpressure691,692,694 A/Dconverter694 A/Derror695 A/Dstep695 absolutepressure693,694,704 barometricpressureadjustment factor693 correctedpressure694 EEPROM695 elevationcorrection694 elevationofthesensor692 errorbudget695 errorvoltage695 estimatethevoltageoutputrange ofourpressuresensor694 FreescaleSemiconductor,Inc. 693 hectopascal(hPa)692 I2Cout695,697 inchesofmercury692 LT1634-CCZ-4.096698 Maxim’sDS18B20695,697, 698 Maxim’sI2C-protocolDS1624 695,696,697,698,708 MCP601698,699 millibar692 Motorola693 MPX6115698,699,704 MPX6115A6U693,694 piezoelectric693 pressuresensor704 pressuresensors693 quantizebarometricpressure721 reducedtosealevelequivalent 693
782
relationshipamongstinchesof mercury,millibars,kilopascals andpoundspersquareinch 692 relationshipbetweenelevation andairpressurechange693 sensorerror695 standardbarometricpressure692 straingauge693 surfacemountadapter693 Surfboard6103693 commandbyte708 controlbyte708 DS1302709 optionaldatabyte708 relativehumidity691,692,704 A/Dconverter692 capacitance691 dielectricconstant691 estimatethemeasurementerror 692 HM-1500692,704 Honeywell’sHIH-3610692 humiditysensors691 Humirel’sHS-1100sensor691, 692 measurecapacitancewithaPIC 691 nominalcapacitance691 quantizehumidity721 relativehumiditymodule692 uncorrectedlinearequation692 watervapor691 relativehumiditysensor692 temperature691,695 24-seriesEEPROM696 A/Dresolution695 addressbyte708 analogtemperaturesensor695 commandbyte696,697,708 configurationregister696,697 continuousmode696 controlbyte696 convertthereturnedvaluetoan actualCelsiustemperature709 databyte696 DS1624708,709 DS18B20709 EEPROM695,696 externalEEPROM695 familycode696 fractionalpart698 I2C696 I2C-protocol695 I2Cin695,697,708 leftjustified697,708 NationalSemiconductor’s LM34C695 one-shotmode696 pinconnections695 realtimeclock709 rightjustifying709
Index temperatureconversion697 two’scomplemented709 serialEEPROM712 temperature,humidityandbarometric pressure711 verifytheA/Dcomponents700 voltagedivider699 voltagescaling698 write723 WriteDM101,102
X X-10messages453,473 functioncode453,456 MBasicprovideslibraryconstants 453 Xin453 Xout453 housecode453,456 MBasicprovideslibraryconstants 453 Xin453 Xout453 unitcode453,456 MBasicprovideslibraryconstants 453 Xin453 Xout453 X-10technology453,454,456,457, 458,459,460,465,469,473, 475,480,486 appliancemodule460 bitorder457 bytetable465,466,481 complements484 LSB-first458,465,481 LSBfirst457,484 mostsignificantbit457 MSB-first465 MSBfirst457,484 serialinterface457 LSBfirst457 startbits483 data456 datablock456 houseblock456
LSB-firstorder456 startblock456 datatransmissionviatheX-10interface469 DS18B20470,471,474 X-10link471 howX-10commandsaresent456 LCDinitialization481 MBasicfunctions binaryequivalents458 MSBfirstorder459 libraryconstants457,461,465, 469 cross-referenceswiththenames andbitsequencesfollowedin X-10documents457 unitcode465 OWin470 Owout470 Realmodifierasafunction474 undocumented474 Xin454,455,457,458,459,468, 469,473 softwareversion480 Xout454,455,457,458,459,460, 461,465,473,476 PAM02appliancecontrolmodule 454 PL513468 protocol453,461,473,483 16-channeltelemetrysystem473 bitleveldataflowintheX-10455 startsignal461 PSC05454 Realmodifierasafunction474 receivingX-10signals468 signalbridge486 three-phasepower455 zerocrossing455,461,468,482 burststructure461 transmit-onlyPL513device454 TW523transceiver454,455,456, 457,459,460,468,481,482, 486 FunctionCode456 HouseCode456
783
IdleTime456 opto-isolator460 powerstrips486 receivingmodules486 RJ11four-pinmodularconnector 454 StartCode456 UnitCode456 XORfunction484 X-10codesniffer480 X-10controlmodule453 addressedbybothhouseandunit codes453 allcall453,459,461,466,485 appliancecontrolmodule454 channelcode473 datacode484 endcode473 falsecoderejection462 functioncode456,458,464,465, 466,469,484 X_Off469 functionname485 housecode453,456,461,464, 466,469,470,473,484,485 keycode461 startingcode483 startcode473,483 unitcode453,456,458,461,464, 465,466,484,485 X-10PromodelPAM02appliance modules459 X-10ProPSC05454 X-10transceivermodule454 X-10transmitter454 X_Units_Off741 X10742 X10interfacing741 X10USA453 Xin741,742 Xin/Xout758 XinandXout741 Xout741,742
Z Zenerdiode35
ELSEVIERSCIENCEDVD-ROMLICENSEAGREEMENT PLEASEREADTHEFOLLOWINGAGREEMENTCAREFULLYBEFOREUSINGTHISDVD-ROMPRODUCT.THISDVD-ROMPRODUCTISLICENSEDUNDERTHETERMSCONTAINEDINTHISDVD-ROMLICENSEAGREEMENT(“Agreement”).BYUSING THISDVD-ROMPRODUCT,YOU,ANINDIVIDUALORENTITYINCLUDINGEMPLOYEES,AGENTSANDREPRESENTATIVES (“You”or“Your”),ACKNOWLEDGETHATYOUHAVEREADTHISAGREEMENT,THATYOUUNDERSTANDIT,ANDTHAT YOUAGREETOBEBOUNDBYTHETERMSANDCONDITIONSOFTHISAGREEMENT.ELSEVIERSCIENCEINC.(“Elsevier Science”)EXPRESSLYDOESNOTAGREETOLICENSETHISDVD-ROMPRODUCTTOYOUUNLESSYOUASSENTTOTHIS AGREEMENT.IFYOUDONOTAGREEWITHANYOFTHEFOLLOWINGTERMS,YOUMAY,WITHINTHIRTY(30)DAYSAFTER YOURRECEIPTOFTHISDVD-ROMPRODUCTRETURNTHEUNUSEDDVD-ROMPRODUCTANDALLACCOMPANYING DOCUMENTATIONTOELSEVIERSCIENCEFORAFULLREFUND. DEFINITIONS AsusedinthisAgreement,thesetermsshallhavethefollowingmeanings: “ProprietaryMaterial”meansthevaluableandproprietaryinformationcontentofthisDVD-ROMProductincludingall indexesandgraphicmaterialsandsoftwareusedtoaccess,index,searchandretrievetheinformationcontentfromthis DVD-ROMProductdevelopedorlicensedbyElsevierScienceand/oritsaffiliates,suppliersandlicensors. “DVD-ROMProduct”meansthecopyoftheProprietaryMaterialandanyothermaterialdeliveredonDVD-ROMandany otherhuman-readableormachine-readablematerialsenclosedwiththisAgreement,includingwithoutlimitationdocumentationrelatingtothesame. OWNERSHIP ThisDVD-ROMProducthasbeensuppliedbyandisproprietarytoElsevierScienceand/oritsaffiliates,suppliersandlicensors.ThecopyrightintheDVD-ROMProductbelongstoElsevierScienceand/oritsaffiliates,suppliersandlicensorsandis protectedbythenationalandstatecopyright,trademark,tradesecretandotherintellectualpropertylawsoftheUnited Statesandinternationaltreatyprovisions,includingwithoutlimitationtheUniversalCopyrightConventionandtheBerne CopyrightConvention.YouhavenoownershiprightsinthisDVD-ROMProduct.Exceptasexpresslysetforthherein,no partofthisDVD-ROMProduct,includingwithoutlimitationtheProprietaryMaterial,maybemodified,copiedordistributed inhardcopyormachine-readableformwithoutpriorwrittenconsentfromElsevierScience.Allrightsnotexpresslygranted toYouhereinareexpresslyreserved.AnyotheruseofthisDVD-ROMProductbyanypersonorentityisstrictlyprohibited andaviolationofthisAgreement. SCOPEOFRIGHTSLICENSED(PERMITTEDUSES) ElsevierScienceisgrantingtoYoualimited,non-exclusive,non-transferablelicensetousethisDVD-ROMProductinaccordancewiththetermsofthisAgreement.YoumayuseorprovideaccesstothisDVD-ROMProductonasinglecomputer orterminalphysicallylocatedatYourpremisesandinasecurenetworkormovethisDVD-ROMProducttoanduseiton anothersinglecomputerorterminalatthesamelocationforpersonaluseonly,butundernocircumstancesmayYouuse orprovideaccesstoanypartorpartsofthisDVD-ROMProductonmorethanonecomputerorterminalsimultaneously. You shall not (a) copy, download, or otherwise reproduce the DVD-ROM Product in any medium, including, without limitation,onlinetransmissions,localareanetworks,wideareanetworks,intranets,extranetsandtheInternet,orinany way,inwholeorinpart,exceptthatYoumayprintordownloadlimitedportionsoftheProprietaryMaterialthatarethe resultsofdiscretesearches;(b)alter,modify,oradapttheDVD-ROMProduct,includingbutnotlimitedtodecompiling, disassembling,reverseengineering,orcreatingderivativeworks,withoutthepriorwrittenapprovalofElsevierScience;(c) sell,licenseorotherwisedistributetothirdpartiestheDVD-ROMProductoranypartorpartsthereof;or(d)alter,remove, obscureorobstructthedisplayofanycopyright,trademarkorotherproprietarynoticeonorintheDVD-ROMProductor onanyprintoutordownloadofportionsoftheProprietaryMaterials. RESTRICTIONSONTRANSFER ThisLicenseispersonaltoYou,andneitherYourrightshereundernorthetangibleembodimentsofthisDVD-ROMProduct, includingwithoutlimitationtheProprietaryMaterial,maybesold,assigned,transferredorsub-licensedtoanyotherperson, includingwithoutlimitationbyoperationoflaw,withoutthepriorwrittenconsentofElsevierScience.Anypurportedsale, assignment,transferorsublicensewithoutthepriorwrittenconsentofElsevierSciencewillbevoidandwillautomatically terminatetheLicensegrantedhereunder.
TERMS ThisAgreementwillremainineffectuntilterminatedpursuanttothetermsofthisAgreement.Youmayterminatethis AgreementatanytimebyremovingfromYoursystemanddestroyingtheDVD-ROMProduct.Unauthorizedcopyingof theDVD-ROMProduct,includingwithoutlimitation,theProprietaryMaterialanddocumentation,orotherwisefailingto complywiththetermsandconditionsofthisAgreementshallresultinautomaticterminationofthislicenseandwillmake availabletoElsevierSciencelegalremedies.UponterminationofthisAgreement,thelicensegrantedhereinwillterminate andYoumustimmediatelydestroytheDVD-ROMProductandaccompanyingdocumentation.Allprovisionsrelatingto proprietaryrightsshallsurviveterminationofthisAgreement. LIMITEDWARRANTYANDLIMITATIONOFLIABILITY NEITHERELSEVIERSCIENCENORITSLICENSORSREPRESENTORWARRANTTHATTHEINFORMATIONCONTAINEDINTHE PROPRIETARYMATERIALSISCOMPLETEORFREEFROMERROR,ANDNEITHERASSUMES,ANDBOTHEXPRESSLYDISCLAIM, ANYLIABILITYTOANYPERSONFORANYLOSSORDAMAGECAUSEDBYERRORSOROMISSIONSINTHEPROPRIETARY MATERIAL,WHETHERSUCHERRORSOROMISSIONSRESULTFROMNEGLIGENCE,ACCIDENT,ORANYOTHERCAUSE. INADDITION,NEITHERELSEVIERSCIENCENORITSLICENSORSMAKEANYREPRESENTATIONSORWARRANTIES,EITHER EXPRESSORIMPLIED,REGARDINGTHEPERFORMANCEOFYOURNETWORKORCOMPUTERSYSTEMWHENUSEDIN CONJUNCTIONWITHTHEDVD-ROMPRODUCT. IfthisDVD-ROMProductisdefective,ElsevierSciencewillreplaceitatnochargeifthedefectiveDVD-ROMProductis returnedtoElsevierSciencewithinsixty(60)days(orthegreatestperiodallowablebyapplicablelaw)fromthedateof shipment. ElsevierSciencewarrantsthatthesoftwareembodiedinthisDVD-ROMProductwillperforminsubstantialcompliance withthedocumentationsuppliedinthisDVD-ROMProduct.IfYoureportsignificantdefectinperformanceinwritingto ElsevierScience,andElsevierScienceisnotabletocorrectsamewithinsixty(60)daysafteritsreceiptofYournotification, YoumayreturnthisDVD-ROMProduct,includingallcopiesanddocumentation,toElsevierScienceandElsevierScience willrefundYourmoney. YOU UNDERSTAND THAT, EXCEPT FOR THE 60-DAY LIMITED WARRANTY RECITED ABOVE, ELSEVIER SCIENCE, ITS AFFILIATES,LICENSORS,SUPPLIERSANDAGENTS,MAKENOWARRANTIES,EXPRESSEDORIMPLIED,WITHRESPECTTO THEDVD-ROMPRODUCT,INCLUDING,WITHOUTLIMITATIONTHEPROPRIETARYMATERIAL,ANSPECIFICALLYDISCLAIM ANYWARRANTYOFMERCHANTABILITYORFITNESSFORAPARTICULARPURPOSE. IftheinformationprovidedonthisDVD-ROMcontainsmedicalorhealthsciencesinformation,itisintendedforprofessional usewithinthemedicalfield.Informationaboutmedicaltreatmentordrugdosagesisintendedstrictlyforprofessional use,andbecauseofrapidadvancesinthemedicalsciences,independentverificationfdiagnosisanddrugdosagesshould bemade. INNOEVENTWILLELSEVIERSCIENCE,ITSAFFILIATES,LICENSORS,SUPPLIERSORAGENTS,BELIABLETOYOUFORANY DAMAGES,INCLUDING,WITHOUTLIMITATION,ANYLOSTPROFITS,LOSTSAVINGSOROTHERINCIDENTALORCONSEQUENTIALDAMAGES,ARISINGOUTOFYOURUSEORINABILITYTOUSETHEDVD-ROMPRODUCTREGARDLESSOF WHETHER SUCH DAMAGES ARE FORESEEABLE OR WHETHER SUCH DAMAGES ARE DEEMED TO RESULT FROM THE FAILUREORINADEQUACYOFANYEXCLUSIVEOROTHERREMEDY. U.S.GOVERNMENTRESTRICTEDRIGHTS TheDVD-ROMProductanddocumentationareprovidedwithrestrictedrights.Use,duplicationordisclosurebytheU.S. Governmentissubjecttorestrictionsassetforthinsubparagraphs(a)through(d)oftheCommercialComputerRestricted RightsclauseatFAR52.22719orinsubparagraph(c)(1)(ii)oftheRightsinTechnicalDataandComputerSoftwareclause atDFARS252.2277013,orat252.2117015,asapplicable.Contractor/ManufacturerisElsevierScienceInc.,655Avenue oftheAmericas,NewYork,NY10010-5107USA. GOVERNINGLAW ThisAgreementshallbegovernedbythelawsoftheStateofNewYork,USA.InanydisputearisingoutofthisAgreement, youandElsevierScienceeachconsenttotheexclusivepersonaljurisdictionandvenueinthestateandfederalcourtswithin NewYorkCounty,NewYork,USA.