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

Version 5 (modified by David Albert, 6 years ago) (diff)

--

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 Encoders and Motor controllers 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);
       // 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);
    
  • 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);
      // to go forward, left motor turns clockwise, right motor counter-clockwise
      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