STM32 Hal库-ADC电压采集-多通道DMA
1、CubeMx配置ADC时钟,配置成12MHz。
2、ADC参数配置
Scan Conversion Mode( 扫描模式 ) :如果使用多个通道,自动设置ENABLE。
Continuous Conversion Mode(连续转换模式) :设置为ENABLE,即连续转换。
3、ADC总转换时间TCONV
TCONV = 采样时间+ 12.5个周期
ADC时钟设置为12MHz,采样时间为71.5个周期,则总转换时间T=7us
4、DMA配置
5、bsp_adc.c
#include "bsp_adc.h"
uint16_t adc1_val_buf[ADC1_CHANNEL_CNT*ADC1_VALUE_CNT]; //传递给DMA存放多通道采样值的数组
uint32_t adc1_aver_val[ADC1_CHANNEL_CNT] = {0}; //计算多通道的平均采样值的过程数组
void ADC1_Start_DMA(void)
{
if(HAL_ADC_Start_DMA(&hadc1, (uint32_t*)&adc1_val_buf, (ADC1_CHANNEL_CNT*ADC1_VALUE_CNT)) != HAL_OK)
{
/* Start Conversation Error */
Error_Handler();
}
}
void ADC1_Stop_DMA(void)
{
if(HAL_ADC_Stop_DMA(&hadc1) != HAL_OK)
{
/* Start Conversation Error */
Error_Handler();
}
}
/* x:对应Rank通道 */
uint16_t ADC1INx_AverValue( uint8_t x )
{
uint16_t i=0;
uint16_t value=0;
/* 在采样值数组中分别取出每个通道的采样值并求和 */
adc1_aver_val[x] = 0;
for(i = 0; i < ADC1_VALUE_CNT; i++)
{
adc1_aver_val[x] += adc1_val_buf[i*ADC1_CHANNEL_CNT+x];
}
/* 对通道采样值求平均值 */
value = adc1_aver_val[x] / ADC1_VALUE_CNT;
return value;
}
5、bsp_adc.h
#ifndef __BSP_ADC_H__
#define __BSP_ADC_H__
#include "main.h"
#include "adc.h"
#include "dma.h"
#include <stdio.h>
#include <string.h>
#define ADC1_CHANNEL_CNT 6 //采样通道数
#define ADC1_VALUE_CNT 20 //单个通道采样次数,用来取平均值
#define Rank1 0
#define Rank2 1
#define Rank3 2
#define Rank4 3
#define Rank5 4
#define Rank6 5
#define Rank7 6
#define Rank8 7
#define Rank9 8
#define Rank10 9
extern uint16_t adc1_val_buf[ADC1_CHANNEL_CNT*ADC1_VALUE_CNT]; //传递给DMA存放多通道采样值的数组
extern uint32_t adc1_aver_val[ADC1_CHANNEL_CNT]; //计算多通道的平均采样值的过程数组
void ADC1_Start_DMA( void );
void ADC1_Stop_DMA( void );
uint16_t ADC1INx_AverValue( uint8_t x );
#endif
6、main.c
/* Infinite loop */
/* USER CODE BEGIN WHILE */
HAL_Delay(1000);
HAL_ADCEx_Calibration_Start(&hadc1); //要是采集的电压不准,上电延时一段时间进行ADC校准
ADC1_Start_DMA();
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
// LED_RUN( 1000 );
OLED_Showdecimal(0,6,ADC1INx_AverValue( Rank5 )*1000/4096*3.3/1000,1,3,16); //采集电压,显示在OLED屏幕
OLED_Showdecimal(60,6,ADC1INx_AverValue( Rank6 )*1000/4096*3.3/1000,1,3,16);
HAL_Delay(1000);
}
/* USER CODE END 3 */
作者:plusming