STM32复习笔记(十三) —— ADC(多通道)采集电压
1.本例程软件设计思路
1)使用 ADC1 扫描检测三个通道引脚上被施加的电压值 2)经过 ADC 转换完成后,通过 DMA 传输到存储器中 3)再由串口打印显示
注意:此处测量的电压范围仅适用于 0 - 3.3V,不得高于 3.3V
2.代码编写
于 main.c 中编写代码
#include "stm32f10x.h"
#include "dr_usart.h"
uint16_t ADC_CurrentValue[3] = {0};
float ADC_RealValue[3] = {0.0, 0.0, 0.0};
static void delay_(uint32_t count);
void ADC1_GPIO_Config(void)
{
RCC->APB2ENR |= ((uint16_t)0x01 << 2);
GPIOA->CRL &= ~((uint32_t)0x0fff << 4);
}
static void ADC1_DMA_Config(void)
{
RCC->AHBENR |= ((uint16_t)0x01 << 0);
DMA1_Channel1->CCR &= ((uint32_t)0xFFFF8000);
DMA1_Channel1->CCR &= ~((uint32_t)0x01 << 14);
DMA1_Channel1->CCR |= ((uint32_t)0x01 << 12);
DMA1_Channel1->CCR |= ((uint32_t)0x01 << 10);
DMA1_Channel1->CCR |= ((uint32_t)0x01 << 8);
DMA1_Channel1->CCR |= ((uint32_t)0x01 << 7);
DMA1_Channel1->CCR &= ~((uint32_t)0x01 << 6);
DMA1_Channel1->CCR |= ((uint32_t)0x01 << 5);
DMA1_Channel1->CCR &= ~((uint32_t)0x01 << 4);
DMA1_Channel1->CNDTR = ((uint32_t)3);
DMA1_Channel1->CPAR = ((uint32_t)(ADC1_BASE + 0x4C));
DMA1_Channel1->CMAR = ((uint32_t)ADC_CurrentValue);
DMA1_Channel1->CCR |= ((uint32_t)0x01 << 0);
}
void ADC1_Config(void)
{
ADC1_GPIO_Config();
ADC1_DMA_Config();
RCC->APB2ENR |= ((uint16_t)0x01 << 9);
ADC1->CR1 &= ~((uint32_t)0x0f << 16);
ADC1->CR1 |= ((uint32_t)0x01 << 8);
ADC1->CR2 |= ((uint32_t)0x0F << 17);
ADC1->CR2 &= ~((uint32_t)0x01 << 11);
ADC1->CR2 |= ((uint32_t)0x01 << 1);
ADC1->SQR1 |= ((uint32_t)0x02 << 20);
RCC->CFGR |= ((uint32_t)0x03 << 14);
ADC1->SMPR2 |= ((uint32_t)0x01FF << 3);
ADC1->SQR3 |= ((uint32_t)0x0C41 << 0);
ADC1->CR2 |= ((uint32_t)0x01 << 8);
ADC1->CR2 |= ((uint32_t)0x01 << 0);
ADC1->CR2 |= ((uint32_t)0x01 << 3);
while(0 != (ADC1->CR2 & ((uint32_t)0x01 << 3)));
ADC1->CR2 |= ((uint32_t)0x01 << 2);
while(0 != (ADC1->CR2 & ((uint32_t)0x01 << 2)));
ADC1->CR2 |= ((uint32_t)0x01 << 22);
}
int main(void)
{
User_Init();
ADC1_Config();
while(1)
{
ADC_RealValue[0] = (float)ADC_CurrentValue[0]/4096*3.3 + 0.005;
ADC_RealValue[1] = (float)ADC_CurrentValue[1]/4096*3.3 + 0.005;
ADC_RealValue[2] = (float)ADC_CurrentValue[2]/4096*3.3 + 0.005;
printf("ADC_CurrentValue_1 = %d.\r\n", ADC_CurrentValue[0]);
printf("ADC_RealValue_1 = %.2f V.\r\n\r\n", ADC_RealValue[0]);
printf("ADC_CurrentValue_2 = %d.\r\n", ADC_CurrentValue[1]);
printf("ADC_RealValue_2 = %.2f V.\r\n\r\n", ADC_RealValue[1]);
printf("ADC_CurrentValue_3 = %d.\r\n", ADC_CurrentValue[2]);
printf("ADC_RealValue_3 = %.2f V.\r\n\r\n", ADC_RealValue[2]);
printf("--------- --------- ---------\r\n");
delay_(500);
}
}
static void delay_(uint32_t count)
{
__IO uint32_t delay_count = (12000 * count);
while(delay_count--);
}
点击编译,如无错误可进入仿真界面 打开串口 点击运行 此时被检测的引脚上 (即 ADC 检测的三个通道) 并未施加电压,所以输出为0V
于三个引脚上分别施加 1V 2V 3V 电压,观察输出变化 此时已经检测到电压值并输出显示,程序运行结果与预想一致
|