EasyStack Docs

SwerveDrivetrain

Esta página aún no está traducida. Se muestra la versión en inglés.

SwerveDrivetrain

SwerveDrivetrain coordinates exactly four SwerveModule objects. It converts a robot relative chassis request into one velocity vector per module, reduces all vectors together if a wheel exceeds maxSpeed, and applies the resulting targets.

Creating the drivetrain

The module order is front right, front left, back left, back right. This differs from MecanumDrive. Supply center to center dimensions, not the outside dimensions of the frame.

Java
import dev.easyfamily.easystack.drivebase.swerve.coaxial
        .SwerveDrivetrain;

SwerveDrivetrain swerve = new SwerveDrivetrain(
        0.60,       // Track width, meters.
        0.70,       // Wheelbase, meters.
        3.0,        // Maximum wheel speed, meters/second.
        frontRight, frontLeft, backLeft, backRight
);

The alternative constructor takes the same three numbers followed by a SwerveModule array in the same order. The constructor rejects arrays with a length other than four, null arrays, null modules, and dimensions or maxSpeed less than or equal to zero.

Consistent speed and geometry

Use the same maximum speed in all modules and in the drivetrain for this example. The drivetrain desaturates against its own maxSpeed, but each module converts velocity to power using its individual value.

getMaxAngularSpeed() returns maxSpeed divided by the distance from the chassis center to a corner module. That radius is calculated from half the track width and half the wheelbase. For 0.60 m by 0.70 m and 3.0 m/s, the derived angular speed is about 6.51 rad/s.

getTrackWidth(), getWheelBase(), and getMaxSpeed() return these constructor settings. They are configuration values, not measured motion.

Driving the swerve chassis

Setting and updating velocity

setTargetVelocity() stores a robot relative request after applying its component limit calculation. It does not immediately update hardware. Call update() afterward to calculate and apply all four wheel vectors.

Java
swerve.setTargetVelocity(new ChassisSpeed(1.0, 0.0, 0.5));
Vector2d[] appliedTargets = swerve.update();

updateWithTargetVelocity() combines those two operations. Use it once per active control iteration when a new request is available.

Java
swerve.updateWithTargetVelocity(
        new 0.0, 0.5)

If any module vector exceeds the drivetrain’s maxSpeed, update() scales all four vectors by the same factor. This preserves their relative magnitudes. The returned array contains those post-scaling target vectors in constructor order, not measured wheel velocities.

Reading state and using the common interface

getTargetVelocity() returns the stored chassis request after the component limit calculation. It is not recomputed from the final desaturated module vectors, so it is not necessarily the motion represented by their final magnitudes.

Java
 = swerve.getTargetVelocity();
swerve.drive(new DrivePowers(1.@, 0.25, 0.5));

The drive() adapter maps forward to vx, strafe to vy, and turn to omega. In this call, the values are velocities: 1.0 forward units per second, 0.25 left units per second, and 0.5 rad/s. They are not normalized motor powers. Prefer ChassisSpeed when that makes the units clearer in your program.

Swerve output limits

What maxOutput changes

SwerveDrivetrain inherits setMaxOutput(), but it does not multiply final wheel powers by that value. setTargetVelocity() uses maxSpeed × maxOutput as a limit for each linear component and maxAngularSpeed × maxOutput as a limit for omega. If a component exceeds its limit, all three components are divided by the largest excess ratio.

Java
swerve.setMaxOutput (O .5);
swerve.setTargetVelocity(new ChassisSpeed(3.0, 0.0, 0.0));
swerve.update();

With maxSpeed = 3.0, this pure forward request is reduced to 1.5 units per second. However, a combined translation and rotation request can produce a wheel speed above 1.5. The final desaturation in update() still uses maxSpeed, not maxSpeed × maxOutput.

Limits that require attention

A maxOutput of zero does not act as a stop in this implementation. Its component checks only run when the calculated limits are positive, so zero or negative values skip those checks. Use stop() to stop hardware.

Changing maxOutput does not immediately rescale a previously stored target. Its component limit is evaluated the next time setTargetVelocity() is called. Continue submitting fresh requests in the loop.

