STM32 LL库踩坑系列三(ADC测电压或外部温度传感器)
这个作者很懒,想到什么就写什么!
写在前面:这个是记录学习LL库的踩坑系列,这个资料很少,想要找例程可以在电脑用户文件下的STM32Cube\Repository里,前提是下载好那个单片机的pack,部分没有例程的可以借鉴同系列的文件。
本次使用DMA读取2个GPIO口的脚的ADC采集值。使用cubemx配置如下
采样的时钟频率一般情况下不宜太小或者太大,对应实际硬件。
生成LL库代码后添加
DMA添加代码
主要有读取后保存的地址和启动DMA
/* Definition of ADCx conversions data table size */
#define ADC_CONVERTED_DATA_BUFFER_SIZE ((uint32_t) 4)
/* Variables for ADC conversion data */
__IO uint16_t aADCxConvertedData[ADC_CONVERTED_DATA_BUFFER_SIZE]; /* ADC group regular conversion data */
void Activate_DMA(void)
{
/* Set DMA transfer addresses of source and destination */
LL_DMA_ConfigAddresses(DMA2,
LL_DMA_STREAM_0,
LL_ADC_DMA_GetRegAddr(ADC1, LL_ADC_DMA_REG_REGULAR_DATA),
(uint32_t)&aADCxConvertedData,
LL_DMA_DIRECTION_PERIPH_TO_MEMORY);
/* Set DMA transfer size */
LL_DMA_SetDataLength(DMA2,
LL_DMA_STREAM_0,
ADC_CONVERTED_DATA_BUFFER_SIZE);
/*## Activation of DMA #####################################################*/
/* Enable the DMA transfer */
LL_DMA_EnableStream(DMA2,LL_DMA_STREAM_0);
}
ADC添加代码
主要为启动ADC和使能转换
void Activate_ADC(void)
{
/*## Operation on ADC hierarchical scope: ADC instance #####################*/
/* Note: Hardware constraint (refer to description of the functions */
/* below): */
/* On this STM32 serie, setting of these features are not */
/* conditioned to ADC state. */
/* However, in order to be compliant with other STM32 series */
/* and to show the best practice usages, ADC state is checked. */
/* Software can be optimized by removing some of these checks, if */
/* they are not relevant considering previous settings and actions */
/* in user application. */
// if (LL_ADC_IsEnabled(ADC1) == 0)
{
/* Enable ADC */
LL_ADC_Enable(ADC1);
/* Start ADC group regular conversion */
LL_ADC_REG_StartConversionSWStart(ADC1);
LL_ADC_REG_SetDMATransfer(ADC1,LL_ADC_REG_DMA_TRANSFER_UNLIMITED);
}
/*## Operation on ADC hierarchical scope: ADC group regular ################*/
/* Note: No operation on ADC group regular performed here. */
/* ADC group regular conversions to be performed after this function */
/* using function: */
/* "LL_ADC_REG_StartConversion();" */
/*## Operation on ADC hierarchical scope: ADC group injected ###############*/
/* Note: No operation on ADC group injected performed here. */
/* ADC group injected conversions to be performed after this function */
/* using function: */
/* "LL_ADC_INJ_StartConversion();"
*/
}
电压转换
/* Definitions of environment analog values */
/* Value of analog reference voltage (Vref+), connected to analog voltage */
/* supply Vdda (unit: mV). */
#define VDDA_APPLI ((uint32_t)3300)
/* 计算电压 */
vdd = __LL_ADC_CALC_DATA_TO_VOLTAGE(VDDA_APPLI, aADCxConvertedData[1], LL_ADC_RESOLUTION_12B);
温度转换需要根据实际使用热敏电阻的规则,使用查表的方式比较得出。