问题:
在用脉冲进行做题的时候发现脉冲输出的频率随着脉冲数值增大而越来越不稳定
典型的情况是10000HZ的时候会变成0HZ或者infHZ也就是无穷大
代码:
c
int BEIGNNUMBER = 0;
int ENDNUMBER = 0;
unsigned char STATETIM = 0;
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim){
//OLED_ShowString(0, "ok");
if(STATETIM == 0){
STATETIM ++;
BEIGNNUMBER = HAL_TIM_ReadCapturedValue(&htim3, TIM_CHANNEL_3);
__HAL_TIM_SET_CAPTUREPOLARITY(&htim3, TIM_CHANNEL_3, TIM_ICPOLARITY_FALLING);
}else if(STATETIM == 1){
STATETIM ++;
__HAL_TIM_SET_CAPTUREPOLARITY(&htim3, TIM_CHANNEL_3, TIM_ICPOLARITY_RISING);
}else if(STATETIM == 2){
STATETIM ++;
ENDNUMBER = HAL_TIM_ReadCapturedValue(&htim3, TIM_CHANNEL_3);
}
}
void Function_PluseShow(){
if(STATETIM == 3){
PLUSEVALUE = (int)(10000 * 1.0 / (ENDNUMBER - BEIGNNUMBER));
myprintf(2, " %dHZ ", PLUSEVALUE);
//myprintf(0, " %d ", ENDNUMBER - BEIGNNUMBER);
//myprintf(2, " %.1f ", (ENDNUMBER - BEIGNNUMBER) / 10.0);
STATETIM = 0;
HAL_Delay(200);
}
}
原因:
原因出在了我CUBMX中TIM3配置的预分频为3200 - 1也就是记一次数花费0.1ms
当脉冲频率足够大的时候也就是说单位时间的脉冲个数也会足够多,此时对于单个脉冲所占据的时间就会越小,以至于小于0.1ms,由于计数器记的数肯定是整数,然而单个脉冲持续时间小于0.1ms,那么计数器记的数只有0或者1,当计数器记的数为0也就是ENDNUMBER - BEIGNNUMBER
为0,也就造成了除法分母为0的操作,自然会出BUG
解决方法:
将预分频调成32 - 1也就是记录单个数耗费0.001ms那么脉冲自然而然稳定
c
void Function_PluseShow(){
if(STATETIM == 3){
PLUSEVALUE = (int)(1000000 * 1.0 / (ENDNUMBER - BEIGNNUMBER));
myprintf(2, " %dHZ ", PLUSEVALUE);
//myprintf(0, " %d ", ENDNUMBER - BEIGNNUMBER);
//myprintf(2, " %.1f ", (ENDNUMBER - BEIGNNUMBER) / 10.0);
STATETIM = 0;
HAL_Delay(200);
}
}
Function函数记得也要改一下