Swerve Drive
This page explains how SwerveDrive works and what it can do. Every SwerveDriveConfig option, with a graphic and an example, is on the SwerveDriveConfig page under this one. To build one from scratch, follow the Swerve Drive tutorial.
How a swerve drive works

You tell the drive how the whole robot should move, as a ChassisVelocities: forward speed, sideways speed and turn rate. The drive's kinematics, built from where each module is, turn that into a speed and an angle for every wheel. Each swerve module then steers and drives its own wheel.
Going the other way, the drive adds up how far each wheel has rolled and combines it with the gyro to estimate where the robot is on the field. That pose is what makes field relative driving, auto-align and path following possible.
Why SwerveDrive is different from other mechanisms
Every other mechanism in YAMS (Arm, Elevator, Pivot, FlyWheel) wraps a single SmartMotorController. SwerveDrive is a mechanism made of mechanisms: it owns an array of SwerveModules, and each SwerveModule owns two SmartMotorControllers of its own (drive and azimuth). SwerveDriveConfig is where the two levels meet: you build each SwerveModule (and its own SwerveModuleConfig) first, then hand the finished modules to SwerveDriveConfig, which derives the robot's kinematics automatically from where you told each module it physically sits.
Basic swerve config
Here is the shape of a four-module config, condensed from the tutorial. The modules are passed front left, front right, back left, back right. The kinematics come from each module's location, so that order is not what makes the robot drive, but arrays such as getModuleStates() and the feedforward Force[] use the same order.
Robot code imports SmartMotorControllerConfig, SwerveDriveConfig, SwerveDrive and SwerveInputStream from the command framework package that matches your vendordep, and everything else from yams.core:
In Commands v3, this is your Mechanism instead of a Subsystem.
A fragment for your subsystem's or mechanism's constructor. driveMotor, azimuthMotor, encoder and gyro are your hardware objects, and the gains are placeholders:
Commands
SwerveDrive has the same commands and functions in Commands v2 and Commands v3.
drive(Supplier<ChassisVelocities>)
✅
✅
Drives with robot relative speeds until interrupted.
driveToPose(Pose2d)
✅
✅
Drives to a pose with the auto-align controllers until interrupted, then stops the drive.
driveToPose(Pose2d, Distance, Angle)
✅
✅
The same, ending once the robot is within the tolerances.
isNear(Pose2d, Distance, Angle)
✅
✅
Whether the robot is within the tolerances of a pose.
stop()
✅
✅
Commands zero speed.
Field relative driving from a controller is a command you write around a SwerveInputStream. These are outlines of the class: config is the SwerveDriveConfig from above.
Driving functions
These set what the drive does and return at once. They are what the commands above are built on.
setFieldRelativeChassisSpeeds(ChassisVelocities)
Drive with speeds measured against the field. This is what a SwerveInputStream gives you.
setRobotRelativeChassisSpeeds(ChassisVelocities)
Drive with speeds measured against the robot. An overload adds a feedforward force per module, for path followers.
setSwerveModuleStates(SwerveModuleVelocity[])
Set every module directly, skipping the kinematics.
lockPose()
Turn the wheels into an X so the robot is hard to push.
resetOdometry(Pose2d)
Tell the drive where it is, and set the gyro to that heading.
zeroGyro()
Make the direction the robot faces now the new zero heading.
addVisionMeasurement(Pose2d, double)
Correct the pose estimate with a vision measurement.
Asking where it is
getPose()
The estimated position and heading on the field.
getRobotRelativeSpeed(), getFieldRelativeSpeed()
How the robot is moving now.
getModuleStates(), getModulePositions()
Each wheel's speed and angle, and how far it has rolled.
getGyroRotation3d()
The robot's attitude from the gyro.
getDistanceFromPose(Pose2d), getAngleDifferenceFromPose(Pose2d)
How far the robot is from a pose.
getField2d()
The Field2d the drive publishes its pose to. Use this one instead of making your own.
Setting up a swerve drive on a real robot
Setting the encoder offsets, checking every direction, tuning the modules and the first drive on the ground are steps in a tutorial now: see Step 5: On the real robot. It ends with the speed limits, the drift corrections and auto-align, in the order to do them.
Module location drives the kinematics
SwerveModuleConfig.withLocation(front, left) is not just bookkeeping. SwerveDrive builds its SwerveDriveKinematics directly from the locations of every module you pass it, so the drive and rotate math is always right for your chassis without you ever constructing a SwerveDriveKinematics yourself.
The withOptimization(true) seen in the config above is a per-module flag, not a drive-level one. See Optimization and Cosine Compensation on the Swerve Module page for what it (and its counterpart withCosineCompensation) actually does.
Gyro integration and field vs. robot relative speeds
SwerveDriveConfig.withGyro(Supplier<Rotation3d>) is what lets SwerveDrive convert between field-relative and robot-relative ChassisVelocities (WPILib 2027's name for ChassisSpeeds). The supplier returns the gyro's full attitude, such as pigeon::getRotation3d or imu::getRotation3d: its yaw is the robot's heading, and its roll and pitch are the robot's tilt. Internally, SwerveDrive always drives the modules with robot-relative speeds; setFieldRelativeChassisSpeeds just rotates the requested speeds into the robot frame using the current heading before handing them to the same code path robot-relative callers use.
withGyroOffset and withGyroInverted correct the gyro's zero and sign without touching your drive code. Both apply to the heading (the yaw).
Gyros mounted on their side
If the gyro is not mounted flat, the robot turning shows up as the gyro's roll or pitch instead of its yaw. withGyroHeadingAxis(GyroAxis) tells SwerveDriveConfig which gyro axis points up through the robot. GyroAxis lives in yams.core.mechanisms.config.enums and has three values:
GyroAxis
Gyro axis pointing up
Use when
YAW
Z
The gyro is mounted flat. This is the default.
ROLL
X
The gyro is on its side, with its Y axis to robot left.
PITCH
Y
The gyro is on its side, with its X axis to robot front.
The gyro's attitude is rotated into the robot's frame first, then withGyroInverted and withGyroOffset are applied to the resulting heading.
Reading the heading
SwerveDrive.getGyroRotation3d() (and SwerveDriveConfig.getGyroRotation3d()) returns the robot's attitude after the heading axis, inversion and offset are applied. Its yaw (getZ(), or toRotation2d()) is the heading, wrapped to +/-180 degrees, and its roll and pitch are the robot's tilt. In simulation, SwerveDrive.getGyroRotation3d() returns the simulated heading with no tilt.
withGyroVelocity and withGyroAngularVelocityScaleFactor correct the path of a robot that drives and turns at the same time, using how fast the gyro says the robot is turning. withGyroAngularVelocityScaleFactor explains how to find the value.
A Commands v2 fragment, in the subsystem's constructor. controller is a CommandGamepad:
Locking the wheels (X pattern)
SwerveDrive.lockPose() turns every wheel to point at the robot center (each module's angle from its withLocation(...)) without driving it. On a rectangular chassis the four wheels form an X, so the robot resists being pushed. Call it every loop for as long as the lock should hold:
In Java each module is locked through SwerveModule.setAzimuthAngle(Rotation2d), which uses SwerveModuleConfig.getLockedState(...). Unlike a normal zero-speed module state, the lock skips the module's velocity deadband, which would otherwise hold the wheels where they are, so the wheels actually turn into the X. With optimization enabled each wheel turns to whichever of the lock angle and its opposite is nearer, since both hold the robot the same way. C++ LockPose() does the same through SwerveModule::SetAzimuthAngle(...). To turn every module to one angle without driving, as the azimuth live tuning does, use setAzimuthAngles(Rotation2d) (C++ SetAzimuthAngles(...)).
How to: follow PathPlanner paths with feedforward forces
setRobotRelativeChassisSpeeds has an overload that accepts a per-module drive-wheel feedforward Force[] (FL, FR, BL, BR order, matching module order) alongside the ChassisVelocities:
This exists specifically to plug into PathPlanner's AutoBuilder.configure(...), whose driveRobotRelative consumer hands back a DriveFeedforwards alongside the requested ChassisVelocities. Its linearForces() is exactly the Force[] this overload expects:
Each module's drive SmartMotorController converts its share of the Force[] into the correct feedforward for whatever control mode it's using (voltage or torque-current) via SmartMotorControllerConfig.convertToVoltage(...)/convertToCurrent(...), which need withGearing(...) and withMechanismCircumference(...)/withWheelRadius(...) configured on that motor to do the conversion. Passing an empty Force[] (or just calling the original single-argument overload) skips the feedforward entirely, so existing code that only calls setRobotRelativeChassisSpeeds(speeds) keeps working unchanged.
Auto-Align
SwerveDrive has a built-in field relative auto-align.
driveToPose(Pose2d)
Returns a Command that drives to the pose until it is interrupted, then stops the drive.
driveToPose(Pose2d, Distance, Angle)
Returns a Command that drives to the pose and ends once the robot is within the distance and heading tolerances, then stops the drive.
isNear(Pose2d, Distance, Angle)
Whether the robot is within the distance and heading tolerances of the pose.
driveToPoseSetpoint(Pose2d)
Computes the ChassisVelocities that drive toward the pose, for use in your own command.
The commands and driveToPoseSetpoint use the translation and rotation PIDControllers from SwerveDriveConfig.withTranslationController(...) and withRotationController(...). Each command is a Commands v2 or Commands v3 Command, depending on which SwerveDrive you use, and all of them exist in both.
A fragment for your bindings. driver is a CommandGamepad:
Use the version with tolerances whenever something has to happen after the robot arrives. The version without them never ends on its own.
Telemetry verbosity
Like every other mechanism, SwerveDriveConfig.withTelemetry(name, TelemetryVerbosity) picks a preset bundle of fields to publish, from pose and gyro angle at LOW up to full desired/measured chassis speeds and module states at HIGH. Each level includes everything the level below it publishes.
Field
NetworkTables key
LOW
MID
HIGH
Pose
pose
✓
✓
✓
Gyro angle
gyro
✓
✓
✓
Current robot-relative ChassisVelocities
chassis/current
✓
✓
Field-relative ChassisVelocities
chassis/field
✓
✓
Current module states
states/current
✓
✓
Desired robot-relative ChassisVelocities
chassis/desired
✓
Desired module states
states/desired
✓
Translation P/I/D (tunable)
autoalign/translation/p,i,d
✓
Rotation P/I/D (tunable)
autoalign/rotation/p,i,d
✓
Auto-align target X (tunable)
autoalign/setpoint/x
✓
Auto-align target Y (tunable)
autoalign/setpoint/y
✓
Auto-align target rotation (tunable)
autoalign/setpoint/rot
✓
Auto-align enabled (tunable)
autoalign/enabled
✓
Modules drive P/I/D (tunable, shared)
modules/drive/feedback/p,i,d
✓
Modules drive kS/kV/kA (tunable, shared)
modules/drive/feedforward/s,v,a
✓
Modules drive velocity (tunable, shared)
modules/drive/velocity
✓
Modules drive tuning enabled (tunable)
modules/drive/enabled
✓
Modules drive in place (tunable)
modules/drive/inplace
✓
Modules drive voltage (tunable, shared)
modules/drive/voltage/setpoint
✓
Modules drive voltage enabled (tunable)
modules/drive/voltage/enabled
✓
Modules azimuth P/I/D (tunable, shared)
modules/azimuth/feedback/p,i,d
✓
Modules azimuth kS/kV/kA (tunable, shared)
modules/azimuth/feedforward/s,v,a
✓
Modules azimuth angle (tunable, shared)
modules/azimuth/angle
✓
Modules azimuth tuning enabled (tunable)
modules/azimuth/enabled
✓
Modules azimuth voltage (tunable, shared)
modules/azimuth/voltage/setpoint
✓
Modules azimuth voltage enabled (tunable)
modules/azimuth/voltage/enabled
✓
Using SwerveDriveTelemetryConfig directly
Pass a SwerveDriveTelemetryConfig instead of a verbosity level when you need finer control than a preset gives you, such as disabling the auto-align tuning fields, or routing telemetry to a DataLog instead of NetworkTables during competition:
SwerveDriveTelemetryConfig(TelemetryVerbosity) is a shorthand constructor equivalent to new SwerveDriveTelemetryConfig().withTelemetryVerbosity(verbosity), useful when you're about to layer more with*() calls on top anyway. See Telemetry for the shared telemetry architecture these configs build on.
Code reference
Last updated
Was this helpful?
