首页 > 代码库 > [STM32F10x] 利用定时器测量频率

[STM32F10x] 利用定时器测量频率

  硬件:STM32F103C8T6

  平台:ARM-MDk V5.11

 

  原理

  利用STM32F10x的定时器的捕获(Capture)单元测量输入信号的频率。

  基本原理是通过两次捕获达到的计数器的差值,来计算输入信号的频率。假如第一次捕获时计数器的值为Val1,第二次捕获计数器的值为Val2,

  定时器的时钟频率为ftimer,那么输入信号的频率finput

                    finput = ftimer / (Val2 - Val1)               (Val2 > Val1)

  或

                    finput = ftimer / (MaxVal - Val1 + Val2)          (Val2 ≤ Val1)

   其中MaxVal为定时器的最大计数值

  

  代码

  以TIM2 CH4为例,定时器配置代码如下:

void CaptureConfig(void){    TIM_ICInitTypeDef  TIM_ICInitStructure;        TIM_ICInitStructure.TIM_Channel     = TIM_Channel_4;    TIM_ICInitStructure.TIM_ICPolarity  = TIM_ICPolarity_Rising;    TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;    TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;    TIM_ICInitStructure.TIM_ICFilter    = 0x0;    TIM_ICInit(TIM2, &TIM_ICInitStructure);        /* TIM enable counter */    TIM_Cmd(TIM2, ENABLE);    /* Enable the CC4 Interrupt Request */    TIM_ITConfig(TIM2, TIM_IT_CC4, ENABLE);}

 

  配置NVIC,使能TIM2的捕获中断:

void BSP_IntConfig(void){    NVIC_InitTypeDef NVIC_InitStructure;    /* Enable the TIM2 global Interrupt */    NVIC_InitStructure.NVIC_IRQChannel                        = TIM2_IRQn;    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority      = 0;    NVIC_InitStructure.NVIC_IRQChannelSubPriority             = 1;    NVIC_InitStructure.NVIC_IRQChannelCmd                     = ENABLE;    NVIC_Init(&NVIC_InitStructure);}

 

  在TIM2中断处理函数中计算出输入信号的频率:

void TIM2_IRQHandler(void){     static U16   Capture, IC4ReadValue1, IC4ReadValue2;    static U8    CaptureNumber = 0;        if(TIM_GetITStatus(TIM2, TIM_IT_CC4) == SET)     {        /* Clear TIM2 Capture compare interrupt pending bit */        TIM_ClearITPendingBit(TIM2, TIM_IT_CC4);        if(CaptureNumber == 0)        {            /* Get the Input Capture value */            IC4ReadValue1 = TIM_GetCapture4(TIM2);            CaptureNumber = 1;        }        else if(CaptureNumber == 1)        {            /* Get the Input Capture value */            IC4ReadValue2 = TIM_GetCapture4(TIM2);             /* Capture computation */            if (IC4ReadValue2 > IC4ReadValue1)            {                Capture = (IC4ReadValue2 - IC4ReadValue1);             }            else            {                Capture = ((0xFFFF - IC4ReadValue1) + IC4ReadValue2);             }            /* Frequency computation */             Freq = (U32) SystemCoreClock / Capture;            CaptureNumber = 0;        }    }}

  注意:Freq是个全局变量。

 /×××××××××××××××××××××××××××××××××××××××× THE END ×××××××××××××××××××××××××××××××××××××××××××××××××/

[STM32F10x] 利用定时器测量频率