Arduino Joystick Module Example




Schematic diagram

Arduino D8 ⟶ LED UP
Arduino D9 ⟶ LED DOWN
Arduino D10 ⟶ LED LEFT
Arduino D11 ⟶ LED RIGHT
Arduino D12 ⟶ LED SW

Arduino A0 ⟶  Y Axis of Joystick
Arduino A1 ⟶  X Axis of Joystick
Arduino D2  ⟶ sw of Joystick
Arduino 5V ⟶ VCC of Joystick
Arduino Gnd ⟶ Gnd of Joystick




Parts list

- Arduino UNO R3
- Joystick module
- Jumper wires
- Breadboard
- LED
- Resistor 220 ohm

Arduino Sketch


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

const int UP_LED_pin = 8;
const int DOWN_LED_pin = 9;
const int LEFT_LED_pin = 10;
const int RIGHT_LED_pin = 11;
const int SW_LED_pin = 12;

const int UD = 0;
const int LR = 0;
const int MID = 10;

int YAxisMid = 0;
int XAxisMid = 0;
int YAxis = 0;
int XAxis = 0;

void setup() {
  pinMode(SW_pin, INPUT);
  digitalWrite(SW_pin, HIGH);

  pinMode( SW_LED_pin, OUTPUT);
  pinMode( UP_LED_pin, OUTPUT);
  pinMode( DOWN_LED_pin , OUTPUT);

  pinMode( LEFT_LED_pin , OUTPUT);
  pinMode( RIGHT_LED_pin , OUTPUT);


  Serial.begin(9600);

  YAxisMid = analogRead(Y_pin);
  XAxisMid = analogRead(X_pin);

}

void loop() {
  /*
  Serial.print("Switch:  ");
  Serial.print(digitalRead(SW_pin));
  Serial.print("\n");
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pin));
  Serial.print("\n");
  Serial.print("Y-axis: ");
  Serial.println(analogRead(Y_pin));
  Serial.print("\n\n");
 */
  YAxis = analogRead(Y_pin);
  XAxis = analogRead(X_pin);

  digitalWrite( SW_LED_pin , !digitalRead(SW_pin));

  chkUpDown(YAxis);
  chkLeftRight(XAxis);

 // delay(500);
}
void chkUpDown( int Y)
{
    if(Y < YAxisMid - MID){
 
    digitalWrite(UP_LED_pin, HIGH);

  }else{

    digitalWrite(UP_LED_pin, LOW);

  }

  if(Y > YAxisMid + MID){
 
    digitalWrite(DOWN_LED_pin, HIGH);

  }else{

    digitalWrite(DOWN_LED_pin, LOW);

  }
}

void chkLeftRight( int X)
{
    if( X > XAxisMid + MID){
 
    digitalWrite(LEFT_LED_pin, HIGH);

  }else{

    digitalWrite(LEFT_LED_pin, LOW);

  }

  if(X < XAxisMid - MID){
 
    digitalWrite(RIGHT_LED_pin, HIGH);

  }else{

    digitalWrite(RIGHT_LED_pin, LOW);

  }
}

ความคิดเห็น