A clear driver slow mode

For predictable input scaling, scale a joystick-derived ChassisSpeed explicitly. The control example later in this guide also bounds combined translation and rotation conservatively so a scale of 0.35 corresponds to at most 35 percent of the configured wheel speed before module angle compensation.

Java
swerve.setMaxOutput (1.0);
ChassisSpeed slowerRequest
swerve.updateWithTargetVelocity(slowerRequest);

Scaling alone is not a guaranteed wheel speed cap for an arbitrary oversized nominalRequest. Its effect must be considered together with the chassis request and module desaturation.

Swerve X lock and stopping

Requesting X lock

updateWithXLock() sends a fixed direction to each module using the constructor order. The angles are −45, 45, 135, and 225 degrees for front right, front left, back left, and back right.

Java
swerve.updateWithXLock();

The method uses a vector magnitude of 0.0001 rather than exactly zero. This gives each vector an explicit direction but also means the calculated traction command can be slightly nonzero. Wheel flip optimization may choose the equivalent opposite steering direction.

Call this method repeatedly while the lock mode is active so the steering wrappers continue updating. Do not also call ordinary update() in that branch, because it would overwrite the lock commands using the stored chassis target.

X lock does not clear targetVelocity and does not use the normal chassis limit or desaturation path. The fixed diagonal angles are a stance command, not a guarantee that the robot cannot be pushed.

Stopping and accessing modules

Java
swerve.stop();
 = swerve.getModule(O);
SwerveModule[] modules = swerve.getModules();

stop() calls stop() on every module, stopping traction and steering. It leaves the stored chassis target intact. Calling update() afterward can resume the old request; submit an intentional new target when restarting control.

getModules() returns a copy of the array, so replacing an entry in that returned array does not replace an internal module. The contained module objects themselves are shared references. getModule(index) returns one internal module, with valid indexes from 0 through 3.

Building four swerve modules

The following setup uses initialized drive motors and EasyCRServo steering objects. Configure their angle feedback in radians and their motor directions beforehand. The example uses meters and the tangential offset convention explained earlier.

Java
double trackWidth = 0.60;
double wheelBase = 0.70;
double maxSpeed = 3.0;
double halfWidth = trackWidth / 2.0;
double halfLength = wheelBase / 2.0;

SwerveModule frontRight = new SwerveModule(
        frontRightMotor, frontRightSteering,
        new Vector2d(halfWidth, halfLength), maxSpeed);

SwerveModule frontLeft = new SwerveModule(
        frontLeftMotor, frontLeftSteering,
        new Vector2d(-halfWidth, halfLength), maxSpeed);

SwerveModule backLeft = new SwerveModule(
        backLeftMotor, backLeftSteering,
        new Vector2d(-halfWidth, -halfLength), maxSpeed);

SwerveModule backRight = new SwerveModule(
Java
        backRightMotor, backRightSteering,
        new Vector2d(halfWidth, -halfLength), maxSpeed);

SwerveDrivetrain swerve = new SwerveDrivetrain(
        trackWidth, wheelBase, maxSpeed,
        frontRight, frontLeft, backLeft, backRight);
swerve.setMaxOutput(1.0);

Use the imports shown in the ChassisSpeed and SwerveModule sections, plus SwerveDrivetrain. Each named hardware variable above is an existing object from your hardware initialization; the example does not assume an unprovided wrapper constructor.

Before combining translation and rotation, verify a forward request, a leftward request, and a small positive rotation request separately. With the stated Cartesian convention and converted offsets, positive rotation should produce tangential module vectors. Correct angle zeroes, signs, and module placement before relying on combined motion.

Swerve driver control example

This helper converts FTC sticks to robot relative physical velocities. Negative left stick Y requests forward motion. Negative left stick X requests positive leftward motion, and negative right stick X requests positive counterclockwise rotation under the convention used in this guide.

Java
import com.qualcomm.robotcore.hardware.Gamepad;
import dev.easyfamily.easystack.drivebase.swerve.ChassisSpeed;
import dev.easyfamily.easystack.drivebase.swerve.coaxial
        .SwerveDrivetrain;

