| 1 | Modify the generated code as follows: |
| 2 | |
| 3 | * Add the following imports: |
| 4 | {{{ |
| 5 | import com.ctre.phoenix.motorcontrol.can.*; |
| 6 | }}} |
| 7 | |
| 8 | * Declare variables for the Motor controllers in the Robot class |
| 9 | {{{ |
| 10 | private WPI_TalonSRX leftMotor, rightMotor; |
| 11 | }}} |
| 12 | |
| 13 | * In robotInit() instantiate the motor controller objects |
| 14 | {{{ |
| 15 | // CAN motor controllers connected to CAN bus (addrs 3,4) |
| 16 | leftMotor = new WPI_TalonSRX(3); |
| 17 | rightMotor = new WPI_TalonSRX(4); |
| 18 | // clear any previously configured settings |
| 19 | leftMotor.configFactoryDefault(); |
| 20 | rightMotor.configFactoryDefault(); |
| 21 | // Quadrature encoders are connected directly to the motor controllers |
| 22 | leftMotor.configSelectedFeedbackSensor(FeedbackDevice.QuadEncoder); |
| 23 | rightMotor.configSelectedFeedbackSensor(FeedbackDevice.QuadEncoder); |
| 24 | }}} |
| 25 | |
| 26 | * Add the following new method to the Robot class: |
| 27 | {{{ |
| 28 | double raw2inches(int raw_count, int counts_per_rotation, double wheel_diameter) { |
| 29 | return (raw_count / counts_per_rotation) * (3.141492 * wheel_diameter); |
| 30 | } |
| 31 | }}} |
| 32 | |
| 33 | * Add the following to the robotPeriodic() method; note the use of the [https://www.ctr-electronics.com/downloads/api/java/html/classcom_1_1ctre_1_1phoenix_1_1motorcontrol_1_1can_1_1_base_motor_controller.html#afb934a11682e710df123eec35aba1ba9 getSelectedFeedbackSensor()] method of the motor controller object which returns raw encoder counts: |
| 34 | {{{ |
| 35 | // Encoders connected to CAN controller return raw counts |
| 36 | int l_raw = leftMotor.getSelectedSensorPosition(); |
| 37 | int r_raw = rightMotor.getSelectedSensorPosition(); |
| 38 | // display distances on smart dashboard |
| 39 | SmartDashboard.putNumber("Left", raw2inches(l_raw, 360*2, 7.5)); |
| 40 | SmartDashboard.putNumber("Right", raw2inches(r_raw, 360*2, 7.5)); |
| 41 | }}} |
| 42 | |
| 43 | * In autonomousInit() start the motors: |
| 44 | {{{ |
| 45 | // start motors turning forward at 20% power |
| 46 | leftMotor.set(0.20); |
| 47 | // to go forward, left motor turns clockwise, right motor counter-clockwise |
| 48 | rightMotor.set(-0.20); |
| 49 | }}} |
| 50 | |
| 51 | * In the default section of autonomousPeriodic() stop if we've gone the desired distance. |
| 52 | Notice our first use of the logical OR operator (!||) to test whether either of two conditions is true |
| 53 | {{{ |
| 54 | int l_raw = leftMotor.getSelectedSensorPosition(); |
| 55 | int r_raw = rightMotor.getSelectedSensorPosition(); |
| 56 | if ((raw2inches(l_raw, 360*2, 7.5) > 36.0) || |
| 57 | (raw2inches(r_raw, 360*2, 7.5) > 36.0)) { |
| 58 | leftMotor.stopMotor(); |
| 59 | rightMotor.stopMotor(); |
| 60 | } |
| 61 | }}} |