翻遍网络罕有STM32F4的HAL库轮训读取ADC的介绍,这里上个代码作为记录
/**
ADC1 init function
*/
void MX_ADC1_Init(void)
{
ADC_ChannelConfTypeDef sConfig;
hadc1.Instance = ADC1;
hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
hadc1.Init.Resolution = ADC_RESOLUTION_12B;
hadc1.Init.ScanConvMode = DISABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.NbrOfDiscConversion = 0;
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.NbrOfConversion = 1;
hadc1.Init.DMAContinuousRequests = DISABLE;
hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
if (HAL_ADC_Init(&hadc1) != HAL_OK) {
_Error_Handler(__FILE__, __LINE__);
}
sConfig.Channel = ADC_CHANNEL_14;
sConfig.Rank = 1;
sConfig.SamplingTime = ADC_SAMPLETIME_56CYCLES;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) {
_Error_Handler(__FILE__, __LINE__);
}
}
/** ADC Msp init function
*/
void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
{
GPIO_InitTypeDef GPIO_InitStruct;
if(adcHandle->Instance==ADC1) {
__HAL_RCC_ADC1_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_4|GPIO_PIN_1|GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
} else if(adcHandle->Instance==ADC2) {
__HAL_RCC_ADC2_CLK_ENABLE();
} else if(adcHandle->Instance==ADC3) {
__HAL_RCC_ADC3_CLK_ENABLE();
}
}
/** ADC Msp deinit function
*/
void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle)
{
if(adcHandle->Instance==ADC1) {
__HAL_RCC_ADC1_CLK_DISABLE();
HAL_GPIO_DeInit(GPIOC, GPIO_PIN_1|GPIO_PIN_4|GPIO_PIN_5);
} else if(adcHandle->Instance==ADC2) {
__HAL_RCC_ADC2_CLK_DISABLE();
} else if(adcHandle->Instance==ADC3) {
__HAL_RCC_ADC3_CLK_DISABLE();
}
}
读取函数代码段
sConfig.Channel = ADC_CHANNEL_x;
sConfig.Rank = 1;
sConfig.SamplingTime = ADC_SAMPLETIME_56CYCLES;
sConfig.Offset = 0;
if(channel == DEV_ADC_CH0) {
hadc = &hadc1;
} else if(channel == DEV_ADC_CH1) {
hadc = &hadc2;
} else if(channel == DEV_ADC_CH2) {
hadc = &hadc3;
}
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) {
_Error_Handler(__FILE__, __LINE__);
}
if(HAL_ADC_Start(hadc) != HAL_OK) {
_Error_Handler(__FILE__, __LINE__);
}
if(HAL_ADC_PollForConversion(hadc, 10) != HAL_OK) {
_Error_Handler(__FILE__, __LINE__);
}
if(HAL_ADC_GetState(hadc) == HAL_ADC_STATE_EOC_REG) {
_Error_Handler(__FILE__, __LINE__);
}
ret = HAL_ADC_GetValue(hadc);
HAL_ADC_Stop(hadc);