public class SwerveControls {
    private final SwerveDrivetrain drive;

    public SwerveControls(SwerveDrivetrain drive) {
        this.drive = drive;
        drive.setMaxOutput(1.0);
    }

    public void update(Gamepad pad, boolean xLock,
            boolean slowMode) {
        if (xLock) {
            drive.updateWithXLock();
            return;
        }
Java
        double x = -pad.left_stick_y;
        double y = -pad.left_stick_x;
        double turn = -pad.right_stick_x;
        double budget = Math.max(1.0,
                Math.hypot(x, y) + Math.abs(turn));
        double scale = (slowMode ? 0.35 : 1.0) / budget;
        drive.updateWithTargetVelocity(new ChassisSpeed(
                x * drive.getMaxSpeed() * scale,
                y * drive.getMaxSpeed() * scale,
                turn * drive.getMaxAngularSpeed() * scale));
    }

    public void stop() {
        drive.stop();
    }
}

The budget shares available wheel speed between translation and rotation. It is a conservative input policy added by this example, not a built-in method. Its bound assumes the rectangular geometry and matching module speed settings from the previous page.

Integrating the control loop

Create hardware and drivebase objects once during initialization. Reuse the control helper on each active loop, and call stop() when leaving the control session. Reconstructing the drivebase every loop is unnecessary and makes configuration harder to maintain.

Calling a helper from an FTC OpMode

The following loop assumes swerve is the configured drivetrain from the setup example and is placed inside a LinearOpMode. A selects X lock while held, and left bumper selects slow mode. The helper uses live Gamepad values; it does not depend on an EasyGamepad API.

Java
SwerveControls controls = new SwerveControls(swerve);

waitForStart();
try {
    while (opModeIsActive()) {
        controls.update(gamepad1,
                gamepad1.a, gamepad1.left_bumper);
        telemetry.addData("Target",
                swerve.getTargetVelocity());
        telemetry.addData("Front right angle",
                swerve.getModule(0).getCurrentAngle());
        telemetry.update();
        idle();
    }
} finally {
    controls.stop();
}

The stored chassis target displayed during X lock can still show the last normal request, because X lock bypasses that target. Read individual module targets or angles when you want information about the lock stance.

The differential, mecanum, and holonomic helpers follow the same lifecycle. Call their update method with the appropriate mode inputs and current heading where needed. Their mixing methods apply output immediately, so they do not need a separate drivebase update() call.

Swerve steering does need repeated updates. Calling setTargetVelocity() once without update(), or sending a steering target only once and then skipping the loop, does not provide the continuous control shown here.

Swerve setup checks

Check one movement at a time before combining translation and rotation. The following checks apply to the supplied swerve implementation.

SymptomWhat to check
Swerve turns wheels toward the centerWhether physical offsets were passed where the implementation expects tangential directions
Swerve steering moves but traction is weakAngle error, cosine compensation, and maxSpeed configuration
Swerve moves again after stopAn update reused the stored target
Swerve maxOutput of zero still movesZero skips the component limit checks; use stop

What the guide does not assume

The provided files do not define motor wrapper constructors, steering feedback setup, IMU initialization, odometry, or path following. The examples therefore accept configured hardware and describe the calls these drivebase classes actually expose. They have been checked against the supplied source; hardware behavior still depends on your mechanism and wrapper implementations.

Source files covered

This guide covers DifferentialDrive.java, HolonomicDrive.java, MecanumDrive.java, DrivePowers.java, Drivetrain.java, RobotDrive.java, ChassisSpeed.java, SwerveModule.java, and SwerveDrivetrain.java. It documents these supplied versions rather than assuming behavior from another library with similarly named classes.

Use the guide alongside your hardware configuration. Keep motor order, direction, length units, angle units, and the chosen field reference consistent across the complete control path.

Última actualización 2026-11-16

EasyStack - FTC Java library

This site records page views of visitors to understand how the documentation is used. Nothing is sold or shared with third parties.