Swerve Drive Guide
Swerve drive is the pinnacle of FRC drivetrain Innovation. It offers unmatched agility and performance on the field. In this guide, we’ll walk through the journey of Discovery—from basic kinematics to our elite 250Hz odometry—showing how this subsystem delivers maximum Impact during the heat of competition.
MARS Innovation MomentInnovation isn’t just about having the most complex hardware; it’s about finding creative ways to overcome limits. By decoupling robot rotation from translation, you’ve innovated beyond the constraints of traditional drivetrains. MARSLib supports this by providing the mathematical foundation to push those innovations to their technical ceilings.
What is Swerve Drive?
Section titled “What is Swerve Drive?”In simple terms: Swerve drive means each wheel can both steer AND drive independently.
Think of it like this:
- ❌ Regular drivetrain: Wheels only spin forward/backward.
- ❌ Tank drive: Left and right sides spin at different speeds to turn.
- ✅ Swerve drive: Each wheel can spin AND point in any direction!
Real-world analogy:
- Shopping cart wheels can spin in any direction (like swerve modules)
- But shopping carts can’t drive themselves - our swerve modules can!
Why Swerve Drive is Awesome
Section titled “Why Swerve Drive is Awesome”Superior movement:
- Move in any direction (including sideways!)
- Turn while moving (like a car)
- Rotate in place (spin like a top)
- Combine movements smoothly.
Competition advantages:
- Navigate around defenders easily.
- Align with game pieces quickly.
- Maintain precise positioning.
- Most agile drivetrain in FRC.
Real-game benefits:
- Strafe around obstacles.
- Drive and aim at the same time.
- Quick position adjustments.
- Better path following.
How Swerve Drive Works
Section titled “How Swerve Drive Works”Each Module is Independent
Section titled “Each Module is Independent”A swerve module has two motors:
- Drive motor: Spins the wheel (makes robot move)
- Steer motor: Rotates the wheel (changes direction)
Think of it like a car:
- Drive motor = engine (moves car forward/backward)
- Steer motor = steering wheel (turns the wheels)
But better: Each wheel works independently!
Four Modules Working Together
Section titled “Four Modules Working Together”Your robot has 4 swerve modules:
- Front-left, front-right, rear-left, rear-right.
- Each can point in different directions.
- Each can spin at different speeds.
The magic: Software coordinates all 4 modules to make the robot move smoothly
Part 1: The 250Hz Thread (High-Speed Updates)
Section titled “Part 1: The 250Hz Thread (High-Speed Updates)”Why Speed Matters
Section titled “Why Speed Matters”Regular robot code runs at 50Hz (every 20ms)
- Good enough for simple mechanisms.
- Too slow for precise positioning.
Swerve drive needs 250Hz (every 4ms)
- 5x faster than regular code.
- Calculates position more accurately.
- Robot responds more quickly.
The Problem with 50Hz Updates
Section titled “The Problem with 50Hz Updates”Example: Robot moving at 5 m/s (about 11 mph)
At 50Hz (20ms between updates):
Position updates: 50 times per secondDistance between updates: 5 m/s × 0.02s = 0.1m = 10cmProblem: Robot could drift 10cm between updates!
- Misses auto line by 10cm.
- Overshoots target by 10cm.
- Accumulates errors over time.
The MARSLib Solution: 250Hz Thread
Section titled “The MARSLib Solution: 250Hz Thread”At 250Hz (4ms between updates):
Position updates: 250 times per secondDistance between updates: 5 m/s × 0.004s = 0.02m = 2cmBenefit: 5x more accurate!
- Auto routines hit targets precisely.
- Odometry stays accurate.
- Robot responds instantly.
How MARSLib Does This
Section titled “How MARSLib Does This”Separate thread dedicated to odometry:
- Runs at 250Hz continuously.
- Doesn’t slow down main robot code.
- Uses CANivore bus for fast communication.
- Zero-allocation (no garbage collection pauses)
Real-world result:
- Position accuracy: ±2cm instead of ±10cm.
- Auto success rate: 95%+ instead of 70%.
- Robot responds predictably every time.
Part 2: Swerve Kinematics (Movement Math)
Section titled “Part 2: Swerve Kinematics (Movement Math)”What is Kinematics?
Section titled “What is Kinematics?”In simple terms: Kinematics is the math that calculates how each wheel should move to make the robot move the way you want.
Think of it like this:
- You want robot to move forward at 2 m/s.
- Kinematics calculates: each wheel should spin at X speed.
- You want robot to move sideways at 1 m/s .
- Kinematics calculates: each wheel should point sideways and spin at Y speed.
The Kinematics Equation
Section titled “The Kinematics Equation”Input: What you want robot to do
vx= forward/backward speed.vy= left/right speed.omega= rotation speed (turning)
Output: What each wheel should do
- Module speed = how fast to spin.
- Module angle = which direction to point.
Example: Moving diagonally
// You want: Move diagonally forward-rightdouble vx = 2.0; // 2 m/s forwarddouble vy = 1.0; // 1 m/s rightdouble omega = 0.0; // No rotation
// Kinematics calculates for each module:// Front-left: speed = 2.24 m/s, angle = 26.6°// Front-right: speed = 2.24 m/s, angle = -26.6°// Rear-left: speed = 2.24 m/s, angle = 26.6°// Rear-right: speed = 2.24 m/s, angle = -26.6°Part 3: Field-Oriented Drive
Section titled “Part 3: Field-Oriented Drive”Robot vs Field Orientation
Section titled “Robot vs Field Orientation”Robot-oriented drive:
- Forward = wherever robot is facing.
- Turn robot, “forward” changes.
- Like driving a car in reverse.
Field-oriented drive:
- Forward = always toward opponent’s alliance wall.
- Turn robot, “forward” stays same.
- Much easier for drivers!
How It Works
Section titled “How It Works”Uses gyroscope (IMU) to know which way robot is pointing:
// Driver pushes joystick forwarddouble forward = joystick.getY(); // Say, 0.5
// Robot is rotated 45° on fielddouble robotAngle = gyro.getRotation2d().getDegrees(); // 45°
// Convert field-oriented to robot-orientedChassisSpeeds fieldSpeeds = new ChassisSpeeds( forward * maxSpeed, // Field forward strafe * maxSpeed, // Field left/right rotation * maxAngularSpeed // Rotation);
// WPILib handles rotation automaticallyChassisSpeeds robotSpeeds = ChassisSpeeds.fromFieldRelativeSpeeds( fieldSpeeds, gyro.getRotation2d());What happens:
- Driver pushes “forward” on joystick.
- Robot moves toward opponent’s wall.
- Even if robot is turned sideways!
- Much more intuitive driving.
Part 4: Vision Integration
Section titled “Part 4: Vision Integration”Vision + Odometry = Super Accurate Positioning
Section titled “Vision + Odometry = Super Accurate Positioning”Odometry alone:
- Great for relative position.
- Drifts over time (small errors add up)
- Can get confused by wheel slip.
Vision alone:
- Absolute position (knows exactly where you are)
- Updates slowly (30-50 Hz vs 250 Hz)
- Can be noisy
Together: Perfect!
- Odometry: Fast, smooth updates.
- Vision: Corrects drift occasionally.
- Result: Accurate positioning all match long!
MegaTag 2.0 Integration
Section titled “MegaTag 2.0 Integration”What it is: Advanced vision system that uses camera + gyroscope data
Why it’s awesome:
- Compensates for camera latency.
- Rejects bad measurements.
- Works while robot is spinning.
- Super accurate localization.
MARSLib advantage:
- 250Hz gyro updates (smoother than 50Hz)
- More accurate vision seeding.
- Better pose estimation.
Real-game scenario:
1. Robot spinning while intaking game piece2. Camera sees AprilTag but data is 50ms old3. MARSLib uses latest gyro data to update vision4. Result: Accurate position even while spinning!Part 5: Traction Control
Section titled “Part 5: Traction Control”Why Traction Control Matters
Section titled “Why Traction Control Matters”The problem: When wheels spin faster than robot moves, you lose traction
Real-world example:
- Car on ice: Spin wheels fast, car doesn’t move.
- Robot on field: Turn too sharply, wheels slip, position becomes inaccurate.
Traction control: Prevents wheels from slipping by limiting acceleration
How MARSLib Does Traction Control
Section titled “How MARSLib Does Traction Control”1. Detects slip:
// Compare commanded speed vs actual speeddouble commandedSpeed = module.getTargetSpeed();double actualSpeed = module.getMeasuredSpeed();
double slip = actualSpeed - commandedSpeed;
if (Math.abs(slip) > threshold) { // Wheels are slipping!}2. Limits acceleration:
// Don't accelerate too fastdouble maxAccel = 3.0; // m/s² - safe acceleration
double newSpeed = currentSpeed + maxAccel × deltaTime;
if (newSpeed > commandedSpeed) { newSpeed = currentSpeed + maxAccel × deltaTime;}3. Reduces voltage when slipping:
if (isSlipping()) { double limitedVoltage = voltage × 0.8; // Reduce power motor.setVoltage(limitedVoltage);}Benefits:
- Wheels maintain grip on field.
- Odometry stays accurate.
- More consistent auto paths.
- Better driving performance.
Interactive Swerve Simulator
Section titled “Interactive Swerve Simulator”See how swerve drive works in real-time:
Try this:
- Move joystick to see how modules respond.
- Watch how each wheel points and spins.
- Try field-oriented vs robot-oriented.
- See how rotation affects all modules.
Real-World Performance
Section titled “Real-World Performance”Accuracy Comparison
Section titled “Accuracy Comparison”50Hz odometry (standard FRC):
- Position drift: ~10cm per second.
- Auto accuracy: ~70%.
- Path following: ±15cm error.
250Hz MARSLib odometry:
- Position drift: ~2cm per second .
- Auto accuracy: ~95%+.
- Path following: ±3cm error.
Real impact:
- Auto scores more consistently.
- Robot positions more accurately.
- Drivers have better control.
- Competition performance improves.
Competition Tips
Section titled “Competition Tips”Before Competition
Section titled “Before Competition”Tuning checklist:
- Verify all 4 modules calibrated correctly.
- Test field-oriented drive.
- Auto routines work in simulation.
- Auto routines work on real field.
- Vision integration tested.
- Traction control tuned.
At Competition
Section titled “At Competition”Pre-match checklist:
- Odometry zeroed correctly.
- Gyro calibrated.
- Vision camera working.
- Auto mode selected.
- Test drive briefly.
Monitoring during match:
- Watch odometry accuracy.
- Check module temperatures.
- Monitor CAN bus utilization.
- Verify vision updates.
Troubleshooting
Section titled “Troubleshooting”Robot not moving straight:
- Check module calibration.
- Verify wheel alignment.
- Check for mechanical issues.
Odometry drifting:
- Verify gyro working.
- Check wheel encoders.
- Test vision integration.
Auto not working:
- Test starting position.
- Check path files load correctly.
- Verify pose estimator.
Advanced Topics
Section titled “Advanced Topics”Custom Path Following
Section titled “Custom Path Following”For experienced programmers:
- Custom path following algorithms.
- Adaptive path following.
- Real-time path replanning.
Module Health Monitoring
Section titled “Module Health Monitoring”Detect failing modules early:
public void checkModuleHealth() { for (SwerveModule module : modules) { double temperature = module.getTemperature(); double current = module.getCurrent();
if (temperature > 80) { warn("Module overheating: " + module.getName()); }
if (current > 40) { warn("Module drawing too much current: " + module.getName()); } }}Advanced Kinematics
Section titled “Advanced Kinematics”For maximum performance:
- Custom kinematics optimization.
- Module-specific tuning.
- Adaptive control strategies.
6 Setup & Operations Reference
Section titled “6 Setup & Operations Reference”Infrastructure Scaffold
Section titled “Infrastructure Scaffold”1. Create Your Drivetrain:
public class Drivetrain extends Subsystem { private final SwerveDrive drive;
public Drivetrain() { drive = new SwerveDrive(); }
public void drive(double vx, double vy, double omega) { drive.drive(vx, vy, omega); }}2. Create a Drive Command:
public class DriveCommand extends Command { private final Drivetrain drivetrain; private final XboxController controller;
public DriveCommand(Drivetrain drivetrain, XboxController controller) { this.drivetrain = drivetrain; this.controller = controller; addRequirements(drivetrain); }
@Override public void execute() { double vx = -controller.getLeftY(); double vy = controller.getLeftX(); double omega = controller.getRightX(); drivetrain.drive(vx, vy, omega); }}Essential Drivetrain Methods
Section titled “Essential Drivetrain Methods”// Drive to specific point on fielddrivetrain.driveToPose(new Pose2d(3.0, 2.0, new Rotation2d()));
// Reset robot position to (0,0) facing forwarddrivetrain.seedFieldRelative();
// Turn to face backwardsdrivetrain.driveToPose(new Pose2d(drivetrain.getPose().getTranslation(), new Rotation2d(Math.PI)));Quick Reference
Section titled “Quick Reference”Swerve Drive Benefits
Section titled “Swerve Drive Benefits”- ✅ Move in any direction.
- ✅ Turn while moving.
- ✅ Rotate in place.
- ✅ Field-oriented driving.
- ✅ Most accurate positioning.
MARSLib Swerve Features
Section titled “MARSLib Swerve Features”- ✅ 250Hz odometry updates.
- ✅ MegaTag 2.0 vision integration.
- ✅ Traction control.
- ✅ Field-oriented drive.
- ✅ Zero-allocation structure.
Performance Targets
Section titled “Performance Targets”- Loop time: < 5ms.
- Odometry accuracy: ±2cm.
- Auto success rate: >95%.
- CAN utilization: <60%.
Summary
Section titled “Summary”Key concepts:
- Swerve drive = each wheel steers and drives independently.
- 250Hz updates = 5x more accurate positioning.
- Kinematics = math that coordinates all 4 wheels.
- Field-oriented drive = easier for drivers.
- Vision integration = corrects odometry drift.
Need swerve help? Ask our community directly on our GitHub tracker if you find a bug!