多语言展示
当前在线:932今日阅读:126今日分享:42

stm32f103rc软件开发 (3) AD操作

在使用stm32单片机时,AD功能经常是我们需要用到的,stm32内的AD功能还是比较强大的,内部12位AD。还可以读内部cpu温度。下面介绍AD功能的软件实现。
工具/原料
1

stm32

2

keil

方法/步骤
1

还是先来一段主函数  这是最简单的一段函数,配置AD后,读一个值然后程序停在while 1中。int main(void){ float  AdValue = 0; /* System Clocks Configuration */ RCC_Configuration(); /* Configure the GPIO ports */ GPIO_Configuration(); Adinit () ;AdValue = AD_Get_Data();while(1);}

2

RCC的配置void RCC_Configuration(void){  /* Setup the microcontroller system. Initialize the Embedded Flash Interface,       initialize the PLL and update the SystemFrequency variable. */  SystemInit();      /* Enable GPIOx clock */  RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO|RCC_APB2Periph_GPIOA, ENABLE);  // AD  PA7  ADC12_IN7  为复用功能 RCC_APB2PeriphClockCmd ( RCC_APB2Periph_ADC1 , ENABLE );      //ADC时钟初始化  }

3

GPIO的配置void GPIO_Configuration(void){    GPIO_InitTypeDef GPIO_InitStructure;    //AD  PA7  ADC12_IN7    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;    GPIO_Init ( GPIOA, &GPIO_InitStructure );}

4

AD的配置void Adinit (void)  //AD采集初始化函数{    /* ADC1 configuration ------------------------------------------------------ */#define ADC1_DR_Address    ((uint32_t)0x4001244C)    ADC_InitTypeDef ADC_InitStructure;    __IO uint16_t ADCConvertedValue;    //      ErrorStatus HSEStartUpStatus;    ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;    ADC_InitStructure.ADC_ScanConvMode = DISABLE;    ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;    ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;    ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;    ADC_InitStructure.ADC_NbrOfChannel = 1;    ADC_Init ( ADC1, &ADC_InitStructure );    /* ADC1 regular channels configuration */    ADC_RegularChannelConfig ( ADC1, ADC_Channel_7, 1, ADC_SampleTime_28Cycles5 );     //开通 7    /* Enable ADC1 */    ADC_Cmd ( ADC1, ENABLE );    /* Enable ADC1 reset calibaration register */    ADC_ResetCalibration ( ADC1 );    /* Check the end of ADC1 reset calibration register */    while ( ADC_GetResetCalibrationStatus ( ADC1 ) );    /* Start ADC1 calibaration */    ADC_StartCalibration ( ADC1 );    /* Check the end of ADC1 calibration */    while ( ADC_GetCalibrationStatus ( ADC1 ) );    /* Start ADC1 Software Conversion */    ADC_SoftwareStartConvCmd ( ADC1, ENABLE );//ADC_TempSensorVrefintCmd( ENABLE );            //读cpu温度使能,需要这个功能就打开,这里例子没有读,可以不打开}//**********************//说明这段程序重要的是 ADC_RegularChannelConfig ( ADC1, ADC_Channel_7, 1, ADC_SampleTime_28Cycles5 );     //开通 7  需要几开通几。如果其它地方要读别的通道AD,要用这个函数修改一下。然后再读,就是那个通道的数据了。明白?

5

AD_Get_Data 的实现float AD_Get_Data ( void ) //读取模拟量函数{ float power_v = 0.0;    power_v = ADC_GetConversionValue ( ADC1 );  power_v = ( power_v  * 3.3 ) / 4096;        //实际电压 return power_v;}很简单的一段函数,因为是12位AD所以4096.然后供电3.3V. 所以这样算。

注意事项

AD功能是经常用到的一种功能

推荐信息