AVR1000XMEGA的C語(yǔ)言代碼編寫入門_第1頁(yè)
AVR1000XMEGA的C語(yǔ)言代碼編寫入門_第2頁(yè)
AVR1000XMEGA的C語(yǔ)言代碼編寫入門_第3頁(yè)
AVR1000XMEGA的C語(yǔ)言代碼編寫入門_第4頁(yè)
AVR1000XMEGA的C語(yǔ)言代碼編寫入門_第5頁(yè)
已閱讀5頁(yè),還剩30頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

8-bit8位Microcontrollers微處理器ApplicationNote應(yīng)用注釋AVR1000:GettingStartedWritingC-codeforXMEGAAVR1000:XMEGA的C語(yǔ)言代碼編寫入門Features特點(diǎn):?Namingconventions命名約定-Registernames寄存器名-Bitnames位名?C-codenamesC-代碼名-Bitandgroupmasks位與組掩碼-Groupconfigurationmasks組配置掩碼?Methodsforaccessingregisters訪問寄存器的方法?Methodsforwritingreusablemodulefunctions可多次使用模塊功能的寫入方法1Introduction引言Shortdevelopmenttimesandhighqualityrequirementsonelectronicproductshasmadehigh-levelprogramminglanguagesarequirement.ThemainreasonisthatHighlevellanguagesmakeiteasiertomaintainandreusecodeduetobetterportabilityandreadability.由于電子產(chǎn)品的開發(fā)時(shí)間短,質(zhì)量要求高,因此需要高層次的編程語(yǔ)言。最主要的原因是,高級(jí)語(yǔ)言具有更好的可移植性和可讀性,使其更易于維護(hù)和重復(fù)使用代碼。Thechoiceofprogramminglanguagealonedoesnotensurehighreadabilityandreusability;goodcodingstyledoes.ThereforetheXMEGA?peripherals,headerfilesanddriversaredesignedwiththisinmind.編程語(yǔ)言的選擇本身并非是能確保具有較高的可讀性和可重復(fù)使用性的唯一條件,還必須有良好的編碼風(fēng)格。因此XMEGA?的外圍設(shè)備,頭文件和驅(qū)動(dòng)程序的設(shè)計(jì)都是基于這方面考慮的。Themostwidelyusedhigh-levellanguageforAVR?microcontrollersisC,andthisapplicationnotethereforefocusesonCprogramming.TosupportmostoftheAVRCcompilersthatareavailable,thecodeexamplesareasfaraspossiblewritteninANSIC.AfewexamplesarespecifictoIAREmbeddedWorkbench?,buttheideasandmethodscanbeusedforothercompilerswithminorchanges.IARspecificexamplesareclearlymarked.AVR?微控制器使用的最廣泛的高級(jí)語(yǔ)言就是C語(yǔ)言,因此本應(yīng)用注釋的重點(diǎn)是C語(yǔ)言編程。為了支持大多數(shù)可用的AVRC語(yǔ)言編譯器,我們盡可能把代碼示例編寫在ANSIC語(yǔ)言的規(guī)范中。有些例子是IAREmbeddedWorkbench?專用的,但其思路和方法可用于與其他變化不大的編譯器。IAR專用的示例都有清晰的標(biāo)示。2XMEGAModulesXMEGA模塊AnAVRXMEGAiscomposedofseveralbuildingblocks:AnAVRCPUcore,SRAM,Flash,EEPROMandanumberofperipheralmodules.Thesebuildingblocksarecalled“moduletypes”.AnXMEGAcanhaveoneormoreinstancesofagivenmoduletype.Allinstancesofamoduletypehavethesamefeaturesandfunctions.一個(gè)AVRXMEGA由數(shù)個(gè)結(jié)構(gòu)塊組成:一個(gè)AVRCPU芯片,一個(gè)SRAM,一個(gè)閃存,一個(gè)EEPROM以及若干外設(shè)模塊。這些結(jié)構(gòu)塊被稱為“模塊類型”。XMEGA可以有一個(gè)或多個(gè)給定模塊類型的實(shí)例。一個(gè)模塊類型的所有實(shí)例都具有相同的特性和功能。Somemoduletypescanbeasubsetofothermoduletypes.Theseinheritasubsetofthefeatures(andregisters)ofthesupertype,allinheritedfeaturesarefullycompatible.Thisappliestoe.g.timersandIOports.Thesubsetofamoduletypecanforatimermeanthatithasfewercompareandcapturechannelsthanafulltimermodule.Similarly,anIOportmayhavelessthaneightpins.有些模塊類型可以是其他模塊類型的子集。這些(模塊類型)繼承了特大模塊類型的某個(gè)子集的特征(和寄存器),其繼承的所有特征都完全兼容。這適用于比如計(jì)時(shí)器和IO端口。用于計(jì)時(shí)器的模塊類型的子集可能意味著它所能得到的比較和捕獲通道比完整的計(jì)時(shí)器模塊的要少。同樣,一個(gè)IO端口的管腳可能不足八個(gè)。Amoduletypecanbea“USART”,whilethemoduleinstanceise.g.“USARTC0”,wherethe“C0”suffixindicatestheinstanceis“USARTnumber0onportC”.Forsimplicity,amoduleinstancewillbereferredtoasamodulethroughoutthisdocument,unlessthereisaneedtodifferentiate.一個(gè)模塊類型可以是“USART”的,如果這個(gè)模塊實(shí)例比如是“USARTC0”,其中的“C0”后綴表示這個(gè)實(shí)例是“端口C上的USART編號(hào)為0”。為了簡(jiǎn)單起見,一個(gè)模塊實(shí)例將被稱為這整個(gè)文件中的一個(gè)模塊,除非是有必要另作區(qū)分。Eachmodulehasanumberofregistersthatcontaincontrolorstatusbits.Allmodulesofagiventypecontainthesameset(orsubset)ofregisters,andalltheseregisterscontainthesameset(orsubset)ofcontrolandstatusbits.每個(gè)模塊都有若干寄存器,這些寄存器都包含控制位或狀態(tài)位。一個(gè)給定類型的所有模塊都包含相同的寄存器集合(或子集),并且所有這些寄存器包含相同的控制位和狀態(tài)位的集合(或子集)。Figure2-1.Moduletypes,instances,registersandbits.圖2-1.模塊類型,實(shí)例,寄存器和位EachmodulehasafixedbaseaddressintheIOmemorymapandallregisterscontainedinthemodulehavefixedoffsetaddressesrelativetothemodulebaseaddress.ThiswayeachregisterwillnotonlyhaveanabsoluteaddressintheIOmemoryspace,butalsoarelativeaddressdefinedbyitsoffset.Theregisteroffsetaddressesareequalforallinstancesofamoduletype,simplifyingthetaskofwritingdriversthatcanbeusedforallmodulesofaspecifictype.在IO內(nèi)存圖里,每個(gè)模塊都有一個(gè)固定的基礎(chǔ)地址,并且該模塊中的所有寄存器都有固定的偏移地址(這是相對(duì)于模塊的基地址而言)。如此這樣,每個(gè)寄存器不僅會(huì)在IO內(nèi)存空間有一個(gè)絕對(duì)地址,而且還有一個(gè)根據(jù)其偏移量定義的相對(duì)地址。一個(gè)模塊類型的所有實(shí)例中的寄存器偏移地址都是平等的,這樣就簡(jiǎn)化了編寫能夠適用于某個(gè)特定類型的所有模塊的驅(qū)動(dòng)程序的任務(wù)。2.1RegisterNamingConvention2.1.寄存器命名約定Registerareroughlyspeakingdividedintocontrol,statusanddataregistersandthenamingofregistersreflectthis.Ageneral-purposecontrolregisterofthemoduleisnamedCTRL.Ifmultiplegeneral-purposecontrolregistersexistsinamoduletheyhaveasuffixcharacter.InthiscasethecontrolregisterswouldbenamedCTRLA,CTRLB,CTRLCandsoon.ThisalsoappliestoSTATUSregisters.大致說來,寄存器有控制寄存器、狀態(tài)寄存器和數(shù)據(jù)寄存器之分,這從寄存器的命名就可看出。模塊的一個(gè)通用的控制寄存器被命名為CTRL。如果在一個(gè)模塊中存在多個(gè)通用控制寄存器,他們都有一個(gè)后綴字符。在這種情況下,控制寄存器將被命名為CTRLA、CTRLB、CTRLC等。這方法也適用于狀態(tài)寄存器。Forregistersthathaveaspecificfunctionthenamereflectsthisfunctionality.Forexample,acontrolregisterthatcontrolstheinterruptlevelofamoduleisnamedINTCTRL.對(duì)于具有特定功能的的寄存器,它們的命名會(huì)反映其功能性。例如,一個(gè)控制寄存器,控制一個(gè)模塊的中斷級(jí)別,它就被命名為INTCTRL。SincetheAVRdatabuswidthis8bit,largerregistersareimplementedusingseveral8-bitregisters.Fora16-bitregister,thehighandlowbytesareaccessedbyappending“H”and“L”respectivelytotheregistername.Forexample,the16-bitTimer/CountercountregisterisnamedCNT.ThetwobytesarenamedCNTLandCNTH.由于AVR的數(shù)據(jù)總線寬度為8位,較大的寄存器得使用幾個(gè)8位寄存器才能生效。對(duì)于一個(gè)16位寄存器,要訪問其高8位元組和低8位元組,得在這個(gè)寄存器的命名上分別附加“H”和“L”。例如,16位計(jì)時(shí)器/計(jì)數(shù)器的計(jì)數(shù)寄存器被命名為CNT,其兩個(gè)8位元組就被命名為CNTL和CNTH。Foraregisterlargerthan16bit,thebytesarenumberedfromtheleastsignificantbyte.Forexample,the32-bitADCcalibrationregisterisnamedCAL.ThefourbytesarenamedCAL0,CAL1,CAL2andCAL3(fromleasttomostsignificantbyte).對(duì)于大于16位的寄存器,其8位元組的編號(hào)是從最低有效的8位元組開始。例如,32位的ADC校準(zhǔn)寄存器被命名為CAL,其四個(gè)8位元組(從最低到最高有效8位元組)就被分別命名為CAL0,CAL1,CAL2和CAL3。MostCcompilersofferautomatichandlingofaccesstomulti-byteregisters.InthatcasethenameCNT,without“H”or“L”suffix,couldbeusedtoperforma16-bitaccesstotheTimer/Countercountregister.Thisisalsothecasefor32-bitregisters.大多數(shù)C語(yǔ)言編譯器都提供了自動(dòng)處理多8位元組寄存器的訪問。在這種情況下,CNT的命名沒有加“H”或“L”后綴的,可以用來執(zhí)行16位的計(jì)時(shí)器/計(jì)數(shù)器的計(jì)數(shù)寄存器的訪問。這方法也同樣使用于32位寄存器。2.2BitNamingConvention2.2位命名約定Registerbitscanhaveanindividualfunctionorbepartofabitgroupthathaveajointfunction:Anindividualbitcouldbeabitthatenablesamodule,e.g.theUSARTENABLEbit.Abitgroupcanconsistoftwoofmorebitsthatjointlyselectaspecificconfigurationofthemodulethattheybelongto.Abitgroupoffersupto2nselections,wherenisthenumberofbitsinthebitgroup.ThetwobitsthatcontroltheUSARTReceiveCompleteinterruptlevel,RXINTLVL[1:0],isanexampleofabitgroup.Thesetwobitsofferthefollowingselections:寄存器位可以有一個(gè)單獨(dú)的函數(shù),或是一個(gè)位組的一部分,有一個(gè)共同的功能:一個(gè)單獨(dú)的位可以是啟用一個(gè)模塊的位,如USARTENABLE位。一個(gè)位組可以由兩個(gè)或兩個(gè)以上的位組成,這些位共同選擇了它們所屬的模塊的特殊配置。一個(gè)位組提供多達(dá)2n個(gè)選項(xiàng),其中的n是位組中位的數(shù)量。這兩個(gè)位控制的USART接收結(jié)束中斷級(jí)別,RXINTLVL[1:0],是一個(gè)位組的一個(gè)例子。這兩個(gè)位提供以下選項(xiàng):Table2-1.RXINTLVLbitsandcorrespondinginterruptlevelselection.表2-1.RXINTLVL位和相應(yīng)的中斷級(jí)別選項(xiàng)RXINTLVL1RXINTLVL0Interruptlevelselection中斷級(jí)別選項(xiàng)00InterruptOff中斷關(guān)閉01Lowlevelinterrupt低級(jí)中斷110Mediumlevelinterrupt中級(jí)中斷11Highlevelinterrupt高級(jí)中斷Bitsthatarepartofagroupwillalwayshaveanumbersuffix.Bitsthatarenotpartofabitgroupwillneverhaveanumbersuffix.ATimer/CountercontrolregisterDhastwobitgroups,EVACTandEVSEL.Thebitsinthesegroupshaveanumbersuffix,whiletheEVDLYbit,whichisnotpartofabitgrouphasnonumbersuffix.作為一個(gè)組的一部分的位,將始終有一個(gè)數(shù)字后綴。不是一個(gè)位組的一部分的位,永遠(yuǎn)不會(huì)有一個(gè)數(shù)字后綴。計(jì)時(shí)器/計(jì)數(shù)器控制寄存器D有兩個(gè)位組:EVACT和EVSEL。在這些組中的位都有一個(gè)數(shù)字后綴,而EVDLY位不是一個(gè)位組的一部分,因此它沒有數(shù)字后綴。Table2-2.BitsgroupsandbitnamesforbitsinTimer/CounterControlregisterD–CTRLD.表2-2.適用于計(jì)時(shí)器/計(jì)數(shù)器控制寄存器D-CTRLD中的位的位組和位名稱BitGroup位組EVACT-EVSELBitname位名EVACT2EVACT1EVACT0EVDLYEVSEL3EVSEL2EVSEL1EVSEL0Bitnumber位編號(hào)765432103WritingC-codeforXMEGA編寫XMEGA的C語(yǔ)言代碼ThefollowingsectionsfocusonhowtowriteC-codefortheXMEGA.TheexamplesshowhowtomakethecodehighlyreadableandportablebetweendifferentXMEGAdevices.Theexamplescanalsobeusedasaguidelinetowritecodethatiseasytoverifyandmaintain.以下各節(jié)重點(diǎn)放在如何編寫XMEGA的C語(yǔ)言代碼。示例顯示了如何使代碼具有很強(qiáng)的可讀性,并能在不同的XMEGA器件之間移植。這些例子也可以作為指導(dǎo)編寫代碼的準(zhǔn)則,使其易于驗(yàn)證和維護(hù)。XMEGAmodulesarelocatedindedicatedandcontinuousblocksinthememoryspaceandcanbeseenasencapsulatedunits.ThisreflectsonthewaythatthemodulesareaccessedwhencodingC:modulesareencapsulatedusingCstructs,inwhichallmoduleregistersarecontained.Figure3-1showsanillustrationofthis.XMEGA的模塊位于內(nèi)存空間的專用的連續(xù)的塊區(qū)域中,我們可以把這些模塊看作是被封裝的單元。這反映了編寫C語(yǔ)言代碼時(shí)訪問模塊的路徑:模塊是用C語(yǔ)言結(jié)構(gòu)封裝的,其中包容了所有的模塊寄存器。圖3-1給出了這個(gè)圖解。Notethatsomeregistershavenodirectmoduleassociation.Thesearenotencapsulatedinstructs,asthestructisusedtoassociateregisterswithamodule.請(qǐng)注意,某些寄存器沒有直接的模塊相聯(lián),這些寄存器都不是封裝在結(jié)構(gòu)里的,因?yàn)樵摻Y(jié)構(gòu)是用來使寄存器與某個(gè)模塊相關(guān)聯(lián)的。Forlargercodeprojectsthemodulestructsprovideadvantages,notonlytoreadability,butalsobecausethecompilerscanreusethemoduledriversandtherebymakethecodeverycompact.Thisisdescribedinmoredetailslater.模塊結(jié)構(gòu)為較大的代碼項(xiàng)目提供的優(yōu)勢(shì)不僅具有可讀性,而且還因?yàn)榫幾g器可以重復(fù)使用模塊驅(qū)動(dòng)程序,從而使代碼非常緊湊。這在后面會(huì)作更詳細(xì)的描述。ThisdocumentintroducesanamingconventionandregisteraccessmethodsthataredifferentfromwhatAVRprogrammingveteransareusedto,butoneshouldbeawarethatthe“classic”waytoaccessregistersisstillsupportedbytheheaderfiles.Thisalsoappliesonthebitlevel.本文檔介紹的命名約定和寄存器訪問的方法,不同于AVR編程老手過去常用的方法,但是有一點(diǎn)應(yīng)該知道:訪問寄存器的“經(jīng)典”方法仍然是要得到頭文件的支持。這方法也同樣適用于對(duì)位級(jí)別的訪問。Figure3-1.ModulesplacedindedicatedblocksinIOmemoryspace.圖3-1.放置在IO內(nèi)存空間里的專用塊區(qū)的模塊。3.1XMEGAHeaderFiles3.1XMEGA的頭文件AdedicatedheaderfileisavailableforeachXMEGAdevice.Ifthetargetdeviceisspecifiedintheprojectsettings(assumingthatoneusestheIDEforIAREWAVR),theIARcompilerwillautomaticallyincludethecorrectheaderfileifthedevicefileisincludedasshowninCodeListing3-1.為每個(gè)XMEGA的設(shè)備提供一個(gè)專用的頭文件,如果目標(biāo)設(shè)備是在項(xiàng)目設(shè)置中指定的(假設(shè)一個(gè)目標(biāo)設(shè)備將IDE用于IAREWAVR),又如果該設(shè)備文件是包含在如代碼列表3-1中所示的文件,那么IAR編譯器將自動(dòng)包含這個(gè)正確的頭文件。CodeListing3-1.IARheaderfileinclusion.代碼列表3-1.IAR的頭文件包含Theadvantageisthatifthetargetdevicechanges,thereisnoneedtochangethesourcefiles,onlytheprojectsettings.它的優(yōu)點(diǎn)是,如果目標(biāo)設(shè)備變了,沒有必要修改源文件,唯有以項(xiàng)目設(shè)置的為準(zhǔn)。3.2ModulesRegisters3.2.模塊寄存器TheIOmapislaidoutsothatallregistersforagivenperipheralmoduleareplacedinonecontinuousmemoryblock.Registersbelongingtodifferentmodulesarenotmixed.ThismakesitpossibletoorganizeallperipheralmodulesinCstructs,wheretheaddressofthestructdefinesthebaseaddress,ofthemodule.Allregistersbelongingtoamoduleareelementsinthemodulestruct.IO地圖的設(shè)計(jì)是使一個(gè)給定的外設(shè)模塊的所有的寄存器都放置在一個(gè)連續(xù)的內(nèi)存塊,屬于不同模塊的寄存器不得混合。這使得IO地圖可以將所有外設(shè)模塊組織到C語(yǔ)言結(jié)構(gòu)中,其結(jié)構(gòu)的地址定義模塊的基礎(chǔ)地址,同屬于一個(gè)模塊的所有的寄存器都是這個(gè)模塊結(jié)構(gòu)中的成員。AnexampleistheProgrammableMulti-levelInterruptController(PMIC)module.ThestructdeclarationforthismoduleisshowninCodeListing3-2andanexampleofitsuseinCodeListing3-3.NotethattheexampleinCodeListing3-3assumesthatthereisaninstanceofthePMIC_ttypenamedPMIC.Thisiscoveredlaterinthisdocument.一個(gè)例子是可編程的多級(jí)中斷控制器(PMIC)模塊。申報(bào)此模塊的結(jié)構(gòu)由代碼列表3-2給出,其用途的例子由代碼列表3-3給出。請(qǐng)注意,在代碼列表3-3中的例子是假設(shè)有一個(gè)PMIC_t類型的實(shí)例被命名為PMIC。這在本文檔后面還有提及。CodeListing3-2.Modulestructdeclaration.代碼列表3-2.模塊結(jié)構(gòu)的申報(bào)CodeListing3-3.Modulestructusage.代碼列表3-3.模塊結(jié)構(gòu)的用途3.2.1Multi-wordRegistersinModuleStructs3.2.1.模塊結(jié)構(gòu)中的多詞寄存器Someregistersareusedinconjunctionwithotherregisterstorepresent16or32bitvalues.AsexampleonecouldlookattheADCstructdeclarationshowninCodeListing3-4.將一些寄存器與其他寄存器一起用來代表16位或32位的值。我們可以舉一個(gè)例子,看看ADC結(jié)構(gòu)申報(bào)的一個(gè)寄存器,見代碼列表3-4:CodeListing3-4.ADCstructdeclaration.代碼列表3-4.ADC結(jié)構(gòu)申報(bào)InCodeListing3-4,theADCchannelresultregistersCH0RES,CH1RES,CH2RES,CH3RESandthecompareregister,CMP,are16-bitvalues.ThesearedeclaredusingtheWORDREGISTERmacroshowninCodeListing3-5.Thecalibrationregister,CAL,isa32-bitvalue,declaredusingtheDWORDREGISTERshowninCodeListing3-6.在代碼列表3-4中,ADC通道的結(jié)果寄存器CH0RES,CH1RES,CH2RES,CH3RES和比較寄存器CMP都是16位值。這些寄存器都是用在代碼列表3-5中所示的WORDREGISTER宏申報(bào)的。校準(zhǔn)寄存器CAL,是一個(gè)32位值的,它是用在代碼列表3-6中所示的DWORDREGISTER宏來申報(bào)的。CodeListing3-5.WORDREGISTERMacro.代碼列表3-5.WORDREGISTER宏CodeListing3-6.DWORDREGISTERMacro.代碼列表3-6.DWORDREGISTER宏Asseen,theWORDREGISTERmacrouses“H”and“L”suffixforthehighandlowbytesrespectively.TheDWORDREGISTERusesnumbersuffixtoindicatethebyteorder.Boththe16-bitand32-bitregisterscanbeaccessedin16-bit/32-bitmode,byusingtheregisternamewithoutsuffixasshowninCodeListing3-7.如我們所看到的,WORDREGISTER宏使用后綴“H”和“L”分別作為高8位元組和低8位元組,DWORDREGISTER使用數(shù)字后綴來表示8位元組的順序。在16/32位模式中,都可以使用不帶后綴的寄存器名訪問16位和32位寄存器,見代碼列表3-7。CodeListing3-7.Accessingregistersofvaryingsize.代碼清單3-7。訪問不同大小的寄存器。CodeListing3-7showshowthesinglebyteregisterCTRLAisread,howthetwoCH0RES[H:L]registersarereadusinga16-bitoperation,andhowthefourCAL[3:0]registersarereadina32-bitoperation.Ccompilershandlemulti-byteregistersautomatically.Notehoweverthatinsomecasesitmayberequiredtoreadandwritemulti-byteregistersinoneatomicoperationtoavoidcorruption.Inthiscase,interruptsmustbedisabledduringthemulti-byteaccesstomakesurethataninterruptserviceroutinedoesnotinterferewiththemulti-byteaccess.AVR1306includesexamplesonhowatomicaccessofregistersisdonefortheXMEGATimer/Countermodules.代碼列表3-7演示了如何讀取單個(gè)8位元組寄存器CTRLA,如何使用一個(gè)16位的操作來讀取兩個(gè)CH0RES[H:L]寄存器,以及如何在32位的操作中讀取四個(gè)CAL[3:0]寄存器。C語(yǔ)言編譯器會(huì)自動(dòng)處理多個(gè)8位元組的寄存器。但是請(qǐng)注意,在某些情況下可能要求在一個(gè)原子操作中讀寫多個(gè)8位元組的寄存器,以避免訛誤。假如這樣的話,在多個(gè)8位元組的訪問期間必須禁止中斷,以確保一個(gè)中斷服務(wù)例程不妨礙多個(gè)8位元組的訪問。AVR1306中有些例子是關(guān)于寄存器是如何對(duì)XMEGA的計(jì)時(shí)器/計(jì)數(shù)器模塊進(jìn)行原子訪問的。3.3ModuleAddresses3.3模塊訪問DefinitionsofallperipheralmodulesarefoundinthedeviceheaderfilesavailablefortheXMEGA.TheaddressforthemodulesisspecifiedinANSICtomakeitcompatiblewithmostavailableCcompilers.CodeListing3-8showshowADC0onportAisdefined.在適用于XMEGA設(shè)備的頭文件中找到所有外設(shè)模塊的定義。這些模塊的地址在ANSIC語(yǔ)言標(biāo)準(zhǔn)中作了明確的規(guī)定,使其與大多數(shù)可用的C語(yǔ)言編譯器兼容。代碼列表3-8顯示了端口A上的ADC0是如何定義的。CodeListing3-8.Peripheralmoduledefinition.代碼列表3-8.外設(shè)模塊的定義CodeListing3-8showshowthemoduleinstancedefinitionusesadereferencedpointertotheabsoluteaddressinthememory,coincidingwiththemoduleinstancebaseaddress.Themodulepointersarepre-definedintheXMEGAheaderfiles,itisthereforenotnecessarytoaddthesedefinitionsinthesourcecode代碼列表3-8顯示模塊實(shí)例定義如何使用一個(gè)被解除引用的指針指向內(nèi)存中的絕對(duì)地址,正好與模塊實(shí)例的基礎(chǔ)地址重合。模塊指針是在XMEGA的頭文件中預(yù)先定義的,因此沒有必要在源代碼中添加這些定義。3.4BitMasksandBitGroupMasks3.4位掩碼和位組掩碼Registerbitscanbemanipulatedusingpre-definedmasks,oralternativelybitpositions.Bitpositionsarenotrecommendedformosttasks.Thepre-definedbitmasksareeitherrelatedtoindividualbits,calledabitmaskorabitgroup,calledabitgroupmask,orgroupmaskforshort.寄存器的位可以使用預(yù)先定義的掩碼,或另一個(gè)位的位置,進(jìn)行操作,但大多數(shù)任務(wù)中并不推薦使用位位置。預(yù)先定義的位掩碼可以與獨(dú)立的位有關(guān),稱之為位掩碼;或與一個(gè)位組有關(guān),稱之為位組掩碼,或簡(jiǎn)稱組掩碼。Abitmaskisusedbothwhensettingandclearingindividualbits.Abitgroupmaskismainlyusedwhenclearingmultiplebitsinabitgroup.Settingmultiplebitthatarepartofabitgroupiscoveredinsection3.5.一個(gè)位掩碼是在設(shè)置和清除獨(dú)立的位時(shí)使用,一個(gè)位組掩碼主要是用在清除一個(gè)位組中的復(fù)合位時(shí)使用。在3.5節(jié)中,介紹了復(fù)合位(作為一個(gè)位組的一部分)的設(shè)置。3.4.1BitMask3.4.1位掩碼ConsideraTimerCounterControlRegisterD,CTRLD.Thebitgroups,bitnames,bitpositionsandbitmasksofthisregistercanbeseeninTable3-1.細(xì)心觀察一個(gè)計(jì)時(shí)器計(jì)數(shù)器控制寄存器D,CTRLD,在表3-1中我們可以看到該寄存器的位組、位名稱、位位置以及位掩碼。Table3-1.Bitgroups,bitnames,bitpositionsandbitmasksforbitsinTimerCounterControlregisterD–CTRLD.表3-1.計(jì)時(shí)器計(jì)數(shù)器控制寄存器D-CTRLD里的位的位組、位名稱、位位置以及位掩碼Sincethenamesofbitsneedtobeuniqueforthecompilertohandlethem,allbitsareprefixedwiththemoduletypeitbelongsto.Inmanycases,themoduletypenameisabbreviated.ForallbitdefinesrelatedtotheTimer/Countermodules,thebitnamesareprefixedby“TC_”.由于位的名稱相對(duì)于處理它們的編譯器而言必須是唯一的,所有的位都是用其所屬的模塊類型作前綴。在許多情況下,模塊類型名稱是縮寫的。對(duì)于所有與計(jì)時(shí)器/計(jì)數(shù)器模塊有關(guān)的位的定義,其位名稱的前綴是“TC_”Todifferentiatebetweenbitmasksandbitpositions,asuffixisalsoappended.Forabitmask,thesuffixis“_bm”.ThenameofthebitmaskfortheEVDLYbitisthusTC_EVDLY_bm.CodeListing3-9showsthetypicalusageofabitmask.TheEVDLYbitintheCTRLDregisterofTimer/CounterD0isset,leavingalltheotherbitsintheregisterunchanged.要區(qū)分位掩碼和位的位置,還得附加一個(gè)后綴。對(duì)于一個(gè)位掩碼,其后綴是“_bm”。因此EVDLY位的位掩碼的名稱是TC_EVDLY_bm。代碼列表3-9顯示了一個(gè)位掩碼的典型用法。將EVDLY位在計(jì)時(shí)器/計(jì)數(shù)器D0的CTRLD寄存器中作了設(shè)置,讓該寄存器內(nèi)的所有其它的位保持不變。CodeListing3-9.Bitmaskusage.代碼列表3-9.位掩碼的用法3.4.2BitGroupMasks3.4.2.位組掩碼Manyfunctionsarecontrolledbyagroupofbits.TimerCounterCTRLDregistertheEVACT[2:0]andtheEVSEL[3:0]bitsaregroupedbits.Thevalueofthebitsinagroupselectsaspecificconfiguration.許多功能是受一組位來控制的,計(jì)時(shí)器計(jì)數(shù)器CTRLD寄存器里的EVACT[2:0]位和EVSEL[3:0]位是被分組的位,一組內(nèi)的位值選擇一個(gè)特定的配置。Whenchangingbitsinabitgroupitisoftenrequiredtoclearthebitgroupbeforeassigninganewvalue.Toputitinanotherway:Itisnotenoughtosetthebitsthatshouldbeset,itisalsorequiredtoclearthebitsthatshouldbecleared.Tomakethiseasyabitgroupmaskisdefined.Thegroupmaskusessamenameasthebitsinthebitgroupandissuffixed“_gm”.當(dāng)改變一個(gè)位組內(nèi)的位時(shí),通常要求先清除該位組后方可分配一個(gè)新的值。換句話說:由于不夠設(shè)置應(yīng)設(shè)置的位,所以還需要清除應(yīng)清除的位。為了簡(jiǎn)單起見,我們對(duì)一個(gè)位組掩碼進(jìn)行定義,該組掩碼采用的名稱與該位組中的位名相同,并且加后綴“_gm”。CodeListing3-10showshowthegroupmaskrelatestothebitmasks.Inreality,thegroupmaskvaluesarepre-calculatedintheheaderfiles,sothecompilerdoesnotneedtocalculatethesameconstantoverandoveragain.代碼列表3-10顯示了如何使組掩碼與位掩碼有聯(lián)系。實(shí)際上,組掩碼值是在頭文件中預(yù)先計(jì)算的,所以編譯器并不需要一遍又一遍地對(duì)相同的常量再作計(jì)算。CodeListing3-10.Groupmaskandbitmaskrelation.代碼列表3-10.組掩碼與位掩碼的關(guān)聯(lián)Thebitgroupmaskisprimarilyintendedtocleartheoldconfigurationofabitgroupbeforewritinganewvalue.CodeListing3-11showshowthiscanbedone.ThecodewillcleartheEVACTbitgroupintheCTRLDregisterofTimer/CounterD0.Thisconstructisnotveryusefulinitself.Thegroupmaskwilltypicallybeusedinconjunctionwithagroupconfigurationmask,whichiscoveredinsection3.5.首先,位組掩碼是要在寫入一個(gè)新值之前先將一個(gè)位組的老的配置清除掉,代碼列表3-11顯示了如何可以做到這一點(diǎn)。代碼將清除掉在計(jì)時(shí)器/計(jì)數(shù)器D0的CTRLD寄存器里的EVACT位組。這種構(gòu)造本身并不是很實(shí)用的。組掩碼通常會(huì)與一個(gè)組配置掩碼一起使用,這在3.5節(jié)中會(huì)涉及到。CodeListing3-11.Groupmaskusage.代碼列表3-11.組掩碼用途3.5BitgroupConfigurationMasks3.5.位組配置掩碼Itisoftenrequiredtoconsultthedatasheettoinvestigatewhatbitpatternneedstobeusedwhensettingabitgrouptoadesiredconfiguration.Thisalsoapplieswhenreadingordebuggingcode.Toincreasethereadabilityandtominimizethelikelinessofsettingbitsinbitgroupsincorrectly,anumberofgroupconfigurationmasksaremadeavailable.Eachgroupconfigurationmaskselectsaconfigurationforaspecificgroupmask.當(dāng)你想把一個(gè)位組設(shè)置成某種理想配置狀態(tài)時(shí),通常要查閱數(shù)據(jù)表,研究需要使用什么樣的位圖。在閱讀代碼或調(diào)試代碼時(shí),這種方法也同樣適用。為了提高可讀性,并盡量減少不正確的設(shè)置位組的位的可能性,有許多組配置掩碼可用,每個(gè)組配置掩碼為一個(gè)特定組掩碼選擇一個(gè)配置。Thenameofagroupconfigurationmaskisaconcatenationofthemoduletype,thebitgroupname,adescriptionoftheconfigurationandasuffix,“_gc”,indicatingthatthisisagroupconfiguration.SeeFigure3-2foranexample.一組配置掩碼的名稱是一連串的模塊類型、位組名、配置的說明以及后綴“_GC”,表明這是一個(gè)組配置。請(qǐng)參見圖3-2的一個(gè)例子。Figure3-2.Groupconfigurationnamecomposition(usingUSARTreceivecompleteinterruptlevelbitsasexample).見圖3-2.組配置名的構(gòu)成(用USART接收完成中斷級(jí)位作為實(shí)例)InspectingthegroupconfigurationFigure3-2,onecanseethatitisusedtoselectaconfigurationfortheRXCINTLVLbitsinaUSARTmodule.Thisspecificgroupconfigurationselectsahigh(HI)interruptlevel.通過仔細(xì)查看組配置圖3-2,我們可以發(fā)現(xiàn)這是用來為一個(gè)USART模塊中的RXCINTLVL位選擇一個(gè)配置的。這個(gè)特定組的配置選擇的是高(HI)中斷級(jí)別。ThebitgroupfortheReceiveCompleteInterruptLevelconsistsoftwobits,RXINTLVL[1:0].Table3-2showstheavailablegroupconfigurationsforthisbitgroup.接收完成中斷級(jí)的位組由兩個(gè)位RXINTLVL[1:0]組成。表3-2顯示了此位組的可用的組配置。Theconfigurationnamesare“OFF”,“LO”,“MED”and“HI”.Thesenamesmakeitveryeasytowriteandmaintaincode,asitrequiresverylittleefforttounderstandwhatconfigurationthespecificconfigurationmaskselects.配置名稱是“OFF”,“LO”,“MED”,“HI”。這些名稱使得編寫和維護(hù)代碼變得很容易,因?yàn)檫@樣你無需太費(fèi)力就能知道特定配置掩碼選擇什么樣的配置。Table3-2.RXINTLVLbitsandcorrespondinginterruptlevelofmoduleinterrupt.表3-2.RXINTLVL位與相關(guān)模塊中斷的中斷級(jí)別Tochangeabitgrouptoanewconfiguration,thebitgroupconfigurationistypicallyusedinconjunctionwiththebitgroupmask,toensurethattheoldconfigurationiserasedfirst.CodeListing3-12showshowthegroupmaskandaconfigurationmaskcanbeusedtoreconfiguretheUSARTC0ReceiveCompleteInterruptleveltomediumlevel.要改變一個(gè)位組到一個(gè)新的配置,位組配置通常結(jié)合位組掩碼使用,以確保首先擦除了舊的配置。代碼列表3-12顯示了如何使用組掩碼和一個(gè)配置掩碼來將USARTC0接收完成中斷優(yōu)先級(jí)重新配置成中等級(jí)別。CodeListing3-12.Changingabitgroupconfiguration.代碼列表3-12.改變一個(gè)位組配置NotethatthoughitmaybetemptingtosplitthecodeinCodeListing3-12intotwoseparatecodelines,onethatclearthebitgroupandonethatsetsthenewvalue,thisisnotrecommended.SincetheINTCTRLregisterisdefinedasvolatile,twoseparatecodelineswilltriggerreadingandwritingtheINTCTRLregistertwiceinsteadofonce.Inadditiontomakingthecodeinefficient,thiscanputtheperipheralinanunintendedstate.請(qǐng)注意,盡管這里可能是引誘你將代碼列表3-12中的代碼分裂成兩個(gè)不同的代碼行,其中一行是用來清除該位組,另一行是用來設(shè)定新的值,但是我們不建議這樣做。由于INTCTRL寄存器被定義為volatile(可變的),因此,兩個(gè)不同的代碼行會(huì)觸發(fā)讀寫這個(gè)INTCTRL寄存器兩次而不是一次。此外,還會(huì)使此代碼效率低下,這樣有可能將外圍設(shè)備置于非預(yù)期的狀態(tài)中。Theuseofgroupmaskstoclearbitsisnotalwaysrequired.CodeListing3-13showshowallinterruptlevelsofUSARTC0canbeconfiguredatthesametime.ReceiveComplete,TransmitCompleteandUSARTDataRegisterEmptyinterruptlevelsaresettoMEDIUM,OFFandLOWinterruptlevelsrespectively.并不總是需要用組掩碼清除位的,代碼列表3-13顯示USARTC0的所有中斷級(jí)別是如何可以在同一時(shí)間進(jìn)行配置的。接收完成、發(fā)送完成以及USART數(shù)據(jù)寄存器空中斷級(jí)別分別被設(shè)置為MEDIUM(中等)、OFF(關(guān)閉)以及LOW(低)的中斷優(yōu)先級(jí)。CodeListing3-13.Settingallconfigurationsinaregisteratthesametime.代碼列表3-13.對(duì)一個(gè)寄存器里的所有配置在同一時(shí)間進(jìn)行設(shè)置3.5.1EnumerationofGroupConfigurationmasks3.5.1組配置掩碼的枚舉Unlikebitmasksandgroupmasks,thebitgroupconfigurationmasksaredefinedusingCenumerators.Oneenumeratorisdefinedforeachbitgroup.TheenumeratorfortheUSARTRXCINTLVLbitgroupisshowninCodeListing3-14.不同的位掩碼和組掩碼,其位組配置掩碼是用C語(yǔ)言枚舉符定義的,為每個(gè)位組定義一個(gè)枚舉符。代碼列表3-14給出了用于USARTRXCINTLVL位組的枚舉符。CodeListing3-14.USARTRXCINTLVLenumerator代碼列表3-14.USARTRXCINTLVL的枚舉符AsseeninCodeListing3-14,thenameoftheenumeratorisaconcatenationofthemoduletype(USART),thebitgroup(RXCINTLVL)andasuffix(_t)thatindicatesthatthisisadatatype.代碼列表3-14中可以看出,枚舉符的名字是一連串的(USART)模塊類型,位組(RXCINTLVL)和后綴(_t),表明這是一種數(shù)據(jù)類型。Eachoftheenumeratorconstantsbehavesmuchlikeanormalconstantwhenusedonitsown.However,usinganenumeratorhastheadvantagethatitcreatesanewdatatype.USART_RXCINTLVL_tcanbeusedasatypename,justlikeanintorchar.Anenumeratorconstantcanbeuseddirectlyasinteger,butassigninganintegertoanenumeratortypewilltriggeracompilerwarning.Thiscanbeusedtotheprogrammersadvantage.ImagineafunctionthatsetsthereceivecompleteinterruptlevelforaUSARTmodule.Ifthefunctionacceptstheinterruptlevelasanintegertype(e.g.unsignedchar),anylegalorillegalvaluecanbepassedtothefunction.IfthefunctioninsteadacceptsaparameteroftypeUSART_RXCINTLVL_t,onlythefourpre-definedconstantsintheUSART_RXCINTLVL_tenumeratorcanbepassedtothefunction.Passinganythingelsewillresultinacompilerwarning.每個(gè)枚舉符的常量單獨(dú)使用時(shí),其表現(xiàn)很像是一個(gè)普通的常數(shù)。然而,使用枚舉符的優(yōu)點(diǎn)在于創(chuàng)建一個(gè)新的數(shù)據(jù)類型。USART_RXCINTLVL_t就像是一個(gè)int或char那樣,可以作為一個(gè)類型名使用。一個(gè)枚舉符常數(shù)完全可以作為整數(shù)使用,但是把一個(gè)整數(shù)賦給一個(gè)枚舉符類型,將會(huì)觸發(fā)一個(gè)編譯器警告。這可能是習(xí)慣了程序員的優(yōu)勢(shì)的緣故。試想一個(gè)函數(shù)設(shè)置一個(gè)USART模塊接收完成中斷級(jí)別,如果此函數(shù)接受中斷級(jí)別為整數(shù)類型(如無符號(hào)的字符),那么任何合法的或非法的值都可以傳遞給此函數(shù);如果此函數(shù)改為接受USART_RXCINTLVL_t類型的參數(shù),那么可以傳遞給此函數(shù)的就只有4個(gè)預(yù)先在USART_RXCINTLVL_t枚舉符中定義的常量。除此而外,給此函數(shù)傳遞任何其它參數(shù)都將會(huì)導(dǎo)致編譯器警告。NoticethattheconstantsinCodeListing3-14areshiftedtotheactualbitposition.Thismeansthattheenumeratorcontstantsaretheactualvaluesthatshallbewrittentotheregister.Noadditionalshiftingisneeded.請(qǐng)注意,在代碼列表3-14中的常量被轉(zhuǎn)移到當(dāng)前的位位置,這意味著枚舉符常量就是應(yīng)寫入該寄存器的當(dāng)前值,無需額外的轉(zhuǎn)移。3.6FunctionsCallsandModuleDrivers3.6函數(shù)調(diào)用與模塊驅(qū)動(dòng)程序Whenwritingdriversformoduletypesthathavemultipleinstances,thefactthatallinstanceshavethesameregistermemorymap,canbeutilizedtomakethedriverreusableforallinstancesofthemoduletype.Ifthedrivertakesapointerargument,pointingtotherelevantmoduleinstance,thedrivercanbeusedforallmodulesofthistype.Whenconsideringportabilitythisrepresentsagreatadvantage.在為含有多個(gè)實(shí)例的模塊類型編寫驅(qū)動(dòng)程序時(shí),可以利用所有實(shí)例都具有相同的寄存器內(nèi)存映射這個(gè)事實(shí),來使驅(qū)動(dòng)程序可重復(fù)用于該模塊類型的所有實(shí)例。如果該驅(qū)動(dòng)程序需要一個(gè)指針參數(shù),指向相關(guān)的模塊實(shí)例,那么該驅(qū)動(dòng)程序可用于這種類型的所有模塊。然而,就可移植性而言,這就表現(xiàn)出了具有極大的優(yōu)勢(shì)。Consideradevicewith8Timers/Counters.ThefunctionstoinitializeandaccesstheTimer/Countermodulescanbesharedbyallmoduleinstances.Eventhoughthereisasmalloverheadinpassingthemodulepointertothefunctions,thetotalcodesizewilloftenbereducedbecausethecodeisreusedforallinstancesofeachmoduletype.Evenmoreimportant,developmenttime,maintenancecost,andportabilitycanbegreatlyimprovedbyusingthisapproach.設(shè)想一個(gè)設(shè)備有8個(gè)計(jì)時(shí)器/計(jì)數(shù)器,初始化和訪問這些計(jì)時(shí)器/計(jì)數(shù)器模塊的函數(shù)可以讓所有模塊實(shí)例共享。即使在將模塊指針傳遞給函數(shù)的過程中有較小的開銷,但總的代碼大小往往會(huì)縮小,因?yàn)槊總€(gè)模塊類型的所有實(shí)例代碼是重復(fù)使用的。更重要的是,由于使用這種方法,可以使開發(fā)時(shí)間、維護(hù)成本以及可移植性都得到了極大的改善。CodeListing3-15showsafunctionthatusesamodule-pointertoselectaclocksourceforanyTimer/Countermodule.代碼列表3-15顯示了一個(gè)使用模塊指針的函數(shù)來選擇任何計(jì)時(shí)器/計(jì)數(shù)器模塊的時(shí)鐘源。CodeListing3-15.Examplefunctionusingmoduleinstancepointer代碼列表3-15.以使用模塊實(shí)例指針的函數(shù)為例Thefunctiontakestwoarguments:amodulepointerofthetype,TC_t,andagroupconfigurationtype,TC_CLKSEL_t.ThecodeinthefunctionusestheTimerCountermodulepointertoaccesstheCTRLAregistertosetanewclockselectionfortheTimer/Countermoduleprovidedthroughthetcparameter.該函數(shù)采用了兩個(gè)參數(shù):一個(gè)TC_t類型的模塊指針,和一個(gè)TC_CLKSEL_t類型的組配置。函數(shù)中的代碼使用計(jì)時(shí)器計(jì)數(shù)器模塊指針來訪問CTRLA寄存器,以便設(shè)置新的時(shí)鐘選擇由tc參數(shù)提供的計(jì)時(shí)器/計(jì)數(shù)器模塊。CodeListing3-16showshowthefunctioninCodeListing3-15canbeusedtoconfiguredifferentTimer/Countermoduleswithdifferentclockselections.代碼列表3-16顯示了如何將代碼列表3-15中的函數(shù)用于給各不相同的計(jì)時(shí)器/計(jì)數(shù)器模塊配置各不相同的時(shí)鐘選擇。CodeListing3-16.Callingafunctionthattakesamodulepointerasparameter代碼列表3-16.調(diào)用的函數(shù)將模塊的指針作為參數(shù)4AlternativeWaysofWritingCode4.編寫代碼的替代方式ForconvenienceandtoavoidforcingAVRprogrammingveteranstochangetheirprogrammingstyleitisstillpossibletouseaprogrammingstylethatdoesnotinvolvestructs.ItisalsopossibletousethebitnamestylethatisusedformegaAVR?.Thissectionbrieflydescribesalternativewaysofaccessingr

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論