Control two servos SG-90 with a joystick

Hi everyone! =)
In this lesson i will tell you, how to make an interesting and easy project with Arduino, two microservos SG-90 and an analog joystick. Let’s go =)
Joystick is an analog input device, which has two potentiometers, a handle and a button. When you move the handle, the handle moves two potentiometers, and they send analog data to the Arduino microcontroller.
Your sketch will get data from joystick, compare it with gradus data for servos (compare joystick and servo, like this — 0-0, 1023-180), and send right data to servo. The Y gear of joystick makes data to one servo, the X gear of joystick makes data for another servo.
It’s important, you don’t need to add any libraries to your IDE, the sketch uses only one library, Servo.h, and it is already builtin in the IDE.
You can copy the code here:
#include <Servo.h>
// Creating servo objects
Servo servoX;
Servo servoY;
// Pin defenitions
const int joyX = A0; // X gear of joystick connected to A0 pin
const int joyY = A1; // Y gear of joystick connected to A1 pin
const int servoPinX = 5; // Servo X connected to pin D5 with PWM
const int servoPinY = 6; // Servo Y connected to pin D6 with PWM
void setup() {
// Attach servo objects to their pins
servoX.attach(servoPinX);
servoY.attach(servoPinY);
}
void loop() {
// Reading data from joystick
int xValue = analogRead(joyX);
int yValue = analogRead(joyY);
// Compairing data (0-180)
int angleX = map(xValue, 0, 1023, 0, 180);
int angleY = map(yValue, 0, 1023, 0, 180);
// Servo control
servoX.write(angleX);
servoY.write(angleY);
// A little delay for stability
delay(10);
}
Connecting scheme is below. It’s important to connect a powerful battery to servos, not to 5 volts on Arduino. Arduino’s builtin converter to 5v gives a little power, it is too small for motors. But I connected servos to Arduino’s 5 volts, and I connected 12 volts power to Arduino’s VIN pin, and servo work good.

Video-demonstration of this project:
(soon)