#include "stm32f4xx.h"
#include "usart.h"
#include "delay.h"
#include "adc.h"
int main(void)
{
u16 adcx;
delay_init(168);
Adc_Init();
uart_init(115200);
while(1)
{
adcx=Get_Adc_Average(ADC_Channel_0,20);//»ñè¡í¨μà5μÄ×a»»Ö죬20′Îè¡Æ½¾ù
printf ("adcx=%d
",adcx);
delay_ms(500);
}
}
#include "adc.h"
#include "delay.h"
void Adc_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
ADC_CommonInitTypeDef ADC_CommonInitStructure;
ADC_InitTypeDef ADC_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);//ê1ÄüGPIOAê±Öó
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE); //ê1ÄüADC1ê±Öó
//Ïè3õê¼»ˉADC1í¨μà5 IO¿ú
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;//PA5 í¨μà5
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;//Ä£Äaêäèë
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;//2»′øéÏÏÂà-
GPIO_Init(GPIOA, &GPIO_InitStructure);//3õê¼»ˉ
RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC1,ENABLE); //ADC1¸′λ
RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC1,DISABLE); //¸′λ½áêø
ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;//¶àá¢Ä£ê½
ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;//ὸö2éÑù½×¶ÎÖ®¼äμÄÑó3ù5¸öê±Öó
ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled; //DMAê§Äü
ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div4;//Ô¤·ÖÆμ4·ÖÆμ¡£ADCCLK=PCLK2/4=84/4=21Mhz,ADCê±Öó×îoÃ2»òa3¬1y36Mhz
ADC_CommonInit(&ADC_CommonInitStructure);//3õê¼»ˉ
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;//12λÄ£ê½
ADC_InitStructure.ADC_ScanConvMode = DISABLE;//·Çé¨ÃèÄ£ê½
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;//1رÕá¬Dø×a»»
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;//½ûÖ1′¥·¢¼ì2a£¬ê1óÃèí¼t′¥·¢
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;//óò¶ÔÆë
ADC_InitStructure.ADC_NbrOfConversion = 1;//1¸ö×a»»Ôú1æÔòDòáDÖD ò2¾íêÇÖ»×a»»1æÔòDòáD1
ADC_Init(ADC1, &ADC_InitStructure);//ADC3õê¼»ˉ
ADC_Cmd(ADC1, ENABLE);//¿aÆôAD×a»»Æ÷
}
//»ñμÃADCÖμ
//ch: @ref ADC_channels
//í¨μàÖμ 0~16è¡Öμ·¶Î§Îa£oADC_Channel_0~ADC_Channel_16
//·μ»ØÖμ:×a»»½á1û
u16 Get_Adc(u8 ch)
{
//éèÖÃÖ¸¶¨ADCμÄ1æÔò×éí¨μ࣬ò»¸öDòáD£¬2éÑùê±¼ä
ADC_RegularChannelConfig(ADC1, ch, 1, ADC_SampleTime_480Cycles ); //ADC1,ADCí¨μà,480¸öÖüÆú,ìá¸ß2éÑùê±¼ä¿éòÔìá¸ß¾«è·¶è
ADC_SoftwareStartConv(ADC1); //ê1ÄüÖ¸¶¨μÄADC1μÄèí¼t×a»»Æô¶ˉ1|Äü
while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC ));//μè′y×a»»½áêø
return ADC_GetConversionValue(ADC1); //·μ»Ø×î½üò»′ÎADC11æÔò×éμÄ×a»»½á1û
}
//»ñè¡í¨μàchμÄ×a»»Ö죬è¡times′Î,è»oóƽ¾ù
//ch:í¨μà±àoÅ
//times:»ñè¡′Îêy
//·μ»ØÖμ:í¨μàchμÄtimes′Î×a»»½á1ûƽ¾ùÖμ
u16 Get_Adc_Average(u8 ch,u8 times)
{
u32 temp_val=0;
u8 t;
for(t=0;t<times;t++)
{
temp_val+=Get_Adc(ch);
delay_ms(5);
}
return temp_val/times;
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
一周热门 更多>