where am I going wrong with this ps2 Library?

I am making a robot that will be controlled using a ps2 controller along with an Arduino mega 2560.what I was trying to do is that i would be able to control the no of steps a stepper motor would go on the press of a button on the controller,and also turn in the opposite direction on press of another button. I made a code ,but it seems to have stuck up in a loop and it shows up in serial monitor as buttons are being pressed even when i am not touching the controller! I am posting the code can someone point out to me where have I gone wrong or any other possible place where I could've done better?

#include <PS2X_lib.h>  //for v1.6
#include <L293.h>      //fr the motors at base 
#include <Servo.h>
#include <Stepper.h>         //for Stepper motor

PS2X ps2x;


int error = 0;       // for 
byte type = 0;       //PS2
byte vibrate = 0;   //controller



const int DPIN_MOTORA_DIRECTION = 12;     //Motor A Direction
const int DPIN_MOTORA_SPEED = 3;          //Motor A Speed
const int DPIN_MOTORA_BRAKE = 9;          //Motor A Brake
//const int APIN_MOTORA_CURRENT = 0;        //Motor A Current Sensing (Not used in this program)
const int DPIN_MOTORB_DIRECTION = 13;     //Motor B Direction
const int DPIN_MOTORB_SPEED = 11;         //Motor B Speed
const int DPIN_MOTORB_BRAKE = 8;          //Motor B Brake
//const int APIN_MOTORB_CURRENT = 1;        //Motor B Current Sensing (Not used in this program)
const int DPIN_MOTOR_MODE_LED = 10;       //Motor mode indicator LED
const int STEPS_PER_REVOLUTION = 48;      //Steps per revolution (360/7.5 deg.)
const int MOTOR_MAX_RPM = 15;             //Max RPMs for motor
const int DELAY_LENGTH = 50;              //Delay in ms for each iteration ofloop 
Stepper stepper(STEPS_PER_REVOLUTION, DPIN_MOTORA_DIRECTION, DPIN_MOTORB_DIRECTION); //Stepper object for motor control
byte ok = false;                                                                     //ok is true if program is okay to run, false if not
byte motorMode = false;                                                              //True if motor is enabled, false otherwise
byte smallRumble;                                                                    //True if small rumble motor should run
byte rumble = 0;                                                                     //Vibrate speed of big rumble motor
int leftJoyXNeutralStart = 0;                                                        //Begining of neutral zone for left joystick
int leftJoyXNeutralEnd = 0;                                                          //End of neutral zone for left joystick



L293 robo(22,23,5,24,15,6); // for
int velocityrobo = 60;     // basemotor motiob ,oin 5 and 6 not used

int pos = 0;
Servo myservo;

int LS1a = 32; 
int LS1b = 33;
int LS2a = 34;
int LS2b = 35;
int LS3a = 36;
int LS3b = 37;
int LS4a = 38;
int LS4b = 39; // for lead screws 4 motors x 2 outputs each

