1、开启RCC时钟,包括ADC 和GPIO的时钟
2、配置ADCCLK的分频器
3、配置多路开关,这里配置成规则组
4、配置ADC转换器
5、开启ADC
6、进行校准
#include "stm32f10x.h" // Device header
void AD_Init(void)
{
//开启RCC时钟,包括ADC 和GPIO的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE);
//配置ADCCLK的分频器
RCC_ADCCLKConfig(RCC_PCLK2_Div6);
//GPIO配置成模拟输入
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AIN;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_0;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
//配置多路开关,这里配置成规则组
ADC_RegularChannelConfig(ADC1,ADC_Channel_0,1,ADC_SampleTime_55Cycles5);
//配置ADC转换器
ADC_InitTypeDef ADC_InitStructure;
ADC_InitStructure.ADC_Mode= ADC_Mode_Independent;
ADC_InitStructure.ADC_DataAlign= ADC_DataAlign_Right;
ADC_InitStructure.ADC_ContinuousConvMode=DISABLE ;
ADC_InitStructure.ADC_ExternalTrigConv= ADC_ExternalTrigConv_None;
ADC_InitStructure.ADC_NbrOfChannel= 1;
ADC_InitStructure.ADC_ScanConvMode=DISABLE ;
ADC_Init(ADC1,&ADC_InitStructure);
//开启ADC
ADC_Cmd(ADC1,ENABLE);
//复位校准
ADC_ResetCalibration(ADC1);
//等待复位校准完成
while(ADC_GetResetCalibrationStatus(ADC1)==SET);
//开始校准
ADC_StartCalibration(ADC1);
//等待校准完成
while(ADC_GetCalibrationStatus(ADC1)==SET);
}
uint16_t AD_GetValue(void)
{
//软件触发转换
ADC_SoftwareStartConvCmd(ADC1,ENABLE);
//获取状态标志位
while(ADC_GetFlagStatus(ADC1,ADC_FLAG_EOC)==RESET);
//获取转换值
return ADC_GetConversionValue(ADC1);
}
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "AD.h"
uint16_t Value;
float Voltage;
int main(void)
{
OLED_Init();
AD_Init();
OLED_ShowString(1,1,"Value:");
OLED_ShowString(2,1,"Voltage:0.00V");
while (1)
{
Value=AD_GetValue();
Voltage=(float)Value/4095*3.3;
OLED_ShowNum(1,7,Value,4);
OLED_ShowNum(2,9,Voltage,1);
OLED_ShowNum(2,11,(uint16_t)(Voltage*100)%100,2);
}
}