Arduino Project
Joystick LED
Course Introduction
In this lesson, you will learn how to use Arduino along with Joystick Module, LEDs, and resistors to create a light play.
Note
If this is your first time working with an Arduino project, we recommend downloading and reviewing the basic materials first.
1.1 Install Arduino IDE(Important)
1.2 Introduction of Arduino IDE
Wiring

Common Connections:
LED
Connect the LEDs cathode to a 1kΩ resistor then to the negative power bus on the breadboard, and the LEDs anode to 2 to 5 on the Arduino.
Joystick Module
VRY: Connect to A1 on the Arduino.
VRX: Connect to A0 on the Arduino.
GND: Connect to breadboard’s negative power bus.
VCC: Connect to breadboard’s red power bus.
Writing the Code
Note
You can copy this code into Arduino IDE.
Don’t forget to select the board(Arduino UNO R4 Minima) and the correct port before clicking the Upload button.
// LED pin definitions
const int redLED = 4; // Represents negative X direction (X low)
const int yellowLED = 2; // Represents negative Y direction (Y low)
const int greenLED = 3; // Represents positive X direction (X high) →
const int blueLED = 5; // Represents positive Y direction (Y high)
// Joystick pin definitions
const int xPin = A0;
const int yPin = A1;
// Define the range for analog values and midpoint
const int MID_VAL = 512;
const int DEAD_ZONE = 100; // Dead zone range (adjust as needed)
void setup() {
pinMode(redLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(blueLED, OUTPUT);
// Initialize all LEDs to OFF
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, LOW);
digitalWrite(blueLED, LOW);
Serial.begin(9600);
}
void loop() {
int xVal = analogRead(xPin);
int yVal = analogRead(yPin);
Serial.print("X: "); Serial.print(xVal);
Serial.print(" Y: "); Serial.println(yVal);
// Turn off all LEDs
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, LOW);
digitalWrite(blueLED, LOW);
// Calculate the offset from the midpoint
int dx = xVal - MID_VAL;
int dy = yVal - MID_VAL;
// If the offset is within the dead zone, do not light up any LED
if (abs(dx) < DEAD_ZONE && abs(dy) < DEAD_ZONE) {
// No LEDs are turned on
} else {
// Consider both X and Y; select the direction with the larger offset
if (abs(dx) > abs(dy)) {
// X-axis has a larger offset, determine the direction
if (dx > 0) {
// Positive X direction => Turn on green LED (right)
digitalWrite(greenLED, HIGH);
} else {
// Negative X direction => Turn on red LED (left)
digitalWrite(redLED, HIGH);
}
} else {
// Y-axis has a larger offset, determine the direction
if (dy > 0) {
// Positive Y direction => Turn on blue LED (up)
digitalWrite(blueLED, HIGH);
} else {
// Negative Y direction => Turn on yellow LED (down)
digitalWrite(yellowLED, HIGH);
}
}
}
delay(100);
}
