stm32ADC多通道采樣例程HAL庫_第1頁
stm32ADC多通道采樣例程HAL庫_第2頁
stm32ADC多通道采樣例程HAL庫_第3頁
stm32ADC多通道采樣例程HAL庫_第4頁
stm32ADC多通道采樣例程HAL庫_第5頁
已閱讀5頁,還剩9頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡(jiǎn)介

Stm32基于HAL庫ADC多通道采樣例程1、用cubemx建立工程,cubemx5.3.0版本,芯片型號(hào):stm32f103zet6(1)開啟外部高速時(shí)鐘HSE,配置系統(tǒng)時(shí)鐘為72MSystemCareRCCModeandConfiguration□MAGPIOIWDGConfiguration「.F釀rMH(H呻1fMdNWT40<M*E岬SystemCareRCCModeandConfiguration□MAGPIOIWDGConfiguration「.F釀rMH(H呻1fMdNWT40<M*E岬ElrircKm<W1c]FkFdTFCLM|iiH4ClKtRhiFCLKnw熱小玷%|UHE注意:ADC1時(shí)鐘配置為9MHz(2)配置串口1,設(shè)置好波特率并開啟串口中斷USART1ModeandConfiguraliDnCategoriesA->IModeAnalogModeAsynchroncusHardwareFlowControl(RS232)DisableTimersConnectivity▼oModeAsynchronous.AnalogHaid^ait-owCentral(RS232:-DisableTimersConfigurationResetConfigurationUSART11152D0Hitse8Bits(includingParity)None1CategoriesA->IModeAnalogModeAsynchroncusHardwareFlowControl(RS232)DisableTimersConnectivity▼oModeAsynchronous.AnalogHaid^ait-owCentral(RS232:-DisableTimersConfigurationResetConfigurationUSART11152D0Hitse8Bits(includingParity)None1ReceiveandT^nsmir1SSamples?IWICSettings?DMASet-tings ?CTIDSo:trgsQParameterSailings?UserConstantsConfigurethebelowparameters:□ART』UART5USART2USART3WordLengthvAdvancedParameters□alaDirectionOverSamplingConnect^/vCANHSP/1CI2C1SDIOSPI1SPI2SPI3UART4UARTSUSART1USART2USART3USBCanfigurationResetConfigurationSNVICSettings?DMASettingsCANHSP/1CI2C1SDIOSPI1SPI2SPI3UART4UARTSUSART1USART2USART3USBCanfigurationResetConfigurationSNVICSettings?DMASettings?GPIOSettings?ParameterSettingsNVICInterruptTabeUSART1globalmternjpitPreemptionPriorit/?Ua甘「Constaint號(hào)SubPriority2、啟用ADC1通道1,3,4,5,6注意要先設(shè)置好通道數(shù)量才能配置,各自ADC通道的參數(shù)。Rank是轉(zhuǎn)換順序,我們按1,2,3,4,5的順序分別對(duì)應(yīng)ADC1通道0,1,4,5,6。多通道采樣要開啟掃描工作模式,在這里我們還有開啟連續(xù)轉(zhuǎn)換方式,連續(xù)轉(zhuǎn)換是在ADC轉(zhuǎn)換按照

約定的轉(zhuǎn)換順序全部通道完成一次轉(zhuǎn)換后,又自動(dòng)啟動(dòng)下一次轉(zhuǎn)換。ADC1ModeandConfi-gurationQINOQIN1□IN2□IN3QIN4□IN5QIN6□IN7C.onfigiura.tianResetConfiguration?ParameterSettings?UserConstants??ParameterSettings?UserConstants?NVICSettings?DMASettings?GPIOSeltingsConfigurethebelowparameters:Search(Cft.+FlDataAlignmentRightalignment數(shù)據(jù)右對(duì)齊ScanConversionModeEnabled便能掃描模式ContinuousConversionMedeEnabled使能連緬獺模式DiscontinuousConversionModeDisabledR0gular_Conv0rsionModgEnableRegularC&nversionsEnable使育羸換國首規(guī)則NumberOfComersicn5^WADC涉為5ExternalTriggerConversionSourceRegularConversionlaunchedbysoftwareADCy Rank1轉(zhuǎn)換順序1ChannelChannel0ffiioSamplingTine239.6Cycles栗祥時(shí)間7 Rank2ChannelChannel1通道1SamplingTine239.5Cycles> Rank> Rank3 ,余下通道按順序配置> Rank5>ADC_njected_ConversionMode3、啟用ADC轉(zhuǎn)換DMA傳輸,多通道轉(zhuǎn)換時(shí)要啟用ADC的DMA傳輸,才能在相應(yīng)的通道轉(zhuǎn)換完成后,DMA自動(dòng)去獲取轉(zhuǎn)換值。中斷方式?jīng)]法在多通道采樣時(shí)使用,因?yàn)樵诙嗤ǖ罀呙枘J较?,只有在最后一個(gè)通道轉(zhuǎn)換結(jié)束時(shí)才會(huì)產(chǎn)生中斷請(qǐng)求。而ADC數(shù)據(jù)寄存器是共用的,這時(shí)候進(jìn)入中斷取值只能得到一個(gè)通道的數(shù)值。

DataWidthMemoryI~IIHIT門ADC1DMA1Channel1PeripheralTdMemoryLow■■DMARequestSettingsPeripheralModeIncrementAddress□Circular7HalfWt>rd▼HalfWord”DataWidthMemoryI~IIHIT門ADC1DMA1Channel1PeripheralTdMemoryLow■■DMARequestSettingsPeripheralModeIncrementAddress□Circular7HalfWt>rd▼HalfWord”ConfigurationResetConfi3Lrator□MARequestDeleteDirection?ParameterS&ttiigs*Use,Corstan:s■NVICSettings?DMASettings?CPIC1EiettncsChanrel4、到此,基礎(chǔ)配置和ADC通道配置已經(jīng)完成,接著我們?cè)O(shè)置工程名稱和保存路徑等就可以了,一般工程名和保存路徑最好不要有中文,不然可能會(huì)出現(xiàn)一些意想不到的問題,在測(cè)試的過程中就遇到工程名或者保存路徑中都用英文但是詞組名稱之間用空格隔開,在打開生成的工程文件后,向新建的分類文件夾中添加自己寫的xxx.c文件,就導(dǎo)致keil軟件卡死,不知道是keil軟件還是cubemx的問題。-ProjectSettingsProjectNameFiveChannelsVoltageSaEplingProjectLtxalionC:\Users^senty\Desktop^jcubemx^adcSamplingC:\Us9ns^s□nty\Desktopk:ubenriiX:\a.dcSamplingVFh/eChanneIsVoltageSamplinglToDl^hainFdd臺(tái)「LacationApplicationStructureTookhain/-ProjectSettingsProjectNameFiveChannelsVoltageSaEplingProjectLtxalionC:\Users^senty\Desktop^jcubemx^adcSamplingC:\Us9ns^s□nty\Desktopk:ubenriiX:\a.dcSamplingVFh/eChanneIsVoltageSamplinglToDl^hainFdd臺(tái)「LacationApplicationStructureTookhain/IDEMinVersion□GeneraleL□DonotgeneratethemainQMDK-ARMI yV5.27BasicPpjectCodeG白血「式?!?STM32CuteMCUpackagesandembeddedsoftwarepacks OCopyallusedlibrariesintotheprojRttfolderProjectCodeGenegE「(*)CnpyrnlytheProjectCodeGenegE「OAddnecessarylibraryfilesasreferenceinthetoolchainprojectccnfigurationfileGeneratedfiles SGenerateperipheralinitializationas日pairof".€:/.h'filesperperipheral□Backuppreviouslygeneratedfileswhenre-generatingS&叩UserCodewhenre-generatingDeletepreviouslygeneratedfileswhennotre-generated5、設(shè)置好工程名稱和路徑后就可以生成代碼了,生成代碼后我們選擇打開工程。?國CodeGeneration XThsCode/successfullygen@rat@dunderCrs/senty/Desktop/cubemx/adcSampling/FrvsChanneVoItageSamplingOpenFoldsrIOpenProjectIClose接著我們開始編寫代碼(1)首先我們要修改main函數(shù)的一個(gè)錯(cuò)誤,就是在初始化時(shí)要把MX_DMA_Init()函數(shù)放在MX_ADC1_Init()函數(shù)之前執(zhí)行,cubemx生成代碼時(shí)MX_DMA_Init()是在ADC初始化函數(shù)之后。如果在后面則轉(zhuǎn)換時(shí)打印輸出的ADC值,大多數(shù)都為0,具體原因就不知道是怎么回事了,應(yīng)該是cubemx這個(gè)版本還不太穩(wěn)定。接下來我們?cè)趗sart.c文件中增加一些代碼1)增加printf重定向到串口的代碼,并定義一個(gè)串口接收到數(shù)據(jù)的標(biāo)志變量和數(shù)據(jù)緩沖數(shù)組。作用是在我們用串口調(diào)試助手給單片機(jī)發(fā)送數(shù)據(jù)時(shí)才打印輸出ADC數(shù)據(jù)。uint8_tRecFlag,RxBuf[512];