void setup() {

  Serial.begin(57600);
  error = ps2x.config_gamepad(13,11,10,12, false, false); 

  if(error == 0){
   { Serial.println("Found Controller, configured successful");
    Serial.println("Try out all the buttons, X will vibrate the controller, faster as you press harder;");
   }
   //Set pin modes
  pinMode(DPIN_MOTORA_DIRECTION, OUTPUT);
  pinMode(DPIN_MOTORA_SPEED, OUTPUT);
  pinMode(DPIN_MOTORA_BRAKE, OUTPUT);
  pinMode(DPIN_MOTORB_DIRECTION, OUTPUT);
  pinMode(DPIN_MOTORB_SPEED, OUTPUT);
  pinMode(DPIN_MOTORB_BRAKE, OUTPUT);
  pinMode(DPIN_MOTOR_MODE_LED, OUTPUT);
  

  
  //Turn motor brakes off (should be off anyways, just being sure)
  digitalWrite(DPIN_MOTORA_BRAKE, LOW);
  digitalWrite(DPIN_MOTORB_BRAKE, LOW);
  
  //Setup PS2 controller
  int error = ps2x.config_gamepad(7,5,4,6, true, true);
  byte controllerType = ps2x.readType();

  if (controllerType == 1 && error == 0)
  {
    ok = true;}}


/*
  Main program loop
*/
}
void loop() {
  ps2x.read_gamepad(false, vibrate);

  if(ps2x.Button(PSB_PAD_RIGHT))
  {
    robo.forward_2W(velocityrobo,velocityrobo);
    Serial.println("robot ---------------->");
  }

  if(ps2x.ButtonReleased(PSB_PAD_RIGHT))
  {
    robo.stopped_2W();
    Serial.println("robot stopped");
  }
  if(ps2x.Button(PSB_PAD_LEFT))
  {
    robo.back_2W(velocityrobo,velocityrobo);
    Serial.println("<------------- robot");
  }
  if(ps2x.ButtonReleased(PSB_PAD_LEFT)){
    robo.stopped_2W();
    Serial.println("robot stopped");
  }


  // //////////////////////////////////////////////end of base motor code ////////////////////////////////////////////

  if (ps2x.Analog(PSS_LY) >= 189) 
  {
    digitalWrite(32,HIGH);
    digitalWrite(33,LOW);
    Serial.println("LY CW works");
  }

  if(ps2x.Analog(PSS_LY) <= 60)
  {
    digitalWrite(32,LOW);
    digitalWrite(33,HIGH);
    Serial.println("LY CCW works");
  }
  if(ps2x.Analog(PSS_LX) >= 189)
  {
    digitalWrite(34,HIGH);
    digitalWrite(35,LOW);
    Serial.println("LX CW works");
  }
  if(ps2x.Analog(PSS_LX) <= 60)
  {
    digitalWrite(34,LOW);
    digitalWrite(35,HIGH);
    Serial.println("LX CCW works");
  }
  if (ps2x.Analog(PSS_RY) >= 189) 
  {
    digitalWrite(36,HIGH);
    digitalWrite(37,LOW);
    Serial.println("RY CW works");
  }

  if(ps2x.Analog(PSS_RY) <= 60)
  {
    digitalWrite(36,LOW);
    digitalWrite(37,HIGH);
    Serial.println("RY CCW works");
  }
  if (ps2x.Analog(PSS_RX) >= 189) 
  {
    digitalWrite(38,HIGH);
    digitalWrite(39,LOW);
    Serial.println("RX CW works");
  }

  if(ps2x.Analog(PSS_RX) <= 60)
  {
    digitalWrite(38,LOW);
    digitalWrite(39,HIGH);
    Serial.println("RX CCW works");
  }
  //////////////////////////////////////////leadscrew program end///////////////////////////////////////////
 ps2x.read_gamepad((rumble > 0), rumble);
    
    //See if motor position should move.  First, check DPADs, then left Joystick, and finally L1/R1.
    //DPAD and Joystick will move motor at variable speed (if supported by controller) and L1/R1 are precision
    //movement - push to move a single step in either direction.
    
    if(motorMode && ps2x.ButtonPressed(PSB_RED))
      //L1 move motor one step to left
      ButtonMoveMotor(255, 5);
          Serial.println("++ 5 steps");

     if(motorMode && ps2x.ButtonPressed(PSB_PINK))
      //R1 move motor one step to right
      ButtonMoveMotor(255, -5);
       Serial.println("--5 steps");

  
  
  delay(DELAY_LENGTH);
}
void ButtonMoveMotor(int pressure, int steps)
{
  int motorSpeed;
  
  if (pressure > 0)
      {
        //Use pressure reading to control speed and rumble
        motorSpeed = map(pressure, 0, 255, 1, MOTOR_MAX_RPM);
        rumble = pressure;
        Serial.println("pressure max values");
      }
      else
      {
        //No pressure reading, use max values
        motorSpeed = MOTOR_MAX_RPM;
        rumble = 255;
          

      stepper.setSpeed(motorSpeed);
      stepper.step(steps);
      }}

Because it's a pretty big chuck of code I'm doubting anybody without the setup is willing to sift to the code to find the bug. (I certainly am no...). So let me give you some advise. Start debugging :slight_smile: Go back to the basics. Command out code you don't really need to check the PS2 controller working etc. Go back (by commenting out the rest) to just receiving the commands from the controller and sending them to serial monitor. From there, add back new pieces one at a time and see when it stops doing what you want/expect. Then you have narrowed it down quite a bit!

