Long long arithmetic optimisation.
I’m controlling the speed and position of a motor with great accuracy across a wide range of values. Although I have a solution that works it feels a little klunky.
The trouble of course is maintaining the precision of the calculation.
The important calculation is the Required Encoder Count at a point in time.
Therefore we have a known start time, and a known point in time, i.e. millis() , both these are unsigned longs of course, and the motor could run for several hours, so the full range of the unsigned long could be used, but overrun is not an issue. We run for hours, not days.
The rate the motor must move is also well defined. This is 2701 microseconds per tick.
Therefore , given the start time, the current millis() and the Rate (2701 us/tick) calculate the Required Ticks at a point in time.
Let us say that Duration = millis() – StartTime
Required ticks is simply given by
const float rate = 2.701
unsigned long duration;
unsigned long requiredTicks;
duration = millis() – StartTime;
requiredTicks = duration / Rate;
Which of course fails miserably on the last line: The 32 bit duration cannot be cast to a float, and the rate cannot be cast accurately as a long.
So we move onto
const unsigned long rate = 2701
unsigned long duration;
unsigned long requiredTicks;
duration = millis() – StartTime;
duration *= 1000;
requiredTicks = duration / Rate;
Which work fine for about an hour and then the duration will roll over.
What I ended up with that works fine for many hours
const unsigned long long rate = 2701
unsigned long long duration;
unsigned long requiredTicks;
duration = millis() – StartTime;
duration *= 1000;
requiredTicks = (long) (duration/rate);
However, using a long long sounds outrageously inefficient to me. I can’t help but think there is a better way, I just can’t see it...
