### Start a NetworkTables Server Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/networktables/networktables-networking.rst Initialize and start a NetworkTables server instance. ```java NetworkTableInstance inst = NetworkTableInstance.getDefault(); inst.startServer(); ``` ```c++ nt::NetworkTableInstance inst = nt::NetworkTableInstance::GetDefault(); inst.StartServer(); ``` ```c++ NT_Inst inst = nt::GetDefaultInstance(); nt::StartServer(inst, "networktables.json", "", NT_DEFAULT_PORT3, NT_DEFAULT_PORT4); ``` ```c NT_Inst inst = NT_GetDefaultInstance(); NT_StartServer(inst, "networktables.json", "", NT_DEFAULT_PORT3, NT_DEFAULT_PORT4); ``` ```python import ntcore inst = ntcore.NetworkTableInstance.get_default() inst.start_server() ``` -------------------------------- ### Simple CameraServer Implementation Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/vision-processing/roborio/using-the-cameraserver-on-the-roborio.rst Initializes and starts a USB camera stream for dashboard viewing. ```java import edu.wpi.first.cameraserver.CameraServer; import edu.wpi.first.wpilibj.TimedRobot; public class Robot extends TimedRobot { @Override public void robotInit() { // This starts the camera server and automatically captures // the USB camera and sends it to the dashboard. CameraServer.startAutomaticCapture(); } } ``` ```c++ #include #include class Robot : public frc::TimedRobot { public: void RobotInit() override { // This starts the camera server and automatically captures // the USB camera and sends it to the dashboard. frc::CameraServer::StartAutomaticCapture(); } }; ``` ```python import wpilib from cscore import CameraServer class MyRobot(wpilib.TimedRobot): def robotInit(self): # This starts the camera server and automatically captures # the USB camera and sends it to the dashboard. CameraServer.startAutomaticCapture() ``` -------------------------------- ### Install dependencies on Ubuntu Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/contributing/wpilib-docs/build-instructions.rst Use these commands to install the necessary Python and LaTeX packages for building documentation on Ubuntu. ```console $ sudo apt update $ sudo apt install python3 $ sudo apt install -y texlive-latex-recommended texlive-fonts-recommended texlive-latex-extra latexmk texlive-lang-greek texlive-luatex texlive-xetex texlive-fonts-extra dvipng librsvg2-bin ``` -------------------------------- ### Implement a Simple Command Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/commandbased/commands-v2/commands.rst Examples of a command that performs a single action and terminates immediately. ```java package frc.robot.commands; import edu.wpi.first.wpilibj2.command.Command; import frc.robot.subsystems.HatchSubsystem; public class GrabHatch extends Command { private final HatchSubsystem m_hatchSubsystem; public GrabHatch(HatchSubsystem subsystem) { m_hatchSubsystem = subsystem; addRequirements(m_hatchSubsystem); } @Override public void initialize() { m_hatchSubsystem.grabHatch(); } @Override public boolean isFinished() { return true; } } ``` ```cpp #pragma once #include #include #include "subsystems/HatchSubsystem.h" class GrabHatch : public frc2::CommandHelper { public: explicit GrabHatch(HatchSubsystem* subsystem); void Initialize() override; bool IsFinished() override; private: HatchSubsystem* m_hatchSubsystem; }; ``` ```cpp #include "commands/GrabHatch.hpp" GrabHatch::GrabHatch(HatchSubsystem* subsystem) : m_hatchSubsystem(subsystem) { AddRequirements(subsystem); } void GrabHatch::Initialize() { m_hatchSubsystem->GrabHatch(); } bool GrabHatch::IsFinished() { return true; } ``` ```python import commands2 from subsystems.hatchsubsystem import HatchSubsystem class GrabHatch(commands2.Command): def __init__(self, subsystem: HatchSubsystem) -> None: super().__init__() self.hatchSubsystem = subsystem self.addRequirements(subsystem) def initialize(self) -> None: self.hatchSubsystem.grabHatch() def isFinished(self) -> bool: return True ``` -------------------------------- ### Start a NetworkTables Client Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/networktables/networktables-networking.rst Initialize and start a NetworkTables client instance with various connection methods. ```java NetworkTableInstance inst = NetworkTableInstance.getDefault(); // start a NT4 client inst.startClient4("example client"); // connect to a roboRIO with team number TEAM inst.setServerTeam(TEAM); // starting a DS client will try to get the roboRIO address from the DS application inst.startDSClient(); // connect to a specific host/port inst.setServer("host", NetworkTableInstance.kDefaultPort4) ``` ```c++ nt::NetworkTableInstance inst = nt::NetworkTableInstance::GetDefault(); // start a NT4 client inst.StartClient4("example client"); // connect to a roboRIO with team number TEAM inst.SetServerTeam(TEAM); // starting a DS client will try to get the roboRIO address from the DS application inst.StartDSClient(); // connect to a specific host/port inst.SetServer("host", NT_DEFAULT_PORT4) ``` ```c++ NT_Inst inst = nt::GetDefaultInstance(); // start a NT4 client nt::StartClient4(inst, "example client"); // connect to a roboRIO with team number TEAM nt::SetServerTeam(inst, TEAM); // starting a DS client will try to get the roboRIO address from the DS application nt::StartDSClient(inst); // connect to a specific host/port nt::SetServer(inst, "host", NT_DEFAULT_PORT4) ``` ```c NT_Inst inst = NT_GetDefaultInstance(); // start a NT4 client NT_StartClient4(inst, "example client"); // connect to a roboRIO with team number TEAM NT_SetServerTeam(inst, TEAM); // starting a DS client will try to get the roboRIO address from the DS application NT_StartDSClient(inst); // connect to a specific host/port NT_SetServer(inst, "host", NT_DEFAULT_PORT4) ``` ```python import ntcore inst = ntcore.NetworkTableInstance.get_default() // start a NT4 client inst.start_client4("example client") // connect to a roboRIO with team number TEAM inst.set_server_team(TEAM) // starting a DS client will try to get the roboRIO address from the DS application inst.startDSClient() // connect to a specific host/port inst.set_server("host", ntcore.NetworkTableInstance.kDefaultPort4) ``` -------------------------------- ### Extract and Run WPILib Installer on Linux Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/zero-to-robot/step-2/wpilib-setup.rst Commands to extract the tarball and execute the installer binary in a terminal environment. ```console $ tar -xf WPILib_Linux-.tar.gz $ cd WPILib_Linux-/ $ ./WPILibInstaller ``` -------------------------------- ### Configure Commands in RobotContainer Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/commandbased/commands-v2/commands.rst Examples of instantiating and binding commands within the RobotContainer class. ```java m_drive.setDefaultCommand( new DefaultDrive( m_drive, () -> -m_driverController.getLeftY(), () -> -m_driverController.getRightX())); new JoystickButton(m_driverController, Button.kA.value) .onTrue(new GrabHatch(m_hatchSubsystem)); ``` ```cpp m_drive.SetDefaultCommand(DefaultDrive( &m_drive, [this] { return -m_driverController.GetLeftY(); }, [this] { return -m_driverController.GetRightX(); })); frc2::JoystickButton(&m_driverController, 1) .OnTrue(GrabHatch(&m_hatchSubsystem).ToPtr()); ``` ```python self.drive.setDefaultCommand( DefaultDrive( self.drive, lambda: -self.driverController.getLeftY(), lambda: -self.driverController.getRightX(), ) ) commands2.button.JoystickButton(self.driverController, 1).onTrue( GrabHatch(self.hatchSubsystem) ) ``` -------------------------------- ### Basic Drivetrain Implementation Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/zero-to-robot/step-4/creating-test-drivetrain-program-cpp-java-python.rst Standard robot drivetrain boilerplate for PWM-controlled motors. These examples serve as a starting point for robot control logic. ```java /* * The remoteliteralinclude directive was used in the source, but the content is not provided inline. */ ``` ```cpp /* * The remoteliteralinclude directive was used in the source, but the content is not provided inline. */ ``` ```python /* * The remoteliteralinclude directive was used in the source, but the content is not provided inline. */ ``` -------------------------------- ### Initialize NetworkTables Client Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/networktables/client-side-program.rst Demonstrates setting up a NetworkTables client, subscribing to topics, and connecting to the robot server. ```c #include #include #include #include int main() { NT_Instance inst = NT_GetDefaultInstance(); NT_Subscriber xSub = NT_Subscribe(NT_GetTopic(inst, "/datatable/x"), NT_DOUBLE, "double", NULL, 0); NT_Subscriber ySub = NT_Subscribe(NT_GetTopic(inst, "/datatable/y"), NT_DOUBLE, "double", NULL, 0); NT_StartClient4(inst, "example client"); NT_SetServerTeam(inst, TEAM); // where TEAM=190, 294, etc, or use inst.setServer("hostname") or similar NT_StartDSClient(inst); // recommended if running on DS computer; this gets the robot IP from the DS while (true) { thrd_sleep(&(struct timespec){.tv_sec=1}, NULL); double x = NT_GetDouble(xSub, 0.0); double y = NT_GetDouble(ySub, 0.0); printf("X: %f Y: %f\n", x, y); } } ``` ```python #!/usr/bin/env python3 import ntcore import time if __name__ == "__main__": inst = ntcore.NetworkTableInstance.get_default() table = inst.get_table("datatable") x_sub = table.get_double_topic("x").subscribe(0) y_sub = table.get_double_topic("y").subscribe(0) inst.start_client4("example client") inst.set_server_team(TEAM) # where TEAM=190, 294, etc, or use inst.set_server("hostname") or similar inst.startDSClient() # recommended if running on DS computer; this gets the robot IP from the DS while True: time.sleep(1) x = x_sub.get() y = y_sub.get() print(f"X: {x} Y: {y}") ``` -------------------------------- ### Install RobotPy on macOS Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/zero-to-robot/step-2/python-setup.rst Commands for installing or upgrading RobotPy on macOS using python3. ```sh python3 -m pip install robotpy ``` ```sh python3 -m pip install --upgrade robotpy ``` ```sh python3 -m pip install --user robotpy ``` -------------------------------- ### Instantiating and Using Command Factories Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/commandbased/commands-v2/organizing-command-based.rst Demonstrates how to instantiate a command factory class and use it to generate commands. ```java AutoRoutines autoRoutines = new AutoRoutines(this.drivetrain, this.intake); Command driveAndIntake = autoRoutines.driveAndIntake(); Command driveThenIntake = autoRoutines.driveThenIntake(); Command drivingAndIntakingSequence = Commands.sequence( autoRoutines.driveAndIntake(), autoRoutines.driveThenIntake() ); ``` ```c++ // TODO ``` -------------------------------- ### Launch VisualVM via Command Line Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/advanced-gradlerio/profiling-with-visualvm.rst Navigate to the VisualVM binary directory and launch it using the WPILib JDK path. ```bash cd "C:\Users\Public\wpilib\visualvm_2110\bin" ./visualvm --jdkhome "C:\Users\Public\wpilib\2025\jdk" ``` -------------------------------- ### Install RobotPy on Windows Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/zero-to-robot/step-2/python-setup.rst Commands for installing or upgrading RobotPy on Windows using the py launcher. ```sh py -3 -m pip install robotpy ``` ```sh py -3 -m pip install --upgrade robotpy ``` ```sh py -3 -m pip install --user robotpy ``` -------------------------------- ### Publishing to a Topic in Python Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/networktables/publish-and-subscribe.rst Demonstrates how to initialize a publisher, set values with various options, and close the publisher when finished. ```python class Example: def __init__(self, dblTopic: ntcore.DoubleTopic): # start publishing; the return value must be retained (in this case, via # an instance variable) self.dblPub = dblTopic.publish() # publish options may be specified using PubSubOption self.dblPub = dblTopic.publish(ntcore.PubSubOptions(keepDuplicates=True)) # publishEx provides additional options such as setting initial # properties and using a custom type string. Using a custom type string for # types other than raw and string is not recommended. The properties # must be a JSON map. self.dblPub = dblTopic.publishEx("double", {"myprop": 5}) def periodic(self): # publish a default value self.dblPub.setDefault(0.0) # publish a value with current timestamp self.dblPub.set(1.0) self.dblPub.set(2.0, 0) # 0 = use current time # publish a value with a specific timestamp with microsecond resolution. # On the roboRIO, this is the same as the FPGA timestamp (e.g. # RobotController.getFPGATime()) self.dblPub.set(3.0, ntcore._now()) # often not required in robot code, unless this class doesn't exist for # the lifetime of the entire robot program, in which case close() needs to be # called to stop publishing def close(self): # stop publishing self.dblPub.close() ``` -------------------------------- ### Install RobotPy on Linux Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/zero-to-robot/step-2/python-setup.rst Commands for checking pip version and installing or upgrading RobotPy on Linux systems. ```sh python3 -m pip --version ``` ```sh python3 -m pip install robotpy ``` ```sh python3 -m pip install --upgrade robotpy ``` -------------------------------- ### Initialize and Push a Git Repository Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/basic-programming/git-getting-started.rst Commands to initialize a local directory as a Git repository and link it to a remote GitHub URL. ```console > cd "C:\Users\ExampleUser9007\Documents\Example Folder" > git init Initialized empty Git repository in C:/Users/ExampleUser9007/Documents/Example Folder/.git/ > echo "# ExampleRepo" >> README.md > git add README.md > git commit -m "First commit" [main (root-commit) fafafa] First commit 1 file changed, 1 insertions(+), 0 deletions(-) create mode 100644 README.md > git remote add origin https://github.com/ExampleUser9007/ExampleRepo.git > git push -u origin main ``` ```console > cd "C:\Users\ExampleUser9007\Documents\Example Folder" > git init Initialized empty Git repository in C:/Users/ExampleUser9007/Documents/Example Folder/.git/ > git add . > git commit -m "First commit" [main (root-commit) fafafa] First commit 1 file changed, 1 insertions(+), 0 deletions(-) create mode 100644 README.md > git remote add origin https://github.com/ExampleUser9007/ExampleRepo.git > git push -u origin main ``` -------------------------------- ### Create LED Buffer Views Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/hardware-apis/misc/addressable-leds.rst Demonstrates creating and reversing buffer views to manage specific segments of an LED strip. ```Java // Create the buffer AddressableLEDBuffer m_buffer = new AddressableLEDBuffer(120); // Create the view for the section of the strip on the left side of the robot. // This section spans LEDs from index 0 through index 59, inclusive. AddressableLEDBufferView m_left = m_buffer.createView(0, 59); // The section of the strip on the right side of the robot. // This section spans LEDs from index 60 through index 119, inclusive. // This view is reversed to cancel out the serpentine arrangement of the // physical LED strip on the robot. AddressableLEDBufferView m_right = m_buffer.createView(60, 119).reversed(); ``` ```C++ // Create the buffer std::array m_buffer; // Create the view for the section of the strip on the left side of the robot. // This section spans LEDs from index 0 through index 59, inclusive. std::view m_left = std::ranges::take_view(m_buffer, 60); // The section of the strip on the right side of the robot. // This section spans LEDs from index 60 through index 119, inclusive. // This view is reversed to cancel out the serpentine arrangement of the // physical LED strip on the robot. std::view m_right = std::ranges::reverse_view( std::ranges::drop_view(m_buffer, 60)); ``` -------------------------------- ### Using Entry to Both Subscribe and Publish in Python Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/networktables/publish-and-subscribe.rst Demonstrates initializing an entry from a topic, performing read/write operations, and managing the lifecycle of the entry. ```python class Example: def __init__(self, dblTopic: ntcore.DoubleTopic): # start subscribing; the return value must be retained. # the parameter is the default value if no value is available when get() is called self.dblEntry = dblTopic.get_entry(0.0) # publish and subscribe options may be specified using PubSubOption self.dblEntry = dblTopic.get_entry( 0.0, ntcore.PubSubOptions(keepDuplicates=True, poll_storage=10) ) # getEntryEx provides the options of using a custom type string. # Using a custom type string for types other than raw and string is not recommended. self.dblEntry = dblTopic.getEntryEx("double", 0.0) def periodic(self): # entries support all the same methods as subscribers: val = self.dblEntry.get() val = self.dblEntry.get(-1.0) val = self.dblEntry.getAsDouble() tsVal = self.dblEntry.getAtomic() tsUpdates = self.dblEntry.read_queue() # entries also support all the same methods as publishers; the first time # one of these is called, an internal publisher is automatically created self.dblEntry.setDefault(0.0) self.dblEntry.set(1.0) self.dblEntry.set(2.0, 0) # 0 = use current time time = ntcore._now() self.dblEntry.set(3.0, time) def unpublish(self): # you can stop publishing while keeping the subscriber alive self.dblEntry.unpublish() # often not required in robot code, unless this class doesn't exist for # the lifetime of the entire robot program, in which case close() needs to be # called to stop subscribing def close(self): # stop subscribing/publishing self.dblEntry.close() ``` -------------------------------- ### Install RobotPy on Linux ARM Coprocessor Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/zero-to-robot/step-2/python-setup.rst Commands for installing RobotPy on ARM devices using prebuilt wheels or source compilation. ```sh python3 -m pip install --extra-index-url=https://wpilib.jfrog.io/artifactory/api/pypi/wpilib-python-release-2025/simple robotpy ``` ```sh export CC=gcc-14 CXX=g++-14 ``` -------------------------------- ### Manual cscore Object Creation Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/vision-processing/introduction/cameraserver-class.rst Demonstrates the manual creation and connection of UsbCamera, MjpegServer, CvSink, and CvSource objects, which CameraServer typically automates. ```java import edu.wpi.cscore.CvSink; import edu.wpi.cscore.CvSource; import edu.wpi.cscore.MjpegServer; import edu.wpi.cscore.UsbCamera; // Creates UsbCamera and MjpegServer [1] and connects them UsbCamera usbCamera = new UsbCamera("USB Camera 0", 0); MjpegServer mjpegServer1 = new MjpegServer("serve_USB Camera 0", 1181); mjpegServer1.setSource(usbCamera); // Creates the CvSink and connects it to the UsbCamera CvSink cvSink = new CvSink("opencv_USB Camera 0"); cvSink.setSource(usbCamera); // Creates the CvSource and MjpegServer [2] and connects them CvSource outputStream = new CvSource("Blur", PixelFormat.kMJPEG, 640, 480, 30); MjpegServer mjpegServer2 = new MjpegServer("serve_Blur", 1182); mjpegServer2.setSource(outputStream); ``` ```c++ #include "wpi/cs/cscore_oo.hpp" // Creates UsbCamera and MjpegServer [1] and connects them wpi::cs::UsbCamera usbCamera("USB Camera 0", 0); wpi::cs::MjpegServer mjpegServer1("serve_USB Camera 0", 1181); mjpegServer1.SetSource(usbCamera); // Creates the CvSink and connects it to the UsbCamera wpi::cs::CvSink cvSink("opencv_USB Camera 0"); cvSink.SetSource(usbCamera); // Creates the CvSource and MjpegServer [2] and connects them wpi::cs::CvSource outputStream("Blur", wpi::cs::PixelFormat::kMJPEG, 640, 480, 30); wpi::cs::MjpegServer mjpegServer2("serve_Blur", 1182); mjpegServer2.SetSource(outputStream); ``` -------------------------------- ### Configure DashboardCmdLine for WPILib Installer Dashboards Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/driverstation/manually-setting-the-driver-station-to-start-custom-dashboard.rst Set the command line to execute a VBScript provided by the WPILib installation. Replace YYYY with the current year and specify the correct dashboard script. ```text wscript C:\Users\Public\wpilib\YYYY\tools\DASHBOARD.vbs ``` ```text DashboardCmdLine = "wscript C:\Users\Public\wpilib\2025\tools\Elastic.vbs" ``` -------------------------------- ### Get Encoder Period Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/hardware-apis/sensors/encoders-software.rst Retrieve the period of the encoder pulses in seconds. ```java double period = encoder.getPeriod(); ``` ```cpp double period = encoder.GetPeriod(); ``` -------------------------------- ### Initialize CameraServer and Video Streams Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/vision-processing/introduction/cameraserver-class.rst Configures automatic camera capture, creates a sink for OpenCV processing, and sets up an output stream for dashboard visualization. ```java import edu.wpi.first.cameraserver.CameraServer; import edu.wpi.cscore.CvSink; import edu.wpi.cscore.CvSource; // Creates UsbCamera and MjpegServer [1] and connects them CameraServer.startAutomaticCapture(); // Creates the CvSink and connects it to the UsbCamera CvSink cvSink = CameraServer.getVideo(); // Creates the CvSource and MjpegServer [2] and connects them CvSource outputStream = CameraServer.putVideo("Blur", 640, 480); ``` ```c++ #include "cameraserver/CameraServer.h" // Creates UsbCamera and MjpegServer [1] and connects them wpi::CameraServer::StartAutomaticCapture(); // Creates the CvSink and connects it to the UsbCamera wpi::cs::CvSink cvSink = wpi::CameraServer::GetVideo(); // Creates the CvSource and MjpegServer [2] and connects them wpi::cs::CvSource outputStream = wpi::CameraServer::PutVideo("Blur", 640, 480); ``` -------------------------------- ### Get Encoder Direction Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/hardware-apis/sensors/encoders-software.rst Retrieve the direction of the last encoder movement. ```java boolean direction = encoder.getDirection(); ``` ```cpp bool direction = encoder.GetDirection(); ``` -------------------------------- ### Get Encoder Distance Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/hardware-apis/sensors/encoders-software.rst Retrieve the total distance traveled by the encoder. ```java double distance = encoder.getDistance(); ``` ```cpp double distance = encoder.GetDistance(); ``` -------------------------------- ### Apply Solid Color Pattern to LEDs Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/hardware-apis/misc/addressable-leds.rst Demonstrates creating a solid color pattern and applying it to an LED buffer. ```Java // Create an LED pattern that sets the entire strip to solid red LEDPattern red = LEDPattern.solid(Color.kRed); // Apply the LED pattern to the data buffer red.applyTo(m_ledBuffer); // Write the data to the LED strip m_led.setData(m_ledBuffer); ``` ```C++ // Create an LED pattern that sets the entire strip to solid red LEDPattern red = LEDPattern.Solid(Color::kRed); // Apply the LED pattern to the data buffer red.ApplyTo(m_ledBuffer); // Write the data to the LED strip m_led.SetData(m_ledBuffer); ``` -------------------------------- ### Creating CommandPtr instances in HatchbotInlined Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/commandbased/commands-v2/cpp-command-discussion.rst Demonstrates using factory methods and decorators to construct command sequences in a C++ project. ```cpp frc2::CommandPtr Autos::ExampleAuto() { return frc2::cmd::Sequence( frc2::cmd::Print("Starting auto"), frc2::cmd::RunOnce([&drive] { drive.ResetEncoders(); }, {&drive}), frc2::cmd::RunOnce([&drive] { drive.TankDriveVolts(10_V, 10_V); }, {&drive}), frc2::cmd::Wait(3_s), frc2::cmd::RunOnce([&drive] { drive.TankDriveVolts(0_V, 0_V); }, {&drive}), frc2::cmd::Print("Ending auto")); } frc2::CommandPtr Autos::ComplexAuto() { return frc2::cmd::Sequence( frc2::cmd::Print("Starting complex auto"), frc2::cmd::ParallelRaceGroup( frc2::cmd::RunOnce([&drive] { drive.TankDriveVolts(10_V, 10_V); }, {&drive}), frc2::cmd::Wait(3_s)), frc2::cmd::RunOnce([&drive] { drive.TankDriveVolts(0_V, 0_V); }, {&drive}), frc2::cmd::Print("Ending complex auto")); } ``` -------------------------------- ### Initialize DataLogManager Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/telemetry/datalog.rst Starts the centralized data log, which automatically records NetworkTables changes. ```java import edu.wpi.first.wpilibj.DataLogManager; // Starts recording to data log DataLogManager.start(); ``` ```c++ #include "wpi/system/DataLogManager.hpp" // Starts recording to data log wpi::DataLogManager::Start(); ``` ```python from wpilib import DataLogManager DataLogManager.start() ``` -------------------------------- ### Create TrapezoidProfile States Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/advanced-controls/controllers/trapezoidal-profiles.rst Define the starting and ending position and velocity states for the mechanism. ```java // Creates a new state with a position of 5 meters // and a velocity of 0 meters per second new TrapezoidProfile.State(5, 0); ``` ```cpp // Creates a new state with a position of 5 meters // and a velocity of 0 meters per second wpi::math::TrapezoidProfile::State{5_m, 0_mps}; ``` ```python from wpimath.trajectory import TrapezoidProfile # Creates a new state with a position of 5 meters # and a velocity of 0 meters per second TrapezoidProfile.State(5, 0) ``` -------------------------------- ### Create Flywheel State-Space System Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/advanced-controls/state-space/state-space-flywheel-walkthrough.rst Examples for initializing a LinearSystem for a flywheel using identified kV and kA constants. ```java var plant = LinearSystemId.identifyVelocitySystem( 0.023, 0.001); var observer = new KalmanFilter<>( Nat.N1(), Nat.N1(), plant, VecBuilder.fill(3.0), VecBuilder.fill(0.01), 0.020); var controller = new LinearQuadraticRegulator<>( plant, VecBuilder.fill(8.0), VecBuilder.fill(12.0), 0.020); ``` ```c++ auto plant = frc::LinearSystemId::IdentifyVelocitySystem<1, 1>(0.023_V / 1_rad_per_s, 0.001_V / 1_rad_per_s_sq); ``` ```c++ frc::LinearSystem<1, 1, 1> plant = frc::LinearSystemId::IdentifyVelocitySystem<1, 1>(0.023_V / 1_rad_per_s, 0.001_V / 1_rad_per_s_sq); frc::KalmanFilter<1, 1, 1> observer{ plant, {3.0}, {0.01}, 20_ms}; frc::LinearQuadraticRegulator<1, 1> controller{ plant, {8.0}, {12.0}, 20_ms}; ``` ```python self.plant = wpimath.system.identification.identifyVelocitySystem( 0.023, 0.001 ) ``` ```python self.plant = wpimath.system.identification.identifyVelocitySystem( 0.023, 0.001 ) self.observer = wpimath.estimator.KalmanFilter( wpimath.Nat.N1(), wpimath.Nat.N1(), self.plant, [3.0], [0.01], 0.020 ) self.controller = wpimath.controller.LinearQuadraticRegulator( self.plant, [8.0], [12.0], 0.020 ) ``` -------------------------------- ### Implement a Default Drive Command Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/commandbased/commands-v2/commands.rst Examples of a command that runs continuously and does not terminate, typically used as a default command. ```java package frc.robot.commands; import edu.wpi.first.wpilibj2.command.Command; import frc.robot.subsystems.DriveSubsystem; import java.util.function.DoubleSupplier; public class DefaultDrive extends Command { private final DriveSubsystem m_drive; private final DoubleSupplier m_forward; private final DoubleSupplier m_rotation; public DefaultDrive(DriveSubsystem subsystem, DoubleSupplier forward, DoubleSupplier rotation) { m_drive = subsystem; m_forward = forward; m_rotation = rotation; addRequirements(m_drive); } @Override public void execute() { m_drive.arcadeDrive(m_forward.getAsDouble(), m_rotation.getAsDouble()); } } ``` ```cpp #pragma once #include #include #include #include "subsystems/DriveSubsystem.h" class DefaultDrive : public frc2::CommandHelper { public: DefaultDrive(DriveSubsystem* subsystem, std::function forward, std::function rotation); void Execute() override; private: DriveSubsystem* m_drive; std::function m_forward; std::function m_rotation; }; ``` ```cpp #include "commands/DefaultDrive.hpp" DefaultDrive::DefaultDrive(DriveSubsystem* subsystem, std::function forward, std::function rotation) : m_drive(subsystem), m_forward(forward), m_rotation(rotation) { AddRequirements(subsystem); } void DefaultDrive::Execute() { m_drive->ArcadeDrive(m_forward(), m_rotation()); } ``` ```python import commands2 import typing from subsystems.drivesubsystem import DriveSubsystem class DefaultDrive(commands2.Command): def __init__( self, subsystem: DriveSubsystem, forward: typing.Callable[[], float], rotation: typing.Callable[[], float] ) -> None: super().__init__() self.drive = subsystem self.forward = forward self.rotation = rotation self.addRequirements(subsystem) def execute(self) -> None: self.drive.arcadeDrive(self.forward(), self.rotation()) ``` -------------------------------- ### RobotContainer Constructor Setup Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/commandbased/commands-v2/structuring-command-based-project.rst The constructor initializes the robot state and triggers configuration methods. ```java public RobotContainer() { // Configure the trigger bindings configureBindings(); } private void configureBindings() { // Schedule `ExampleCommand` when `exampleCondition` is true new Trigger(m_exampleSubsystem::exampleCondition) .onTrue(new ExampleCommand(m_exampleSubsystem)); // Schedule `exampleMethodCommand` when the Xbox controller's B button is pressed, // cancelling on release. m_driverController.b().whileTrue(m_subsystem.exampleMethodCommand()); } ``` ```cpp RobotContainer::RobotContainer() { ConfigureBindings(); } void RobotContainer::ConfigureBindings() {} ``` -------------------------------- ### Simulation Console Output Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/wpilib-tools/robot-simulation/introduction.rst Example of console output when running simulation without the GUI. ```console ********** Robot program starting ********** Default disabledInit() method... Override me! Default disabledPeriodic() method... Override me! Default robotPeriodic() method... Override me! ``` -------------------------------- ### Example Documentation Structure Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/contributing/wpilib-docs/style-guide.rst Demonstrates the expected structure for ReST documentation files including code blocks. ```ReST # Title This is an example article ```java System.out.println("Hello World"); ``` ## Section This is a section! ``` -------------------------------- ### Manage NetworkTables Instances Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/networktables/multiple-instances.rst Demonstrates how to retrieve the default instance, create a new instance, and destroy an instance across different programming languages. ```java // get the default NetworkTable instance NetworkTableInstance defaultInst = NetworkTableInstance.getDefault(); // create a NetworkTable instance NetworkTableInstance inst = NetworkTableInstance.create(); // destroy a NetworkTable instance inst.close(); ``` ```cpp // get the default NetworkTable instance nt::NetworkTableInstance defaultInst = nt::NetworkTableInstance::GetDefault(); // create a NetworkTable instance nt::NetworkTableInstance inst = nt::NetworkTableInstance::Create(); // destroy a NetworkTable instance; NetworkTableInstance objects are not RAII nt::NetworkTableInstance::Destroy(inst); ``` ```cpp // get the default NetworkTable instance NT_Instance defaultInst = nt::GetDefaultInstance(); // create a NetworkTable instance NT_Instance inst = nt::CreateInstance(); // destroy a NetworkTable instance nt::DestroyInstance(inst); ``` ```c // get the default NetworkTable instance NT_Instance defaultInst = NT_GetDefaultInstance(); // create a NetworkTable instance NT_Instance inst = NT_CreateInstance(); // destroy a NetworkTable instance NT_DestroyInstance(inst); ``` ```python import ntcore # get the default NetworkTable instance defaultInst = ntcore.NetworkTableInstance.get_default() # create a NetworkTable instance inst = ntcore.NetworkTableInstance.create() # destroy a NetworkTable instance ntcore.NetworkTableInstance.destroy(inst) ``` -------------------------------- ### Swap Initialization Script Content Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/basic-programming/java-gc.rst The content required for the /etc/init.d/addswap.sh script to enable the swap file on boot. ```text #!/bin/sh [ -x /sbin/swapon ] && swapon -e /u/swapfile : exit 0 ``` -------------------------------- ### Java Division by Zero Stack Trace Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/software/basic-programming/reading-stacktraces.rst Example output showing a java.lang.ArithmeticException in the console. ```text ********** Robot program starting ********** Error at frc.robot.Robot.robotInit(Robot.java:24): Unhandled exception: java.lang.ArithmeticException: / by zero at frc.robot.Robot.robotInit(Robot.java:24) at edu.wpi.first.wpilibj.TimedRobot.startCompetition(TimedRobot.java:107) at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:373) at edu.wpi.first.wpilibj.RobotBase.startRobot(RobotBase.java:463) at frc.robot.Main.main(Main.java:23) Warning at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:388): The robot program quit unexpectedly. This is usually due to a code error. The above stacktrace can help determine where the error occurred. See https://wpilib.org/stacktrace for more information. Error at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:395): The startCompetition() method (or methods called by it) should have handled the exception above. ``` -------------------------------- ### Initialize a new RobotPy project Source: https://github.com/wpilibsuite/wpilib-docs/blob/main/source/docs/zero-to-robot/step-2/python-setup.rst Creates a skeleton robot.py and pyproject.toml file in the current directory. ```sh py -3 -m robotpy init ``` ```sh python3 -m robotpy init ```