Here is my code, throttle comes out to -18 when I run the program, and when I do the math I get 77.941... which is what I'm looking for. I am programming it on an Atmega 328P using Arduino IDE on Windows 10.
The following example prints -18 and according to my calculations it should be 77.941:
int throttle = (((800 - 270) * 100) / 680);
Serial.println(throttle);
This is the visualized code:
throttle = (((throttleSensor - oldMinValue) * (newMax - newMin)) / (oldMax - oldMin));
I am trying to do this, Convert a number range to another range, maintaining ratio
Also, I should add, it works fine when the result is below 47, above that it flips to a negative number.
The short answer is, (800 - 270) * 100
= 53000. which is too large a number for the space that was allocated for the calculation results, integer overflow.
so changing the code from this...
int throttle = (((800 - 270) * 100) / 680);
to this...
long largeValue = 100;
int throttle = (((800 - 270) * largeValue) / 680);
fixes the problem. The number 100
or value of (newMax - newMin)
has to be a "long" or the processor will miscalculate. Someone, please correct me on this if need be or post a better answer if you got one. Also if someone has a better suggestion for the title so it can be easier found for future people with the same problem, go ahead and commend it below.
Thanks to the StackOverflow community for helping me solve this issue!