In one of my own recent projects, I found myself using the code for this in for a GameCube T3 joystick. After programming the micro controller, I ran into a pretty egregious problem. After going a certain distance on the joystick, it would somehow consistently end up going in the opposite direction than intended. This happened when going up on the Y axis, and when going left on the X axis.
So I spent a while trying to debug this and eventually I figured out there was an integer overflow that was happening somewhere in this function:
C:
static int16_t Map(int x, int inMin, int inMax, int outMin, int outMax) {
// Map a single value onto a different range
return (((x - inMin) * (outMax - outMin)) / (inMax - inMin)) +outMin;
}
I considered that the multiplication being used with a 16 bit integer could be leading to an overflow. So I modified the code to use a 32 bit integer for the multiplication here:
C:
static int16_t Map(int x, int inMin, int inMax, int outMin, int outMax) {
// Map a single value onto a different range
return (int16_t)(((int32_t)(x - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin);
}
Doing this fixed the problem. I figured there was likely an integer overflow happening since the joystick was just suddenly going from a fairly high positive value to an extremely high negative value. Pairing this with commenting out various bits of code and then testing helped me to figure out where the real issue was.
I'd like to thank
@Gman for helping me debug this. I've made him aware of the issue and he said he'll be updating the github repo soon to include this fix. From what I gathered, I wasn't the only person having this issue, so with any luck this should fix the problem once and for all.