static int Encoder_Count_Last = 0;static uint32_t Time_Last = 0;void Init_Encoder_Speed(void) { Encoder_Count_Last = TIM4->CNT;Time_Last = HAL_GetTick();}float Read_Encoder_Speed(void) { int Encoder_Count = TIM4->CNT; uint32_t Time = HAL_GetTick(); int Encoder_Diff = Encoder_Count - Encoder_Count_Last; if (Encoder_Diff > 0x7fff) { Encoder_Diff -= 0xffff; } else if (Encoder_Diff < -0x7fff) { Encoder_Diff += 0xffff; } float Speed = Encoder_Diff / 192.0f / ((Time - Time_Last) / 1000000.0f);Encoder_Count_Last = Encoder_Count;Time_Last = 时间;返回速度;}使用这段代码测速后将速度值通过串口打印到终端上后显示速度为inf怎么修改代码
时间: 2023-06-11 15:05:58 浏览: 102
Example_Encoder_IT.7z
这段代码中可能出现速度为inf的情况是因为除数为0,也就是时间间隔为0,导致计算出的速度为无穷大(inf)。
为了避免这种情况,你可以在计算速度之前先判断时间间隔是否为0,如果为0则将速度设置为0,如下所示:
```
float Speed;
int Encoder_Count = TIM4->CNT;
uint32_t Time = HAL_GetTick();
int Encoder_Diff = Encoder_Count - Encoder_Count_Last;
if (Encoder_Diff > 0x7fff) {
Encoder_Diff -= 0xffff;
} else if (Encoder_Diff < -0x7fff) {
Encoder_Diff += 0xffff;
}
float Time_Diff = (Time - Time_Last) / 1000000.0f;
if (Time_Diff == 0) {
Speed = 0;
} else {
Speed = Encoder_Diff / 192.0f / Time_Diff;
}
Encoder_Count_Last = Encoder_Count;
Time_Last = Time;
return Speed;
```
这样就可以避免出现速度为inf的情况了。
阅读全文