auto calibrate zero for ps joystick

result is sent over a zigbee, everything's working fine, just feels like it could be more concise because I have more axises I want to control and this just feels clunky, especially if I have to do it 3 or more time per loop... oh and by the way were just controlling motion at this point...

The gist if you don't want to dl the .ino
the analog value (really really hoping it's at rest at this point) is captured in the setup loop, and mapped against a more granular output (0-5000), set as midpoint by virtue of a couple re-maps (0-setup val = map1 & setup val - 1023 = map2 combine map1&2 and map to less granular desired range)

How do I do this more efficiently... or am I just thinking wrong from the get go?

thanks in advance :slight_smile:

Ps2SticksSmall.ino (1.75 KB)

RTFM Okay got the code embed now...

/*
 The circuit:

Controller Pinout
1  Right Button    (Red Stripe)
2  Right X    A2
3  Right Y    A3
4  Gnd
5  VCC
6  Left X    A0
7  Left Y    A1
8  Left Button

Bottom View:
                    Red Stripe
[ ] [ ] [8] [6] [4] [2]
[ ] [ ] [7] [5] [3] [1]
  
 */
#include <SoftwareSerial.h>
SoftwareSerial xbee(2, 3); // RX, TX

const int JoyStick1x = A0;  // Analog input pin that the potentiometer is attached to

int JoyStick1xVal = 0;        // value read from the pot
int JoyStick1xOut = 0;        // mapped output
int temp1 = 0;                // Temp holders to calc top and bottom halves of the map
int temp2 = 0;                // etc...
int temp3 = 0;
int temp4 = 0;

void setup() {
  Serial.begin(9600); 
  xbee.begin(9600);
  temp3 = analogRead(JoyStick1x); // Grab a baseline to calibrate to
}

void loop() {

  JoyStick1xVal = analogRead(JoyStick1x);     // read the analog in value:
  temp1 = map(JoyStick1xVal, temp3, 1023, 0, 5000);    // map bottom half of range 
  temp2 = map(JoyStick1xVal, 0, temp3, 0, 5000)-5000;  // map top half of range 
  temp4 = temp1 + temp2;
  JoyStick1xOut = map(temp4,-10000 ,10000, 0, 100);
  xbee.write( JoyStick1xOut );  
  // print the results to the serial monitor:
  /* or dont if its slow in debug verbose...
  Serial.print("sensor 1X = " );                       
  Serial.print("\t");      
  Serial.print(JoyStick1xVal); 
  Serial.print("\t"); 
  
  Serial.print("\t output 1X = ");      
  Serial.print("\t");      
  Serial.print(temp1);
  Serial.print("\t");      
  Serial.print(temp2);
  Serial.print("\t"); 
  Serial.print(temp3);
  Serial.print("\t"); 
  Serial.print(temp4);
  Serial.print("\t");   
  */
  Serial.println(JoyStick1xOut); 

  // wait 200 milliseconds before the next loop
  delay(200);                     
}