### Create SwerveDrive from JSON Configuration (Java) Source: https://docs.yagsl.com/configuring-yagsl/code-setup This snippet demonstrates how to create a SwerveDrive object using a JSON configuration file. It utilizes the SwerveParser class to load settings from the 'deploy/swerve' directory and instantiate the SwerveDrive with a specified maximum speed. Ensure the swerve JSON directory is correctly placed and all necessary dependencies are installed. ```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(swerveJsonDirectory).createSwerveDrive(maximumSpeed); ``` -------------------------------- ### MAXSwerve Module Configuration Example Source: https://docs.yagsl.com/bringing-up-swerve/check-your-motors An example JSON configuration for a MAXSwerve module, demonstrating settings for drive and angle motors, encoder, inversion, absolute encoder inversion, offset, and location. This is crucial for setting up the swerve drive correctly. ```json { "drive": { "type": "sparkmax", "id": 12, "canbus": null }, "angle": { "type": "sparkmax", "id": 11, "canbus": null }, "encoder": { "type": "attached", "id": 0, "canbus": null }, "inverted": { "drive": false, "angle": false }, "absoluteEncoderInverted": true, "absoluteEncoderOffset": -90, "location": { "front": 12, "left": -12 } } ``` -------------------------------- ### Module Configuration Example (JSON) Source: https://docs.yagsl.com/devices/motor-controllers/sparkflex A JSON configuration file example for a single robot module using Spark Flex controllers. It details the 'drive' and 'angle' motor types, their CAN IDs, and optional CAN bus assignments. It also includes encoder configuration, inversion settings, and module location. ```json { "drive": { "type": "sparkflex", "id": 5, "canbus": null }, "angle": { "type": "sparkflex", "id": 6, "canbus": null }, "encoder": { "type": "cancoder", "id": 11, "canbus": null }, "inverted": { "drive": false, "angle": false }, "absoluteEncoderOffset": -18.281, "location": { "front": -12, "left": -12 } } ``` -------------------------------- ### Swerve Drive JSON Configuration Example Source: https://docs.yagsl.com/configuring-yagsl/configuration/swerve-drive-configuration An example of the swervedrive.json file, which configures the robot's Swerve Drive. It specifies the IMU (gyroscope) and the paths to individual module configuration files. Ensure the IMU type, ID, and CAN bus are correctly set. ```json { "imu": { "type": "pigeon2", "id": 13, "canbus": "canivore" }, "invertedIMU": true, "modules": [ "frontleft.json", "frontright.json", "backleft.json", "backright.json" ] } ``` -------------------------------- ### Swerve Module Configuration Example (JSON) Source: https://docs.yagsl.com/configuring-yagsl/configuration/swerve-module-configuration An example JSON configuration for a swerve module, specifying drive and angle motor controllers, absolute encoder details, inversion states, encoder offset, and module location relative to the robot's center. This configuration is crucial for defining individual swerve module behavior. ```json { "drive": { "type": "sparkmax", "id": 2, "canbus": null }, "angle": { "type": "sparkmax", "id": 1, "canbus": null }, "encoder": { "type": "cancoder", "id": 10, "canbus": null }, "inverted": { "drive": false, "angle": false }, "absoluteEncoderInverted": false, "absoluteEncoderOffset": -50.977, "location": { "front": 12, "left": -12 } } ``` -------------------------------- ### Module Configuration Example (JSON) Source: https://docs.yagsl.com/configuring-yagsl/configuration Demonstrates the JSON structure for configuring a single swerve drive module. It specifies the type and ID for drive and angle motors, the CANcoder ID, inversion settings, absolute encoder offset, and the physical location of the module on the robot. ```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 } } ``` ```json { "drive": { "type": "sparkmax", "id": 7, "canbus": null }, "angle": { "type": "sparkmax", "id": 8, "canbus": null }, "encoder": { "type": "cancoder", "id": 12, "canbus": null }, "inverted": { "drive": false, "angle": false }, "absoluteEncoderOffset": 6.504, "location": { "front": -12, "left": 12 } } ``` -------------------------------- ### Create CANSparkFlex Object (Java) Source: https://docs.yagsl.com/devices/motor-controllers/sparkflex An example of how to instantiate a CANSparkFlex object. This requires importing the necessary REV Robotics library classes and specifying the CAN ID and motor type. This is a fundamental step for controlling a Spark Flex motor. ```java import com.revrobotics.CANSparkFlex; import com.revrobotics.CANSparkLowLevel.MotorType; new CANSparkFlex(10, MotorType.kBrushless); ``` -------------------------------- ### Initialize SwerveDriveOdometry and Kinematics (Java) Source: https://docs.yagsl.com/fundamentals/swerve-drive Initializes SwerveDriveKinematics with module translations and creates a SwerveDriveOdometry object. This setup is essential for converting chassis speeds into individual module states and tracking the robot's position based on sensor inputs. ```java // Import relevant classes. import edu.wpi.first.math.kinematics.SwerveDriveKinematics; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.math.util.Units; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.math.kinematics.SwerveModulePosition; import edu.wpi.first.math.kinematics.SwerveDriveOdometry; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.wpilibj2.command.SubsystemBase; // Example SwerveDrive class public class SwerveDrive extends SubsystemBase { // Attributes SwerveDriveKinematics kinematics; SwerveDriveOdometry odometry; Gyroscope gyro; // Psuedo-class representing a gyroscope. SwerveModule[] swerveModules; // Psuedo-class representing swerve modules. // Constructor public SwerveDrive () { swerveModules = new SwerveModule[4]; // Psuedo-code; Create swerve modules here. // Create SwerveDriveKinematics object // 12.5in from center of robot to center of wheel. // 12.5in is converted to meters to work with object. // Translation2d(x,y) == Translation2d(front, left) kinematics = new SwerveDriveKinematics( new Translation2d(Units.inchesToMeters(12.5), Units.inchesToMeters(12.5)), // Front Left new Translation2d(Units.inchesToMeters(12.5), Units.inchesToMeters(-12.5)), // Front Right new Translation2d(Units.inchesToMeters(-12.5), Units.inchesToMeters(12.5)), // Back Left new Translation2d(Units.inchesToMeters(-12.5), Units.inchesToMeters(-12.5)) // Back Right ); gyro = new Gyroscope(); // Psuedo-constructor for generating gyroscope. // Create the SwerveDriveOdometry given the current angle, the robot is at x=0, r=0, and heading=0 odometry = new SwerveDriveOdometry( kinematics, gyro.getAngle(), // returns current gyro reading as a Rotation2d new SwerveModulePosition[]{new SwerveModulePosition(), new SwerveModulePosition(), new SwerveModulePosition(), new SwerveModulePosition}, // Front-Left, Front-Right, Back-Left, Back-Right new Pose2d(0,0,new Rotation2d()) // x=0, y=0, heading=0 ); } ``` -------------------------------- ### Get SwerveDrive Gyro Instance Source: https://docs.yagsl.com/overview/changelog Introduces `SwerveDrive.getGyro()` which returns the `SwerveIMU` instance associated with the drive. This allows direct access to the IMU for advanced sensor readings or configurations. ```Java SwerveIMU gyro = swerveDrive.getGyro(); // Access gyro methods like gyro.getPitch() ``` -------------------------------- ### Configure SwerveDrive Telemetry Verbosity (Java) Source: https://docs.yagsl.com/configuring-yagsl/code-setup This code snippet shows how to adjust the telemetry verbosity for the SwerveDrive. By modifying the `SwerveDriveTelemetry.verbosity` static field, you can control the amount of telemetry data generated, which can help reduce program delays. Options include HIGH, MEDIUM, LOW, and NONE. ```java import swervelib.telemetry.SwerveDriveTelemetry; import swervelib.telemetry.SwerveDriveTelemetry.TelemetryVerbosity; SwerveDriveTelemetry.verbosity = TelemetryVerbosity.HIGH; ``` -------------------------------- ### PIDF Properties Configuration (JSON) Source: https://docs.yagsl.com/devices/motor-controllers/sparkflex A JSON configuration file example for PIDF (Proportional, Integral, Derivative, Feedforward) properties used in YAGSL. This file allows for fine-tuning the control loops for both the drive and angle motors. Proper PIDF tuning is crucial for accurate swerve drive performance. ```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 } } ``` -------------------------------- ### TalonFX Module Configuration (JSON) Source: https://docs.yagsl.com/devices/motor-controllers/talonfx An example JSON configuration file for a single swerve module using TalonFX for both drive and angle control. It specifies CAN IDs, bus, inversion settings, and encoder details. This configuration is essential for YAGSL to properly control each module. ```json { "drive": { "type": "talonfx", "id": 5, "canbus": null }, "angle": { "type": "talonfx", "id": 6, "canbus": null }, "encoder": { "type": "cancoder", "id": 11, "canbus": null }, "inverted": { "drive": false, "angle": false }, "absoluteEncoderOffset": -18.281, "location": { "front": -12, "left": -12 } } ``` -------------------------------- ### Swerve Controller Configuration (JSON) Source: https://docs.yagsl.com/configuring-yagsl/configuration/controller-properties-configuration Example JSON structure for Swerve Controller properties. This configuration maps directly to the `ControllerPropertiesJson` class and defines parameters like the joystick deadband for angle control and the PID controller for robot heading. ```json { "angleJoystickRadiusDeadband": 0.5, "heading": { "p": 0.4, "i": 0, "d": 0.01 } } ``` -------------------------------- ### Configure Absolute Encoder in JSON (YAGSL) Source: https://docs.yagsl.com/devices/absolute-encoders Example JSON configuration for a swerve drive module, specifying details for the drive motor, angle motor, and absolute encoder. This configuration includes device types, IDs, CAN bus assignments, inversion settings, offset, and physical location. ```json { "drive": { "type": "sparkmax", "id": 5, "canbus": null }, "angle": { "type": "sparkmax", "id": 6, "canbus": null }, "encoder": { "type": "cancoder", "id": 11, "canbus": null }, "inverted": { "drive": false, "angle": false }, "absoluteEncoderOffset": -18.281, "absoluteEncoderInverted": false, "location": { "front": -12, "left": -12 } } ``` -------------------------------- ### Configure SwerveDrive Telemetry Verbosity in Java Source: https://docs.yagsl.com/overview/our-features/telemetry This Java code snippet demonstrates how to configure the telemetry verbosity for a SwerveDrive subsystem during initialization. It sets the `SwerveDriveTelemetry.verbosity` static variable to `TelemetryVerbosity.HIGH` before creating the `SwerveDrive` object. This ensures that high-level telemetry data is enabled from the start. Be aware that higher verbosity might impact robot performance. ```java /** * Initialize {@link SwerveDrive} with the directory provided. * * @param directory Directory of swerve drive config files. */ public SwerveSubsystem(File directory) { // Configure the Telemetry before creating the SwerveDrive to avoid unnecessary objects being created. SwerveDriveTelemetry.verbosity = TelemetryVerbosity.HIGH; swerveDrive = new SwerveParser(directory).createSwerveDrive(Constants.MAX_SPEED); } ``` -------------------------------- ### Java Swerve Drive Command with Heading Setpoint Source: https://docs.yagsl.com/configuring-yagsl/code-setup This command drives the robot using translation inputs and a heading setpoint. It utilizes `SwerveMath.scaleTranslation` to scale input values and `swerveDrive.swerveController.getTargetSpeeds` to calculate target speeds for field-oriented driving. The robot's odometry heading is used to maintain orientation. ```java /** * Command to drive the robot using translative values and heading as a setpoint. * * @param translationX Translation in the X direction. * @param translationY Translation in the Y direction. * @param headingX Heading X to calculate angle of the joystick. * @param headingY Heading Y to calculate angle of the joystick. * @return Drive command. */ public Command driveCommand(DoubleSupplier translationX, DoubleSupplier translationY, DoubleSupplier headingX, DoubleSupplier headingY) { return run(() -> { Translation2d scaledInputs = SwerveMath.scaleTranslation(new Translation2d(translationX.getAsDouble(), translationY.getAsDouble()), 0.8); // Make the robot move driveFieldOriented(swerveDrive.swerveController.getTargetSpeeds(scaledInputs.getX(), scaledInputs.getY(), headingX.getAsDouble(), headingY.getAsDouble(), swerveDrive.getOdometryHeading().getRadians(), swerveDrive.getMaximumVelocity())); }); } ``` -------------------------------- ### Initialize SwerveSubsystem with Directory (Java) Source: https://docs.yagsl.com/devices/absolute-encoders Initializes the SwerveSubsystem by parsing a directory of swerve drive configuration files. It calculates conversion factors for angle and drive motors and configures the SwerveDrive. This method also iterates through the swerve modules to access their absolute encoders. ```java import com.ctre.phoenix6.hardware.CANcoder; import edu.wpi.first.units.Units; import swervelib.SwerveDrive; import swervelib.SwerveMath; import swervelib.SwerveModule; import swervelib.parser.SwerveParser; import swervelib.telemetry.SwerveDriveTelemetry; import swervelib.telemetry.TelemetryVerbosity; import java.io.File; public class SwerveSubsystem { // Assume maximumSpeed is defined elsewhere private double maximumSpeed; private SwerveDrive swerveDrive; /** * Initialize {@link SwerveDrive} with the directory provided. * * @param directory Directory of swerve drive config files. */ public SwerveSubsystem(File directory) { // Angle conversion factor is 360 / (GEAR RATIO * ENCODER RESOLUTION) // In this case the gear ratio is 12.8 motor revolutions per wheel rotation. // The encoder resolution per motor revolution is 1 per motor revolution. double angleConversionFactor = SwerveMath.calculateDegreesPerSteeringRotation(12.8, 1); // Motor conversion factor is (PI * WHEEL DIAMETER IN METERS) / (GEAR RATIO * ENCODER RESOLUTION). // In this case the wheel diameter is 4 inches, which must be converted to meters to get meters/second. // The gear ratio is 6.75 motor revolutions per wheel rotation. // The encoder resolution per motor revolution is 1 per motor revolution. double driveConversionFactor = SwerveMath.calculateMetersPerRotation(Units.inchesToMeters(4), 6.75, 1); // Configure the Telemetry before creating the SwerveDrive to avoid unnecessary objects being created. SwerveDriveTelemetry.verbosity = TelemetryVerbosity.HIGH; try { swerveDrive = new SwerveParser(directory).createSwerveDrive(maximumSpeed, angleConversionFactor, driveConversionFactor); } catch (Exception e) { throw new RuntimeException(e); } swerveDrive.setHeadingCorrection(false); // Heading correction should only be used while controlling the robot via angle. for(SwerveModule m : swerveDrive.getModules()) { System.out.println("Module Name: "+m.configuration.name); CANcoder absoluteEncoder = (CANcoder)m.configuration.absoluteEncoder.getAbsoluteEncoder(); } } } ``` -------------------------------- ### Get Current Swerve Module Positions (Java) Source: https://docs.yagsl.com/fundamentals/swerve-drive Retrieves the current distance and angle for each of the four swerve modules. This data is crucial for updating the robot's odometry. ```java // Fetch the current swerve module positions. public SwerveModulePosition[] getCurrentSwerveModulePositions () { return new SwerveModulePosition[]{ new SwerveModulePosition(swerveModules[0].getDistance(), swerveModules[0].getAngle()), // Front-Left new SwerveModulePosition(swerveModules[1].getDistance(), swerveModules[1].getAngle()), // Front-Right new SwerveModulePosition(swerveModules[2].getDistance(), swerveModules[2].getAngle()), // Back-Left new SwerveModulePosition(swerveModules[3].getDistance(), swerveModules[3].getAngle()) // Back-Right }; } ``` -------------------------------- ### Instantiate CANSparkMax in Java Source: https://docs.yagsl.com/devices/motor-controllers/sparkmax This Java code snippet demonstrates how to create an instance of the CANSparkMax controller. It requires the `com.revrobotics` package and specifies the motor type. The device ID and motor type are essential inputs. ```java import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkLowLevel.MotorType; new CANSparkMax(10, MotorType.kBrushless); ``` -------------------------------- ### Get Swerve Module Angle (Java) Source: https://docs.yagsl.com/fundamentals/swerve-modules Obtains the current angle of the swerve module in degrees, using the steer encoder. It relies on the Rotation2d class for angle representation and the steerEncoder for readings. ```java /** Get the angle. */ public Rotation2d getAngle() { return Rotation2d.fromDegrees(steerEncoder.getPosition()); } ``` -------------------------------- ### Get Swerve Module Distance (Java) Source: https://docs.yagsl.com/fundamentals/swerve-modules Retrieves the current distance in meters from the drive encoder. This method depends on the driveEncoder object being properly initialized and providing accurate position data. ```java /** Get the distance in meters. */ public double getDistance() { return driveEncoder.getPosition(); } ``` -------------------------------- ### Initialize SwerveDrive with SwerveParser in Java Source: https://docs.yagsl.com/devices/motor-controllers This Java code initializes a SwerveDrive object using the SwerveParser, which reads configuration from a specified directory. It calculates conversion factors for angle and drive motors based on gear ratios and encoder resolutions, and sets up telemetry verbosity. It also iterates through the created SwerveModules to access their angle and drive motors, specifically CANSparkMax controllers. ```java /** * Initialize {@link SwerveDrive} with the directory provided. * * @param directory Directory of swerve drive config files. */ public SwerveSubsystem(File directory) { // Angle conversion factor is 360 / (GEAR RATIO * ENCODER RESOLUTION) // In this case the gear ratio is 12.8 motor revolutions per wheel rotation. // The encoder resolution per motor revolution is 1 per motor revolution. double angleConversionFactor = SwerveMath.calculateDegreesPerSteeringRotation(12.8, 1); // Motor conversion factor is (PI * WHEEL DIAMETER IN METERS) / (GEAR RATIO * ENCODER RESOLUTION). // In this case the wheel diameter is 4 inches, which must be converted to meters to get meters/second. // The gear ratio is 6.75 motor revolutions per wheel rotation. // The encoder resolution per motor revolution is 1 per motor revolution. double driveConversionFactor = SwerveMath.calculateMetersPerRotation(Units.inchesToMeters(4), 6.75, 1); // Configure the Telemetry before creating the SwerveDrive to avoid unnecessary objects being created. SwerveDriveTelemetry.verbosity = TelemetryVerbosity.HIGH; try { swerveDrive = new SwerveParser(directory).createSwerveDrive(maximumSpeed, angleConversionFactor, driveConversionFactor); } catch (Exception e) { throw new RuntimeException(e); } swerveDrive.setHeadingCorrection(false); // Heading correction should only be used while controlling the robot via angle. for(SwerveModule m : swerveDrive.getModules()) { System.out.println("Module Name: "+m.configuration.name); CANSparkMax steeringMotor = (CANSparkMax)m.getAngleMotor().getMotor(); CANSparkMax driveMotor = (CANSparkMax)m.getDriveMotor().getMotor(); } } ``` -------------------------------- ### Configure Swerve Module Angle Inversion Source: https://docs.yagsl.com/configuring-yagsl/when-to-invert This JSON configuration snippet demonstrates how to invert the angle motor for a swerve module. This is necessary when the Raw Angle Encoder value is decreasing while the motor is expected to increase counterclockwise. ```json { "drive": { "type": "sparkmax", "id": 2, "canbus": null }, "angle": { "type": "sparkmax", "id": 1, "canbus": null }, "encoder": { "type": "cancoder", "id": 10, "canbus": null }, "inverted": { "drive": false, "angle": true }, "absoluteEncoderInverted": false, "absoluteEncoderOffset": -50.977, "location": { "front": 12, "left": -12 } } ``` -------------------------------- ### Swerve Drive Initialization with Conversion Factors (Java) Source: https://docs.yagsl.com/configuring-yagsl/configuration Demonstrates how to initialize a SwerveDrive object in Java, providing custom conversion factors for steering and drive motors. This is useful when motors differ across modules or when not specifying them in the swervedrive.json. ```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); ``` -------------------------------- ### Configure Swerve Module Drive Motor Inversion Source: https://docs.yagsl.com/configuring-yagsl/when-to-invert This JSON configuration snippet illustrates how to invert the drive motor for a swerve module. This correction is applied when the Raw Drive Encoder value decreases when it should be increasing during counterclockwise rotation. ```json { "drive": { "type": "sparkmax", "id": 2, "canbus": null }, "angle": { "type": "sparkmax", "id": 1, "canbus": null }, "encoder": { "type": "cancoder", "id": 10, "canbus": null }, "inverted": { "drive": true, "angle": false }, "absoluteEncoderInverted": false, "absoluteEncoderOffset": -50.977, "location": { "front": 12, "left": -12 } } ``` -------------------------------- ### SwerveParser Initialization in Java Source: https://docs.yagsl.com/configuring-yagsl/configuration Initializes the SwerveParser for a swerve drive system using a configuration file. It takes a File object pointing to the 'swerve' directory within the deploy directory and a double value representing the robot's wheel base (in meters). ```java new SwerveParser(new File(Filesystem.getDeployDirectory(),"swerve")).createSwerveDrive(Units.feetToMeters(4.5)); ``` -------------------------------- ### Configure Attached Absolute Encoder (JSON) Source: https://docs.yagsl.com/devices/absolute-encoders This configuration snippet shows how to set up an 'attached' absolute encoder. It specifies the encoder type, an ID, and a null CAN bus, typically used for integrated encoders on devices like the SparkMAX. ```json { "encoder": { "type": "attached", "id": 11, "canbus": null } } ``` -------------------------------- ### Initialize SwerveDrive with Gyroscope (Java) Source: https://docs.yagsl.com/devices/gyroscope This Java code snippet demonstrates how to initialize the SwerveDrive object using a configuration file. It calculates conversion factors for angles and drive units, sets telemetry verbosity, and retrieves the IMU object, casting it to the specific AHRS class for NavX. ```java /** * Initialize {@link SwerveDrive} with the directory provided. * * @param directory Directory of swerve drive config files. */ public SwerveSubsystem(File directory) { // Angle conversion factor is 360 / (GEAR RATIO * ENCODER RESOLUTION) // In this case the gear ratio is 12.8 motor revolutions per wheel rotation. // The encoder resolution per motor revolution is 1 per motor revolution. double angleConversionFactor = SwerveMath.calculateDegreesPerSteeringRotation(12.8, 1); // Motor conversion factor is (PI * WHEEL DIAMETER IN METERS) / (GEAR RATIO * ENCODER RESOLUTION). // In this case the wheel diameter is 4 inches, which must be converted to meters to get meters/second. // The gear ratio is 6.75 motor revolutions per wheel rotation. // The encoder resolution per motor revolution is 1 per motor revolution. double driveConversionFactor = SwerveMath.calculateMetersPerRotation(Units.inchesToMeters(4), 6.75, 1); // Configure the Telemetry before creating the SwerveDrive to avoid unnecessary objects being created. SwerveDriveTelemetry.verbosity = TelemetryVerbosity.HIGH; try { swerveDrive = new SwerveParser(directory).createSwerveDrive(maximumSpeed, angleConversionFactor, driveConversionFactor); } catch (Exception e) { throw new RuntimeException(e); } swerveDrive.setHeadingCorrection(false); // Heading correction should only be used while controlling the robot via angle. AHRS navx = (AHRS)swerveDrive.getGyro().getIMU(); } ``` -------------------------------- ### Configure Swerve Module Absolute Encoder Inversion Source: https://docs.yagsl.com/configuring-yagsl/when-to-invert This JSON configuration snippet shows how to invert the absolute encoder for a swerve module. This adjustment is needed if the Raw Absolute Encoder value decreases unexpectedly, indicating a need to flip its reading. ```json { "drive": { "type": "sparkmax", "id": 2, "canbus": null }, "angle": { "type": "sparkmax", "id": 1, "canbus": null }, "encoder": { "type": "cancoder", "id": 10, "canbus": null }, "inverted": { "drive": false, "angle": false }, "absoluteEncoderInverted": true, "absoluteEncoderOffset": -50.977, "location": { "front": 12, "left": -12 } } ``` -------------------------------- ### Initialize and Control TalonFX Motor (Java) Source: https://docs.yagsl.com/devices/motor-controllers/talonfx Demonstrates how to initialize a TalonFX motor controller and set its output using the DutyCycleOut control mode. This is a fundamental step for motor operation. It requires the Phoenix 6 library. ```java import com.ctre.phoenix6.hardware.TalonFX; import com.ctre.phoenix6.controls.DutyCycleOut; TalonFX motor = new TalonFX(10); motor.setControl(new DutyCycleOut(1.0)); // 100% full speed positive. ``` -------------------------------- ### Java Swerve Drive Command with Angular Velocity Source: https://docs.yagsl.com/configuring-yagsl/code-setup This command drives the robot using translation inputs and a specified angular velocity. It directly applies the scaled translation values and angular rotation to the `swerveDrive.drive` method. This is useful for direct control over the robot's rotation. ```java /** * Command to drive the robot using translative values and heading as angular velocity. * * @param translationX Translation in the X direction. * @param translationY Translation in the Y direction. * @param angularRotationX Rotation of the robot to set * @return Drive command. */ public Command driveCommand(DoubleSupplier translationX, DoubleSupplier translationY, DoubleSupplier angularRotationX) { return run(() -> { // Make the robot move swerveDrive.drive(new Translation2d(translationX.getAsDouble() * swerveDrive.getMaximumVelocity(), translationY.getAsDouble() * swerveDrive.getMaximumVelocity()), angularRotationX.getAsDouble() * swerveDrive.getMaximumAngularVelocity(), true, false); }); } ``` -------------------------------- ### Configure Robot Module Settings (JSON) Source: https://docs.yagsl.com/configuring-yagsl/the-eight-steps This JSON configuration defines the parameters for a single swerve drive module, including the types and IDs for drive and angle motors, encoder details, inversion settings for drive and angle, absolute encoder offset, and the module's physical location. These settings are crucial for proper robot movement and calibration. ```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 } } ``` ```json { "drive": { "type": "sparkmax", "id": 5, "canbus": null }, "angle": { "type": "sparkmax", "id": 6, "canbus": null }, "encoder": { "type": "cancoder", "id": 11, "canbus": null }, "inverted": { "drive": false, "angle": false }, "absoluteEncoderOffset": -18.281, "location": { "front": -12, "left": -12 } } ``` -------------------------------- ### Prepare Robot Drive Code with Field-Oriented Control (Java) Source: https://docs.yagsl.com/configuring-yagsl/the-eight-steps This Java code snippet demonstrates how to set up a default drive command for a SwerveSubsystem in the YAGSL project. It applies deadbands to joystick inputs and configures the drive to use field-oriented control with a direct angle setpoint, which is crucial for debugging heading-related issues. It relies on the SwerveSubsystem and OperatorConstants classes. ```java ... SwerveSubsystem drivebase; CommandXboxController driverXbox; ... // Applies deadbands and inverts controls because joysticks // are back-right positive while robot // controls are front-left positive // left stick controls translation // right stick controls the desired angle NOT angular rotation Command driveFieldOrientedDirectAngle = drivebase.driveCommand( () -> MathUtil.applyDeadband(driverXbox.getLeftY(), OperatorConstants.LEFT_Y_DEADBAND), () -> MathUtil.applyDeadband(driverXbox.getLeftX(), OperatorConstants.LEFT_X_DEADBAND), () -> driverXbox.getRightX(), () -> driverXbox.getRightY()); drivebase.setDefaultCommand(driveFieldOrientedDirectAngle); .... ``` ```java ... public class SwerveSubsytem extends SubsystemBase { ... SwerveDrive swerveDrive; /** * Command to drive the robot using translative values and heading as a setpoint. * * @param translationX Translation in the X direction. Cubed for smoother controls. * @param translationY Translation in the Y direction. Cubed for smoother controls. * @param headingX Heading X to calculate angle of the joystick. * @param headingY Heading Y to calculate angle of the joystick. * @return Drive command. */ public Command driveCommand(DoubleSupplier translationX, DoubleSupplier translationY, DoubleSupplier headingX, DoubleSupplier headingY) { // swerveDrive.setHeadingCorrection(true); // Normally you would want heading correction for this kind of control. return run(() -> { Translation2d scaledInputs = SwerveMath.scaleTranslation(new Translation2d(translationX.getAsDouble(), translationY.getAsDouble()), 0.8); // Make the robot move driveFieldOriented(swerveDrive.swerveController.getTargetSpeeds(scaledInputs.getX(), scaledInputs.getY(), headingX.getAsDouble(), headingY.getAsDouble(), swerveDrive.getOdometryHeading().getRadians(), swerveDrive.getMaximumVelocity())); }); } /** * Drive the robot given a chassis field oriented velocity. * * @param velocity Velocity according to the field. */ public void driveFieldOriented(ChassisSpeeds velocity) { swerveDrive.driveFieldOriented(velocity); } ... ```