一、代码
#include "main.h"/********************************************************************** @fn ADC_Function_Init** @brief Initializes ADC collection.** @return none*/
void ADC_Function_Init(void)
{ADC_InitTypeDef ADC_InitStructure = {0};GPIO_InitTypeDef GPIO_InitStructure = {0};RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;GPIO_Init(GPIOA, &GPIO_InitStructure);GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;GPIO_Init(GPIOA, &GPIO_InitStructure);ADC_DeInit(ADC1);ADC_CLKConfig(ADC1, ADC_CLK_Div6); // 采样时钟ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;ADC_InitStructure.ADC_ScanConvMode = DISABLE; // 非扫描模式ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; // ENABLE; // 非连续采样ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; // 无外部触发ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; // 采样数据右对齐ADC_InitStructure.ADC_NbrOfChannel = 2; // adc 通道数量ADC_Init(ADC1, &ADC_InitStructure);//ADC_DMACmd(ADC1, ENABLE); // 使能 DMAADC_Cmd(ADC1, ENABLE);
}/********************************************************************** @fn Get_ADC_Val** @brief Returns ADCx conversion result data.** @param ch - ADC channel.* ADC_Channel_0 - ADC Channel0 selected.* ADC_Channel_1 - ADC Channel1 selected.* ADC_Channel_2 - ADC Channel2 selected.* ADC_Channel_3 - ADC Channel3 selected.* ADC_Channel_4 - ADC Channel4 selected.* ADC_Channel_5 - ADC Channel5 selected.* ADC_Channel_6 - ADC Channel6 selected.* ADC_Channel_7 - ADC Channel7 selected.* ADC_Channel_8 - ADC Channel8 selected.* ADC_Channel_9 - ADC Channel9 selected.* ADC_Channel_10 - ADC Channel10 selected.* ADC_Channel_11 - ADC Channel11 selected.* ADC_Channel_12 - ADC Channel12 selected.* ADC_Channel_13 - ADC Channel13 selected.* ADC_Channel_14 - ADC Channel14 selected.* ADC_Channel_15 - ADC Channel15 selected.** @return none*/
u16 Get_ADC_Val(u8 ch)
{u16 val;ADC_RegularChannelConfig(ADC1, ch, 1, ADC_SampleTime_11Cycles);ADC_SoftwareStartConvCmd(ADC1, ENABLE);while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC));val = ADC_GetConversionValue(ADC1);return val;
}
// 验证采集第0个通道和第1个通道 两个通道的电压值
void test_ad_fun(void)
{while(1){u16 ad_0_val = 0;u16 ad_1_val = 0;Delay_Ms(100);ad_0_val = Get_ADC_Val(0);ad_1_val = Get_ADC_Val(1);
// Get_ADC_Val(3);
// Get_ADC_Val(4);PRINT("ad 0 = %d,ad 1 = %d.\n",ad_0_val,ad_1_val);}
}
二、调试
三、验证
给通道0的引脚接入0.4v 电压 验证打印出来ad值为330 左右
ADC是12bit精度 参考电压就是供电电压 我用usb供电所以参考电压就是5v