STM32F7xx —— ADC

                             STM32F7xx —— ADC

 

基础知识参考:ADC   

 

/*****************************************************************************
*          ADC1     ADC2     ADC3
* 通道0    PA0      PA0      PA0
* 通道1    PA1      PA1      PA1
* 通道2    PA2      PA2      PA2
* 通道3    PA3      PA3      PA3
* 通道4    PA4      PA4      PF6
* 通道5    PA5      PA5      PF7
* 通道6    PA6      PA6      PF8
* 通道7    PA7      PA7      PF9
* 通道8    PB0      PB0      PF10
* 通道9    PB1      PB1      PF3
* 通道10   PC0      PC0      PC0
* 通道11   PC1      PC1      PC1
* 通道12   PC2      PC2      PC2
* 通道13   PC3      PC3      PC3
* 通道14   PC4      PC4      PF4
* 通道15   PC5      PC5      PF5
* 通道18   温度传感器
*****************************************************************************/
static ADC_HandleTypeDef adc_handle;

static void adc_gpio_init(void)
{

}

static void adc_mode_init(void)
{
  __HAL_RCC_ADC1_CLK_ENABLE();
  adc_handle.Instance = ADC1;
  adc_handle.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
  adc_handle.Init.Resolution = ADC_RESOLUTION_12B; //12 位模式
  adc_handle.Init.DataAlign = ADC_DATAALIGN_RIGHT; //右对齐
  adc_handle.Init.ScanConvMode = DISABLE; //非扫描模式
  adc_handle.Init.EOCSelection = DISABLE; //关闭 EOC 中断
  adc_handle.Init.ContinuousConvMode = DISABLE; //关闭连续转换
  adc_handle.Init.NbrOfConversion = 1;
  adc_handle.Init.DiscontinuousConvMode = DISABLE; //禁止不连续采样模式
  adc_handle.Init.NbrOfDiscConversion = 0; //不连续采样通道数为 0
  adc_handle.Init.ExternalTrigConv = ADC_SOFTWARE_START; //软件触发
  adc_handle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; //使用软件触发
  adc_handle.Init.DMAContinuousRequests = DISABLE; //关闭 DMA 请求
  HAL_ADC_Init(&adc_handle);
}

void ADCInit(void)
{
  adc_gpio_init();
  adc_mode_init();
}

uint16_t ADCGet(uint32_t channel)
{
  ADC_ChannelConfTypeDef adc_config;

  adc_config.Channel = channel;
  adc_config.Rank = 1;
  adc_config.SamplingTime = ADC_SAMPLETIME_480CYCLES;
  adc_config.Offset = 0;

  HAL_ADC_ConfigChannel(&adc_handle, &adc_config);
  HAL_ADC_Start(&adc_handle);
  HAL_ADC_PollForConversion(&adc_handle, 10); //轮询转换

  return (uint16_t)HAL_ADC_GetValue(&adc_handle);
}

float ADCAverageGet(uint32_t channel, uint16_t times)
{
  float temp;
  uint32_t value = 0, average;
  uint16_t i;

  for(i = 0; i < times; ++i)
  {
    value += ADCGet(channel);
  }

  average = value / times;

  temp = (float)average * (3.3 / 4096);

  return temp;
}

// T = ((Vsense - V25) / avg_slope) + 25;
// V25:Vsense在25°时的数值(0.76)
// avg_slope:温度与Vsense曲线的平均斜率(2.5mV/度)
float ADCSocInnerTemperature(void)
{
  float temperature;

  temperature = ADCAverageGet(ADC_CHANNEL_TEMPSENSOR, 10);

  temperature = (temperature - 0.76f) * 400 + 25;

  printf("%f\r\n", temperature);

  return temperature;
}

 

 

 

 

你可能感兴趣的:(STM32F7xx)