天天看点

STM32—ADC单通道采集模拟量前言:ADC配置过程:

前言:

最近在调试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函数即可。

继续阅读