Code: Select all
// Analog Stick Calibration
//Remap the data range
mapX=map(analogRead(23),185, 839, 0, 1023); //I used dxtweak2 on Windows to read at the minimum and maximum values of my stick (X: min=185, max=839, Y: min=125, max=830)
mapY=map(analogRead(22),125, 830, 0, 1023); //and remapped them to the absolute maximum and minimum values for analog output.
//Deadzones
if(mapX<512+deadzone&&mapX>512-deadzone)mapX=512;
if(mapY<512+deadzone&&mapY>512-deadzone)mapY=512;
if(mapX<24)mapX=0;
if(mapY<24)mapY=0;
//Non-linear correction.
// This changes the sticks behaviour from linear acceleration to "exponential". Small stick movements result in slower movement,
// while great movement results in faster movement. This way the stick is more accurate for fine movements, but loses some of its range.
mapX=(int)(0.00000302*mapX*mapX*mapX-0.004631*mapX*mapX+2.577*mapX+1.23);
if(mapX>1023) mapX=1023;
if(mapX<0) mapX=0;
mapY=(int)(0.00000302*mapY*mapY*mapY-0.004631*mapY*mapY+2.577*mapY+1.23);
if(mapY>1023) mapY=1023;
if(mapY<0) mapY=0;
//Send final values
Joystick.X(mapX);
Joystick.Y(mapY);
Visualization of the non-linear calibration. The function I used in the code is a more accurate fit using MATHLAB. Dont use this formula! The stick would be at 561 (off-center) in rest position.