Advertisement
Guest User

Untitled

a guest
Sep 29th, 2017
483
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. #include <Joystick.h>
  2.  
  3. const bool DEBUG = true;  // set to true to debug the raw values
  4.  
  5. int xPin = A2;
  6. int yPin = A3;
  7. int xAxis = 0;
  8. int yAxis = 0;
  9. int xZero,yZero,xValue,yValue;
  10. int xMax = 200;
  11. int yMax = 200;
  12. int xMaxNeg = -200;
  13. int yMaxNeg = -200;
  14. int deadzone = 25;  // smaller values will be set to 0
  15.  
  16. void setup(){
  17.     pinMode(xPin, INPUT);
  18.     pinMode(yPin, INPUT);
  19.  
  20.     if(DEBUG) {
  21.         Serial.begin(9600);
  22.     }
  23.  
  24.     // calculate neutral position
  25.     xZero = analogRead(xPin);
  26.     yZero = analogRead(yPin);
  27.  
  28.     Joystick.begin();
  29. }
  30.  
  31. void loop(){
  32.     xValue = analogRead(xPin) - xZero;
  33.     yValue = analogRead(yPin) - yZero;
  34.  
  35.     // determine Max values for further calculations.
  36.     // we have to differentiate between positive and negative values, as they have
  37.     // different max values (depends on the determined middle (rest) position, which is dynamic).
  38.     // we also dont even know what max values we can have, those have to be observed and re-calculated during runtime
  39.     if (xValue > xMax)
  40.         xMax = xValue;
  41.     if (yValue > yMax)
  42.         yMax = yValue;
  43.     if (xValue < xMaxNeg)
  44.         xMaxNeg = xValue;
  45.     if (yValue < yMaxNeg)
  46.         yMaxNeg = yValue;
  47.  
  48.     // negative xAxis = left
  49.     if (xValue < 0)
  50.     {
  51.         if(xValue > deadzone * -1)
  52.             xValue = 0;
  53.     }
  54.     // positive xAxis = right
  55.     if (xValue > 0)
  56.     {
  57.         if(xValue < deadzone)
  58.             xValue = 0;
  59.     }
  60.  
  61.     // negative yAxis = up
  62.     if (yValue < 0)
  63.     {
  64.         if(yValue > deadzone * -1)
  65.             yValue = 0;
  66.     }
  67.     // positive yAxis = down
  68.     if (yValue > 0)
  69.     {
  70.         if(yValue < deadzone)
  71.             yValue = 0;
  72.     }
  73.  
  74.     xAxis = map(xValue, xMaxNeg, xMax, -127, 127);
  75.     yAxis = map(yValue, yMaxNeg, yMax, -127, 127);
  76.  
  77.     if(DEBUG && (xValue != 0 || yValue != 0)) {
  78.         Serial.print("X: ");
  79.         Serial.println(xValue);
  80.         Serial.print("Y: ");
  81.         Serial.println(yValue);
  82.     }
  83.  
  84.     // Send to USB
  85.     Joystick.setXAxis(xAxis);
  86.     Joystick.setYAxis(yAxis);
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement