代码
在main.c中,添加头文件,若不添加会出现 identifier “FILE” is undefined报错。
/* USER CODE BEGIN Includes */
#include "stdio.h"
/* USER CODE END Includes */
函数声明和串口重定向:
/* USER CODE BEGIN PFP */
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/* USER CODE END PFP */
/* USER CODE BEGIN 0 */
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&huart1 , (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
/* USER CODE END 0 */
变量定义:
/* USER CODE BEGIN 1 */
uint32_t ADC_1, ADC_2,ADC_3;
//各采样30次,故30*3为90
uint32_t ADC_Value[90];
uint8_t i;
/* USER CODE END 1 */
使用DMA传输:
/* USER CODE BEGIN 2 */
HAL_ADC_Start_DMA(&hadc,(uint32_t*)&ADC_Value,90); //使用DMA传输
/* USER CODE END 2 */
主循环:
/* USER CODE BEGIN WHILE */
while (1)
{
//放个延迟,防止程序运行第一次读出数据有误
HAL_Delay(100);
ADC_1=0;
ADC_2=0;
ADC_3=0;
for(i=0,ADC_1=0,ADC_2=0;i<90;)
{
ADC_1+=ADC_Value[i++];
ADC_2+=ADC_Value[i++];
ADC_3+=ADC_Value[i++];
}
printf("ADC数据如下\n");
//除以30为求30次平均ADC值,乘以3.3为以3.3电压为基准,除以4096为ADC配置为12位
printf("ADC_IN0=%1.4f\r\n",ADC_1/30*3.3f/4096);
printf("ADC_IN1=%1.4f\r\n",ADC_2/30*3.3f/4096);
printf("ADC_IN2=%1.4f\r\n",ADC_3/30*3.3f/4096);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_Delay(900);
}
/* USER CODE END 3 */