1.5.9 - Programming the Complete Robot
On The Panther Project, a robot that only drives is not a competitor. To score, three separate mechanisms have to work together, and every one of them needs its own programming strategy.
Here is what we are building:
- The Drivetrain: Two motors, two encoders, and a gyro. It has to drive well, drive straight, and know how far it has moved.
- The Intake: A spinning wheel on a hinged arm. It needs to swing down, grab a piece, and tuck away.
- The Shooter: A flywheel driven through a MOSFET plus a servo gate that holds the piece back until the wheel is at speed.
0. Before You Type Anything
Section titled “0. Before You Type Anything”You need three things installed before Step 1:
- WPILib — the toolchain. Download it from docs.wpilib.org and run the installer. This also installs VS Code and Java for you.
- The XRP extension — open VS Code, go to the Extensions panel, search
XRP, install the WPILib XRP extension. - Your controller plugged in — a PS4 controller over USB.
Now create the project:
- Press
Ctrl+Shift+Pto open the command palette. - Type
WPILib: Create a new project. - Select XRP as the template.
- Name it
XRPBot. - Press Create.
VS Code opens the new project. Do not hand-edit anything outside the src folder — the rest is generated.
1. Learn the Map of the Project
Section titled “1. Learn the Map of the Project”Open the file explorer on the left and drill down to:
src/main/java/frc/robot/That folder is where all of your work happens. Inside it:
| Folder / file | What lives there |
|---|---|
subsystems/ | One class per mechanism. Each one owns its motors and sensors. |
commands/ | Actions that combine mechanisms, like the autonomous routine. |
Constants.java | Every number and port in one place. |
RobotContainer.java | Wires buttons to mechanisms. |
Robot.java | The robot’s life cycle. Runs once at boot, then loops forever. |
Main.java | Boilerplate. You will never touch it. |
Why this matters: This layout is called the command-based framework. A subsystem is a piece of hardware (a motor, a servo, an encoder). A command is an action that uses subsystems. Keeping them in separate files means one broken mechanism does not take down the other two, and the scheduler can stop any action that fights another.
Naming rule
Section titled “Naming rule”The file name must match the class name exactly, capitalization included. Drivetrain.java holds public class Drivetrain. If you name the file drivetrain.java, Java will not find it.
2. Wire the Robot to Match the Code
Section titled “2. Wire the Robot to Match the Code”The code below hardcodes these ports. Wire to this table or the code will move the wrong thing.
| Device | XRP port |
|---|---|
| Left drive motor | Motor 0 |
| Right drive motor | Motor 3 |
| Left drive encoder | DIO 4 / 5 |
| Right drive encoder | DIO 10 / 11 |
| Intake wheel motor | Motor 1 |
| Intake arm servo | Servo 4 |
| Flywheel motor (through MOSFET) | Motor 2 |
| Gate servo | Servo 5 |
Why this matters: XRP motor ports are numbered 0 through 3 and servo ports 4 and 5. The encoder channels are chosen to sit far from the motors so the cables do not collide. If you change a port on the robot, you change the matching line in Constants.java in Step 3, and nothing else.
3. Constants.java: One Place for Every Number
Section titled “3. Constants.java: One Place for Every Number”Path: src/main/java/frc/robot/Constants.java
package frc.robot;
import static edu.wpi.first.units.Units.Inches;import static edu.wpi.first.units.Units.Millimeters;
/** All robot-wide constants live here. */public final class Constants { private Constants() {}
public static final class OperatorConstants { public static final int DRIVER_CONTROLLER_PORT = 0; }
public static final class DriveConstants { public record EncoderPortPair(int aChannel, int bChannel) {}
// XRP motor ports public static final int LEFT_DRIVE_MOTOR = 0; public static final int RIGHT_DRIVE_MOTOR = 3;
// XRP encoder DIO channels (match the motor ports above) public static final EncoderPortPair LEFT_ENCODER = new EncoderPortPair(4, 5); public static final EncoderPortPair RIGHT_ENCODER = new EncoderPortPair(10, 11);
private static final double WHEEL_DIAMETER_INCHES = Inches.convertFrom(60, Millimeters); private static final double ENCODER_TICKS_PER_REVOLUTION = 585.6; public static final double DISTANCE_PER_PULSE = (WHEEL_DIAMETER_INCHES * Math.PI) / ENCODER_TICKS_PER_REVOLUTION;
// Driving feel - increased deadband to combat stick drift public static final double STICK_DEADBAND = 0.15; public static final double SLOW_MODE_MULTIPLIER = 0.4;
// Drive-straight (Cross) public static final double DRIVE_STRAIGHT_SPEED = -0.5; public static final double kP_GYRO_TELEOP = 0.022; public static final double MAX_GYRO_CORRECTION = 0.3; }
public static final class IntakeConstants { public static final int INTAKE_MOTOR = 1; // XRP motor port 1 public static final double INTAKE_POWER = 1.0;
public static final int ARM_SERVO = 4; // XRP Servo 1 (channel 4) public static final double ARM_STOWED_ANGLE = 60.0; public static final double ARM_DEPLOYED_ANGLE = 162.0; public static final double ARM_MIN_ANGLE = 60.0; public static final double ARM_MAX_ANGLE = 180.0; }
public static final class ShooterConstants { // Flywheel: XRP motor port 2 -> drives MOSFET on physical Motor 3 header public static final int FLYWHEEL_MOTOR = 2;
// Ramp gate: XRP Servo 2 (channel 5) public static final int GATE_SERVO = 5;
// Gate angles public static final double GATE_CLOSED_ANGLE = 70.0; public static final double GATE_OPEN_ANGLE = 130.0; public static final double GATE_MIN_ANGLE = 0.0; public static final double GATE_MAX_ANGLE = 180.0;
// Spin-up delay (in seconds) and acceleration ramping public static final double SPIN_UP_SECONDS = 1.5; public static final double FLYWHEEL_RAMP_PER_SECOND = 2.5;
// D-pad speed presets (fraction of full power, 0..1) public static final double[] SPEED_PRESETS = {0.6, 0.7, 0.8, 0.9, 1.0}; public static final int DEFAULT_PRESET_INDEX = 2; // Default 100%
// Preferences keys public static final String PREF_GATE_OPEN = "Shooter/GateOpenAngle"; public static final String PREF_GATE_CLOSED = "Shooter/GateClosedAngle"; }}Why this matters
Section titled “Why this matters”- One source of truth. Port
2appears once. Change it here and the drivetrain, intake, and shooter all keep working. WHEEL_DIAMETER_INCHESandENCODER_TICKS_PER_REVOLUTIONare used to convert raw encoder ticks into real inches. A 60 mm wheel rolling one full turn covers about 7.4 inches, and the encoder reports 585.6 ticks per turn, so dividing gives inches per tick.STICK_DEADBAND = 0.15exists because worn sticks do not return to exactly zero. Without it the robot creeps when you let go.SPEED_PRESETSlets the driver change flywheel power from the controller without a laptop.
4. The Drivetrain Subsystem
Section titled “4. The Drivetrain Subsystem”Create the file src/main/java/frc/robot/subsystems/Drivetrain.java.
package frc.robot.subsystems;
import edu.wpi.first.math.MathUtil;import edu.wpi.first.wpilibj.Encoder;import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;import edu.wpi.first.wpilibj.xrp.XRPGyro;import edu.wpi.first.wpilibj.xrp.XRPMotor;import edu.wpi.first.wpilibj2.command.Command;import edu.wpi.first.wpilibj2.command.SubsystemBase;import frc.robot.Constants.DriveConstants;import java.util.function.BooleanSupplier;import java.util.function.DoubleSupplier;
public class Drivetrain extends SubsystemBase {
private final XRPMotor leftMotor = new XRPMotor(DriveConstants.LEFT_DRIVE_MOTOR); private final XRPMotor rightMotor = new XRPMotor(DriveConstants.RIGHT_DRIVE_MOTOR);
private final Encoder leftEncoder = new Encoder( DriveConstants.LEFT_ENCODER.aChannel(), DriveConstants.LEFT_ENCODER.bChannel() ); private final Encoder rightEncoder = new Encoder( DriveConstants.RIGHT_ENCODER.aChannel(), DriveConstants.RIGHT_ENCODER.bChannel() );
private final XRPGyro gyro = new XRPGyro();
public Drivetrain() { leftEncoder.setDistancePerPulse(DriveConstants.DISTANCE_PER_PULSE); rightEncoder.setDistancePerPulse(DriveConstants.DISTANCE_PER_PULSE);
// Flipped motor inversions to fix reverse driving direction leftMotor.setInverted(false); rightMotor.setInverted(true);
resetEncoders(); resetGyro(); }
public void tankDrive(double left, double right) { leftMotor.set(MathUtil.clamp(left, -1.0, 1.0)); rightMotor.set(MathUtil.clamp(right, -1.0, 1.0)); }
public void stop() { tankDrive(0.0, 0.0); }
public Command driveCommand(DoubleSupplier leftY, DoubleSupplier rightY, BooleanSupplier slowMode) { return run(() -> { double left = MathUtil.applyDeadband(-leftY.getAsDouble(), DriveConstants.STICK_DEADBAND); double right = MathUtil.applyDeadband(-rightY.getAsDouble(), DriveConstants.STICK_DEADBAND);
if (slowMode.getAsBoolean()) { left *= DriveConstants.SLOW_MODE_MULTIPLIER; right *= DriveConstants.SLOW_MODE_MULTIPLIER; }
tankDrive(left, right); }); }
public Command driveStraightCommand(double speed) { return runOnce(this::resetGyro) .andThen(run(() -> { double headingError = getGyroAngleZ(); double turnCorrection = MathUtil.clamp( -headingError * DriveConstants.kP_GYRO_TELEOP, -DriveConstants.MAX_GYRO_CORRECTION, DriveConstants.MAX_GYRO_CORRECTION ); tankDrive(speed + turnCorrection, speed - turnCorrection); })) .finallyDo(this::stop); }
public void resetEncoders() { leftEncoder.reset(); rightEncoder.reset(); }
public double getLeftDistanceInches() { return leftEncoder.getDistance(); }
public double getRightDistanceInches() { return rightEncoder.getDistance(); }
public double getAverageDistanceInches() { return (getLeftDistanceInches() + getRightDistanceInches()) / 2.0; }
public void resetGyro() { gyro.reset(); }
public double getGyroAngleZ() { return gyro.getAngleZ(); }
@Override public void periodic() { SmartDashboard.putNumber("Drive/Left Inches", getLeftDistanceInches()); SmartDashboard.putNumber("Drive/Right Inches", getRightDistanceInches()); SmartDashboard.putNumber("Drive/Gyro Z Deg", getGyroAngleZ()); }}Why this matters
Section titled “Why this matters”SubsystemBaseis the base class every mechanism extends. It gives the scheduler a way to know which mechanism is busy so two commands cannot fight over the same motor.setInverted(true)on the right motor flips its direction so that positive power on both motors drives forward. Without it the robot spins in place.MathUtil.clampguarantees the motor never receives more than 100% power, even after corrections are added.applyDeadbandturns any stick reading smaller than 0.15 into zero.driveStraightCommandis a mini autopilot. It reads the gyro, and if the robot has drifted, it nudges one side faster than the other to steer back.kP_GYRO_TELEOPsets how hard it corrects andMAX_GYRO_CORRECTIONcaps it.SmartDashboard.putNumberprints live numbers to the dashboard so you can watch distance and heading while tuning.
5. The Intake Subsystem
Section titled “5. The Intake Subsystem”Create src/main/java/frc/robot/subsystems/Intake.java.
package frc.robot.subsystems;
import edu.wpi.first.math.MathUtil;import edu.wpi.first.wpilibj.xrp.XRPMotor;import edu.wpi.first.wpilibj.xrp.XRPServo;import edu.wpi.first.wpilibj2.command.Command;import edu.wpi.first.wpilibj2.command.SubsystemBase;import frc.robot.Constants.IntakeConstants;
public class Intake extends SubsystemBase {
private final XRPMotor intakeMotor = new XRPMotor(IntakeConstants.INTAKE_MOTOR); private final XRPServo armServo = new XRPServo(IntakeConstants.ARM_SERVO);
public Intake() { intakeMotor.setInverted(false); stowArm(); stopWheels(); }
public void setArmAngle(double degrees) { armServo.setAngle(MathUtil.clamp(degrees, IntakeConstants.ARM_MIN_ANGLE, IntakeConstants.ARM_MAX_ANGLE)); }
public void deployArm() { setArmAngle(IntakeConstants.ARM_DEPLOYED_ANGLE); }
public void stowArm() { setArmAngle(IntakeConstants.ARM_STOWED_ANGLE); }
public void runWheels() { intakeMotor.set(IntakeConstants.INTAKE_POWER); }
public void stopWheels() { intakeMotor.set(0.0); }
public Command intakeCommand() { return startEnd( () -> { deployArm(); runWheels(); }, () -> { stowArm(); stopWheels(); } ); }
public Command armDeployCommand() { return startEnd(this::deployArm, this::stowArm); }}Why this matters
Section titled “Why this matters”startEndbuilds a command from two lambdas: what to do when it starts, and what to do when it stops. Here, holding the button lowers the arm and spins the wheel; releasing it puts everything back.- The clamp in
setArmAngleprotects the servo. Servos strip gears when commanded past their mechanical stops, and the clamp makes that impossible. - The constructor calls
stowArm()andstopWheels()so the arm never boots up hanging out into the field. intakeCommandandarmDeployCommandare separate so you can grab a piece (both actions) or just flip the arm down (arm only) without the wheel running.
6. The Shooter Subsystem
Section titled “6. The Shooter Subsystem”Create src/main/java/frc/robot/subsystems/Shooter.java.
package frc.robot.subsystems;
import edu.wpi.first.math.MathUtil;import edu.wpi.first.wpilibj.Preferences;import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;import edu.wpi.first.wpilibj.xrp.XRPMotor;import edu.wpi.first.wpilibj.xrp.XRPServo;import edu.wpi.first.wpilibj2.command.Command;import edu.wpi.first.wpilibj2.command.Commands;import edu.wpi.first.wpilibj2.command.SubsystemBase;import frc.robot.Constants.ShooterConstants;import java.util.Set;
public class Shooter extends SubsystemBase {
private final XRPMotor flywheel = new XRPMotor(ShooterConstants.FLYWHEEL_MOTOR); private final XRPServo gate = new XRPServo(ShooterConstants.GATE_SERVO);
private int presetIndex = ShooterConstants.DEFAULT_PRESET_INDEX; private boolean flywheelEnabled = false; private boolean gateOpen = false;
public Shooter() { Preferences.initDouble(ShooterConstants.PREF_GATE_OPEN, ShooterConstants.GATE_OPEN_ANGLE); Preferences.initDouble(ShooterConstants.PREF_GATE_CLOSED, ShooterConstants.GATE_CLOSED_ANGLE);
flywheel.setInverted(false); stop(); }
/** * Fire sequence (Direct speed, no ramping): * 1. Close gate & enable flywheel (instantly snaps to selected preset output). * 2. Wait spin-up time. * 3. Open gate to fire. * 4. On release / cancel: close gate & set flywheel to 0.0 immediately. */ public Command fireCommand() { return Commands.sequence( runOnce(() -> { closeGate(); flywheelEnabled = true; }), Commands.defer(() -> Commands.waitSeconds(getSpinUpSeconds()), Set.of()), runOnce(this::openGate), Commands.idle(this)) .finallyDo((interrupted) -> stop()); }
/** Immediate stop (flywheel output 0.0, gate closed). */ public void stop() { flywheelEnabled = false; flywheel.set(0.0); closeGate(); }
public void nextPreset() { presetIndex = Math.min(presetIndex + 1, ShooterConstants.SPEED_PRESETS.length - 1); }
public void previousPreset() { presetIndex = Math.max(presetIndex - 1, 0); }
public double getSelectedSpeed() { return ShooterConstants.SPEED_PRESETS[presetIndex]; }
public void openGate() { setGateAngle(Preferences.getDouble(ShooterConstants.PREF_GATE_OPEN, ShooterConstants.GATE_OPEN_ANGLE)); gateOpen = true; }
public void closeGate() { setGateAngle(Preferences.getDouble(ShooterConstants.PREF_GATE_CLOSED, ShooterConstants.GATE_CLOSED_ANGLE)); gateOpen = false; }
private void setGateAngle(double degrees) { gate.setAngle(MathUtil.clamp(degrees, ShooterConstants.GATE_MIN_ANGLE, ShooterConstants.GATE_MAX_ANGLE)); }
private double getSpinUpSeconds() { return Math.max(0.0, ShooterConstants.SPIN_UP_SECONDS); }
@Override public void periodic() { // Snaps directly to selected preset speed when enabled, 0.0 when disabled double output = flywheelEnabled ? getSelectedSpeed() : 0.0; flywheel.set(output);
SmartDashboard.putNumber("Shooter/Preset Speed %", getSelectedSpeed() * 100.0); SmartDashboard.putNumber("Shooter/Output %", output * 100.0); SmartDashboard.putBoolean("Shooter/Flywheel On", flywheelEnabled); SmartDashboard.putBoolean("Shooter/Gate Open", gateOpen); }}Why this matters
Section titled “Why this matters”- The MOSFET. The flywheel is a big motor that would melt an XRP header. It runs through a MOSFET wired to motor port
2, so the XRP only sends the signal while the MOSFET carries the current. flywheelEnabledinstead of callingset()directly. The actual motor output is written every loop inperiodic(). Commands only flip the flag. This means a preset change takes effect on the very next loop and nothing else has to know.- The order inside
fireCommandis the whole design. Close the gate, spin up, wait, then open. If you opened the gate first, the piece would dribble out of a slow wheel and land on the floor. Preferencesstores the gate angles on the roboRIO. You can retune them from the dashboard without recompiling, and they survive a reboot.nextPreset/previousPresetclamp to the ends of the array, so holding D-pad up at the top preset does nothing instead of crashing.Commands.idle(this)holds the command running forever. The fire sequence does not end on its own; the button release or the.withTimeout()in auto ends it, and.finallyDothen shuts everything down.
7. The Autonomous Command
Section titled “7. The Autonomous Command”Create src/main/java/frc/robot/commands/Autonomous.java.
package frc.robot.commands;
import edu.wpi.first.wpilibj2.command.Commands;import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;import frc.robot.subsystems.Drivetrain;import frc.robot.subsystems.Intake;import frc.robot.subsystems.Shooter;import java.util.function.DoubleSupplier;
public class Autonomous extends SequentialCommandGroup {
/** Option 1: Drive straight & Shoot (No intake). */ public Autonomous( double distanceInches, double driveSpeed, Drivetrain drivetrain, Shooter shooter) { this(distanceInches, driveSpeed, false, 0.0, drivetrain, null, shooter); }
/** Option 2: Full Routine — Drive & Intake ball, Turn, Drive to goal, and Shoot. */ public Autonomous( double distanceInches, double driveSpeed, boolean useIntake, double turnDegrees, Drivetrain drivetrain, Intake intake, Shooter shooter) {
DoubleSupplier distanceSupplier = drivetrain::getAverageDistanceInches;
// Step 0: Reset encoders & gyro at auto start addCommands( Commands.runOnce(() -> { drivetrain.resetEncoders(); drivetrain.resetGyro(); }) );
// Step 1: Drive forward (with optional intake active) if (useIntake && intake != null) { addCommands( Commands.parallel( drivetrain.driveStraightCommand(-Math.abs(driveSpeed)) .until(() -> Math.abs(distanceSupplier.getAsDouble()) >= Math.abs(distanceInches)), intake.intakeCommand() ).withTimeout(4.0) ); } else { addCommands( drivetrain.driveStraightCommand(-Math.abs(driveSpeed)) .until(() -> Math.abs(distanceSupplier.getAsDouble()) >= Math.abs(distanceInches)) ); }
// Step 2: Stop drive and stow intake arm addCommands(Commands.runOnce(drivetrain::stop, drivetrain)); if (useIntake && intake != null) { addCommands( Commands.runOnce(intake::stowArm, intake), Commands.runOnce(intake::stopWheels, intake) ); }
// Step 3: Turn toward target using raw gyro angle Z if (Math.abs(turnDegrees) > 1.0) { addCommands( Commands.runOnce(drivetrain::resetGyro), Commands.run(() -> { double currentAngle = drivetrain.getGyroAngleZ(); double error = turnDegrees - currentAngle; double turnOutput = Math.copySign(Math.min(0.4, Math.abs(error) * 0.02), error); drivetrain.tankDrive(-turnOutput, turnOutput); }, drivetrain) .until(() -> Math.abs(turnDegrees - drivetrain.getGyroAngleZ()) < 3.0) .withTimeout(2.0), Commands.runOnce(drivetrain::stop, drivetrain) ); }
// Step 4: Shoot (Spin up -> Gate Open -> Fire for 3s total -> Stop) addCommands( shooter.fireCommand().withTimeout(3.0), Commands.runOnce(() -> { drivetrain.stop(); shooter.stop(); if (intake != null) intake.stopWheels(); }) ); }}Why this matters
Section titled “Why this matters”SequentialCommandGroupruns its children in order and waits for each to finish. That is exactly what a routine is..until(...)ends the drive step the moment the encoder average reaches the target distance. It is a real measurement, not a guessed timer..withTimeout(...)on every step is a safety net. If an encoder dies or the robot gets stuck, the step still gives up instead of driving into a wall forever.Commands.parallel(...)runs the drive and the intake at the same time, so the piece is already collected by the time the robot stops.- The turn uses a proportional controller like the drive-straight code, and stops within 3 degrees.
- The last command block calls
stop()on everything so nothing is left spinning after the routine ends.
8. RobotContainer: Wiring the Controller
Section titled “8. RobotContainer: Wiring the Controller”Path: src/main/java/frc/robot/RobotContainer.java
package frc.robot;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;import edu.wpi.first.wpilibj2.command.Command;import edu.wpi.first.wpilibj2.command.Commands;import edu.wpi.first.wpilibj2.command.button.CommandPS4Controller;import frc.robot.Constants.DriveConstants;import frc.robot.Constants.OperatorConstants;import frc.robot.commands.Autonomous;import frc.robot.subsystems.Drivetrain;import frc.robot.subsystems.Intake;import frc.robot.subsystems.Shooter;
public class RobotContainer {
private final Drivetrain drivetrain = new Drivetrain(); private final Intake intake = new Intake(); private final Shooter shooter = new Shooter();
private final CommandPS4Controller driver = new CommandPS4Controller(OperatorConstants.DRIVER_CONTROLLER_PORT);
private final SendableChooser<Command> autoChooser = new SendableChooser<>();
public RobotContainer() { drivetrain.setDefaultCommand( drivetrain.driveCommand(driver::getLeftY, driver::getRightY, driver.circle()));
configureButtonBindings(); configureAutoChooser(); }
private void configureButtonBindings() { // Hold R1: Spins flywheel to selected preset speed instantly and opens servo gate after delay driver.R1().whileTrue(shooter.fireCommand());
// Cycle speed presets using D-Pad Up / Down driver.povUp().onTrue(Commands.runOnce(shooter::nextPreset, shooter)); driver.povDown().onTrue(Commands.runOnce(shooter::previousPreset, shooter));
// Intake & Arm control driver.L1().whileTrue(intake.intakeCommand()); driver.square().whileTrue(intake.armDeployCommand());
// Straight drive helper driver.cross().whileTrue(drivetrain.driveStraightCommand(DriveConstants.DRIVE_STRAIGHT_SPEED)); }
private void configureAutoChooser() { autoChooser.setDefaultOption( "1. Drive 24 in & Shoot", new Autonomous(24.0, 0.5, drivetrain, shooter));
autoChooser.addOption( "2. Intake + Turn 90° + Shoot", new Autonomous(24.0, 0.4, true, 90.0, drivetrain, intake, shooter));
autoChooser.addOption("3. Do Nothing", Commands.none());
SmartDashboard.putData("Auto Routine", autoChooser); }
public Command getAutonomousCommand() { return autoChooser.getSelected(); }
public void stopAllSubsystems() { drivetrain.stop(); shooter.stop(); intake.stopWheels(); }}Why this matters
Section titled “Why this matters”- The subsystems are created once, here. Every command in the robot is handed one of these same objects, so they all talk to the same motors.
setDefaultCommandgives the drivetrain something to do whenever no other command needs it. That is what makes the sticks work with no button held.whileTrueversusonTrue.whileTrueruns for as long as the button is held (driving, intake, firing).onTruefires once per press (changing a preset).SendableChooserbuilds the dropdown on the dashboard so the drive team picks the auto routine instead of you editing code at the field.stopAllSubsystems()is whatRobot.javacalls when the robot is disabled, so nothing keeps running between matches.
9. Robot.java: The Life Cycle
Section titled “9. Robot.java: The Life Cycle”Open the existing src/main/java/frc/robot/Robot.java, select all, and paste over it.
package frc.robot;
import edu.wpi.first.wpilibj.TimedRobot;import edu.wpi.first.wpilibj2.command.Command;import edu.wpi.first.wpilibj2.command.CommandScheduler;
public class Robot extends TimedRobot { private Command m_autonomousCommand; private RobotContainer m_robotContainer;
@Override public void robotInit() { m_robotContainer = new RobotContainer(); }
@Override public void robotPeriodic() { CommandScheduler.getInstance().run(); }
@Override public void disabledInit() { if (m_robotContainer != null) { m_robotContainer.stopAllSubsystems(); } }
@Override public void disabledPeriodic() {}
@Override public void autonomousInit() { m_autonomousCommand = m_robotContainer.getAutonomousCommand();
if (m_autonomousCommand != null) { m_autonomousCommand.schedule(); } }
@Override public void autonomousPeriodic() {}
@Override public void teleopInit() { if (m_autonomousCommand != null) { m_autonomousCommand.cancel(); } }
@Override public void teleopPeriodic() {}
@Override public void testInit() { CommandScheduler.getInstance().cancelAll(); }
@Override public void testPeriodic() {}}Why this matters
Section titled “Why this matters”robotPeriodicrunsCommandScheduler.run()50 times per second. That single line is what actually executes every command in the robot. Forget it and nothing works.teleopInitcancels the auto command so the routine cannot keep running when the match switches to driver control.disabledInitstops everything so a motor is never left humming while the robot sits on the field.
10. Build and Deploy
Section titled “10. Build and Deploy”- Plug the XRP into your laptop over USB.
- Press
F5, runWPILib: Simulate Robot Code. - Open the dashboard and confirm
Drive/Left InchesandDrive/Gyro Z Degare reporting.
Driver control reference
Section titled “Driver control reference”| Input | Action |
|---|---|
| Left stick (up/down) | Left wheels |
| Right stick (up/down) | Right wheels |
| Circle (hold) | Slow mode |
| Cross (hold) | Drive straight with gyro assist |
| L1 (hold) | Lower arm and run intake |
| Square (hold) | Lower arm only |
| R1 (hold) | Spin up and fire |
| D-pad up / down | Raise / lower flywheel preset |
| Dashboard dropdown | Choose the auto routine |
11. Newbie Customization Guide
Section titled “11. Newbie Customization Guide”1. Changing a port
Section titled “1. Changing a port”- Where:
Constants.java - What: the matching
*_MOTOR,*_SERVO, orEncoderPortPairline. - Why: you moved a cable. Change it here and nowhere else.
2. Adjusting stick feel
Section titled “2. Adjusting stick feel”- Where:
DriveConstants.STICK_DEADBAND(default0.15) - Why: raise it if the robot creeps with the sticks centered. Lower it if small stick inputs feel dead.
3. Making drive-straight stiffer or gentler
Section titled “3. Making drive-straight stiffer or gentler”- Where:
DriveConstants.kP_GYRO_TELEOP(default0.022) - Why: raise it if the robot wanders. Lower it if it weaves side to side while driving straight.
4. Changing flywheel presets
Section titled “4. Changing flywheel presets”- Where:
ShooterConstants.SPEED_PRESETSandDEFAULT_PRESET_INDEX - Why: each entry is a fraction of full power.
DEFAULT_PRESET_INDEXis which one the robot boots on, counted from0.
5. Retuning the gate angles without recompiling
Section titled “5. Retuning the gate angles without recompiling”- Where: the dashboard, under
Shooter/GateOpenAngleandShooter/GateClosedAngle - Why:
Preferencessaves these to the robot. Once you like a value, copy it intoGATE_OPEN_ANGLE/GATE_CLOSED_ANGLEso a fresh robot starts correct.
6. Changing auto distances and turns
Section titled “6. Changing auto distances and turns”- Where:
RobotContainer.configureAutoChooser() - Why: the numbers passed to
new Autonomous(...)are inches and degrees. Option 2 is24.0inches,0.4speed,truefor intake,90.0degrees.
12. Troubleshooting
Section titled “12. Troubleshooting”| Symptom | Cause | Fix |
|---|---|---|
cannot find symbol | A file is named wrong, or a class name has different capitalization | File name and class name must match exactly, same case |
package frc.robot.subsystems does not exist | The file is in the wrong folder | Subsystems go in subsystems/, commands in commands/ |
| Robot drives backward | Right motor inversion missing | Confirm rightMotor.setInverted(true) in Drivetrain.java |
| Robot creeps when idle | Deadband too low | Raise STICK_DEADBAND |
| Flywheel does not spin | MOSFET wired to the wrong header | Move it to motor port 2 |
| Piece dribbles out of the shooter | Spin-up too short | Raise SPIN_UP_SECONDS |
| Nothing responds to buttons | CommandScheduler.run() missing | Confirm it is inside robotPeriodic |
| Dashboard shows nothing | periodic() cleared | Restore the SmartDashboard calls in Drivetrain.periodic() |
13. Glossary
Section titled “13. Glossary”- Subsystem — one mechanism and the code that owns it.
- Command — an action. Runs, does its job, ends.
- Scheduler — the 50 Hz loop that decides which commands run.
- Default command — what a subsystem does when nothing else needs it.
- Deadband — an input size treated as zero.
- Closed loop — measuring a sensor and correcting toward a target, like the gyro hold.
- MOSFET — a switch that lets a small signal control a big motor.
- Preferences — saved values that survive a reboot.
Answered: 0 / 0 (0%)