ADC多通道采集是在ADC单通道DMA传输的基础上写的,代码如下:
volatile u16 adcconverdata[2]={0,0};
static void ADC_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_1|GPIO_Pin_2;//添加PA2的GPIO初始化代码
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
static void ADC_Mode_Config(void)
{
ADC_InitTypeDef ADC_InitStructure;
DMA_InitTypeDef DMA_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1,ENABLE);
DMA_DeInit(DMA1_Channel1);
DMA_InitStructure.DMA_PeripheralBaseAddr=(uint32_t)&ADC1->DR;
DMA_InitStructure.DMA_MemoryBaseAddr=(uint32_t)adcconverdata;//由于采集的是多通道的数据,必须定义数组来存放数据,而数组的名字就是数组的首地址。所以不能这么写(uint32_t)&adcconverdata;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStructure.DMA_BufferSize=2; //由于是两个通道,这里改成2
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable; //开启内存地址自增
DMA_InitStructure.DMA_PeripheralInc =DMA_PeripheralInc_Disable ;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
DMA_InitStructure.DMA_Priority = DMA_Priority_Medium;
DMA_InitStructure.DMA_M2M=DMA_M2M_Disable;
DMA_Init(DMA1_Channel1,&DMA_InitStructure);
DMA_Cmd(DMA1_Channel1,ENABLE);
ADC_DeInit(ADC1);
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
ADC_InitStructure.ADC_ScanConvMode=ENABLE; //开启扫描模式
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfChannel=2; //通道书为2
ADC_Init(ADC1,&ADC_InitStructure);
RCC_ADCCLKConfig(RCC_PCLK2_Div8);
ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_239Cycles5);
ADC_RegularChannelConfig(ADC1, ADC_Channel_2, 2, ADC_SampleTime_239Cycles5);//定义通道的转换顺序
ADC_DMACmd(ADC1,ENABLE);
ADC_Cmd(ADC1,ENABLE);
ADC_ResetCalibration(ADC1);
while(ADC_GetResetCalibrationStatus(ADC1));
ADC_StartCalibration(ADC1);
while(ADC_GetCalibrationStatus(ADC1));
ADC_SoftwareStartConvCmd(ADC1,ENABLE);
}
void ADC_InitConfig(void)
{
ADC_GPIO_Config();
ADC_Mode_Config();
}
上述代码中红色部分为需要修改或者添加的代码,此部分代码我已经注释,比较容易理解
下面附主函数的代码
extern volatile u16 adcconverdata[2];
int main(void)
{
float m[2];
delay_init();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
uart_init(115200);
ADC_InitConfig();
while(1)
{
printf("adcconverdata[0]=%d \r\n",adcconverdata[0]);
printf("adcconverdata[1]=%d \r\n",adcconverdata[1]); delay_ms(500);
}
}
代码在while循环里直接打印出采集到的数据。上面代码我使用的是PA1和PA2作为采集通道。