天天看點

STM32F7xx —— ADC                             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;
}
           

繼續閱讀