Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Joystick.h>
- const bool DEBUG = true; // set to true to debug the raw values
- int xPin = A2;
- int yPin = A3;
- int xAxis = 0;
- int yAxis = 0;
- int xZero,yZero,xValue,yValue;
- int xMax = 200;
- int yMax = 200;
- int xMaxNeg = -200;
- int yMaxNeg = -200;
- int deadzone = 25; // smaller values will be set to 0
- void setup(){
- pinMode(xPin, INPUT);
- pinMode(yPin, INPUT);
- if(DEBUG) {
- Serial.begin(9600);
- }
- // calculate neutral position
- xZero = analogRead(xPin);
- yZero = analogRead(yPin);
- Joystick.begin();
- }
- void loop(){
- xValue = analogRead(xPin) - xZero;
- yValue = analogRead(yPin) - yZero;
- // determine Max values for further calculations.
- // we have to differentiate between positive and negative values, as they have
- // different max values (depends on the determined middle (rest) position, which is dynamic).
- // we also dont even know what max values we can have, those have to be observed and re-calculated during runtime
- if (xValue > xMax)
- xMax = xValue;
- if (yValue > yMax)
- yMax = yValue;
- if (xValue < xMaxNeg)
- xMaxNeg = xValue;
- if (yValue < yMaxNeg)
- yMaxNeg = yValue;
- // negative xAxis = left
- if (xValue < 0)
- {
- if(xValue > deadzone * -1)
- xValue = 0;
- }
- // positive xAxis = right
- if (xValue > 0)
- {
- if(xValue < deadzone)
- xValue = 0;
- }
- // negative yAxis = up
- if (yValue < 0)
- {
- if(yValue > deadzone * -1)
- yValue = 0;
- }
- // positive yAxis = down
- if (yValue > 0)
- {
- if(yValue < deadzone)
- yValue = 0;
- }
- xAxis = map(xValue, xMaxNeg, xMax, -127, 127);
- yAxis = map(yValue, yMaxNeg, yMax, -127, 127);
- if(DEBUG && (xValue != 0 || yValue != 0)) {
- Serial.print("X: ");
- Serial.println(xValue);
- Serial.print("Y: ");
- Serial.println(yValue);
- }
- // Send to USB
- Joystick.setXAxis(xAxis);
- Joystick.setYAxis(yAxis);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement