#include "adc.h"
#include "delay.h"
//////////////////////////////////////////////////////////////////////////////////
//初始化ADC
//这里我们仅以规则通道为例
//我们默认将开启通道0~3
void Adc_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA |RCC_APB2Periph_ADC1 , ENABLE );
RCC_ADCCLKConfig (RCC_PCLK2_Div6);// 小于14M
ADC_DeInit (ADC1 );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; //LED0-->PB.5 端口配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN; //推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz
GPIO_Init(GPIOA, &GPIO_InitStructure);
ADC_DeInit (ADC1 );//复位ADC1,将外设 ADC1 的全部寄存器重设为缺省值
ADC_InitStructure.ADC_ContinuousConvMode= DISABLE ;
ADC_InitStructure.ADC_DataAlign= ADC_DataAlign_Right;
ADC_InitStructure.ADC_ExternalTrigConv=ADC_ExternalTrigConv_None;
ADC_InitStructure.ADC_Mode=ADC_Mode_Independent;
ADC_InitStructure.ADC_NbrOfChannel=1;
ADC_InitStructure.ADC_ScanConvMode=DISABLE ;
ADC_Init (ADC1 ,&ADC_InitStructure);
ADC_Cmd (ADC1 ,ENABLE );
ADC_TempSensorVrefintCmd (ENABLE );
ADC_ResetCalibration(ADC1); //使能复位校准
while(ADC_GetResetCalibrationStatus(ADC1)); //等待复位校准结束
ADC_StartCalibration(ADC1); //开启AD校准
while(ADC_GetCalibrationStatus(ADC1)); //等待校准结束
// ADC_SoftwareStartConvCmd(ADC1, ENABLE); //使能指定的ADC1的软件转换启动功能
}
u16 Get_Adc(u8 ch)
{
ADC_RegularChannelConfig (ADC1 ,ch,1,ADC_SampleTime_239Cycles5);//选择第几个规则通道 以及规则通道的顺序
ADC_SoftwareStartConvCmd (ADC1 ,ENABLE );
while(!ADC_GetFlagStatus (ADC1 ,ADC_FLAG_EOC));
return ADC_GetConversionValue (ADC1 );
}
u16 Get_Adc_Average(u8 ch,u8 times)
{
u32 temp;
u8 t;
for(t=0;t<times ;t++)
{
temp+= Get_Adc(ch);
delay_ms (5);
}
return temp /times ;
}
u16 T_Get_Adc(u8 ch) //获得某个通道值
{
ADC_RegularChannelConfig (ADC1 ,ch,1,ADC_SampleTime_239Cycles5);
ADC_SoftwareStartConvCmd (ADC1 ,ENABLE );
while(!ADC_GetFlagStatus (ADC1 ,ADC_FLAG_EOC ));
return ADC_GetConversionValue (ADC1 );
}
u16 T_Get_Adc_Average(u8 ch,u8 times)//局部变量
{
u32 temp;
u8 t;
for(t=0;t<times ;t++)
{
temp +=T_Get_Adc (ch);
delay_ms(5);
}
return temp/times ;
}
short Get_Temprate(void)
{
u32 adcx;
short result;
double temperate;
adcx =T_Get_Adc_Average(ADC_Channel_16 ,20) ;
temperate=(float)adcx*(3.3/4096);
temperate=(1.43-temperate)/0.0043+25;
result =temperate *=10;
return result ;
}
|