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

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.Goal(5, 3);

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.TrapezoidProfileSubsystem;
13/** A robot arm subsystem that moves with a motion profile. */
14public class ArmSubsystem extends TrapezoidProfileSubsystem {
15  private final ExampleSmartMotorController m_motor =
16      new ExampleSmartMotorController(ArmConstants.kMotorPort);
17  private final ArmFeedforward m_feedforward =
18      new ArmFeedforward(
19          ArmConstants.kSVolts, ArmConstants.kCosVolts,
20          ArmConstants.kVVoltSecondPerRad, ArmConstants.kAVoltSecondSquaredPerRad);
22  /** Create a new ArmSubsystem. */
23  public ArmSubsystem() {
24    super(
25        new TrapezoidProfile.Constraints(
26            ArmConstants.kMaxVelocityRadPerSecond, ArmConstants.kMaxAccelerationRadPerSecSquared),
27        ArmConstants.kArmOffsetRads);
28    m_motor.setPID(ArmConstants.kP, 0, 0);
29  }
31  @Override
32  public void useState(TrapezoidProfile.State setpoint) {
33    // Calculate the feedforward from the sepoint
34    double feedforward = m_feedforward.calculate(setpoint.position, setpoint.velocity);
35    // Add the feedforward to the PID output to get the motor output
36    m_motor.setSetpoint(
37        ExampleSmartMotorController.PIDMode.kPosition, setpoint.position, feedforward / 12.0);
38  }

Using a TrapezoidProfileSubsystem with commands can be quite simple:

59    // Move the arm to 2 radians above horizontal when the 'A' button is pressed.
60    new JoystickButton(m_driverController, Button.kA.value)
61        .whenPressed(() -> m_robotArm.setGoal(2), m_robotArm);
63    // Move the arm to neutral position when the 'B' button is pressed.
64    new JoystickButton(m_driverController, Button.kB.value)
65        .whenPressed(() -> m_robotArm.setGoal(Constants.ArmConstants.kArmOffsetRads), m_robotArm);



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.

As with TrapezoidProfileSubsystem, users can create a TrapezoidProfileCommand by subclassing the TrapezoidProfileCommand class. However, as with many of the other command classes in the command-based library, users may want to save code by defining a TrapezoidProfileCommand inline.

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.

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):

23  /**
24   * Creates a new TrapezoidProfileCommand that will execute the given {@link TrapezoidProfile}.
25   * Output will be piped to the provided consumer function.
26   *
27   * @param profile The motion profile to execute.
28   * @param output The consumer for the profile output.
29   * @param requirements The subsystems required by this command.
30   */
31  public TrapezoidProfileCommand(
32      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:

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