### Define Module Configuration Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Example configuration for an individual swerve module, specifying motor IDs, encoder offsets, and physical location. ```json { "drive": { "type": "sparkmax", "id": 4, "canbus": null }, "angle": { "type": "sparkmax", "id": 3, "canbus": null }, "encoder": { "type": "cancoder", "id": 9, "canbus": null }, "inverted": { "drive": false, "angle": false }, "absoluteEncoderOffset": -114.609, "location": { "front": 12, "left": 12 } } ``` -------------------------------- ### Initialize Swerve Drive with JSON Configuration Source: https://github.com/yet-another-software-suite/yagsl_old/blob/main/README.md Initialize the entire swerve drive using a JSON configuration file. Ensure the necessary libraries like NavX, Phoenix, REVLib, and ReduxLib are installed. ```java import edu.wpi.first.math.util.Units; SwerveDrive swerveDrive=new SwerveParser(new File(Filesystem.getDeployDirectory(),"swerve")).createSwerveDrive(Units.feetToMeters(14.5)); ``` -------------------------------- ### Get Robot Pose and Heading with SwerveDrive Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Retrieves the current estimated robot pose and heading from odometry. Requires the SwerveDrive instance to be initialized. ```java import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import swervelib.SwerveDrive; public class DriveSubsystem { private SwerveDrive swerveDrive; /** * Get the current estimated robot pose */ public Pose2d getPose() { return swerveDrive.getPose(); } /** * Get current robot heading from odometry */ public Rotation2d getHeading() { return swerveDrive.getOdometryHeading(); } } ``` -------------------------------- ### Get Gyroscope Data Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Retrieves heading (yaw), pitch, and roll from the robot's IMU. This data is crucial for navigation and orientation. ```java import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Rotation3d; import edu.wpi.first.math.geometry.Translation3d; import swervelib.SwerveDrive; import swervelib.imu.SwerveIMU; import java.util.Optional; public class DriveSubsystem { private SwerveDrive swerveDrive; /** * Get yaw (heading) from IMU */ public Rotation2d getYaw() { return swerveDrive.getYaw(); } /** * Get pitch from IMU */ public Rotation2d getPitch() { return swerveDrive.getPitch(); } /** * Get roll from IMU */ public Rotation2d getRoll() { return swerveDrive.getRoll(); } /** * Get full 3D rotation */ public Rotation3d getGyroRotation3d() { return swerveDrive.getGyroRotation3d(); } /** * Get acceleration (if supported by gyro) */ public Optional getAcceleration() { return swerveDrive.getAccel(); } /** * Set gyro to specific angle */ public void setGyro(Rotation3d gyro) { swerveDrive.setGyro(gyro); } /** * Access raw IMU object */ public SwerveIMU getGyro() { return swerveDrive.getGyro(); } } ``` -------------------------------- ### Get Swerve Module States Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Retrieves the current velocity and angle for all swerve modules. This is useful for monitoring the robot's current motion. ```java import edu.wpi.first.math.kinematics.SwerveModuleState; import swervelib.SwerveDrive; public class DriveSubsystem { private SwerveDrive swerveDrive; /** * Get all module states (velocity and angle) */ public SwerveModuleState[] getModuleStates() { return swerveDrive.getStates(); } /** * Get all module positions (distance and angle) */ public SwerveModulePosition[] getModulePositions() { return swerveDrive.getModulePositions(); } /** * Set module states directly (for autonomous paths) */ public void setModuleStates(SwerveModuleState[] states, boolean isOpenLoop) { swerveDrive.setModuleStates(states, isOpenLoop); } } ``` -------------------------------- ### Zero Gyroscope with SwerveDrive Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Resets the gyroscope to zero and updates the robot's heading accordingly. This is typically done at the start of a match or autonomous period. ```java import swervelib.SwerveDrive; public class DriveSubsystem { private SwerveDrive swerveDrive; /** * Zero the gyro and reset heading */ public void zeroGyro() { swerveDrive.zeroGyro(); } } ``` -------------------------------- ### Initialize SwerveDrive from JSON Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Use the SwerveParser class to load configuration files from the deploy directory and instantiate the SwerveDrive object. ```java import edu.wpi.first.math.util.Units; import edu.wpi.first.wpilibj.Filesystem; import swervelib.SwerveDrive; import swervelib.parser.SwerveParser; import java.io.File; import java.io.IOException; public class DriveSubsystem { private SwerveDrive swerveDrive; public DriveSubsystem() { try { // Create SwerveDrive from JSON files in deploy/swerve directory File swerveDirectory = new File(Filesystem.getDeployDirectory(), "swerve"); double maxSpeedMPS = Units.feetToMeters(14.5); // Maximum robot speed in meters/second swerveDrive = new SwerveParser(swerveDirectory).createSwerveDrive(maxSpeedMPS); // Optionally specify custom conversion factors // double angleConversionFactor = SwerveMath.calculateDegreesPerSteeringRotation(12.8, 1); // double driveConversionFactor = SwerveMath.calculateMetersPerRotation(Units.inchesToMeters(4), 6.75, 1); // swerveDrive = new SwerveParser(swerveDirectory).createSwerveDrive(maxSpeedMPS, angleConversionFactor, driveConversionFactor); } catch (IOException e) { throw new RuntimeException("Failed to parse swerve configuration", e); } } } ``` -------------------------------- ### Create SwerveDrive from JSON Configuration Source: https://github.com/yet-another-software-suite/yagsl_old/wiki/Legacy-Home Instantiate a SwerveDrive object using a JSON configuration file located in the deploy directory. Ensure the maximum speed is specified. ```java import java.io.File; import edu.wpi.first.wpilibj.Filesystem; import swervelib.parser.SwerveParser; import swervelib.SwerveDrive; import edu.wpi.first.math.util.Units; double maximumSpeed = Units.feetToMeters(4.5) File swerveJsonDirectory = new File(Filesystem.getDeployDirectory(),"swerve"); SwerveDrive swerveDrive = new SwerveParser(directory).createSwerveDrive(maximumSpeed); ``` -------------------------------- ### Calculate Target Speeds and Apply Slew Rate Limiters Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Demonstrates how to generate ChassisSpeeds from joystick inputs or target angles and apply acceleration limits to prevent jerky movement. ```java import edu.wpi.first.math.filter.SlewRateLimiter; import edu.wpi.first.math.kinematics.ChassisSpeeds; import swervelib.SwerveDrive; import swervelib.SwerveController; public class DriveSubsystem { private SwerveDrive swerveDrive; public void useController() { SwerveController controller = swerveDrive.getSwerveController(); double maxSpeed = swerveDrive.getMaximumChassisVelocity(); double currentHeading = swerveDrive.getOdometryHeading().getRadians(); // Get speeds with heading control using two joysticks // Left stick: translation, Right stick: heading direction ChassisSpeeds speeds = controller.getTargetSpeeds( -0.5, // X input (forward) 0.3, // Y input (strafe) 0.8, // Heading X (right stick) 0.6, // Heading Y (right stick) currentHeading, maxSpeed ); // Get speeds with specific target angle ChassisSpeeds angleSpeeds = controller.getTargetSpeeds( -0.5, // X input 0.3, // Y input Math.PI / 2, // Target angle in radians currentHeading, maxSpeed ); // Get raw speeds with omega (angular velocity) ChassisSpeeds rawSpeeds = controller.getRawTargetSpeeds( 2.0, // X speed in m/s 1.5, // Y speed in m/s 1.0 // Omega in rad/s ); // Add slew rate limiters to prevent jerky movement controller.addSlewRateLimiters( new SlewRateLimiter(3), // X acceleration limit (m/s^2) new SlewRateLimiter(3), // Y acceleration limit new SlewRateLimiter(3) // Angular acceleration limit ); } } ``` -------------------------------- ### Define swervedrive.json Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Main configuration file defining the IMU hardware and the list of module configuration files. ```json { "imu": { "type": "pigeon2", "id": 13, "canbus": "canivore" }, "invertedIMU": true, "modules": [ "frontleft.json", "frontright.json", "backleft.json", "backright.json" ] } ``` -------------------------------- ### Supported Hardware Configuration Strings Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Use these string identifiers within your JSON configuration files to define motors, encoders, and IMUs. ```java /** * Supported device types for JSON configuration: * * Motors: * - "sparkmax" / "neo" - REV SparkMax with NEO motor * - "sparkflex" - REV SparkFlex * - "sparkmax_brushed" - SparkMax with brushed motor * - "falcon" / "talonfx" - CTRE Falcon 500 / Kraken * - "talonfxs" - CTRE TalonFXS * - "talonsrx" - CTRE Talon SRX * - "thriftynova" - ThriftyBot ThriftyNova * * Absolute Encoders: * - "cancoder" - CTRE CANCoder * - "canandcoder" / "canandcoder_can" - Redux Canandcoder * - "throughbore" / "dutycycle" - REV Through Bore Encoder * - "analog" - Analog absolute encoder * - "thrifty" - ThriftyBot encoder * - "attached" / "integrated" - Motor integrated encoder * - "sparkmax_analog" - SparkMax analog port * - "ma3" / "rev_hex" / "am_mag" / "ctre_mag" - Various mag encoders * * IMUs: * - "pigeon2" - CTRE Pigeon 2.0 * - "pigeon" - CTRE Pigeon 1.0 * - "navx" / "navx_spi" / "navx_usb" / "navx_i2c" - Kauai Labs NavX * - "adis16470" - Analog Devices ADIS16470 * - "adis16448" - Analog Devices ADIS16448 * - "adxrs450" - Analog Devices ADXRS450 * - "analog" - Analog gyro * - "canandgyro" - Redux Canandgyro */ ``` -------------------------------- ### Swerve Drive Configuration (`swervedrive.json`) Source: https://github.com/yet-another-software-suite/yagsl_old/wiki/Swerve-Drive The `swervedrive.json` file defines the parameters for the robot's Swerve Drive system. It is used to create a `SwerveDriveConfiguration` object, which in turn initializes the `SwerveDrive` object. ```APIDOC ## Swerve Drive Configuration (`swervedrive.json`) ### Description This JSON file configures the overall Swerve Drive system for the robot. It directly corresponds to the `SwerveDriveJson.java` class, which is responsible for creating the `SwerveDriveConfiguration` and subsequently the `SwerveDrive` object. ### JSON Fields #### Required Fields - **imu** (Device) - Required - The robot's Inertial Measurement Unit (IMU) used for determining the robot's heading. - **invertedIMU** (Boolean) - Required - Specifies the inversion state of the IMU. - **modules** (String array) - Required - An array of strings representing the module JSON configurations. These should be listed in clockwise order, starting from the front-left module. ### Example Configuration ```json { "imu": { "type": "BNO086", "port": 0 }, "invertedIMU": false, "modules": [ "frontLeft", "frontRight", "backRight", "backLeft" ] } ``` ``` -------------------------------- ### Define controllerproperties.json Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Configures joystick deadbands and heading correction PID values. ```json { "angleJoystickRadiusDeadband": 0.5, "heading": { "p": 0.4, "i": 0, "d": 0.01 } } ``` -------------------------------- ### Configure Swerve Drive Optimizations and Limits Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Apply performance enhancements like chassis discretization and heading correction, and define speed constraints for the swerve drive system. ```java import swervelib.SwerveDrive; public class DriveSubsystem { private SwerveDrive swerveDrive; public void configureOptimizations() { // Enable chassis velocity correction (reduces drift during rotation) // Based on Team 254's discretization compensation swerveDrive.setChassisDiscretization( true, // Enable in teleop true, // Enable in auto 0.02 // Loop period in seconds ); // Enable angular velocity skew compensation // Helps reduce skew when translating while rotating swerveDrive.setAngularVelocityCompensation( true, // Enable in teleop true, // Enable in auto 0.1 // Coefficient (typically -0.15 to 0.15) ); // Enable heading correction // Maintains heading when driving straight swerveDrive.setHeadingCorrection(true); swerveDrive.setHeadingCorrection(true, 0.01); // With custom deadband // Enable/disable cosine compensation // Reduces wheel scrub when changing direction swerveDrive.setCosineCompensator(true); // Enable auto-centering of modules // Modules will rotate to forward position when stopped swerveDrive.setAutoCenteringModules(true); // Enable encoder auto-synchronization // Syncs integrated encoders with absolute encoders when stopped swerveDrive.setModuleEncoderAutoSynchronize(true, 3.0); // 3 degree deadband } public void configureSpeedLimits() { // Set attainable speed limits for desaturation swerveDrive.setMaximumAttainableSpeeds( 4.5, // Max translational speed m/s Math.PI * 2 // Max rotational velocity rad/s ); // Set allowable speed limits (can be lower than attainable) swerveDrive.setMaximumAllowableSpeeds( 4.0, // Allowed max translational speed Math.PI // Allowed max rotational velocity ); } } ``` -------------------------------- ### Create SwerveDrive with Custom Conversion Factors Source: https://github.com/yet-another-software-suite/yagsl_old/wiki/Legacy-Home Instantiate a SwerveDrive object with custom drive and steering conversion factors. This is an alternative to specifying them in the swerve drive's JSON configuration. ```java double DriveConversionFactor = SwerveMath.calculateMetersPerRotation(Units.inchesToMeters(WHEEL_DIAMETER), GEAR_RATIO, ENCODER_RESOLUTION); double SteeringConversionFactor = SwerveMath.calculateDegreesPerSteeringRotation(GEAR_RATIO, ENCODER_RESOLUTION); new SwerveParser(directory).createSwerveDrive(maximumSpeed, SteeringConversionFactor, DriveConversionFactor); ``` -------------------------------- ### Swerve Module Configuration (`module/x.json`) Source: https://github.com/yet-another-software-suite/yagsl_old/wiki/Swerve-Module This configuration file defines the unique properties for each swerve module, including its drive, angle, and encoder configurations, as well as its physical location and inversion states. ```APIDOC ## Swerve Module Configuration (`module/x.json`) ### Description Configures unique properties of each swerve module. It maps 1:1 with `ModuleJson.java` which is used to create `SwerveModuleConfiguration`. This configuration file interacts directly with swerve kinematics. ### Fields | Name | Units | Required | Description | |-------------------------|-----------------------------|----------|---------------------------------------------------------------------------| | drive | [Device](Device-Configuration) | Y | Drive motor device configuration. | | angle | [Device](Device-Configuration) | Y | Angle motor device configuration. | | encoder | [Device](Device-Configuration) | Y | Absolute encoder device configuration. | | inverted | [MotorConfig](#MotorConfig) | Y | Inversion state of each motor as a boolean. | | absoluteEncoderOffset | Degrees | Y | Absolute encoder offset from 0 in degrees. May need to be a negative number. | | absoluteEncoderInverted | Bool | N | Inversion state of the Absolute Encoder. | | location | [Location](#Location) | Y | The location of the swerve module from the center of the robot in inches. +x is torwards the robot front, and +y is torwards robot left. | | conversionFactor | [MotorConfig](#MotorConfig) | N | _OVERRIDE_ Conversion factor applied to the motor controller for the onboard PID, used to override this setting in [`swervedrive.json`](https://github.com/BroncBotz3481/YAGSL/wiki/Swerve-Drive) ### MotorConfig | Name | Units | Required | Description | |-------|-------|----------|--------------------| | drive | Value | Y | Drive motor value. | | angle | Value | Y | Angle motor value. | ### Location | Name | Units | Required | Description | |-------|-------|----------|--------------------| | front | Value | Y | Inches from robot center to module in forward direction. | | left | Value | Y | Inches from robot center to module in left direction. | ``` -------------------------------- ### Configure SwerveInputStream for Controller Input Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Sets up SwerveInputStream for driving with translation on the left stick and rotation on the right stick X-axis. Includes deadband, scaling, alliance-relative control, and a non-linear translation response curve. ```java import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.math.kinematics.ChassisSpeeds; import swervelib.SwerveInputStream; import swervelib.SwerveDrive; public class DriveSubsystem { private SwerveDrive swerveDrive; private XboxController driverController = new XboxController(0); // Angular velocity control (right stick X for rotation) private SwerveInputStream driveAngularVelocity; // Heading-based control (right stick for heading direction) private SwerveInputStream driveDirectAngle; public void configureInputStream() { // Create stream with translation on left stick, rotation on right stick X driveAngularVelocity = SwerveInputStream.of( swerveDrive, () -> -driverController.getLeftY(), // Forward/backward (inverted) () -> -driverController.getLeftX() // Left/right strafe (inverted) ) .withControllerRotationAxis(() -> -driverController.getRightX()) .deadband(0.1) // Apply 10% deadband .scaleTranslation(0.8) // Scale translation to 80% .scaleRotation(0.7) // Scale rotation to 70% .allianceRelativeControl(true) // Flip controls for red alliance .cubeTranslationControllerAxis(true); // Non-linear response curve // Create heading-based control from angular velocity stream driveDirectAngle = driveAngularVelocity.copy() .withControllerHeadingAxis( () -> -driverController.getRightX(), () -> -driverController.getRightY() ) .headingWhile(true); } public void teleopDrive() { // Get ChassisSpeeds from the stream ChassisSpeeds speeds = driveAngularVelocity.get(); swerveDrive.driveFieldOriented(speeds); } public void teleopDriveWithHeading() { ChassisSpeeds speeds = driveDirectAngle.get(); swerveDrive.driveFieldOriented(speeds); } } ``` -------------------------------- ### PIDF Configuration Schema Source: https://github.com/yet-another-software-suite/yagsl_old/wiki/Swerve-Module-PIDF-Properties Details the required fields for configuring PIDF properties in the swerve module. ```APIDOC ## PIDF Configuration (pidfpropreties.json) ### Description Configures the PIDF values, integral zone, and maximum output for the drive and angle motors of each swerve module. This file maps directly to the PIDFPropertiesJson.java class. ### Parameters - **drive** (PIDF Object) - Required - The configuration used for the PIDF on the drive motor, including integral zone and output limit. - **angle** (PIDF Object) - Required - The configuration used for the PIDF on the angle motor, including integral zone and output limit. ### Request Example { "drive": { "p": 0.1, "i": 0.0, "d": 0.0, "f": 0.0, "izone": 0.0, "output": 1.0 }, "angle": { "p": 0.1, "i": 0.0, "d": 0.0, "f": 0.0, "izone": 0.0, "output": 1.0 } } ``` -------------------------------- ### Configure Swerve Modules Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Provides direct access to individual swerve modules for advanced configuration, including setting PIDF values for drive and angle motors, and accessing motor and encoder objects. ```java import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.math.kinematics.SwerveModulePosition; import swervelib.SwerveDrive; import swervelib.SwerveModule; import swervelib.parser.PIDFConfig; public class DriveSubsystem { private SwerveDrive swerveDrive; /** * Access individual modules */ public void configureModules() { SwerveModule[] modules = swerveDrive.getModules(); for (SwerveModule module : modules) { // Get module info double absolutePosition = module.getAbsolutePosition(); double relativePosition = module.getRelativePosition(); // Configure PIDF values PIDFConfig drivePIDF = new PIDFConfig(0.002, 0, 0, 0); module.setDrivePIDF(drivePIDF); PIDFConfig anglePIDF = new PIDFConfig(0.01, 0, 0, 0); module.setAnglePIDF(anglePIDF); // Get motor objects for advanced configuration var driveMotor = module.getDriveMotor(); var angleMotor = module.getAngleMotor(); var absoluteEncoder = module.getAbsoluteEncoder(); } } } ``` -------------------------------- ### PIDF Configuration Fields Source: https://github.com/yet-another-software-suite/yagsl_old/wiki/PIDF Defines the parameters available for PIDF configurations, mapping directly to the PIDFConfig.java class. ```APIDOC ## PIDF Configuration Structure This section describes the fields available for configuring PIDF controllers. ### Fields | Name | Units | Required | Description | |--------|-----------------|----------|----------------------------------------------| | p | kP Gain | Y | Proportional Gain for the PID. | | i | kI Gain | Y | Integral Gain for the PID. | | d | kD Gain | Y | Derivative Gain for the PID. | | f | Number | N | Feedforward for the PID. | | iz | Number | N | Integral zone for the integrator of the PID. | | output | [Range](#Range) | N | The output range for the PID. | ### Range | Name | Units | Required | Description | |------|--------|----------|-------------------------------------------------------| | min | Number | N | The minimum value in the PID range. Defaults to `-1`. | | max | Number | N | The maximum value in the PID range. Defaults to `1`. | ``` -------------------------------- ### Configure Simulation and Telemetry Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Provides methods for accessing MapleSim simulation data, setting telemetry verbosity, and managing the odometry update thread. ```java import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.wpilibj.smartdashboard.Field2d; import org.ironmaple.simulation.drivesims.SwerveDriveSimulation; import swervelib.SwerveDrive; import swervelib.telemetry.SwerveDriveTelemetry; import java.util.Optional; public class DriveSubsystem { private SwerveDrive swerveDrive; public void configureSimulation() { // Check if running in simulation if (SwerveDriveTelemetry.isSimulation) { // Get the MapleSim drive simulation instance Optional simDrive = swerveDrive.getMapleSimDrive(); // Get actual simulated pose (ground truth) Optional simPose = swerveDrive.getSimulationDriveTrainPose(); simPose.ifPresent(pose -> { System.out.println("Simulated pose: " + pose); }); } } public void configureTelemetry() { // Set telemetry verbosity level SwerveDriveTelemetry.verbosity = SwerveDriveTelemetry.TelemetryVerbosity.HIGH; // Access the field visualization Field2d field = swerveDrive.field; // Post a trajectory for visualization // swerveDrive.postTrajectory(trajectory); } public void setOdometryPeriod() { // Configure odometry update period (default 0.02s for real, 0.004s for sim) swerveDrive.setOdometryPeriod(0.02); // Or stop the odometry thread for manual updates swerveDrive.stopOdometryThread(); } } ``` -------------------------------- ### Define physicalproperties.json Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Sets physical constraints such as gear ratios, wheel diameter, current limits, and voltage. ```json { "conversionFactors": { "drive": { "gearRatio": 6.75, "diameter": 4 }, "angle": { "gearRatio": 12.8 } }, "currentLimit": { "drive": 40, "angle": 20 }, "rampRate": { "drive": 0.25, "angle": 0.25 }, "wheelGripCoefficientOfFriction": 1.19, "optimalVoltage": 12 } ``` -------------------------------- ### Swerve Configuration Directory Structure Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt The required file system layout for YAGSL configuration files within the deploy directory. ```text swerve/ ├── controllerproperties.json ├── modules/ │ ├── backleft.json │ ├── backright.json │ ├── frontleft.json │ ├── frontright.json │ ├── physicalproperties.json │ └── pidfproperties.json └── swervedrive.json ``` -------------------------------- ### Define pidfproperties.json Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Defines PIDF constants for both drive and angle motors. ```json { "drive": { "p": 0.0020645, "i": 0, "d": 0, "f": 0, "iz": 0 }, "angle": { "p": 0.01, "i": 0, "d": 0, "f": 0, "iz": 0 } } ``` -------------------------------- ### Drive with ChassisSpeeds Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Directly controls the robot using ChassisSpeeds, suitable for autonomous routines or path following. ```java import edu.wpi.first.math.kinematics.ChassisSpeeds; import swervelib.SwerveDrive; public class DriveSubsystem { private SwerveDrive swerveDrive; /** * Drive using robot-relative ChassisSpeeds */ public void driveRobotRelative(ChassisSpeeds robotRelativeSpeeds) { swerveDrive.drive(robotRelativeSpeeds); } /** * Drive using field-relative ChassisSpeeds */ public void driveFieldOriented(ChassisSpeeds fieldRelativeSpeeds) { swerveDrive.driveFieldOriented(fieldRelativeSpeeds); } /** * Set chassis speeds for autonomous (uses closed-loop control) */ public void setChassisSpeeds(ChassisSpeeds speeds) { swerveDrive.setChassisSpeeds(speeds); } /** * Drive with both field and robot oriented components * Useful for combining driver input with automated aiming */ public void driveHybrid(ChassisSpeeds fieldRelative, ChassisSpeeds robotRelative) { swerveDrive.driveFieldOrientedAndRobotOriented(fieldRelative, robotRelative); } /** * Get current robot velocity */ public ChassisSpeeds getRobotVelocity() { return swerveDrive.getRobotVelocity(); // Robot-relative } public ChassisSpeeds getFieldVelocity() { return swerveDrive.getFieldVelocity(); // Field-relative } } ``` -------------------------------- ### Reset Odometry with SwerveDrive Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Resets the robot's odometry to a specified Pose2d. This is useful for initializing the robot's position on the field. ```java import edu.wpi.first.math.geometry.Pose2d; import swervelib.SwerveDrive; public class DriveSubsystem { private SwerveDrive swerveDrive; /** * Reset odometry to a specific pose */ public void resetOdometry(Pose2d pose) { swerveDrive.resetOdometry(pose); } } ``` -------------------------------- ### Drive with Translation and Rotation Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Uses joystick inputs to command the robot, supporting field-relative modes and closed-loop velocity control. ```java import edu.wpi.first.math.geometry.Translation2d; import swervelib.SwerveDrive; public class DriveSubsystem { private SwerveDrive swerveDrive; /** * Drive the robot using joystick inputs * @param translationX Forward/backward input (-1 to 1) * @param translationY Left/right strafe input (-1 to 1) * @param rotation Rotation input (-1 to 1) * @param fieldRelative True for field-oriented driving */ public void drive(double translationX, double translationY, double rotation, boolean fieldRelative) { double maxSpeed = swerveDrive.getMaximumChassisVelocity(); double maxAngularVelocity = swerveDrive.getMaximumChassisAngularVelocity(); // Convert joystick inputs to translation vector (meters/second) Translation2d translation = new Translation2d( translationX * maxSpeed, translationY * maxSpeed ); // Convert rotation input to radians/second double rotationRadPerSec = rotation * maxAngularVelocity; // Drive with closed-loop velocity control (isOpenLoop = false) swerveDrive.drive( translation, // Translation velocity in m/s rotationRadPerSec, // Rotation in rad/s fieldRelative, // Field-relative mode false // Use closed-loop control ); } /** * Drive with a custom center of rotation */ public void driveWithCenterOfRotation(Translation2d translation, double rotation, boolean fieldRelative, Translation2d centerOfRotation) { swerveDrive.drive( translation, rotation, fieldRelative, false, centerOfRotation // Offset from robot center in meters ); } } ``` -------------------------------- ### Swerve Controller Configuration Schema Source: https://github.com/yet-another-software-suite/yagsl_old/wiki/Controller-Properties Defines the structure and required fields for the controllerproperties.json file used to configure swerve drive autonomous and joystick heading behavior. ```APIDOC ## Swerve Controller Configuration (controllerproperties.json) ### Description The Swerve Controller configuration defines how the swerve drive operates during autonomous and joystick-driven heading adjustments. Proper tuning of these values is critical for autonomous functionality. ### Parameters #### Request Body - **angleJoystickRadiusDeadband** (Double) - Required - The minimum radius of the angle control joystick to allow for heading adjustment of the robot. - **heading** (PID) - Required - The PID configuration used to control the robot heading. ### Request Example { "angleJoystickRadiusDeadband": 0.05, "heading": { "p": 0.1, "i": 0.0, "d": 0.0 } } ``` -------------------------------- ### Calculate Swerve Conversion Factors Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Use SwerveMath to determine meters per rotation for drive motors and degrees per rotation for steering motors based on gear ratios and wheel dimensions. ```java import edu.wpi.first.math.util.Units; import swervelib.math.SwerveMath; public class SwerveConfig { // Physical constants private static final double WHEEL_DIAMETER_INCHES = 4.0; private static final double DRIVE_GEAR_RATIO = 6.75; // L2 MK4i private static final double ANGLE_GEAR_RATIO = 21.428; // MK4i /** * Calculate meters per rotation for drive motor * Used to convert motor rotations to distance traveled */ public static double getDriveConversionFactor() { double wheelDiameterMeters = Units.inchesToMeters(WHEEL_DIAMETER_INCHES); // With integrated encoder (pulsePerRotation = 1) return SwerveMath.calculateMetersPerRotation( wheelDiameterMeters, DRIVE_GEAR_RATIO ); // With external encoder (e.g., 2048 counts per revolution) // return SwerveMath.calculateMetersPerRotation(wheelDiameterMeters, DRIVE_GEAR_RATIO, 2048); } /** * Calculate degrees per rotation for angle/azimuth motor * Used to convert motor rotations to module angle */ public static double getAngleConversionFactor() { // With integrated encoder return SwerveMath.calculateDegreesPerSteeringRotation(ANGLE_GEAR_RATIO); // With external encoder // return SwerveMath.calculateDegreesPerSteeringRotation(ANGLE_GEAR_RATIO, 2048); } /** * Calculate maximum angular velocity */ public static double getMaxAngularVelocity(double maxSpeedMPS, double moduleDistanceFromCenter) { return SwerveMath.calculateMaxAngularVelocity( maxSpeedMPS, moduleDistanceFromCenter, // furthest X moduleDistanceFromCenter // furthest Y ); } /** * Calculate maximum acceleration based on wheel grip */ public static double getMaxAcceleration() { double wheelGripCoF = 1.19; // Coefficient of friction return SwerveMath.calculateMaxAcceleration(wheelGripCoF); } } ``` -------------------------------- ### Add Vision Measurement to SwerveDrive Odometry Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Incorporates vision measurements to improve pose estimation accuracy. Can be used with default or custom standard deviations for trust weighting. ```java import edu.wpi.first.math.Matrix; import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.numbers.N1; import edu.wpi.first.math.numbers.N3; import edu.wpi.first.wpilibj.Timer; import swervelib.SwerveDrive; public class DriveSubsystem { private SwerveDrive swerveDrive; /** * Add a vision measurement to improve pose estimation */ public void addVisionMeasurement(Pose2d visionPose) { double timestamp = Timer.getFPGATimestamp(); swerveDrive.addVisionMeasurement(visionPose, timestamp); } /** * Add vision measurement with custom standard deviations * Lower values = higher trust in vision */ public void addVisionMeasurement(Pose2d visionPose, double timestamp, double xStdDev, double yStdDev, double thetaStdDev) { Matrix stdDevs = VecBuilder.fill(xStdDev, yStdDev, thetaStdDev); swerveDrive.addVisionMeasurement(visionPose, timestamp, stdDevs); } } ``` -------------------------------- ### Set Motor Brake Mode Source: https://context7.com/yet-another-software-suite/yagsl_old/llms.txt Controls whether the swerve drive motors are in brake mode or coast mode. Use brake mode to hold position and coast mode to allow free movement. ```java import swervelib.SwerveDrive; public class DriveSubsystem { private SwerveDrive swerveDrive; /** * Set motor brake mode * @param brake True for brake mode, false for coast */ public void setMotorBrake(boolean brake) { swerveDrive.setMotorIdleMode(brake); } /** * Lock wheels in X pattern to prevent movement * Useful for defense or holding position on inclines */ public void lockPose() { swerveDrive.lockPose(); } /** * Reset drive encoders to zero */ public void resetEncoders() { swerveDrive.resetDriveEncoders(); } /** * Synchronize integrated encoders with absolute encoders */ public void synchronizeEncoders() { swerveDrive.synchronizeModuleEncoders(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.