最近的一个项目中,使用了ADC1的ch2/ch3,ADC2的ch4/ch5,共4个通道,要求控制两个ADC分别采集这4路信号,ADC1、ADC2都配置为扫描、非连续、间断,查询方式。
ADC1配置如下:
void MX_ADC1_Init(void)
{hadc1.Instance = ADC1;
hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.DiscontinuousConvMode = ENABLE;
hadc1.Init.NbrOfDiscConversion = 1;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.NbrOfConversion = 2;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
sConfig.Channel = ADC_CHANNEL_2;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
sConfig.Channel = ADC_CHANNEL_3;
sConfig.Rank = ADC_REGULAR_RANK_2;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
}
ADC2配置如下:
void MX_ADC2_Init(void)
{
hadc2.Instance = ADC2;
hadc2.Init.ScanConvMode = ADC_SCAN_ENABLE;
hadc2.Init.ContinuousConvMode = DISABLE;
hadc2.Init.DiscontinuousConvMode = ENABLE;
hadc2.Init.NbrOfDiscConversion = 1;
hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc2.Init.NbrOfConversion = 2;
if (HAL_ADC_Init(&hadc2) != HAL_OK)
{
Error_Handler();
}
sConfig.Channel = ADC_CHANNEL_4;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
{
Error_Handler();
}
sConfig.Channel = ADC_CHANNEL_5;
sConfig.Rank = ADC_REGULAR_RANK_2;
if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
{
Error_Handler();
}
}
在主程序中使用如下代码查询:
if ( adc1_start )
{
uint16_t v2_cur_value = 0;
uint16_t v3_cur_value = 0;
v2_cur_value = ADC1_IN();
if(v2_cur_value < v1_threshold)
GPIOA->BSRR = (uint32_t)GPIO_PIN_11 << 16;
else
GPIOA->BSRR = GPIO_PIN_11;
v3_cur_value = ADC1_IN();
if(v3_cur_value < v2_threshold)
GPIOA->BSRR = (uint32_t)GPIO_PIN_12 << 16;
else
GPIOA->BSRR = GPIO_PIN_12;
HAL_ADC_Stop(&hadc1);
}
if ( adc2_start)
{
uint16_t v3_cur_value = 0;
uint16_t v4_cur_value = 0;
v3_cur_value = ADC2_IN();
if(v3_cur_value < v3_threshold)
GPIOB->BSRR = (uint32_t)GPIO_PIN_3 << 16;
else
GPIOB->BSRR = GPIO_PIN_3;
v4_cur_value = ADC2_IN();
if(v4_cur_value < v4_threshold)
GPIOB->BSRR = (uint32_t)GPIO_PIN_4 << 16;
else
GPIOB->BSRR = GPIO_PIN_4;
HAL_ADC_Stop(&hadc2);
}
ADC1_IN(),ADC2_IN()函数为采集过程,代码如下:
uint16_t ADC1_IN(void)
{
HAL_ADC_Start(&hadc1);
HAL_ADC_PollForConversion(&hadc1,0xffff);
if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))
{
return HAL_ADC_GetValue(&hadc1);
}
return 0;
}
uint16_t ADC2_IN(void)
{
HAL_ADC_Start(&hadc2);
HAL_ADC_PollForConversion(&hadc2,0xffff);
if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc2), HAL_ADC_STATE_REG_EOC))
{
return HAL_ADC_GetValue(&hadc2);
}
return 0;
}
现在的问题是,有时候ADC1的ch3通道采集的信号异常,有时候ADC2的ch5通道采集的信号异常,都为固定电平,而其它三个通道采集的数据正确,百思不得其解,求高手相帮,多谢了!