This is a cut and paste job from our code last year. Thanks to Joe Johnson for giving us parts of the following code in New York two years ago when our drive system was horrible.
Just as a note, all of the numbers are in hexadecimal and shifting by X = dividing by 2^x. If you have no idea what I'm talking about, email me (or reply) and I'll explain. Sorry for the really obfuscated code, you'll probably want some free time to analyze it fully.
Alan's Highly Scalable/Complex Speed Balancer -- (MESSAGE FROM ALAN: I don't understand either ) If you are not him, here is my (Kai's) explanation.
First we must seperate the code into three easy to digest portions '"((abs(PWM1-$80)" gets us the distance we are trying to travel from neutral, the answer will be signed then we multiply that answer by "(13 + (3 * ((PWM1 - $80)) >> 15 )) >> 4 )". If we are going forward, we get a zero from "(3 * ((PWM1 - $80)) >> 15 )", if we are going reverse, we get a 3.
The number we get out of that (0 or 3) is added to 13 which is then multiplied to the desired speed (NOT velocity).
After multiplying by either 13 or 16, we shift by 4 which is effectively dividing by 16. Therefore, we lower (by 13/16) the speed is the motor is going forward and keep it the same if we are going in reverse.
The last step of "* (1 - ((PWM1 - $80) >> 15 << 1)) + $80) MIN $24 MAX $DE" allows us add direction into speed and make it work.
We are using this equation as the example: "PWM1 = ((abs (PWM1 - $80) * (13 + (3 * ((PWM1 - $80)) >> 15 )) >> 4 ) * (1 - ((PWM1 - $80) >> 15 << 1)) + $80) MIN $24 MAX $DE"
If we need to change the ratio, we need to find denominator which is a power of 2. Now we need the numerator and we need to find the difference between the numerator and denominator.
([numerator] + ([numerator - denominator] * ((PWM1 - $80)) >> 15 )) >> [denominator who is a integer power of 2 (ex. 2,4,8,16,32,64,etc)] )
Code:
PWM1 = (((abs (PWM1 - $80) * (13 + (3 * ((PWM1 - $80) >> 15)))) >> 4 ) * (1 - ((PWM1 - $80) >> 15 << 1)) + $80) MIN $24 MAX $DE
PWM2 = (((abs (PWM2 - $80) * (13 + (3 * ((PWM2 - $80) >> 15)))) >> 4 ) * (1 - ((PWM2 - $80) >> 15 << 1)) + $80) MIN $24 MAX $DE
-Kai Zhao