lec-into_to_prog_embedded_systems

lec-into_to_prog_embedded_systems

ID:39138311

大小:2.22 MB

页数:35页

时间:2019-06-25

上传者:不努力梦想只是梦
lec-into_to_prog_embedded_systems_第1页
lec-into_to_prog_embedded_systems_第2页
lec-into_to_prog_embedded_systems_第3页
lec-into_to_prog_embedded_systems_第4页
lec-into_to_prog_embedded_systems_第5页
资源描述:

《lec-into_to_prog_embedded_systems》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库

IntroductiontoProgrammingEmbeddedSystemsSebastianFischmeistersfischme@seas.upenn.eduDepartmentofComputerandInformationScienceUniversityofPennsylvania1GoalsRoughunderstandingoftheunderlyinghardware.Understandhowtodevelopsoftwareforthelabplatform.CSE480/CIS700S.Fischmeister21 WhatisAnEmbeddedSystem?Ageneral-purposedefinitionofembeddedsystemsisthattheyaredevicesusedtocontrol,monitororassisttheoperationofequipment,machineryorplant.“Embedded”reflectsthefactthattheyareanintegralpartofthesystem.Inmanycases,their“embeddedness”maybesuchthattheirpresenceisfarfromobvioustothecasualobserver.InstituteofElectricalEngineers(IEE)CSE480/CIS700S.Fischmeister3ForUsPIC18F2680o3,328BRAMo64kBROMo1.024BEEPROMo5MIPS@20MHzoA/Dconverterso1xUARTo1x8bitTimero3x16bitTimerCSE480/CIS700S.Fischmeister42 WilluseinthePICDEM2boardtoBlinkLEDsControlanLCDdisplayCommunicateviatheseriallinewithaPCCommunicateviatheCANprotocolwithothermicrochipsDriveasteppermotorCSE480/CIS700S.Fischmeister5UseitfurthertoControlamodularrobot:CSE480/CIS700S.Fischmeister63 TheHardware7AMicroprocessorIntroducedasaprogrammablereplacementforlogic-basedcircuitsinthe1970s.Advantagescomparedtologic-basedcircuits:oProvidefunctionalupgrades(e.g.,addnewfeaturetomachinetoolafterdeployment)oProvideeasymaintenanceupgrades(e.g.,fixabuginthecellphoneviaanSMSfirmwareupgrade)oLessfragile(e.g.,insteadofhundredsdiscretelogicchipsandwiringonlyonemicroprocessor)oProtectionofintellectualproperty(itismoredifficulttocopysoftwareburntintheon-chipmemorythantocheckthepartnumbersandthewiring)CSE480/CIS700S.Fischmeister84 WhatmakesaMicroprocessor?ProcessoroAnarithmeticlogicunit(ALU)forprocessing.MemoryoPermanentmemoryforkeepingtheprogram(=ROM)oVolatilememoryforcomputation(=RAM)oRewritablepermanentmemoryforlogging,tuning,storingintermediatedata(=EEPROM)ConnectivitytoperipheralsoBinaryoutputsviasinglechippinsoIntegratedasynchronousandsynchronousserialinterfacessuchasUART,I2C,RS232,CANCSE480/CIS700S.Fischmeister9WhatmakesaMicroprocessor?TimersoEventcounting,inputcapture,real-timeinterrupt,watchdogtimeroPulse-widthmodulation(PWM)SupportfortheanalogueworldoAnalog-to-digitalconverter(ADC)oDigital-to-analogconverter(DAC)SoftwaredebugsupporthardwareoJTAGCSE480/CIS700S.Fischmeister105 MeetthePIC18F2680CSE480/CIS700S.Fischmeister11InsideCSE480/CIS700S.Fischmeister126 HarvardArchitectureAssigndataandprograminstructionstodifferentmemoryspaces.Eachmemoryspacehasaseparatebus.Thisallows:oDifferenttiming,size,andstructureforprograminstructionsanddata.oConcurrentaccesstodataandinstructions.oClearpartitioningofdataandinstructions(=>security)Thismakesithardertoprogram,becausestaticdatacanbeintheprogramspaceorinthedataspace.Iftheprogramspaceandthedataspaceareincompatible,copyingdataisnolongera(,len)dump.CSE480/CIS700S.Fischmeister13DataMemoryMemorylayoutoInstructionsinthePIC18arelimitedto16bits.oToaddressthewholeareayouwouldneed12bit=>toomany.oMemoryissplitinto256Bbanks.Onlyoneisactive.RegistertypesoGeneral-purposeregisters(GPR)oSpecialfunctionregisters(SFR)SFRcontroltheMCUandtheperipherals.CSE480/CIS700S.Fischmeister147 ProgramMemoryReturnaddressstack(31-entries)forsubroutinecallsandinterruptprocessing.Resetvector(0000h)istheprogram-startingaddressafterpower-onormanualreset.Highpriorityint.vec(0008h)isthestartingaddressofthisISRwithatmost16B.Lowpriorityint.vec(0018h)dittobutwithoutarestriction.Theuserprogramfollowsthelowpriorityint.vectorprogram.CSE480/CIS700S.Fischmeister15FurtherProcessorInformationIthasalonglistofCPUregisters(seespecification).oNotimportantwhenprogrammingC,notirrelevanteither.oForexampleSTKPTR,INTCON*,STATUSPIC18supportsinstructionpipeliningwithadepthoftwostepsoInstructionfetchoInstructionexecuteCSE480/CIS700S.Fischmeister168 TheProgrammingProcess17OverviewoftheProgrammingProcessCSE480/CIS700S.Fischmeister189 Sourcefile#include#defineSHIFT_ME3#defineLOOP_FOREVER()while(1);voiddelay(unsignedintx){while(x--);}voidmain(void){unsignedintxx=100%2<requiresabankswitchinginstruction.oNearspecifiesthatitisintheaccessbank.Near/farprogrammemoryobjectsoFarspecifiesthattheobjectisanywhereintheprogrammemory.oNearspecifiesthatitiswithin64KB.Thedefaultstoragequalifierforprogramanddatamemoryobjectsisfar.CSE480/CIS700S.Fischmeister4020 Ram/RomQualifiersIntheHarvardarchitecture,programandmemoryspaceareseparated=>requiremeanstospecifywheretofindlook.RamqualifieroRamspecifiesthattheobjectislocatedinthedatamemory.oItisthedefaultforvariables.RomqualifieroRomspecifiesthattheobjectislocatedintheprogrammemory.oUsefulforconstantdatasuchaslookuptables.CSE480/CIS700S.Fischmeister41MCC18ANSI/ISODivergencesMPLABC18implementssomeoptimizationsthatarenotspecifiedordifferfromtheANSI/ISOCstandard.IntegerpromotionsoC18willperformarithmeticatthesizeofthelargestoperand,evenifbothoperandsaresmallerthananinteger.unsignedcharj,k;#defineX0x20unsignedi;#defineY0x5j=0x79;#defineZ(X)*(Y)k=0x87;i=j+k;unsginedi;i=Z;iwillbe0x0insteadof0x100.CSE480/CIS700S.Fischmeister4221 MCC18ANSI/ISODivergencesNumericconstantsoC18allowsspecifyingbinaryvaluesusingthe0bprefix.o0b0111001=0x39=57StringconstantsoStringsaretypicallystoredintheprogrammemory.oUsualqualifiersare:constromchar[]oTwowaystodeclarestringarraysromconstchartable[][20]={"string1","string2",80B"string3","string4"};romconstchar*romtable2[]={"string1","string2",44B"string3","string4"};CSE480/CIS700S.Fischmeister43CopyingDatabetweenROM&RAMPointerstodatamemoryandprogrammemoryareincompatible!Adatamemorypointercannotbepassedasaprogrammemorypointerandviceversa.Copyingbetweendataandprogrammemorylookslikethis:voidstr2ram(staticchar*dest,staticcharrom*src){while((*dest++=*src++)!='');}CSE480/CIS700S.Fischmeister4422 InlineAssemblyAnassemblysectionstartswith_asmandendswith_endasm._asmnop_endasmUsefulforoptimizationandimplantingexplicitcodeintheprogram(e.g.,fortracesorbenchmarks).Shouldbekepttoaminimum,becauseitturnsoffcompileroptimization.CSE480/CIS700S.Fischmeister45AccesstoAssemblyInstructionsAssemblyprovidesinstructionsthatarenottypicallyaccessiblefromthehigh-levellanguage(e.g.,swapupperandlowernibble,nop)CSE480/CIS700S.Fischmeister4623 #pragmaThe#pragmastatementisusedtomanageoProgrammemorywith#pragmacode,#pragmaromdataoDatamemorywith#pragmaudata,#pragmaidataoInterruptfunctionswith#pragmainterruptoConfigurationsettingswith#pragmaconfigProgrammemoryo#pragmacode[overlay][section-name[=address]]Allowsplacingcodeataspecificlocationintheprogrammemory.#pragmacodeuart_int_service=0x08Overlaytellsthecompilertotryandoverlayasmanysectionsofthespecifiedfunctionsaspossible.CSE480/CIS700S.Fischmeister47#pragmaProgrammemoryo#pragmaromdata[sectionname[=address]]Allowstoplacethedatafollowingthe#pragmaintheprogrammemory.Usefulforcorrelatedlookuptablesthatcanthenbeabsolutelyaddressfromtheprogramcode(table2_data=table1_data[i]+offset).Datamemoryo#pragmaudata[attribute-list][sectionname[=address]]Specifiesalocationforthefollowingstaticallyallocateduninitializeddata(udata).Perdefault,allglobalvariableswithoutinitialvalueareplacedinudata.o#pragmaidata[attribute-list][sectionname[=address]]Similartoudata,butforstaticallyallocatedinitializeddata,only.Usefulfor256Bbankrestriction.oAttributeaccessandoverlayAllowsplacingaspecificsectionintotheaccessregionofthedatamemory(=>ACCESSBANK)Mustbedeclaredwithanearkeyword.CSE480/CIS700S.Fischmeister4824 #pragmaInterruptserviceroutinesoInterruptserviceroutinespreemptthecurrentexecution.AfterfinishingtheISRcomplete,theexecutionresumes.(=>contextswitch)oTheISRsavesaminimalcontextofWREG,BSR,STATUS,etc.oInterruptfunctionshaveaseparatetemporarysectionsinmemorythatarenotoverlaidwithothersections(seethe.mapfile).o#pragmainterrupt[tmpname][save=][nosave=[tmpname][save=][nosave=o#pragmavarlocate"section-name"oUsefultolocationvariablesinspecificbanksforperformancereasons.//**placec1intobank1#pragmavarlocate1c1externsignedcharc1;//**placec2intobank1#pragmavarlocate1c2externsignedcharc2;voidmain(void){c1+=5;/*NoMOVLBinstructionneedstobegeneratedhere.*/c2+=5;}CSE480/CIS700S.Fischmeister5025 #pragmaChipconfigurationo#pragmaconfigoAllowsspecifyingprocessor-specificconfigurationsettings.oE.g.,#pragmaconfigWDT=ON,WDTPS=128#pragmaconfigOSC=HSCSE480/CIS700S.Fischmeister51DebuggingandEmulation5226 IntroductionDebuggingRestricttheintroductionofuntestedandflawedsoftware(realprogrammerusegcc-xc-<2.78MB/SecCSE480/CIS700S.Fischmeister6030 PolledI/OProgrammingSeveralproblemswithpolledI/Oprogramming:oSystemtimingandsynchronizationiscompletelysoftwaredependent.Changesintheprocessorspeed,frequency,powerconsumptionChangesinthesoftwareoNotwellsuitedforburstydatatransferHighoverheadTheoldpollingvsinterruptargumentoDifficulttodebugDifficulttoreproduceerrorsDifficulttosettherightbreakpointsoTime-referencedsystemCannotentersuspendmodes=>highenergyconsumptionCSE480/CIS700S.Fischmeister61WhatisanInterrupt?Everyoneexperiencesinterruptsasa(e.g.,cellphones,emailpop-ups,peopleaskingquestions)Inanembeddedsystems,interruptsareservicerequests.Theadvantageofinterruptsisthattheyallowsplittingsoftwareintoabackgroundpartandaforegroundpart(=>moretocomelater).oThebackgroundpartperformstasksunrelatedtointerrupts.oInterruptsaretransparent,sonospecialprecautionsneedtobedone.oTheforegroundpartservicesinterrupts.CSE480/CIS700S.Fischmeister6231 InterruptsSourcesofinterruptsare:oInternalinterruptsgeneratedbytheon-chipperipheralssuchasserialorparallelports,andtimers.oExternalinterruptsgeneratedbyperipheralsconnectedtotheprocessor.oExceptionsthrownbytheprocessor.oSoftwareinterruptsUsefultosteercontrolflowinyourapplication.Arethesourceofalotofevil,ifnotdoneright.Non-maskableinterrupts(NMI)oMostinterruptscanbeturnedoffandon(=ignored).oSomecannotbeturnedoffandon(=non-maskableinterrupts):Reset,watchdogtimer,memoryparityfailure(=>restartmachine).CSE480/CIS700S.Fischmeister63ExceptionsExceptionsarebrokendownintotraps,faults,andaborts.Trapsaredetectedandservicedimmediatelyaftertheexecutionoftheinstructionthatcausedtheerrorcondition(=>returnaddresspointstothenextinstruction)Faultsaredetectedandservicedbeforeexecutionoftheinstruction(=>returnaddresspointstotheinstructioncausingthefault).Abortsaresimilartofaults,however,themachinestatecannotberestoredtotheconditionjustpriortotheexception.ExceptionsdetectedbytheIntelProcessorareforexample:oFaults:divideerror,invalidopcode,nomathcoprocessor,segmentnotpresentoTraps:Debug,breakpoint,OverflowoAborts:doublefault,failureofinternalcacheCSE480/CIS700S.Fischmeister6432 RecognizinganInterruptInternalinterruptsarespecifiedbythemanufacturerastheyarealreadyhardwired.InterruptdetectionoEdgetriggered:therisingedgemarksaninterrupt.Latchtheinterruptline.Checkforinterrupt.Ifso,startISR.oLeveltriggered:Adifferenceinthelogiclevelmarksininterrupt.E.g.,checkthelevelaftereveryinstructionoreveryclockedge.Someprocessorsrequiretheleveltobeheldforaminimumnumberofclocksorpulsewidthtoignorenoisylines.MaintainingtheinterruptoWhenshouldyouresettheinterrupt?oRecommendedpracticeis:afteryouservicedit.InternalqueuingofinterruptsoStrategyone:haveacounterthatcountshowoftentheinterrupthasbeenasserteduntilitisserviced.oStrategytwo:Ignoreinterruptuntilithasbeenserviced.CSE480/CIS700S.Fischmeister65TheInterruptMechanismWhathappensafteraninterrupthasbeenasserted?oNothing,ifittheinterruptisnotafaultorabort.oStarttheinterruptservicingprocessattheinstructionboundary.InterruptservicingprocessoSaveprocessorstateinformationrelatedtothecurrentexecution(rememberthe#pragma?).oLocatetheISR.oStartexecutingtheISRuntilhittingareturn.oRestorestateinformationandcontinue.FastinterruptsoThedetectionprocedureissimilarto‘slow’interrupts.oNocontextinformationissaved,theprocessorperformsajumptoaspecifiedaddress(=>shadowregisters).oSpecialreturninstruction(retfie).CSE480/CIS700S.Fischmeister6633 InterruptLatencyInterruptlatencyisthetimeittakestheprocessorfromrecognizingtheinterruptuntilthestartoftheISRexecution.Elementsthataddtotheinterruptlatency:oTimetakentorecognizetheinterrupt.Reconsidermultisamplingtolowerfaultyinterruptdetection.oTimetakentocompletethecurrentinstruction.LowinRISCsystems,potentiallylonginCISCsystems.WithCISCsomecompilersrestrictusetofastinstructionstoreduceinterruptlatency(=>replacehardwareinstructionswithsoftwareroutines)oTimetakenforthecontextswitch.oTimetakentofetchtheinterruptvector.oTimetakentostarttheISR.Forthemicroprocessor,computingtheworstcaseinterruptlatencyisdoable,butconsidersystemswithcaches,flexibleinterruptvectors,largenumberofregisters,deeppipelines,etc.CSE480/CIS700S.Fischmeister67Do’sandDon’tswithInterruptsAlwaysexpecttheunexpectedinterruptoWriteagenericinterrupthandlerthatsavestheprocessorstateforlatteranalysis(e.g.,intheEEPROM).InterruptsarenotnegligibleoSwitchingtotheISRcoststime.oToomanyinterruptswillintroduceahighswitchingoverhead.oToolongISRswillcausestarvationforothercomputationtasks.ClearyourinterruptsoLeavingthemsetwillhavetheprocessorignorethem.BewarefalseinterruptsoAlthoughhardwareengineersgivetheirbest,theycanoccur.oDesignthesoftwareaccordingly.CSE480/CIS700S.Fischmeister6834 Do’sandDon’tswithInterruptsUseinterruptlevelsoProcessorsallowmultiplelevelsofinterrupts(high,med,low).oPIC18allowstwo:high,low;highforfastinterrupts,lowfornormalonesControlresourcesharing{Interrupt!!{read(a);mask_int();a=2*a;read(a);printf("a=",a);a=2*a;}printf("a=",a);unmask_int();}CSE480/CIS700S.Fischmeister69DirectMemoryAccessDirectmemoryaccess(DMA)isahigh-performance,low-latencyI/Odata-transfermethodwithspecialhardware.ADMAcontrollerisattachedtotheprocessorandhandlescopyingdatafromtheperipheralsintomemoryregionsspecificallyreservedfortheperipherals.ForfurtherinformationonDMAseeyourcomputerarchitecturelecture.CSE480/CIS700S.Fischmeister7035

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。
相关文章
更多
相关标签
关闭