### Accessing Deploy Directory in WPILib Source: https://github.com/crosstheroadelec/phoenix6-examples/blob/main/java/CANdle/src/main/deploy/example.txt Demonstrates how to get the path to the deploy directory on the RoboRIO using the Filesystem.getDeployDirectory() function in WPILib. This is useful for accessing configuration files or other resources deployed with the robot code. ```java String deployDirectory = Filesystem.getDeployDirectory(); // Use deployDirectory to access deployed files. ``` -------------------------------- ### Accessing Deploy Directory in C++ Source: https://github.com/crosstheroadelec/phoenix6-examples/blob/main/cpp/CurrentLimits/src/main/deploy/example.txt Demonstrates how to access the deploy directory on the RoboRIO using the FRC Filesystem library in C++. This is useful for reading configuration files or other resources deployed with the robot code. ```cpp #include "frc/Filesystem.h" #include // ... inside a function or method ... std::string deployDirectory = frc::filesystem::GetDeployDirectory(); // Now you can use deployDirectory to construct paths to your files. ``` -------------------------------- ### Accessing Deploy Directory in WPILib Source: https://github.com/crosstheroadelec/phoenix6-examples/blob/main/java/CANcoder/src/main/deploy/example.txt Demonstrates how to obtain the path to the deploy directory on the RoboRIO using the WPILib function. This is crucial for accessing configuration files or other resources deployed with your robot code. It relies on the WPILib library. ```java String deployDirectory = edu.wpi.first.wpilibj.Filesystem.getDeployDirectory(); ``` -------------------------------- ### Get RoboRIO Deploy Directory Path (C++) Source: https://github.com/crosstheroadelec/phoenix6-examples/blob/main/cpp/ArcadeDrive/src/main/deploy/example.txt This snippet shows how to retrieve the absolute path to the deploy directory on the RoboRIO. It uses the `frc::filesystem::GetDeployDirectory` function, which requires including the `frc/Filesystem.h` header. The returned path is relative to the RoboRIO's home folder. ```cpp #include "frc/Filesystem.h" #include // ... inside a function or method ... std::string deployDirectory = frc::filesystem::GetDeployDirectory(); // Now you can use deployDirectory to construct paths to files in the deploy folder. ``` -------------------------------- ### Compensate CAN Bus Latency with Derivative Signals (Java) Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt Illustrates how to compensate for CAN bus latency by using derivative signals to extrapolate current values from timestamped measurements. This example uses CANcoder, TalonFX, and Pigeon2 hardware. ```java import com.ctre.phoenix6.BaseStatusSignal; import com.ctre.phoenix6.StatusSignal; import com.ctre.phoenix6.hardware.CANcoder; import com.ctre.phoenix6.hardware.Pigeon2; import com.ctre.phoenix6.hardware.TalonFX; import edu.wpi.first.units.measure.Angle; import edu.wpi.first.units.measure.AngularVelocity; import static edu.wpi.first.units.Units.*; public class Robot extends TimedRobot { private final CANcoder m_cc = new CANcoder(0, "canivore"); private final TalonFX m_fx = new TalonFX(0, "canivore"); private final Pigeon2 m_p2 = new Pigeon2(0, "canivore"); // Create status signals without auto-refresh private final StatusSignal m_ccpos = m_cc.getPosition(false); private final StatusSignal m_fxpos = m_fx.getPosition(false); private final StatusSignal m_p2yaw = m_p2.getYaw(false); private final StatusSignal m_ccvel = m_cc.getVelocity(false); private final StatusSignal m_fxvel = m_fx.getVelocity(false); private final StatusSignal m_p2yawRate = m_p2.getAngularVelocityZWorld(false); @Override public void robotPeriodic() { // Refresh all signals at once BaseStatusSignal.refreshAll(m_fxpos, m_fxvel, m_ccpos, m_ccvel, m_p2yaw, m_p2yawRate); // Use latency compensation helper function var ccCompensatedPos = BaseStatusSignal.getLatencyCompensatedValue(m_ccpos, m_ccvel); var fxCompensatedPos = BaseStatusSignal.getLatencyCompensatedValue(m_fxpos, m_fxvel); var p2CompensatedYaw = BaseStatusSignal.getLatencyCompensatedValue(m_p2yaw, m_p2yawRate); System.out.printf( "CANcoder: Pos: %10.3f - Latency-Compensated: %10.3f - Difference: %6.5f%n", m_ccpos.getValue().in(Rotations), ccCompensatedPos.in(Rotations), ccCompensatedPos.minus(m_ccpos.getValue()).in(Rotations) ); // Dynamically adjust signal update frequency if (m_joystick.getLeftBumperButtonPressed()) { BaseStatusSignal.setUpdateFrequencyForAll(1000, m_fxpos, m_ccpos, m_p2yaw); // 1 kHz } if (m_joystick.getRightBumperButtonPressed()) { BaseStatusSignal.setUpdateFrequencyForAll(10, m_fxpos, m_ccpos, m_p2yaw); // 10 Hz } } } ``` -------------------------------- ### TalonFX Velocity Control with Feedforward (Java) Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt Implements TalonFX velocity control using either voltage-based or torque-based modes with feedforward compensation. This example configures static friction (kS) and proportional gains (kP) for accurate velocity tracking. Dependencies include Phoenix 6 libraries and WPILib. ```Java import com.ctre.phoenix6.configs.TalonFXConfiguration; import com.ctre.phoenix6.controls.VelocityTorqueCurrentFOC; import com.ctre.phoenix6.controls.VelocityVoltage; import static edu.wpi.first.units.Units.*; public class Robot extends TimedRobot { private final TalonFX m_fx = new TalonFX(0, "canivore"); private final VelocityVoltage m_velocityVoltage = new VelocityVoltage(0).withSlot(0); private final VelocityTorqueCurrentFOC m_velocityTorque = new VelocityTorqueCurrentFOC(0).withSlot(1); public Robot() { TalonFXConfiguration configs = new TalonFXConfiguration(); // Voltage-based velocity control with feed forward configs.Slot0.kS = 0.1; // Static friction feedforward configs.Slot0.kV = 0.12; // Kraken X60: 500 kV motor, 1/8.33 = 0.12 V per rps configs.Slot0.kP = 0.11; // 1 rps error = 0.11 V output configs.Slot0.kI = 0; configs.Slot0.kD = 0; configs.Voltage.withPeakForwardVoltage(Volts.of(8)) .withPeakReverseVoltage(Volts.of(-8)); // Torque-based velocity control (no velocity feedforward needed) configs.Slot1.kS = 2.5; // Static friction feedforward configs.Slot1.kP = 5; // 1 rps error = 5 A output configs.Slot1.kI = 0; configs.Slot1.kD = 0; configs.TorqueCurrent.withPeakForwardTorqueCurrent(Amps.of(40)) .withPeakReverseTorqueCurrent(Amps.of(-40)); m_fx.getConfigurator().apply(configs); } @Override public void teleopPeriodic() { double joyValue = m_joystick.getLeftY(); if (Math.abs(joyValue) < 0.1) joyValue = 0; double desiredRotationsPerSecond = joyValue * 50; // ±50 rps if (m_joystick.getLeftBumperButton()) { m_fx.setControl(m_velocityVoltage.withVelocity(desiredRotationsPerSecond)); } else if (m_joystick.getRightBumperButton()) { m_fx.setControl(m_velocityTorque.withVelocity(desiredRotationsPerSecond)); } } } ``` -------------------------------- ### Accessing Deploy Directory in Java Source: https://github.com/crosstheroadelec/phoenix6-examples/blob/main/python/SwerveWithPathPlanner/deploy/example.txt This snippet shows how to access the RoboRIO's deploy directory using the `Filesystem.getDeployDirectory()` function in Java. This is crucial for reading configuration files or other assets deployed with your robot code. ```java import edu.wpi.first.wpilibj.Filesystem; // ... inside a method or constructor ... String deployDirectory = Filesystem.getDeployDirectory(); System.out.println("Deploy directory: " + deployDirectory); // You can then construct paths to files within this directory // For example, to read a config file: // File configFile = new File(deployDirectory, "config.json"); ``` -------------------------------- ### Implement Arcade Drive with Phoenix 6 in C++ Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt This C++ code demonstrates the Arcade Drive implementation using the Phoenix 6 library. It initializes Talon FX motors, configures their inversions, sets up follower motors, and processes joystick input for teleoperation. ```cpp // C++: ArcadeDrive implementation #include "Robot.h" using namespace ctre::phoenix6; Robot::Robot() { configs::TalonFXConfiguration leftConfiguration{}; configs::TalonFXConfiguration rightConfiguration{}; leftConfiguration.MotorOutput.Inverted = signals::InvertedValue::CounterClockwise_Positive; rightConfiguration.MotorOutput.Inverted = signals::InvertedValue::Clockwise_Positive; leftLeader.GetConfigurator().Apply(leftConfiguration); rightLeader.GetConfigurator().Apply(rightConfiguration); leftFollower.SetControl(controls::Follower{leftLeader.GetDeviceID(), false}); rightFollower.SetControl(controls::Follower{rightLeader.GetDeviceID(), false}); } void Robot::TeleopPeriodic() { double fwd = -joystick.GetLeftY(); double rot = joystick.GetRightX(); leftOut.Output = fwd + rot; rightOut.Output = fwd - rot; leftLeader.SetControl(leftOut); rightLeader.SetControl(rightOut); } ``` -------------------------------- ### Accessing Deploy Directory in C++ Source: https://github.com/crosstheroadelec/phoenix6-examples/blob/main/cpp/ControlRequestLimits/src/main/deploy/example.txt Demonstrates how to retrieve the path to the deploy directory on the RoboRIO using the `frc::filesystem::GetDeployDirectory` function. This function is part of the WPILib library and ensures correct path resolution relative to the deploy directory. ```cpp #include "frc/Filesystem.h" #include // ... inside a function or method ... std::string deployDirectory = frc::filesystem::GetDeployDirectory(); // Now you can use deployDirectory to construct paths to files in the deploy folder. ``` -------------------------------- ### Python: Update Project Templates Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt This script automates the process of updating project templates for Java, C++, and Python FRC projects. It removes files from target directories that do not match exclusion patterns and then copies new template files into each example project. Dependencies include the 'os', 're', and 'shutil' Python modules. ```python import os import re import shutil TEMPLATE_DIRS = { "./.automation/java_template/": "./java", "./.automation/cpp_template/": "./cpp", "./.automation/python_template/": "./python" } DEL_EXCLUSIONS = [ r'src(?:/|\\)', r'deploy(?:/|\\)', r'.*.py$', r'tuner-project.json', r'(?i)vendordeps(?:/|\\)(?!Phoenix6|WPILibNewCommands)', ] def update_templates(template_dirs, del_exclusions): for template_dir, target_seek_dir in template_dirs.items(): for root, dirs, files in os.walk(target_seek_dir): # Remove files not matching exclusion patterns for file in files: full_path = os.path.join(root, file) to_keep = any(re.search(glob, full_path) for glob in del_exclusions) if not to_keep: print("Removing", full_path) os.remove(full_path) # Copy template files to all example projects for dir in os.listdir(target_seek_dir): target_dir = os.path.join(target_seek_dir, dir) for src_path in os.listdir(template_dir): source_path = os.path.join(template_dir, src_path) target_path = os.path.join(target_dir, src_path) print("Copying", source_path, "to", target_path) shutil.copytree(source_path, target_path, dirs_exist_ok=True) if __name__ == "__main__": update_templates(TEMPLATE_DIRS, DEL_EXCLUSIONS) ``` -------------------------------- ### PowerShell: Build FRC Projects Sequentially Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt This PowerShell script builds all FRC projects sequentially. It iterates through specified project directories ('cpp', 'java'), finds all subdirectories within them, and executes the './gradlew build' command for each project. It ensures projects are built in a defined order. ```powershell # PowerShell: Build all FRC projects sequentially # build_all_frc_projects.ps1 $projectDirs = @("cpp", "java") foreach ($dir in $projectDirs) { Get-ChildItem -Path $dir -Directory | ForEach-Object { Write-Host "Building $($_.FullName)" Push-Location $_.FullName & ./gradlew build Pop-Location } } ``` -------------------------------- ### Read Pigeon2 IMU Data with Signal Optimization (Java) Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt Demonstrates how to read yaw, pitch, roll, and gravity vectors from a Pigeon2 IMU. It optimizes signal updates to 100 Hz for low-latency readings and includes latency reporting. ```java import com.ctre.phoenix6.BaseStatusSignal; import com.ctre.phoenix6.configs.Pigeon2Configuration; import com.ctre.phoenix6.hardware.Pigeon2; import static edu.wpi.first.units.Units.*; public class Robot extends TimedRobot { private final Pigeon2 pidgey = new Pigeon2(1, "rio"); public Robot() { var toApply = new Pigeon2Configuration(); pidgey.getConfigurator().apply(toApply); // Speed up signals to 100 Hz BaseStatusSignal.setUpdateFrequencyForAll(100, pidgey.getYaw(), pidgey.getGravityVectorZ()); } @Override public void robotPeriodic() { // Automatic refresh on getYaw() var yaw = pidgey.getYaw(); System.out.println("Yaw is " + yaw.toString() + " with " + yaw.getTimestamp().getLatency() + " seconds of latency"); // Wait for new signal to minimize latency var gravityVectorZ = pidgey.getGravityVectorZ(false); gravityVectorZ.waitForUpdate(0.5); System.out.println("Gravity Vector Z is " + gravityVectorZ.getValue() + " " + gravityVectorZ.getUnits() + " with " + gravityVectorZ.getTimestamp().getLatency() + " seconds of latency"); } @Override public void teleopInit() { pidgey.setYaw(Degrees.of(144), 0.1); pidgey.getYaw().waitForUpdate(0.1); System.out.println("Set yaw to 144 degrees, currently at " + pidgey.getYaw()); } } ``` -------------------------------- ### Implement Arcade Drive with Phoenix 6 in Python Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt This Python code demonstrates how to set up and control a differential drive robot using the Phoenix 6 library. It configures Talon FX motors, sets up follower motors, and applies Arcade Drive logic based on Xbox controller input. ```python import wpilib from phoenix6 import CANBus, configs, controls, hardware, signals class MyRobot(wpilib.TimedRobot): def robotInit(self): self.canivore = CANBus("canivore") self.front_left_motor = hardware.TalonFX(0, self.canivore) self.rear_left_motor = hardware.TalonFX(1, self.canivore) self.front_right_motor = hardware.TalonFX(2, self.canivore) self.rear_right_motor = hardware.TalonFX(3, self.canivore) # Configure motor inversions cfg = configs.TalonFXConfiguration() cfg.motor_output.inverted = configs.config_groups.InvertedValue.COUNTER_CLOCKWISE_POSITIVE self.front_left_motor.configurator.apply(cfg) cfg.motor_output.inverted = configs.config_groups.InvertedValue.CLOCKWISE_POSITIVE self.front_right_motor.configurator.apply(cfg) # Configure followers self.rear_left_motor.set_control(controls.Follower(0, signals.MotorAlignmentValue.ALIGNED)) self.rear_right_motor.set_control(controls.Follower(2, signals.MotorAlignmentValue.ALIGNED)) self.left_out = controls.DutyCycleOut(0) self.right_out = controls.DutyCycleOut(0) self.joy = wpilib.XboxController(0) def teleopPeriodic(self): throttle = self.joy.getLeftY() * -1 wheel = self.joy.getRightX() * 1 self.front_left_motor.set_control(self.left_out.with_output(throttle + wheel)) self.front_right_motor.set_control(self.right_out.with_output(throttle - wheel)) ``` -------------------------------- ### Motion Magic with TalonFX in Python Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt Demonstrates how to configure and use Motion Magic for precise position control of a TalonFX motor. It includes setting up gear ratios, Motion Magic parameters, and PID+feedforward gains. The code assumes a joystick input for controlling the target position. ```python from phoenix6 import hardware, controls, configs, StatusCode class MyRobot(wpilib.TimedRobot): def robotInit(self): self.talonfx = hardware.TalonFX(1, "canivore") self.motion_magic = controls.MotionMagicVoltage(0) self.joystick = wpilib.XboxController(0) cfg = configs.TalonFXConfiguration() # Configure gear ratio cfg.feedback.sensor_to_mechanism_ratio = 12.8 # Configure Motion Magic parameters cfg.motion_magic.motion_magic_cruise_velocity = 5 # 5 rps cruise cfg.motion_magic.motion_magic_acceleration = 10 # 0.5s to max velocity cfg.motion_magic.motion_magic_jerk = 100 # 0.1s to max accel # Configure PID + feedforward gains cfg.slot0.k_s = 0.25 # Static friction: 0.25 V cfg.slot0.k_v = 0.12 # Velocity: 1 rps = 0.12 V cfg.slot0.k_a = 0.01 # Acceleration: 1 rps/s = 0.01 V cfg.slot0.k_p = 60 # Position: 0.2 rot error = 12 V cfg.slot0.k_i = 0 cfg.slot0.k_d = 0.5 # Velocity error: 1 rps = 0.5 V # Retry configuration up to 5 times status = StatusCode.STATUS_CODE_NOT_INITIALIZED for _ in range(5): status = self.talonfx.configurator.apply(cfg) if status.is_ok(): break if not status.is_ok(): print(f"Could not apply configs, error code: {status.name}") def teleopPeriodic(self): left_y = self.joystick.getLeftY() if abs(left_y) < 0.1: left_y = 0 # Command motor to position with Motion Magic self.talonfx.set_control( self.motion_magic.with_position(left_y * 10).with_slot(0) ) # Reset position on button press if self.joystick.getBButton(): self.talonfx.set_position(1) ``` -------------------------------- ### Arcade Drive Control with TalonFX (Java) Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt Implements a basic differential drive system using TalonFX motor controllers. It configures leader and follower motors, applies necessary configurations like inversion, and reads Xbox controller input for teleoperation. ```java import com.ctre.phoenix6.CANBus; import com.ctre.phoenix6.configs.TalonFXConfiguration; import com.ctre.phoenix6.controls.DutyCycleOut; import com.ctre.phoenix6.controls.Follower; import com.ctre.phoenix6.hardware.TalonFX; import com.ctre.phoenix6.signals.InvertedValue; import com.ctre.phoenix6.signals.MotorAlignmentValue; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.XboxController; public class Robot extends TimedRobot { private final CANBus kCANBus = new CANBus("canivore"); private final TalonFX leftLeader = new TalonFX(1, kCANBus); private final TalonFX leftFollower = new TalonFX(2, kCANBus); private final TalonFX rightLeader = new TalonFX(3, kCANBus); private final TalonFX rightFollower = new TalonFX(4, kCANBus); private final DutyCycleOut leftOut = new DutyCycleOut(0); private final DutyCycleOut rightOut = new DutyCycleOut(0); private final XboxController joystick = new XboxController(0); public Robot() { // Configure motor inversions var leftConfiguration = new TalonFXConfiguration(); var rightConfiguration = new TalonFXConfiguration(); leftConfiguration.MotorOutput.Inverted = InvertedValue.CounterClockwise_Positive; rightConfiguration.MotorOutput.Inverted = InvertedValue.Clockwise_Positive; leftLeader.getConfigurator().apply(leftConfiguration); rightLeader.getConfigurator().apply(rightConfiguration); // Set up follower motors leftFollower.setControl(new Follower(leftLeader.getDeviceID(), MotorAlignmentValue.Aligned)); rightFollower.setControl(new Follower(rightLeader.getDeviceID(), MotorAlignmentValue.Aligned)); } @Override public void teleopPeriodic() { double fwd = -joystick.getLeftY(); // Invert Y axis double rot = joystick.getRightX(); leftOut.Output = fwd + rot; rightOut.Output = fwd - rot; leftLeader.setControl(leftOut); rightLeader.setControl(rightOut); } } ``` -------------------------------- ### CANcoder Absolute Encoder with Latency Compensation in Java Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt Demonstrates reading position and velocity from a CANcoder with latency compensation using `waitForUpdate`. This ensures synchronous CAN bus updates for more accurate sensor readings. It also shows how to configure update frequencies and set/get motor positions. ```java // Java: CANcoder usage with latency compensation import com.ctre.phoenix6.BaseStatusSignal; import com.ctre.phoenix6.configs.CANcoderConfiguration; import com.ctre.phoenix6.hardware.CANcoder; import static edu.wpi.first.units.Units.*; public class Robot extends TimedRobot { private final CANcoder cancoder = new CANcoder(1, "rio"); public Robot() { var toApply = new CANcoderConfiguration(); cancoder.getConfigurator().apply(toApply); // Speed up signals for better update rate BaseStatusSignal.setUpdateFrequencyForAll(100, cancoder.getPosition(), cancoder.getVelocity()); } @Override public void robotPeriodic() { // getPosition() automatically refreshes var pos = cancoder.getPosition(); System.out.println("Position is " + pos.toString() + " with " + pos.getTimestamp().getLatency() + " seconds of latency"); // Get velocity without refreshing, then wait for update to reduce latency var vel = cancoder.getVelocity(false); vel.waitForUpdate(0.5); // Wait up to 500ms for new data System.out.println("Velocity is " + vel.getValue() + " " + vel.getUnits() + " with " + vel.getTimestamp().getLatency() + " seconds of latency"); } @Override public void teleopInit() { // Set position and wait for setter to take effect cancoder.setPosition(Rotations.of(0.4), 0.1); cancoder.getPosition().waitForUpdate(0.1); System.out.println("Set position to 0.4 rotations, currently at " + cancoder.getPosition()); } } ``` -------------------------------- ### TalonFX Position Control with Voltage or Torque FOC (Java) Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt Demonstrates TalonFX position control using either voltage-based or torque-based Field Oriented Control (FOC). It configures PID gains for two different control slots and allows switching between modes using joystick input. Dependencies include Phoenix 6 libraries and WPILib. ```Java import com.ctre.phoenix6.StatusCode; import com.ctre.phoenix6.configs.TalonFXConfiguration; import com.ctre.phoenix6.controls.NeutralOut; import com.ctre.phoenix6.controls.PositionTorqueCurrentFOC; import com.ctre.phoenix6.controls.PositionVoltage; import com.ctre.phoenix6.hardware.TalonFX; import static edu.wpi.first.units.Units.*; public class Robot extends TimedRobot { private final TalonFX m_fx = new TalonFX(1, "canivore"); private final PositionVoltage m_positionVoltage = new PositionVoltage(0).withSlot(0); private final PositionTorqueCurrentFOC m_positionTorque = new PositionTorqueCurrentFOC(0).withSlot(1); private final NeutralOut m_brake = new NeutralOut(); private final XboxController m_joystick = new XboxController(0); public Robot() { TalonFXConfiguration configs = new TalonFXConfiguration(); // Voltage-based position control (Slot 0) configs.Slot0.kP = 2.4; // 1 rotation error = 2.4 V output configs.Slot0.kI = 0; configs.Slot0.kD = 0.1; // 1 rps velocity = 0.1 V output configs.Voltage.withPeakForwardVoltage(Volts.of(8)) .withPeakReverseVoltage(Volts.of(-8)); // Torque-based position control (Slot 1) configs.Slot1.kP = 60; // 1 rotation error = 60 A output configs.Slot1.kI = 0; configs.Slot1.kD = 6; // 1 rps velocity = 6 A output configs.TorqueCurrent.withPeakForwardTorqueCurrent(Amps.of(120)) .withPeakReverseTorqueCurrent(Amps.of(-120)); // Retry config apply up to 5 times StatusCode status = StatusCode.StatusCodeNotInitialized; for (int i = 0; i < 5; ++i) { status = m_fx.getConfigurator().apply(configs); if (status.isOK()) break; } if (!status.isOK()) { System.out.println("Could not apply configs, error code: " + status.toString()); } m_fx.setPosition(0); } @Override public void teleopPeriodic() { double desiredRotations = m_joystick.getLeftY() * 10; // ±10 rotations if (Math.abs(desiredRotations) <= 0.1) { desiredRotations = 0; } if (m_joystick.getLeftBumperButton()) { m_fx.setControl(m_positionVoltage.withPosition(desiredRotations)); } else if (m_joystick.getRightBumperButton()) { m_fx.setControl(m_positionTorque.withPosition(desiredRotations)); } else { m_fx.setControl(m_brake); } } } ``` -------------------------------- ### Motion Magic with TalonFX in C++ Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt Provides a C++ implementation for Motion Magic control of a TalonFX motor. This includes configuring sensor ratios, Motion Magic specific parameters like cruise velocity and acceleration, and PID controller gains. It utilizes specific units for configuration values. ```cpp // C++: Motion Magic implementation #include using namespace ctre::phoenix6; Robot::Robot() { configs::TalonFXConfiguration cfg{}; // Configure gear ratio cfg.Feedback.SensorToMechanismRatio = 12.8; // Configure Motion Magic cfg.MotionMagic.MotionMagicCruiseVelocity = 5_tps; cfg.MotionMagic.MotionMagicAcceleration = 10_tr_per_s_sq; cfg.MotionMagic.MotionMagicJerk = 100_tr_per_s_cu; // Configure gains cfg.Slot0.kS = 0.25; cfg.Slot0.kV = 0.12; cfg.Slot0.kA = 0.01; cfg.Slot0.kP = 60; cfg.Slot0.kI = 0; cfg.Slot0.kD = 0.5; m_motor.GetConfigurator().Apply(cfg); } void Robot::TeleopPeriodic() { double leftY = m_joystick.GetLeftY(); if (fabs(leftY) < 0.1) leftY = 0; m_motor.SetControl(m_mmReq.WithPosition(leftY * 10_tr).WithSlot(0)); } ``` -------------------------------- ### Parallel FRC Project Build Automation (Python) Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt Automates the process of building all FRC projects within specified directories in parallel using GitHub Actions. This script generates a GitHub Actions workflow file (`.github/workflows/build-all-parallel.yml`) that defines a matrix build strategy, allowing multiple projects to be compiled and tested concurrently. It searches for projects in 'cpp' and 'java' directories and structures them for parallel execution. ```python # Python: Parallel build workflow generator import os WORKFLOW_TEMPLATE = """ name: Build all FRC Projects on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: strategy: fail-fast: false matrix: include:{projects_as_matrix} runs-on: ubuntu-latest container: wpilib/roborio-cross-ubuntu:2025-22.04 steps: - uses: actions/checkout@v4 - name: Grant execute permission for gradlew run: cd "${{{{ matrix.directory }}}}" && chmod +x gradlew - name: Compile and run tests on robot code run: cd "${{{{ matrix.directory }}}}" && ./gradlew build """ PROJECT_MATRIX_TEMPLATE = """ - project-name: '{project_name}' directory: '{project_dir}'""" PROJECTS_TO_SEARCH = ["cpp", "java"] project_matrix = [] for project_dir in PROJECTS_TO_SEARCH: for project in os.listdir(project_dir): project_matrix.append( PROJECT_MATRIX_TEMPLATE.format( project_name=project, project_dir=f"{project_dir}/{project}" ) ) with open(".github/workflows/build-all-parallel.yml", "w") as f: f.write(WORKFLOW_TEMPLATE.format(projects_as_matrix="".join(project_matrix))) ``` -------------------------------- ### Swerve Drivetrain Control with PathPlanner (Java) Source: https://context7.com/crosstheroadelec/phoenix6-examples/llms.txt Implements a field-centric swerve drivetrain control system using Phoenix 6 and integrates PathPlanner for autonomous path following. This snippet configures drivetrain requests, joystick bindings for manual control (driving, braking, and wheel orientation), and sets up an autonomous command chooser. It also includes a command to warm up PathPlanner to prevent potential Java pauses during autonomous execution. ```java // Java: Swerve with PathPlanner autonomous import com.ctre.phoenix6.swerve.SwerveModule.DriveRequestType; import com.ctre.phoenix6.swerve.SwerveRequest; import com.pathplanner.lib.auto.AutoBuilder; import com.pathplanner.lib.commands.FollowPathCommand; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.button.CommandXboxController; import frc.robot.generated.TunerConstants; import frc.robot.subsystems.CommandSwerveDrivetrain; import static edu.wpi.first.units.Units.*; public class RobotContainer { private double MaxSpeed = TunerConstants.kSpeedAt12Volts.in(MetersPerSecond); private double MaxAngularRate = RotationsPerSecond.of(0.75).in(RadiansPerSecond); private final SwerveRequest.FieldCentric drive = new SwerveRequest.FieldCentric() .withDeadband(MaxSpeed * 0.1) .withRotationalDeadband(MaxAngularRate * 0.1) .withDriveRequestType(DriveRequestType.OpenLoopVoltage); private final SwerveRequest.SwerveDriveBrake brake = new SwerveRequest.SwerveDriveBrake(); private final SwerveRequest.PointWheelsAt point = new SwerveRequest.PointWheelsAt(); private final CommandXboxController joystick = new CommandXboxController(0); public final CommandSwerveDrivetrain drivetrain = TunerConstants.createDrivetrain(); private final SendableChooser autoChooser; public RobotContainer() { // Build auto chooser with PathPlanner paths autoChooser = AutoBuilder.buildAutoChooser("Tests"); SmartDashboard.putData("Auto Mode", autoChooser); configureBindings(); // Warmup PathPlanner to avoid Java pauses during auto FollowPathCommand.warmupCommand().schedule(); } private void configureBindings() { // Default drive command with field-centric control drivetrain.setDefaultCommand( drivetrain.applyRequest(() -> drive.withVelocityX(-joystick.getLeftY() * MaxSpeed) .withVelocityY(-joystick.getLeftX() * MaxSpeed) .withRotationalRate(-joystick.getRightX() * MaxAngularRate) ) ); // Brake mode on A button joystick.a().whileTrue(drivetrain.applyRequest(() -> brake)); // Point wheels in joystick direction on B button joystick.b().whileTrue(drivetrain.applyRequest(() -> point.withModuleDirection(new Rotation2d(-joystick.getLeftY(), -joystick.getLeftX())) )); // Reset field-centric heading joystick.leftBumper().onTrue(drivetrain.runOnce(drivetrain::seedFieldCentric)); } public Command getAutonomousCommand() { return autoChooser.getSelected(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.