// Pin connections
const int joystickXPin = A0; // Joystick X-axis pin
const int joystickYPin = A1; // Joystick Y-axis pin
// Relay pins
const int upRelayPin = 9;
const int downRelayPin = 10;
const int leftRelayPin = 11;
const int rightRelayPin = 12;
// Thresholds for joystick direction detection
const int joystickThreshold = 500;
const int joystickOffset = 512;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set relay pins as output
pinMode(upRelayPin, OUTPUT);
pinMode(downRelayPin, OUTPUT);
pinMode(leftRelayPin, OUTPUT);
pinMode(rightRelayPin, OUTPUT);
}
void loop() {
// Read analog values from joystick axes
int joystickXValue = analogRead(joystickXPin);
int joystickYValue = analogRead(joystickYPin);
// Check joystick direction
if (joystickXValue > joystickOffset + joystickThreshold) {
activateRelay(rightRelayPin);
} else if (joystickXValue < joystickOffset - joystickThreshold) {
activateRelay(leftRelayPin);
} else {
deactivateRelay(rightRelayPin);
deactivateRelay(leftRelayPin);
}
if (joystickYValue > joystickOffset + joystickThreshold) {
activateRelay(downRelayPin);
} else if (joystickYValue < joystickOffset - joystickThreshold) {
activateRelay(upRelayPin);
} else {
deactivateRelay(downRelayPin);
deactivateRelay(upRelayPin);
}
// Print the joystick values
Serial.print("Joystick X: ");
Serial.print(joystickXValue);
Serial.print("\tJoystick Y: ");
Serial.println(joystickYValue);
// Delay for smooth operation
delay(50);
}
// Activate a relay
void activateRelay(int pin) {
digitalWrite(pin, HIGH);
}
// Deactivate a relay
void deactivateRelay(int pin) {
digitalWrite(pin, LOW);
}