21222324252€27221222324252€272329SO3132333435363738394041f'USERCODE3EGIN07#in.cl-jde"st-dio.#in.cl'ade"atrinc.tinuin.t8_tRecFlag,RxBaf[512];〃〃堂定向C庫函數(shù)8i^tfg.USARTxstruct_FILE"標(biāo)準(zhǔn)庫需要的支持函數(shù)EHinthandle;intfputcflntch,FILE-fJ早]while(2115工七1.工11日仁311仁已-:>酬&0乂40)^口):,/循環(huán)發(fā)送,直到發(fā)送完畢ri'jaitJ..Instance->DR=(nint3_t}cn;refarnfcri);/':USERCODEEND0〃【代碼】:////重定向c庫函數(shù)printf到USARTxstruct__FILE//標(biāo)準(zhǔn)庫需要的支持函數(shù){inthandle;};intfputc(intch,FILE*f){while((huart1.Instance->SR&0X40)==0);//循環(huán)發(fā)送,直到發(fā)送完畢huart1.Instance->DR=(uint8_t)ch;return(ch);}2)編寫串口數(shù)據(jù)接收函數(shù)voidMy_UsartDateRec(UART_HandleTypeDef*huart),這里就不在回調(diào)函數(shù)中編寫了,然后stm32f1xx_it.c文件中的串口中斷函數(shù)中調(diào)用這個(gè)函數(shù)來接收串口數(shù)據(jù)。此外我們還需要在串口初始化函數(shù)voidHAL_UART_MspInit(UART_HandleTypeDef*uartHandle)中,增力口使能串口接收中斷和空閑中斷。__HAL_UART_ENABLE_IT(&huart1,UART_IT_RXNE);//使能接收中斷__HAL_UART_ENABLE_IT(&huart1,UART_IT_IDLE);〃使能空閑中斷

