赞
踩
void GP2Y_ADC_init() { GPIO_InitTypeDef GPIO_InitStructure; ADC_InitTypeDef ADC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOF|RCC_APB2Periph_AFIO|RCC_APB2Periph_ADC3,ENABLE); RCC_ADCCLKConfig(RCC_PCLK2_Div6);//12M 最大14M 设置ADC时钟(ADCCLk) ADC_DeInit(ADC3); GPIO_InitStructure.GPIO_Pin=GPIO_Pin_6;//ADC GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AIN; //模拟输入 GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; GPIO_Init(GPIOF,&GPIO_InitStructure); ADC_InitStructure.ADC_Mode = ADC_Mode_Independent; ADC_InitStructure.ADC_ScanConvMode = DISABLE; ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; ADC_InitStructure.ADC_NbrOfChannel = 4; ADC_Init(ADC3, &ADC_InitStructure); //设置指定ADC的规则组通道,设置它们的转化顺序和采样时间ADC_RegularChannelConfig(ADC1,ADC_Channel_1,1,ADC_SampleTime_239Cycles5); //内部温度传感器是在ADC1通道16的 ADC_RegularChannelConfig(ADC3,ADC_Channel_4,1,ADC_SampleTime_239Cycles5); // ADC_TempSensorVrefintCmd(ENABLE);//打开内部温度传感器使能 ADC_Cmd(ADC3,ENABLE); ADC_ResetCalibration(ADC3);//重置指定的ADC的校准寄存器 while(ADC_GetResetCalibrationStatus(ADC3));//获取ADC重置校准寄存器的状态 ADC_StartCalibration(ADC3);//开始指定ADC的校准状态 while(ADC_GetCalibrationStatus(ADC3));//获取指定ADC的校准程序 ADC_SoftwareStartConvCmd(ADC3, ENABLE);//使能或者失能指定的ADC的软件转换启动功能 GPIO_SetBits(GPIOC, GPIO_Pin_2);//置1 u16 GetGP2YAverageValue(u8 times) { u32 temp_val=0; u8 t; for(t=0;t<times;t++) { temp_val+=GetGP2YSingleValue(); } return temp_val/times; } u16 GetGP2YSingleValue(void) { int samplingTime = 280;//等待LED开启的时间是280μs int deltaTime = 40;//整个脉冲持续时间为320μs。因此,我们还需再等待40μs uint16_t ADCVal; float dustVal = 0; float Voltage; GPIO_ResetBits(GPIOC, GPIO_Pin_2);//置1 开启内部LED ???????? delay_us(samplingTime); // 开启LED后的280us的等待时间 ADC_SoftwareStartConvCmd(ADC3, ENABLE); while(!ADC_GetFlagStatus(ADC3,ADC_FLAG_EOC)); ADCVal = ADC_GetConversionValue(ADC3); delay_us(40); GPIO_SetBits(GPIOC, GPIO_Pin_2);//置0 delay_us(9680);//需要脉宽比0.32ms/10ms的PWM信号驱动传感器中的LED Voltage = ADCVal * 3.3 / 4096; dustVal = (Voltage + 1) * 1000 / 10;//*1000作用是将单位转换为ug/m3 // if(ADCVal > 36.455) // dustVal = ((float)(ADCVal / 1024.0) - 0.0356) * 120000 * 0.035; // dustVal = 0.17 * ADCVal - 0.1; // dustVal = ADCVal; // return dustVal; // mg/m3 return dustVal; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。