Motion Profiling through TrapezoidProfileSubsystems and TrapezoidProfileCommands


For a description of the WPILib motion profiling features used by these command-based wrappers, see Trapezoidal Motion Profiles in WPILib.


The TrapezoidProfile command wrappers are generally intended for composition with custom or external controllers. For combining trapezoidal motion profiling with WPILib’s PIDController, see Combining Motion Profiling and PID in Command-Based.

When controlling a mechanism, is often desirable to move it smoothly between two positions, rather than to abruptly change its setpoint. This is called “motion-profiling,” and is supported in WPILib through the TrapezoidProfile class (Java, C++).

To further help teams integrate motion profiling into their command-based robot projects, WPILib includes two convenience wrappers for the TrapezoidProfile class: TrapezoidProfileSubsystem, which automatically generates and executes motion profiles in its periodic() method, and the TrapezoidProfileCommand, which executes a single user-provided TrapezoidProfile.



In C++, the TrapezoidProfileSubsystem class is templated on the unit type used for distance measurements, which may be angular or linear. The passed-in values must have units consistent with the distance units, or a compile-time error will be thrown. For more information on C++ units, see The C++ Units Library.

The TrapezoidProfileSubsystem class (Java, C++) will automatically create and execute trapezoidal motion profiles to reach the user-provided goal state. To use the TrapezoidProfileSubsystem class, users must create a subclass of it.

Creating a TrapezoidProfileSubsystem


If periodic is overridden when inheriting from TrapezoidProfileSubsystem, make sure to call super.periodic()! Otherwise, motion profiling functionality will not work properly.

When subclassing TrapezoidProfileSubsystem, users must override a single abstract method to provide functionality that the class will use in its ordinary operation:


  protected abstract void useState(TrapezoidProfile.State state);

The useState() method consumes the current state of the motion profile. The TrapezoidProfileSubsystem will automatically call this method from its periodic() block, and pass it the motion profile state corresponding to the subsystem’s current progress through the motion profile.

Users may do whatever they want with this state; a typical use case (as shown in the Full TrapezoidProfileSubsystem Example) is to use the state to obtain a setpoint and a feedforward for an external “smart” motor controller.

Constructor Parameters

Users must pass in a set of TrapezoidProfile.Constraints to the TrapezoidProfileSubsystem base class through the superclass constructor call of their subclass. This serves to constrain the automatically-generated profiles to a given maximum velocity and acceleration.

Users must also pass in an initial position for the mechanism.

Advanced users may pass in an alternate value for the loop period, if a non-standard main loop period is being used.

Using a TrapezoidProfileSubsystem

Once an instance of a TrapezoidProfileSubsystem subclass has been created, it can be used by commands through the following methods:



If you wish to set the goal to a simple distance with an implicit target velocity of zero, an overload of setGoal() exists that takes a single distance value, rather than a full motion profile state.

The setGoal() method can be used to set the goal state of the TrapezoidProfileSubsystem. The subsystem will automatically execute a profile to the goal, passing the current state at each iteration to the provided useState() method.

