ADC初始化要做的一些事情,主要是通过调用 ADC_CommonInit和ADC_Init,对ADC进行初始化。
特别要注意的是,GPIO要配置成模拟输入,不是AF。ADC的时钟不要操作36MHZ。
具体的代码注解,见D: 2 Learn 2 UC_OSmyproLesson 18
void Adc_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; ADC_CommonInitTypeDef ADC_CommonInitStructure; ADC_InitTypeDef ADC_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);//使能GPIOA时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE); //使能ADC1时钟 //对GPIO进行初始化 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;//PA5 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;//模拟通道 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;//没有上下拉 GPIO_Init(GPIOA, &GPIO_InitStructure);//GPIO初始化 RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC1,ENABLE); //ADC1复位 RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC1,DISABLE); //ADC1解复位 ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;//独立模式 ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;//采样延时 ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled; //DMA禁止 ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div4;// ADCCLK=PCLK2/4=84/4=21Mhz ADC_CommonInit(&ADC_CommonInitStructure);//这个函数其实就是配置ADC_CCR 寄存器,把以上的这些配置写入 ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;//12 bit ADC_InitStructure.ADC_ScanConvMode = DISABLE;//扫描禁止 ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;//连续转换禁止 ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;//禁止触发检测 ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;//右对齐 ADC_InitStructure.ADC_NbrOfConversion = 1;// ADC_Init(ADC1, &ADC_InitStructure);//ADC初始化,就是配置CR1,CR2,SQR
ADC_Cmd(ADC1, ENABLE);//通道使能 }
以上是对ADC进行配置,下面的读取ADC的值。同样也是调用库函数。
获得ADC的值,需要如下步骤:
1、 ADC_RegularChannelConfig(ADC1, ch, 1, ADC_SampleTime_480Cycles ); 选择哪个ADC,通道,转换规则,采样时间
2、ADC_SoftwareStartConv(ADC1); 转换启动,CR2的30bit
3、ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC ) 读ADC_SR的EOC位,判断转换是否结束
4、ADC_GetConversionValue(ADC1) 读DR值,就是转换结果
DAC相关的操作就更简单了,需要注意的是,DAC的管脚也需要配置成GPIO_Mode_AN。
DAC_InitType.DAC_Trigger=DAC_Trigger_None; //不使用触发功能 DAC_CR[2] TEN1=0 DAC_InitType.DAC_WaveGeneration=DAC_WaveGeneration_None;//不使用波形发生 DAC_CR[7:6] DAC_InitType.DAC_LFSRUnmask_TriangleAmplitude=DAC_LFSRUnmask_Bit0;//通道屏蔽设置 DAC_CR[11:8] DAC_InitType.DAC_OutputBuffer=DAC_OutputBuffer_Disable ; //不适用缓存功能DAC_CR[1] BOFF1=1 使用缓存能增加驱动能力 DAC_Init(DAC_Channel_1,&DAC_InitType); //初始化 DAC_Cmd(DAC_Channel_1, ENABLE); // DAC_CR[0] 使能DAC DAC_SetChannel1Data(DAC_Align_12b_R, 0); // 以右对齐的方式,写入数据保持寄存器