借助STM32L452内部的ADC,再配置一个OLED屏就可形成一个简单的数字电压表,其显示效果如图1至图3所示。
A/D采集所使用的通道为ADC_CHANNEL_9,占用的引脚为PA4。
图1 悬空状态下的采集值
图2 连接GND的测量值
图3 连接VDD的测量值
实现该显示效果的主程序为:
int main(void)
{
HAL_Init();
SystemClock_Config();
BSP_LED_Init(LED2);
AdcHandle.Instance = ADCx;
if (HAL_ADC_DeInit(&AdcHandle) != HAL_OK)
{
Error_Handler();
}
AdcHandle.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;
AdcHandle.Init.Resolution = ADC_RESOLUTION_12B;
AdcHandle.Init.DataAlign = ADC_DATAALIGN_RIGHT;
AdcHandle.Init.ScanConvMode = DISABLE;
AdcHandle.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
AdcHandle.Init.LowPowerAutoWait = DISABLE;
AdcHandle.Init.ContinuousConvMode = ENABLE;
AdcHandle.Init.NbrOfConversion = 1;
AdcHandle.Init.DiscontinuousConvMode = DISABLE;
AdcHandle.Init.NbrOfDiscConversion = 1;
AdcHandle.Init.ExternalTrigConv = ADC_SOFTWARE_START;
AdcHandle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
AdcHandle.Init.DMAContinuousRequests = DISABLE;
AdcHandle.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;
AdcHandle.Init.OversamplingMode = ENABLE;
AdcHandle.Init.Oversampling.Ratio = OVERSAMPLING_RATIO;
AdcHandle.Init.Oversampling.RightBitShift = RIGHTBITSHIFT;
AdcHandle.Init.Oversampling.TriggeredMode = TRIGGEREDMODE;
AdcHandle.Init.Oversampling.OversamplingStopReset = OVERSAMPLINGSTOPRESET;
if (HAL_ADC_Init(&AdcHandle) != HAL_OK)
{
Error_Handler();
}
if (HAL_ADCEx_Calibration_Start(&AdcHandle, ADC_SINGLE_ENDED) != HAL_OK)
{
Error_Handler();
}
sConfig.Channel = ADCx_CHANNEL;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_6CYCLES_5;
sConfig.SingleDiff = ADC_SINGLE_ENDED;
sConfig.OffsetNumber = ADC_OFFSET_NONE;
sConfig.Offset = 0;
if (HAL_ADC_ConfigChannel(&AdcHandle, &sConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_ADC_Start(&AdcHandle) != HAL_OK)
{
Error_Handler();
}
APP_OLED_Init();
OLED_Init();
OLED_Clear();
OLED_ShowString(8,0,"STM32L452RE",16);
OLED_ShowString(8,2,"OLED & ADC ",16);
OLED_ShowCHinese(80,0,0);
OLED_ShowCHinese(96,0,1);
OLED_ShowCHinese(112,0,2);
OLED_ShowString(60,6,"mV",16);
while (1)
{
if (HAL_ADC_PollForConversion(&AdcHandle, 10) != HAL_OK)
{
Error_Handler();
}
uwConvertedValue = HAL_ADC_GetValue(&AdcHandle);
OLED_ShowNum(10,4,uwConvertedValue,6,16);
uwInputVoltage = uwConvertedValue * 3300;
uwInputVoltage = uwInputVoltage / 0xFFF0;
OLED_ShowNum(10,6,uwInputVoltage,5,16);
HAL_Delay(500);
}
}
引用: freebsder 发表于 2021-1-6 21:46 谢谢分享!