Sunday, September 8, 2013

Interfacing a Joystick to an Arduino

We recently received a kit of sensors, and have started documenting how to use them. The sensor we are working with today is a joystick. This is a 2-axis unit with a push button on the shaft. There are two analog outputs, and one digital for the switch. At rest, the unit reads 512x512, with a 1 on the switch. The joystick can be pushed in all directions, with 0x1023, 0x512, 0x0, 512x0, 1023x512, 1023x1023, and 512x1023 at the extremes. Make sure you have your serial monitor speed set correctly. Please suggest practical projects based on this sensor, and we may build it!


Sensor Kit
Male to Female Jumper Kit


// Arduino pin numbers
const int SW_pin = 2; // digital pin connected to switch output
const int X_pin = 0; // analog pin connected to X output
const int Y_pin = 1; // analog pin connected to Y output

void setup() {
  pinMode(SW_pin, INPUT);
  digitalWrite(SW_pin, HIGH);
  Serial.begin(115200);
}

void loop() {
  Serial.print(digitalRead(SW_pin));
  Serial.print(" @ ");
  Serial.print(analogRead(X_pin));
  Serial.print("x");
  Serial.println(analogRead(Y_pin));
  delay(10);
}