wiki:ControlSystems/SoftwareTeam/Training/GettingStarted/Autonomous/PWM

Modify the generated code as follows:

  • Add the following imports:
       import edu.wpi.first.wpilibj.Encoder;
       import edu.wpi.first.wpilibj.Talon;
    
  • Declare variables for the Encoder and Talon (motor controller) objects in the Robot class
       private Talon leftMotor, rightMotor;
       private Encoder leftEncoder, rightEncoder;
    
  • In robotInit() instantiate the Encoder and Motor objects
       // Quadrature encoder has A and B channels connected to DIO0,1, DIO2,3
       leftEncoder = new Encoder(0, 1);
       rightEncoder = new Encoder(2, 3, true); // right side direction is reversed
       // Peanut wheels are 7.5" in diameter
       // Encoders provide 1 count per degree of rotation
       leftEncoder.setDistancePerPulse((3.141592*7.5)/360);
       rightEncoder.setDistancePerPulse((3.141592*7.5)/360);
       // PWM motor controllers connected to PWM0, PWM1
       leftMotor = new Talon(0);
       rightMotor = new Talon(1);
       // right side must turn in opposite direction
       rightMotor.setInverted(true);
    
  • In robotPeriodic() display the encoder values:
      SmartDashboard.putNumber("Left", leftEncoder.getDistance());
      SmartDashboard.putNumber("Right", rightEncoder.getDistance());
    
  • In autonomousInit() reset the encoder counts and start the motors:
      // Reset encoder counts to 0
      leftEncoder.reset();
      rightEncoder.reset();
      // start motors turning forward at 20% power
      leftMotor.set(0.20);
      rightMotor.set(0.20);
    
  • In the default section of autonomousPeriodic() stop if we've gone the desired distance. Notice our first use of the logical OR operator (||) to test whether either of two conditions is true
      if ((leftEncoder.getDistance() > 36.0) || 
          (rightEncoder.getDistance() > 36.0)) {
          leftMotor.stopMotor();
          rightMotor.stopMotor();
      }
    

For the complete Robot.java see here

Last modified 18 months ago Last modified on Nov 12, 2019, 6:35:51 PM