int LS4b = 39; // for lead screws 4 motors x 2 outputs each

Where are the completely useless, misleading, comments for the other LSnx variables?

 error = ps2x.config_gamepad(13,11,10,12, false, false);

What do the arguments to that method mean? They look suspiciously like pin number - the same pin numbers that you have your motors connected to.

I'm doubting anybody without the setup is willing to sift to the code to find the bug.

It really wasn't that hard.

Okay! Tried doing exactly as you said. Seems I configured the pins twice in the same code ...that was the reason for those erratic values in serial monitor. Thanks though

error = ps2x.config_gamepad(13,11,10,12, false, false);

and here again

  int error = ps2x.config_gamepad(7,5,4,6, true, true);

@paulS Thanks for going through the code .
The comment was for other people in my project team to understand the working better

int LS4b = 39; // for lead screws 4 motors x 2 outputs each

and yes those numbers are pin numbers , and the other two values are for pressure sensitivity and rumble feature of the dualshock 2 controller

error = ps2x.config_gamepad(13,11,10,12, false, false);

The comment was for other people in my project team to understand the working better

// Comments can go before a block of statements.
// Putting comments about the number of things that
// need to be defined, and valued, BEFORE the code
// makes sense.

int youShoudlHaveEightVariablesWithValues; // Putting them after the last line of code does not.

Okay @paulS will make sure I comment the code properly the next time I post it again. :slight_smile:
I have one more problem . I need to control the speed of a spinning motor on my robot by varying the duty cycle (PWM),but i want to increase the speed by pressing one button on the PS2 controller and decrease by pressing another button.But i just dont know where to start . can you help ?

But i just dont know where to start

Can you detect when one of the switches BECOMES pressed (not IS pressed)? The state change detection example shows how.

When you can do that, incrementing a variable (duty cycle) or decrementing it when the appropriate switch changes state is trivial.

If you want to press the switch, and have the variable increment or decrement while the switch is held down, you need to define how often the change should happen.

Is this correct ? can't test it until tomorrow ,because i don't have the arduino and other stuff with me right now!

#include <PS2X_lib.h> //library for th PS2 controller ,By Bill Porter

int value   = 0 ; //variable to store the PWM value
const int spinpin = 8; // defined pin 8 for the motor 
 PS2X ps2x;     //call the ps2 Library to initialise the controller
void setup()
{
pinMode(spinpin,OUTPUT);// set the pin 8 as output
}
void loop()
{

if (ps2x.NewButtonState(PSB_L1)) // (ps2x.NewButtonState(PSB_L1)) is true if the button l1 changes i.e. either pushed or released
{ 
  if (value < 255); // so variable does not go beyond max scale of analogWrite 
    value++;         // to increase the value of variable
  }
    


if (ps2x.NewButtonState(PSB_R1))
 { 
    if (value > 0); //so variable does not go beyond min scale of analogWrite 
    
      value--; // to decrease value of variable
      
 }
  analogWrite(spinpin,value); // write the value to the pin
  }
int value   = 0 ; //variable to store the PWM value

Why not use a name that you'll instantly recognize the meaning of, like pwmDutyCycle?

if (ps2x.NewButtonState(PSB_L1)) // (ps2x.NewButtonState(PSB_L1)) is true if the button l1 changes i.e. either pushed or released
{
  if (value < 255); // so variable does not go beyond max scale of analogWrite
    value++;         // to increase the value of variable
  }

Why
not
properly
indent
your
code?

Tools + Auto Format makes it so easy...

    if (value > 0); //so variable does not go beyond min scale of analogWrite

If the value is greater than 0, do nothing. Otherwise, do nothing. Why bother testing?

The ; on the end of that statement IS the body of the statement. It means no-op - do nothing.

  analogWrite(spinpin,value); // write the value to the pin

It would certainly be more useful to call this function if the motor were connected to a pin capable of PWM.

Pressing the switch 255 times to get the motor up to full speed or down to a stop is going to wear your thumbs out. Perhaps you should consider a somewhat larger step.

@PaulS yes I do intend to increase those steps , and also intend my code properly. And I guess digital pin 7 on Arduino mega2560 is PWM capable.
The ";" seems like a mistake though thanks for pointing it out.