ebook img

Embedded computing and mechatronics with the PIC32 microcontroller PDF

613 Pages·2015·26.404 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Embedded computing and mechatronics with the PIC32 microcontroller

Embedded Computing and Mechatronics with the PIC32 Microcontroller Embedded Computing and Mechatronics with the PIC32 Microcontroller Kevin M. Lynch Nicholas Marchuk Matthew L. Elwin AMSTERDAM(cid:129)BOSTON(cid:129)HEIDELBERG(cid:129)LONDON NEWYORK(cid:129)OXFORD(cid:129)PARIS(cid:129)SANDIEGO SANFRANCISCO(cid:129)SINGAPORE(cid:129)SYDNEY(cid:129)TOKYO NewnesisanimprintofElsevier NewnesisanimprintofElsevier 225WymanStreet,Waltham,MA02451,USA TheBoulevard,LangfordLane,Kidlington,OxfordOX51GB,UK Copyright[C]2016ElsevierInc.Allrightsreserved. Nopartofthispublicationmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,including photocopying,recording,oranyinformationstorageandretrievalsystem,withoutpermissioninwritingfromthepublisher. Detailsonhowtoseekpermission,furtherinformationaboutthePublisher’spermissionspoliciesandourarrangementswith organizationssuchastheCopyrightClearanceCenterandtheCopyrightLicensingAgency,canbefoundatourwebsite: www.elsevier.com/permissions. ThisbookandtheindividualcontributionscontainedinitareprotectedundercopyrightbythePublisher(otherthanasmaybe notedherein). Notices Knowledgeandbestpracticeinthisfieldareconstantlychanging.Asnewresearchandexperiencebroadenourunderstanding, changesinresearchmethods,professionalpractices,ormedicaltreatmentmaybecomenecessary. Practitionersandresearchersmustalwaysrelyontheirownexperienceandknowledgeinevaluatingandusinganyinformation, methods,compounds,orexperimentsdescribedherein.Inusingsuchinformationormethodstheyshouldbemindfuloftheirown safetyandthesafetyofothers,includingpartiesforwhomtheyhaveaprofessionalresponsibility. Tothefullestextentofthelaw,neitherthePublishernortheauthors,contributors,oreditors,assumeanyliabilityforanyinjury and/ordamagetopersonsorpropertyasamatterofproductsliability,negligenceorotherwise,orfromanyuseoroperationof anymethods,products,instructions,orideascontainedinthematerialherein. BritishLibraryCataloguinginPublicationData AcataloguerecordforthisbookisavailablefromtheBritishLibrary LibraryofCongressCataloging-in-PublicationData AcatalogrecordforthisbookisavailablefromtheLibraryofCongress ForinformationonallNewnespublications visitourwebsiteathttp://store.elsevier.com/ ISBN:978-0-12-420165-1 PrintedandboundinUS Dedication To Yuko, Erin, and Patrick. –Kevin M. Lynch To Mark and Liz. –Nicholas Marchuk To Hannah. –Matthew L. Elwin Figure Credits Theauthorsthankthefollowingcompaniesforpermissiontousetheircopyrightedimagesin thisbook. *MicrochipTechnology,Inc.www.microchip.com. *DigiInternational,Inc.www.digi.com. *PololuRoboticsandElectronics.www.pololu.com. *Digi-KeyElectronics.www.digikey.com. *AdvancedPhotonix,Inc.www.advancedphotonix.com. *ContelecAG.www.contelec.ch/en. *OmegaEngineering,Inc.,Stamford,CT06907USA.www.omega.com. *AvagoTechnologies.www.avagotech.com. *Micro-Measurements,abrandofVishayPrecisionGroup(VPG),Raleigh,NC,USA. www.vpgsensors.com. *MaxonPrecisionMotors.www.maxonmotorusa.com. *CopleyControls.www.copleycontrols.com. *H2WTechnologies.www.h2wtech.com. *HitecRCDUSA.www.hitecrcd.com. Preface ThisbookisabouttheMicrochip32-bitPIC32microcontroller,itshardware,programmingit inC,andinterfacingittosensorsandactuators.Thisbookalsocoversrelatedmechatronics topicssuchasmotortheory,choosingmotorgearing,andpracticalintroductionstodigital signalprocessingandfeedbackcontrol.Thisbookiswrittenfor: • AnyonestartingoutwiththeMicrochipPIC3232-bitmicrocontroller.Microchip documentationcanbehardtonavigate;thisisthebookwewishwehadwhenwestarted! • ThehobbyistreadytoexplorebeyondArduino.Arduinosoftwareanditslargeuser supportcommunityallowyoutobeupandrunningquicklywithAtmelmicrocontrollers. ButrelianceonArduinosoftwarepreventsyoufromfullyexploitingorunderstandingthe capabilityofthemicrocontroller. • Teachersandstudentsinmechatronics.Theexercises,onlinematerial,andassociated kitaredesignedtosupportintroductory,advanced,andflippedoronlinecoursesin mechatronics. • Anyoneinterestedinmechatronics,actuators,sensors,andpracticalembedded control. Contents Thisbookwaswrittenbasedonthetwo-quartermechatronicssequenceatNorthwestern University,ME333IntroductiontoMechatronicsandME433AdvancedMechatronics.In ME333,studentslearnaboutPIC32hardware,fundamentalsofprogrammingthePIC32inC, theuseofsomebasicperipherals,andinterfacingthePIC32withsensorsandactuators.In ME433,materialfromtherestofthebookisusedasreferencebygroupsworkingon projects.Studentstakingthesequencerangefromsophomorestograduatestudents.Theonly prerequisiteisintroductorycircuitanalysisanddesign;experienceinCprogrammingisnot required.WhileexperienceinCwouldallowfasterprogressionthroughthematerial,we decidednottorequireit,tomakethecourseavailabletothebroadsetofstudentsinterestedin thematerial.TopartiallycompensateforthewiderangeofexperienceinC(fromexpertto none),webeginME333withanintensivetwo-weekintroductiontofundamentalCconcepts andsyntaxusingthe“CrashCourseinC”inAppendixA.Wealsotakeadvantageofstudent expertisebyfacilitatingpeermentoring. xix xx Preface ThegoalsofthisbookmirrorthoseoftheNorthwesternmechatronicssequence: • toprovidethebeginnerasoundintroductiontomicrocontrollersusingtheexampleofthe PIC32,amodern32-bitarchitecture; • todosobyfirstprovidinganoverviewofmicrocontrollerhardware,firminthebeliefthat microcontrollerprogrammingismuchmoregroundedwhentightly connectedtothe hardwarethatimplementsit; • toprovideaclearunderstandingofthefundamentalsofprofessionalPIC32programming inC,whichbuildsafoundationforfurtherexplorationofthePIC32’scapabilitiesusing Microchipdocumentationandotheradvancedreferences; • toprovidereferencematerialandsamplecodeonthemajorperipheralsandspecial featuresofthePIC32; • toinstillanunderstandingofthetheoryofmotoroperationandcontrol;and • toteachhowmicrocontrollerperipheralscanbeusedtointerfacewithsensorsandmotors. Toachievethesegoals,thebookisdividedintofivemainparts: 1. Quickstart.Thispart(Chapter1)allowsthestudenttogetupandrunningwiththePIC32 quickly. 2. Fundamentals.Afterachievingsomeearlysuccesswiththequickstart,thefivechapters inFundamentals(Chapters2to6)examinethePIC32hardware,thebuildprocessinC andtheconnectionofthecodetothehardware,theuseoflibraries,andtwoimportant topicsforreal-timeembeddedcomputing:interruptsandthetimeandspaceefficiencyof code.Thetimeinvestmentinthesechaptersprovidesthefoundationneededtomove quicklythroughlaterchaptersandtoprofitfromotherreferencematerial,likeMicrochip’s PIC32ReferenceManual,DataSheets,andXC32C/C++CompilerUser’sGuide. 3. PeripheralReference.Thispart(Chapters7to20)givesdetailsontheoperationofthe variousperipheralsonthePIC32,aswellassamplecodeandapplications.Itisprimarily referencematerialthatcanbereadinanyorder,thoughwerecommendthefirstfew chapters(digitalI/O,counter/timers,outputcompare,andanaloginput)becoveredin order.TheperipheralreferenceconcludeswithanintroductiontoHarmony,Microchip’s recentframeworkforhigh-levelprogrammingofPIC32s. 4. Mechatronics.Thispart(Chapters21to29)focusesoninterfacingsensorstoa microcontroller,digitalsignalprocessing,feedbackcontrol,brushedDCmotortheory, motorsizingandgearing,controlbyamicrocontroller,andotheractuatorssuchas brushlessmotors,steppermotors,andservomotors. 5. Appendixes.Theappendixescoverbackgroundtopicssuchasanalysisofsimplecircuits andanintroductiontoprogramminginC.WehaveourstudentsfirstgetusedtowritingC programsontheirlaptops,andcompilingwithgcc,beforemovingontoprogramminga microcontroller. Preface xxi InME333,wecoverthecrashcourseinC;theQuickstart;theFundamentals;selecttopics fromthePeripheralReference(digitalI/O,counter/timers,outputcompare/PWM,andanalog input);andsimplesensorinterfacing,DCmotortheory,motorsizingandgearing,andcontrol ofaDCmotorfromtheMechatronicspart.OtherchaptersareusedforreferenceinME433 andotherprojectsthatstudentsundertake. Choicesmadeinthisbook WemadeseveralchoicesabouthowtoteachmechatronicsinME333,andthosechoicesare reflectedinthisbook.Ourchoicesarebasedonthedesiretoexposeourstudentstothetopics theywillneedtointegratesensorsandactuatorsandmicrocontrollersprofessionally,subject totheconstraintthatmoststudentswilltakeonlyoneortwocoursesinmechatronics.Our choicesarebasedonwhatwebelievetobethesmallestbuildingblocksthatamechatronics engineerneedstoknowabout.Forexample,wedonotattempttoteachmicrocontroller architectureatthelevelthatacomputerengineermightlearnit,sinceamechatronicsengineer isnotlikelytodesignamicrocontroller.Ontheotherhand,wealsodonotrelyonsoftware andhardwareabstractionsthatkeepthebuddingmechatronicsengineeratarm’slengthfrom conceptsneededtoprogressbeyondthelevelofahobbyist.Withthatphilosophyinmind, herearesomeofthechoicesmadeforME333andthisbook: • Microcontrollersvs.sensorsandactuators.Mechatronicsengineeringintegratessensors, actuators,andmicrocontrollers.Handingastudentamicrocontrollerdevelopmentboard andsamplecodepotentiallyallowsthecoursetofocusonthesensorsandactuatorspart. InME333,however,weoptedtomakeunderstandingthehardwareandsoftwareofthe microcontrollerapproximately50%ofthecourse.Thischoicerecognizesthefundamental rolemicrocontrollersplayinmechatronics,andthatmechatronicsengineersmustbe comfortablewithprogramming. • Choiceofmicrocontrollermanufacturer.Therearemanymicrocontrollersonthemarket, withawidevarietyoffeatures.ManufacturersincludeMicrochip,Atmel,Freescale, TexasInstruments,STMicroelectronics,andmanyothers.Inparticular,Atmel microcontrollersareusedinArduinoboards.Arduinosareheavilyusedbyhobbyistsand inK-12anduniversitycoursesinlargepartduetothelargeonlineusersupport communityandthewidevarietyofadd-onboardsanduser-developedsoftwarelibraries. Inthisbook,weoptforthecommerciallypopularMicrochipPICmicrocontrollers,and weavoidthehigh-levelsoftwareabstractionssynonymouswithArduino.(Arduinosare usedinotherNorthwesterncourses,particularlythosefocusingonrapidproduct prototypingwithlittle mechatronicsdesign.) • Choiceofaparticularmicrocontrollermodel.Microchip’smicrocontrollerlineconsists ofhundredsofdifferentmodels,including8-bit,16-bit,and32-bitarchitectures.Wehave chosenamodern32-bitarchitecture.Andinsteadoftryingtowriteabookthatdealswith allPIC32models,whichincludessixdifferentfamiliesofPIC32sasofthiswriting(see xxii Preface AppendixC),wefocusononeparticularmodel:thePIC32MX795F512H.Thereasons forthischoiceare(a)itisapowerfulchipwithplentyofperipheralsandmemory (128KBdataRAMand512KBprogramflash),and,moreimportantly,(b)focusingona singlechipallowsustobeconcreteinthedetailsofitsoperation.Thisisespecially importantwhenlearninghowthehardwarerelatestothesoftware.(Oneofthereasons Microchip’sdocumentationisdifficulttoread,andissofullofexceptionsandspecial cases,isthatitiswrittentobegeneraltoallPIC32sinthecaseoftheReferenceManual, orallPIC32sinaspecificfamilyinthecaseoftheDataSheets.)Oncethereaderhas learnedabouttheoperationofaspecificPIC32,itisnottoodifficulttolearnaboutthe differencesforadifferentPIC32model. • Programminglanguage:C++vs.Cvs.assembly.C++isarelativelyhigh-level language,Cislowerlevel,andassemblyislowerstill. WechoosetoprograminC becauseoftheportabilityofthelanguage,whilestayingrelativelyclosetotheassembly languagelevelandminimizing abstractionsintroducedbyC++. • IntegratedDevelopmentEnvironmentvs.commandline.MPLABXisMicrochip’s IntegratedDevelopmentEnvironment(IDE)fordevelopingsoftwareforPICs.Sowhydo weavoidusingitinthisbook?Becausewefeelthatithideskeystepsinunderstanding howthecodeyouwriteturnsintoanexecutableforthePIC32.Inthisbook,codeis writteninatexteditorandtheCcompilerisinvokedatthecommandline.Thereareno hiddensteps.Oncethereaderhasmasteredthematerialinthefirstfewchaptersofthis book,MPLABwillnolongerbemysterious. • UseoftheHarmonysoftwarevs.ignoringit.Microchipprovidesanextensivelibraryof middleware,devicedrivers,systemservices,andothersoftwaretosupportalloftheir PIC32models.Onegoalofthissoftwareistoallowyoutowriteprogramsthatare portableacrossdifferentPIC32models.Toachievethis,however,asignificantamountof abstractionisintroduced,separatingthecodeyouwritefromtheactualhardware implementation.ThisisbadpedagogicallyasyoulearnaboutthePIC32.Instead,weuse low-levelsoftwarecommandstocontrolthePIC32’speripherals,reinforcingthehardware documentationinthisbookandintheDataSheetandReferenceManual.Onlywiththe morecomplicatedperipheralsdoweusetheHarmonysoftware,specificallyforUSB,in Chapter20. • Samplecodevs.writingityourself.TheusualwaytolearntoprogramPIC32sistotake someworkingsamplecodeandtrytomodifyittodosomethingelse.Thisisnatural, exceptthatifyourmodifiedcodefails,youareoftenleftwithnoideawhattodo.Inthis bookweprovideplentyofsamplecode,butwealsofocusonthefundamentalsof programmingthePIC32sothatyoulearntowritecodefromscratchaswellasstrategies todebugifthingsgowrong(Figure0.1). Thephilosophyrepresentedbythechoicesabovecanbesummedupsuccinctly:Thereshould benomagicsteps!Youshouldknowhowandwhythecodeyouwriteworks,andhowit Preface xxiii This book PIC32 programming ability Usual Copying trajectory code Foundations Quickstart Time Figure0.1 ThetrajectoryofPIC32programmingabilityvs.timefortheusual“copyandmodify”approachvs. thefoundationalapproachinthisbook.Thecrossovershouldoccuratonlyafewweeks! connectstothehardware.Youshouldnotbesimplymodifyingopaqueandabstractcode, compilingwithamysteriousIDE,andhopingforthebest. TheNU32developmentboard TheNU32developmentboardwascreatedtosupportthisbook.Ifyoudonothavetheboard, youcanstilllearnalotabouthowaPIC32worksfromreadingthisbook.Wehighly recommendthatyougettheNU32boardandthekitofmechatronicsparts,however,toallow youtoworkthroughtheexamplesinthebook. Inkeepingwiththe“nomagic”philosophy,theprimaryfunctionoftheNU32istobreakout thepinsofthePIC32MX795F512Htoasolderlessprototypingbreadboard,toalloweasy wiringtothepins.Otherwisewetrytokeeptheboardasbarebonesandinexpensiveas possible,leavingexternalcircuitstothereader.Toallowyoutogetupandrunningasquickly aspossible,though,theboarddoesprovideafewdevicesexternaltothePIC32:twoLEDs andtwobuttonsforsimpleuserinteraction;a3.3Vregulator(toprovidepowertothePIC32) anda5Vregulator(toprovideacommonlyneededvoltage);aresonatortoprovideaclock signal;andaUSB-to-UARTchipthatsimplifiescommunicationbetweentheuser’scomputer andthePIC32. ThePIC32ontheNU32comeswithabootloaderprogrampre-installed,allowingyouto programthePIC32withjustaUSBcable.TheNU32canalsobeprogrammeddirectlyusinga programmerdevice,likethePICkit3.ThisiscoveredinChapter3.6.

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.