美文网首页
STM32F4 ADC

STM32F4 ADC

作者: 嵌入式工作 | 来源:发表于2018-09-22 16:22 被阅读0次
    //³õʼ»¯ADC
    //ÕâÀïÎÒÃǽöÒÔ¹æÔòͨµÀΪÀý
    //ÎÒÃÇĬÈϽö¿ªÆôADC1_CH5                                                                       
    void  Adc_Init(void)
    {    
        //Ïȳõʼ»¯IO¿Ú
    //  RCC->APB2ENR|=1<<8;     //ʹÄÜADC1ʱÖÓ 
    //  RCC->AHB1ENR|=1<<0;     //ʹÄÜPORTAʱÖÓ   
    //  
    //  GPIO_Set(GPIOA,PIN5,GPIO_MODE_AIN,0,0,GPIO_PUPD_PU);    //PA5,Ä£ÄâÊäÈë,ÏÂÀ­   
    //  
        
         __HAL_RCC_ADC1_CLK_ENABLE();
         __HAL_RCC_GPIOA_CLK_ENABLE();
         __HAL_RCC_GPIOD_CLK_ENABLE();
        
         GPIO_InitTypeDef GPIO_InitStruct;
        
        GPIO_InitStruct.Pin = MOTO1_ADC_Pin|MOTO2_ADC_Pin|NH3_ADC_Pin; // GPIO_PIN_0|
        GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
        GPIO_InitStruct.Pull = GPIO_NOPULL;
        HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    
    
        GPIO_InitStruct.Pin =LIG_ADC_Pin;
        GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
        GPIO_InitStruct.Pull = GPIO_NOPULL;
        HAL_GPIO_Init(LIG_ADC_GPIO_Port, &GPIO_InitStruct);
        
    
    
    
        RCC->APB2RSTR|=1<<8;    //ADCs¸´Î»
        RCC->APB2RSTR&=~(1<<8); //¸´Î»½áÊø   
        ADC->CCR=3<<16;         //ADCCLK=PCLK2/4=84/4=21Mhz,ADCʱÖÓ×îºÃ²»Òª³¬¹ý36Mhz
        
        ADC1->CR1=0;            //CR1ÉèÖÃÇåÁã
        ADC1->CR2=0;            //CR2ÉèÖÃÇåÁã
        ADC1->CR1|=0<<24;       //12λģʽ
        ADC1->CR1|=0<<8;        //·ÇɨÃèģʽ    
        
        ADC1->CR2&=~(1<<1);     //µ¥´Îת»»Ä£Ê½
        ADC1->CR2&=~(1<<11);    //ÓÒ¶ÔÆë    
        ADC1->CR2|=0<<28;       //Èí¼þ´¥·¢
        
        ADC1->SQR1&=~(0XF<<20);
        ADC1->SQR1|=0<<20;      //1¸öת»»ÔÚ¹æÔòÐòÁÐÖÐ Ò²¾ÍÊÇֻת»»¹æÔòÐòÁÐ1                
        //ÉèÖÃͨµÀ5µÄ²ÉÑùʱ¼ä
        ADC1->SMPR2&=~(7<<(3*5));//ͨµÀ5²ÉÑùʱ¼äÇå¿Õ      
        ADC1->SMPR2|=7<<(3*5);  //ͨµÀ5  480¸öÖÜÆÚ,Ìá¸ß²ÉÑùʱ¼ä¿ÉÒÔÌá¸ß¾«È·¶È    
        ADC1->CR2|=1<<0;        //¿ªÆôADת»»Æ÷    
    }                 
    //»ñµÃADCÖµ
    //ch:ͨµÀÖµ 0~16
    //·µ»ØÖµ:ת»»½á¹û
    u16 Get_Adc(u8 ch)   
    {
        //ÉèÖÃת»»ÐòÁÐ           
        ADC1->SQR3&=0XFFFFFFE0;//¹æÔòÐòÁÐ1 ͨµÀch
        ADC1->SQR3|=ch;                     
        ADC1->CR2|=1<<30;       //Æô¶¯¹æÔòת»»Í¨µÀ 
        while(!(ADC1->SR&1<<1));//µÈ´ýת»»½áÊø         
        return ADC1->DR;        //·µ»ØadcÖµ 
    }
    //»ñȡͨµÀchµÄת»»Öµ£¬È¡times´Î,È»ºóƽ¾ù 
    //ch:ͨµÀ±àºÅ
    //times:»ñÈ¡´ÎÊý
    //·µ»ØÖµ:ͨµÀchµÄtimes´Îת»»½á¹ûƽ¾ùÖµ
    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;
    }  
    
    

    相关文章

      网友评论

          本文标题:STM32F4 ADC

          本文链接:https://www.haomeiwen.com/subject/ckrxoftx.html