Pressing joystick centers both x and y servo

Hi there.

May I please ask for help - I've messed up couple versions and back to the original.

I have a joystick (+button) controlling 2 servo's.

My joystick's switch pin is connected to digital 2.

I'm trying to get the servo's to center once the joystick button is pressed. Could someone please guide me into getting this to work?

Many many thanks

#include <Servo.h>

Servo myservo1;
Servo myservo2;

int a,b,X,Y;
int YAxis = 1;
int XAxis = 0;

void setup() {
Serial.begin(9600);
pinMode(XAxis, INPUT);
myservo1.attach(8);
pinMode(YAxis, INPUT);
myservo2.attach(9);
}

void loop() {

a=myservo1.read();
b=myservo2.read();
X=analogRead(XAxis);
Y=analogRead(YAxis);

if(X>550){
a=a-1;
myservo1.write(a);
delay(50);
}
if(X<450){
a=a+1;
myservo1.write(a);
delay(50);
}
if(Y>600){
b=b+1;
myservo2.write(b);
delay(50);
}
if(Y<450){
b=b-1;
myservo2.write(b);
delay(50);
}
}

Welcome to the forum

Today seems to be one of those where new users don't bother to read the advice that they are directed to when joining the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum

Try adding these lines...

Add this before setup()

int SELECT = 2; // connect SELECT (joystick button) to Digital pin 2

Add this inside setup()

  pinMode(SELECT, INPUT_PULLUP); // configure SELECT button for HIGH when not pressed, LOW when pressed

Add this inside loop()

  if (!digitalRead(SELECT)) { // LOW means button was pressed
    myservo1.write(90); // center myservo1
    myservo2.write(90); // center myservo2
  }

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.