Pan/Tilt servo drifting?

I'm trying to make a pan/tilt system where there's a dead zone in the middle of a joystick, and moving it to the left or right makes a servo move up/down and left/right. My pan (x plane) servo works perfectly, and I tried to copy that code to the Y axis servo, but it jitters, drifts, and jumps erratically. Can anyone spot an error? Thanks!

#include <Servo.h>

int servoPos1 = 90; //starting pos for x 
int servoPos2 = 50; //starting pos for y
int joyStickPinx = A0; //x pin for joystick
int joyStickPiny = A1; //y pin for joystick
int refreshTime = 20;  // make this smaller to make servo move faster

Servo pan; //fairly obvious
Servo tilt;

void setup() {

  pan.attach(9); //setup
  tilt.attach(10);

}

void loop() {

  int joyReadx = analogRead(joyStickPinx); //read x joystick
  int joyReady = analogRead(joyStickPiny); //read y joystick
  joyReadx = map(joyReadx, 0, 1023, 3, -3); //map x values
  joyReady = map(joyReady, 0, 1023, 3, -3); //map y values
  servoPos1 += joyReadx; //honestly not sure of these two lines, they were in the code I copied
  servoPos2 += joyReady;
  constrain(servoPos1, 0, 180); //Assuming this is what holds the servos in position
  constrain(servoPos2, 0, 180);
  
  pan.write(servoPos1);
  tilt.write(servoPos2);

  delay(refreshTime);
  
}

How do you have the servos powered?
Can you draw up a wiring diagram and post it here?

Which servos do you have?

I can try to post a picture later, the servos are both Towerpro 9G, wired to 5V on a breadboard from an Arduino Uno

You don't have any deadband with that scheme, the joystick is jittering around 1 and -1, Serial.println() your ADC and joyReady readings to see what you're getting.

Icyartillary:
I can try to post a picture later, the servos are both Towerpro 9G, wired to 5V on a breadboard from an Arduino Uno

So you are using the 5V from the UNO?
You need to power 2 servos with a separate 5V supply for the servo units, the current required by the servos can be as high as 1A each, more than can be supplied through the PCB of the UNO.
Thanks.. Tom.. :slight_smile:

This is a good diagram. the 9v battery is pretty shortlived for this, but the servo power is illustrated well.

ServoDiagram.jpg