原子哥以下程序怎么捕获频率老是不准?
使用STM8 16M时钟
TIM1自动装值为0xffff时代码标红底的地方,测1Khz 计数结果为15900左右.
TIM1的自动装入值改为0xff时, 同样测1Khz 计数结果为956左右.(这个结果有点相近)
这计数器装入值,难道会影响计算频率的吗?
void Hz_CounterConfig() //初始化Tim1 比较捕获通道2
{
/*端口初始化*/
GPIO_Init(HZ_COUNTER_PROT, HZ_COUNTER_PIN, GPIO_MODE_IN_PU_NO_IT);
TIM1_DeInit();
TIM1_TimeBaseInit(16, TIM1_COUNTERMODE_UP, 0xffff, 0x00);
//频率计使用TIM1_CH2,信号从PD.4引脚引入
TIM1_ICInit(TIM1_CHANNEL_2, TIM2_ICPOLARITY_RISING, TIM1_ICSELECTION_DIRECTTI, TIM1_ICPSC_DIV1, 0x00);
//启用捕获中断和更新中断
TIM1_ITConfig (TIM1_IT_UPDATE, ENABLE);
TIM1_ClearFlag (TIM1_FLAG_UPDATE);
enableInterrupts ();
/*TIM1_ITConfig(TIM1_IT_UPDATE|TIM1_IT_CC2, ENABLE);
TIM1_ClearFlag(TIM1_FLAG_UPDATE|TIM1_FLAG_CC2);
ITC_SetSoftwarePriority(ITC_IRQ_TIM1_CAPCOM, ITC_PRIORITYLEVEL_2);
enableInterrupts();*/
}
void Hz_CounterON() //启用输入捕获功能
{
i=0;
TIM1CH2_CAPTURE_VAL=0;
TIM1_ClearFlag(TIM1_FLAG_CC2|TIM1_IT_UPDATE);
TIM1_Cmd(ENABLE);
temp=0;
while(i<3)
{
//捕获第1次高电平
//TIM1_OC2PolarityConfig(TIM1_OCPOLARITY_HIGH);
TIM1_SetCounter(0);
while((TIM1->SR1 & TIM1_FLAG_CC2) != TIM1_FLAG_CC2);
//capt1 = TIM1_GetCapture2();
TIM1_ClearFlag(TIM1_FLAG_CC2);
TIM1_SetCounter(0);
TIM1CH2_CAPTURE_VAL=0;
//设置捕获下降沿
//TIM1_OC2PolarityConfig(TIM1_OCPOLARITY_LOW);
//捕获第2次高电平
while((TIM1->SR1 & TIM1_FLAG_CC2) != TIM1_FLAG_CC2);
TIM1_ClearFlag(TIM1_FLAG_CC2);
capt2 = TIM1_GetCapture2();
temp=TIM1CH2_CAPTURE_VAL*0xffff;
temp+=capt2;
value[i++]=temp;
if(TIM1CH2_CAPTURE_VAL>=0xffff) //257*255=65535待测频率溢出计数超出16位变量范围时将TIM1捕获频率降低
{
TIM1_Cmd(DISABLE);
TIM1_PRE*=10;
TIM1_TimeBaseInit(TIM1_PRE, TIM1_COUNTERMODE_UP, 0xffff, 0x00);
i=0;
TIM1_Cmd(ENABLE);
}
}
TIM1_Cmd(DISABLE);
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
一周热门 更多>