For the complete documentation index, see llms.txt. This page is also available as Markdown.
Swerve Drive
Learn how to program a Swerve Drive.
This tutorial needs three libraries: YAMS, REVLib (for the SparkMax motor controllers) and Phoenix 6 (for the CANcoders and the Pigeon2). Create a project and install YAMS walks through installing them.
Intro
This tutorial builds a swerve drive that works in real life and simulation with the same code.
You ask for a chassis speed. SwerveDrive works out the four modules.
Details
This swerve drive uses the following hardware and controls:
4x CANcoder absolute encoders, CAN IDs 3, 6, 9, 12
Pigeon2 gyro, CAN ID 14
SDS MK4 L2 modules: drive gear ratio 6.75:1, azimuth gear ratio 12.8:1, 4 inch wheels
The left stick translates, and the right stick's X axis rotates
Holding the left bumper drives to a pose on the field, and the top face button zeroes the gyro
YAMS simulates all eight motors, so a swerve simulation uses more of your computer than a single mechanism does. If it runs slowly, close other programs while it runs.
The steps
The three coding steps, one page each. Step 4 then tunes it in simulation, and step 5 runs it on the real robot.
Every step has a tab for Java with Commands v2, Java with Commands v3 and C++. Steps 1 to 3 each end with a check you can run, and each check names the likely failures. Troubleshooting has more.
Set the encoder offsets, check every direction, tune the modules and drive on the ground.
Complete example
The following files from the YAMS simple_robot-2027 Commands v2 example are a complete swerve drive for the same hardware. The example has no encoder offsets or tuned gains, so it is a reference for the code, not for your robot's numbers.
// Copyright (c) 2026 Yet Another Software Suite
// SPDX-License-Identifier: LGPL-3.0-or-later
package first.robot.subsystems;
import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.DegreesPerSecond;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.MetersPerSecond;
import static org.wpilib.units.Units.Radians;
import static org.wpilib.units.Units.RotationsPerSecond;
import com.ctre.phoenix6.CANBus;
import org.wpilib.hardware.bus.CANPort;
import com.ctre.phoenix6.hardware.CANcoder;
import com.ctre.phoenix6.hardware.Pigeon2;
import com.revrobotics.util.CANPorts;
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.math.controller.PIDController;
import org.wpilib.math.geometry.Pose2d;
import org.wpilib.math.geometry.Rotation2d;
import org.wpilib.math.geometry.Rotation3d;
import org.wpilib.math.geometry.Translation2d;
import org.wpilib.math.kinematics.ChassisVelocities;
import org.wpilib.math.system.DCMotor;
import org.wpilib.command2.Command;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.command2.button.CommandNiDsXboxController;
import java.util.function.Supplier;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.config.SwerveDriveConfig;
import yams.commands2.swerve.SwerveDrive;
import yams.commands2.swerve.SwerveInputStream;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.SwerveModuleConfig;
import yams.core.mechanisms.swerve.SwerveModule;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;
public class SwerveSubsystem extends SubsystemBase {
private final SwerveDrive drive;
public SwerveModule createModule(
SparkMax drive,
SparkMax azimuth,
CANcoder absoluteEncoder,
String moduleName,
Translation2d location) {
MechanismGearing driveGearing = new MechanismGearing(GearBox.fromReductionStages(6.75));
MechanismGearing azimuthGearing = new MechanismGearing(GearBox.fromReductionStages(12.8));
SmartMotorControllerConfig driveCfg =
new SmartMotorControllerConfig(this)
.withWheelDiameter(Inches.of(4))
.withClosedLoopController(0.4, 0, 0)
// .withFeedforward(new SimpleMotorFeedforward(0, 0.7, 0.1))
.withGearing(driveGearing)
.withStatorCurrentLimit(Amps.of(40))
.withTelemetry("driveMotor", TelemetryVerbosity.HIGH);
SmartMotorControllerConfig azimuthCfg =
new SmartMotorControllerConfig(this)
.withClosedLoopController(3.8476, 0, 0)
.withContinuousWrapping(Radians.of(-Math.PI), Radians.of(Math.PI))
.withGearing(azimuthGearing)
.withStatorCurrentLimit(Amps.of(40))
.withTelemetry("angleMotor", TelemetryVerbosity.HIGH);
SmartMotorController driveSMC = new SparkWrapper(drive, DCMotor.getNEO(1), driveCfg);
SmartMotorController azimuthSMC = new SparkWrapper(azimuth, DCMotor.getNEO(1), azimuthCfg);
SwerveModuleConfig moduleConfig =
new SwerveModuleConfig(driveSMC, azimuthSMC)
.withAbsoluteEncoder(absoluteEncoder.getAbsolutePosition().asSupplier())
.withTelemetry(moduleName, TelemetryVerbosity.HIGH)
.withLocation(location)
.withOptimization(true);
return new SwerveModule(moduleConfig);
}
private final Pigeon2 gyro = new Pigeon2(14, new CANBus(CANPort.CAN_S0));
public SwerveSubsystem()
{
var fl = createModule(new SparkMax(CANPorts.fromBusId(1), 1, MotorType.kBrushless),
new SparkMax(CANPorts.fromBusId(1), 2, MotorType.kBrushless),
new CANcoder(3, new CANBus(CANPort.CAN_S0)),
"frontleft",
new Translation2d(Inches.of(24), Inches.of(24)));
var fr = createModule(new SparkMax(CANPorts.fromBusId(1), 4, MotorType.kBrushless),
new SparkMax(CANPorts.fromBusId(1), 5, MotorType.kBrushless),
new CANcoder(6, new CANBus(CANPort.CAN_S0)),
"frontright",
new Translation2d(Inches.of(24), Inches.of(-24)));
var bl = createModule(new SparkMax(CANPorts.fromBusId(1), 7, MotorType.kBrushless),
new SparkMax(CANPorts.fromBusId(1), 8, MotorType.kBrushless),
new CANcoder(9, new CANBus(CANPort.CAN_S0)),
"backleft",
new Translation2d(Inches.of(-24), Inches.of(24)));
var br = createModule(new SparkMax(CANPorts.fromBusId(1), 10, MotorType.kBrushless),
new SparkMax(CANPorts.fromBusId(1), 11, MotorType.kBrushless),
new CANcoder(12, new CANBus(CANPort.CAN_S0)),
"backright",
new Translation2d(Inches.of(-24), Inches.of(-24)));
SwerveDriveConfig config = new SwerveDriveConfig(this, fl, fr, bl, br)
.withGyro(gyro::getRotation3d)
.withMaximumChassisSpeed(MetersPerSecond.of(4), RotationsPerSecond.of(360))
.withStartingPose(new Pose2d(0, 0, Rotation2d.fromDegrees(0)))
.withTranslationController(new PIDController(1, 0, 0))
.withRotationController(new PIDController(1, 0, 0));
drive = new SwerveDrive(config);
}
public Command setRobotRelativeChassisSpeeds(ChassisVelocities speeds)
{
return run(() -> drive.setRobotRelativeChassisSpeeds(speeds));
}
public Command driveToPose(Pose2d pose) {
return drive.driveToPose(pose);
}
public Command driveRobotRelative(Supplier<ChassisVelocities> speedsSupplier)
{
return drive.drive(speedsSupplier);
}
/**
* Drive the robot field-relative using a driver controller, converting joystick axes into {@link
* ChassisVelocities} via {@link SwerveInputStream}.
*
* @param controller Driver controller to read translation/rotation axes from.
* @return {@link Command} that drives the robot while scheduled.
*/
public Command driveWithJoystick(CommandNiDsXboxController controller) {
SwerveInputStream inputStream =
SwerveInputStream.of(drive, () -> -controller.getLeftY(), () -> -controller.getLeftX())
.withControllerRotationAxis(() -> -controller.getRightX())
.withMaximumLinearVelocity(MetersPerSecond.of(4))
.withMaximumAngularVelocity(DegreesPerSecond.of(360))
.withDeadband(0.05)
.withCubeTranslationControllerAxis()
.withAllianceRelativeControl()
.withTelemetry("Driver", TelemetryVerbosity.HIGH);
return drive.drive(
() -> inputStream.get().toRobotRelative(drive.getGyroRotation3d().toRotation2d()));
}
public Command lock() {
return run(drive::lockPose);
}
@Override
public void periodic() {
drive.updateTelemetry();
}
@Override
public void simulationPeriodic() {
drive.simIterate();
gyro.getSimState().setRawYaw(drive.getSimPose().getRotation().getDegrees());
}
public Pose2d getPose() {
return drive.getPose();
}
public ChassisVelocities getFieldOrientedChassisSpeed()
{
return drive.getFieldRelativeSpeed();
}
public Rotation3d getGyroRotation3d() {
return drive.getGyroRotation3d();
}
}
// Copyright (c) 2026 Yet Another Software Suite
// SPDX-License-Identifier: LGPL-3.0-or-later
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package first.robot;
import static org.wpilib.units.Units.Degrees;
import static org.wpilib.units.Units.Meters;
import static org.wpilib.units.Units.RPM;
import org.wpilib.driverstation.internal.DriverStationBackend;
import org.wpilib.command2.Command;
import org.wpilib.command2.Commands;
import org.wpilib.command2.button.CommandNiDsXboxController;
import first.robot.subsystems.ArmSubsystem;
import first.robot.subsystems.ElevatorSubsystem;
import first.robot.subsystems.ShooterSubsystem;
import first.robot.subsystems.SwerveSubsystem;
public class RobotContainer {
private final SwerveSubsystem drive = new SwerveSubsystem();
private final ArmSubsystem arm = new ArmSubsystem();
private final ElevatorSubsystem elevator = new ElevatorSubsystem();
private final ShooterSubsystem shooter = new ShooterSubsystem();
private final CommandNiDsXboxController xboxController = new CommandNiDsXboxController(0);
public RobotContainer() {
DriverStationBackend.silenceJoystickConnectionAlert(true);
drive.setDefaultCommand(drive.driveWithJoystick(xboxController));
arm.setDefaultCommand(arm.setAngle(Degrees.of(0)));
elevator.setDefaultCommand(elevator.setHeight(Meters.of(0)));
shooter.setDefaultCommand(shooter.setVelocity(RPM.of(0)));
configureBindings();
}
private void configureBindings() {
xboxController.getHID().button(1).whileTrue(arm.setAngle(Degrees.of(30)));
xboxController.getHID().button(2).whileTrue(arm.setAngle(Degrees.of(80)));
xboxController.getHID().button(3).whileTrue(elevator.setHeight(Meters.of(0.5)));
xboxController.getHID().button(4).whileTrue(elevator.setHeight(Meters.of(1.5)));
xboxController.getHID().button(5).whileTrue(shooter.setVelocity(RPM.of(3500)));
xboxController.getHID().button(6).whileTrue(shooter.setVelocity(RPM.of(2000)));
}
public Command getAutonomousCommand() {
return Commands.print("No autonomous command configured");
}
}