通过ADC通道16,采集内部温度传感器输出电压值和温度值,具体程序如下:
adc.h文件
#ifndef USER_ADC_H_
#define USER_ADC_H_
void ADC_Function_Init(void);
u16 Get_ADC_Val(u8 ch);
u16 Get_ADC_Average(u8 ch, u8 times);
u16 Get_ConversionVal(s16 val);
#endif
adc.h文件主要是函数的声明.
adc.c文件
#include "debug.h"
s16 Calibrattion_Val = 0;
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);
RCC_ADCCLKConfig(RCC_PCLK2_Div8);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
ADC_DeInit(ADC1);
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 = 1;
ADC_Init(ADC1, &ADC_InitStructure);
ADC_Cmd(ADC1, ENABLE);
ADC_BufferCmd(ADC1, DISABLE);
ADC_ResetCalibration(ADC1);
while(ADC_GetResetCalibrationStatus(ADC1));
ADC_StartCalibration(ADC1);
while(ADC_GetCalibrationStatus(ADC1));
Calibrattion_Val = Get_CalibrationValue(ADC1);
ADC_BufferCmd(ADC1, ENABLE);
ADC_TempSensorVrefintCmd(ENABLE);
}
u16 Get_ADC_Val(u8 ch)
{
u16 val;
ADC_RegularChannelConfig(ADC1, ch, 1, ADC_SampleTime_239Cycles5);
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC));
val = ADC_GetConversionValue(ADC1);
return val;
}
u16 Get_ADC_Average(u8 ch, u8 times)
{
u32 temp_val = 0;
u8 t;
u16 val;
for(t = 0; t < times; t++) {
temp_val += Get_ADC_Val(ch);
Delay_Ms(5);
}
val = temp_val / times;
return val;
}
u16 Get_ConversionVal(s16 val)
{
if((val + Calibrattion_Val) < 0)
return 0;
if((Calibrattion_Val + val) > 4095)
return 4095;
return (val + Calibrattion_Val);
}
通过以上配置,即可ADC值进行读取。
main.c文件
#include "debug.h"
#include "iic.h"
#include "oled.h"
#include "ADC.h"
int main(void)
{
IIC_Init(800000, 0x78);
OLED_Init();
OLED_Clear(0);
OLED_ShowString(20,0,"CH32V208 TEST",16);
u16 ADC_val;
s32 val_mv;
Delay_Init();
ADC_Function_Init();
while(1)
{
ADC_val = Get_ADC_Average(ADC_Channel_TempSensor, 10);
Delay_Ms(500);
ADC_val = Get_ConversionVal(ADC_val);
OLED_ShowNum(20,4,ADC_val,8,16);
val_mv = (ADC_val * 3300 / 4096);
OLED_ShowNum(20,6,TempSensor_Volt_To_Temper(val_mv),8,16);
Delay_Ms(2);
}
}
main.c文件主要进行相关函数的初始化以及输出通过ADC_IN1读取到的ADC值。
|