### Basic Java 'Hello World' Example Source: https://docs.wpilib.org/en/stable/docs/contributing/frc-docs/style-guide A simple 'Hello World' example in Java, demonstrating basic console output. This snippet is provided as a general example within the documentation. ```java System.out.println("Hello World"); ``` -------------------------------- ### Initialize RobotPy Project (Cross-Platform) Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/python-setup Initializes a new RobotPy robot project in the current directory or an empty directory. Creates `robot.py` for robot code and `pyproject.toml` for project dependencies. Ensure you have the `robotpy` project installed. ```shell py -3 -m robotpy init ``` ```shell python3 -m robotpy init ``` ```shell python3 -m robotpy init ``` -------------------------------- ### CameraServer Setup (Java and C++) Source: https://docs.wpilib.org/en/stable/docs/software/vision-processing/introduction/cameraserver-class This snippet demonstrates the high-level setup of camera capture and video output using the CameraServer class. It initializes an automatic capture, gets a video sink, and creates a video source for streaming. ```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); ``` ```cpp #include "cameraserver/CameraServer.h" // Creates UsbCamera and MjpegServer [1] and connects them frc::CameraServer::StartAutomaticCapture(); // Creates the CvSink and connects it to the UsbCamera cs::CvSink cvSink = frc::CameraServer::GetVideo(); // Creates the CvSource and MjpegServer [2] and connects them cs::CvSource outputStream = frc::CameraServer::PutVideo("Blur", 640, 480); ``` -------------------------------- ### Install RobotPy to User Site-Packages (Windows) Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/python-setup Installs RobotPy to the user site-packages directory on Windows when administrative rights are not available. This uses pip and Python 3. ```bash py -3 -m pip install --user robotpy ``` -------------------------------- ### Generate Example Trajectory in Java Source: https://docs.wpilib.org/en/stable/docs/software/pathplanning/trajectory-tutorial/creating-following-trajectory Generates an example trajectory using TrajectoryGenerator in Java. It defines the start and end poses, intermediate waypoints, and passes the pre-configured TrajectoryConfig to create a followable path for the robot. ```java Trajectory exampleTrajectory = TrajectoryGenerator.generateTrajectory(new Pose2d(0, 0, new Rotation2d(0)), List.of(new Translation2d(1, 1), new Translation2d(2, -1)), new Pose2d(3, 0, new Rotation2d(0)), config); ``` -------------------------------- ### Sync RobotPy Packages (Cross-Platform) Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/python-setup Downloads and installs Python compiled for roboRIO, roboRIO-compatible Python packages, and installs specified packages into your local environment. This command requires a working robot project and `pyproject.toml` to be configured. The `--user` argument can be used for user-specific installations without administrative privileges. ```shell py -3 -m robotpy sync ``` ```shell python3 -m robotpy sync ``` ```shell python3 -m robotpy sync ``` -------------------------------- ### Install RobotPy Core Packages (Windows) Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/python-setup Installs the core RobotPy packages on Windows using pip. Requires Python 3 and the Visual Studio 2022 redistributable package. This command should be run from cmd or PowerShell. ```bash py -3 -m pip install robotpy ``` -------------------------------- ### Create Example Subsystem - Java Source: https://docs.wpilib.org/en/stable/docs/software/commandbased/subsystems Demonstrates how to create a basic subsystem in Java by extending `SubsystemBase`. Includes methods for creating example commands, querying subsystem state, and periodic/simulation updates. Requires the WPILib library. ```java import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.SubsystemBase; public class ExampleSubsystem extends SubsystemBase { /** Creates a new ExampleSubsystem. */ public ExampleSubsystem() {} /** * Example command factory method. * * @return a command */ public Command exampleMethodCommand() { // Inline construction of command goes here. // Subsystem::RunOnce implicitly requires `this` subsystem. return runOnce( () -> { /* one-time action goes here */ }); } /** * An example method querying a boolean state of the subsystem (for example, a digital sensor). * * @return value of some boolean subsystem state, such as a digital sensor. */ public boolean exampleCondition() { // Query some boolean state, such as a digital sensor. return false; } @Override public void periodic() { // This method will be called once per scheduler run } @Override public void simulationPeriodic() { // This method will be called once per scheduler run during simulation } } ``` -------------------------------- ### Check Pip Version (Linux) Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/python-setup Checks the version of pip installed on a Linux system. A version of 20.3 or newer is recommended for RobotPy installation. ```bash python3 -m pip --version ``` -------------------------------- ### Install RobotPy to User Site-Packages (macOS) Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/python-setup Installs RobotPy to the user site-packages directory on macOS when administrative rights are not available. This uses pip and Python 3. ```bash python3 -m pip install --user robotpy ``` -------------------------------- ### Initialize and Push Empty Directory Git Repository Source: https://docs.wpilib.org/en/stable/docs/software/basic-programming/git-getting-started This snippet demonstrates the process of initializing a new Git repository in an empty directory, adding a README file, and pushing it to a remote origin. It's useful for starting a project from scratch. Dependencies include Git being installed and a remote repository URL. ```shell > 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 ``` -------------------------------- ### Start a Simple Web Server (Java) Source: https://docs.wpilib.org/en/stable/docs/yearly-overview/yearly-changelog Starts a simple web server to serve files from a specified directory. This is useful for hosting static assets or configuration files. Requires the WebServer class and Filesystem utility. ```java WebServer.start(5800, Filesystem.getDeployDirectory()); ``` -------------------------------- ### Install RobotPy Core Packages (macOS) Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/python-setup Installs the core RobotPy packages on macOS using pip and Python 3. This command may require administrator rights and should be run from the Terminal. ```bash python3 -m pip install robotpy ``` -------------------------------- ### Initialize and Push Existing Project Git Repository Source: https://docs.wpilib.org/en/stable/docs/software/basic-programming/git-getting-started This snippet shows how to initialize a Git repository in an existing project directory, add all current files, commit them, and push to a remote origin. This is suitable for projects that already have files. Dependencies include Git installation and a remote repository URL. ```shell > 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 ``` -------------------------------- ### Install RobotPy with Extra Index URL (Linux ARM) Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/python-setup Installs RobotPy on Linux ARM coprocessors by specifying an extra index URL for prebuilt wheels from Artifactory. Requires pip and Python 3. ```bash python3 -m pip install --extra-index-url=https://wpilib.jfrog.io/artifactory/api/pypi/wpilib-python-release-2025/simple robotpy ``` -------------------------------- ### Example .styleguide for wpiformat Source: https://docs.wpilib.org/en/stable/docs/software/advanced-gradlerio/code-formatting An example configuration file for wpiformat, specifying include patterns for C++ header and source files, and defining directories to exclude from formatting. Teams can customize this file. ```config cppHeaderFileInclude { \.h$ \.hpp$ \.inc$ \.inl$ } cppSrcFileInclude { \.cpp$ } modifiableFileExclude { gradle/ } ``` -------------------------------- ### Image Inclusion Example Source: https://docs.wpilib.org/en/stable/docs/contributing/frc-docs/style-guide Provides an example of how to include an image in the documentation using the `.. image::` directive. It includes the required `:alt:` directive for accessibility and specifies the image path. ```rst .. image:: images/my-article/my-image.png :alt: Always add alt text here describing the image. ``` -------------------------------- ### Run C++ Robot Simulation via Gradle Source: https://docs.wpilib.org/en/stable/docs/software/wpilib-tools/robot-simulation/introduction Execute C++ robot simulation directly from the command line using the Gradle wrapper. This command initiates the simulation process for your C++ robot code. Ensure a native compiler is installed. ```bash ./gradlew simulateNative ``` -------------------------------- ### Set C++ Compiler for Source Install (Linux) Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/python-setup Sets the C and C++ compiler environment variables for building RobotPy from source on Linux. This is useful for specifying specific compiler versions. ```bash export CC=gcc-12 export CXX=g++-12 ``` -------------------------------- ### Configure SmartDashboard for Simulation Source: https://docs.wpilib.org/en/stable/docs/software/wpilib-tools/robot-simulation/introduction Connect SmartDashboard to a simulation by opening its preferences and entering `localhost` in the Team Number field. This ensures SmartDashboard connects to the local simulation instance instead of the robotRIO. ```text Open SmartDashboard preferences -> File menu. In the Team Number field, enter: localhost ``` -------------------------------- ### Run Java Robot Simulation via Gradle Source: https://docs.wpilib.org/en/stable/docs/software/wpilib-tools/robot-simulation/introduction Execute Java robot simulation directly from the command line using the Gradle wrapper. This command initiates the simulation process for your Java robot code. ```bash ./gradlew simulateJava ``` -------------------------------- ### NT3 NetworkTableEntry Example (C++) Source: https://docs.wpilib.org/en/stable/docs/software/networktables/nt4-migration-guide Shows the C++ implementation of the legacy NetworkTableEntry API. It involves obtaining a NetworkTableInstance, accessing a specific subtable, and then getting entries for reading and writing double values. The example reads from 'Y' and writes to 'Out'. ```cpp class Example { nt::NetworkTableEntry yEntry; nt::NetworkTableEntry outEntry; public: Example() { nt::NetworkTableInstance inst = nt::NetworkTableInstance::GetDefault(); // get the subtable called "datatable" auto datatable = inst.GetTable("datatable"); // get the entry in "datatable" called "Y" yEntry = datatable->GetEntry("Y"); // get the entry in "datatable" called "Out" outEntry = datatable->GetEntry("Out"); } void Periodic() { // read a double value from Y, and set Out to that value multiplied by 2 double value = yEntry.GetDouble(0.0); // default to 0 outEntry.SetDouble(value * 2); } }; ``` -------------------------------- ### Create Example Subsystem - C++ Source: https://docs.wpilib.org/en/stable/docs/software/commandbased/subsystems Shows how to define a basic subsystem in C++ by inheriting from `frc2::SubsystemBase`. This includes method declarations for commands, state queries, and periodic updates. Requires WPILib headers. ```cpp #pragma once #include #include class ExampleSubsystem : public frc2::SubsystemBase { public: ExampleSubsystem(); /** * Example command factory method. */ frc2::CommandPtr ExampleMethodCommand(); /** * An example method querying a boolean state of the subsystem (for example, a * digital sensor). * * @return value of some boolean subsystem state, such as a digital sensor. */ bool ExampleCondition(); /** * Will be called periodically whenever the CommandScheduler runs. */ void Periodic() override; /** * Will be called periodically whenever the CommandScheduler runs during * simulation. */ void SimulationPeriodic() override; private: // Components (e.g. motor controllers and sensors) should generally be // declared private and exposed only through public methods. }; ``` -------------------------------- ### NT3 NetworkTableEntry Example (Python) Source: https://docs.wpilib.org/en/stable/docs/software/networktables/nt4-migration-guide Provides a Python example for using the NetworkTableEntry API. It initializes by getting the default NetworkTableInstance, accessing a subtable, and then retrieving specific entries. The periodic method reads a double from 'Y' and writes twice that value to 'Out'. ```python class Example: def __init__(self): inst = ntcore.NetworkTableInstance.getDefault() # get the subtable called "datatable" datatable = inst.getTable("datatable") # get the entry in "datatable" called "Y" self.yEntry = datatable.getEntry("Y") # get the entry in "datatable" called "Out" self.outEntry = datatable.getEntry("Out") def periodic(self): # read a double value from Y, and set Out to that value multiplied by 2 value = self.yEntry.getDouble(0.0) # default to 0 self.outEntry.setDouble(value * 2) ``` -------------------------------- ### C++ WPILib Robot Main Entry Point Source: https://docs.wpilib.org/en/stable/docs/software/vision-processing/roborio/using-the-cameraserver-on-the-roborio The standard C++ entry point for a WPILib robot application. It initializes the robot framework and starts the main robot class. This code is typically found in the main.cpp file. ```cpp #ifndef RUNNING_FRC_TESTS int main() { return frc::StartRobot(); } #endif ``` -------------------------------- ### NT4 NetworkTable Entry Example (Python) Source: https://docs.wpilib.org/en/stable/docs/software/networktables/nt4-migration-guide Provides a Python example for the NT4 API, utilizing DoubleSubscriber and DoublePublisher. It gets the default NetworkTableInstance, accesses the 'datatable' subtable, subscribes to the 'Y' double topic with a default value, and publishes to the 'Out' double topic. ```python class Example: def __init__(self) -> None: inst = ntcore.NetworkTableInstance.getDefault() # get the subtable called "datatable" datatable = inst.getTable("datatable") # subscribe to the topic in "datatable" called "Y" # default value is 0 self.ySub = datatable.getDoubleTopic("Y").subscribe(0.0) # publish to the topic in "datatable" called "Out" self.outPub = datatable.getDoubleTopic("Out").publish() def periodic(self): # read a double value from Y, and set Out to that value multiplied by 2 value = self.ySub.get() self.outPub.set(value * 2) # often not required in robot code, unless this class doesn't exist for ``` -------------------------------- ### Linux Installer Execution Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/wpilib-setup Instructions for running the WPILib installer on Linux after extracting the tar.gz archive. This involves navigating to the extracted directory and executing the installer script via the terminal. ```bash tar -xf WPILib_Linux-.tar.gz cd WPILib_Linux-/ ./WPILibInstaller ``` -------------------------------- ### Run Intake Sequence with Parameterization (Java & C++) Source: https://docs.wpilib.org/en/stable/docs/software/commandbased/organizing-command-based Illustrates using the parameterized `runIntakeCommand` to create a sequence of actions. This example shows running the intake forward, waiting, and then running it backward with specific timeouts, demonstrating advanced command composition. ```java Command intakeRunSequence = intake.runIntakeCommand(1.0).withTimeout(2.0) .andThen(Commands.waitSeconds(2.0)) .andThen(intake.runIntakeCommand(-1.0).withTimeout(5.0)); ``` ```cpp frc2::CommandPtr intakeRunSequence = intake.RunIntakeCommand(1.0).WithTimeout(2.0_s) .AndThen(frc2::cmd::Wait(2.0_s)) .AndThen(intake.RunIntakeCommand(-1.0).WithTimeout(5.0_s)); ``` -------------------------------- ### Create Example Subsystem - Python Source: https://docs.wpilib.org/en/stable/docs/software/commandbased/subsystems Illustrates creating a simple subsystem in Python by subclassing `commands2.Subsystem`. Features include a constructor, command factory, state checking method, and periodic update functions. Relies on the `commands2` library. ```python from commands2 import Command from commands2 import Subsystem class ExampleSubsystem(Subsystem): def __init__(self): """Creates a new ExampleSubsystem.""" super().__init__() def exampleMethodCommand()->Command: """ Example command factory method. :return a command """ return self.runOnce( lambda: # one-time action goes here # ) def exampleCondition(self)->bool: """ An example method querying a boolean state of the subsystem (for example, a digital sensor). :return value of some boolean subsystem state, such as a digital sensor. """ #Query some boolean state, such as a digital sensor. return False def periodic(self): # This method will be called once per scheduler run pass def simulationPeriodic(self): # This method will be called once per scheduler run during simulation pass ``` -------------------------------- ### Uninstall RobotPy (Windows) Source: https://docs.wpilib.org/en/stable/docs/zero-to-robot/step-2/python-setup Uninstalls a previous version of RobotPy on Windows using pip. This is recommended before upgrading to a new version. ```bash py -m pip uninstall robotpy ``` -------------------------------- ### Enable Desktop Support in build.gradle (Java/C++) Source: https://docs.wpilib.org/en/stable/docs/software/wpilib-tools/robot-simulation/introduction This snippet shows how to enable desktop simulation support by modifying the `build.gradle` file. It involves changing a boolean flag to `true`. Ensure this is done at the root of your robot project. ```gradle includeDesktopSupport = true ``` -------------------------------- ### NT3 NetworkTableEntry Example (Java) Source: https://docs.wpilib.org/en/stable/docs/software/networktables/nt4-migration-guide Demonstrates how to use the legacy NetworkTableEntry API in Java to get a network table subtable and specific entries, then read a double value from one entry and set another entry to twice that value. It uses NetworkTableInstance.getDefault() to get the default instance and getTable() to access subtables. ```java public class Example { final NetworkTableEntry yEntry; final NetworkTableEntry outEntry; public Example() { NetworkTableInstance inst = NetworkTableInstance.getDefault(); // get the subtable called "datatable" NetworkTable datatable = inst.getTable("datatable"); // get the entry in "datatable" called "Y" yEntry = datatable.getEntry("Y"); // get the entry in "datatable" called "Out" outEntry = datatable.getEntry("Out"); } public void periodic() { // read a double value from Y, and set Out to that value multiplied by 2 double value = yEntry.getDouble(0.0); // default to 0 outEntry.setDouble(value * 2); } } ``` -------------------------------- ### Run Spotless Formatting and Checks via Gradle Source: https://docs.wpilib.org/en/stable/docs/software/advanced-gradlerio/code-formatting Demonstrates how to execute Spotless tasks using the Gradle wrapper. The `./gradlew spotlessApply` command formats code, while `./gradlew spotlessCheck` verifies if the code adheres to the defined formatting rules, making it suitable for CI integration. ```bash ./gradlew spotlessApply ``` ```bash ./gradlew spotlessCheck ``` ```bash ./gradlew spotlessmiscApply ```