A subsystem models a physical mechanism on your robot: an arm, an elevator, a flywheel, or an intake. In WPILib, each subsystem extends SubsystemBase and directly manages access to its motors and sensors.
This lesson walks through building a production subsystem class from scratch, importing the constants measured in Stage 1.
1. Subsystem Architecture
Section titled “1. Subsystem Architecture”A well-structured subsystem class contains four sections:
- Hardware Handles & Control Requests: Declared as
private final. - Constructor & Configuration: Instantiates hardware and applies configuration.
- Hardware Configuration Method: Sets gains, current limits, and travel limits.
- Periodic Telemetry: Publishes diagnostic data to NetworkTables every 20ms.
2. Complete Subsystem Implementation
Section titled “2. Complete Subsystem Implementation”Below is a complete implementation of an articulated arm subsystem using CTRE Phoenix 6 and WPILib Units:
package frc.robot.subsystems;
import edu.wpi.first.wpilibj2.command.SubsystemBase;import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;import com.ctre.phoenix6.hardware.TalonFX;import com.ctre.phoenix6.hardware.CANcoder;import com.ctre.phoenix6.configs.TalonFXConfiguration;import com.ctre.phoenix6.controls.MotionMagicVoltage;import com.ctre.phoenix6.signals.GravityTypeValue;import com.ctre.phoenix6.signals.NeutralModeValue;
import edu.wpi.first.units.measure.Angle;import static edu.wpi.first.units.Units.*;
public class ArmSubsystem extends SubsystemBase { // 1. Hardware handles private final TalonFX m_motor; private final CANcoder m_encoder;
// 2. Control request objects (reused to avoid memory allocation) private final MotionMagicVoltage m_request = new MotionMagicVoltage(0).withSlot(0);
// Mechanical gear ratio: 50 motor rotations = 1 arm rotation private static final double GEAR_RATIO = 50.0;
public ArmSubsystem(int motorId, int encoderId, String canbus) { m_motor = new TalonFX(motorId, canbus); m_encoder = new CANcoder(encoderId, canbus);
configureHardware(); }
private void configureHardware() { TalonFXConfiguration config = new TalonFXConfiguration();
// Neutral mode: Brake to hold position when disabled config.MotorOutput.NeutralMode = NeutralModeValue.Brake;
// Transfer measured Tuner X gains (from Stage 1) config.Slot0.kS = 0.22; // 0.22V friction voltage config.Slot0.kV = 0.14; // 0.14 V/(rot/s) config.Slot0.kG = 0.45; // 0.45V horizontal holding voltage config.Slot0.GravityType = GravityTypeValue.Arm_Cosine; config.Slot0.kP = 5.20; // 5.20 V/rot proportional error gain config.Slot0.kD = 0.20; // 0.20 V/(rot/s) derivative damping
// Motion Magic Profile Parameters config.MotionMagic.MotionMagicCruiseVelocity = 40.0; // motor rot/s config.MotionMagic.MotionMagicAcceleration = 80.0; // motor rot/s² config.MotionMagic.MotionMagicJerk = 800.0; // motor rot/s³
// Software Travel Limits (in mechanism rotations) config.SoftwareLimitSwitch.ForwardSoftLimitEnable = true; config.SoftwareLimitSwitch.ForwardSoftLimitThreshold = 0.25 * GEAR_RATIO; // +90 degrees config.SoftwareLimitSwitch.ReverseSoftLimitEnable = true; config.SoftwareLimitSwitch.ReverseSoftLimitThreshold = -0.05 * GEAR_RATIO; // -18 degrees
// Current Limits: Protect motor and mechanical gears config.CurrentLimits.StatorCurrentLimitEnable = true; config.CurrentLimits.StatorCurrentLimit = 40.0; // 40 Amperes
// Apply configuration to motor controller m_motor.getConfigurator().apply(config); }
/** Sets the target arm angle using Motion Magic. */ public void setTargetAngle(Angle target) { double motorRotations = target.in(Rotations) * GEAR_RATIO; m_motor.setControl(m_request.withPosition(motorRotations)); }
/** Returns current arm angle. */ public Angle getAngle() { return Rotations.of(m_motor.getPosition().getValueAsDouble() / GEAR_RATIO); }
@Override public void periodic() { // Runs every 20ms: Publish signals to NetworkTables for AdvantageScope SmartDashboard.putNumber("Arm/AngleDeg", getAngle().in(Degrees)); SmartDashboard.putNumber("Arm/StatorCurrentAmps", m_motor.getStatorCurrent().getValueAsDouble()); SmartDashboard.putNumber("Arm/MotorVoltage", m_motor.getMotorVoltage().getValueAsDouble()); }}Notice line 55: StatorCurrentLimit = 40.0. A Kraken X60 can draw over 300A at stall without current limiting, which will melt motor wire insulation and trip the main 120A breaker within seconds. Never deploy a subsystem without active stator current limits.
3. Telemetry Publishing
Section titled “3. Telemetry Publishing”The periodic() method executes automatically every 20ms. Use it to publish:
- Measured Sensor States: Physical angle, elevator height, or flywheel velocity.
- Motor Diagnostics: Commanded voltage and stator current.
- Target Setpoints: Enables AdvantageScope comparisons of commanded targets against actual motion.
Common Failure Modes
Section titled “Common Failure Modes”1. Allocating Objects Inside periodic()
Section titled “1. Allocating Objects Inside periodic()”- Symptom: RoboRIO garbage collector stutters loop cycles every few seconds.
- Cause: Creating
new MotionMagicVoltage()or string concatenations insideperiodic(). - Fix: Declare request objects as private final fields and mutate them using fluent
.withPosition().
2. Gear Ratio Applied in Reverse
Section titled “2. Gear Ratio Applied in Reverse”- Symptom: Motor commands 90 degrees and spins 50 times faster or slower than expected.
- Cause: Multiplying by
GEAR_RATIOinstead of dividing (or vice versa). - Fix: Remember: if the gearbox is 50:1, 1 mechanism rotation requires 50 motor rotations. Multiply mechanism target by gear ratio to compute motor shaft rotations.
Check Your Work
Section titled “Check Your Work”- Add the subsystem class to your robot project.
- Build with
./gradlew build. - Launch desktop simulation (F5) and verify that
Arm/AngleDegappears in NetworkTables.
Verified Sources & Standards
- WPILib Subsystems Architecturedocs.wpilib.orgWPILib Standard
- CTRE Phoenix 6 Hardware Configuration Buildersv6.docs.ctr-electronics.comHardware Vendor