E5tt5r7tS69707.L727373757tE5tt5r7tS69707.L727373757t777375803.L乳S3B4853t378339SQ91929354359t973三95日{GFID_InitTypeDefSPIO_I^itStract={j?;日{if^uartHandle—:>Instance==USARTl)□!/*USERCODE3EGZNUSARTl_M5pInit/*USERCODEEIJDUSAKTl_MEpInlt0*7/、USART1clackenable*/_HAL_RCC_USART2_CLZ_EETAELE();HALRCC_GFIOA_CLK_ENABLE\;IE] 7^*USART1-GFIOConfigurationPA3 :>USART1_TXPA10 >USART1RX-*/一GPIQ_I^itStruct.Pin=&PID_PIN_S;GPID^I^itStrj.ct.Mode=GPZO_MDDE_AF_PP;SPIO^I^itStr-JCt.Speed=3PID_5FEED_FREQ_HZS?i;HAL_GFIC_Init(GPIOAf£G-PIO_InitStract);GPIO_Initserver.Fin=&PID_PIM_1Q;GPIO_InitStrJ.ct.Mode=GPIO_M0DE_INPUT;GPIo2lTiitSCrj.ct.Pull=GPIO^NOPUKL;HM._GFI0_l7Lit(GPIO-A,£&PID_InitSt:rJGb);汴U5ART1inteiiapt二3it7HAL_NVIC_SetPriority(USART1_IRQnf二.二斗;HAL2NVIC2E^ableIRQ(USART1_IRQnJ;/*USERCODE三EGHHUSART1Msplnit1'/__HAL_HART_ERAELE_工T(.hua^ta;UART_工R_RXNEjT 史音,理夜甲肝二HALluART二ENABLe]工T(ihaarZlrUART二工T二工DLE1:'/便肓苣空閑中斷1001Q1■Lm1過1001Q1130131130131132133134135A13613713B1391^0141」1^2IL里31仃1^5146!■€7JLTB//EntH_CC£B,E=OJstar1cunsignedintnum;"接收計(jì)裁/*USEftCODEEEGLUT1*/voidMJ/JSdILDiteElec(BARIBdDdLleT^-tEtef*hUd£cF門登詢是否發(fā)生了空閑中斷ifIHALUC&KTSETFLAS(kuaitHDARTETJidrIDLEJ!-E£5ET££H1LHARTSETITSCCTRCE|huaztrUAETITIDLE)!-RESET]ReoF二卻=二門收到數(shù)Wnum=C';_HAL_UAP.T_CLEAP._rDLEFLAG(nuarrJ:門滑降空閑中斷elseIT|&LB.LUBcRTSETIT5DCJRCE(Jiu.ar-ErUAET_IT_RKNT>!?旺3口卜『了幀傳輪未完成;接字節(jié)接收if(mm<5izea.f(RkBll£)jJ?1'港沖區(qū)未;芮]U:Eur|nKnL+*]=(uintac|sftiuarc->liL3T;arice->Dn)jelse打鍵沖區(qū)溢出_,CETHp=nuari:->Instance->ER;HAZQAHTCLEARFTA&(huazt,UART_FLfijG_RM:EfE|>;150L>151/*口非KCODEEm17152記得在stm32f1xx_it.c文件開始部分包含usart.h頭文件。

29 /*USSRCOD:EENDHeadei2021 /*Incl'ades 22#incl'ade^main.hn23#incl-aderrstm3211xx_it.24 /*Piivateincl'iides 25八USSRCOD:EBEGINIzicl-ades72€#incl'ade"'ma工七.三開27 /*USSRCOD:EENDIncl-Jdes黃/22522022122222322422522€22522022122222322422522€22722322-9236/*USERCODE3EGINUSARTlIRQnQ*//*USERCODEENDUSARTl_IRQnQ*/HAI._UART_IRQHandler(S:riaartl);/*UBE及UCEiE三EG工M口5或11工£Ori1*/My_UsartD3t&Rec;^^^^^SEm55T3E^!Tn^W!EI^^^n!Si17/*USERCODEBEGIN1*■'/【代碼】:voidMy_UsartDateRec(UART_HandleTypeDef*huart){//uint8_ttemp=0;staticunsignedintnum;//接收計(jì)數(shù)//查詢是否發(fā)生了空閑中斷if(__HAL_UART_GET_FLAG(huart,UART_FLAG_IDLE)!=RESET&&__HAL_UART_GET_IT_SOURCE(huart,UART_IT_IDLE)!=RESET){RecFlag=1;//收到數(shù)據(jù)num=0;_HAL_UART_CLEAR_IDLEFLAG(huart);//清除空閑中斷}elseif(_HAL_UART_GET_IT_SOURCE(huart,UART_IT_RXNE)!=RESET)//幀傳輸未完成,按字節(jié)接收{(diào)if(num<sizeof(RxBuf))//緩沖區(qū)未滿RxBuf[num++]=(uint8_t)(huart->Instance->DR);// else//緩沖區(qū)溢出// temp=huart->Instance->DR;__HAL_UART_CLEAR_FLAG(huart,UART_FLAG_RXNE);}}(2)在adc.c文件中增加代碼

1)定義采樣次數(shù)和通道數(shù)量,ADC數(shù)據(jù)保存數(shù)組2021222320212223242S262723293。3132333435363丁#include"adc.?1rl/*USERCODE3EGIMQ*/|includenstring.h"^defi^eM23”采樣次數(shù)^defi^eKS”通道數(shù)EJ#ifK>_volatileJiin七工E_tNDCJJal/]H];〃多個(gè)通道定義成數(shù)組^FelsejintlttADCValje;^endifGet;ADCtiir.es=2QfdiannelHums;//采樣次數(shù)和通道數(shù)volatile ADC_Val3uf[LQC]={Q?;//1QQ=2Q--5ADC_VaLB^f/£USERCODEENDQ*/【代碼】:#include"adc.h"/*USERCODEBEGIN0*/#include"string.h"defineM20//采樣次數(shù)defineN5//通道數(shù)ifN>1volatileuint16_tADC_Value[N];//多個(gè)通道定義成數(shù)組#elseuint16_tADC_Value;#endif//uint8_tGetADCtimes=20,ChannelNums;//采樣次數(shù)和通道數(shù)volatileuint16_tADC_ValBuf[100]={0};//100=20*5ADC_ValBuf/*USERCODEEND0*/ADC_HandleTypeDefhadc1;DMA_HandleTypeDefhdma_adc1;2)編寫ADC計(jì)算平均值函數(shù)voidGet_ADC_AverageValue(void),并在adc.h中聲明。

1811321831811321831341351861ST13313919019119219315419519€1971981992GG2Q12Q22G32042Q5"多通道按順序循環(huán)轉(zhuǎn)換,皿二值也按順序存放在ADJVml峰數(shù)組中"voidGetADCAverageVaIue(void}{ _ _lJint32_tsun[N;={j>;aintl6tifj;for//for(j=0;j工;j++)5uiu[j]+=ABC_ValBjf[i-W+j];“獲取各個(gè)通道AD匚值總和for(i=j;i<N;i44)ADC_Val.ie[ ■計(jì)算平均值#elsevoidGetADCAvexdgeValae(void){——aint32_tsum;alnt16ti;for(i=^;i<M;i44)suir.+=ADC_Va13af[i];ADC_Valae=suiiL/N;//計(jì)算平均值L#endif/*'USERCODEEMD1*7【代碼】:/*USERCODEBEGIN1*/#ifN>1/*多通道按順序循環(huán)轉(zhuǎn)換,ADC值也按順序存放在ADC_Value數(shù)組中*/voidGet_ADC_AverageValue(void){uint32_tsum[N]={0};uint16_ti,j;for(i=0;i<M;i++) //sum[0]對(duì)應(yīng)通道0,sum[1]對(duì)應(yīng)通道1for(j=0;j<N;j++)sum[j]+=ADC_ValBuf[i*N+j];//獲取各個(gè)通道ADC值總和for(i=0;i<N;i++)ADC_Value[i]=sum[i]/M;//計(jì)算平均值}#elsevoidGet_ADC_AverageValue(void){uint32_tsum;uint16_ti;for(i=0;i<M;i++)sum+=ADC_ValBuf[i];ADC_Value=sum/N;//計(jì)算平均值#endif/*USERCODEEND1*/(3)最后我們就可以編寫main函數(shù)了Length變量是數(shù)據(jù)的個(gè)數(shù),所以直接通過sizeof(ADC_ValBuf)/2來計(jì)算得出。首先,我們要在main函數(shù)開頭的初始化部分調(diào)用ADCDMA啟動(dòng)函數(shù),HAL_ADC_Start_DMA()函數(shù)中HAL_ADC_Start_DMA(&hadc1,(uint32_t*)&ADC_ValBuf,sizeof(ADC_ValBuf)/2);gg100101102Initzalxzsallconfigoiedp=riph=rals百,MX_GPIC_IniL():MX二;!£X"ADCl_Init();I€K_U5JIRTl_nART_In1r(>://id£_DH?t_Iniit(7;八USERCODEBEGIS2*/HALADCStartCHl(;badc_,iuLnz32t^};ALCVa:LBu:f,m二zcof:AD「ValBuf^2);/DM1/?USERCODEE5IDZ"接著我們編寫while循環(huán)中的函數(shù)。103工口鼻105Z016~1/士Infiniteloop7/'U5ERCODEBE3IETWHILE*/while|1|10710810911011111211311411511€117113119120121122123124125-]12612712S129130131132133134135136137-138-139140141/*,USER3ODEZNDWHILEV/*'USERCODEBEGIN3*/if《RuuFLug--!.}EecFlai^O;Get_ADC_AverageValue();for(i=D7i<sizeof(ADCValBuf卜/2:T++]if茲葭易-An]打印出每個(gè)通道”次采樣的豫值prinEi(rr^d,"'fadcvaiBur[1]);printf(;r:+算平均數(shù)后各通道的山口二信為二n:fox(i=3;i<5;SWl匚二」1)“打印出計(jì)笄平均數(shù)后每個(gè)通道的AEcttcase0:printf(nADClChannel0Value:%d\n,T,ADC_Value[i]Mbreak;1:r-rintf(TIADCLCTianneL1;二m"1r入DCVa1二耳]:[卜;casecasebreak?Z;printfbreak?3:printfbreak;4:printfbreak?C"ADC_(nADCl(r,ADClChannelChannelCbamnelYal-jc; AEC¥a1上亡[:]卜;Value: ADCValue[i]|;Value: 1T.ADCValue[i]?;/*USERCODEEND3*/【代碼】:while(1){/*USERCODEENDWHILE*//*USERCODEBEGIN3*/if(RecFlag==1){RecFlag=0;Get_ADC_AverageValue();for(i=0;i<sizeof(ADC_ValBuf)/2;i++){if(i>4&&i%5==0)printf("\n");//打印出每個(gè)通道20次采樣的數(shù)值printf("%d",ADC_ValBuf[i]);}printf("\n\n");printf("計(jì)算平均數(shù)后各通道的ADC值為:\n");for(i=0;i<5;i++){switch(i)//打印出計(jì)算平均數(shù)后每個(gè)通道的ADC值{case0:printf("ADC1Channel0Value:%d\n",ADC_Value[i]);break;case1:printf("ADC1Channel1Value:%d\n",ADC_Value[i]);break;case2:printf("ADC1Channel4Value:%d\n",ADC_Value[i]);break;case3:printf("AD

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(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)論