Lab 4: First Drive (Translation Only)¶
Goal: drive the robot! All four wheels point where the stick points, and roll at a speed set by how far you push it. No rotation yet, and no kinematics: that comes in Lab 5.
Why: the simplest swerve¶
If the robot isn't rotating, every point on it moves with the same velocity. So all four modules get the same state:
stick (x, y) → angle = atan2(y, x)
speed = maxSpeed × √(x² + y²)
SwerveModuleState holds exactly that: a speed (m/s) and an angle (Rotation2d).
Optimization: never turn more than 90°. Pull the stick from straight up to straight down. Without optimization, every wheel rotates 180° before the robot reverses. But a wheel pointing at 0° rolling backward is the same as a wheel at 180° rolling forward. So:
error = target − current, wrapped into (−180°, 180°]
if |error| > 90°:
target = target + 180°
speed = −speed
Example: current 0°, target 170°, +2 m/s → target −10°, −2 m/s. The module turns 10° instead of 170°.
Holding the angle at zero. When you let go of the stick, atan2(0, 0) = 0°, so every wheel would snap to forward. Instead, if the speed is ~0, keep the last angle.
Students write: MyModuleOptimizer¶
Create src/main/java/frc/robot/lib/MyModuleOptimizer.java. Write the body yourselves before looking anything up:
package frc.robot.lib;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.SwerveModuleState;
public final class MyModuleOptimizer {
private MyModuleOptimizer() {}
/**
* Returns a state that reaches the same wheel motion as `desired`
* while rotating the module at most 90° from `currentAngle`.
*/
public static SwerveModuleState optimize(SwerveModuleState desired, Rotation2d currentAngle) {
// TODO (students):
// 1. error = desired angle minus current angle. Hint: Rotation2d.minus() wraps for you.
// 2. If |error| > 90°, flip the angle by 180° and negate the speed.
// 3. Return a NEW SwerveModuleState.
return desired;
}
}
Then write a unit test in src/test/java/frc/robot/lib/MyModuleOptimizerTest.java that compares yours to WPILib's. In 2026 WPILib, optimize is an instance method that changes the state in place (state.optimize(currentAngle)); the old static version is deprecated. Test at least: target 0°, ±90°, ±180°, and crossing ±180° (current 170°, target −170°).
@Test
void flipsWhenMoreThan90Away() {
var desired = new SwerveModuleState(2.0, Rotation2d.fromDegrees(170));
var current = Rotation2d.fromDegrees(0);
var ours = MyModuleOptimizer.optimize(desired, current);
var wpilib = new SwerveModuleState(desired.speedMetersPerSecond, desired.angle);
wpilib.optimize(current);
assertEquals(wpilib.speedMetersPerSecond, ours.speedMetersPerSecond, 1e-9);
assertEquals(wpilib.angle.getRadians(), ours.angle.getRadians(), 1e-9);
}
Run with ./gradlew test. No robot needed.
Code¶
SwerveModule gets the method every later lab uses:
private Rotation2d lastAngle = new Rotation2d();
/** Drive this module at a speed (m/s) and angle. Call every loop. */
public void setDesiredState(SwerveModuleState desired) {
if (Tunable.toggle("Swerve/UseOptimization", true)) {
desired = MyModuleOptimizer.optimize(desired, getAngle());
}
// Stick released: keep pointing where we were instead of snapping to 0°.
boolean stopped = Math.abs(desired.speedMetersPerSecond) < 0.01;
Rotation2d targetAngle =
(stopped && Tunable.toggle("Swerve/HoldAngleAtZero", true)) ? lastAngle : desired.angle;
lastAngle = targetAngle;
setSteerTarget(targetAngle);
// Open loop for now: 12 V ≈ theoretical top speed, so scale linearly. Lab 6 replaces this.
double driveVolts = 12.0 * desired.speedMetersPerSecond / Constants.Swerve.MAX_THEORETICAL_SPEED_METERS_PER_SECOND;
io.setDriveVoltage(driveSign() * driveVolts);
desiredState = new SwerveModuleState(desired.speedMetersPerSecond, targetAngle);
}
private SwerveModuleState desiredState = new SwerveModuleState();
public SwerveModuleState getDesiredState() { return desiredState; }
public SwerveModuleState getState() {
return new SwerveModuleState(getDriveVelocityMetersPerSecond(), getAngle());
}
SwerveSubsystem publishes the states so AdvantageScope can draw them:
// imports: edu.wpi.first.networktables.NetworkTableInstance,
// edu.wpi.first.networktables.StructArrayPublisher
private final StructArrayPublisher<SwerveModuleState> desiredPublisher =
NetworkTableInstance.getDefault()
.getStructArrayTopic("Swerve/DesiredStates", SwerveModuleState.struct).publish();
private final StructArrayPublisher<SwerveModuleState> actualPublisher =
NetworkTableInstance.getDefault()
.getStructArrayTopic("Swerve/ActualStates", SwerveModuleState.struct).publish();
public void setAllModules(SwerveModuleState state) {
for (SwerveModule module : modules) {
module.setDesiredState(state);
}
}
// in periodic():
SwerveModuleState[] desired = new SwerveModuleState[4];
SwerveModuleState[] actual = new SwerveModuleState[4];
for (int i = 0; i < 4; i++) {
desired[i] = modules[i].getDesiredState();
actual[i] = modules[i].getState();
}
desiredPublisher.set(desired);
actualPublisher.set(actual);
Students write the stick math in RobotContainer (fill in the TODOs):
swerve.setDefaultCommand(Commands.run(() -> {
double deadband = Tunable.number("Drive/Deadband", 0.1);
double maxSpeed = Tunable.number("Drive/MaxSpeedMps", 0.5);
// Robot frame: +X forward, +Y left. Xbox: up and left are NEGATIVE.
double x = MathUtil.applyDeadband(-controller.getLeftY(), deadband);
double y = MathUtil.applyDeadband(-controller.getLeftX(), deadband);
// TODO (students): speed (m/s) and angle from x and y.
double speedMetersPerSecond = 0;
Rotation2d angle = new Rotation2d();
swerve.setAllModules(new SwerveModuleState(speedMetersPerSecond, angle));
}, swerve));
Try it¶
- AdvantageScope → new tab → Swerve. Add
Swerve/DesiredStates(red) andSwerve/ActualStates(blue). - Add
Sim/TrueModuleStates(green) too. Push the stick up, left, diagonal. Do the true wheels match the arrows? - New tab → 2D Field. Add
Sim/TruePose. Drive forward, left, diagonal at 0.5 m/s: the robot moves on the field and should not rotate. - Turn the robot? You can't yet. (Lab 5.)
Experiments¶
| Change | Predict | What you'll see |
|---|---|---|
Flick the stick from up to down, UseOptimization on |
How far do the wheels turn? | They don't turn; they reverse |
Same, UseOptimization off |
Every wheel spins 180° first; the robot pauses | |
Let go of the stick, HoldAngleAtZero off |
Wheels snap back to 0° each time | |
Drive/Deadband = 0 |
Robot creeps when nobody touches the stick (sticks don't center perfectly) | |
Drive/Deadband = 0.4 |
Large dead zone; hard to drive slowly | |
| Push the stick to a diagonal corner: what's the speed? | √(1² + 1²) = 1.41 × max! | Fix it: clamp the magnitude to 1 |
Square the magnitude (m * m) before scaling |
Easier or harder to drive slowly? | Easier: fine control near center, full speed at the edge |
Checkpoint¶
Summary: With no rotation, every module gets the same state. Optimization keeps turns under 90°.
Quiz
- Stick at 45° up-left, max 0.5 m/s. What state does each module get?
- Current 10°, target 200°, +1 m/s. What does the optimizer return?
- Why does holding the last angle matter when the driver releases the stick?
- Why can't this code rotate the robot?
- Why does a diagonal stick need clamping?
What could go wrong in the real world: a wheel that drives backward because of a bad offset or inversion (try Sim/Faults/FL/DriveReversed: the robot creeps sideways or rotates); the stick axis mapped wrong (robot drives sideways when you push up); an optimizer that doesn't wrap angles and flips back and forth near ±90°; one bad offset making the robot slowly rotate while translating.