// The subsystem will execute a profile to a position of 5 and a velocity of 3.
examplePIDSubsystem.setGoal(new TrapezoidProfile.State(5, 3);

enable() and disable()

The enable() and disable() methods enable and disable the motion profiling control of the TrapezoidProfileSubsystem. When the subsystem is enabled, it will automatically run the control loop and call useState() periodically. When it is disabled, no control is performed.

Full TrapezoidProfileSubsystem Example

What does a TrapezoidProfileSubsystem look like when used in practice? The following examples are taking from the ArmbotOffobard example project (Java, C++):

 5package edu.wpi.first.wpilibj.examples.armbotoffboard.subsystems;
 7import edu.wpi.first.math.controller.ArmFeedforward;
 8import edu.wpi.first.math.trajectory.TrapezoidProfile;
 9import edu.wpi.first.wpilibj.examples.armbotoffboard.Constants.ArmConstants;
10import edu.wpi.first.wpilibj.examples.armbotoffboard.ExampleSmartMotorController;
11import edu.wpi.first.wpilibj2.command.Command;
12import edu.wpi.first.wpilibj2.command.Commands;
13import edu.wpi.first.wpilibj2.command.TrapezoidProfileSubsystem;
15/** A robot arm subsystem that moves with a motion profile. */
16public class ArmSubsystem extends TrapezoidProfileSubsystem {
17  private final ExampleSmartMotorController m_motor =
18      new ExampleSmartMotorController(ArmConstants.kMotorPort);
19  private final ArmFeedforward m_feedforward =
20      new ArmFeedforward(
21          ArmConstants.kSVolts, ArmConstants.kGVolts,
22          ArmConstants.kVVoltSecondPerRad, ArmConstants.kAVoltSecondSquaredPerRad);
24  /** Create a new ArmSubsystem. */
25  public ArmSubsystem() {
26    super(
27        new TrapezoidProfile.Constraints(
28            ArmConstants.kMaxVelocityRadPerSecond, ArmConstants.kMaxAccelerationRadPerSecSquared),
29        ArmConstants.kArmOffsetRads);
30    m_motor.setPID(ArmConstants.kP, 0, 0);
31  }
33  @Override
34  public void useState(TrapezoidProfile.State setpoint) {
35    // Calculate the feedforward from the sepoint
36    double feedforward = m_feedforward.calculate(setpoint.position, setpoint.velocity);
37    // Add the feedforward to the PID output to get the motor output
38    m_motor.setSetpoint(
39        ExampleSmartMotorController.PIDMode.kPosition, setpoint.position, feedforward / 12.0);
40  }
42  public Command setArmGoalCommand(double kArmOffsetRads) {
43    return Commands.runOnce(() -> setGoal(kArmOffsetRads), this);
44  }

Using a TrapezoidProfileSubsystem with commands can be quite simple:

52    // Move the arm to 2 radians above horizontal when the 'A' button is pressed.
53    m_driverController.a().onTrue(m_robotArm.setArmGoalCommand(2));
55    // Move the arm to neutral position when the 'B' button is pressed.
56    m_driverController
57        .b()
58        .onTrue(m_robotArm.setArmGoalCommand(Constants.ArmConstants.kArmOffsetRads));



In C++, the TrapezoidProfileCommand class is templated on the unit type used for distance measurements, which may be angular or linear. The passed-in values must have units consistent with the distance units, or a compile-time error will be thrown. For more information on C++ units, see The C++ Units Library.

The TrapezoidProfileCommand class (Java, C++) allows users to create a command that will execute a single TrapezoidProfile, passing its current state at each iteration to a user-defined function.

Creating a TrapezoidProfileCommand

A TrapezoidProfileCommand can be created two ways - by subclassing the TrapezoidProfileCommand class, or by defining the command inline. Both methods ultimately extremely similar, and ultimately the choice of which to use comes down to where the user desires that the relevant code be located.


If subclassing TrapezoidProfileCommand and overriding any methods, make sure to call the super version of those methods! Otherwise, motion profiling functionality will not work properly.

In either case, a TrapezoidProfileCommand is created by passing the necessary parameters to its constructor (if defining a subclass, this can be done with a super() call):

25  /**
26   * Creates a new TrapezoidProfileCommand that will execute the given {@link TrapezoidProfile}.
27   * Output will be piped to the provided consumer function.
28   *
29   * @param profile The motion profile to execute.
30   * @param output The consumer for the profile output.
31   * @param requirements The subsystems required by this command.
32   */
33  public TrapezoidProfileCommand(
34      TrapezoidProfile profile, Consumer<State> output, Subsystem... requirements) {


The profile parameter is the TrapezoidProfile object that will be executed by the command. By passing this in, users specify the start state, end state, and motion constraints of the profile that the command will use.


The output parameter is a function (usually passed as a lambda) that consumes the output and setpoint of the control loop. Passing in the useOutput function in PIDCommand is functionally analogous to overriding the useState() function in PIDSubsystem.


Like all inlineable commands, TrapezoidProfileCommand allows the user to specify its subsystem requirements as a constructor parameter.

Full TrapezoidProfileCommand Example

What does a TrapezoidProfileSubsystem look like when used in practice? The following examples are taking from the DriveDistanceOffboard example project (Java, C++):

 5package edu.wpi.first.wpilibj.examples.drivedistanceoffboard.commands;
 7import edu.wpi.first.math.trajectory.TrapezoidProfile;
 8import edu.wpi.first.wpilibj.examples.drivedistanceoffboard.Constants.DriveConstants;
 9import edu.wpi.first.wpilibj.examples.drivedistanceoffboard.subsystems.DriveSubsystem;
10import edu.wpi.first.wpilibj2.command.TrapezoidProfileCommand;
12/** Drives a set distance using a motion profile. */
13public class DriveDistanceProfiled extends TrapezoidProfileCommand {
14  /**
15   * Creates a new DriveDistanceProfiled command.
16   *
17   * @param meters The distance to drive.
18   * @param drive The drive subsystem to use.
19   */
20  public DriveDistanceProfiled(double meters, DriveSubsystem drive) {
21    super(
22        new TrapezoidProfile(
23            // Limit the max acceleration and velocity
24            new TrapezoidProfile.Constraints(
25                DriveConstants.kMaxSpeedMetersPerSecond,
26                DriveConstants.kMaxAccelerationMetersPerSecondSquared),
27            // End at desired position in meters; implicitly starts at 0
28            new TrapezoidProfile.State(meters, 0)),
29        // Pipe the profile state to the drive
30        setpointState -> drive.setDriveStates(setpointState, setpointState),
31        // Require the drive
32        drive);
33    // Reset drive encoders since we're starting at 0
34    drive.resetEncoders();
35  }

And, for an inlined example:

66    // Do the same thing as above when the 'B' button is pressed, but defined inline
67    m_driverController
68        .b()
69        .onTrue(
70            new TrapezoidProfileCommand(
71                    new TrapezoidProfile(
72                        // Limit the max acceleration and velocity
73                        new TrapezoidProfile.Constraints(
74                            DriveConstants.kMaxSpeedMetersPerSecond,
75                            DriveConstants.kMaxAccelerationMetersPerSecondSquared),
76                        // End at desired position in meters; implicitly starts at 0
77                        new TrapezoidProfile.State(3, 0)),
78                    // Pipe the profile state to the drive
79                    setpointState -> m_robotDrive.setDriveStates(setpointState, setpointState),
80                    // Require the drive
81                    m_robotDrive)
82                .beforeStarting(m_robotDrive::resetEncoders)
83                .withTimeout(10));