下面是我用定时器TIM2的两个通道测量频率的程序,计数值为0xFFFF,频率为1M,为了解决双通道测量的问题,我的解决方案是在每个计数周期内仅打开一个通道,有更新中断发生时打开另一通道,从测量结果来看较好的解决了双通道测量的问题,但我本人对这个程序很不满意,第一个问题就是我原来设想两次捕获就关掉通道计算频率,在频率限定的情况下,两次捕获理论上应该发生在同一计数周期内,实际则是有时会出现跨周期计数,就需判断ICValue2和ICValue1的大小,无法理解。第二个问题就是没有输入时频率归零的问题,我用了很多方法,比如有捕获是标志位置一,在发生更新中断时判断标志位,如果标志位为0就认为无输入,频率归零,实际情况是很多计数周期内都会出现没有捕获的情况,希望大家加入讨论,尤其是给一个无输入频率归零的可靠方案。
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
if(Channel_Flag == 0)
{
TIM_ITConfig(TIM2, TIM_IT_CC3, ENABLE);
Channel_Flag = 1;
}
else if(Channel_Flag == 1)
{
TIM_ITConfig(TIM2, TIM_IT_CC2, ENABLE);
Channel_Flag = 0;
}
}
if(TIM_GetITStatus(TIM2, TIM_IT_CC2) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_CC2);
CC2_flag = 1;
if(IC2Num == 0)
{
IC2Value1 = TIM_GetCapture2(TIM2);
IC2Num = 1;
}
else if(IC2Num == 1)
{
IC2Value2 = TIM_GetCapture2(TIM2);
IC2Num = 0;
if(IC2Value2 > IC2Value1)
{
IC2Capture = IC2Value2 - IC2Value1;
}
else
{
IC2Capture = 0xFFFF - IC2Value1 + IC2Value2 + 1;
}
IC2Freq = 1000000 / IC2Capture;
LCD_DisplayChar(Line0, 239, IC2Freq/10000+0x30);
LCD_DisplayChar(Line0, 223, (IC2Freq%10000)/1000+0x30);
LCD_DisplayChar(Line0, 207, ((IC2Freq%10000)%1000)/100+0x30);
LCD_DisplayChar(Line0, 191, (((IC2Freq%10000)%1000)%100)/10+0x30);
LCD_DisplayChar(Line0, 175, (((IC2Freq%10000)%1000)%100)%10+0x30);
TIM_ITConfig(TIM2, TIM_IT_CC2, DISABLE);
}
}
if(TIM_GetITStatus(TIM2, TIM_IT_CC3) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_CC3);
CC3_flag = 1;
if(IC3Num == 0)
{
IC3Value1 = TIM_GetCapture3(TIM2);
IC3Num = 1;
}
else if(IC3Num == 1)
{
IC3Value2 = TIM_GetCapture3(TIM2);
IC3Num = 0;
if(IC3Value2 > IC3Value1)
{
IC3Capture = IC3Value2 - IC3Value1;
}
else
{
IC3Capture = 0xFFFF - IC3Value1 + IC3Value2 + 1;
}
IC3Freq = 1000000 / IC3Capture;
LCD_DisplayChar(Line4, 239, IC3Freq/10000+0x30);
LCD_DisplayChar(Line4, 223, (IC3Freq%10000)/1000+0x30);
LCD_DisplayChar(Line4, 207, ((IC3Freq%10000)%1000)/100+0x30);
LCD_DisplayChar(Line4, 191, (((IC3Freq%10000)%1000)%100)/10+0x30);
LCD_DisplayChar(Line4, 175, (((IC3Freq%10000)%1000)%100)%10+0x30);
TIM_ITConfig(TIM2, TIM_IT_CC3, DISABLE);
}
}
} |