stm32f103 adc 查询方式 基于HAL库
时间: 2023-09-25 09:15:42 浏览: 156
下面是使用HAL库进行STM32F103 ADC查询的步骤:
1. 初始化ADC:
```
ADC_HandleTypeDef hadc;
hadc.Instance = ADC1;
hadc.Init.ScanConvMode = DISABLE;
hadc.Init.ContinuousConvMode = DISABLE;
hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc.Init.NbrOfConversion = 1;
HAL_ADC_Init(&hadc);
```
2. 配置ADC通道:
```
ADC_ChannelConfTypeDef sConfig;
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;
HAL_ADC_ConfigChannel(&hadc, &sConfig);
```
3. 启动ADC转换:
```
HAL_ADC_Start(&hadc);
```
4. 等待转换完成:
```
HAL_ADC_PollForConversion(&hadc, 100);
```
5. 读取转换值:
```
uint16_t adc_value = HAL_ADC_GetValue(&hadc);
```
完整代码示例:
```
ADC_HandleTypeDef hadc;
ADC_ChannelConfTypeDef sConfig;
void MX_ADC1_Init(void)
{
hadc.Instance = ADC1;
hadc.Init.ScanConvMode = DISABLE;
hadc.Init.ContinuousConvMode = DISABLE;
hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc.Init.NbrOfConversion = 1;
HAL_ADC_Init(&hadc);
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;
HAL_ADC_ConfigChannel(&hadc, &sConfig);
}
uint16_t adc_read(void)
{
uint16_t adc_value = 0;
HAL_ADC_Start(&hadc);
HAL_ADC_PollForConversion(&hadc, 100);
adc_value = HAL_ADC_GetValue(&hadc);
return adc_value;
}
```
阅读全文