How to Use a Joystick with Serial Monitor

This project will show you how to use joystick with serial monitor.

Operation and uses

 

The joystick is similar to two potentiometers connected together, one for the vertical movement (Y-axis) and other for the horizontal movement (X-axis).

 

 

The potentiometers are variable resistances and, in a way, they act as sensors that provide us with varying voltage depending on their rotation.

Generally, joysticks are used in the military, leisure and aviation sectors.

 

Using the joystick pins

 

VCC

GND

VRx -> Variable resistance x

VRY -> Variable resistance Y

SW -> Switch / Button

Connection

MODULE -> ARDUINO

  • VCC -> 5V
  • GND -> GND
  • VRx -> A0
  • VRy -> A1
  • SW -> Pin 2
int VRx = A0;
int VRy = A1;
int SW = 2;

int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;

void setup() {
  Serial.begin(9600); 
  
  pinMode(VRx, INPUT);
  pinMode(VRy, INPUT);
  pinMode(SW, INPUT_PULLUP); 
  
}

void loop() {
  xPosition = analogRead(VRx);
  yPosition = analogRead(VRy);
  SW_state = digitalRead(SW);
  mapX = map(xPosition, 0, 1023, -512, 512);
  mapY = map(yPosition, 0, 1023, -512, 512);
  
  Serial.print("X: ");
  Serial.print(mapX);
  Serial.print(" | Y: ");
  Serial.print(mapY);
  Serial.print(" | Button: ");
  Serial.println(SW_state);

  delay(100);
  
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.