本文根据et’s Do!STM32WBA55无线MCU开发大作战活动要求,实现STM32WBA55ADC采集电池电压
一、ADC输入引脚确认
选择ADC4 CHANNEL2 对应PA7
二、STM32CuteMX配置
ADC4,选择IN2(通道2)
对应生成的代码:
hadc4.Instance = ADC4; hadc4.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV4; hadc4.Init.Resolution = ADC_RESOLUTION_12B; hadc4.Init.DataAlign = ADC_DATAALIGN_RIGHT; hadc4.Init.ScanConvMode = ADC_SCAN_DISABLE; hadc4.Init.EOCSelection = ADC_EOC_SINGLE_CONV; hadc4.Init.LowPowerAutoPowerOff = DISABLE; hadc4.Init.LowPowerAutonomousDPD = ADC_LP_AUTONOMOUS_DPD_DISABLE; hadc4.Init.LowPowerAutoWait = DISABLE; hadc4.Init.ContinuousConvMode = DISABLE; hadc4.Init.NbrOfConversion = 1; hadc4.Init.ExternalTrigConv = ADC_SOFTWARE_START; hadc4.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; hadc4.Init.DMAContinuousRequests = DISABLE; hadc4.Init.TriggerFrequencyMode = ADC_TRIGGER_FREQ_LOW; hadc4.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN; hadc4.Init.SamplingTimeCommon1 = ADC_SAMPLETIME_79CYCLES_5; hadc4.Init.SamplingTimeCommon2 = ADC_SAMPLETIME_79CYCLES_5; hadc4.Init.OversamplingMode = ENABLE; hadc4.Init.Oversampling.Ratio = ADC_OVERSAMPLING_RATIO_16; hadc4.Init.Oversampling.RightBitShift = ADC_RIGHTBITSHIFT_4; hadc4.Init.Oversampling.TriggeredMode = ADC_TRIGGEREDMODE_SINGLE_TRIGGER; if (HAL_ADC_Init(&hadc4) != HAL_OK) { Error_Handler(); } /** Configure Regular Channel */ sConfig.Channel = ADC_CHANNEL_2; sConfig.Rank = ADC_REGULAR_RANK_1; sConfig.SamplingTime = ADC_SAMPLINGTIME_COMMON_1; if (HAL_ADC_ConfigChannel(&hadc4, &sConfig) != HAL_OK) { Error_Handler(); }
hadc4.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV4;:设置ADC时钟预分频器为异步时钟除以4。这意味着ADC的时钟频率是异步时钟频率的四分之一。
hadc4.Init.Resolution = ADC_RESOLUTION_12B;:设置ADC分辨率为12位。这意味着ADC可以转换的最大值为4095(2^12 - 1)。
hadc4.Init.SamplingTimeCommon1 = ADC_SAMPLETIME_79CYCLES_5; 和 hadc4.Init.SamplingTimeCommon2 = ADC_SAMPLETIME_79CYCLES_5;:设置通道组的采样时间为79.5个ADC时钟周期。
hadc4.Init.OversamplingMode = ENABLE;:启用过采样模式。
hadc4.Init.Oversampling.Ratio = ADC_OVERSAMPLING_RATIO_16;:设置过采样比为16。这意味着将进行16次转换并平均以提高分辨率。
hadc4.Init.Oversampling.RightBitShift = ADC_RIGHTBITSHIFT_4;:设置右移位数为4。这用于在平均后调整结果的位置。
hadc4.Init.Oversampling.TriggeredMode = ADC_TRIGGEREDMODE_SINGLE_TRIGGER;:设置过采样触发模式为单次触发。
三、程序
1、main()中启动ADC校准
/* Perform ADC calibration */ if (HAL_ADCEx_Calibration_Start(&hadc4) != HAL_OK) { /* Calibration Error */ Error_Handler(); }
2、while(1)
while (1) { if (HAL_ADC_Start(&hadc4) != HAL_OK) { /* ADC conversion start error */ Error_Handler(); } /* Wait for ADC conversion completed */ if (HAL_ADC_PollForConversion(&hadc4, 10) != HAL_OK) { /* End Of Conversion flag not set on time */ Error_Handler(); } uhADCxConvertedData = HAL_ADC_GetValue(&hadc4); voltage=uhADCxConvertedData*3.3/4096; printf("PA7 ADC Voltage:%0.2fv\r\n",voltage); HAL_Delay(1000); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ }
HAL_ADC_Start:启动ADC采样
HAL_ADC_PollForConversion:等待采样完成
uhADCxConvertedData = HAL_ADC_GetValue(&hadc4);获得采样值
采样结果换算成电压:
voltage=uhADCxConvertedData*3.3/4096;
四、运行效果