#include <Servo.h>
#define X_PIN A0 // HORIZ
#define Y_PIN A1 // VERT
#define SERVO_X_PIN 2 // Servo 1
#define SERVO_Y_PIN 3 // Servo 2
Servo xServo; // create servo object to control Servo 1
Servo yServo; // create servo object to control Servo 2
int oldX = 512, oldY = 512; // to compare with new readings to move servos only on change
void setup() {
Serial.begin(9600) ;
xServo.attach(SERVO_X_PIN);
yServo.attach(SERVO_Y_PIN);
Serial.println("Press the joystick Up/Down/Left/Right");
delay(500);
}
void loop() {
// read analog X and Y analog values
int xValue = analogRead(X_PIN);
int yValue = analogRead(Y_PIN);
if (xValue != oldX || yValue != oldY) {
moveServos(xValue, yValue);
oldX = xValue;
oldY = yValue;
}
}
void moveServos(int xValue, int yValue) {
int xAngle = map(xValue, 0, 1023, 180, 0); // servo angle (0 to 180)
int yAngle = map(yValue, 0, 1023, 0, 180); // servo angle (0 to 180)
xServo.write(xAngle); // rotate servo motor 1
yServo.write(yAngle); // rotate servo motor 2
Serial.print("JoystickX: ");
spacepad(xValue);
Serial.print(xValue);
Serial.print(" ServoX:");
spacepad(xAngle - 90);
Serial.print(xAngle - 90);
Serial.print("° ");
Serial.print("JoystickY: ");
spacepad(yValue);
Serial.print(yValue);
Serial.print(" ServoY:");
spacepad(yAngle - 90);
Serial.print(yAngle - 90);
Serial.println("°");
// delay(200);
}
void spacepad(int value) {
if (value < 1000)
Serial.print(" ");
if (value < 100 && value >= 0)
Serial.print(" ");
if (value < 10 && value >= 0)
Serial.print(" ");
}