joystick with 12v motors

Hi
I was trying to control a 12v gear motors using an Arduino and a joystick, I have written the code and tested it with2 stepper motors connect with an easydriver board and worked flawlessly. However, I tried to do the same with the gear motors that are connected to an L298 driver but unfortunately, I couldn’t get it to work properly. When I move the joystick (X-axis) to the back the motors move but when moving the joystick forward (x-axis ) the motors do not move at all. Here is the code:

int motor1pin1 = 2;
int motor1pin2 = 3;
int motor2pin1 = 4;
int motor2pin2 = 5;

//joystick 
int Xpin=A0;
int Ypin=A1;
int Xvalue;
int Yvalue;

void setup(){
  Serial.begin(9600);

  pinMode(motor1pin1, OUTPUT);
  pinMode(motor1pin2, OUTPUT);
  pinMode(motor2pin1, OUTPUT);
  pinMode(motor2pin2, OUTPUT);
  
  //set joystick to be input 
    pinMode(Xpin,INPUT);
    pinMode(Ypin,INPUT);
}

void loop(){
  //read the values of the joystick 
    Xvalue=analogRead(Xpin);
    Yvalue=analogRead(Ypin);

   if(Xvalue>500){ //backward 
  digitalWrite(motor1pin1, HIGH);
  digitalWrite(motor1pin2, LOW);

  digitalWrite(motor2pin1, HIGH);
  digitalWrite(motor2pin2, LOW);
}

   if(Xvalue<50){ //backward 
  digitalWrite(motor1pin1, LOW);
  digitalWrite(motor1pin2, HIGH);

  digitalWrite(motor2pin1, LOW);
  digitalWrite(motor2pin2, HIGH);
}

   else { //backward 
  digitalWrite(motor1pin1, LOW);
  digitalWrite(motor1pin2, LOW);

  digitalWrite(motor2pin1, LOW);
  digitalWrite(motor2pin2, LOW);
} 

}

I tried to used (if) statement followed by (else if) and then (else) and the motors kept moving forward even though the joystick no touched, and the move backwards when moving the joystick backwards, but I don’t want this I want them off when the joystick not touched and normally move forward and backwards based on the value of joystick.

I also tried to change the axis and use the y-axis but the same results occurred.

I will really appreciate your help and guidance.

Put some Serial.reads in to see what actual values you are getting from the joysticks. Normally centred is somewhere around 512. with full one way around 0 and full the other way around 1023

Why do all your comments say 'backward'?

Steve

You compare forward to >500 and backward to <50
I imagine that 50 should be 500.

I have finally get it to work I used two variable for the joystick one was used to move the motors forward and the other for backward movement and worked just fine.Thank you for your reply.