Creación de perfiles de movimiento a través de los subsistemas TrapezoidProfile y los comandos TrapezoidProfile

Nota

Para obtener una descripción de las funciones de creación de perfiles de movimiento de WPILib utilizadas por estos contenedores basados en comandos, consulte Perfil de movimiento trapezoidal en WPILib.

Nota

Los contenedores de comando TrapezoidProfile generalmente están destinados a la composición con controladores personalizados o externos. Para combinar la creación de perfiles de movimiento trapezoidal con el PIDController de WPILib, consulte Combinando Motion Profiling y PID Basado en Comandos.

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++).

Para ayudar aún más a los equipos a integrar la creación de perfiles de movimiento en sus proyectos de robots basados en comandos, WPILib incluye dos envoltorios de conveniencia para la clase TrapezoidProfile: TrapezoidProfileSubsystem, que genera y ejecuta automáticamente perfiles de movimiento en su método periodic() , y el``TrapezoidProfileCommand``, que ejecuta un único TrapezoidProfile proporcionado por el usuario.

TrapezoideProfileSubsystem

Nota

En C ++, la clase TrapezoidProfileSubsystem se basa en el tipo de unidad utilizada para las mediciones de distancia, que puede ser angular o lineal. Los valores pasados deben tener unidades consistentes con las unidades de distancia, o se lanzará un error en tiempo de compilación. Para obtener más información sobre las unidades C ++, consulte Biblioteca de unidades de C++.

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.

Creación de un subsistema de perfil trapezoidal

Nota

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

Al subclasificar TrapezoidProfileSubsystem, los usuarios deben anular un único método abstracto para proporcionar la funcionalidad que la clase usará en su operación ordinaria:

useState()

  protected abstract void useState(TrapezoidProfile.State state);

El método useState() consume el estado actual del perfil de movimiento. El TrapezoidProfileSubsystem llamará automáticamente a este método desde su bloque periodic() y le pasará el estado del perfil de movimiento correspondiente al progreso actual del subsistema a través del perfil de movimiento.

Los usuarios pueden hacer lo que quieran con este estado; un caso de uso típico (como se muestra en el Full TrapezoidProfileSubsystem Example) es usar el estado para obtener un punto de ajuste y un avance para un controlador de motor «inteligente» externo.

Parámetros de constructor

Los usuarios deben pasar un conjunto de TrapezoidProfile.Constraints a la clase base TrapezoidProfileSubsystem a través de la llamada al constructor de superclase de su subclase. Esto sirve para restringir los perfiles generados automáticamente a una velocidad y aceleración máximas determinadas.

Los usuarios también deben pasar en una posición inicial para el mecanismo.

Los usuarios avanzados pueden pasar un valor alternativo para el período de bucle, si se está utilizando un período de bucle principal no estándar.

Uso de un TrapezoidProfileSubsystem

Una vez que se ha creado una instancia de una subclase TrapezoidProfileSubsystem, los comandos pueden usarla a través de los siguientes métodos:

setGoal()

Nota

Si desea establecer el objetivo en una distancia simple con una velocidad objetivo implícita de cero, existe una sobrecarga de setGoal() que toma un valor de distancia único, en lugar de un estado de perfil de movimiento completo.

El método setGoal() se puede utilizar para establecer el estado objetivo del TrapezoidProfileSubsystem. El subsistema ejecutará automáticamente un perfil para el objetivo, pasando el estado actual en cada iteración al método useState() proporcionado.

// 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.

Ejemplo completo de TrapezoidProfileSubsystem

¿Qué aspecto tiene un TrapezoidProfileSubsystem cuando se utiliza en la práctica? Los siguientes ejemplos están tomados del proyecto de ejemplo ArmbotOffobard (Java, C++):

 5package edu.wpi.first.wpilibj.examples.armbotoffboard.subsystems;
 6
 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;
14
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);
23
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  }
32
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  }
41
42  public Command setArmGoalCommand(double kArmOffsetRads) {
43    return Commands.runOnce(() -> setGoal(kArmOffsetRads), this);
44  }
45}

Usar un TrapezoidProfileSubsystem con comandos puede ser bastante 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));
54
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));

Comando TrapezoideProfile

Nota

En C++, la clase TrapezoidProfileCommand se basa en el tipo de unidad utilizada para las mediciones de distancia, que puede ser angular o lineal. Los valores pasados deben tener unidades consistentes con las unidades de distancia, o se lanzará un error en tiempo de compilación. Para obtener más información sobre las unidades C++, consulte Biblioteca de unidades de C++.

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.

Creando un 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.

Nota

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.

En cualquier caso, se crea un TrapezoidProfileCommand pasando los parámetros necesarios a su constructor (si se define una subclase, esto se puede hacer con una llamada super ()):

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

profile

El parámetro profile es el objeto TrapezoidProfile que será ejecutado por el comando. Al pasar esto, los usuarios especifican el estado inicial, el estado final y las restricciones de movimiento del perfil que usará el comando.

output

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.

requisitos

Como todos los comandos en línea, TrapezoidProfileCommand permite al usuario especificar los requisitos de su subsistema como un parámetro de constructor.

Ejemplo completo de TrapezoidProfileCommand

¿Qué aspecto tiene un TrapezoidProfileSubsystem cuando se utiliza en la práctica? Los siguientes ejemplos están tomados del proyecto de ejemplo DriveDistanceOffboard (Java, C++):

 5package edu.wpi.first.wpilibj.examples.drivedistanceoffboard.commands;
 6
 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;
11
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  }
36}

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