|
Re: Negative numbers?
You'll find that it's easier to work with the pwm values if at the beginning of your user code you copy the numbers into a signed char, manipulate those, and then at the end translate that back into the unsigned world. This eliminates all this 127 business, so for example you can simply halve your output by dividing by two.
This would look something like "signed char pwm01S = (signed char)pwm01 - 127;".
In the code you posted, it looks like both sections would have problems. You have to take into account two problems with calculations in programming: overflow and round-off error. Even if you know that the final value must fall within the proper range for the type that is expected, the intermediate values may be too extreme. Two chars multiplied by each other is not that safe - what if they're both 255? You get 65025, and even if you subtract 65000 right after that, you still overflowed and get unpredictable results from that point onward in the formula. The solution is to cast to a larger type - instead of "(p1_y - 127) * (p1_y - 127)" it would be "(int)(p1_y - 127) * (p1_y - 127)". The first term is promoted to an integer before multiplication, and the second value is implicitly promoted as well (at least I think; an integer times a smaller value should yield an integer).
Also, since you have a floating point number, you have to make sure it's treated as a float and not an int or char during calculations, using similar casts. Actually, because the float comes first in the formula, you may be in the clear - everything after it might get promoted to a float. I wouldn't be able to tell you without testing it right in front of my face.
To be safe, you can add in redundant casts all over the place for debug purposes. If that doesn't work, add a printf statement that outputs the values at different stages in the calculation, and find out where the discrepancy lies.
Remember that this is an integer processor, and floating point operations are implemented in software. You'll want to avoid calculations in floats when they can be performed using simpler types.
|