本帖最后由 一路向北lm 于 2020-4-28 16:43 编辑
调试完串口,下面开始测试ADC 啦!
ADC初始化函数如下:
//使能ADC1的时钟
void ADC_RCC_ClockSet(ADC_TypeDef* ADCx, FunctionalState NewState)
{
if(ADCx == ADC1)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE);
}
}
//
static void ADCxSampleTimeConfig(ADC_TypeDef* ADCn, ADCSAM_TypeDef sampleTime)
{
ADCn->CFGR &= ~ADC_CFGR_SAMCTL;
ADCn->CFGR |= sampleTime;
}
//ADC1外设初始化
void ADC1BasicConfigWithParameter(void)
{
ADC_InitTypeDef ADC_InitStructure;
ADC_TypeDef* ADCn;
ADCn = ADC1;
ADC_StructInit(&ADC_InitStructure);
ADC_RCC_ClockSet(ADCn,ENABLE);
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_PRESCARE=ADC_PCLK2_PRESCARE_16; //ADC prescale factor
ADC_InitStructure.ADC_Mode=ADC_Mode_Continue; //Set ADC mode to continuous conversion mode
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
//AD data right-justified
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC1;
ADC_Init(ADCn, &ADC_InitStructure);
ADCxSampleTimeConfig(ADCn, ADC_Samctl_13_5);
ADC_Cmd(ADCn,ENABLE); //Enable AD conversion
}
void ADCxChannelEnable(ADC_TypeDef* ADCn, u32 channel)
{
ADCn->CHSR &= ~(1 << channel);
ADCn->CHSR |= (1 << channel);
}
void ADC1ChannelConfigWithParameter(void)
{
ADC_TypeDef* ADCn;
ADCn = ADC1;
ADCxChannelEnable(ADCn, ADC_Channel_1);
// ADCxChannelEnable(ADCn,ADC_Channel_1);
// ADCxChannelEnable(ADCn,ADC_Channel_2);
// ADCxChannelEnable(ADCn,ADC_Channel_3);
}
void ADCxAssignPin(GPIO_TypeDef* GPIOx, u16 pin)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_StructInit(&GPIO_InitStructure);
CFG_GPIO_Clock(GPIOx, ENABLE);
GPIO_InitStructure.GPIO_Pin = pin;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //Output speed
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN; //GPIO mode
GPIO_Init(GPIOx, &GPIO_InitStructure);
}
unsigned int ADC1_SingleChannel_Get(void)
{
u16 puiADData;
ADC_SoftwareStartConvCmd(ADC1, ENABLE); //Software start conversion
while(ADC_GetFlagStatus(ADC1, ADC_IT_EOC) == 0);
ADC_ClearFlag(ADC1, ADC_IT_EOC);
puiADData = ADC_GetConversionValue(ADC1);
return puiADData;
}
unsigned int Get_Adc_Average(uint8_t times)
{
u32 temp_val = 0;
u8 t;
u8 delay;
for(t = 0; t < times; t++) {
temp_val += ADC1_SingleChannel_Get();
for(delay = 0; delay < 100; delay++);
}
return temp_val / times;
}
void ADC1PinConfigWithParameter(void)
{
//customer can change below config based Pin assign
//sample No.1
ADCxAssignPin(GPIOA, GPIO_Pin_1);
//ADCxAssignPin(GPIOA, GPIO_Pin_4);
//ADCxAssignPin(GPIOA, GPIO_Pin_5);
//sample No.2
//ADCxAssignPin(GPIOA, GPIO_Pin_4);
//ADCxAssignPin(GPIOA, GPIO_Pin_5);
//ADCxAssignPin(GPIOA, GPIO_Pin_6);
}
|