Our motor control code is not detecting Xbox input

Our code that gets axis informations from Xbox controller and sets motor speed based on that infos are not working, here is the code:

package frc.robot;

import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.motorcontrol.PWMTalonSRX;
import edu.wpi.first.wpilibj.motorcontrol.PWMVictorSPX;
import edu.wpi.first.wpilibj.XboxController;

/**
 * The VM is configured to automatically run this class, and to call the functions corresponding to
 * each mode, as described in the TimedRobot documentation. If you change the name of this class or
 * the package after creating this project, you must also update the build.gradle file in the
 * project.
 */
public class Robot extends TimedRobot{

  PWMTalonSRX talon = new PWMTalonSRX(0);
  PWMVictorSPX victor = new PWMVictorSPX(1);
  XboxController controller = new XboxController(0);

  double leftAxis = controller.getLeftX();
  double  rightAxis = controller.getLeftY();
  double motorPower = leftAxis+(rightAxis*-1);
  
  @Override
  public void teleopPeriodic() {
    
    talon.set(motorPower);
    victor.set(motorPower);
    System.out.println(motorPower);

  }

From what I can see, motorPower is only set when the TimedRobot class is created. If you want to be able to move your motor while in Teleop, you need to update leftAxis, rightAxis, and motorPower in teleopPeriodic.

Thanks, that really worked! But as I remember, we defined axises out of the TeleOperated before. Did that changed or I remembered wrong?

You’re likely misremembering.

Controller axis/button state getter methods only return the “current” value. Written how you do above, this is then stored in your motorPower class member variable but never updated. So when you use that variable, it always has the same value (0.0 based on when it ran).

You could keep it at the class level and simply update the value in teleopPeriodic… or you wrap it in a supplier object and get that value in teleopPeriodic. There are reasons you might want to do that, but neither of those approaches make much sense for the code you’ve shared and only add complexity with minimal benefit.

1 Like