Arduino Uno

prototype shield

Corner
-->

Analog joystick

I found this joystick at the recycling center, but the cable was cut off, so I had to test all pins in order to determine which one correspond to what function. For the main stick, it used two potentiometers but I had to solder one more wire to make them work. I took all necessary information from the official Arduino joystick page, but I adapted the code.

Code

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
 * The program read the values from the joystick (analog inputs!),
 * performs some auto-callibration and outputs X and Y as of an
 * intervall [-10,10].
 */

int joyPinX = 1;                 // X pin
int joyPinY = 0;                 // Y pin
int value = 0;                   // variable to hold the actual reading 
int xmin = 200;                  // X minimum value
int xmax = 800;                  // X maximum value
int ymin = 200;                  // Y minimum value
int ymax = 800;                  // Y maximum value
int xzero = 0;                   // the first X value (don't touch the joystick at startup!)
int yzero = 0;                   // the first Y value
int segs = 20;                   // number of intervalls to consider par half direction
double zerohold = 4;             // number of intervalls to consider as "zero position" 

void setup() 
{
  Serial.begin(115200);

  // do the first reading  
  yzero = analogRead(joyPinY);  
  xzero = analogRead(joyPinX);  
}



void loop() 
{
  // read the X value
  value = analogRead(joyPinX);   
  // push limits
  if(value<xmin) xmin=value;
  else if (value>xmax) xmax = value;
  // start at zero
  int x = 0;
  // divide lower half
  int seg = (xzero-xmin)/(segs+zerohold);
  // find what segment we are in
  for(int i=0;i<segs+1;i++)
  {
    if (value>=xzero-((segs-i)+zerohold)*seg) x=i;
  }
  // devide upper part
  seg = (xmax-xzero)/(segs+zerohold);
  // find what segment we are in
  for(int i=segs+1;i<2*segs+1;i++)
  {
     if (value>=xzero+((i-segs-1)+zerohold)*seg) x=i;
  }
  // make X range from [-10,10] instead of [0,20]
  x-=segs;
  // invert X
  x=-x;

  // the same as before but with "Y" :-)
  value = analogRead(joyPinY);   
  if(value<ymin) ymin=value;
  else if (value>ymax) ymax = value;
  int y = 0;
  seg = (yzero-ymin)/(segs+1);
  for(int i=0;i<segs+1;i++)
  {
    if (value>=yzero-((segs-i)+1)*seg) y=i;
  }
  seg = (ymax-yzero)/(segs+zerohold);
  for(int i=segs+1;i<2*segs+1;i++)
  {
    if (value>=yzero+((i-segs-1)+zerohold)*seg) y=i;
  }
  y-=segs;

  // print if on the screen
  Serial.print("X = ");
  Serial.print(x);
  Serial.print("  -  Y = ");
  Serial.println(y);

  // wait some time
  delay(100);
}

Links

 Arduino Joystick