ADC_HandleTypeDef hadc1;//ADC句柄
//初始化ADC
void MY_ADC_Init(void)
{
hadc1.Instance = ADC1;
hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4; //4分频,ADCCLK=PCLK2/4=90/4=22.5MHZ
hadc1.Init.Resolution = ADC_RESOLUTION_12B; //12位模式
hadc1.Init.ScanConvMode = DISABLE; //非扫描模式
hadc1.Init.ContinuousConvMode = DISABLE; //关闭连续转换
hadc1.Init.DiscontinuousConvMode = DISABLE; //禁止不连续采样模式
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; //使用软件触发
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START; //软件触发
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT; //右对齐
hadc1.Init.NbrOfConversion = 1; //1个转换在规则序列中 也就是只转换规则序列1
hadc1.Init.DMAContinuousRequests = DISABLE; //关闭DMA请求
hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV; //关闭EOC中断
if (HAL_ADC_Init(&hadc1) != HAL_OK) //初始化
{
Error_Handler();
}
}
//ADC底层驱动,引脚配置,时钟使能
//此函数会被HAL_ADC_Init()调用
//hadc:ADC句柄
void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
{
if(adcHandle->Instance==ADC1)
{
__HAL_RCC_ADC1_CLK_ENABLE(); //使能ADC1时钟
}
}
//获得ADC值
uint16_t get_adc(uint32_t ch)
{
ADC_ChannelConfTypeDef sConfig = {0};
sConfig.Channel = ADC_CHANNEL_TEMPSENSOR; //选择内部温度传感器通道
sConfig.Rank = 1; //1个序列
sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES; //采样时间
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)//通道配置
{
Error_Handler();
}
HAL_ADC_Start(&hadc1); //开启ADC
HAL_ADC_PollForConversion(&hadc1,10); //轮询转换
return (uint16_t )HAL_ADC_GetValue(&hadc1); //返回最近一次ADC1规则组的转换结果
}
//获取指定通道的转换值,取times次,然后平均
//times:获取次数
//返回值:通道ch的cnt次转换结果平均值
uint16_t Get_Adc_Average(uint32_t ch,uint8_t cnt)
{
uint32_t temp_val=0;
uint8_t n;
for(n=0;n<cnt;n++)
{
temp_val+=get_adc(ch);
delay_ms(5);
}
return temp_val/cnt;
}
//得到温度值
//返回值:温度值(扩大了100倍,单位:℃.)
short Get_Temprate(void)
{
uint32_t adcx;
short result;
double temperate;
adcx=Get_Adc_Average(ADC_CHANNEL_TEMPSENSOR,10);//读取内部温度传感器通道,10次取平均
temperate=(float)adcx*(3.3/4096); //电压值
temperate=(temperate-0.76)/0.0025 + 25; //转换为温度值
result=temperate*=100; //扩大100倍.
return result;
}
|