Class SwerveDrive
java.lang.Object
yams.core.mechanisms.swerve.SwerveDrive
- Direct Known Subclasses:
SwerveDrive, SwerveDrive
Swerve Drive mechanism.
This core class holds swerve state, odometry, and physics simulation only. Command
factories such as drive() live on SwerveDrive, which
extends this class. See that class's Javadoc for a full usage example.
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected SwerveDriveTelemetryTelemetry and live tuning of the drive. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedSwerveDrive(SwerveDriveConfig<?> config) Create a SwerveDrive. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddVisionMeasurement(org.wpilib.math.geometry.Pose2d robotPose, double timestamp) Add a vision measurement to theSwerveDrivePoseEstimatorand update the gyro reading with the given timestamp of the vision measurement.voidaddVisionMeasurement(org.wpilib.math.geometry.Pose2d robotPose, double timestamp, org.wpilib.math.linalg.Matrix<org.wpilib.math.numbers.N3, org.wpilib.math.numbers.N1> visionMeasurementStdDevs) Add a vision measurement to theSwerveDrivePoseEstimatorand update the gyro reading with the given timestamp of the vision measurement.voidApply the live-tuned values (from NetworkTables) to thisSwerveDrive's drive-to-pose controllers.org.wpilib.math.kinematics.ChassisVelocitiesdriveToPoseSetpoint(org.wpilib.math.geometry.Pose2d targetPose) Drive to the target pose, primarily for use in Live Tuning, could also be used for setpoint commands.org.wpilib.math.kinematics.ChassisVelocitiesdriveToPoseSetpoint(org.wpilib.math.geometry.Pose2d targetPose, org.wpilib.math.geometry.Pose2d currentPose, org.wpilib.math.geometry.Rotation2d heading) Drive to the target pose from a given pose, e.g.org.wpilib.units.measure.AnglegetAngleDifferenceFromPose(org.wpilib.math.geometry.Pose2d pose) Get the angle difference between the robot's current pose and the given pose.Get theSwerveDriveConfigof the drive.org.wpilib.math.kinematics.ChassisVelocitiesGet the last-commanded desired robot-relativeChassisVelocitiesof the drive.org.wpilib.math.kinematics.SwerveModuleVelocity[]Get the last-commanded desiredSwerveModuleVelocitys of the drive.org.wpilib.units.measure.DistancegetDistanceFromPose(org.wpilib.math.geometry.Pose2d pose) Get theDistancefrom the given pose to the robot.org.wpilib.smartdashboard.Field2dGet theField2dused to display the robot's pose, so callers (e.g.org.wpilib.math.kinematics.ChassisVelocitiesGet the field relative speed of the drive.org.wpilib.math.geometry.Rotation3dGet the robot's attitude from the gyro (seeSwerveDriveConfig.getGyroRotation3d()): its yaw is the robot's heading.org.wpilib.math.kinematics.SwerveDriveKinematicsCreate theSwerveDriveKinematicsso you can recreate a newSwerveDrivePoseEstimator.Get a module by its name.org.wpilib.math.kinematics.SwerveModulePosition[]Get theSwerveModulePositionof the modules.Get allSwerveModules for thisSwerveDrive.org.wpilib.math.kinematics.SwerveModuleVelocity[]Get theSwerveModuleVelocityof the modules.getName()Get the name of the drive.org.wpilib.math.geometry.Pose2dgetPose()Gets the measured pose (position and rotation) of the robot, as reported by odometry.org.wpilib.math.kinematics.ChassisVelocitiesgetRobotRelativeChassisSpeedsFromState(org.wpilib.math.kinematics.SwerveModuleVelocity[] states) Get theChassisVelocitiesbased off theSwerveModuleVelocitys.org.wpilib.math.kinematics.ChassisVelocitiesGet the robot relative speed of the drive.org.wpilib.math.geometry.Pose2dGet the simulated pose of the robot, assuming theSwerveModuleVelocitys commanded to the modules are met perfectly.org.wpilib.math.kinematics.SwerveModuleVelocity[]getStateFromRobotRelativeChassisSpeeds(org.wpilib.math.kinematics.ChassisVelocities robotRelativeChassisSpeeds) Get theSwerveModuleVelocitys of the swerve drive given a robot relative chassis speed.booleanisNear(org.wpilib.math.geometry.Pose2d pose, org.wpilib.units.measure.Distance translationTolerance, org.wpilib.units.measure.Angle rotationTolerance) Whether the robot is within the given tolerances of a pose.voidlockPose()Point all modules toward the robot center, thus making the robot very difficult to move.voidresetOdometry(org.wpilib.math.geometry.Pose2d pose) Resets odometry to the given pose, and sets the gyro to read the pose's heading.voidResets the auto-align rotational PID controller, if one is configured.voidResets the auto-align translation PID controller, if one is configured.voidsetAzimuthAngles(org.wpilib.math.geometry.Rotation2d angle) Turn every module to the given angle without driving, as for tuning the azimuth motors.voidsetFieldRelativeChassisSpeeds(org.wpilib.math.kinematics.ChassisVelocities fieldRelativeChassisSpeeds) Set field relative chassis speeds.voidsetRobotRelativeChassisSpeeds(org.wpilib.math.kinematics.ChassisVelocities robotRelativeChassisSpeeds) Set robot relative chassis speeds.voidsetRobotRelativeChassisSpeeds(org.wpilib.math.kinematics.ChassisVelocities robotRelativeChassisSpeeds, org.wpilib.units.measure.Force[] feedforwardForces) Set robot relative chassis speeds, with an additional drive wheel feedforwardForceapplied per module, e.g.voidsetRotationPID(org.wpilib.math.controller.PIDController controller) Set the auto-align rotational PID controller.voidsetSwerveModuleStates(org.wpilib.math.kinematics.SwerveModuleVelocity[] states) Set theSwerveModuleVelocitys of the swerve drive directly.voidsetSwerveModuleStates(org.wpilib.math.kinematics.SwerveModuleVelocity[] states, org.wpilib.units.measure.Force[] feedforwardForces) Set theSwerveModuleVelocitys of the swerve drive directly, with an additional drive wheel feedforwardForceapplied per module, e.g.voidsetTranslationPID(org.wpilib.math.controller.PIDController controller) Sets the auto-align translation PID controller.voidsetVisionMeasurementStdDevs(org.wpilib.math.linalg.Matrix<org.wpilib.math.numbers.N3, org.wpilib.math.numbers.N1> visionMeasurementStdDevs) Sets the pose estimator's trust of global measurements.voidSimulate the drive, updating the gyroscope based off of module states.voidReset the auto-align PID controllers and pull the live-tuned values (from NetworkTables) into thisSwerveDrive.voidstop()Stop the drive by commanding zero chassis speeds.voidUpdate the telemetry andSwerveDrivePoseEstimatorof the drive.voidzeroGyro()Resets the gyro angle to zero and resets odometry to the same position, but facing toward 0 (red alliance station).
-
Field Details
-
m_swerveTelemetry
Telemetry and live tuning of the drive.
-
-
Constructor Details
-
SwerveDrive
Create a SwerveDrive.- Parameters:
config-SwerveDriveConfigfor the drive.- Throws:
IllegalStateException- on a real robot (not in simulation), if no gyro supplier was set withSwerveDriveConfig.withGyro(java.util.function.Supplier).SmartMotorControllerConfigurationException- if a module's drive motor has no mechanism circumference configured (e.g. viaSwerveModuleConfig.withWheelRadius(Distance)), so its position cannot be converted to a distance.- Implementation Note:
- Protected so only
SwerveDrivecan construct this.
-
-
Method Details
-
startDriveToPoseTuning
public void startDriveToPoseTuning()Reset the auto-align PID controllers and pull the live-tuned values (from NetworkTables) into thisSwerveDrive. Intended to be wired into a periodic/scheduled callback by the command layer, e.g. viayams.commands2.swerve.SwerveDrive's drive-to-pose tuning command. -
applyTuningValues
public void applyTuningValues()Apply the live-tuned values (from NetworkTables) to thisSwerveDrive's drive-to-pose controllers. Intended to be wired into a periodic/scheduled callback by the command layer.- Throws:
IllegalStateException- if the auto-align tuning toggle is enabled and a gyro angular velocity scale factor is configured withSwerveDriveConfig.withGyroAngularVelocityScaleFactor(double)but no gyro supplier was set withSwerveDriveConfig.withGyro(java.util.function.Supplier).
-
getGyroRotation3d
public org.wpilib.math.geometry.Rotation3d getGyroRotation3d()Get the robot's attitude from the gyro (seeSwerveDriveConfig.getGyroRotation3d()): its yaw is the robot's heading. In simulation, the simulated heading with no tilt.- Returns:
- The robot's attitude.
-
getSimPose
public org.wpilib.math.geometry.Pose2d getSimPose()Get the simulated pose of the robot, assuming theSwerveModuleVelocitys commanded to the modules are met perfectly. Useful for feeding a simulated vision system with ground-truth poses under perfect-world conditions.- Returns:
- Simulated
Pose2dof the robot. Only updated in simulation bysimIterate(); on a real robot this remains the configured starting pose.
-
lockPose
public void lockPose()Point all modules toward the robot center, thus making the robot very difficult to move. Forcing the robot to keep the current pose.- Implementation Note:
- Not compatible with AdvantageKit
-
setAzimuthAngles
public void setAzimuthAngles(org.wpilib.math.geometry.Rotation2d angle) Turn every module to the given angle without driving, as for tuning the azimuth motors. The velocity deadband does not hold the wheels where they are (seeSwerveModule.setAzimuthAngle(Rotation2d)).- Parameters:
angle- Angle to turn every module to.
-
setSwerveModuleStates
public void setSwerveModuleStates(org.wpilib.math.kinematics.SwerveModuleVelocity[] states) Set theSwerveModuleVelocitys of the swerve drive directly.- Parameters:
states-SwerveModuleVelocitys to use, must be the same count as the swerve drive is configured order is Clockwise from FL.- Implementation Note:
- Not compatible with AdvantageKit if MapleSim is defined.
-
setSwerveModuleStates
public void setSwerveModuleStates(org.wpilib.math.kinematics.SwerveModuleVelocity[] states, org.wpilib.units.measure.Force[] feedforwardForces) Set theSwerveModuleVelocitys of the swerve drive directly, with an additional drive wheel feedforwardForceapplied per module, e.g. from a PathPlanner set-point generator.- Parameters:
states-SwerveModuleVelocitys to use, must be the same count as the swerve drive is configured order is Clockwise from FL.feedforwardForces- FeedforwardForces to apply, one per module in the same FL, FR, BL, BR order asstates.- Implementation Note:
- Not compatible with AdvantageKit if MapleSim is defined.
-
getStateFromRobotRelativeChassisSpeeds
public org.wpilib.math.kinematics.SwerveModuleVelocity[] getStateFromRobotRelativeChassisSpeeds(org.wpilib.math.kinematics.ChassisVelocities robotRelativeChassisSpeeds) Get theSwerveModuleVelocitys of the swerve drive given a robot relative chassis speed. When a maximum module speed is configured withSwerveDriveConfig.withMaximumModuleSpeed(LinearVelocity), the module speeds are scaled down together so none exceeds it, also respectingSwerveDriveConfig.withMaximumChassisSpeed(LinearVelocity, AngularVelocity)if set, which keeps the direction of travel and rotation intact.- Parameters:
robotRelativeChassisSpeeds- Robot relativeChassisVelocities.- Returns:
SwerveModuleVelocitys of the swerve drive.- Throws:
IllegalStateException- if a gyro angular velocity scale factor is configured withSwerveDriveConfig.withGyroAngularVelocityScaleFactor(double)but no gyro supplier was set withSwerveDriveConfig.withGyro(java.util.function.Supplier).
-
getRobotRelativeChassisSpeedsFromState
public org.wpilib.math.kinematics.ChassisVelocities getRobotRelativeChassisSpeedsFromState(org.wpilib.math.kinematics.SwerveModuleVelocity[] states) Get theChassisVelocitiesbased off theSwerveModuleVelocitys.- Parameters:
states-SwerveModuleVelocitys to use, must be the same count as the swerve drive is.- Returns:
ChassisVelocitiesbased off theSwerveModuleVelocitys.
-
setRobotRelativeChassisSpeeds
public void setRobotRelativeChassisSpeeds(org.wpilib.math.kinematics.ChassisVelocities robotRelativeChassisSpeeds) Set robot relative chassis speeds.- Parameters:
robotRelativeChassisSpeeds- Robot relative chassis speeds.- Throws:
IllegalStateException- if a gyro angular velocity scale factor is configured withSwerveDriveConfig.withGyroAngularVelocityScaleFactor(double)but no gyro supplier was set withSwerveDriveConfig.withGyro(java.util.function.Supplier).
-
setRobotRelativeChassisSpeeds
public void setRobotRelativeChassisSpeeds(org.wpilib.math.kinematics.ChassisVelocities robotRelativeChassisSpeeds, org.wpilib.units.measure.Force[] feedforwardForces) Set robot relative chassis speeds, with an additional drive wheel feedforwardForceapplied per module, e.g. from a PathPlanner set-point generator.- Parameters:
robotRelativeChassisSpeeds- Robot relative chassis speeds.feedforwardForces- FeedforwardForces to apply, one per module in FL, FR, BL, BR order. Pass an empty array to apply no feedforward.- Throws:
IllegalArgumentException- iffeedforwardForcesis not empty and its length does not match the number of modules.IllegalStateException- if a gyro angular velocity scale factor is configured withSwerveDriveConfig.withGyroAngularVelocityScaleFactor(double)but no gyro supplier was set withSwerveDriveConfig.withGyro(java.util.function.Supplier).
-
setFieldRelativeChassisSpeeds
public void setFieldRelativeChassisSpeeds(org.wpilib.math.kinematics.ChassisVelocities fieldRelativeChassisSpeeds) Set field relative chassis speeds.- Parameters:
fieldRelativeChassisSpeeds- Field relative chassis speeds.- Throws:
IllegalStateException- if a gyro angular velocity scale factor is configured withSwerveDriveConfig.withGyroAngularVelocityScaleFactor(double)but no gyro supplier was set withSwerveDriveConfig.withGyro(java.util.function.Supplier).
-
getPose
public org.wpilib.math.geometry.Pose2d getPose()Gets the measured pose (position and rotation) of the robot, as reported by odometry.- Returns:
- The robot's pose
-
getKinematics
public org.wpilib.math.kinematics.SwerveDriveKinematics getKinematics()Create theSwerveDriveKinematicsso you can recreate a newSwerveDrivePoseEstimator.- Returns:
SwerveDriveKinematics
-
zeroGyro
public void zeroGyro()Resets the gyro angle to zero and resets odometry to the same position, but facing toward 0 (red alliance station).- Implementation Note:
- Not compatible with AdvantageKit
-
getName
-
resetOdometry
public void resetOdometry(org.wpilib.math.geometry.Pose2d pose) Resets odometry to the given pose, and sets the gyro to read the pose's heading. Field relative driving and heading control use the gyro, so keeping it aligned with the pose makes them agree with the reset pose. Module positions do not need to be reset when calling this method.- Parameters:
pose- The pose to set the odometry to. Field relative, blue-origin where 0deg is facing towards RED alliance.
-
resetRotationPID
public void resetRotationPID()Resets the auto-align rotational PID controller, if one is configured. -
resetTranslationPID
public void resetTranslationPID()Resets the auto-align translation PID controller, if one is configured. -
setRotationPID
public void setRotationPID(org.wpilib.math.controller.PIDController controller) Set the auto-align rotational PID controller.- Parameters:
controller-PIDControllerto use, units given is in Radians.
-
setTranslationPID
public void setTranslationPID(org.wpilib.math.controller.PIDController controller) Sets the auto-align translation PID controller.- Parameters:
controller-PIDControllerto reset, Units given is in Meters.
-
getDistanceFromPose
public org.wpilib.units.measure.Distance getDistanceFromPose(org.wpilib.math.geometry.Pose2d pose) Get theDistancefrom the given pose to the robot.- Parameters:
pose-Pose2dto get the distance from.- Returns:
Distancefrom the given pose to the robot.
-
getAngleDifferenceFromPose
public org.wpilib.units.measure.Angle getAngleDifferenceFromPose(org.wpilib.math.geometry.Pose2d pose) Get the angle difference between the robot's current pose and the given pose.- Parameters:
pose-Pose2dto get the angle difference from.- Returns:
Angledifference between the robot's current pose and the given pose.
-
isNear
public boolean isNear(org.wpilib.math.geometry.Pose2d pose, org.wpilib.units.measure.Distance translationTolerance, org.wpilib.units.measure.Angle rotationTolerance) Whether the robot is within the given tolerances of a pose.- Parameters:
pose-Pose2dto compare against.translationTolerance- Maximum distance from the pose.rotationTolerance- Maximum heading error from the pose.- Returns:
- True if the robot is within both tolerances of the pose.
-
stop
public void stop()Stop the drive by commanding zero chassis speeds.- Throws:
IllegalStateException- if a gyro angular velocity scale factor is configured but no gyro supplier was set withwithGyro(Supplier).
-
driveToPoseSetpoint
public org.wpilib.math.kinematics.ChassisVelocities driveToPoseSetpoint(org.wpilib.math.geometry.Pose2d targetPose) Drive to the target pose, primarily for use in Live Tuning, could also be used for setpoint commands.- Parameters:
targetPose- Pose to drive towards.- Returns:
- robot-relative
ChassisVelocitiesto drive the robot to the given pose. - Throws:
SwerveDriveConfigurationException- if the translation PID controller is not configured.SwerveDriveConfigurationException- if the rotation PID controller is not configured.- Implementation Note:
- Remember to call
resetRotationPID()andresetTranslationPID()before calling this method in a loop.
-
driveToPoseSetpoint
public org.wpilib.math.kinematics.ChassisVelocities driveToPoseSetpoint(org.wpilib.math.geometry.Pose2d targetPose, org.wpilib.math.geometry.Pose2d currentPose, org.wpilib.math.geometry.Rotation2d heading) Drive to the target pose from a given pose, e.g. a pose replayed from a log. The translation speed is the translation PID output toward the target, proportional to the distance for a P controller.- Parameters:
targetPose- Pose to drive towards.currentPose- Pose of the robot.heading- Heading of the robot, used to convert the result to robot-relative speeds.- Returns:
- robot-relative
ChassisVelocitiesto drive the robot to the given pose. - Throws:
SwerveDriveConfigurationException- if the translation PID controller is not configured.SwerveDriveConfigurationException- if the rotation PID controller is not configured.- Implementation Note:
- Remember to call
resetRotationPID()andresetTranslationPID()before calling this method in a loop.
-
addVisionMeasurement
public void addVisionMeasurement(org.wpilib.math.geometry.Pose2d robotPose, double timestamp, org.wpilib.math.linalg.Matrix<org.wpilib.math.numbers.N3, org.wpilib.math.numbers.N1> visionMeasurementStdDevs) Add a vision measurement to theSwerveDrivePoseEstimatorand update the gyro reading with the given timestamp of the vision measurement.- Parameters:
robotPose- RobotPose2das measured by vision.timestamp- Timestamp the measurement was taken as time since startup, should be taken fromTimer.getTimestamp()or similar sources.visionMeasurementStdDevs- Vision measurement standard deviation that will be sent to theSwerveDrivePoseEstimator.The standard deviation of the vision measurement, for best accuracy calculate the standard deviation at 2 or more points and fit a line to it with the calculated optimal standard deviation. (Units should be meters per pixel). By optimizing this you can get * vision accurate to inches instead of feet.
-
setVisionMeasurementStdDevs
public void setVisionMeasurementStdDevs(org.wpilib.math.linalg.Matrix<org.wpilib.math.numbers.N3, org.wpilib.math.numbers.N1> visionMeasurementStdDevs) Sets the pose estimator's trust of global measurements. This might be used to change trust in vision measurements after the autonomous period, or to change trust as distance to a vision target increases.- Parameters:
visionMeasurementStdDevs- Standard deviations of the vision measurements. Increase these numbers to trust global measurements from vision less. This matrix is in the form [x, y, theta], with units in meters and radians.
-
addVisionMeasurement
public void addVisionMeasurement(org.wpilib.math.geometry.Pose2d robotPose, double timestamp) Add a vision measurement to theSwerveDrivePoseEstimatorand update the gyro reading with the given timestamp of the vision measurement.- Parameters:
robotPose- RobotPose2das measured by vision.timestamp- Timestamp the measurement was taken as time since startup, should be taken fromTimer.getTimestamp()or similar sources.
-
updateTelemetry
public void updateTelemetry()Update the telemetry andSwerveDrivePoseEstimatorof the drive. -
simIterate
public void simIterate()Simulate the drive, updating the gyroscope based off of module states. -
getRobotRelativeSpeed
public org.wpilib.math.kinematics.ChassisVelocities getRobotRelativeSpeed()Get the robot relative speed of the drive.- Returns:
- Robot relative speed of the drive.
-
getFieldRelativeSpeed
public org.wpilib.math.kinematics.ChassisVelocities getFieldRelativeSpeed()Get the field relative speed of the drive.- Returns:
- Field relative speed of the drive.
-
getModulePositions
public org.wpilib.math.kinematics.SwerveModulePosition[] getModulePositions()Get theSwerveModulePositionof the modules.- Returns:
SwerveModulePositionof the modules.
-
getModuleStates
public org.wpilib.math.kinematics.SwerveModuleVelocity[] getModuleStates()Get theSwerveModuleVelocityof the modules.- Returns:
SwerveModuleVelocityof the modules.
-
getConfig
Get theSwerveDriveConfigof the drive.- Returns:
SwerveDriveConfigof the drive.
-
getField2d
public org.wpilib.smartdashboard.Field2d getField2d()Get theField2dused to display the robot's pose, so callers (e.g. vision subsystems) can publish additionalFieldObject2ds onto the same field widget instead of creating their own.- Returns:
Field2dof the drive.
-
getDesiredChassisSpeeds
public org.wpilib.math.kinematics.ChassisVelocities getDesiredChassisSpeeds()Get the last-commanded desired robot-relativeChassisVelocitiesof the drive. This is the value cached bysetRobotRelativeChassisSpeeds(ChassisVelocities)(whichsetFieldRelativeChassisSpeeds(ChassisVelocities)andSwerveDrive.drive(java.util.function.Supplier)funnel through) and published on everyupdateTelemetry()call.- Returns:
- Robot-relative
ChassisVelocitieslast commanded to the drive. Defaults to a zeroedChassisVelocitiesif the drive has never been commanded. - Implementation Note:
- It is a setpoint, not a measurement of actual robot motion.
Use
getRobotRelativeSpeed()orgetFieldRelativeSpeed()instead if you need the drive's actual measured speed.
-
getDesiredModuleStates
public org.wpilib.math.kinematics.SwerveModuleVelocity[] getDesiredModuleStates()Get the last-commanded desiredSwerveModuleVelocitys of the drive.- Returns:
SwerveModuleVelocitys last commanded to the drive. Defaults to a zeroedSwerveModuleVelocitys if the drive has never been commanded.
-
getModule
Get a module by its name.- Parameters:
moduleName- Name of the module.- Returns:
SwerveModulewith the given name if it exists.
-
getModules
Get allSwerveModules for thisSwerveDrive.- Returns:
- Array of
SwerveModules.
-