I am working in an embedded STM32F4 project and as a constraint i can only use integers.
I have already a working solution using floats.
#define TIMER_PERIOD 0.0000020833
float Get_Speed_Period(){
int tics = Get_Timer_Tics();
return tics * TIMER_PERIOD;
}
float Get_Rotation_Speed(float speed_period){
return (1 / speed_period * 64);
}
int main(){
float W = Get_Rotation_Speed ( Get_Speed_Period() );
return 0;
}
My goal is to only use integers. How can I achieve that ?
Thanks.
One quick note: you may wish to use a long long
datatype for a higher storage capacity (typically 8 bytes) depending on the size of the resulting integers you're calculating.
But if you use the functions the way you are, you are losing some of the optimizations you can make math-wise. Functionally you're doing this:
W = (1/(tics * timerperiod) * 64)
And if you simplify that math (note that your 64 ends up in the numerator -- if that's not what you wanted, then you need to reframe this some), you get:
W = 64 * (1/timerperiod) / tics
1/timerperiod = 1/0.000020833 = 4800.7680
W = 64 * 48000.7680 / tics
W = 64 * 48000.7680 / Get_Timer_Tics();
So then you can implement it using mostly integers:
long long W = 64 * 48000 / Get_Timer_Tics();
Note that I rounded the 48000 down since I suspect the original value was not 48001 and floating point math made it off by a bit.