/*
* This Arduino Nano ESP32 code was developed by newbiely.com
*
* This Arduino Nano ESP32 code is made available for public use without any restriction
*
* For comprehensive instructions and wiring diagrams, please visit:
* https://newbiely.com/tutorials/arduino-nano-esp32/arduino-nano-esp32-joystick-servo-motor
*/
#include <Servo.h>
#define VRX_PIN A1 // The Arduino Nano ESP32 pin connected to VRX pin
#define VRY_PIN A0 // The Arduino Nano ESP32 pin connected to VRY pin
#define SERVO_X_PIN 6 // The Arduino Nano ESP32 pin connected to Servo motor 1
#define SERVO_Y_PIN 5 // The Arduino Nano ESP32 pin connected to Servo motor 2
Servo xServo; // create servo object to control a servo 1
Servo yServo; // create servo object to control a servo 2
void setup() {
Serial.begin(9600) ;
xServo.attach(SERVO_X_PIN);
yServo.attach(SERVO_Y_PIN);
}
void loop() {
// read X and Y analog values
int valueX = analogRead(VRX_PIN);
int valueY = analogRead(VRY_PIN);
int xAngle = map(valueX, 0, 4095, 0, 180); // scale it to the servo's angle (0 to 180)
int yAngle = map(valueY, 0, 4095, 0, 180); // scale it to the servo's angle (0 to 180)
xServo.write(xAngle); // rotate servo motor 1
yServo.write(yAngle); // rotate servo motor 2
// print data to Serial Monitor on Arduino IDE
Serial.print("Joystick: ");
Serial.print(valueX);
Serial.print(", ");
Serial.print(valueY);
Serial.print(" => Servo Motor: ");
Serial.print(xAngle);
Serial.print("°, ");
Serial.print(yAngle);
Serial.println("°");
}