STM32—ADC單通道採集模擬量
阿新 • • 發佈:2019-02-10
前言:
最近在除錯STM32L152晶片ADC單通道採集資料程式,總結下STM32L152晶片ADC單通道採集模擬量的使用方法。
硬體平臺:STM32L152
軟體平臺:keil v5+cubeMX
函式庫:HAL庫
ADC配置過程:
1.先初始化ADC的管腳,本例中ADC對應PA1管腳。
ADC_HandleTypeDef hadc; void ADC_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; /*Configure GPIO pin : PA1 */ GPIO_InitStructure.Pin = GPIO_PIN_1; GPIO_InitStructure.Mode = GPIO_MODE_ANALOG; GPIO_InitStructure.Pull = GPIO_NOPULL; HAL_GPIO_Init(ADC1_GPIO, &GPIO_InitStructure); }
2.初始化ADC的各引數
void MX_ADC_Init(void) { ADC_ChannelConfTypeDef sConfig; /**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) */ hadc.Instance = ADC1; hadc.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;//時鐘分頻 hadc.Init.Resolution = ADC_RESOLUTION_12B;//ADC的解析度 hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;//右對齊,低12有效 hadc.Init.ScanConvMode = ADC_SCAN_DISABLE;//關閉瀏覽模式,即單通道有效 hadc.Init.EOCSelection = ADC_EOC_SEQ_CONV; hadc.Init.LowPowerAutoWait = ADC_AUTOWAIT_DISABLE; hadc.Init.LowPowerAutoPowerOff = ADC_AUTOPOWEROFF_DISABLE; hadc.Init.ChannelsBank = ADC_CHANNELS_BANK_A; hadc.Init.ContinuousConvMode = DISABLE; //單次轉化模式 hadc.Init.NbrOfConversion = 1;//通道數量 hadc.Init.DiscontinuousConvMode = DISABLE; hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START;// 軟體觸發 hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; hadc.Init.DMAContinuousRequests = DISABLE; if (HAL_ADC_Init(&hadc) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /**Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. */ sConfig.Channel = ADC1_Channel; sConfig.Rank = 1; sConfig.SamplingTime = ADC_SAMPLETIME_4CYCLES; if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } }
3.獲取ADC採集資料
u16 ADC_ReadData(void)
{
static u16 AD_Data;
HAL_ADC_Start(&hadc);
HAL_ADC_PollForConversion(&hadc,100);
AD_Data=(u16)HAL_ADC_GetValue(&hadc);
HAL_ADC_Stop(&hadc);
delay_ms(5);
return AD_Data;
}
4.獲取採集資料進行平均
u16 ADC_average(u8 times) { u32 sum=0,i,adc_average; for(i=0;i<times;i++) { sum+=ADC_ReadData(); } adc_average=sum/times; return adc_average; }
需要獲取ADC資料時直接呼叫ADC_average函式即可。