> This is part 1 of 4 of the full documentation (pages 1–100 of 314).
> The content is paginated: fetch every part to see all of it.
> Next part: https://yams.yassrobotics.com/llms-full.txt/1
> Page index: https://yams.yassrobotics.com/llms.txt

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://yams.yassrobotics.com/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Yet Another Mechanism System

Yet Another Mechanism System: the mechanism library built from years of FRC experience. Describe your mechanism once, and get the commands, simulation, telemetry, and live tuning.

<h2 align="center"><mark style="color:$primary;">Yet Another Mechanism System</mark></h2>

<p align="center">Describe your mechanism once. YAMS gives you the commands, simulation, telemetry, and live tuning that top FRC teams spend seasons building, all in one open-source library.</p>

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="image">Cover image</th></tr></thead><tbody><tr><td><i class="fa-wand-magic-sparkles">:wand-magic-sparkles:</i></td><td><strong>Generate a mechanism</strong></td><td>Want to skip straight to working code? Describe your mechanism in a form, and YAMG, our mechanism generator, writes the YAMS subsystem for you, ready to drop into your robot. It handles elevators, arms, pivots, turrets, and flywheels, with support for absolute encoders and homing switches.</td><td><a href="https://yamg.yassrobotics.com">https://yamg.yassrobotics.com</a></td><td><a href="https://1716920675-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7CGD7e6lKU4QRNJBaUs1%2Fuploads%2Fgit-blob-f102670213946765aad837958a19f8d4370d5b96%2Fyamg.png?alt=media">yamg.png</a></td></tr><tr><td><i class="fa-robot">:robot:</i></td><td><strong>Examples</strong></td><td>Download complete robot projects built with YAMS from the latest release, for Commands v2 and v3: BroncBotz, Everybot, Kitbot, the REV and WCP 2026 robots, and more, each ready to simulate.</td><td><a href="https://github.com/Yet-Another-Software-Suite/YAMS/releases/latest">https://github.com/Yet-Another-Software-Suite/YAMS/releases/latest</a></td><td><a href="https://1716920675-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7CGD7e6lKU4QRNJBaUs1%2Fuploads%2Fgit-blob-087258e19ae6f7a4017d45cf3348e961d16a8fc7%2Fexamples.png?alt=media">examples.png</a></td></tr></tbody></table>

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><i class="fa-book">:book:</i></td><td><strong>Documentation</strong></td><td>Step-by-step tutorials for arms, elevators, flywheels, and swerve, from simulation and  live tuning, to running on the robot.</td><td><a href="https://yams.yassrobotics.com/documentation/">Documentation</a></td></tr><tr><td><i class="fa-code">:code:</i></td><td><strong>API reference</strong></td><td>Every class and every config option, what it does, and how to use it.</td><td><a href="https://yams.yassrobotics.com/api-reference/">API Reference</a></td></tr></tbody></table>

{% columns %}
{% column %}

### Getting started

1. **Create a project and install YAMS.** It is one vendordep in a standard WPILib 2027 project.
2. **Describe your mechanism.** Configure the motor controller, then the mechanism, inside a subsystem, as in the code here. [How YAMS drives a motor](https://yams.yassrobotics.com/documentation/tutorials/how-yams-drives-a-motor) explains how those pieces fit together, the [Arm tutorial](https://yams.yassrobotics.com/documentation/tutorials/arm) walks you through them, or [YAMG](https://yamg.yassrobotics.com) writes them for you from a form.
3. **Run it in simulation.** Every mechanism simulates itself. Drive it, tune it, and graph it in AdvantageScope before the robot is built.
4. **Run it on the robot.** Set the CAN IDs, check the motor direction with the robot disabled, and rest the mechanism at its starting position. Then enable it and tune it on the real mechanism, as in [Run it on the robot](https://yams.yassrobotics.com/documentation/tutorials/arm/robot). If it misbehaves, [Troubleshooting](https://yams.yassrobotics.com/documentation/tutorials/troubleshooting) covers the common failures.

<a href="https://yams.yassrobotics.com/documentation/tutorials/project-setup" class="button primary" data-icon="rocket-launch">Get started</a> <a href="https://yamg.yassrobotics.com" class="button secondary" data-icon="wand-magic-sparkles">Open YAMG</a> <a href="https://github.com/Yet-Another-Software-Suite/YAMS/releases/latest" class="button secondary" data-icon="download">Download examples</a>
{% endcolumn %}

{% column %}
{% code title="An arm, from motor to command (Java, Commands v2)" %}

```java
// This goes inside your arm subsystem's constructor: `this` is the subsystem.

// 1. Configure the motor controller: control, gains, gearing and limits.
SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0) // Example gain, tune it for your arm.
    .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
    .withFeedforward(new ArmFeedforward(0, 0, 0, 0)) // Placeholder gains, until you tune them.
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withSoftLimits(Degrees.of(-30), Degrees.of(100))
    .withStatorCurrentLimit(Amps.of(40))
    .withZeroPower(MotorMode.BRAKE)
    .withStartingPosition(Degrees.of(0))
    .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);

// 2. Create the motor controller.
TalonFX armMotor = new TalonFX(1, new CANBus(CANPort.CAN_S0));
SmartMotorController motor = new TalonFXWrapper(armMotor, DCMotor.getKrakenX60(1), motorConfig);

// 3. Configure the arm.
ArmConfig armConfig = new ArmConfig()
    .withLength(Meters.of(0.135))
    .withHardLimits(Degrees.of(-100), Degrees.of(200))
    .withTelemetry("Arm", TelemetryVerbosity.HIGH);

// 4. Create the arm, and use its commands.
Arm arm = new Arm(armConfig, motor);
Command raise = arm.setAngle(Degrees.of(90));
```

{% endcode %}

For the whole subsystem with its imports, see [the complete arm file](https://yams.yassrobotics.com/documentation/tutorials/arm/mechanism#the-complete-file) in the Arm tutorial.
{% endcolumn %}
{% endcolumns %}

{% columns %}
{% column %}

### Built from years of FRC experience

The best FRC teams have spent years building their own mechanism code: motion profiles that plan for what a motor can really do, simulations that include the battery drain under load, gains they can tune while the robot runs, absolute encoders that know where a turret is the moment the robot turns on. That code usually stays on one team's robot, while every other team tries to reinvent the robotic wheel every year.&#x20;

YAMS brings those ideas together in one open-source library. Now any team can use these features from its very first mechanism. Built by Yet Another Software Suite, the team behind YAGSL, whose main developers have been doing FRC for over 10 years.&#x20;

<a href="/documentation/why-yams" class="button primary" data-icon="rocket">Why YAMS?</a> <a href="https://github.com/Yet-Another-Software-Suite/YAMS" class="button secondary" data-icon="github">Source on GitHub</a>
{% endcolumn %}

{% column %}

<figure><img src="https://1716920675-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7CGD7e6lKU4QRNJBaUs1%2Fuploads%2Fgit-blob-5676fc440147bf970eeca17663417c43d4f9a903%2Fbattery-sim-mechanisms.png?alt=media" alt="How much current an arm, an elevator, a flywheel, a turret and a swerve drive draw over time, and the battery sag when their peaks line up"><figcaption><p>YAMS simulates the drain across every mechanism at once, so you catch brownouts in sim instead of on the field. </p></figcaption></figure>
{% endcolumn %}
{% endcolumns %}

{% columns %}
{% column %}

<figure><img src="https://1716920675-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7CGD7e6lKU4QRNJBaUs1%2Fuploads%2Fgit-blob-cd805259e0788a8a85c06cc806a53802c26af5ab%2Fexponential-profile-compare.png?alt=media" alt="A trapezoidal and an exponential profile for the same move: the exponential one plans for the motor having less torque as it speeds up"><figcaption><p>Exponential profiles plan for a motor losing torque as it speeds up.</p></figcaption></figure>
{% endcolumn %}

{% column %}

### Everything a mechanism needs, built in

* **Simulation** of every mechanism with no extra code, including a [battery simulation](https://yams.yassrobotics.com/documentation/how-to-simulation-and-logging/how-do-i-enable-battery-discharge-simulation) of the whole robot.
* [**Live tuning**](https://yams.yassrobotics.com/documentation/how-to-tuning/live-tuning) of the gains, the profile, and the limits from a dashboard, applied while the robot runs.
* [**Telemetry**](https://yams.yassrobotics.com/documentation/understanding/telemetry) of the motor and the mechanism, at the verbosity you choose.
* **Control** beyond PID: trapezoidal and [exponential profiles](https://yams.yassrobotics.com/documentation/how-to-motor-controllers-and-sensors/how-do-i-use-exponential-profiles), and [LQR](https://yams.yassrobotics.com/documentation/details/editor/lqr-controllers).
* [**Absolute encoders**](https://yams.yassrobotics.com/documentation/how-to-mechanisms/how-do-i-use-absolute-encoders-on-my-arm) that know where the mechanism is from power up, plus [EasyCRT](https://yams.yassrobotics.com/documentation/details/easycrt) to find a turret's angle from two of them.
* **Sensors** that simulate themselves: wrap a limit switch, a beam break, or any other [sensor](https://yams.yassrobotics.com/documentation/details/sensors), and the simulation triggers it just like the real one, such as a [homing switch](https://yams.yassrobotics.com/documentation/how-to-mechanisms/how-do-i-home-a-mechanism-with-limit-switches) that presses when the mechanism reaches its hard stop.
* **Every common mechanism**: arms, elevators, pivots, turrets, flywheels, double-jointed arms, differential mechanisms, and swerve drives.
* **Your hardware**: TalonFX, TalonFXS, SPARK MAX, SPARK Flex, and Thrifty Nova are all supported in Java and C++, using WPILib Commands v2 or v3.
  {% endcolumn %}
  {% endcolumns %}

<h2 align="center"><mark style="color:$primary;">Join a community of over 500 teams</mark></h2>

<p align="center">Stuck on a config, found a bug, or just wanna talk about robots? Here's where to find us. </p>

{% columns %}
{% column %}

### YASS Discord&#x20;

The Discord is the fastest way to reach us! Ask questions, report bugs, or just say hi with over 1,000 FRC enthusiasts.&#x20;

<a href="https://discord.gg/yass" class="button primary" data-icon="discord">Join Discord</a>
{% endcolumn %}

{% column %}

### Instagram

Quick updates, announcements,  Team YASS shoutouts, and Rivet trivia.

<a href="https://instagram.com/yassrobotics" class="button primary" data-icon="instagram">Follow on Instagram</a>
{% endcolumn %}

{% column %}

### GitHub

File issues, open pull requests, or browse the source for any of our projects.&#x20;

<a href="https://github.com/Yet-Another-Software-Suite/YAMS/issues" class="button primary" data-icon="github">Report an issue</a> <a href="https://github.com/Yet-Another-Software-Suite/YAMS/pulls" class="button secondary" data-icon="code-pull-request">Pull requests</a>
{% endcolumn %}
{% endcolumns %}


# Welcome

Welcome to the Yet Another Mechanism System (YAMS) documentation.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FvgmqC89Zxh6rR44L755F%2FYAMS.png?alt=media&amp;token=88e9bba1-74d6-41fa-81dc-646154d61cc3" alt="The YAMS logo"><figcaption></figcaption></figure>

YAMS fuses simulation and real control as closely as possible to real life. You can debug and program your robot without the actual robot. You can also program your robot before it is built.

YAMS targets WPILib 2027 (`2027_alpha7`) and the SystemCore. Upgrading a 2026 project? See [Upgrading from 2026 to 2027](/documentation/upgrading/upgrading-from-2026-to-2027).

### Start here

These docs are written for FRC student programmers. You should know some Java (or C++) and have used a WPILib [command-based](https://docs.wpilib.org/en/stable/docs/software/commandbased/index.html) project. You don't need to know PID or feedforward yet: the tutorials teach what you need as you go.

{% hint style="success" %}
**New to YAMS?** Start with [Create a project and install YAMS](/documentation/tutorials/project-setup), then follow the [Arm](/documentation/tutorials/arm) tutorial from start to finish.
{% endhint %}

The arm tutorial takes you the whole way:

1. [Create a project and install YAMS](/documentation/tutorials/project-setup)
2. [Configure the motor controller](/documentation/tutorials/arm/motor-controller), [describe the arm](/documentation/tutorials/arm/mechanism) and [bind it to buttons](/documentation/tutorials/arm/commands)
3. [Run it in simulation](/documentation/tutorials/arm/simulate)
4. [Tune it](/documentation/tutorials/arm/tune)
5. [Run it on the robot](/documentation/tutorials/arm/robot)

Stuck? See [Troubleshooting](/documentation/tutorials/troubleshooting).

### Installation

YAMS ships as two vendordeps, one per WPILib command framework. Install **only one** of them; they conflict with each other.

| Command framework                                 | Vendordep                                  | Online URL                                         |
| ------------------------------------------------- | ------------------------------------------ | -------------------------------------------------- |
| Commands v2 (`org.wpilib.command2`, Java and C++) | Yet Another Mechanism System (Commands v2) | `https://cdn.yassrobotics.com/yams_commands2.json` |
| Commands v3 (`org.wpilib.command3`, Java only)    | Yet Another Mechanism System (Commands v3) | `https://cdn.yassrobotics.com/yams_commands3.json` |

If you are not sure which one you need, use Commands v2. The [tutorials](/documentation/tutorials/project-setup) have a tab for Java with Commands v2, Java with Commands v3, and C++.

{% tabs %}
{% tab title="Online" %}

1. In VS Code, open the command palette with <kbd>Ctrl+Shift+P</kbd> (<kbd>Cmd+Shift+P</kbd> on macOS).
2. Run **WPILib: Manage Vendor Libraries**, then **Install new libraries (online)**.
3. Paste the vendordep URL for your command framework from the table above and press Enter.
4. Install your motor controller's vendor library too, such as REVLib or Phoenix 6. YAMS drives the vendor's own motor controller objects, so it needs their library.
   {% endtab %}

{% tab title="Offline" %}

1. Install WPILib 2027 (`2027_alpha7`) first, which creates the `2027_alpha7` WPILib home folder.
2. Download `<version>-YAMS-Offline.zip` from the [YAMS GitHub releases](https://github.com/Yet-Another-Software-Suite/YAMS/releases).
3. Extract it into the WPILib home folder, so its `maven` and `vendordeps` folders merge with the existing ones:
   * **Windows:** `C:\Users\Public\wpilib\2027_alpha7`
   * **macOS and Linux:** `~/wpilib/2027_alpha7`
4. In VS Code, run **WPILib: Manage Vendor Libraries**, then **Install new libraries (offline)**, and pick **Yet Another Mechanism System (Commands v2)** or **Yet Another Mechanism System (Commands v3)**.
   {% endtab %}
   {% endtabs %}

YAMS maven artifacts are served from `https://cdn.yassrobotics.com/`.

### Get started with YAMG

The quickest way to get started is [YAMG](https://yamg.yassrobotics.com/), the Yet Another Mechanisms Generator. Fill in a form about your mechanism and it writes the code for you, ready to copy into your project.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-e10a605368e8bf8e78df5290d05e7fffe4d9c3c4%2Fyamg.png?alt=media" alt="The YAMG website, in the YASS style, generating an arm. On the left, the form: subsystem name ArmSubsystem, mechanism type Arm, Use YAMS turned on, Commands v2, and the motor configuration with a SparkMAX and a NEO. On the right, the generated ArmSubsystem.java with its SparkMax and SmartMotorControllerConfig, in tabs next to Robot.java and RobotContainer.java, with Copy, Save File, Copy Link and Download All buttons. A WPILib 2026 and WPILib 2027 toggle is at the top right."><figcaption><p>YAMG generating an arm with YAMS.</p></figcaption></figure>

1. Pick your WPILib version with the toggle at the top right: 2027, or 2026 for a 2026 project.
2. Turn on **Use YAMS**. Without it, YAMG writes code that uses only WPILib and the motor controller's vendor library.
3. Name your subsystem and pick the mechanism type: an elevator, an arm, a pivot or a flywheel.
4. Pick the command framework that matches the vendordep you installed: Commands v2 or Commands v3.
5. Fill in your motor controller, motor, gearing, limits and gains.
6. Copy each generated file into your project, or press **Download All**. Along with the mechanism, YAMG writes `Robot.java` and, for Commands v2, `RobotContainer.java` with controller bindings, or, for Commands v3, a teleop op mode.

**Copy Link** puts the whole form into a link, so you can share the mechanism with your team or come back to it later.

The tutorials below build the same mechanisms step by step and explain each part.

### Jump right in

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden></th></tr></thead><tbody><tr><td><h4><i class="fa-bolt">:bolt:</i></h4></td><td><strong>Create an Arm</strong></td><td>Create your first Arm.</td><td><a href="/documentation/tutorials/arm">Arm</a></td><td></td><td></td></tr><tr><td><h4><i class="fa-leaf">:leaf:</i></h4></td><td><strong>Create an Elevator</strong></td><td>Create your first elevator.</td><td><a href="/documentation/tutorials/elevator">Elevator</a></td><td></td><td></td></tr><tr><td><i class="fa-crosshairs">:crosshairs:</i></td><td><strong>Create a shooter</strong></td><td>Create your first shooter.</td><td><a href="/documentation/tutorials/shooter-flywheels">Shooter/FlyWheels</a></td><td></td><td></td></tr></tbody></table>


# Why YAMS?

## The problem with creating a subsystem from scratch

Teams routinely spend days getting a single mechanism working in simulation, only to discover the real robot behaves differently because the sim wasn't accurate enough to tune against. YAMS eliminates that cycle.

Writing a motor subsystem from scratch is repetitive and error-prone. A production-quality subsystem requires:

* Motor controller configuration (PID, feedforward, gearing, current limits, zero power mode, ramp rates…)
* A physics simulation that actually matches your hardware
* Periodic telemetry publishing so you can see what's happening
* A `Mechanism2d` drawing of the mechanism, to watch it move in AdvantageScope
* Command factories that respect WPILib's requirement system
* Soft limits and hard limits
* Separate sim-only tuning paths
* Simulation of the motor controllers and sensors, so the same code runs in simulation and on the robot

## What YAMS replaces

A typical Arm subsystem created from scratch is 150-300 lines of code: config, sim state, periodic updates, command factories, limit enforcement, and telemetry. The YAMS equivalent is about 20 lines: one `SmartMotorControllerConfig`, one `SmartMotorController`, one `ArmConfig`, and one `Arm`, whose commands you use directly.

{% code title="Inside an arm subsystem's constructor (Java, Commands v2)" %}

```java
// `this` is the arm subsystem.
SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0) // Example gain, tune it for your arm.
    .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
    .withFeedforward(new ArmFeedforward(0, 0, 0, 0)) // Placeholder gains, until you tune them.
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withZeroPower(MotorMode.BRAKE)
    .withStatorCurrentLimit(Amps.of(40))
    .withStartingPosition(Degrees.of(0))
    .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);

SmartMotorController smc = new SparkWrapper(new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless), DCMotor.getNEO(1), motorConfig);

ArmConfig armConfig = new ArmConfig()
    .withLength(Feet.of(2))
    .withHardLimits(Degrees.of(-10), Degrees.of(120));

Arm arm = new Arm(armConfig, smc);
Command raise = arm.setAngle(Degrees.of(90));
```

{% endcode %}

Add two calls to the subsystem, `arm.updateTelemetry()` in `periodic()` and `arm.simIterate()` in `simulationPeriodic()`, and that's it. Simulation, telemetry, hard limits, and a physics-backed `Mechanism2d`, all in one library. The [Arm tutorial](/documentation/tutorials/arm) builds this subsystem step by step, with the complete file.

## Built-in physics simulation

Every YAMS mechanism type ships with a physics model:

* **Arm:** WPILib's `SingleJointedArmSim`, with gravity included.
* **Pivot:** a `DCMotorSim` built from the pivot's moment of inertia.
* **Elevator:** `ElevatorSim`, with the carriage weight (`withCarriageWeight`) and the elevator's angle (`withAngle`).
* **FlyWheel:** a `DCMotorSim` built from the flywheel's moment of inertia.

YAMS creates the model for you when the code runs in simulation. Your code only calls `simIterate()` every loop in simulation. In Commands v2 that is the subsystem's `simulationPeriodic()`. In Commands v3, `Robot.java` starts it, as [Update it every loop](/documentation/tutorials/arm/mechanism#update-it-every-loop) shows.

Because the simulation uses accurate physics, the PID and feedforward gains you tune in sim are a reliable starting point for real hardware. You may still need minor adjustments, but you won't be starting from zero on the field.

## TunerX in simulation (CTRE hardware)

For CTRE TalonFX and TalonFXS motors, YAMS feeds its physics results back into Phoenix's simulation, so Phoenix Tuner X can connect to your simulated robot. Every TalonFX signal (position, velocity, voltage and current) reads exactly as it would from real hardware.

You can watch closed-loop error, plot signal graphs, and verify your gains in TunerX's familiar interface without touching a physical robot. The same workflow you use to diagnose real hardware works identically in simulation. [TunerX in simulation](/documentation/how-to-tuning/live-tuning/tunerx-in-simulation) shows how to connect.

## Live tuning without redeploying

`TelemetryVerbosity.HIGH` publishes all PID gains, feedforward constants, motion profile constraints, soft limits, and current limits as values you can change from a dashboard. At `HIGH` verbosity YAMS also registers a `Live Tuning` command for each motor (call `setupLiveTuning()` on the config to register it in other cases). While that command runs, from Elastic or any other NetworkTables dashboard, YAMS applies the values you change to the running motor controller.

Changing `kP` from 4 to 6 and seeing the mechanism respond takes seconds, not the minutes a redeploy would cost. [Live tuning](/documentation/how-to-tuning/live-tuning) shows how to tune a mechanism this way, and [Live tuning keys and units](/documentation/reference/keys-and-units) lists every value you can change.

## Loop overruns

Heavy subsystems whose telemetry, simulation, and visualization code is created from scratch can push the 20 ms robot loop toward or past its budget, especially when multiple mechanisms run simultaneously. YAMS's telemetry and simulation paths are tightly optimized and only run the work that the verbosity level requires; `LOW` publishes only the fields you actually need for competition, keeping loop time predictable.

The SystemCore, which YAMS 2027 runs on, has plenty of processing headroom, so running `TelemetryVerbosity.HIGH` with multiple mechanisms active is not a practical loop time concern.

## Safety by default

YAMS enforces mechanism safety automatically:

* **Hard limits** are enforced in simulation as physical stops: the mechanism cannot travel past them.
* **Soft limits** are pushed to the motor controller, so the closed-loop controller respects them independent of your command logic.
* **Misconfigured limits** throw an exception when the code starts (for example, a lower limit greater than the upper limit), so the mistake shows up in testing rather than during a match.

You can also set a **temperature cutoff** with `withTemperatureCutoff`, which stops the motor if it overheats.

## AdvantageKit integration

YAMS mechanisms fit behind AdvantageKit's IO layer, so you keep YAMS's simulation and live tuning and get AdvantageKit's log replay. The [AdvantageKit](/documentation/tutorials/advantagekit-integration) tutorial walks you through it.


# Create a project and install YAMS

Make the robot project that every tutorial starts from.

Every tutorial starts from the same place: a WPILib command-based project with YAMS installed. This page makes one.

Each tutorial page has a tab for **Java with Commands v2**, **Java with Commands v3** and **C++**. Pick the one you want now, because it decides which project template and which YAMS vendordep you need.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-71a0a8635fee31e5995ac683850107265a850ef4%2Ftutorial-flavors.png?alt=media" alt="A table comparing the three ways to follow the tutorials. Java with Commands v2 uses the Command v2 Robot template and the YAMS Commands v2 vendordep; the mechanism lives in a subsystem class that extends SubsystemBase, buttons are bound in RobotContainer.java, and the scheduler calls periodic. Java with Commands v3 uses the Command v3 Robot template and the YAMS Commands v3 vendordep; the mechanism lives in a class that implements Mechanism, buttons are bound in ExampleTeleop.java, and you call periodic yourself from Robot.robotPeriodic. C++ uses the Command v2 Robot template for C++ and the YAMS Commands v2 vendordep; the mechanism lives in a subsystem header and source file, buttons are bound in RobotContainer.cpp, and the scheduler calls periodic."><figcaption><p>The YAMS calls are the same. The project around them is what changes.</p></figcaption></figure>

{% hint style="success" %}
Not sure which to pick? Use **Java, Commands v2**. It is what most teams use today, and most of the other pages in these docs show it first.
{% endhint %}

## Create the project

Bring up the Visual Studio Code command palette with <kbd>Ctrl+Shift+P</kbd> and type "WPILib". Select **WPILib: Create a new project**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fv8EXUEReWVEt3PaxTETf%2Fimage.png?alt=media&amp;token=3499f3d8-f076-4da0-9f96-234a5e0d684c" alt=""><figcaption></figcaption></figure>

This brings up the New Project Creator:

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FOZxXhcwt1pKd9pSXMCrx%2Fimage.png?alt=media&amp;token=50e2e75a-f9c7-4c68-9762-b2aa48e996cf" alt=""><figcaption></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}

1. Click on **Select a project type (Example or Template)**.
2. Select **Template**, then **Java**, then **Command v2 Robot**.
   {% endtab %}

{% tab title="Java, Commands v3" %}

1. Click on **Select a project type (Example or Template)**.
2. Select **Template**, then **Java**, then **Command v3 Robot**.
   {% endtab %}

{% tab title="C++" %}

1. Click on **Select a project type (Example or Template)**.
2. Select **Template**, then **C++**, then **Command v2 Robot**.
   {% endtab %}
   {% endtabs %}

Then, whichever you picked:

3. Click on **Select a new project folder** and choose where to keep the project.
4. Fill in **Project Name**.
5. Enter your **Team Number**, so that you can deploy to your robot.
6. Check **Enable Desktop Support**, so that you can run the simulation.

Filled in, it looks something like this. The screenshots on this page show the Java Commands v2 choice.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fmir5YcWV8yINfcSfsgwU%2Fimage.png?alt=media&amp;token=c9040032-eb3d-467c-8645-0fc71785902e" alt=""><figcaption></figcaption></figure>

You now have a command-based robot project.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FmAW2IQ3CSKzETRk8LZXV%2Fimage.png?alt=media&amp;token=6e886daa-4fa9-4138-b128-544eba95b870" alt=""><figcaption></figcaption></figure>

## Install YAMS

YAMS ships as two vendordeps, one for each WPILib command framework. Install only the one for your tab: the two conflict with each other.

Click on the **WPILib logo** in the left bar to open the vendor library list.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FBCk58wEvzhW9tFJ2NzlS%2FRobotContainer.java%20-%20simple_robot%20-%20Visual%20Studio%20Code%209_2_2025%203_40_21%20PM.png?alt=media&amp;token=b5423a72-14b6-43e1-8470-984e529d252b" alt=""><figcaption></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
Scroll down to **Yet Another Mechanism System (Commands v2)** and click **Install**.

If it is not in the list, open the command palette with <kbd>Ctrl+Shift+P</kbd>, run **WPILib: Manage Vendor Libraries**, choose **Install new libraries (online)** and paste `https://cdn.yassrobotics.com/yams_commands2.json`.
{% endtab %}

{% tab title="Java, Commands v3" %}
Scroll down to **Yet Another Mechanism System (Commands v3)** and click **Install**.

If it is not in the list, open the command palette with <kbd>Ctrl+Shift+P</kbd>, run **WPILib: Manage Vendor Libraries**, choose **Install new libraries (online)** and paste `https://cdn.yassrobotics.com/yams_commands3.json`.
{% endtab %}

{% tab title="C++" %}
Scroll down to **Yet Another Mechanism System (Commands v2)** and click **Install**. The Commands v2 vendordep holds both the Java and the C++ library.

If it is not in the list, open the command palette with <kbd>Ctrl+Shift+P</kbd>, run **WPILib: Manage Vendor Libraries**, choose **Install new libraries (online)** and paste `https://cdn.yassrobotics.com/yams_commands2.json`.
{% endtab %}
{% endtabs %}

See [Installation](/documentation#installation) for the offline install.

## Install your motor controller's library

YAMS drives the vendor's own motor controller objects, so the vendor's library has to be installed too. Install it from the same list:

| Tutorial                                                                                                                                            | Hardware                          | Vendor library       |
| --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | -------------------- |
| [Arm](/documentation/tutorials/arm), [Elevator](/documentation/tutorials/elevator), [Shooter/FlyWheels](/documentation/tutorials/shooter-flywheels) | `SparkMax`                        | REVLib               |
| [Double FlyWheel](/documentation/tutorials/double-flywheel)                                                                                         | `TalonFX`                         | Phoenix 6            |
| [Swerve Drive](/documentation/tutorials/swerve-drive)                                                                                               | `SparkMax`, `CANcoder`, `Pigeon2` | REVLib and Phoenix 6 |

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Ff0DnFCCZ192W3hJNnvr7%2Fimage.png?alt=media&amp;token=9718fda8-a87d-4e18-ac1d-39ce2b55fda2" alt=""><figcaption></figcaption></figure>

## Where the tutorials put things

{% tabs %}
{% tab title="Java, Commands v2" %}
The template gives you `RobotContainer.java` and a `subsystems` folder. Each tutorial adds one subsystem class to `subsystems`, and then creates it and binds its buttons in `RobotContainer.java`.

A subsystem `extends SubsystemBase`, so the command scheduler calls its `periodic()` and `simulationPeriodic()` for you.
{% endtab %}

{% tab title="Java, Commands v3" %}
The template gives you `Robot.java`, `ExampleTeleop.java` and a `mechanisms` folder. Each tutorial adds one mechanism class to `mechanisms`, creates it in `Robot.java`, and binds its buttons in `ExampleTeleop.java`.

A Commands v3 mechanism `implements Mechanism`. Nothing calls a periodic method on it for you, so each tutorial gives the class a `periodic()` and a `simulationPeriodic()`, and `Robot.java` calls them:

* `Robot.robotPeriodic()` runs every loop, on the robot and in simulation. It calls each mechanism's `periodic()`, runs the scheduler, and then publishes the scheduler so that a dashboard shows which commands are running.
* `Robot.simulationInit()` runs once, when the simulation starts. It starts each mechanism's `simulationPeriodic()` in its own `Notifier`, which runs it every loop, in simulation only.

With an arm and an elevator on the robot, `Robot.java` ends up with this:

```java
private final Scheduler scheduler = Scheduler.getDefault();
// Each mechanism's simulation Notifier, kept so that it is not garbage collected.
private final List<Notifier> simulationNotifiers = new ArrayList<>();

@Override
public void robotPeriodic() {
  arm.periodic();
  elevator.periodic();
  scheduler.run();
  Telemetry.log("Scheduler", scheduler, Scheduler.proto);
}

@Override
public void simulationInit() {
  // Runs once, when the simulation starts.
  // Run each mechanism's simulation in its own Notifier, every robot loop.
  startSimulation("Arm", arm::simulationPeriodic);
  startSimulation("Elevator", elevator::simulationPeriodic);
}

/** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
private void startSimulation(String name, Runnable simulationPeriodic) {
  Notifier notifier = new Notifier(simulationPeriodic);
  notifier.setName(name + " Simulation");
  notifier.startPeriodic(getPeriod());
  simulationNotifiers.add(notifier);
}
```

Forget the first and the mechanism publishes no telemetry and ignores live tuning. Forget the second and it never moves in simulation.

{% hint style="success" %}
Run each mechanism's simulation in its own `Notifier`, as above, instead of calling it from `Robot.simulationPeriodic()`. The simulation then runs on its own thread, so it does not add to the time each robot loop takes, and every mechanism keeps stepping at a steady rate even when a loop runs long.

This needs a YAMS release newer than 2026.10.19, which makes the shared battery simulation safe to use from several threads. With an older release, call each mechanism's `simulationPeriodic()` from `Robot.simulationPeriodic()` instead.

With AdvantageKit, keep calling it from `Robot.simulationPeriodic()`, so that the simulation stays in step with the log.
{% endhint %}

YAMS for Commands v3 lives in `yams.commands3` where the Commands v2 pages say `yams.commands2`. Everything in `yams.core` is shared.
{% endtab %}

{% tab title="C++" %}
The template gives you `RobotContainer.hpp`, `RobotContainer.cpp`, and a `subsystems` folder under both `src/main/include` and `src/main/cpp`. Each tutorial adds one subsystem as a header and a source file, and then creates it and binds its buttons in `RobotContainer`.

The C++ library uses Commands v2. Its methods have the same names as the Java ones with a capital first letter, such as `WithGearing` or `Run`. Where a name is different, the tutorial says so.
{% endtab %}
{% endtabs %}

## Pick a tutorial

* [Arm](/documentation/tutorials/arm)
* [Elevator](/documentation/tutorials/elevator)
* [Shooter/FlyWheels](/documentation/tutorials/shooter-flywheels)
* [Double FlyWheel](/documentation/tutorials/double-flywheel)
* [Swerve Drive](/documentation/tutorials/swerve-drive)


# How YAMS drives a motor

This page explains the ideas every other page assumes that you already know. Read it once before the tutorials, and come back when a word on another page is new.

* Three layers of YAMS code
* Definitions for:
  * A rotor according to YAMS
  * Mechanism
  * Measurement
* Open and closed loops
* Units for gains

## Three layers

Every YAMS mechanism is built from the same three layers, from the motor up.

1. **The motor controller.** The vendor's object, such as a `SparkMax` or a `TalonFX`, talks to the hardware. YAMS wraps it in a `SmartMotorController` (a `SparkWrapper`, `TalonFXWrapper`, `TalonFXSWrapper`, `NovaWrapper` or `A301Wrapper`), and you describe how the motor should behave in a `SmartMotorControllerConfig`: gearing, gains, limits and encoders. The config is written the same way for every vendor.
2. **The mechanism.** An `Arm`, `Elevator`, `Pivot` or `FlyWheel` takes the `SmartMotorController` and a mechanism config (`ArmConfig`, `ElevatorConfig` and so on) that says what the mechanism is: its length, mass and hard stops. It gives you commands such as `arm.run(Degrees.of(45))`, simulates the physics and draws the mechanism on the dashboard.
3. **The subsystem.** In Commands v2 a `SubsystemBase` holds the mechanism and hands its commands to the rest of the robot. In Commands v3 a class that `implements Mechanism` does the same job. Keep at most one YAMS mechanism in each, so live tuning can find it.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-9ac4402ed53c7caf15787f40f7a6245c3ef8a7c2%2Fmech-two-configs.png?alt=media" alt="A diagram. A mechanism config, which says what the mechanism is, such as its length, mass, hard stops and how it is drawn, and a SmartMotorControllerConfig, which says how its motor behaves, such as gearing, PID, feedforward, soft limits and current, both go into the mechanism class. The mechanism then drives the simulation&#x27;s physics and Mechanism2d, and the real robot&#x27;s commands and telemetry."><figcaption><p>Two configs go into one mechanism.</p></figcaption></figure>

You can skip layer 2 and command a `SmartMotorController` yourself: see [How do I control a mechanism without a mechanism class?](/documentation/how-to-mechanisms/how-do-i-control-a-mechanism-without-a-mechanism-class)

## Rotor, mechanism and measurement

YAMS measures a motor's movement in three places. These words mean the same thing on every page.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FAMxbim1J0b5WuJ94m9ja%2Fimage.png?alt=media&amp;token=43ab64dc-75d5-4537-a62b-9fb48fed9a57" alt="An exploded NEO motor, gearbox stages, output shaft and wheel. The rotor is the NEO&#x27;s own shaft, the mechanism is the output shaft after the gearbox, and the measurement is the wheel&#x27;s rim. Rotor and mechanism are angles and angular velocities; the measurement is a distance and a linear velocity."><figcaption><p>Rotor, mechanism and measurement.</p></figcaption></figure>

* **Rotor** is the motor's own shaft, before any gearing.
* **Mechanism** is the output after the gearing: an arm's pivot, an elevator's drum, a flywheel's axle. YAMS reports positions as mechanism angles, such as `Degrees.of(90)` for an arm.
* **Measurement** is the distance the mechanism moves in a line, such as an elevator's height in meters. It needs the [mechanism circumference](/documentation/reference/editor/config/gearing-and-units#withmechanismcircumference): one mechanism rotation moves one circumference.

[`withGearing`](/documentation/reference/editor/config/gearing-and-units#withgearing) tells YAMS how many rotor rotations make one mechanism rotation, so you only ever think in mechanism units.

{% hint style="info" %}

#### Engineering Note

A rotor is the rotating part of an electric motor. It sits inside the stator, and turns when it inteacts with the magnetic field produced by the stator.\
\
The rotor is connected to the **motor shaft**. A motor shaft is a solid steel rod running through the center of the rotor. The shaft then transfers the mechanical motion to the load.\
\
in the above documentation, the shaft is incorrectly called a rotor...
{% endhint %}

> <sub>"I'm not changing the entire API because I called a shaft, a rotor and you don't like it!" \~nstrike</sub>

## Open loop and closed loop

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-a48a31fa0da188e6c1bb4094d31caac6d12de543%2Fsmc-control-mode.png?alt=media" alt="Two panels. In OPEN_LOOP your code sends volts or duty cycle straight to the motor and no PID, feedforward or profile runs. In CLOSED_LOOP, the default, your code sends a setpoint to the PID, feedforward and profile, which drive the motor using the encoder position and velocity."><figcaption><p>Open loop sends an output straight to the motor. Closed loop drives to a setpoint.</p></figcaption></figure>

* **Open loop** sends a voltage or a duty cycle (a fraction of full output, from -1 to 1) straight to the motor. Nothing checks where the mechanism ends up. Commands such as `arm.set(0.2)` and `arm.setVoltage(Volts.of(2))` are open loop.
* **Closed loop** takes a **setpoint**, the position or speed you want, and keeps adjusting the voltage until the encoder says the mechanism is there. It adds three parts: a **feedforward** that predicts the voltage the move needs, a **PID** controller that corrects the error left over, and an optional **motion profile** that slides the setpoint there smoothly. `arm.run(Degrees.of(45))` is closed loop.

[`withControlMode`](/documentation/reference/editor/config/motor-basics#withcontrolmode) chooses between them. `ControlMode.CLOSED_LOOP` is the default, and it still lets you send voltages.

## Where the loop runs

The closed loop runs either on the motor controller itself, every millisecond, or on the SystemCore, every 20 ms by default. Which one depends on the motor controller and the options you pick: a TalonFX or Thrifty Nova runs PID and trapezoidal profiles itself, while an LQR runs on the SystemCore on every motor controller, and an A301, which has no closed loop of its own, runs everything on the SystemCore. You do not call anything either way. It matters for a few options, and for tuning: gains found with the loop in one place do not carry over to the other. [Where the loop runs](/documentation/reference/editor/config/closed-loop-control#where-the-loop-runs) has the full table of options.

## Units of your gains

Write every gain in mechanism units: **volts per mechanism rotation**, or **volts per meter** for an elevator or another mechanism that moves in a line. A `kP` of 4 on an arm means 4 V of output for each full rotation of error, which is about 0.1 V for each 10° off. A feedforward `kV` of 2 means 2 V for each rotation per second.

YAMS converts your gains to whatever each motor controller wants, so the same numbers behave the same on a SPARK, a Talon, a Nova or an A301. You never multiply by the gear ratio yourself.

## Next

Build one: start with the [Arm tutorial](/documentation/tutorials/arm). Look up an option: [SmartMotorControllerConfig](/documentation/reference/editor/config).


# Arm

Learn how to program an Arm.

## Intro

At the end of this tutorial you will have an `Arm` that works in both real life and simulation with the same code!

{% columns %}
{% column %}

#### Simulation

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2F4V5u1RtPYNGAVRzfbmnx%2Farm.gif?alt=media&amp;token=93c0ddc6-d5bf-4a53-9c27-44850db5ce76" alt=""><figcaption></figcaption></figure>
{% endcolumn %}

{% column %}

#### Real Life

{% embed url="<https://www.youtube.com/shorts/sKhi0ieo6WE>" %}
{% endcolumn %}
{% endcolumns %}

## Details

This `Arm` uses the following hardware and controls:

* A `SparkMax` driving one NEO controls the `Arm`
* A `12:1` gearbox on the `Arm`
* Holding the bottom face button (`A` on an Xbox controller) takes the `Arm` to -5 degrees
* Holding the right face button (`B` on an Xbox controller) takes the `Arm` to 15 degrees
* Holding the left face button (`X` on an Xbox controller) drives the `Arm` up
* Holding the top face button (`Y` on an Xbox controller) drives the `Arm` down
* With no button held, the `Arm` goes to 0 degrees

## The steps

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-c9f4c9cb2dc61c7f6c67d206f84e472a5b229950%2Ftutorial-arm-steps.png?alt=media" alt="The four steps of the arm tutorial, each building on the one before. Step 1, the motor controller: a SparkMax and a SmartMotorControllerConfig. Step 2, the arm: an ArmConfig and the SmartMotorController. Step 3, commands and buttons: run and set commands bound to a controller. Step 4, simulation: the same code run on your computer."><figcaption><p>Four steps, one page each.</p></figcaption></figure>

Every step has a tab for **Java with Commands v2**, **Java with Commands v3** and **C++**.

| Step                                                                          | What you do                                                                                   |
| ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| [Before you start](/documentation/tutorials/project-setup)                    | Create a WPILib project and install YAMS and REVLib. Skip this if you already have a project. |
| [Step 1: The motor controller](/documentation/tutorials/arm/motor-controller) | Configure the `SparkMax` and wrap it in a `SmartMotorController`.                             |
| [Step 2: The arm](/documentation/tutorials/arm/mechanism)                     | Describe the arm with an `ArmConfig` and create the `Arm`.                                    |
| [Step 3: Commands and buttons](/documentation/tutorials/arm/commands)         | Turn the `Arm` into commands and bind them to controller buttons.                             |
| [Step 4: Simulate it](/documentation/tutorials/arm/simulate)                  | Run the code on your computer and drive the arm with a controller.                            |
| [Step 5: Tune it](/documentation/tutorials/arm/tune)                          | Tune the gains while the simulation runs, and copy them into your code.                       |
| [Step 6: Run it on the robot](/documentation/tutorials/arm/robot)             | Check the arm safely on the robot, then tune it there.                                        |

## More than one motor

Two motors on one shaft or gearbox? Add the second as a follower with `withFollowers`. Two motors that aren't on the same shaft or gearbox, such as one on each side of the mechanism? Make the second a loosely coupled follower with `withLooselyCoupledFollowers`: the mechanism still works as this tutorial shows. [Followers](/documentation/reference/editor/config/followers) explains both.

## Complete Example

The following files show a complete, working Arm from the YAMS `simple_robot-2027` Commands v2 example. It uses a `TalonFX` with a `CANcoder` instead of the `SparkMax` in this tutorial; the YAMS code is otherwise the same.

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/ArmSubsystem.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/RobotContainer.java>" %}

The same robot in the other two flavors:

* **Java, Commands v3:** [`mechanisms/ArmMechanism.java`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/simple_robot-2027/src/main/java/first/robot/mechanisms/ArmMechanism.java) in `examples/commands3/simple_robot-2027`
* **C++:** [`ArmSubsystem.h`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/include/subsystems/ArmSubsystem.h) and [`ArmSubsystem.cpp`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/cpp/subsystems/ArmSubsystem.cpp) in `examples/cpptest`


# Step 1: The motor controller

Configure the SparkMax and wrap it in a SmartMotorController.

{% hint style="info" %}
This page assumes a project with YAMS and REVLib installed. If you do not have one yet, start at [Create a project and install YAMS](/documentation/tutorials/project-setup).
{% endhint %}

A `SmartMotorController` is how YAMS talks to a motor controller. It takes three things:

1. **The vendor's motor controller object**, here a `SparkMax`.
2. **The motor** that is plugged into it, here one NEO.
3. **A `SmartMotorControllerConfig`** that says what the motor controller should do: its control mode, its PID and feedforward gains, its motion profile, the gearing between the motor and the arm, where the arm starts, and how far the closed loop may take it.

YAMS applies the config to the `SparkMax` for you, and uses the same config to build the simulation.

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

## Create the file

{% tabs %}
{% tab title="Java, Commands v2" %}
Create `ArmSubsystem.java` in the `subsystems` folder, next to the template's `ExampleSubsystem.java`.
{% endtab %}

{% tab title="Java, Commands v3" %}
Create `ArmMechanism.java` in the `mechanisms` folder, next to the template's `ExampleMechanism.java`.

The config comes from `yams.commands3.config`, and it takes the `Mechanism` where Commands v2 passes the subsystem.
{% endtab %}

{% tab title="C++" %}
Create `ArmSubsystem.hpp` in `src/main/include/subsystems` and `ArmSubsystem.cpp` in `src/main/cpp/subsystems`.

YAMS keeps a pointer to the config and to the `SparkMax`, so in C++ both are members of the subsystem. The constructor fills in the config and then creates the `SmartMotorController`, which is why that one is a `std::optional`.

`WithFeedback` is the C++ name of `withClosedLoopController`, `WithMotorGearing` of `withGearing`, and `WithMechanismLimits` of `withSoftLimits`.
{% endtab %}
{% endtabs %}

{% stepper %}
{% step %}

### Start the config

Everything the motor controller should do goes into one `SmartMotorControllerConfig`. Start it, and put it in closed loop mode so that it can hold a position.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
// What the motor controller should do: its control mode, gains, gearing and limits.
private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
// What the motor controller should do: its control mode, gains, gearing and limits.
private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ArmSubsystem.hpp" %}

```cpp
// What the motor controller should do. It is filled in by the constructor.
yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;
```

{% endcode %}

{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
// What the motor controller should do: its control mode, gains, gearing and limits.
m_smcConfig
    .WithSubsystem(this)
    .WithClosedLoopMode()
```

{% endcode %}
{% endtab %}
{% endtabs %}

Want the details? [Motor basics](/documentation/reference/editor/config/motor-basics)
{% endstep %}

{% step %}

### PID and feedforward

The PID gains correct the difference between where the arm is and where you asked it to be. The feedforward supplies the voltage you already know it needs. The `Sim` options are used only in simulation, so the simulation can be tuned without touching the real robot's gains.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
// Feedback constants (PID), on the real robot and in simulation.
.withClosedLoopController(50, 0, 0)
.withSimClosedLoopController(50, 0, 0)

// Feedforward constants, on the real robot and in simulation.
.withFeedforward(new ArmFeedforward(0, 0, 0))
.withSimFeedforward(new ArmFeedforward(0, 0, 0))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
// Feedback constants (PID), on the real robot and in simulation.
.withClosedLoopController(50, 0, 0)
.withSimClosedLoopController(50, 0, 0)

// Feedforward constants, on the real robot and in simulation.
.withFeedforward(new ArmFeedforward(0, 0, 0))
.withSimFeedforward(new ArmFeedforward(0, 0, 0))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
// Feedback constants (PID), on the real robot and in simulation.
.WithFeedback(50, 0, 0)
.WithSimClosedLoopController(50, 0, 0)

// Feedforward constants: kS, kG and kV.
.WithFeedforward(wpi::math::ArmFeedforward{
    0_V, 0_V, wpi::units::unit_t<wpi::math::ArmFeedforward::kv_unit>{0}})
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** These numbers are only a place to start. Leave them, get the arm moving, then tune them with [Live tuning](/documentation/how-to-tuning/live-tuning).

Want the details? [Closed loop control](/documentation/reference/editor/config/closed-loop-control) and [Feedforward](/documentation/reference/editor/config/feedforward)
{% endstep %}

{% step %}

### Motion profile

The profile caps how fast the arm may move and accelerate on its way to a setpoint, so that it glides there instead of lunging.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
// The fastest the closed loop is allowed to move and accelerate the arm.
.withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
// The fastest the closed loop is allowed to move and accelerate the arm.
.withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
// The fastest the closed loop is allowed to move and accelerate the arm.
.WithTrapezoidProfile(90_deg_per_s, 45_deg_per_s_sq)
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Start slow. Raise the two numbers once the mechanism moves safely.

Want the details? [Motion profiles](/documentation/reference/editor/config/motion-profiles)
{% endstep %}

{% step %}

### Gearing

The gearing tells YAMS how many turns of the motor make one turn of the arm.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-74ee72576d43ddbb20cacb97d8296685d989a195%2Ftutorial-gearing.gif?alt=media" alt="Animation of a motor rotor turning 12 times while the mechanism it drives through a 3 to 1 stage and a 4 to 1 stage, 12 to 1 in total, turns once. Counters show the motor rotations and the mechanism rotations and angle."><figcaption><p>With 12:1 gearing, twelve rotations of the motor are one rotation of the mechanism.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
// Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
.withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
// Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
.withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
// Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
.WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({3.0, 4.0})})
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** List your gearbox stages in order, from the motor outward. `3, 4` here is a 3:1 stage followed by a 4:1 stage.

Want the details? [Gearing and units](/documentation/reference/editor/config/gearing-and-units)
{% endstep %}

{% step %}

### Direction, idle mode and current limit

Which way is positive, what the motor does when it is given no power, and the most current it may draw.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
.withMotorInverted(false)
.withZeroPower(MotorMode.BRAKE)
.withStatorCurrentLimit(Amps.of(40))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
.withMotorInverted(false)
.withZeroPower(MotorMode.BRAKE)
.withStatorCurrentLimit(Amps.of(40))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
.WithMotorInverted(false)
.WithZeroPower(Cfg::MotorMode::BRAKE)
.WithStatorCurrentLimit(40_A)
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Flip the inversion if a positive output moves your arm the wrong way. Keep the current limit within what your wiring and breaker allow.

Want the details? [Motor basics](/documentation/reference/editor/config/motor-basics) and [Limits and protection](/documentation/reference/editor/config/limits-and-protection)
{% endstep %}

{% step %}

### Starting position and soft limits

The starting position is where the arm is when the robot turns on. The soft limits are as far as the closed loop is allowed to take it.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b4934b97bacb73e6df57d1dc94e5c782997037e8%2Fsmc-soft-limits.png?alt=media" alt="A bar showing a mechanism&#x27;s travel between two hard stops, with a lower and an upper soft limit a little inside them. The mechanism may move between the soft limits. A setpoint asked for beyond the upper limit is moved back to the limit."><figcaption><p>Soft limits sit a little inside the hard stops.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
// Where the arm is when the robot turns on.
.withStartingPosition(Degrees.of(-5))
// The closed loop will not take the arm past these angles.
.withSoftLimits(Degrees.of(-20), Degrees.of(30))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
// Where the arm is when the robot turns on.
.withStartingPosition(Degrees.of(-5))
// The closed loop will not take the arm past these angles.
.withSoftLimits(Degrees.of(-20), Degrees.of(30))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
// Where the arm is when the robot turns on.
.WithStartingPosition(-5_deg)
// The closed loop will not take the arm past these angles.
.WithMechanismLimits(-20_deg, 30_deg)
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Set the starting position to where your arm really rests, and the soft limits just inside its hard stops.

Want the details? [Limits and protection](/documentation/reference/editor/config/limits-and-protection)
{% endstep %}

{% step %}

### Telemetry

The name the motor gets on your dashboard, and how much it publishes. `HIGH` publishes everything, which is what you want while tuning.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
// Telemetry name and how much to publish.
.withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
// Telemetry name and how much to publish.
.withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
// Telemetry name and how much to publish.
.WithTelemetry("ArmMotor", Cfg::TelemetryVerbosity::HIGH);
```

{% endcode %}
{% endtab %}
{% endtabs %}

Want the details? [Telemetry](/documentation/understanding/telemetry)
{% endstep %}

{% step %}

### The motor controller object

This is the vendor's own object, exactly as you would create it without YAMS.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
// The vendor motor controller object: a SPARK MAX with CAN ID 4.
private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
// The vendor motor controller object: a SPARK MAX with CAN ID 4.
private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ArmSubsystem.hpp" %}

```cpp
// The vendor motor controller object: a SPARK MAX with CAN ID 4.
rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the CAN ID to yours. Using a different motor controller? See the [feature matrix](/documentation/reference/editor/feature-matrix) for the wrapper that goes with it.
{% endstep %}

{% step %}

### The SmartMotorController

The wrapper brings the three together: the motor controller object, the motor plugged into it, and the config.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
// The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
// The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ArmSubsystem.hpp" %}

```cpp
// The SmartMotorController, created in the constructor once the config is ready.
std::optional<yams::motorcontrollers::local::SparkWrapper> m_motor;
```

{% endcode %}

{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
// The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
m_motor.emplace(&m_spark, wpi::math::DCMotor::NEO(1), &m_smcConfig);
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the motor to the kind and the number of motors you have.

Want the details? [Smart motor controllers](/documentation/reference/editor)
{% endstep %}
{% endstepper %}

## The complete file

Every part above, in one file, with its imports.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" lineNumbers="true" %}

```java
package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Degrees;
import static org.wpilib.units.Units.DegreesPerSecond;
import static org.wpilib.units.Units.DegreesPerSecondPerSecond;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ArmFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ArmSubsystem extends SubsystemBase {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(50, 0, 0)
      .withSimClosedLoopController(50, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the arm.
      .withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ArmFeedforward(0, 0, 0))
      .withSimFeedforward(new ArmFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the arm is when the robot turns on.
      .withStartingPosition(Degrees.of(-5))
      // The closed loop will not take the arm past these angles.
      .withSoftLimits(Degrees.of(-20), Degrees.of(30))
      // Telemetry name and how much to publish.
      .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" lineNumbers="true" %}

```java
package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Degrees;
import static org.wpilib.units.Units.DegreesPerSecond;
import static org.wpilib.units.Units.DegreesPerSecondPerSecond;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ArmFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands3.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ArmMechanism implements Mechanism {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(50, 0, 0)
      .withSimClosedLoopController(50, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the arm.
      .withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ArmFeedforward(0, 0, 0))
      .withSimFeedforward(new ArmFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the arm is when the robot turns on.
      .withStartingPosition(Degrees.of(-5))
      // The closed loop will not take the arm past these angles.
      .withSoftLimits(Degrees.of(-20), Degrees.of(30))
      // Telemetry name and how much to publish.
      .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ArmSubsystem.hpp" lineNumbers="true" %}

```cpp
#pragma once

#include <optional>

#include <rev/SparkMax.h>
#include <wpi/commands2/SubsystemBase.hpp>
#include <wpi/hardware/bus/CANPort.hpp>

#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/local/SparkWrapper.hpp"

class ArmSubsystem : public wpi::cmd::SubsystemBase {
 public:
  ArmSubsystem();

 private:
  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};

  // What the motor controller should do. It is filled in by the constructor.
  yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;

  // The SmartMotorController, created in the constructor once the config is ready.
  std::optional<yams::motorcontrollers::local::SparkWrapper> m_motor;
};
```

{% endcode %}

{% code title="cpp/subsystems/ArmSubsystem.cpp" lineNumbers="true" %}

```cpp
#include "subsystems/ArmSubsystem.hpp"

#include <wpi/math/controller/ArmFeedforward.hpp>
#include <wpi/math/system/DCMotor.hpp>
#include <wpi/units/angle.hpp>
#include <wpi/units/angular_acceleration.hpp>
#include <wpi/units/angular_velocity.hpp>
#include <wpi/units/current.hpp>
#include <wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;

ArmSubsystem::ArmSubsystem() {
  // What the motor controller should do: its control mode, gains, gearing and limits.
  m_smcConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // Feedback constants (PID), on the real robot and in simulation.
      .WithFeedback(50, 0, 0)
      .WithSimClosedLoopController(50, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the arm.
      .WithTrapezoidProfile(90_deg_per_s, 45_deg_per_s_sq)
      // Feedforward constants: kS, kG and kV.
      .WithFeedforward(wpi::math::ArmFeedforward{
          0_V, 0_V, wpi::units::unit_t<wpi::math::ArmFeedforward::kv_unit>{0}})
      // Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({3.0, 4.0})})
      .WithMotorInverted(false)
      .WithZeroPower(Cfg::MotorMode::BRAKE)
      .WithStatorCurrentLimit(40_A)
      // Where the arm is when the robot turns on.
      .WithStartingPosition(-5_deg)
      // The closed loop will not take the arm past these angles.
      .WithMechanismLimits(-20_deg, 30_deg)
      // Telemetry name and how much to publish.
      .WithTelemetry("ArmMotor", Cfg::TelemetryVerbosity::HIGH);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  m_motor.emplace(&m_spark, wpi::math::DCMotor::NEO(1), &m_smcConfig);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Read more

Every option used here has its own section in the `SmartMotorControllerConfig` pages:

* [Motor basics](/documentation/reference/editor/config/motor-basics): control mode, inversion, what the motor does at zero power
* [Gearing and units](/documentation/reference/editor/config/gearing-and-units): gearing, and how rotations become distance
* [Closed loop control](/documentation/reference/editor/config/closed-loop-control), [Feedforward](/documentation/reference/editor/config/feedforward) and [Motion profiles](/documentation/reference/editor/config/motion-profiles)
* [Limits and protection](/documentation/reference/editor/config/limits-and-protection): soft limits and current limits
* [Simulation](/documentation/reference/editor/config/simulation): the simulation only gains

The PID and feedforward numbers on this page are a place to start, not tuned values. You tune them in [Step 5: Tune it](/documentation/tutorials/arm/tune).

## Check it

Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Build Robot Code**. It should build. Nothing moves yet, because nothing tells the motor what to do.

* **`SparkMax` cannot be found:** REVLib is not installed. See [Install your motor controller's library](/documentation/tutorials/project-setup#install-your-motor-controllers-library).
* **`SmartMotorControllerConfig` cannot be found:** YAMS is not installed, or the import is from the other command framework (`yams.commands2` or `yams.commands3`).


# Step 2: The arm

Describe the arm and create the Arm mechanism.

The `SmartMotorController` from step 1 is configured, but nothing tells it to move yet. An `Arm` adds what makes it an arm: a physics simulation, a drawing of the mechanism for your dashboard, and the commands and triggers you will use in step 3.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-9ac4402ed53c7caf15787f40f7a6245c3ef8a7c2%2Fmech-two-configs.png?alt=media" alt="A diagram. A mechanism config, which says what the mechanism is, such as its length, mass, hard stops and how it is drawn, and a SmartMotorControllerConfig, which says how its motor behaves, such as gearing, PID, feedforward, soft limits and current, both go into the mechanism class. The mechanism then drives the simulation&#x27;s physics and Mechanism2d, and the real robot&#x27;s commands and telemetry."><figcaption><p>Two configs go into one mechanism.</p></figcaption></figure>

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

{% stepper %}
{% step %}

### Describe the arm

`ArmConfig` describes the arm itself: its length and its hard limits. The simulation uses both. The hard limits are where the arm physically stops, which is different from the soft limits you set in step 1.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-309f8e0214d8774fbbf0a818888126af56d043bd%2Ftutorial-arm-angles.png?alt=media" alt="A side view of the arm and the angles used in this tutorial. The hard limits are minus 30 and 40 degrees: where the arm physically stops, set on ArmConfig and used by the simulation. The soft limits are minus 20 and 30 degrees: as far as the closed loop will go, set on SmartMotorControllerConfig. Inside them are the setpoints: minus 5 degrees for the A button, which is also where the arm starts, 15 degrees for the B button, and 0 degrees for the default command."><figcaption><p>The soft limits from step 1 sit inside the hard limits from this step.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
private final ArmConfig armConfig = new ArmConfig()
    // The hard stops, used by the simulation.
    .withHardLimits(Degrees.of(-30), Degrees.of(40))
    // The length of the arm, used by the simulation.
    .withLength(Feet.of(3))
    // Telemetry name and how much to publish.
    .withTelemetry("Arm", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
private final ArmConfig armConfig = new ArmConfig()
    // The hard stops, used by the simulation.
    .withHardLimits(Degrees.of(-30), Degrees.of(40))
    // The length of the arm, used by the simulation.
    .withLength(Feet.of(3))
    // Telemetry name and how much to publish.
    .withTelemetry("Arm", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ArmSubsystem.hpp" %}

```cpp
// The arm mechanism and its config, also set up in the constructor.
yams::mechanisms::config::ArmConfig m_armConfig;
std::optional<yams::mechanisms::positional::Arm> m_arm;
```

{% endcode %}

{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
m_armConfig
    // The hard stops, used by the simulation.
    .WithMinAngle(-30_deg)
    .WithMaxAngle(40_deg)
    // The length of the arm, used by the simulation.
    .WithArmLength(3_ft)
    // Telemetry name.
    .WithTelemetryName("Arm");
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Set the length of your arm, and where its hard stops are.

Want the details? [Arms](/documentation/understanding/arms) and [ArmConfig](/documentation/reference/mechanism-configs/arm-config)
{% endstep %}

{% step %}

### Create the Arm

Hand the config, and the `SmartMotorController` from step 1, to the `Arm`.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
// The arm mechanism.
private final Arm arm = new Arm(armConfig, motor);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
// The arm mechanism.
private final Arm arm = new Arm(armConfig, motor);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
// The arm mechanism.
m_arm.emplace(&m_armConfig, &m_motor.value());
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}

### Update it every loop

Two calls keep the mechanism alive. `updateTelemetry()` publishes its telemetry and applies anything you change through live tuning. `simIterate()` runs the physics simulation, and only needs to run in simulation.

In Commands v2 and C++ the scheduler calls a subsystem's periodic methods for you, so there is nothing more to do.

In Commands v3 nothing calls a `Mechanism` every loop, so `Robot.java` does it. `Robot.java` has the two functions you need:

* **`robotPeriodic()`** runs every loop, on the robot and in simulation. Call the mechanism's `periodic()` here, before `scheduler.run()`, so that the commands see fresh values.
* **`simulationInit()`** runs once, when the simulation starts. The template does not have it yet, so add it, and start the mechanism's `simulationPeriodic()` here with `startSimulation(...)`, which runs it in its own `Notifier` every loop, in simulation only. That keeps the simulation from adding to the robot loop's time, as [Where the tutorials put things](/documentation/tutorials/project-setup#where-the-tutorials-put-things) explains.

Every mechanism you add to the robot gets one line in each of the two.

Two smaller changes tidy up the template while you are here. Keep `Scheduler.getDefault()` in a `scheduler` attribute instead of asking for it every loop, and publish the scheduler with `Telemetry.log(...)` after it runs, so that a dashboard shows which commands are running and which mechanisms they hold.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
@Override
public void periodic() {
  // Publishes the arm's telemetry, and applies anything changed through live tuning.
  arm.updateTelemetry();
}

@Override
public void simulationPeriodic() {
  // Runs the arm's physics simulation.
  arm.simIterate();
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
/** Call this from Robot.robotPeriodic(), before the scheduler runs. */
public void periodic() {
  // Publishes the arm's telemetry, and applies anything changed through live tuning.
  arm.updateTelemetry();
}

/** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
public void simulationPeriodic() {
  // Runs the arm's physics simulation.
  arm.simIterate();
}
```

{% endcode %}

{% code title="Robot.java" %}

```java
import java.util.ArrayList;
import java.util.List;
import org.wpilib.system.Notifier;
import org.wpilib.telemetry.Telemetry;
import first.robot.mechanisms.ArmMechanism;

public class Robot extends OpModeRobot {
  // ...
  final ArmMechanism arm = new ArmMechanism();
  // ...

  // The scheduler that runs every command.
  private final Scheduler scheduler = Scheduler.getDefault();
  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
  private final List<Notifier> simulationNotifiers = new ArrayList<>();

  // ...

  @Override
  public void robotPeriodic() {
    // Runs every loop, on the robot and in simulation.
    // Update the mechanism before the scheduler runs its commands.
    arm.periodic();
    scheduler.run();
    // Publish the scheduler, so that a dashboard shows which commands are running.
    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
  }

  @Override
  public void simulationInit() {
    // Runs once, when the simulation starts.
    // Run each mechanism's simulation in its own Notifier, every robot loop.
    startSimulation("Arm", arm::simulationPeriodic);
  }

  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
  private void startSimulation(String name, Runnable simulationPeriodic) {
    Notifier notifier = new Notifier(simulationPeriodic);
    notifier.setName(name + " Simulation");
    notifier.startPeriodic(getPeriod());
    simulationNotifiers.add(notifier);
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ArmSubsystem.hpp" %}

```cpp
void Periodic() override;
void SimulationPeriodic() override;
```

{% endcode %}

{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
void ArmSubsystem::Periodic() {
  // Publishes the arm's telemetry, and applies anything changed through live tuning.
  m_arm->UpdateTelemetry();
}

void ArmSubsystem::SimulationPeriodic() {
  // Runs the arm's physics simulation.
  m_arm->SimIterate();
}
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
The highlighted lines are new in this step.

`ArmSubsystem` extends `SubsystemBase`, so the scheduler calls `periodic()` and `simulationPeriodic()` for you.

<pre class="language-java" data-title="subsystems/ArmSubsystem.java" data-line-numbers><code class="lang-java">package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Degrees;
import static org.wpilib.units.Units.DegreesPerSecond;
import static org.wpilib.units.Units.DegreesPerSecondPerSecond;
<strong>import static org.wpilib.units.Units.Feet;
</strong>
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ArmFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands2.config.SmartMotorControllerConfig;
<strong>import yams.commands2.mechanisms.Arm;
</strong>import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
<strong>import yams.core.mechanisms.config.ArmConfig;
</strong>import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ArmSubsystem extends SubsystemBase {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(50, 0, 0)
      .withSimClosedLoopController(50, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the arm.
      .withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ArmFeedforward(0, 0, 0))
      .withSimFeedforward(new ArmFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the arm is when the robot turns on.
      .withStartingPosition(Degrees.of(-5))
      // The closed loop will not take the arm past these angles.
      .withSoftLimits(Degrees.of(-20), Degrees.of(30))
      // Telemetry name and how much to publish.
      .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

<strong>  private final ArmConfig armConfig = new ArmConfig()
</strong><strong>      // The hard stops, used by the simulation.
</strong><strong>      .withHardLimits(Degrees.of(-30), Degrees.of(40))
</strong><strong>      // The length of the arm, used by the simulation.
</strong><strong>      .withLength(Feet.of(3))
</strong><strong>      // Telemetry name and how much to publish.
</strong><strong>      .withTelemetry("Arm", TelemetryVerbosity.HIGH);
</strong>
<strong>  // The arm mechanism.
</strong><strong>  private final Arm arm = new Arm(armConfig, motor);
</strong>
<strong>  @Override
</strong><strong>  public void periodic() {
</strong><strong>    // Publishes the arm's telemetry, and applies anything changed through live tuning.
</strong><strong>    arm.updateTelemetry();
</strong><strong>  }
</strong>
<strong>  @Override
</strong><strong>  public void simulationPeriodic() {
</strong><strong>    // Runs the arm's physics simulation.
</strong><strong>    arm.simIterate();
</strong><strong>  }
</strong>}
</code></pre>

{% endtab %}

{% tab title="Java, Commands v3" %}
The highlighted lines are new in this step.

Nothing calls a periodic method on a Commands v3 `Mechanism`, so give the class its own `periodic()` and `simulationPeriodic()` and create the mechanism in `Robot.java`. Then call its `periodic()` from `Robot.robotPeriodic()`, before the scheduler runs, and start its `simulationPeriodic()` in its own `Notifier` from `Robot.simulationInit()`.

<pre class="language-java" data-title="mechanisms/ArmMechanism.java" data-line-numbers><code class="lang-java">package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Degrees;
import static org.wpilib.units.Units.DegreesPerSecond;
import static org.wpilib.units.Units.DegreesPerSecondPerSecond;
<strong>import static org.wpilib.units.Units.Feet;
</strong>
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ArmFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands3.config.SmartMotorControllerConfig;
<strong>import yams.commands3.mechanisms.Arm;
</strong>import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
<strong>import yams.core.mechanisms.config.ArmConfig;
</strong>import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ArmMechanism implements Mechanism {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(50, 0, 0)
      .withSimClosedLoopController(50, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the arm.
      .withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ArmFeedforward(0, 0, 0))
      .withSimFeedforward(new ArmFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the arm is when the robot turns on.
      .withStartingPosition(Degrees.of(-5))
      // The closed loop will not take the arm past these angles.
      .withSoftLimits(Degrees.of(-20), Degrees.of(30))
      // Telemetry name and how much to publish.
      .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

<strong>  private final ArmConfig armConfig = new ArmConfig()
</strong><strong>      // The hard stops, used by the simulation.
</strong><strong>      .withHardLimits(Degrees.of(-30), Degrees.of(40))
</strong><strong>      // The length of the arm, used by the simulation.
</strong><strong>      .withLength(Feet.of(3))
</strong><strong>      // Telemetry name and how much to publish.
</strong><strong>      .withTelemetry("Arm", TelemetryVerbosity.HIGH);
</strong>
<strong>  // The arm mechanism.
</strong><strong>  private final Arm arm = new Arm(armConfig, motor);
</strong>
<strong>  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
</strong><strong>  public void periodic() {
</strong><strong>    // Publishes the arm's telemetry, and applies anything changed through live tuning.
</strong><strong>    arm.updateTelemetry();
</strong><strong>  }
</strong>
<strong>  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
</strong><strong>  public void simulationPeriodic() {
</strong><strong>    // Runs the arm's physics simulation.
</strong><strong>    arm.simIterate();
</strong><strong>  }
</strong>}
</code></pre>

<pre class="language-java" data-title="Robot.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import java.util.ArrayList;
</strong><strong>import java.util.List;
</strong>import org.wpilib.command3.Scheduler;
import org.wpilib.command3.button.CommandGamepad;
import org.wpilib.framework.OpModeRobot;
<strong>import org.wpilib.system.Notifier;
</strong><strong>import org.wpilib.telemetry.Telemetry;
</strong>import first.robot.constants.DriverConstants;
<strong>import first.robot.mechanisms.ArmMechanism;
</strong>import first.robot.mechanisms.ExampleMechanism;

public class Robot extends OpModeRobot {
  final ExampleMechanism exampleMechanism = new ExampleMechanism();
<strong>  final ArmMechanism arm = new ArmMechanism();
</strong>  final CommandGamepad exampleController =
      new CommandGamepad(DriverConstants.DRIVER_CONTROLLER_PORT);

<strong>  // The scheduler that runs every command.
</strong><strong>  private final Scheduler scheduler = Scheduler.getDefault();
</strong><strong>  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
</strong><strong>  private final List&#x3C;Notifier> simulationNotifiers = new ArrayList&#x3C;>();
</strong>
  public Robot() {}

  @Override
  public void robotPeriodic() {
<strong>    // Runs every loop, on the robot and in simulation.
</strong><strong>    // Update the mechanism before the scheduler runs its commands.
</strong><strong>    arm.periodic();
</strong><strong>    scheduler.run();
</strong><strong>    // Publish the scheduler, so that a dashboard shows which commands are running.
</strong><strong>    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
</strong><strong>  }
</strong>
<strong>  @Override
</strong><strong>  public void simulationInit() {
</strong><strong>    // Runs once, when the simulation starts.
</strong><strong>    // Run each mechanism's simulation in its own Notifier, every robot loop.
</strong><strong>    startSimulation("Arm", arm::simulationPeriodic);
</strong><strong>  }
</strong>
<strong>  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
</strong><strong>  private void startSimulation(String name, Runnable simulationPeriodic) {
</strong><strong>    Notifier notifier = new Notifier(simulationPeriodic);
</strong><strong>    notifier.setName(name + " Simulation");
</strong><strong>    notifier.startPeriodic(getPeriod());
</strong><strong>    simulationNotifiers.add(notifier);
</strong><strong>  }
</strong>}
</code></pre>

{% endtab %}

{% tab title="C++" %}
The highlighted lines are new in this step.

`ArmConfig` in C++ takes the two hard limits separately, with `WithMinAngle` and `WithMaxAngle`, and `WithArmLength` is the C++ name of `withLength`. The C++ mechanism configs take a telemetry name only.

<pre class="language-cpp" data-title="include/subsystems/ArmSubsystem.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include &#x3C;optional>

#include &#x3C;rev/SparkMax.h>
#include &#x3C;wpi/commands2/SubsystemBase.hpp>
#include &#x3C;wpi/hardware/bus/CANPort.hpp>

<strong>#include "yams/mechanisms/config/ArmConfig.hpp"
</strong><strong>#include "yams/mechanisms/positional/Arm.hpp"
</strong>#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/local/SparkWrapper.hpp"

class ArmSubsystem : public wpi::cmd::SubsystemBase {
 public:
  ArmSubsystem();

<strong>  void Periodic() override;
</strong><strong>  void SimulationPeriodic() override;
</strong>
 private:
  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};

  // What the motor controller should do. It is filled in by the constructor.
  yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;

  // The SmartMotorController, created in the constructor once the config is ready.
  std::optional&#x3C;yams::motorcontrollers::local::SparkWrapper> m_motor;

<strong>  // The arm mechanism and its config, also set up in the constructor.
</strong><strong>  yams::mechanisms::config::ArmConfig m_armConfig;
</strong><strong>  std::optional&#x3C;yams::mechanisms::positional::Arm> m_arm;
</strong>};
</code></pre>

<pre class="language-cpp" data-title="cpp/subsystems/ArmSubsystem.cpp" data-line-numbers><code class="lang-cpp">#include "subsystems/ArmSubsystem.hpp"

#include &#x3C;wpi/math/controller/ArmFeedforward.hpp>
#include &#x3C;wpi/math/system/DCMotor.hpp>
#include &#x3C;wpi/units/angle.hpp>
#include &#x3C;wpi/units/angular_acceleration.hpp>
#include &#x3C;wpi/units/angular_velocity.hpp>
#include &#x3C;wpi/units/current.hpp>
<strong>#include &#x3C;wpi/units/length.hpp>
</strong>#include &#x3C;wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;

ArmSubsystem::ArmSubsystem() {
  // What the motor controller should do: its control mode, gains, gearing and limits.
  m_smcConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // Feedback constants (PID), on the real robot and in simulation.
      .WithFeedback(50, 0, 0)
      .WithSimClosedLoopController(50, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the arm.
      .WithTrapezoidProfile(90_deg_per_s, 45_deg_per_s_sq)
      // Feedforward constants: kS, kG and kV.
      .WithFeedforward(wpi::math::ArmFeedforward{
          0_V, 0_V, wpi::units::unit_t&#x3C;wpi::math::ArmFeedforward::kv_unit>{0}})
      // Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({3.0, 4.0})})
      .WithMotorInverted(false)
      .WithZeroPower(Cfg::MotorMode::BRAKE)
      .WithStatorCurrentLimit(40_A)
      // Where the arm is when the robot turns on.
      .WithStartingPosition(-5_deg)
      // The closed loop will not take the arm past these angles.
      .WithMechanismLimits(-20_deg, 30_deg)
      // Telemetry name and how much to publish.
      .WithTelemetry("ArmMotor", Cfg::TelemetryVerbosity::HIGH);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  m_motor.emplace(&#x26;m_spark, wpi::math::DCMotor::NEO(1), &#x26;m_smcConfig);

<strong>  m_armConfig
</strong><strong>      // The hard stops, used by the simulation.
</strong><strong>      .WithMinAngle(-30_deg)
</strong><strong>      .WithMaxAngle(40_deg)
</strong><strong>      // The length of the arm, used by the simulation.
</strong><strong>      .WithArmLength(3_ft)
</strong><strong>      // Telemetry name.
</strong><strong>      .WithTelemetryName("Arm");
</strong>
<strong>  // The arm mechanism.
</strong><strong>  m_arm.emplace(&#x26;m_armConfig, &#x26;m_motor.value());
</strong>}

<strong>void ArmSubsystem::Periodic() {
</strong><strong>  // Publishes the arm's telemetry, and applies anything changed through live tuning.
</strong><strong>  m_arm->UpdateTelemetry();
</strong><strong>}
</strong>
<strong>void ArmSubsystem::SimulationPeriodic() {
</strong><strong>  // Runs the arm's physics simulation.
</strong><strong>  m_arm->SimIterate();
</strong><strong>}
</strong></code></pre>

{% endtab %}
{% endtabs %}

## Check it

Build the code again. You can already run the simulation as in [step 4](/documentation/tutorials/arm/simulate): the arm is drawn at -5 degrees. It does not move yet, because nothing gives it a setpoint.


# Step 3: Commands and buttons

Make commands from the Arm and bind them to controller buttons.

The `Arm` makes commands for you. Your class hands them out, and the buttons schedule them.

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

{% stepper %}
{% step %}

### Make the commands

The `Arm` makes the commands. Your class only hands them out, so that the rest of the robot code never touches the motor directly.

| What it does                                                  | Java, Commands v2             | Java, Commands v3             | C++                              |
| ------------------------------------------------------------- | ----------------------------- | ----------------------------- | -------------------------------- |
| Go to an angle and hold it. It never ends on its own.         | `arm.run(angle)`              | `arm.setAngle(angle)`         | `m_arm->Run(angle)`              |
| Go to an angle, and end when the arm is within the tolerance. | `arm.runTo(angle, tolerance)` | `arm.runTo(angle, tolerance)` | `m_arm->RunTo(angle, tolerance)` |
| Drive at a duty cycle from -1 to 1, with the closed loop off. | `arm.set(dutycycle)`          | `arm.set(dutycycle)`          | `m_arm->Set(dutycycle)`          |

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
/** Go to an angle and hold it. This command does not end on its own. */
public Command run(Angle angle) {
  return arm.run(angle);
}

/** Go to an angle, and end once the arm is within the tolerance of it. */
public Command runTo(Angle angle, Angle tolerance) {
  return arm.runTo(angle, tolerance);
}

/** Drive the arm with a duty cycle from -1 to 1. The closed loop is not used. */
public Command set(double dutycycle) {
  return arm.set(dutycycle);
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
/** Go to an angle and hold it. This command does not end on its own. */
public Command setAngle(Angle angle) {
  return arm.setAngle(angle);
}

/** Go to an angle, and end once the arm is within the tolerance of it. */
public Command moveTo(Angle angle, Angle tolerance) {
  return arm.runTo(angle, tolerance);
}

/** Drive the arm with a duty cycle from -1 to 1. The closed loop is not used. */
public Command set(double dutycycle) {
  return arm.set(dutycycle);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ArmSubsystem.hpp" %}

```cpp
/** Go to an angle and hold it. This command does not end on its own. */
wpi::cmd::CommandPtr Run(wpi::units::degree_t angle);

/** Go to an angle, and end once the arm is within the tolerance of it. */
wpi::cmd::CommandPtr RunTo(wpi::units::degree_t angle, wpi::units::degree_t tolerance);

/** Drive the arm with a duty cycle from -1 to 1. The closed loop is not used. */
wpi::cmd::CommandPtr Set(double dutycycle);
```

{% endcode %}

{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
wpi::cmd::CommandPtr ArmSubsystem::Run(wpi::units::degree_t angle) {
  return m_arm->Run(angle);
}

wpi::cmd::CommandPtr ArmSubsystem::RunTo(wpi::units::degree_t angle, wpi::units::degree_t tolerance) {
  return m_arm->RunTo(angle, tolerance);
}

wpi::cmd::CommandPtr ArmSubsystem::Set(double dutycycle) {
  return m_arm->Set(dutycycle);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Rename these to suit your robot, or add more. Each one is a single line.

Want the details? [When mechanism commands end](/documentation/understanding/run-vs-runto)
{% endstep %}

{% step %}

### Set the default command

The **default command** runs whenever no other command is using the arm. Here it holds the arm at 0 degrees. In Commands v3 the default command is given the lowest priority, so that any other command for the mechanism can interrupt it.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="RobotContainer.java" %}

```java
import first.robot.subsystems.ArmSubsystem;

private final ArmSubsystem arm = new ArmSubsystem();

// When no other command is using the arm, hold it at 0 degrees.
arm.setDefaultCommand(arm.run(Degrees.of(0)));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
/** Hold an angle at the lowest priority, so that any other arm command can interrupt it. */
public Command hold(Angle angle) {
  return run(coroutine -> coroutine.await(arm.setAngle(angle)))
      .withPriority(Command.LOWEST_PRIORITY)
      .named("Arm Hold");
}
```

{% endcode %}

{% code title="Robot.java" %}

```java
public class Robot extends OpModeRobot {
  // ...

  public Robot() {
    // When no other command is using the arm, hold it at 0 degrees.
    arm.setDefaultCommand(arm.hold(Degrees.of(0)));
  }

  // ...
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/RobotContainer.hpp" %}

```cpp
#include "subsystems/ArmSubsystem.hpp"

ArmSubsystem arm;
```

{% endcode %}

{% code title="cpp/RobotContainer.cpp" %}

```cpp
// When no other command is using the arm, hold it at 0 degrees.
arm.SetDefaultCommand(arm.Run(0_deg));
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Choose what your mechanism should do when nobody is asking anything of it.
{% endstep %}

{% step %}

### Bind the buttons

`whileTrue` runs a command for as long as its button is held, and cancels it on release. The default command then takes back over.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-7d1a6f53a140fb87c1a17a2cd90bb5582a98e559%2Ftutorial-arm-buttons.gif?alt=media" alt="Animation of the four face buttons of a controller, the arm, and the command that is running. With no button held the default command runs: hold the arm at 0 degrees. While A is held its command runs: hold the arm at minus 5 degrees. While B is held: hold the arm at 15 degrees. While X is held the arm is driven at a 30 percent duty cycle with the closed loop off. Each time a button is released the default command takes back over."><figcaption><p>A held button owns the arm. Let go, and the default command brings it back to 0°.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="RobotContainer.java" %}

```java
// Hold an angle while the bottom (A) or right (B) face button is held.
driverController.faceDown().whileTrue(arm.run(Degrees.of(-5)));
driverController.faceRight().whileTrue(arm.run(Degrees.of(15)));
// Drive the arm up or down while the left (X) or top (Y) face button is held.
driverController.faceLeft().whileTrue(arm.set(0.3));
driverController.faceUp().whileTrue(arm.set(-0.3));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="ExampleTeleop.java" %}

```java
// Hold an angle while the bottom (A) or right (B) face button is held.
robot.exampleController.faceDown().whileTrue(robot.arm.setAngle(Degrees.of(-5)));
robot.exampleController.faceRight().whileTrue(robot.arm.setAngle(Degrees.of(15)));
// Drive the arm up or down while the left (X) or top (Y) face button is held.
robot.exampleController.faceLeft().whileTrue(robot.arm.set(0.3));
robot.exampleController.faceUp().whileTrue(robot.arm.set(-0.3));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/RobotContainer.cpp" %}

```cpp
// Hold an angle while the bottom (A) or right (B) face button is held.
driverController.FaceDown().WhileTrue(arm.Run(-5_deg));
driverController.FaceRight().WhileTrue(arm.Run(15_deg));
// Drive the arm up or down while the left (X) or top (Y) face button is held.
driverController.FaceLeft().WhileTrue(arm.Set(0.3));
driverController.FaceUp().WhileTrue(arm.Set(-0.3));
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Pick your own buttons and setpoints. Use `onTrue` instead if one press should start a command that keeps running after the button is released.
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
The highlighted lines are new in this step.

Add the commands to `ArmSubsystem.java`, then create the subsystem and bind the buttons in `RobotContainer.java`. The template bound the right face button to its example command; that binding is replaced.

<pre class="language-java" data-title="subsystems/ArmSubsystem.java" data-line-numbers><code class="lang-java">package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Degrees;
import static org.wpilib.units.Units.DegreesPerSecond;
import static org.wpilib.units.Units.DegreesPerSecondPerSecond;
import static org.wpilib.units.Units.Feet;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
<strong>import org.wpilib.command2.Command;
</strong>import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ArmFeedforward;
import org.wpilib.math.system.DCMotor;
<strong>import org.wpilib.units.measure.Angle;
</strong>import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.mechanisms.Arm;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.ArmConfig;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ArmSubsystem extends SubsystemBase {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(50, 0, 0)
      .withSimClosedLoopController(50, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the arm.
      .withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ArmFeedforward(0, 0, 0))
      .withSimFeedforward(new ArmFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the arm is when the robot turns on.
      .withStartingPosition(Degrees.of(-5))
      // The closed loop will not take the arm past these angles.
      .withSoftLimits(Degrees.of(-20), Degrees.of(30))
      // Telemetry name and how much to publish.
      .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

  private final ArmConfig armConfig = new ArmConfig()
      // The hard stops, used by the simulation.
      .withHardLimits(Degrees.of(-30), Degrees.of(40))
      // The length of the arm, used by the simulation.
      .withLength(Feet.of(3))
      // Telemetry name and how much to publish.
      .withTelemetry("Arm", TelemetryVerbosity.HIGH);

  // The arm mechanism.
  private final Arm arm = new Arm(armConfig, motor);

<strong>  /** Go to an angle and hold it. This command does not end on its own. */
</strong><strong>  public Command run(Angle angle) {
</strong><strong>    return arm.run(angle);
</strong><strong>  }
</strong>
<strong>  /** Go to an angle, and end once the arm is within the tolerance of it. */
</strong><strong>  public Command runTo(Angle angle, Angle tolerance) {
</strong><strong>    return arm.runTo(angle, tolerance);
</strong><strong>  }
</strong>
<strong>  /** Drive the arm with a duty cycle from -1 to 1. The closed loop is not used. */
</strong><strong>  public Command set(double dutycycle) {
</strong><strong>    return arm.set(dutycycle);
</strong><strong>  }
</strong>
  @Override
  public void periodic() {
    // Publishes the arm's telemetry, and applies anything changed through live tuning.
    arm.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    // Runs the arm's physics simulation.
    arm.simIterate();
  }
}
</code></pre>

<pre class="language-java" data-title="RobotContainer.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.Degrees;
</strong>
import org.wpilib.command2.Command;
import org.wpilib.command2.button.CommandGamepad;
import org.wpilib.command2.button.Trigger;
import first.robot.Constants.OperatorConstants;
import first.robot.commands.Autos;
import first.robot.commands.ExampleCommand;
<strong>import first.robot.subsystems.ArmSubsystem;
</strong>import first.robot.subsystems.ExampleSubsystem;

/**
 * This class is where the bulk of the robot should be declared. Since Command-based is a
 * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
 * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
 * subsystems, commands, and trigger mappings) should be declared here.
 */
public class RobotContainer {
  // The robot's subsystems and commands are defined here...
  private final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
<strong>  private final ArmSubsystem arm = new ArmSubsystem();
</strong>
  private final CommandGamepad driverController =
      new CommandGamepad(OperatorConstants.DRIVER_CONTROLLER_PORT);

  /** The container for the robot. Contains subsystems, OI devices, and commands. */
  public RobotContainer() {
    // Configure the trigger bindings
    configureBindings();

<strong>    // When no other command is using the arm, hold it at 0 degrees.
</strong><strong>    arm.setDefaultCommand(arm.run(Degrees.of(0)));
</strong>  }

  /**
   * Use this method to define your trigger->command mappings. Triggers can be created via the
   * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary
   * predicate, or via the named factories in {@link org.wpilib.command2.button.CommandGenericHID}'s
   * subclasses for {@link CommandGamepad Gamepad} gamepads or {@link
   * org.wpilib.command2.button.CommandJoystick Flight joysticks}.
   */
  private void configureBindings() {
    // Schedule `ExampleCommand` when `exampleCondition` changes to `true`
    new Trigger(exampleSubsystem::exampleCondition).onTrue(new ExampleCommand(exampleSubsystem));

<strong>    // Hold an angle while the bottom (A) or right (B) face button is held.
</strong><strong>    driverController.faceDown().whileTrue(arm.run(Degrees.of(-5)));
</strong><strong>    driverController.faceRight().whileTrue(arm.run(Degrees.of(15)));
</strong><strong>    // Drive the arm up or down while the left (X) or top (Y) face button is held.
</strong><strong>    driverController.faceLeft().whileTrue(arm.set(0.3));
</strong><strong>    driverController.faceUp().whileTrue(arm.set(-0.3));
</strong>  }

  /**
   * Use this to pass the autonomous command to the main {@link Robot} class.
   *
   * @return the command to run in autonomous
   */
  public Command getAutonomousCommand() {
    // An example command will be run in autonomous
    return Autos.exampleAuto(exampleSubsystem);
  }
}
</code></pre>

{% endtab %}

{% tab title="Java, Commands v3" %}
The highlighted lines are new in this step.

Add the commands to `ArmMechanism.java`, set the default command in `Robot.java`, and bind the buttons in `ExampleTeleop.java`.

A `Mechanism` already has a `run(...)` method that takes a coroutine, so the commands here have their own names. The default command is wrapped with `Command.LOWEST_PRIORITY`, so that any other command for the arm can interrupt it.

<pre class="language-java" data-title="mechanisms/ArmMechanism.java" data-line-numbers><code class="lang-java">package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Degrees;
import static org.wpilib.units.Units.DegreesPerSecond;
import static org.wpilib.units.Units.DegreesPerSecondPerSecond;
import static org.wpilib.units.Units.Feet;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
<strong>import org.wpilib.command3.Command;
</strong>import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ArmFeedforward;
import org.wpilib.math.system.DCMotor;
<strong>import org.wpilib.units.measure.Angle;
</strong>import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.mechanisms.Arm;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.ArmConfig;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ArmMechanism implements Mechanism {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(50, 0, 0)
      .withSimClosedLoopController(50, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the arm.
      .withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ArmFeedforward(0, 0, 0))
      .withSimFeedforward(new ArmFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the arm is when the robot turns on.
      .withStartingPosition(Degrees.of(-5))
      // The closed loop will not take the arm past these angles.
      .withSoftLimits(Degrees.of(-20), Degrees.of(30))
      // Telemetry name and how much to publish.
      .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

  private final ArmConfig armConfig = new ArmConfig()
      // The hard stops, used by the simulation.
      .withHardLimits(Degrees.of(-30), Degrees.of(40))
      // The length of the arm, used by the simulation.
      .withLength(Feet.of(3))
      // Telemetry name and how much to publish.
      .withTelemetry("Arm", TelemetryVerbosity.HIGH);

  // The arm mechanism.
  private final Arm arm = new Arm(armConfig, motor);

<strong>  /** Go to an angle and hold it. This command does not end on its own. */
</strong><strong>  public Command setAngle(Angle angle) {
</strong><strong>    return arm.setAngle(angle);
</strong><strong>  }
</strong>
<strong>  /** Go to an angle, and end once the arm is within the tolerance of it. */
</strong><strong>  public Command moveTo(Angle angle, Angle tolerance) {
</strong><strong>    return arm.runTo(angle, tolerance);
</strong><strong>  }
</strong>
<strong>  /** Drive the arm with a duty cycle from -1 to 1. The closed loop is not used. */
</strong><strong>  public Command set(double dutycycle) {
</strong><strong>    return arm.set(dutycycle);
</strong><strong>  }
</strong>
<strong>  /** Hold an angle at the lowest priority, so that any other arm command can interrupt it. */
</strong><strong>  public Command hold(Angle angle) {
</strong><strong>    return run(coroutine -> coroutine.await(arm.setAngle(angle)))
</strong><strong>        .withPriority(Command.LOWEST_PRIORITY)
</strong><strong>        .named("Arm Hold");
</strong><strong>  }
</strong>
  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
  public void periodic() {
    // Publishes the arm's telemetry, and applies anything changed through live tuning.
    arm.updateTelemetry();
  }

  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
  public void simulationPeriodic() {
    // Runs the arm's physics simulation.
    arm.simIterate();
  }
}
</code></pre>

<pre class="language-java" data-title="Robot.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.Degrees;
</strong>
import java.util.ArrayList;
import java.util.List;
import org.wpilib.command3.Scheduler;
import org.wpilib.command3.button.CommandGamepad;
import org.wpilib.framework.OpModeRobot;
import org.wpilib.system.Notifier;
import org.wpilib.telemetry.Telemetry;
import first.robot.constants.DriverConstants;
import first.robot.mechanisms.ArmMechanism;
import first.robot.mechanisms.ExampleMechanism;

public class Robot extends OpModeRobot {
  final ExampleMechanism exampleMechanism = new ExampleMechanism();
  final ArmMechanism arm = new ArmMechanism();
  final CommandGamepad exampleController =
      new CommandGamepad(DriverConstants.DRIVER_CONTROLLER_PORT);

  // The scheduler that runs every command.
  private final Scheduler scheduler = Scheduler.getDefault();
  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
  private final List&#x3C;Notifier> simulationNotifiers = new ArrayList&#x3C;>();

<strong>  public Robot() {
</strong><strong>    // When no other command is using the arm, hold it at 0 degrees.
</strong><strong>    arm.setDefaultCommand(arm.hold(Degrees.of(0)));
</strong><strong>  }
</strong>
  @Override
  public void robotPeriodic() {
    // Runs every loop, on the robot and in simulation.
    // Update the mechanism before the scheduler runs its commands.
    arm.periodic();
    scheduler.run();
    // Publish the scheduler, so that a dashboard shows which commands are running.
    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
  }

  @Override
  public void simulationInit() {
    // Runs once, when the simulation starts.
    // Run each mechanism's simulation in its own Notifier, every robot loop.
    startSimulation("Arm", arm::simulationPeriodic);
  }

  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
  private void startSimulation(String name, Runnable simulationPeriodic) {
    Notifier notifier = new Notifier(simulationPeriodic);
    notifier.setName(name + " Simulation");
    notifier.startPeriodic(getPeriod());
    simulationNotifiers.add(notifier);
  }
}
</code></pre>

<pre class="language-java" data-title="ExampleTeleop.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.Degrees;
</strong>
import org.wpilib.opmode.OpMode;
import org.wpilib.opmode.Teleop;

@Teleop
public class ExampleTeleop implements OpMode {
  public ExampleTeleop(Robot robot) {
    robot.exampleController.rightStick().whileTrue(robot.exampleMechanism.exampleCommand());

<strong>    // Hold an angle while the bottom (A) or right (B) face button is held.
</strong><strong>    robot.exampleController.faceDown().whileTrue(robot.arm.setAngle(Degrees.of(-5)));
</strong><strong>    robot.exampleController.faceRight().whileTrue(robot.arm.setAngle(Degrees.of(15)));
</strong><strong>    // Drive the arm up or down while the left (X) or top (Y) face button is held.
</strong><strong>    robot.exampleController.faceLeft().whileTrue(robot.arm.set(0.3));
</strong><strong>    robot.exampleController.faceUp().whileTrue(robot.arm.set(-0.3));
</strong>  }
}
</code></pre>

{% endtab %}

{% tab title="C++" %}
The highlighted lines are new in this step.

Declare the commands in `ArmSubsystem.hpp`, define them in `ArmSubsystem.cpp`, then create the subsystem and bind the buttons in `RobotContainer`. The template bound the right face button to its example command; that binding is replaced.

<pre class="language-cpp" data-title="include/subsystems/ArmSubsystem.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include &#x3C;optional>

#include &#x3C;rev/SparkMax.h>
<strong>#include &#x3C;wpi/commands2/CommandPtr.hpp>
</strong>#include &#x3C;wpi/commands2/SubsystemBase.hpp>
#include &#x3C;wpi/hardware/bus/CANPort.hpp>
<strong>#include &#x3C;wpi/units/angle.hpp>
</strong>
#include "yams/mechanisms/config/ArmConfig.hpp"
#include "yams/mechanisms/positional/Arm.hpp"
#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/local/SparkWrapper.hpp"

class ArmSubsystem : public wpi::cmd::SubsystemBase {
 public:
  ArmSubsystem();

<strong>  /** Go to an angle and hold it. This command does not end on its own. */
</strong><strong>  wpi::cmd::CommandPtr Run(wpi::units::degree_t angle);
</strong>
<strong>  /** Go to an angle, and end once the arm is within the tolerance of it. */
</strong><strong>  wpi::cmd::CommandPtr RunTo(wpi::units::degree_t angle, wpi::units::degree_t tolerance);
</strong>
<strong>  /** Drive the arm with a duty cycle from -1 to 1. The closed loop is not used. */
</strong><strong>  wpi::cmd::CommandPtr Set(double dutycycle);
</strong>
  void Periodic() override;
  void SimulationPeriodic() override;

 private:
  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};

  // What the motor controller should do. It is filled in by the constructor.
  yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;

  // The SmartMotorController, created in the constructor once the config is ready.
  std::optional&#x3C;yams::motorcontrollers::local::SparkWrapper> m_motor;

  // The arm mechanism and its config, also set up in the constructor.
  yams::mechanisms::config::ArmConfig m_armConfig;
  std::optional&#x3C;yams::mechanisms::positional::Arm> m_arm;
};
</code></pre>

<pre class="language-cpp" data-title="cpp/subsystems/ArmSubsystem.cpp" data-line-numbers><code class="lang-cpp">#include "subsystems/ArmSubsystem.hpp"

#include &#x3C;wpi/math/controller/ArmFeedforward.hpp>
#include &#x3C;wpi/math/system/DCMotor.hpp>
#include &#x3C;wpi/units/angle.hpp>
#include &#x3C;wpi/units/angular_acceleration.hpp>
#include &#x3C;wpi/units/angular_velocity.hpp>
#include &#x3C;wpi/units/current.hpp>
#include &#x3C;wpi/units/length.hpp>
#include &#x3C;wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;

ArmSubsystem::ArmSubsystem() {
  // What the motor controller should do: its control mode, gains, gearing and limits.
  m_smcConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // Feedback constants (PID), on the real robot and in simulation.
      .WithFeedback(50, 0, 0)
      .WithSimClosedLoopController(50, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the arm.
      .WithTrapezoidProfile(90_deg_per_s, 45_deg_per_s_sq)
      // Feedforward constants: kS, kG and kV.
      .WithFeedforward(wpi::math::ArmFeedforward{
          0_V, 0_V, wpi::units::unit_t&#x3C;wpi::math::ArmFeedforward::kv_unit>{0}})
      // Gearing from the motor rotor to the arm: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({3.0, 4.0})})
      .WithMotorInverted(false)
      .WithZeroPower(Cfg::MotorMode::BRAKE)
      .WithStatorCurrentLimit(40_A)
      // Where the arm is when the robot turns on.
      .WithStartingPosition(-5_deg)
      // The closed loop will not take the arm past these angles.
      .WithMechanismLimits(-20_deg, 30_deg)
      // Telemetry name and how much to publish.
      .WithTelemetry("ArmMotor", Cfg::TelemetryVerbosity::HIGH);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  m_motor.emplace(&#x26;m_spark, wpi::math::DCMotor::NEO(1), &#x26;m_smcConfig);

  m_armConfig
      // The hard stops, used by the simulation.
      .WithMinAngle(-30_deg)
      .WithMaxAngle(40_deg)
      // The length of the arm, used by the simulation.
      .WithArmLength(3_ft)
      // Telemetry name.
      .WithTelemetryName("Arm");

  // The arm mechanism.
  m_arm.emplace(&#x26;m_armConfig, &#x26;m_motor.value());
}

<strong>wpi::cmd::CommandPtr ArmSubsystem::Run(wpi::units::degree_t angle) {
</strong><strong>  return m_arm->Run(angle);
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr ArmSubsystem::RunTo(wpi::units::degree_t angle, wpi::units::degree_t tolerance) {
</strong><strong>  return m_arm->RunTo(angle, tolerance);
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr ArmSubsystem::Set(double dutycycle) {
</strong><strong>  return m_arm->Set(dutycycle);
</strong><strong>}
</strong>
void ArmSubsystem::Periodic() {
  // Publishes the arm's telemetry, and applies anything changed through live tuning.
  m_arm->UpdateTelemetry();
}

void ArmSubsystem::SimulationPeriodic() {
  // Runs the arm's physics simulation.
  m_arm->SimIterate();
}
</code></pre>

<pre class="language-cpp" data-title="include/RobotContainer.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include "Constants.hpp"
<strong>#include "subsystems/ArmSubsystem.hpp"
</strong>#include "subsystems/ExampleSubsystem.hpp"
#include "wpi/commands2/CommandPtr.hpp"
#include "wpi/commands2/button/CommandGamepad.hpp"

/**
 * This class is where the bulk of the robot should be declared.  Since
 * Command-based is a "declarative" paradigm, very little robot logic should
 * actually be handled in the {@link Robot} periodic methods (other than the
 * scheduler calls).  Instead, the structure of the robot (including subsystems,
 * commands, and trigger mappings) should be declared here.
 */
class RobotContainer {
 public:
  RobotContainer();

  wpi::cmd::CommandPtr GetAutonomousCommand();

 private:
  // Replace with CommandPS4Controller or CommandJoystick if needed
  wpi::cmd::CommandGamepad driverController{
      OperatorConstants::DRIVER_CONTROLLER_PORT};

  // The robot's subsystems are defined here...
  ExampleSubsystem subsystem;
<strong>  ArmSubsystem arm;
</strong>
  void ConfigureBindings();
};
</code></pre>

<pre class="language-cpp" data-title="cpp/RobotContainer.cpp" data-line-numbers><code class="lang-cpp">#include "RobotContainer.hpp"

#include "commands/Autos.hpp"
#include "commands/ExampleCommand.hpp"
#include "wpi/commands2/button/Trigger.hpp"
<strong>#include "wpi/units/angle.hpp"
</strong>
RobotContainer::RobotContainer() {
  // Initialize all of your commands and subsystems here

<strong>  // When no other command is using the arm, hold it at 0 degrees.
</strong><strong>  arm.SetDefaultCommand(arm.Run(0_deg));
</strong>
  // Configure the button bindings
  ConfigureBindings();
}

void RobotContainer::ConfigureBindings() {
  // Configure your trigger bindings here

  // Schedule `ExampleCommand` when `exampleCondition` changes to `true`
  wpi::cmd::Trigger([this] {
    return subsystem.ExampleCondition();
  }).OnTrue(ExampleCommand(&#x26;subsystem).ToPtr());

<strong>  // Hold an angle while the bottom (A) or right (B) face button is held.
</strong><strong>  driverController.FaceDown().WhileTrue(arm.Run(-5_deg));
</strong><strong>  driverController.FaceRight().WhileTrue(arm.Run(15_deg));
</strong><strong>  // Drive the arm up or down while the left (X) or top (Y) face button is held.
</strong><strong>  driverController.FaceLeft().WhileTrue(arm.Set(0.3));
</strong><strong>  driverController.FaceUp().WhileTrue(arm.Set(-0.3));
</strong>}

wpi::cmd::CommandPtr RobotContainer::GetAutonomousCommand() {
  // An example command will be run in autonomous
  return autos::ExampleAuto(&#x26;subsystem);
}
</code></pre>

{% endtab %}
{% endtabs %}

{% hint style="info" %}
These commands are helpers that start and stop the closed loop for you. If you would rather set setpoints from your own command or state machine, see [How do I write my own mechanism command?](/documentation/how-to-mechanisms/how-do-i-write-my-own-mechanism-command).
{% endhint %}

## run or runTo?

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b9bf2f3b35bcc8a63582994010075c40a1e80efe%2Fhowto-arm-run-vs-runto.gif?alt=media" alt="Animation of the same arm moving to 45 degrees with two commands, with a default command of run to 0 degrees. With run the command keeps running after the arm arrives, and the arm stays at 45 degrees. With runTo and a tolerance of 3 degrees the command ends once the arm has stayed inside the tolerance for 0.1 seconds, then the default command takes over and moves the arm back to 0 degrees."><figcaption><p><code>run()</code> keeps running until something interrupts it. <code>runTo()</code> ends at the setpoint, and the default command takes over.</p></figcaption></figure>

The buttons here use the command that never ends, because a button that is held should keep holding the arm. Use the one that ends when you need to know the arm has arrived, such as in an autonomous sequence. [When mechanism commands end](/documentation/understanding/run-vs-runto) covers the difference, and [How do I set an arm's target angle?](/documentation/how-to-mechanisms/how-to-set-an-arms-target-angle) has more examples.

## Check it

Build the code. If it builds, every button is bound. Next you run it and press them.


# Step 4: Simulate it

Run the arm in simulation and drive it with a controller.

The code from the first three steps runs on your computer exactly as it will on the robot. YAMS simulates the motor, the gearing and the arm, so the closed loop, the limits and the commands all behave the way they will on the real mechanism.

{% stepper %}
{% step %}

### Start the simulation

{% tabs %}
{% tab title="Java, Commands v2" %}
Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Simulate Robot Code**. If you are asked which extensions to run, tick **Sim GUI**.
{% endtab %}

{% tab title="Java, Commands v3" %}
Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Simulate Robot Code**. If you are asked which extensions to run, tick **Sim GUI**.

The buttons are bound in the `ExampleTeleop` op mode, so that is the op mode to run when you enable.

If the simulated mechanism never moves, check that `Robot.java` has a `simulationInit()` that calls `startSimulation(...)` for the mechanism.
{% endtab %}

{% tab title="C++" %}
Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Simulate Robot Code**. If you are asked which extensions to run, tick **Sim GUI**.

The first C++ build compiles the whole project, so it takes a few minutes. Later builds are much faster.
{% endtab %}
{% endtabs %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2F04lmc9ZfMo9DPRuEp9gh%2Fimage.png?alt=media&amp;token=de5c8905-4617-4c86-bfd9-2c4acdccac09" alt="The Sim GUI, the window that opens with the simulation, with the Robot State, System Joysticks, Joysticks and NetworkTables panels"><figcaption><p>The Sim GUI.</p></figcaption></figure>
{% endstep %}

{% step %}

### Drive it

1. Connect a controller to your computer, then drag it from **System Joysticks** to **Joystick\[0]**.
2. Open the simulated mechanism with **NetworkTables -> Mechanisms -> Arm -> mechanism**. It is named after the `withTelemetry("Arm", ...)` on the `ArmConfig`.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FHsk3IxpPpxSTFmnfYHq5%2Fimage.png?alt=media&amp;token=f597e9ff-6c33-4288-8fc1-63ef60ced3ff" alt="The NetworkTables menu of the Sim GUI, opened to the arm&#x27;s mechanism"><figcaption></figcaption></figure>

3. Resize **Arm/mechanism** to your liking.
4. Commands v3: pick the `ExampleTeleop` op mode first. Then press **Teleoperated** in **Robot State**. The controller now drives the simulated arm just as it would the real one.

No controller? The Sim GUI can use the keyboard as a joystick: drag **Keyboard 0** to **Joystick\[0]**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FIaFP0S36FJJTgv7TY5ni%2FarmTest2.gif?alt=media&amp;token=56b5f06b-7083-4134-b34b-98e36785ac9f" alt="The simulated arm in its Mechanism2d window, moving between angles as buttons are pressed"><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

## What you should see

* Before you enable, the arm starts at -5 degrees, its starting position, and drops toward its lower hard limit at -30 degrees: a disabled robot's motors get no power, in simulation too.
* When you enable, the default command takes it up to 0 degrees, level.
* Holding **A** takes it to -5 degrees, and holding **B** to 15 degrees. Let go, and it goes back to 0 degrees.
* Holding **X** drives it up, and **Y** drives it down, until the soft limits stop it.
* It sits a little below each setpoint. That is the placeholder gains: `kG` is 0, so nothing holds the arm up against gravity except `kP`. The next step fixes it.

## If it did not work

* **The arm is not in the NetworkTables menu.** Look under **Mechanisms**, not **SmartDashboard**.
* **The arm does not move.** Check the robot is enabled in **Teleoperated** and the controller is on **Joystick\[0]**. Commands v3: check `Robot.simulationInit()` starts the arm's simulation.
* **The code stops with an error when the simulation starts.** Read the first error. YAMS names the setting that is missing, such as a starting position outside the hard limits.

More problems and fixes: [Troubleshooting](/documentation/tutorials/troubleshooting).


# Step 5: Tune it

Tune the arm's gains while the simulation runs, then copy them into your code.

The gains from step 1 are placeholders: `kP` is 50 and every feedforward gain is 0. They are enough to move the arm, but it sags below its setpoint. On this page you tune them while the simulation runs, the same way you will tune the real arm in [step 6](/documentation/tutorials/arm/robot).

You change one number at a time on a dashboard and watch a graph. Nothing is saved until you copy the numbers into your code at the end.

{% hint style="info" %}
**In simulation you are tuning the simulation's gains.** While the code runs in simulation, live tuning changes the `withSimClosedLoopController` and `withSimFeedforward` values. On the real robot it changes `withClosedLoopController` and `withFeedforward`. The two sets are kept apart because a simulated arm is never exactly like the real one.
{% endhint %}

## Before you start

* Start the simulation and enable **Teleoperated**, as in [step 4](/documentation/tutorials/arm/simulate). The arm holds 0 degrees (level).
* Do not press any of the arm's buttons while you tune. A button runs another arm command, which stops live tuning. If that happens, start live tuning again.

Then tune with the YAMS Live Tuner, or by typing the values in AdvantageScope and Elastic. Both change the same values, so pick one.

{% tabs %}
{% tab title="YAMS Live Tuner" %}
The [YAMS Live Tuner](/documentation/how-to-tuning/live-tuning/live-tuner) is a web page that walks you through it: it checks the arm before anything moves, then you send setpoints and change gains while watching a graph.

{% stepper %}
{% step %}

### Connect

Open [tuning.yassrobotics.com](https://tuning.yassrobotics.com/), pick **Simulation**, and press **Connect**. If your browser asks whether the page may connect to devices on your local network, allow it.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-a69700cfe54cd00a2f7ec8e514840bf783ce65f6%2Flive-tuner-connect.png?alt=media" alt="The Live Tuner header connected to a simulation on localhost, with the robot in Teleop and enabled"><figcaption><p>Connected to the simulation, with the robot enabled in Teleop.</p></figcaption></figure>

**Check it:** the badge in the header shows `localhost`, with the robot enabled in Teleop.
{% endstep %}

{% step %}

### Pick the arm

1. Under **Telemetry name**, choose `Arm/ArmMotor`: the names from the arm's and the motor's `withTelemetry`.
2. Under **Live Tuning command**, choose `ArmSubsystem` (Commands v2 and C++) or `ArmMechanism` (Commands v3).
3. Set **Type** to **Arm**. Setpoints are in degrees.
4. Press **Continue**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-bc6ed896350eed8b9c231d8f8f93f9c94c38ac44%2Flive-tuner-tutorial-arm-mechanism.png?alt=media" alt="The Mechanism step with Arm/ArmMotor as the telemetry name, ArmSubsystem as the Live Tuning command and Arm as the type, so setpoints are in degrees"><figcaption><p>The tutorial arm: its motor, its subsystem's <code>Live Tuning</code> command, and the Arm type.</p></figcaption></figure>

**Check it:** the telemetry card shows the arm's angle, near 0 degrees.
{% endstep %}

{% step %}

### Checklist and inversions

1. Tick every item on the pre-motion checklist, leave **Current trip (A)** at 40, and press **Continue**.
2. Tick the confirmation and press **Start voltage control**.
3. Drag the voltage slider all the way to the right and hold it. The arm swings up, and with no closed loop it keeps going until its hard stop, so let go once **Positive voltage moves forward** is ticked. The slider goes back to 0 V when you let go.
4. If the arm does not move with the slider all the way to the right, select the number at the slider's right end, 1.00 V to start with, and raise it a little. The number at the left end sets how far the slider goes the other way.
5. Press **Finish check**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-61fc7cc5be03de423f245937c844114057bf3f38%2Flive-tuner-tutorial-arm-inversions.png?alt=media" alt="Holding 1 V: Positive voltage moves forward is ticked, the position reads 41.7 degrees, and Finish check is enabled"><figcaption><p>At 1 V the arm swings up, so <strong>Positive voltage moves forward</strong> is ticked.</p></figcaption></figure>

**Check it:** **Positive voltage moves forward** was ticked when the arm swung up. If the Live Tuner warns that the angle went the wrong way, the motor or encoder inversion in step 1 is wrong.
{% endstep %}

{% step %}

### Set the range of motion

Choose **Enter range manually**. The ends start at the soft limits from step 1, -20 and 30 degrees, so press **Use this range**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-9058e8a99bc5488e68a6146ca268831601e176f5%2Flive-tuner-tutorial-arm-range.png?alt=media" alt="Enter range manually chosen, with the lower end at -20.0 and the upper end at 30.0 degrees, the soft limits, and Use this range"><figcaption><p>The ends start at the arm's soft limits.</p></figcaption></figure>

**Check it:** the Live tune card opens.
{% endstep %}

{% step %}

### Start live tuning and find kG

Press **Start Live Tuning**. The setpoints and gains you send are now applied to the arm every loop.

`kG` is the voltage it takes to hold the arm level against gravity. YAMS scales it by the cosine of the angle, so the arm gets all of it when level and none when it points straight up or down. With `kG` at 0, only `kP` holds the arm up, so the arm sags a little below its setpoint.

1. On the **Setpoints** tab, drag the slider to 0 degrees and let go. The setpoint is sent when you let go.
2. Once the arm has stopped, read its output voltage on the telemetry card. For this arm it reads about `0.12`.
3. Type that voltage into **kG** on the Settings card's **Gains** tab, and press **Enter**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-93eb1a719c109ae4f53ed0ac8b56ca7c9417f709%2Flive-tuner-tutorial-arm-kg.png?alt=media" alt="Live tuning the arm at a 0 degree setpoint: the position reads 0.0 degrees and the output 0.12 V, and the measured line sits on the setpoint line"><figcaption><p>With kG at 0.12 V, the arm holds 0 degrees with no sag.</p></figcaption></figure>

**Check it:** the measured angle moves up onto the setpoint on the graph and stays there.
{% endstep %}

{% step %}

### Tune kP and kD

1. Turn on **Alternate setpoints**, with **Setpoint A** at `-5` and **Setpoint B** at `15`. The arm now moves between them every 5 seconds.
2. Watch each move on the graph and change **kP** on the **Gains** tab:
   * It is slow, or stops short: double `kP`.
   * It overshoots and swings back and forth: lower `kP` by about a third.
3. If it still overshoots a little at a `kP` that is quick enough, raise **kD** a little at a time, starting at `1`.

A change that made it worse? Press **was** under the value to put the last one back.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-0b29eba66df91e87b15d9d6a384185ec7c169348%2Flive-tuning-response.png?alt=media" alt="Three step responses: kP too low rises slowly and stops short, about right settles quickly on the setpoint, kP too high overshoots and rings"><figcaption><p>What the angle looks like on the graph after each setpoint change.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-f803a6ca64a5cc422615a456b2d2ff956fa49565%2Flive-tuner-tutorial-arm-alternate.png?alt=media" alt="Alternate setpoints on, switching between -5 and 15 degrees: the measured angle follows each step up and back down"><figcaption><p>Alternating between -5 and 15 degrees, so each change of gain can be compared with the last move.</p></figcaption></figure>

**Check it:** after each change of setpoint the arm gets there within a second or so and stops without swinging.
{% endstep %}

{% step %}

### Tune the motion profile and kV

The motion profile limits how fast the arm moves and speeds up. On the **Gains** tab, **Max velocity** and **Max acceleration** are in degrees per second, 90 and 45 from step 1, with the RPM YAMS uses shown under each.

1. With **Alternate setpoints** still on, raise **Max velocity** and **Max acceleration** a step at a time.
2. Stop raising them when the measured angle falls behind the setpoint while it moves, or the stator current on the graph jumps.
3. Raise **kV** until the measured angle follows the setpoint during a move, instead of falling behind and catching up at the end. `kV` only acts while the arm moves.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-7cafcc98b461e5b483900f411f7519a09b88087a%2Flive-tuner-tutorial-arm-gains.png?alt=media" alt="The Settings card&#x27;s Gains tab: kP 50, kG 0.12 V with was 0 under it, and Max velocity and Max accel raised to 180, with was 90 and was 45 under them and 30 RPM shown under each"><figcaption><p>Max velocity and max acceleration raised from 90 and 45 to 180. <strong>was</strong> shows the value before each change.</p></figcaption></figure>

**Check it:** the arm follows the setpoint through each move and arrives without lagging. Press **Space** to stop when you are done.
{% endstep %}
{% endstepper %}
{% endtab %}

{% tab title="AdvantageScope and Elastic" %}
You type each value into its NetworkTables key yourself, and graph the arm in AdvantageScope.

Open [AdvantageScope](https://docs.advantagescope.org/) and connect it to the simulation (**File > Connect to Simulator**).

{% stepper %}
{% step %}

### Start live tuning

YAMS gives the arm a `Live Tuning` command. While it runs, numbers you type on the dashboard are applied to the arm straight away.

* **Commands v2 and C++:** the command is published at `NT:/Tuning/ArmSubsystem/Live Tuning`, named after the subsystem. In [Elastic](https://frc-elastic.gitbook.io/docs), add `Tuning/ArmSubsystem/Live Tuning` to a tab and press its button.
* **Commands v3:** the command is published at `NT:/Tuning/ArmMechanism/Live Tuning`, named after the mechanism. Set the boolean `NT:/Tuning/ArmMechanism/Live Tuning/running` to `true`. In AdvantageScope, first turn on tuning mode (step 2), then click the value to change it.

**Check it:** the command shows as running. The arm keeps holding 0 degrees.
{% endstep %}

{% step %}

### Find the numbers and graph the arm

The arm's values are under two tables. Both use the names from `withTelemetry`: `Arm` for the arm and `ArmMotor` for its motor.

|                  | Where                          | Used for                                     |
| ---------------- | ------------------------------ | -------------------------------------------- |
| Values you type  | `NT:/Tuning/Arm/ArmMotor/`     | Gains, setpoints, limits                     |
| Values you watch | `NT:/Mechanisms/Arm/ArmMotor/` | Where the arm is and what the motor is doing |

1. In AdvantageScope, turn on **tuning mode**: the sliders icon beside the search box at the top of the sidebar. Without it, typed values are ignored.
2. Make a **Line Graph** and drag in, from `NT:/Mechanisms/Arm/ArmMotor/`:
   * `mechanism/position`: where the arm is.
   * `closedloop/setpoint/position`: where the arm is asked to be.
   * `motor/outputVoltage`: the voltage the motor is given.

{% hint style="warning" %}
**You type degrees, you read rotations.** A setpoint typed as `15` (degrees) is graphed as `0.0417` (rotations). To graph in degrees, see [See both in the same units with AdvantageScope](/documentation/reference/keys-and-units#see-both-in-the-same-units-with-advantagescope).
{% endhint %}

**Check it:** the two position lines are close together near 0, with the measured position a little below the setpoint. That gap is the sag you fix next.
{% endstep %}

{% step %}

### kG: hold the arm up

`kG` is the voltage it takes to hold the arm level against gravity. YAMS scales it by the cosine of the angle, so the arm gets all of it when level and none when it points straight up or down. That only works if 0 degrees is level, as it is in this tutorial.

With `kG` at 0, only `kP` holds the arm up. `kP` only pushes when there is an error, so the arm has to sag a little before the motor pushes hard enough. The voltage it settles at is the voltage gravity needs.

1. Let the arm settle at 0 degrees and read `motor/outputVoltage`. For this arm it reads about `0.12`.
2. Type that voltage into `NT:/Tuning/Arm/ArmMotor/closedloop/feedforward/kG`.

**Check it:** the measured position moves up onto the setpoint and stays there. The output voltage stays about the same, because `kG` now supplies it instead of `kP`.

If the arm drifts, adjust `kG` a little: up if it sits low, down if it sits high.
{% endstep %}

{% step %}

### kP and kD: reach a setpoint

`kP` is how hard the motor pushes for each rotation of error. A `kP` of 50 is 50 volts per rotation, about 0.14 volts per degree.

1. Type `15` into `NT:/Tuning/Arm/ArmMotor/closedloop/setpoint/position`. The arm moves to 15 degrees.
2. Type `-5`, then `15` again, and watch the position line each time.
3. Compare the line with the picture below and change `NT:/Tuning/Arm/ArmMotor/closedloop/feedback/kP`:
   * It is slow, or stops short: double `kP`.
   * It overshoots and swings back and forth: lower `kP` by about a third.
4. If it still overshoots a little at a `kP` that is quick enough, raise `closedloop/feedback/kD` a little at a time, starting at `1`.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-0b29eba66df91e87b15d9d6a384185ec7c169348%2Flive-tuning-response.png?alt=media" alt="Three step responses: kP too low rises slowly and stops short, about right settles quickly on the setpoint, kP too high overshoots and rings"><figcaption><p>What the position line looks like after a setpoint change.</p></figcaption></figure>

**Check it:** after each setpoint change the arm gets there within a second or so and stops without swinging.

The arm cannot go past the soft limits from step 1, -20 and 30 degrees. A setpoint beyond them is held at the limit.
{% endstep %}

{% step %}

### The motion profile and kV

The motion profile limits how fast the arm moves and speeds up: 90 degrees per second and 45 degrees per second squared from step 1. On the dashboard they are in RPM: 15 RPM and 7.5 RPM per second.

1. Raise `NT:/Tuning/Arm/ArmMotor/closedloop/motionprofile/maxVelocity` and `maxAcceleration` a step at a time while moving between `-5` and `15`.
2. Stop raising them when the measured position falls behind the setpoint while it moves, or `current/stator` jumps.
3. Add `mechanism/velocity` and `closedloop/setpoint/velocity` to the graph. Raise `closedloop/feedforward/kV` until the measured velocity follows the setpoint velocity during a move. `kV` only acts while the arm moves.

**Check it:** the measured velocity sits on top of the setpoint velocity, and the arm arrives without lagging behind.

For more on each value, see [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order).
{% endstep %}
{% endstepper %}
{% endtab %}
{% endtabs %}

## Copy the numbers into your code

Dashboard changes are lost when the code restarts. Write the numbers you ended up with into the config from step 1. In simulation they go into the `Sim` versions.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
// Before
.withSimClosedLoopController(50, 0, 0)
.withSimFeedforward(new ArmFeedforward(0, 0, 0))

// After: your numbers. ArmFeedforward takes kS, kG, kV.
.withSimClosedLoopController(80, 0, 2)
.withSimFeedforward(new ArmFeedforward(0, 0.12, 0.3))
```

{% endcode %}

Copy the motion profile limits into `withTrapezoidalProfile` too, converted back to degrees per second.
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ArmMechanism.java" %}

```java
// Before
.withSimClosedLoopController(50, 0, 0)
.withSimFeedforward(new ArmFeedforward(0, 0, 0))

// After: your numbers. ArmFeedforward takes kS, kG, kV.
.withSimClosedLoopController(80, 0, 2)
.withSimFeedforward(new ArmFeedforward(0, 0.12, 0.3))
```

{% endcode %}

Copy the motion profile limits into `withTrapezoidalProfile` too, converted back to degrees per second.
{% endtab %}

{% tab title="C++" %}
The C++ config in step 1 has a simulation PID with `WithSimClosedLoopController`, but only one feedforward, `WithFeedforward`, which simulation uses too. Copy your numbers there:

{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
// Your numbers: kP, kI, kD, then kS, kG and kV.
.WithSimClosedLoopController(80, 0, 2)
.WithFeedforward(wpi::math::ArmFeedforward{
    0_V, 0.12_V, wpi::units::unit_t<wpi::math::ArmFeedforward::kv_unit>{0.3}})
```

{% endcode %}

Copy the motion profile limits into `WithTrapezoidProfile` too, converted back to degrees per second.
{% endtab %}
{% endtabs %}

The numbers above are an example. Use the ones you found.

**Check it:** restart the simulation and enable it. The arm holds 0 degrees without sagging, and the A and B buttons move it smoothly.

## If it did not work

* **AdvantageScope: typing a value does nothing.** Turn on AdvantageScope's tuning mode, check the `Live Tuning` command is still running, and check you typed under `NT:/Tuning`, not `NT:/Mechanisms`.
* **Live Tuner: the arm is not in the Telemetry name list.** Check the simulation is running and you connected to **Simulation**. The list only fills in once the robot code has started.
* **Live tuning stopped on its own.** A button press, or the default command, took over the arm. On the Live Tuner, the current trip, leaving the range of motion, or pressing Space also stops it. Start it again.
* **The arm swings harder and harder.** `kP` is too high. Lower it, or disable and restart the simulation.
* **The numbers were gone after a restart.** They only last until the code stops. Copy them into your code, as in [Copy the numbers into your code](#copy-the-numbers-into-your-code).

More problems and fixes: [Troubleshooting](/documentation/tutorials/troubleshooting).


# Step 6: Run it on the robot

Put the arm code on the robot, check it safely, and tune it on the real arm.

The same code runs on the robot. Before you enable it, check a few things that simulation cannot tell you: that the code talks to the right motor, that it measures the arm the right way round, and that the arm starts where the code thinks it does.

{% hint style="danger" %}
**Be ready to stop the arm.** Keep everyone clear of the arm, and keep a hand on the Driver Station: **Enter** disables the robot and **Space** stops it until it is rebooted. Do every enable in this step with the arm free to move and nothing in its way.
{% endhint %}

{% stepper %}
{% step %}

### Set the CAN ID

The code talks to the `SparkMax` with CAN ID 4 (step 1, part 8).

1. Connect to the SPARK MAX with the [REV Hardware Client](https://docs.revrobotics.com/rev-hardware-client).
2. Update its firmware and set its CAN ID to `4`, or change the `4` in your code to the ID it already has.

Every device on the CAN bus needs its own ID.
{% endstep %}

{% step %}

### Put the arm at its starting position

The NEO's encoder only measures how far the motor turns, not where the arm is. When the code starts, YAMS assumes the arm is at the starting position from step 1, part 6: -5 degrees.

Before each time the robot code starts, rest the arm at that angle. Here that is 5 degrees below level.

{% hint style="warning" %}
If the arm starts somewhere else, every angle, setpoint and soft limit is off by the difference. An arm started 30 degrees too high thinks a hard stop is 30 degrees further away than it is.
{% endhint %}

Change `withStartingPosition` to wherever your arm really rests, such as on a hard stop.
{% endstep %}

{% step %}

### Deploy

Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Deploy Robot Code**.

**Check it:** the Driver Station shows robot code, and its messages show no errors about the SPARK MAX. A CAN error there means the ID or the wiring is wrong.
{% endstep %}

{% step %}

### Check the direction, with the robot disabled

Keep the robot **disabled**. YAMS still publishes where the arm is.

1. In AdvantageScope or Elastic, watch `NT:/Mechanisms/Arm/ArmMotor/mechanism/position`. It reads about `-0.014` rotations (-5 degrees).
2. Lift the arm by hand, about 45 degrees.

**Check it:**

* The value goes **up**. Positive is up, the same as in simulation.
* It goes up by about `0.125` rotations, which is 45 degrees.

If it goes down instead, set `.withMotorInverted(true)` in step 1, part 5, deploy, and check again. If it moves much more or less than 45 degrees, the gearing in step 1, part 4 does not match your arm.

{% hint style="info" %}
In brake mode the motor resists being moved, and the gearbox makes the arm stiff to lift. If you can't move it by hand, set `.withZeroPower(MotorMode.COAST)` while you check, then set it back.
{% endhint %}

Do not skip this check. If the direction is wrong, the closed loop pushes the arm away from its setpoint, faster and faster, into a hard stop.
{% endstep %}

{% step %}

### First enable

1. Put the arm back at its starting position, and restart the robot code (or deploy again).
2. Enable **Teleoperated**.

**Check it:** the default command takes the arm from -5 degrees up to 0 degrees, smoothly, and holds it there. With the placeholder gains it may sag a little below level. That is fixed in the next part.

**Disable straight away** if the arm moves fast, heads for a hard stop, or shakes. Then go back to part 4.
{% endstep %}

{% step %}

### Tune it on the robot

Tune the real arm the same way you tuned the simulation in [step 5](/documentation/tutorials/arm/tune). On the robot the dashboard changes `withClosedLoopController` and `withFeedforward`, not the `Sim` versions.

The real arm usually needs a larger `kG` than the simulation, because of the arm's real weight, and some `kS` to get past friction. To find `kS`, raise `closedloop/feedforward/kS` until the arm just starts to creep, then back it off a little.

When you are done, copy the numbers into the config:

{% tabs %}
{% tab title="Java" %}

```java
// The real robot's gains. ArmFeedforward takes kS, kG, kV.
.withClosedLoopController(60, 0, 1)
.withFeedforward(new ArmFeedforward(0.1, 1.2, 0.3))
```

{% endtab %}

{% tab title="C++" %}

```cpp
// The real robot's gains: kP, kI, kD, then kS, kG and kV.
.WithFeedback(60, 0, 1)
.WithFeedforward(wpi::math::ArmFeedforward{
    0.1_V, 1.2_V, wpi::units::unit_t<wpi::math::ArmFeedforward::kv_unit>{0.3}})
```

The C++ tutorial uses one feedforward for both, so the simulation now uses the robot's feedforward too.
{% endtab %}
{% endtabs %}

The numbers are an example. Use the ones you found.
{% endstep %}

{% step %}

### Check the soft limits

1. With live tuning running, type `30` into `NT:/Tuning/Arm/ArmMotor/closedloop/setpoint/position`.
2. The arm should stop at 30 degrees, the upper soft limit, short of the hard stop.

Do the same with `-20` for the lower soft limit. Set `withSoftLimits` in step 1 to just inside your arm's real hard stops.
{% endstep %}
{% endstepper %}

## If it did not work

* **Nothing moves, and the Driver Station shows a CAN error.** The CAN ID in the code does not match the SPARK MAX, or the CAN wiring is loose.
* **The arm runs into a hard stop as soon as it is enabled.** The direction is wrong. Disable, and redo part 4.
* **Angles are off by a fixed amount.** The arm was not at its starting position when the code started. Redo part 2.
* **Angles are off by a factor.** The gearing does not match the arm.
* **The arm sags or shakes.** Tune it, as in part 6.

More problems and fixes: [Troubleshooting](/documentation/tutorials/troubleshooting).

## Read more

Your arm works on the robot. From here:

* Keep your constants tidy as the robot grows: [Organizing configs in constants](/documentation/understanding/config-organization)
* Everything an arm can do: [Arms](/documentation/understanding/arms)


# Elevator

Learn how to program an Elevator.

{% hint style="info" %}
Two motors on one shaft or gearbox? Add the second as a follower with `withFollowers`. Two motors that aren't on the same shaft or gearbox, such as one on each side of the mechanism? Make the second a loosely coupled follower with `withLooselyCoupledFollowers`: the mechanism still works as this tutorial shows. [Followers](/documentation/reference/editor/config/followers) explains both.
{% endhint %}

## Intro

At the end of this tutorial you will have an `Elevator` that works in both real life and simulation with the same code!

{% columns %}
{% column %}

#### Simulation

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FR6PlKTmaurVX24NArs1j%2FRobot%20Simulation%202025-08-30%2018-27-07.gif?alt=media&amp;token=e9c58fd1-ad2e-4c26-a57b-0117c72fa75e" alt="The simulated elevator in its Mechanism2d window: the carriage bar rises to a height and stops there"><figcaption></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FZdaaTFAtUEcoLKsw3qzY%2FRobot%20Simulation%202025-08-30%2018-37-59.gif?alt=media&amp;token=0b4e3353-320f-4983-9309-d452471b7311" alt="The simulated elevator moving between heights as controller buttons are pressed, staying between its limit marks"><figcaption></figcaption></figure>
{% endcolumn %}

{% column %}

#### Real Life

{% embed url="<https://www.youtube.com/shorts/XKmsW8-85Dg>" %}
{% endcolumn %}
{% endcolumns %}

## Details

This `Elevator` uses the following hardware and controls:

* A `SparkMax` driving one NEO controls the `Elevator`
* A `12:1` gearbox on the `Elevator`
* \#25 chain on a 22 tooth sprocket lifts the carriage
* Holding the bottom face button (`A` on an Xbox controller) takes the `Elevator` to 0.5 m
* Holding the right face button (`B` on an Xbox controller) takes the `Elevator` to 1 m
* Holding the left face button (`X` on an Xbox controller) drives the `Elevator` up
* Holding the top face button (`Y` on an Xbox controller) drives the `Elevator` down
* With no button held, the `Elevator` goes to 0 m

## The steps

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-687757197fc8fe13eab19c2a9137189198db0822%2Ftutorial-elevator-steps.png?alt=media" alt="The four steps of the elevator tutorial, each building on the one before. Step 1, the motor controller: a SparkMax and a SmartMotorControllerConfig. Step 2, the elevator: an ElevatorConfig and the SmartMotorController. Step 3, commands and buttons: run and set commands bound to a controller. Step 4, simulation: the same code run on your computer."><figcaption><p>The first four steps, one page each. Then you tune it and run it on the robot.</p></figcaption></figure>

Every step has a tab for **Java with Commands v2**, **Java with Commands v3** and **C++**.

| Step                                                                               | What you do                                                                                   |
| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| [Before you start](/documentation/tutorials/project-setup)                         | Create a WPILib project and install YAMS and REVLib. Skip this if you already have a project. |
| [Step 1: The motor controller](/documentation/tutorials/elevator/motor-controller) | Configure the `SparkMax` and wrap it in a `SmartMotorController`.                             |
| [Step 2: The elevator](/documentation/tutorials/elevator/mechanism)                | Describe the elevator with an `ElevatorConfig` and create the `Elevator`.                     |
| [Step 3: Commands and buttons](/documentation/tutorials/elevator/commands)         | Turn the `Elevator` into commands and bind them to controller buttons.                        |
| [Step 4: Simulate it](/documentation/tutorials/elevator/simulate)                  | Run the code on your computer and drive the elevator with a controller.                       |
| [Step 5: Tune it](/documentation/tutorials/elevator/tune)                          | Find `kG`, `kP` and the profile while the simulation runs, and copy them into your code.      |
| [Step 6: Run it on the robot](/documentation/tutorials/arm/robot)                  | The arm's robot step, with the elevator differences listed at the end of step 5.              |

## Complete Example

The following files show a complete, working Elevator from the YAMS `simple_robot-2027` Commands v2 example. It uses an exponential profile instead of the trapezoidal profile in this tutorial.

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/ElevatorSubsystem.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/RobotContainer.java>" %}

The same robot in the other two flavors:

* **Java, Commands v3:** [`mechanisms/ElevatorMechanism.java`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/simple_robot-2027/src/main/java/first/robot/mechanisms/ElevatorMechanism.java) in `examples/commands3/simple_robot-2027`
* **C++:** [`ElevatorSubsystem.h`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/include/subsystems/ElevatorSubsystem.h) and [`ElevatorSubsystem.cpp`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/cpp/subsystems/ElevatorSubsystem.cpp) in `examples/cpptest`


# Step 1: The motor controller

Configure the SparkMax and wrap it in a SmartMotorController.

{% hint style="info" %}
This page assumes a project with YAMS and REVLib installed. If you do not have one yet, start at [Create a project and install YAMS](/documentation/tutorials/project-setup).
{% endhint %}

{% hint style="info" %}
**Did the arm tutorial?** This step is the same as [the arm's step 1](/documentation/tutorials/arm/motor-controller), except:

* **The sprocket or drum** (part 2) is new. It tells YAMS how far the carriage moves for each turn, so that you can work in meters.
* **Linear units.** The motion profile, starting position and soft limits are in meters and meters per second, not degrees.
* **`ElevatorFeedforward`** replaces `ArmFeedforward`. Its `kG` is the same at every height, because gravity pulls the carriage straight down wherever it is.
* **Cascading elevators** divide the gearing by the number of stages (part 5).

Skim the parts you know and read those four.
{% endhint %}

A `SmartMotorController` is how YAMS talks to a motor controller. It takes three things:

1. **The vendor's motor controller object**, here a `SparkMax`.
2. **The motor** that is plugged into it, here one NEO.
3. **A `SmartMotorControllerConfig`** that says what the motor controller should do: its control mode, its PID and feedforward gains, its motion profile, the gearing between the motor and the sprocket, how far the carriage moves for each turn of the sprocket, where the carriage starts, and how far the closed loop may take it.

YAMS applies the config to the `SparkMax` for you, and uses the same config to build the simulation.

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

## Create the file

{% tabs %}
{% tab title="Java, Commands v2" %}
Create `ElevatorSubsystem.java` in the `subsystems` folder, next to the template's `ExampleSubsystem.java`.
{% endtab %}

{% tab title="Java, Commands v3" %}
Create `ElevatorMechanism.java` in the `mechanisms` folder, next to the template's `ExampleMechanism.java`.

The config comes from `yams.commands3.config`, and it takes the `Mechanism` where Commands v2 passes the subsystem.
{% endtab %}

{% tab title="C++" %}
Create `ElevatorSubsystem.hpp` in `src/main/include/subsystems` and `ElevatorSubsystem.cpp` in `src/main/cpp/subsystems`.

YAMS keeps a pointer to the config and to the `SparkMax`, so in C++ both are members of the subsystem. The constructor fills in the config and then creates the `SmartMotorController`, which is why that one is a `std::optional`.

`WithFeedback` is the C++ name of `withClosedLoopController`, `WithMotorGearing` of `withGearing`, `WithLinearTrapezoidProfile` of the linear `withTrapezoidalProfile`, and `WithMeasurementLimits` of the linear `withSoftLimits`. The sprocket is described with `WithMechanismCircumference(pitch, teeth)` where Java uses `withDrumRadius(pitch, teeth)`.
{% endtab %}
{% endtabs %}

{% stepper %}
{% step %}

### Start the config

Everything the motor controller should do goes into one `SmartMotorControllerConfig`. Start it, and put it in closed loop mode so that it can hold a position.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// What the motor controller should do: its control mode, gains, gearing and limits.
private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// What the motor controller should do: its control mode, gains, gearing and limits.
private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ElevatorSubsystem.hpp" %}

```cpp
// What the motor controller should do. It is filled in by the constructor.
yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;
```

{% endcode %}

{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
// What the motor controller should do: its control mode, gains, gearing and limits.
m_smcConfig
    .WithSubsystem(this)
    .WithClosedLoopMode()
```

{% endcode %}
{% endtab %}
{% endtabs %}

Want the details? [Motor basics](/documentation/reference/editor/config/motor-basics)
{% endstep %}

{% step %}

### The sprocket or drum

An elevator has to know how far the carriage moves for each turn of the output shaft. Without it YAMS cannot turn rotations into a height.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-898d5376582d6de685136b38acf1881c8c42e59b%2Fhowto-mechanism-circumference.gif?alt=media" alt="Animation of a 4 inch drum and a 22 tooth sprocket on 0.25 inch pitch chain, each turning two rotations. The drum moves its cable 12.57 inches per rotation, 25.13 inches in total. The sprocket moves its chain 5.50 inches per rotation, 11 inches in total."><figcaption><p>Each rotation of the mechanism moves it by one circumference.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// How far the carriage moves for each turn of the output shaft:
// #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
// so one turn moves the chain pitch x teeth = 5.5 inches.
.withDrumRadius(Inches.of(0.25), 22)
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// How far the carriage moves for each turn of the output shaft:
// #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
// so one turn moves the chain pitch x teeth = 5.5 inches.
.withDrumRadius(Inches.of(0.25), 22)
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
// How far the carriage moves for each turn of the output shaft:
// #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
// so one turn moves the chain pitch x teeth = 5.5 inches.
.WithMechanismCircumference(0.25_in, 22)
```

{% endcode %}
{% endtab %}
{% endtabs %}

`withDrumRadius(pitch, teeth)` works the radius out from the chain for you: one turn of the sprocket moves the chain one pitch per tooth, 0.25 inch x 22 = 5.5 inches here.

**For your robot:** Use your own chain pitch and tooth count, or the radius of your drum:

{% tabs %}
{% tab title="Java, Commands v2" %}

```java
.withDrumRadius(Inches.of(0.25), 22)   // #25 chain (0.25 inch pitch), 22 tooth sprocket
.withDrumRadius(Inches.of(0.375), 16)  // #35 chain (0.375 inch pitch), 16 tooth sprocket
.withDrumRadius(Inches.of(0.875))      // a spool or drum with a 0.875 inch radius
```

{% endtab %}

{% tab title="Java, Commands v3" %}

```java
.withDrumRadius(Inches.of(0.25), 22)   // #25 chain (0.25 inch pitch), 22 tooth sprocket
.withDrumRadius(Inches.of(0.375), 16)  // #35 chain (0.375 inch pitch), 16 tooth sprocket
.withDrumRadius(Inches.of(0.875))      // a spool or drum with a 0.875 inch radius
```

{% endtab %}

{% tab title="C++" %}

```cpp
.WithMechanismCircumference(0.25_in, 22)   // #25 chain (0.25 inch pitch), 22 tooth sprocket
.WithMechanismCircumference(0.375_in, 16)  // #35 chain (0.375 inch pitch), 16 tooth sprocket
.WithMechanismRadius(0.875_in)             // a spool or drum with a 0.875 inch radius
```

{% endtab %}
{% endtabs %}

Want the details? [How do I find my mechanism's circumference?](/documentation/how-to-motor-controllers-and-sensors/how-to-find-your-mechanism-circumference)
{% endstep %}

{% step %}

### PID and feedforward

The PID gains correct the difference between where the elevator is and where you asked it to be. The feedforward supplies the voltage you already know it needs. The `Sim` options are used only in simulation, so the simulation can be tuned without touching the real robot's gains.

**Gravity on an elevator.** Gravity always pulls the carriage down with the same force, at the bottom, in the middle or at the top. So the motor needs the same voltage just to hold it still at any height. That voltage is `kG`, the middle number of `ElevatorFeedforward(kS, kG, kV)`. (An arm is different: its `kG` shrinks as it points up or down.)

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// Feedback constants (PID), on the real robot and in simulation.
.withClosedLoopController(4, 0, 0)
.withSimClosedLoopController(4, 0, 0)

// Feedforward constants, on the real robot and in simulation.
.withFeedforward(new ElevatorFeedforward(0, 0, 0))
.withSimFeedforward(new ElevatorFeedforward(0, 0, 0))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// Feedback constants (PID), on the real robot and in simulation.
.withClosedLoopController(4, 0, 0)
.withSimClosedLoopController(4, 0, 0)

// Feedforward constants, on the real robot and in simulation.
.withFeedforward(new ElevatorFeedforward(0, 0, 0))
.withSimFeedforward(new ElevatorFeedforward(0, 0, 0))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
// Feedback constants (PID), on the real robot and in simulation.
.WithFeedback(4, 0, 0)
.WithSimClosedLoopController(4, 0, 0)

// Feedforward constants (kS, kG and kV), on the real robot and in simulation.
.WithFeedforward(wpi::math::ElevatorFeedforward{
    0_V, 0_V, wpi::units::unit_t<wpi::math::ElevatorFeedforward::kv_unit>{0}})
.WithSimFeedforward(wpi::math::ElevatorFeedforward{
    0_V, 0_V, wpi::units::unit_t<wpi::math::ElevatorFeedforward::kv_unit>{0}})
```

{% endcode %}
{% endtab %}
{% endtabs %}

These gains are **placeholders**. `kP` of 4 is 4 volts for each meter of error, and every feedforward gain is 0.

**What to expect with them:** the elevator moves, but with `kG` at 0 only `kP` holds the carriage up. `kP` only pushes when the carriage is below its setpoint, so the carriage sags: in simulation it settles roughly 15 cm below each setpoint. That is expected. You find `kG` in [Step 5: Tune it](/documentation/tutorials/elevator/tune), and the sag goes away.

**For your robot:** Leave these numbers for now, and tune them in step 5.

Want the details? [Closed loop control](/documentation/reference/editor/config/closed-loop-control) and [Feedforward](/documentation/reference/editor/config/feedforward)
{% endstep %}

{% step %}

### Motion profile

The profile caps how fast the elevator may move and accelerate on its way to a setpoint, so that it glides there instead of lunging.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// The fastest the closed loop is allowed to move and accelerate the carriage.
.withTrapezoidalProfile(MetersPerSecond.of(0.5), MetersPerSecondPerSecond.of(0.5))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// The fastest the closed loop is allowed to move and accelerate the carriage.
.withTrapezoidalProfile(MetersPerSecond.of(0.5), MetersPerSecondPerSecond.of(0.5))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
// The fastest the closed loop is allowed to move and accelerate the carriage.
.WithLinearTrapezoidProfile(0.5_mps, 0.5_mps_sq)
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Start slow. Raise the two numbers once the mechanism moves safely.

Want the details? [Motion profiles](/documentation/reference/editor/config/motion-profiles)
{% endstep %}

{% step %}

### Gearing

The gearing tells YAMS how many turns of the motor make one turn of the sprocket.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-74ee72576d43ddbb20cacb97d8296685d989a195%2Ftutorial-gearing.gif?alt=media" alt="Animation of a motor rotor turning 12 times while the mechanism it drives through a 3 to 1 stage and a 4 to 1 stage, 12 to 1 in total, turns once. Counters show the motor rotations and the mechanism rotations and angle."><figcaption><p>With 12:1 gearing, twelve rotations of the motor are one rotation of the mechanism.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
.withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
.withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
// Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
.WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({3.0, 4.0})})
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** List your gearbox stages in order, from the motor outward. `3, 4` here is a 3:1 stage followed by a 4:1 stage.

**Cascading elevator?** In a cascading elevator each stage rides on the one below, so the top carriage moves faster than the chain. Add the number of stages right **after** `withGearing`. It divides the gearing that is already set, so put before `withGearing` it would be overwritten:

{% tabs %}
{% tab title="Java" %}

```java
.withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
// A two stage cascading elevator: divides the 12:1 gearing above by 2.
.withCascadingElevatorStages(2)
```

{% endtab %}

{% tab title="C++" %}

```cpp
.WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({3.0, 4.0})})
// A two stage cascading elevator: divides the 12:1 gearing above by 2.
.WithCascadingElevatorStages(2)
```

{% endtab %}
{% endtabs %}

Skip this for a continuous elevator, like the one in this tutorial.

Want the details? [Gearing and units](/documentation/reference/editor/config/gearing-and-units)
{% endstep %}

{% step %}

### Direction, idle mode and current limit

Which way is positive, what the motor does when it is given no power, and the most current it may draw.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
.withMotorInverted(false)
.withZeroPower(MotorMode.BRAKE)
.withStatorCurrentLimit(Amps.of(40))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
.withMotorInverted(false)
.withZeroPower(MotorMode.BRAKE)
.withStatorCurrentLimit(Amps.of(40))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
.WithMotorInverted(false)
.WithZeroPower(Cfg::MotorMode::BRAKE)
.WithStatorCurrentLimit(40_A)
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Flip the inversion if a positive output moves your elevator the wrong way. Keep the current limit within what your wiring and breaker allow.

Want the details? [Motor basics](/documentation/reference/editor/config/motor-basics) and [Limits and protection](/documentation/reference/editor/config/limits-and-protection)
{% endstep %}

{% step %}

### Starting position and soft limits

The starting position is where the elevator is when the robot turns on. The soft limits are as far as the closed loop is allowed to take it.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b4934b97bacb73e6df57d1dc94e5c782997037e8%2Fsmc-soft-limits.png?alt=media" alt="A bar showing a mechanism&#x27;s travel between two hard stops, with a lower and an upper soft limit a little inside them. The mechanism may move between the soft limits. A setpoint asked for beyond the upper limit is moved back to the limit."><figcaption><p>Soft limits sit a little inside the hard stops.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// Where the carriage is when the robot turns on.
.withStartingPosition(Meters.of(0))
// The closed loop will not take the carriage past these heights.
.withSoftLimits(Meters.of(0), Meters.of(2))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// Where the carriage is when the robot turns on.
.withStartingPosition(Meters.of(0))
// The closed loop will not take the carriage past these heights.
.withSoftLimits(Meters.of(0), Meters.of(2))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
// Where the carriage is when the robot turns on.
.WithStartingPosition(0_m)
// The closed loop will not take the carriage past these heights.
.WithMeasurementLimits(0_m, 2_m)
```

{% endcode %}
{% endtab %}
{% endtabs %}

Both take meters, so they need the sprocket from part 2 first: YAMS uses its circumference to turn meters into rotations. That is why `withDrumRadius` comes earlier in the config. In C++, `WithStartingPosition(meters)` and `WithMeasurementLimits` throw an error if `WithMechanismCircumference` has not been called yet, and in Java `withStartingPosition(meters)` and `withSoftLimits(meters)` do the same without `withDrumRadius`.

The lower soft limit here is 0 m, the same as the bottom hard stop and the starting height. That is on purpose: the carriage rests on the bottom stop, and the default command parks it there, so the closed loop never asks for a height below it.

**For your robot:** Set the starting position to where your carriage really rests when the robot turns on, and the upper soft limit a little below the top hard stop. If your carriage pushes into the bottom stop when it parks, raise the lower soft limit and the parking height a little, such as 0.02 m.

Want the details? [Limits and protection](/documentation/reference/editor/config/limits-and-protection)
{% endstep %}

{% step %}

### Telemetry

The name the motor gets on your dashboard, and how much it publishes. `HIGH` publishes everything, which is what you want while tuning.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// Telemetry name and how much to publish.
.withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// Telemetry name and how much to publish.
.withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
// Telemetry name and how much to publish.
.WithTelemetry("ElevatorMotor", Cfg::TelemetryVerbosity::HIGH);
```

{% endcode %}
{% endtab %}
{% endtabs %}

Want the details? [Telemetry](/documentation/understanding/telemetry)
{% endstep %}

{% step %}

### The motor controller object

This is the vendor's own object, exactly as you would create it without YAMS.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// The vendor motor controller object: a SPARK MAX with CAN ID 4.
private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// The vendor motor controller object: a SPARK MAX with CAN ID 4.
private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ElevatorSubsystem.hpp" %}

```cpp
// The vendor motor controller object: a SPARK MAX with CAN ID 4.
rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the CAN ID to yours. Using a different motor controller? See the [feature matrix](/documentation/reference/editor/feature-matrix) for the wrapper that goes with it.
{% endstep %}

{% step %}

### The SmartMotorController

The wrapper brings the three together: the motor controller object, the motor plugged into it, and the config.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ElevatorSubsystem.hpp" %}

```cpp
// The SmartMotorController, created in the constructor once the config is ready.
std::optional<yams::motorcontrollers::local::SparkWrapper> m_motor;
```

{% endcode %}

{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
// The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
m_motor.emplace(&m_spark, wpi::math::DCMotor::NEO(1), &m_smcConfig);
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the motor to the kind and the number of motors you have.

Want the details? [Smart motor controllers](/documentation/reference/editor)
{% endstep %}
{% endstepper %}

## The complete file

Every part above, in one file, with its imports.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" lineNumbers="true" %}

```java
package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Meters;
import static org.wpilib.units.Units.MetersPerSecond;
import static org.wpilib.units.Units.MetersPerSecondPerSecond;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ElevatorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ElevatorSubsystem extends SubsystemBase {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // How far the carriage moves for each turn of the output shaft:
      // #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
      // so one turn moves the chain pitch x teeth = 5.5 inches.
      .withDrumRadius(Inches.of(0.25), 22)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(4, 0, 0)
      .withSimClosedLoopController(4, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the carriage.
      .withTrapezoidalProfile(MetersPerSecond.of(0.5), MetersPerSecondPerSecond.of(0.5))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ElevatorFeedforward(0, 0, 0))
      .withSimFeedforward(new ElevatorFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the carriage is when the robot turns on.
      .withStartingPosition(Meters.of(0))
      // The closed loop will not take the carriage past these heights.
      .withSoftLimits(Meters.of(0), Meters.of(2))
      // Telemetry name and how much to publish.
      .withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" lineNumbers="true" %}

```java
package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Meters;
import static org.wpilib.units.Units.MetersPerSecond;
import static org.wpilib.units.Units.MetersPerSecondPerSecond;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ElevatorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands3.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ElevatorMechanism implements Mechanism {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // How far the carriage moves for each turn of the output shaft:
      // #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
      // so one turn moves the chain pitch x teeth = 5.5 inches.
      .withDrumRadius(Inches.of(0.25), 22)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(4, 0, 0)
      .withSimClosedLoopController(4, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the carriage.
      .withTrapezoidalProfile(MetersPerSecond.of(0.5), MetersPerSecondPerSecond.of(0.5))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ElevatorFeedforward(0, 0, 0))
      .withSimFeedforward(new ElevatorFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the carriage is when the robot turns on.
      .withStartingPosition(Meters.of(0))
      // The closed loop will not take the carriage past these heights.
      .withSoftLimits(Meters.of(0), Meters.of(2))
      // Telemetry name and how much to publish.
      .withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ElevatorSubsystem.hpp" lineNumbers="true" %}

```cpp
#pragma once

#include <optional>

#include <rev/SparkMax.h>
#include <wpi/commands2/SubsystemBase.hpp>
#include <wpi/hardware/bus/CANPort.hpp>

#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/local/SparkWrapper.hpp"

class ElevatorSubsystem : public wpi::cmd::SubsystemBase {
 public:
  ElevatorSubsystem();

 private:
  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};

  // What the motor controller should do. It is filled in by the constructor.
  yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;

  // The SmartMotorController, created in the constructor once the config is ready.
  std::optional<yams::motorcontrollers::local::SparkWrapper> m_motor;
};
```

{% endcode %}

{% code title="cpp/subsystems/ElevatorSubsystem.cpp" lineNumbers="true" %}

```cpp
#include "subsystems/ElevatorSubsystem.hpp"

#include <wpi/math/controller/ElevatorFeedforward.hpp>
#include <wpi/math/system/DCMotor.hpp>
#include <wpi/units/acceleration.hpp>
#include <wpi/units/current.hpp>
#include <wpi/units/length.hpp>
#include <wpi/units/velocity.hpp>
#include <wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;

ElevatorSubsystem::ElevatorSubsystem() {
  // What the motor controller should do: its control mode, gains, gearing and limits.
  m_smcConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // How far the carriage moves for each turn of the output shaft:
      // #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
      // so one turn moves the chain pitch x teeth = 5.5 inches.
      .WithMechanismCircumference(0.25_in, 22)
      // Feedback constants (PID), on the real robot and in simulation.
      .WithFeedback(4, 0, 0)
      .WithSimClosedLoopController(4, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the carriage.
      .WithLinearTrapezoidProfile(0.5_mps, 0.5_mps_sq)
      // Feedforward constants (kS, kG and kV), on the real robot and in simulation.
      .WithFeedforward(wpi::math::ElevatorFeedforward{
          0_V, 0_V, wpi::units::unit_t<wpi::math::ElevatorFeedforward::kv_unit>{0}})
      .WithSimFeedforward(wpi::math::ElevatorFeedforward{
          0_V, 0_V, wpi::units::unit_t<wpi::math::ElevatorFeedforward::kv_unit>{0}})
      // Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({3.0, 4.0})})
      .WithMotorInverted(false)
      .WithZeroPower(Cfg::MotorMode::BRAKE)
      .WithStatorCurrentLimit(40_A)
      // Where the carriage is when the robot turns on.
      .WithStartingPosition(0_m)
      // The closed loop will not take the carriage past these heights.
      .WithMeasurementLimits(0_m, 2_m)
      // Telemetry name and how much to publish.
      .WithTelemetry("ElevatorMotor", Cfg::TelemetryVerbosity::HIGH);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  m_motor.emplace(&m_spark, wpi::math::DCMotor::NEO(1), &m_smcConfig);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Read more

Every option used here has its own section in the `SmartMotorControllerConfig` pages:

* [Motor basics](/documentation/reference/editor/config/motor-basics): control mode, inversion, what the motor does at zero power
* [Gearing and units](/documentation/reference/editor/config/gearing-and-units): gearing, and how rotations become distance
* [Closed loop control](/documentation/reference/editor/config/closed-loop-control), [Feedforward](/documentation/reference/editor/config/feedforward) and [Motion profiles](/documentation/reference/editor/config/motion-profiles)
* [Limits and protection](/documentation/reference/editor/config/limits-and-protection): soft limits and current limits
* [Simulation](/documentation/reference/editor/config/simulation): the simulation only gains

The PID and feedforward numbers on this page are a place to start, not tuned values. You tune them in [Step 5: Tune it](/documentation/tutorials/elevator/tune).

## Check it

Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Build Robot Code**. It should build. Nothing moves yet, because nothing tells the motor what to do.

* **`SparkMax` or `SparkWrapper` cannot be found:** REVLib is not installed. See [Install your motor controller's library](/documentation/tutorials/project-setup#install-your-motor-controllers-library).
* **`SmartMotorControllerConfig` cannot be found:** YAMS is not installed, or the import is from the other command framework (`yams.commands2` or `yams.commands3`).


# Step 2: The elevator

Describe the elevator and create the Elevator mechanism.

The `SmartMotorController` from step 1 is configured, but nothing tells it to move yet. An `Elevator` adds what makes it an elevator: a physics simulation, a drawing of the mechanism for your dashboard, and the commands and triggers you will use in step 3.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-9ac4402ed53c7caf15787f40f7a6245c3ef8a7c2%2Fmech-two-configs.png?alt=media" alt="A diagram. A mechanism config, which says what the mechanism is, such as its length, mass, hard stops and how it is drawn, and a SmartMotorControllerConfig, which says how its motor behaves, such as gearing, PID, feedforward, soft limits and current, both go into the mechanism class. The mechanism then drives the simulation&#x27;s physics and Mechanism2d, and the real robot&#x27;s commands and telemetry."><figcaption><p>Two configs go into one mechanism.</p></figcaption></figure>

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

{% stepper %}
{% step %}

### Describe the elevator

`ElevatorConfig` describes the elevator itself: its hard limits and the weight of its carriage. The simulation uses both. The hard limits are where the carriage physically stops, which is different from the soft limits you set in step 1.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-3cf96dd36e04b25ad3da7b5d3a40e3730be81724%2Ftutorial-elevator-heights.png?alt=media" alt="A side view of the elevator and the heights used in this tutorial. The hard limits are 0 and 3 meters: where the carriage physically stops, set on ElevatorConfig and used by the simulation. The soft limits are 0 and 2 meters: as far as the closed loop will go, set on SmartMotorControllerConfig. Inside them are the setpoints: 0.5 meters for the A button, 1 meter for the B button, and 0 meters for the default command, which is also where the carriage starts."><figcaption><p>The soft limits from step 1 sit inside the hard limits from this step.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
private final ElevatorConfig elevatorConfig = new ElevatorConfig()
    // The hard stops, used by the simulation.
    .withHardLimits(Meters.of(0), Meters.of(3))
    // The weight of the carriage and everything on it, used by the simulation.
    .withCarriageWeight(Pounds.of(16))
    // Telemetry name and how much to publish.
    .withTelemetry("Elevator", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
private final ElevatorConfig elevatorConfig = new ElevatorConfig()
    // The hard stops, used by the simulation.
    .withHardLimits(Meters.of(0), Meters.of(3))
    // The weight of the carriage and everything on it, used by the simulation.
    .withCarriageWeight(Pounds.of(16))
    // Telemetry name and how much to publish.
    .withTelemetry("Elevator", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ElevatorSubsystem.hpp" %}

```cpp
// The elevator mechanism and its config, also set up in the constructor.
yams::mechanisms::config::ElevatorConfig m_elevatorConfig;
std::optional<yams::mechanisms::positional::Elevator> m_elevator;
```

{% endcode %}

{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
m_elevatorConfig
    // The hard stops, used by the simulation.
    .WithMinimumHeight(0_m)
    .WithMaximumHeight(3_m)
    // The weight of the carriage and everything on it, used by the simulation.
    .WithCarriageMass(16_lb)
    // Telemetry name.
    .WithTelemetryName("Elevator");
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Set where your carriage's hard stops are, and what the carriage weighs with everything that rides on it.

Want the details? [Elevators](/documentation/understanding/elevators) and [ElevatorConfig](/documentation/reference/mechanism-configs/elevator-config)
{% endstep %}

{% step %}

### Create the Elevator

Hand the config, and the `SmartMotorController` from step 1, to the `Elevator`.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// The elevator mechanism.
private final Elevator elevator = new Elevator(elevatorConfig, motor);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// The elevator mechanism.
private final Elevator elevator = new Elevator(elevatorConfig, motor);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
// The elevator mechanism.
m_elevator.emplace(&m_elevatorConfig, &m_motor.value());
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}

### Update it every loop

Two calls keep the mechanism alive. `updateTelemetry()` publishes its telemetry and applies anything you change through live tuning. `simIterate()` runs the physics simulation, and only needs to run in simulation.

In Commands v2 and C++ the scheduler calls a subsystem's periodic methods for you, so there is nothing more to do.

In Commands v3 nothing calls a `Mechanism` every loop, so `Robot.java` does it, the same way as in [the arm tutorial's step 2](/documentation/tutorials/arm/mechanism#update-it-every-loop), which explains each part. Every mechanism gets one line in `robotPeriodic()`, before `scheduler.run()`, and one in `simulationInit()`.

If your `Robot.java` already has `simulationInit()` and `startSimulation(...)` from the arm tutorial, add the lines below. If not, copy the whole `Robot.java` from the Commands v3 tab of [the complete file](#the-complete-file).

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
@Override
public void periodic() {
  // Publishes the elevator's telemetry, and applies anything changed through live tuning.
  elevator.updateTelemetry();
}

@Override
public void simulationPeriodic() {
  // Runs the elevator's physics simulation.
  elevator.simIterate();
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
/** Call this from Robot.robotPeriodic(), before the scheduler runs. */
public void periodic() {
  // Publishes the elevator's telemetry, and applies anything changed through live tuning.
  elevator.updateTelemetry();
}

/** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
public void simulationPeriodic() {
  // Runs the elevator's physics simulation.
  elevator.simIterate();
}
```

{% endcode %}

{% code title="Robot.java" %}

```java
import first.robot.mechanisms.ElevatorMechanism;

// A field of Robot.
final ElevatorMechanism elevator = new ElevatorMechanism();

// In robotPeriodic(), before scheduler.run():
elevator.periodic();

// In simulationInit():
startSimulation("Elevator", elevator::simulationPeriodic);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ElevatorSubsystem.hpp" %}

```cpp
void Periodic() override;
void SimulationPeriodic() override;
```

{% endcode %}

{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
void ElevatorSubsystem::Periodic() {
  // Publishes the elevator's telemetry, and applies anything changed through live tuning.
  m_elevator->UpdateTelemetry();
}

void ElevatorSubsystem::SimulationPeriodic() {
  // Runs the elevator's physics simulation.
  m_elevator->SimIterate();
}
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
The highlighted lines are new in this step.

`ElevatorSubsystem` extends `SubsystemBase`, so the scheduler calls `periodic()` and `simulationPeriodic()` for you.

<pre class="language-java" data-title="subsystems/ElevatorSubsystem.java" data-line-numbers><code class="lang-java">package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Meters;
import static org.wpilib.units.Units.MetersPerSecond;
import static org.wpilib.units.Units.MetersPerSecondPerSecond;
<strong>import static org.wpilib.units.Units.Pounds;
</strong>
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ElevatorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands2.config.SmartMotorControllerConfig;
<strong>import yams.commands2.mechanisms.Elevator;
</strong>import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
<strong>import yams.core.mechanisms.config.ElevatorConfig;
</strong>import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ElevatorSubsystem extends SubsystemBase {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // How far the carriage moves for each turn of the output shaft:
      // #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
      // so one turn moves the chain pitch x teeth = 5.5 inches.
      .withDrumRadius(Inches.of(0.25), 22)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(4, 0, 0)
      .withSimClosedLoopController(4, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the carriage.
      .withTrapezoidalProfile(MetersPerSecond.of(0.5), MetersPerSecondPerSecond.of(0.5))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ElevatorFeedforward(0, 0, 0))
      .withSimFeedforward(new ElevatorFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the carriage is when the robot turns on.
      .withStartingPosition(Meters.of(0))
      // The closed loop will not take the carriage past these heights.
      .withSoftLimits(Meters.of(0), Meters.of(2))
      // Telemetry name and how much to publish.
      .withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

<strong>  private final ElevatorConfig elevatorConfig = new ElevatorConfig()
</strong><strong>      // The hard stops, used by the simulation.
</strong><strong>      .withHardLimits(Meters.of(0), Meters.of(3))
</strong><strong>      // The weight of the carriage and everything on it, used by the simulation.
</strong><strong>      .withCarriageWeight(Pounds.of(16))
</strong><strong>      // Telemetry name and how much to publish.
</strong><strong>      .withTelemetry("Elevator", TelemetryVerbosity.HIGH);
</strong>
<strong>  // The elevator mechanism.
</strong><strong>  private final Elevator elevator = new Elevator(elevatorConfig, motor);
</strong>
<strong>  @Override
</strong><strong>  public void periodic() {
</strong><strong>    // Publishes the elevator's telemetry, and applies anything changed through live tuning.
</strong><strong>    elevator.updateTelemetry();
</strong><strong>  }
</strong>
<strong>  @Override
</strong><strong>  public void simulationPeriodic() {
</strong><strong>    // Runs the elevator's physics simulation.
</strong><strong>    elevator.simIterate();
</strong><strong>  }
</strong>}
</code></pre>

{% endtab %}

{% tab title="Java, Commands v3" %}
The highlighted lines are new in this step.

Nothing calls a periodic method on a Commands v3 `Mechanism`, so give the class its own `periodic()` and `simulationPeriodic()` and create the mechanism in `Robot.java`. Then call its `periodic()` from `Robot.robotPeriodic()`, before the scheduler runs, and start its `simulationPeriodic()` in its own `Notifier` from `Robot.simulationInit()`.

<pre class="language-java" data-title="mechanisms/ElevatorMechanism.java" data-line-numbers><code class="lang-java">package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Meters;
import static org.wpilib.units.Units.MetersPerSecond;
import static org.wpilib.units.Units.MetersPerSecondPerSecond;
<strong>import static org.wpilib.units.Units.Pounds;
</strong>
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ElevatorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands3.config.SmartMotorControllerConfig;
<strong>import yams.commands3.mechanisms.Elevator;
</strong>import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
<strong>import yams.core.mechanisms.config.ElevatorConfig;
</strong>import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ElevatorMechanism implements Mechanism {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // How far the carriage moves for each turn of the output shaft:
      // #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
      // so one turn moves the chain pitch x teeth = 5.5 inches.
      .withDrumRadius(Inches.of(0.25), 22)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(4, 0, 0)
      .withSimClosedLoopController(4, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the carriage.
      .withTrapezoidalProfile(MetersPerSecond.of(0.5), MetersPerSecondPerSecond.of(0.5))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ElevatorFeedforward(0, 0, 0))
      .withSimFeedforward(new ElevatorFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the carriage is when the robot turns on.
      .withStartingPosition(Meters.of(0))
      // The closed loop will not take the carriage past these heights.
      .withSoftLimits(Meters.of(0), Meters.of(2))
      // Telemetry name and how much to publish.
      .withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

<strong>  private final ElevatorConfig elevatorConfig = new ElevatorConfig()
</strong><strong>      // The hard stops, used by the simulation.
</strong><strong>      .withHardLimits(Meters.of(0), Meters.of(3))
</strong><strong>      // The weight of the carriage and everything on it, used by the simulation.
</strong><strong>      .withCarriageWeight(Pounds.of(16))
</strong><strong>      // Telemetry name and how much to publish.
</strong><strong>      .withTelemetry("Elevator", TelemetryVerbosity.HIGH);
</strong>
<strong>  // The elevator mechanism.
</strong><strong>  private final Elevator elevator = new Elevator(elevatorConfig, motor);
</strong>
<strong>  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
</strong><strong>  public void periodic() {
</strong><strong>    // Publishes the elevator's telemetry, and applies anything changed through live tuning.
</strong><strong>    elevator.updateTelemetry();
</strong><strong>  }
</strong>
<strong>  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
</strong><strong>  public void simulationPeriodic() {
</strong><strong>    // Runs the elevator's physics simulation.
</strong><strong>    elevator.simIterate();
</strong><strong>  }
</strong>}
</code></pre>

<pre class="language-java" data-title="Robot.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import java.util.ArrayList;
</strong><strong>import java.util.List;
</strong>import org.wpilib.command3.Scheduler;
import org.wpilib.command3.button.CommandGamepad;
import org.wpilib.framework.OpModeRobot;
<strong>import org.wpilib.system.Notifier;
</strong><strong>import org.wpilib.telemetry.Telemetry;
</strong>import first.robot.constants.DriverConstants;
<strong>import first.robot.mechanisms.ElevatorMechanism;
</strong>import first.robot.mechanisms.ExampleMechanism;

public class Robot extends OpModeRobot {
  final ExampleMechanism exampleMechanism = new ExampleMechanism();
<strong>  final ElevatorMechanism elevator = new ElevatorMechanism();
</strong>  final CommandGamepad exampleController =
      new CommandGamepad(DriverConstants.DRIVER_CONTROLLER_PORT);

<strong>  // The scheduler that runs every command.
</strong><strong>  private final Scheduler scheduler = Scheduler.getDefault();
</strong><strong>  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
</strong><strong>  private final List&#x3C;Notifier> simulationNotifiers = new ArrayList&#x3C;>();
</strong>
  public Robot() {}

  @Override
  public void robotPeriodic() {
<strong>    // Runs every loop, on the robot and in simulation.
</strong><strong>    // Update the mechanism before the scheduler runs its commands.
</strong><strong>    elevator.periodic();
</strong><strong>    scheduler.run();
</strong><strong>    // Publish the scheduler, so that a dashboard shows which commands are running.
</strong><strong>    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
</strong><strong>  }
</strong>
<strong>  @Override
</strong><strong>  public void simulationInit() {
</strong><strong>    // Runs once, when the simulation starts.
</strong><strong>    // Run each mechanism's simulation in its own Notifier, every robot loop.
</strong><strong>    startSimulation("Elevator", elevator::simulationPeriodic);
</strong><strong>  }
</strong>
<strong>  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
</strong><strong>  private void startSimulation(String name, Runnable simulationPeriodic) {
</strong><strong>    Notifier notifier = new Notifier(simulationPeriodic);
</strong><strong>    notifier.setName(name + " Simulation");
</strong><strong>    notifier.startPeriodic(getPeriod());
</strong><strong>    simulationNotifiers.add(notifier);
</strong><strong>  }
</strong>}
</code></pre>

{% endtab %}

{% tab title="C++" %}
The highlighted lines are new in this step.

`ElevatorConfig` in C++ takes the two hard limits separately, with `WithMinimumHeight` and `WithMaximumHeight`, and `WithCarriageMass` is the C++ name of `withCarriageWeight`. The C++ mechanism configs take a telemetry name only.

<pre class="language-cpp" data-title="include/subsystems/ElevatorSubsystem.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include &#x3C;optional>

#include &#x3C;rev/SparkMax.h>
#include &#x3C;wpi/commands2/SubsystemBase.hpp>
#include &#x3C;wpi/hardware/bus/CANPort.hpp>

<strong>#include "yams/mechanisms/config/ElevatorConfig.hpp"
</strong><strong>#include "yams/mechanisms/positional/Elevator.hpp"
</strong>#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/local/SparkWrapper.hpp"

class ElevatorSubsystem : public wpi::cmd::SubsystemBase {
 public:
  ElevatorSubsystem();

<strong>  void Periodic() override;
</strong><strong>  void SimulationPeriodic() override;
</strong>
 private:
  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};

  // What the motor controller should do. It is filled in by the constructor.
  yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;

  // The SmartMotorController, created in the constructor once the config is ready.
  std::optional&#x3C;yams::motorcontrollers::local::SparkWrapper> m_motor;

<strong>  // The elevator mechanism and its config, also set up in the constructor.
</strong><strong>  yams::mechanisms::config::ElevatorConfig m_elevatorConfig;
</strong><strong>  std::optional&#x3C;yams::mechanisms::positional::Elevator> m_elevator;
</strong>};
</code></pre>

<pre class="language-cpp" data-title="cpp/subsystems/ElevatorSubsystem.cpp" data-line-numbers><code class="lang-cpp">#include "subsystems/ElevatorSubsystem.hpp"

#include &#x3C;wpi/math/controller/ElevatorFeedforward.hpp>
#include &#x3C;wpi/math/system/DCMotor.hpp>
#include &#x3C;wpi/units/acceleration.hpp>
#include &#x3C;wpi/units/current.hpp>
#include &#x3C;wpi/units/length.hpp>
<strong>#include &#x3C;wpi/units/mass.hpp>
</strong>#include &#x3C;wpi/units/velocity.hpp>
#include &#x3C;wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;

ElevatorSubsystem::ElevatorSubsystem() {
  // What the motor controller should do: its control mode, gains, gearing and limits.
  m_smcConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // How far the carriage moves for each turn of the output shaft:
      // #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
      // so one turn moves the chain pitch x teeth = 5.5 inches.
      .WithMechanismCircumference(0.25_in, 22)
      // Feedback constants (PID), on the real robot and in simulation.
      .WithFeedback(4, 0, 0)
      .WithSimClosedLoopController(4, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the carriage.
      .WithLinearTrapezoidProfile(0.5_mps, 0.5_mps_sq)
      // Feedforward constants (kS, kG and kV), on the real robot and in simulation.
      .WithFeedforward(wpi::math::ElevatorFeedforward{
          0_V, 0_V, wpi::units::unit_t&#x3C;wpi::math::ElevatorFeedforward::kv_unit>{0}})
      .WithSimFeedforward(wpi::math::ElevatorFeedforward{
          0_V, 0_V, wpi::units::unit_t&#x3C;wpi::math::ElevatorFeedforward::kv_unit>{0}})
      // Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({3.0, 4.0})})
      .WithMotorInverted(false)
      .WithZeroPower(Cfg::MotorMode::BRAKE)
      .WithStatorCurrentLimit(40_A)
      // Where the carriage is when the robot turns on.
      .WithStartingPosition(0_m)
      // The closed loop will not take the carriage past these heights.
      .WithMeasurementLimits(0_m, 2_m)
      // Telemetry name and how much to publish.
      .WithTelemetry("ElevatorMotor", Cfg::TelemetryVerbosity::HIGH);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  m_motor.emplace(&#x26;m_spark, wpi::math::DCMotor::NEO(1), &#x26;m_smcConfig);

<strong>  m_elevatorConfig
</strong><strong>      // The hard stops, used by the simulation.
</strong><strong>      .WithMinimumHeight(0_m)
</strong><strong>      .WithMaximumHeight(3_m)
</strong><strong>      // The weight of the carriage and everything on it, used by the simulation.
</strong><strong>      .WithCarriageMass(16_lb)
</strong><strong>      // Telemetry name.
</strong><strong>      .WithTelemetryName("Elevator");
</strong>
<strong>  // The elevator mechanism.
</strong><strong>  m_elevator.emplace(&#x26;m_elevatorConfig, &#x26;m_motor.value());
</strong>}

<strong>void ElevatorSubsystem::Periodic() {
</strong><strong>  // Publishes the elevator's telemetry, and applies anything changed through live tuning.
</strong><strong>  m_elevator->UpdateTelemetry();
</strong><strong>}
</strong>
<strong>void ElevatorSubsystem::SimulationPeriodic() {
</strong><strong>  // Runs the elevator's physics simulation.
</strong><strong>  m_elevator->SimIterate();
</strong><strong>}
</strong></code></pre>

{% endtab %}
{% endtabs %}

## Check it

Build the code again. You can already run the simulation as in [step 4](/documentation/tutorials/elevator/simulate): the elevator is drawn with the carriage at 0 m, its starting position. It does not move yet, because nothing gives it a setpoint.

* **`Elevator` cannot be found:** the import is from the other command framework. Commands v2 uses `yams.commands2.mechanisms.Elevator`, Commands v3 uses `yams.commands3.mechanisms.Elevator`.


# Step 3: Commands and buttons

Make commands from the Elevator and bind them to controller buttons.

The `Elevator` makes commands for you. Your class hands them out, and the buttons schedule them.

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

{% stepper %}
{% step %}

### Make the commands

The `Elevator` makes the commands. Your class only hands them out, so that the rest of the robot code never touches the motor directly.

| What it does                                                       | Java, Commands v2                   | Java, Commands v3                   | C++                                    |
| ------------------------------------------------------------------ | ----------------------------------- | ----------------------------------- | -------------------------------------- |
| Go to a height and hold it. It never ends on its own.              | `elevator.run(height)`              | `elevator.setHeight(height)`        | `m_elevator->Run(height)`              |
| Go to a height, and end when the carriage is within the tolerance. | `elevator.runTo(height, tolerance)` | `elevator.runTo(height, tolerance)` | `m_elevator->RunTo(height, tolerance)` |
| Drive at a duty cycle from -1 to 1, with the closed loop off.      | `elevator.set(dutycycle)`           | `elevator.set(dutycycle)`           | `m_elevator->Set(dutycycle)`           |

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
/** Go to a height and hold it. This command does not end on its own. */
public Command run(Distance height) {
  return elevator.run(height);
}

/** Go to a height, and end once the carriage is within the tolerance of it. */
public Command runTo(Distance height, Distance tolerance) {
  return elevator.runTo(height, tolerance);
}

/** Drive the elevator with a duty cycle from -1 to 1. The closed loop is not used. */
public Command set(double dutycycle) {
  return elevator.set(dutycycle);
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
/** Go to a height and hold it. This command does not end on its own. */
public Command setHeight(Distance height) {
  return elevator.setHeight(height);
}

/** Go to a height, and end once the carriage is within the tolerance of it. */
public Command moveTo(Distance height, Distance tolerance) {
  return elevator.runTo(height, tolerance);
}

/** Drive the elevator with a duty cycle from -1 to 1. The closed loop is not used. */
public Command set(double dutycycle) {
  return elevator.set(dutycycle);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ElevatorSubsystem.hpp" %}

```cpp
/** Go to a height and hold it. This command does not end on its own. */
wpi::cmd::CommandPtr Run(wpi::units::meter_t height);

/** Go to a height, and end once the carriage is within the tolerance of it. */
wpi::cmd::CommandPtr RunTo(wpi::units::meter_t height, wpi::units::meter_t tolerance);

/** Drive the elevator with a duty cycle from -1 to 1. The closed loop is not used. */
wpi::cmd::CommandPtr Set(double dutycycle);
```

{% endcode %}

{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
wpi::cmd::CommandPtr ElevatorSubsystem::Run(wpi::units::meter_t height) {
  return m_elevator->Run(height);
}

wpi::cmd::CommandPtr ElevatorSubsystem::RunTo(wpi::units::meter_t height, wpi::units::meter_t tolerance) {
  return m_elevator->RunTo(height, tolerance);
}

wpi::cmd::CommandPtr ElevatorSubsystem::Set(double dutycycle) {
  return m_elevator->Set(dutycycle);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Rename these to suit your robot, or add more. Each one is a single line.

Want the details? [When mechanism commands end](/documentation/understanding/run-vs-runto)
{% endstep %}

{% step %}

### Set the default command

The **default command** runs whenever no other command is using the elevator. Here it holds the carriage at the bottom. In Commands v3 the default command is given the lowest priority, so that any other command for the mechanism can interrupt it.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="RobotContainer.java" %}

```java
import first.robot.subsystems.ElevatorSubsystem;

private final ElevatorSubsystem elevator = new ElevatorSubsystem();

// When no other command is using the elevator, hold it at the bottom.
elevator.setDefaultCommand(elevator.run(Meters.of(0)));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
/** Hold a height at the lowest priority, so that any other elevator command can interrupt it. */
public Command hold(Distance height) {
  return run(coroutine -> coroutine.await(elevator.setHeight(height)))
      .withPriority(Command.LOWEST_PRIORITY)
      .named("Elevator Hold");
}
```

{% endcode %}

{% code title="Robot.java" %}

```java
public class Robot extends OpModeRobot {
  // ...

  public Robot() {
    // When no other command is using the elevator, hold it at the bottom.
    elevator.setDefaultCommand(elevator.hold(Meters.of(0)));
  }

  // ...
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/RobotContainer.hpp" %}

```cpp
#include "subsystems/ElevatorSubsystem.hpp"

ElevatorSubsystem elevator;
```

{% endcode %}

{% code title="cpp/RobotContainer.cpp" %}

```cpp
// When no other command is using the elevator, hold it at the bottom.
elevator.SetDefaultCommand(elevator.Run(0_m));
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Choose what your mechanism should do when nobody is asking anything of it.
{% endstep %}

{% step %}

### Bind the buttons

`whileTrue` runs a command for as long as its button is held, and cancels it on release. The default command then takes back over.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-7c76c5d4398a7182749b5d7da48804ab7e0c2b6e%2Ftutorial-elevator-buttons.gif?alt=media" alt="Animation of the four face buttons of a controller, the elevator, and the command that is running. With no button held the default command runs: hold the elevator at 0 meters. While A is held its command runs: hold the elevator at 0.5 meters. While B is held: hold the elevator at 1 meter. While X is held the elevator is driven at a 30 percent duty cycle with the closed loop off. Each time a button is released the default command takes back over."><figcaption><p>A held button owns the elevator. Let go, and the default command brings it back down.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="RobotContainer.java" %}

```java
// Hold a height while the bottom (A) or right (B) face button is held.
driverController.faceDown().whileTrue(elevator.run(Meters.of(0.5)));
driverController.faceRight().whileTrue(elevator.run(Meters.of(1)));
// Drive the elevator up or down while the left (X) or top (Y) face button is held.
driverController.faceLeft().whileTrue(elevator.set(0.3));
driverController.faceUp().whileTrue(elevator.set(-0.3));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="ExampleTeleop.java" %}

```java
// Hold a height while the bottom (A) or right (B) face button is held.
robot.exampleController.faceDown().whileTrue(robot.elevator.setHeight(Meters.of(0.5)));
robot.exampleController.faceRight().whileTrue(robot.elevator.setHeight(Meters.of(1)));
// Drive the elevator up or down while the left (X) or top (Y) face button is held.
robot.exampleController.faceLeft().whileTrue(robot.elevator.set(0.3));
robot.exampleController.faceUp().whileTrue(robot.elevator.set(-0.3));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/RobotContainer.cpp" %}

```cpp
// Hold a height while the bottom (A) or right (B) face button is held.
driverController.FaceDown().WhileTrue(elevator.Run(0.5_m));
driverController.FaceRight().WhileTrue(elevator.Run(1_m));
// Drive the elevator up or down while the left (X) or top (Y) face button is held.
driverController.FaceLeft().WhileTrue(elevator.Set(0.3));
driverController.FaceUp().WhileTrue(elevator.Set(-0.3));
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Pick your own buttons and setpoints. Use `onTrue` instead if one press should start a command that keeps running after the button is released.
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
The highlighted lines are new in this step.

Add the commands to `ElevatorSubsystem.java`, then create the subsystem and bind the buttons in `RobotContainer.java`. The template bound the right face button to its example command; that binding is replaced.

<pre class="language-java" data-title="subsystems/ElevatorSubsystem.java" data-line-numbers><code class="lang-java">package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Meters;
import static org.wpilib.units.Units.MetersPerSecond;
import static org.wpilib.units.Units.MetersPerSecondPerSecond;
import static org.wpilib.units.Units.Pounds;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
<strong>import org.wpilib.command2.Command;
</strong>import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ElevatorFeedforward;
import org.wpilib.math.system.DCMotor;
<strong>import org.wpilib.units.measure.Distance;
</strong>import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.mechanisms.Elevator;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.ElevatorConfig;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ElevatorSubsystem extends SubsystemBase {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // How far the carriage moves for each turn of the output shaft:
      // #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
      // so one turn moves the chain pitch x teeth = 5.5 inches.
      .withDrumRadius(Inches.of(0.25), 22)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(4, 0, 0)
      .withSimClosedLoopController(4, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the carriage.
      .withTrapezoidalProfile(MetersPerSecond.of(0.5), MetersPerSecondPerSecond.of(0.5))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ElevatorFeedforward(0, 0, 0))
      .withSimFeedforward(new ElevatorFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the carriage is when the robot turns on.
      .withStartingPosition(Meters.of(0))
      // The closed loop will not take the carriage past these heights.
      .withSoftLimits(Meters.of(0), Meters.of(2))
      // Telemetry name and how much to publish.
      .withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

  private final ElevatorConfig elevatorConfig = new ElevatorConfig()
      // The hard stops, used by the simulation.
      .withHardLimits(Meters.of(0), Meters.of(3))
      // The weight of the carriage and everything on it, used by the simulation.
      .withCarriageWeight(Pounds.of(16))
      // Telemetry name and how much to publish.
      .withTelemetry("Elevator", TelemetryVerbosity.HIGH);

  // The elevator mechanism.
  private final Elevator elevator = new Elevator(elevatorConfig, motor);

<strong>  /** Go to a height and hold it. This command does not end on its own. */
</strong><strong>  public Command run(Distance height) {
</strong><strong>    return elevator.run(height);
</strong><strong>  }
</strong>
<strong>  /** Go to a height, and end once the carriage is within the tolerance of it. */
</strong><strong>  public Command runTo(Distance height, Distance tolerance) {
</strong><strong>    return elevator.runTo(height, tolerance);
</strong><strong>  }
</strong>
<strong>  /** Drive the elevator with a duty cycle from -1 to 1. The closed loop is not used. */
</strong><strong>  public Command set(double dutycycle) {
</strong><strong>    return elevator.set(dutycycle);
</strong><strong>  }
</strong>
  @Override
  public void periodic() {
    // Publishes the elevator's telemetry, and applies anything changed through live tuning.
    elevator.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    // Runs the elevator's physics simulation.
    elevator.simIterate();
  }
}
</code></pre>

<pre class="language-java" data-title="RobotContainer.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.Meters;
</strong>
import org.wpilib.command2.Command;
import org.wpilib.command2.button.CommandGamepad;
import org.wpilib.command2.button.Trigger;
import first.robot.Constants.OperatorConstants;
import first.robot.commands.Autos;
import first.robot.commands.ExampleCommand;
<strong>import first.robot.subsystems.ElevatorSubsystem;
</strong>import first.robot.subsystems.ExampleSubsystem;

/**
 * This class is where the bulk of the robot should be declared. Since Command-based is a
 * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
 * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
 * subsystems, commands, and trigger mappings) should be declared here.
 */
public class RobotContainer {
  // The robot's subsystems and commands are defined here...
  private final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
<strong>  private final ElevatorSubsystem elevator = new ElevatorSubsystem();
</strong>
  private final CommandGamepad driverController =
      new CommandGamepad(OperatorConstants.DRIVER_CONTROLLER_PORT);

  /** The container for the robot. Contains subsystems, OI devices, and commands. */
  public RobotContainer() {
    // Configure the trigger bindings
    configureBindings();

<strong>    // When no other command is using the elevator, hold it at the bottom.
</strong><strong>    elevator.setDefaultCommand(elevator.run(Meters.of(0)));
</strong>  }

  /**
   * Use this method to define your trigger->command mappings. Triggers can be created via the
   * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary
   * predicate, or via the named factories in {@link org.wpilib.command2.button.CommandGenericHID}'s
   * subclasses for {@link CommandGamepad Gamepad} gamepads or {@link
   * org.wpilib.command2.button.CommandJoystick Flight joysticks}.
   */
  private void configureBindings() {
    // Schedule `ExampleCommand` when `exampleCondition` changes to `true`
    new Trigger(exampleSubsystem::exampleCondition).onTrue(new ExampleCommand(exampleSubsystem));

<strong>    // Hold a height while the bottom (A) or right (B) face button is held.
</strong><strong>    driverController.faceDown().whileTrue(elevator.run(Meters.of(0.5)));
</strong><strong>    driverController.faceRight().whileTrue(elevator.run(Meters.of(1)));
</strong><strong>    // Drive the elevator up or down while the left (X) or top (Y) face button is held.
</strong><strong>    driverController.faceLeft().whileTrue(elevator.set(0.3));
</strong><strong>    driverController.faceUp().whileTrue(elevator.set(-0.3));
</strong>  }

  /**
   * Use this to pass the autonomous command to the main {@link Robot} class.
   *
   * @return the command to run in autonomous
   */
  public Command getAutonomousCommand() {
    // An example command will be run in autonomous
    return Autos.exampleAuto(exampleSubsystem);
  }
}
</code></pre>

{% endtab %}

{% tab title="Java, Commands v3" %}
The highlighted lines are new in this step.

Add the commands to `ElevatorMechanism.java`, set the default command in `Robot.java`, and bind the buttons in `ExampleTeleop.java`.

A `Mechanism` already has a `run(...)` method that takes a coroutine, so the commands here have their own names. The default command is wrapped with `Command.LOWEST_PRIORITY`, so that any other command for the elevator can interrupt it.

<pre class="language-java" data-title="mechanisms/ElevatorMechanism.java" data-line-numbers><code class="lang-java">package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Meters;
import static org.wpilib.units.Units.MetersPerSecond;
import static org.wpilib.units.Units.MetersPerSecondPerSecond;
import static org.wpilib.units.Units.Pounds;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
<strong>import org.wpilib.command3.Command;
</strong>import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ElevatorFeedforward;
import org.wpilib.math.system.DCMotor;
<strong>import org.wpilib.units.measure.Distance;
</strong>import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.mechanisms.Elevator;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.ElevatorConfig;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ElevatorMechanism implements Mechanism {

  // What the motor controller should do: its control mode, gains, gearing and limits.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // How far the carriage moves for each turn of the output shaft:
      // #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
      // so one turn moves the chain pitch x teeth = 5.5 inches.
      .withDrumRadius(Inches.of(0.25), 22)
      // Feedback constants (PID), on the real robot and in simulation.
      .withClosedLoopController(4, 0, 0)
      .withSimClosedLoopController(4, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the carriage.
      .withTrapezoidalProfile(MetersPerSecond.of(0.5), MetersPerSecondPerSecond.of(0.5))
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new ElevatorFeedforward(0, 0, 0))
      .withSimFeedforward(new ElevatorFeedforward(0, 0, 0))
      // Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.BRAKE)
      .withStatorCurrentLimit(Amps.of(40))
      // Where the carriage is when the robot turns on.
      .withStartingPosition(Meters.of(0))
      // The closed loop will not take the carriage past these heights.
      .withSoftLimits(Meters.of(0), Meters.of(2))
      // Telemetry name and how much to publish.
      .withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

  private final ElevatorConfig elevatorConfig = new ElevatorConfig()
      // The hard stops, used by the simulation.
      .withHardLimits(Meters.of(0), Meters.of(3))
      // The weight of the carriage and everything on it, used by the simulation.
      .withCarriageWeight(Pounds.of(16))
      // Telemetry name and how much to publish.
      .withTelemetry("Elevator", TelemetryVerbosity.HIGH);

  // The elevator mechanism.
  private final Elevator elevator = new Elevator(elevatorConfig, motor);

<strong>  /** Go to a height and hold it. This command does not end on its own. */
</strong><strong>  public Command setHeight(Distance height) {
</strong><strong>    return elevator.setHeight(height);
</strong><strong>  }
</strong>
<strong>  /** Go to a height, and end once the carriage is within the tolerance of it. */
</strong><strong>  public Command moveTo(Distance height, Distance tolerance) {
</strong><strong>    return elevator.runTo(height, tolerance);
</strong><strong>  }
</strong>
<strong>  /** Drive the elevator with a duty cycle from -1 to 1. The closed loop is not used. */
</strong><strong>  public Command set(double dutycycle) {
</strong><strong>    return elevator.set(dutycycle);
</strong><strong>  }
</strong>
<strong>  /** Hold a height at the lowest priority, so that any other elevator command can interrupt it. */
</strong><strong>  public Command hold(Distance height) {
</strong><strong>    return run(coroutine -> coroutine.await(elevator.setHeight(height)))
</strong><strong>        .withPriority(Command.LOWEST_PRIORITY)
</strong><strong>        .named("Elevator Hold");
</strong><strong>  }
</strong>
  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
  public void periodic() {
    // Publishes the elevator's telemetry, and applies anything changed through live tuning.
    elevator.updateTelemetry();
  }

  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
  public void simulationPeriodic() {
    // Runs the elevator's physics simulation.
    elevator.simIterate();
  }
}
</code></pre>

<pre class="language-java" data-title="Robot.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.Meters;
</strong>
import java.util.ArrayList;
import java.util.List;
import org.wpilib.command3.Scheduler;
import org.wpilib.command3.button.CommandGamepad;
import org.wpilib.framework.OpModeRobot;
import org.wpilib.system.Notifier;
import org.wpilib.telemetry.Telemetry;
import first.robot.constants.DriverConstants;
import first.robot.mechanisms.ElevatorMechanism;
import first.robot.mechanisms.ExampleMechanism;

public class Robot extends OpModeRobot {
  final ExampleMechanism exampleMechanism = new ExampleMechanism();
  final ElevatorMechanism elevator = new ElevatorMechanism();
  final CommandGamepad exampleController =
      new CommandGamepad(DriverConstants.DRIVER_CONTROLLER_PORT);

  // The scheduler that runs every command.
  private final Scheduler scheduler = Scheduler.getDefault();
  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
  private final List&#x3C;Notifier> simulationNotifiers = new ArrayList&#x3C;>();

<strong>  public Robot() {
</strong><strong>    // When no other command is using the elevator, hold it at the bottom.
</strong><strong>    elevator.setDefaultCommand(elevator.hold(Meters.of(0)));
</strong><strong>  }
</strong>
  @Override
  public void robotPeriodic() {
    // Runs every loop, on the robot and in simulation.
    // Update the mechanism before the scheduler runs its commands.
    elevator.periodic();
    scheduler.run();
    // Publish the scheduler, so that a dashboard shows which commands are running.
    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
  }

  @Override
  public void simulationInit() {
    // Runs once, when the simulation starts.
    // Run each mechanism's simulation in its own Notifier, every robot loop.
    startSimulation("Elevator", elevator::simulationPeriodic);
  }

  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
  private void startSimulation(String name, Runnable simulationPeriodic) {
    Notifier notifier = new Notifier(simulationPeriodic);
    notifier.setName(name + " Simulation");
    notifier.startPeriodic(getPeriod());
    simulationNotifiers.add(notifier);
  }
}
</code></pre>

<pre class="language-java" data-title="ExampleTeleop.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.Meters;
</strong>
import org.wpilib.opmode.OpMode;
import org.wpilib.opmode.Teleop;

@Teleop
public class ExampleTeleop implements OpMode {
  public ExampleTeleop(Robot robot) {
    robot.exampleController.rightStick().whileTrue(robot.exampleMechanism.exampleCommand());

<strong>    // Hold a height while the bottom (A) or right (B) face button is held.
</strong><strong>    robot.exampleController.faceDown().whileTrue(robot.elevator.setHeight(Meters.of(0.5)));
</strong><strong>    robot.exampleController.faceRight().whileTrue(robot.elevator.setHeight(Meters.of(1)));
</strong><strong>    // Drive the elevator up or down while the left (X) or top (Y) face button is held.
</strong><strong>    robot.exampleController.faceLeft().whileTrue(robot.elevator.set(0.3));
</strong><strong>    robot.exampleController.faceUp().whileTrue(robot.elevator.set(-0.3));
</strong>  }
}
</code></pre>

{% endtab %}

{% tab title="C++" %}
The highlighted lines are new in this step.

Declare the commands in `ElevatorSubsystem.hpp`, define them in `ElevatorSubsystem.cpp`, then create the subsystem and bind the buttons in `RobotContainer`. The template bound the right face button to its example command; that binding is replaced.

<pre class="language-cpp" data-title="include/subsystems/ElevatorSubsystem.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include &#x3C;optional>

#include &#x3C;rev/SparkMax.h>
<strong>#include &#x3C;wpi/commands2/CommandPtr.hpp>
</strong>#include &#x3C;wpi/commands2/SubsystemBase.hpp>
#include &#x3C;wpi/hardware/bus/CANPort.hpp>
<strong>#include &#x3C;wpi/units/length.hpp>
</strong>
#include "yams/mechanisms/config/ElevatorConfig.hpp"
#include "yams/mechanisms/positional/Elevator.hpp"
#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/local/SparkWrapper.hpp"

class ElevatorSubsystem : public wpi::cmd::SubsystemBase {
 public:
  ElevatorSubsystem();

<strong>  /** Go to a height and hold it. This command does not end on its own. */
</strong><strong>  wpi::cmd::CommandPtr Run(wpi::units::meter_t height);
</strong>
<strong>  /** Go to a height, and end once the carriage is within the tolerance of it. */
</strong><strong>  wpi::cmd::CommandPtr RunTo(wpi::units::meter_t height, wpi::units::meter_t tolerance);
</strong>
<strong>  /** Drive the elevator with a duty cycle from -1 to 1. The closed loop is not used. */
</strong><strong>  wpi::cmd::CommandPtr Set(double dutycycle);
</strong>
  void Periodic() override;
  void SimulationPeriodic() override;

 private:
  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};

  // What the motor controller should do. It is filled in by the constructor.
  yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;

  // The SmartMotorController, created in the constructor once the config is ready.
  std::optional&#x3C;yams::motorcontrollers::local::SparkWrapper> m_motor;

  // The elevator mechanism and its config, also set up in the constructor.
  yams::mechanisms::config::ElevatorConfig m_elevatorConfig;
  std::optional&#x3C;yams::mechanisms::positional::Elevator> m_elevator;
};
</code></pre>

<pre class="language-cpp" data-title="cpp/subsystems/ElevatorSubsystem.cpp" data-line-numbers><code class="lang-cpp">#include "subsystems/ElevatorSubsystem.hpp"

#include &#x3C;wpi/math/controller/ElevatorFeedforward.hpp>
#include &#x3C;wpi/math/system/DCMotor.hpp>
#include &#x3C;wpi/units/acceleration.hpp>
#include &#x3C;wpi/units/current.hpp>
#include &#x3C;wpi/units/length.hpp>
#include &#x3C;wpi/units/mass.hpp>
#include &#x3C;wpi/units/velocity.hpp>
#include &#x3C;wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;

ElevatorSubsystem::ElevatorSubsystem() {
  // What the motor controller should do: its control mode, gains, gearing and limits.
  m_smcConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // How far the carriage moves for each turn of the output shaft:
      // #25 chain has a 0.25 inch pitch, and the sprocket has 22 teeth,
      // so one turn moves the chain pitch x teeth = 5.5 inches.
      .WithMechanismCircumference(0.25_in, 22)
      // Feedback constants (PID), on the real robot and in simulation.
      .WithFeedback(4, 0, 0)
      .WithSimClosedLoopController(4, 0, 0)
      // The fastest the closed loop is allowed to move and accelerate the carriage.
      .WithLinearTrapezoidProfile(0.5_mps, 0.5_mps_sq)
      // Feedforward constants (kS, kG and kV), on the real robot and in simulation.
      .WithFeedforward(wpi::math::ElevatorFeedforward{
          0_V, 0_V, wpi::units::unit_t&#x3C;wpi::math::ElevatorFeedforward::kv_unit>{0}})
      .WithSimFeedforward(wpi::math::ElevatorFeedforward{
          0_V, 0_V, wpi::units::unit_t&#x3C;wpi::math::ElevatorFeedforward::kv_unit>{0}})
      // Gearing from the motor rotor to the sprocket: a 3:1 stage and a 4:1 stage, 12:1 in total.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({3.0, 4.0})})
      .WithMotorInverted(false)
      .WithZeroPower(Cfg::MotorMode::BRAKE)
      .WithStatorCurrentLimit(40_A)
      // Where the carriage is when the robot turns on.
      .WithStartingPosition(0_m)
      // The closed loop will not take the carriage past these heights.
      .WithMeasurementLimits(0_m, 2_m)
      // Telemetry name and how much to publish.
      .WithTelemetry("ElevatorMotor", Cfg::TelemetryVerbosity::HIGH);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  m_motor.emplace(&#x26;m_spark, wpi::math::DCMotor::NEO(1), &#x26;m_smcConfig);

  m_elevatorConfig
      // The hard stops, used by the simulation.
      .WithMinimumHeight(0_m)
      .WithMaximumHeight(3_m)
      // The weight of the carriage and everything on it, used by the simulation.
      .WithCarriageMass(16_lb)
      // Telemetry name.
      .WithTelemetryName("Elevator");

  // The elevator mechanism.
  m_elevator.emplace(&#x26;m_elevatorConfig, &#x26;m_motor.value());
}

<strong>wpi::cmd::CommandPtr ElevatorSubsystem::Run(wpi::units::meter_t height) {
</strong><strong>  return m_elevator->Run(height);
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr ElevatorSubsystem::RunTo(wpi::units::meter_t height, wpi::units::meter_t tolerance) {
</strong><strong>  return m_elevator->RunTo(height, tolerance);
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr ElevatorSubsystem::Set(double dutycycle) {
</strong><strong>  return m_elevator->Set(dutycycle);
</strong><strong>}
</strong>
void ElevatorSubsystem::Periodic() {
  // Publishes the elevator's telemetry, and applies anything changed through live tuning.
  m_elevator->UpdateTelemetry();
}

void ElevatorSubsystem::SimulationPeriodic() {
  // Runs the elevator's physics simulation.
  m_elevator->SimIterate();
}
</code></pre>

<pre class="language-cpp" data-title="include/RobotContainer.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include "Constants.hpp"
<strong>#include "subsystems/ElevatorSubsystem.hpp"
</strong>#include "subsystems/ExampleSubsystem.hpp"
#include "wpi/commands2/CommandPtr.hpp"
#include "wpi/commands2/button/CommandGamepad.hpp"

/**
 * This class is where the bulk of the robot should be declared.  Since
 * Command-based is a "declarative" paradigm, very little robot logic should
 * actually be handled in the {@link Robot} periodic methods (other than the
 * scheduler calls).  Instead, the structure of the robot (including subsystems,
 * commands, and trigger mappings) should be declared here.
 */
class RobotContainer {
 public:
  RobotContainer();

  wpi::cmd::CommandPtr GetAutonomousCommand();

 private:
  // Replace with CommandPS4Controller or CommandJoystick if needed
  wpi::cmd::CommandGamepad driverController{
      OperatorConstants::DRIVER_CONTROLLER_PORT};

  // The robot's subsystems are defined here...
  ExampleSubsystem subsystem;
<strong>  ElevatorSubsystem elevator;
</strong>
  void ConfigureBindings();
};
</code></pre>

<pre class="language-cpp" data-title="cpp/RobotContainer.cpp" data-line-numbers><code class="lang-cpp">#include "RobotContainer.hpp"

#include "commands/Autos.hpp"
#include "commands/ExampleCommand.hpp"
#include "wpi/commands2/button/Trigger.hpp"
<strong>#include "wpi/units/length.hpp"
</strong>
RobotContainer::RobotContainer() {
  // Initialize all of your commands and subsystems here

<strong>  // When no other command is using the elevator, hold it at the bottom.
</strong><strong>  elevator.SetDefaultCommand(elevator.Run(0_m));
</strong>
  // Configure the button bindings
  ConfigureBindings();
}

void RobotContainer::ConfigureBindings() {
  // Configure your trigger bindings here

  // Schedule `ExampleCommand` when `exampleCondition` changes to `true`
  wpi::cmd::Trigger([this] {
    return subsystem.ExampleCondition();
  }).OnTrue(ExampleCommand(&#x26;subsystem).ToPtr());

<strong>  // Hold a height while the bottom (A) or right (B) face button is held.
</strong><strong>  driverController.FaceDown().WhileTrue(elevator.Run(0.5_m));
</strong><strong>  driverController.FaceRight().WhileTrue(elevator.Run(1_m));
</strong><strong>  // Drive the elevator up or down while the left (X) or top (Y) face button is held.
</strong><strong>  driverController.FaceLeft().WhileTrue(elevator.Set(0.3));
</strong><strong>  driverController.FaceUp().WhileTrue(elevator.Set(-0.3));
</strong>}

wpi::cmd::CommandPtr RobotContainer::GetAutonomousCommand() {
  // An example command will be run in autonomous
  return autos::ExampleAuto(&#x26;subsystem);
}
</code></pre>

{% endtab %}
{% endtabs %}

{% hint style="info" %}
These commands are helpers that start and stop the closed loop for you. If you would rather set setpoints from your own command or state machine, see [How do I write my own mechanism command?](/documentation/how-to-mechanisms/how-do-i-write-my-own-mechanism-command).
{% endhint %}

## Which command ends?

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-3fadf4560c9eaad8dd912329ba84d272841fdef5%2Fmech-commands.png?alt=media" alt="Three timelines starting when the command is scheduled. run(setpoint), also called setAngle or setHeight, runs until something else takes the mechanism and holds the setpoint the whole time. runTo(setpoint, tolerance) ends when the mechanism is within the tolerance, and then the default command takes over. set(dutycycle) and setVoltage(volts) are open loop with no PID and run until interrupted. The closed loop starts again when the next run or runTo command begins, such as the default command."><figcaption><p>When each kind of command ends.</p></figcaption></figure>

The buttons here use the command that never ends, because a button that is held should keep holding the carriage. Use the one that ends when you need to know the carriage has arrived, such as in an autonomous sequence. [When mechanism commands end](/documentation/understanding/run-vs-runto) covers the difference, and [How do I set an elevator's target height?](/documentation/how-to-mechanisms/how-to-set-an-elevators-target-height) has more examples.

## Check it

Build the code. If it builds, every button is bound. Next you run it and press them.


# Step 4: Simulate it

Run the elevator in simulation and drive it with a controller.

The code from the first three steps runs on your computer exactly as it will on the robot. YAMS simulates the motor, the gearing, the carriage and gravity, so the closed loop, the limits and the commands all behave the way they will on the real elevator.

{% stepper %}
{% step %}

### Start the simulation

{% tabs %}
{% tab title="Java, Commands v2" %}
Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Simulate Robot Code**. If you are asked which extensions to run, tick **Sim GUI**.
{% endtab %}

{% tab title="Java, Commands v3" %}
Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Simulate Robot Code**. If you are asked which extensions to run, tick **Sim GUI**.

The buttons are bound in the `ExampleTeleop` op mode, so that is the op mode to run when you enable.

If the simulated mechanism never moves, check that `Robot.java` has a `simulationInit()` that calls `startSimulation(...)` for the mechanism.
{% endtab %}

{% tab title="C++" %}
Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Simulate Robot Code**. If you are asked which extensions to run, tick **Sim GUI**.

The first C++ build compiles the whole project, so it takes a few minutes. Later builds are much faster.
{% endtab %}
{% endtabs %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2F04lmc9ZfMo9DPRuEp9gh%2Fimage.png?alt=media&amp;token=de5c8905-4617-4c86-bfd9-2c4acdccac09" alt="The Sim GUI, the window that opens with the simulation, with the Robot State, System Joysticks, Joysticks and NetworkTables panels"><figcaption><p>The Sim GUI.</p></figcaption></figure>
{% endstep %}

{% step %}

### Drive it

1. Connect a controller to your computer, then drag it from **System Joysticks** to **Joystick\[0]**.
2. Open the simulated mechanism with **NetworkTables -> Mechanisms -> Elevator -> mechanism**. It is named after the `withTelemetry("Elevator", ...)` on the `ElevatorConfig`. It shows the carriage as a bar that grows upward as the carriage rises, with short marks beside it for the soft limits and the hard stops.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FLFZWXPofThkqLoUsplTR%2FRobot%20Simulation%208_30_2025%207_06_08%20PM.png?alt=media&amp;token=18b8bec7-865d-451e-a12b-d9adcf088f0e" alt="The Sim GUI with the elevator&#x27;s Mechanism2d window open: a vertical bar for the carriage height, next to marks for the limits"><figcaption></figcaption></figure>

3. Resize **Elevator/mechanism** to your liking.
4. Commands v3: pick the `ExampleTeleop` op mode first. Then press **Teleoperated** in **Robot State**. The controller now drives the simulated elevator just as it would the real one.

No controller? The Sim GUI can use the keyboard as a joystick: drag **Keyboard 0** to **Joystick\[0]**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FZdaaTFAtUEcoLKsw3qzY%2FRobot%20Simulation%202025-08-30%2018-37-59.gif?alt=media&amp;token=0b4e3353-320f-4983-9309-d452471b7311" alt="The simulated elevator in its Mechanism2d window, the carriage bar rising and falling between heights as buttons are pressed"><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

## What you should see

* Before you enable, the carriage is drawn at 0 m, its starting position, at the bottom.
* When you enable, the default command holds it at 0 m, so it stays at the bottom.
* Holding **A** raises it toward 0.5 m, and holding **B** toward 1 m. Let go, and it goes back down to 0 m. It moves no faster than 0.5 m/s, the limit from the motion profile.
* Holding **X** drives it up, and **Y** drives it down, until the soft limits stop it at 0 m and 2 m.
* It settles below each setpoint, roughly 15 cm with the placeholder gains. That is gravity: `kG` is 0, so only `kP` holds the carriage up, and `kP` only pushes once the carriage has dropped below the setpoint. The next step fixes it.

## If it did not work

* **The elevator is not in the NetworkTables menu.** Look under **Mechanisms**, not **SmartDashboard**.
* **The elevator does not move.** Check the robot is enabled in **Teleoperated** and the controller is on **Joystick\[0]**. Commands v3: check you picked `ExampleTeleop`, and that `Robot.simulationInit()` starts the elevator's simulation with `startSimulation(...)`.
* **The code stops with an error when the simulation starts.** Read the first error. YAMS names the setting that is missing, such as soft limits in meters set before `withDrumRadius`.

More problems and fixes: [Troubleshooting](/documentation/tutorials/troubleshooting).


# Step 5: Tune it

Tune the elevator's gains while the simulation runs, then copy them into your code.

The gains from step 1 are placeholders: `kP` is 4 and every feedforward gain is 0. They are enough to move the elevator, but the carriage sags below its setpoint. On this page you tune them while the simulation runs, the same way you will tune the real elevator on the robot.

You change one number at a time on a dashboard and watch a graph. Nothing is saved until you copy the numbers into your code at the end.

If you did [the arm's tune step](/documentation/tutorials/arm/tune), this is the same except for gravity (`kG` is the same at every height) and the units (meters, not degrees).

{% hint style="info" %}
**In simulation you are tuning the simulation's gains.** While the code runs in simulation, live tuning changes the `withSimClosedLoopController` and `withSimFeedforward` values. On the real robot it changes `withClosedLoopController` and `withFeedforward`. The two sets are kept apart because a simulated elevator is never exactly like the real one.
{% endhint %}

## Before you start

* Start the simulation and enable **Teleoperated**, as in [step 4](/documentation/tutorials/elevator/simulate). The carriage rests at 0 m.
* Do not press any of the elevator's buttons while you tune. A button runs another elevator command, which stops live tuning. If that happens, start live tuning again.

Then tune with the YAMS Live Tuner, or by typing the values in AdvantageScope and Elastic. Both change the same values, so pick one.

{% tabs %}
{% tab title="YAMS Live Tuner" %}
The [YAMS Live Tuner](/documentation/how-to-tuning/live-tuning/live-tuner) is a web page that walks you through it: it checks the elevator before anything moves, then you send setpoints and change gains while watching a graph.

{% stepper %}
{% step %}

### Connect

Open [tuning.yassrobotics.com](https://tuning.yassrobotics.com/), pick **Simulation**, and press **Connect**. If your browser asks whether the page may connect to devices on your local network, allow it.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-a69700cfe54cd00a2f7ec8e514840bf783ce65f6%2Flive-tuner-connect.png?alt=media" alt="The Live Tuner header connected to a simulation on localhost, with the robot in Teleop and enabled"><figcaption><p>Connected to the simulation, with the robot enabled in Teleop.</p></figcaption></figure>

**Check it:** the badge in the header shows `localhost`, with the robot enabled in Teleop.
{% endstep %}

{% step %}

### Pick the elevator

1. Under **Telemetry name**, choose `Elevator/ElevatorMotor`: the names from the elevator's and the motor's `withTelemetry`.
2. Under **Live Tuning command**, choose `ElevatorSubsystem` (Commands v2 and C++) or `ElevatorMechanism` (Commands v3).
3. Set **Type** to **Elevator**. Setpoints are in meters.
4. Press **Continue**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-9fafcc33c264997599ffc8800b6f21615b452a3a%2Flive-tuner-tutorial-elevator-mechanism.png?alt=media" alt="The Mechanism step with Elevator/ElevatorMotor as the telemetry name, ElevatorSubsystem as the Live Tuning command and Elevator as the type, so setpoints are in meters"><figcaption><p>The tutorial elevator: its motor, its subsystem's <code>Live Tuning</code> command, and the Elevator type.</p></figcaption></figure>

**Check it:** the telemetry card shows the carriage at 0 m.
{% endstep %}

{% step %}

### Checklist and inversions

1. Tick every item on the pre-motion checklist, leave **Current trip (A)** at 40, and press **Continue**.
2. Tick the confirmation and press **Start voltage control**.
3. Drag the voltage slider all the way to the right and hold it. The carriage rises. Let go once **Positive voltage moves up** is ticked: the slider goes back to 0 V.
4. If the carriage does not move with the slider all the way to the right, select the number at the slider's right end, 1.00 V to start with, and raise it a little. The number at the left end sets how far the slider goes the other way. Gravity pulls the carriage down, so it can need more voltage to rise than to fall.
5. Press **Finish check**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-1b96caa8f452d97d1dfc0ec18d7f3ff81ba2dfe2%2Flive-tuner-tutorial-elevator-inversions.png?alt=media" alt="Holding 1 V: Positive voltage moves up is ticked and Finish check is enabled"><figcaption><p>At 1 V the carriage rises, so <strong>Positive voltage moves up</strong> is ticked.</p></figcaption></figure>

**Check it:** **Positive voltage moves up** was ticked when the carriage rose. If the Live Tuner warns that the height went the wrong way, the motor or encoder inversion in step 1 is wrong.
{% endstep %}

{% step %}

### Set the range of motion

Choose **Enter range manually**. The ends start at the soft limits from step 1, 0 and 2 meters, so press **Use this range**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-68b177571e09ae2d6b8705a0d517a6fc1e8974fc%2Flive-tuner-tutorial-elevator-range.png?alt=media" alt="Enter range manually chosen, with the lower end at 0 and the upper end at 2 meters, the soft limits, and Use this range"><figcaption><p>The ends start at the elevator's soft limits.</p></figcaption></figure>

**Check it:** the Live tune card opens.
{% endstep %}

{% step %}

### Start live tuning and find kG

Press **Start Live Tuning**. The setpoints and gains you send are now applied to the elevator every loop.

`kG` is the voltage it takes to hold the carriage still against gravity. Gravity pulls just as hard at every height, so one `kG` is right everywhere. With `kG` at 0, only `kP` holds the carriage up, so it sags below its setpoint.

1. On the **Setpoints** tab, press **Mid**: 1 m, halfway up the 0 to 2 m range. The carriage rises, then settles below 1 m: about 0.85 m with the placeholder `kP`.
2. Once it has stopped, read its output voltage on the telemetry card. For this elevator it reads about `0.6`.
3. Type that voltage into **kG** on the Settings card's **Gains** tab, and press **Enter**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-3073b9a9ea7953a1e5a7834d0aa6a203a76da590%2Flive-tuner-tutorial-elevator-kg.png?alt=media" alt="Live tuning the elevator at a 1 m setpoint after kG is set to 0.6: the measured height climbs from about 0.85 m onto the setpoint, with the output at 0.67 V"><figcaption><p>With kG at 0.6 V, the carriage climbs from where it sagged onto the 1 m setpoint.</p></figcaption></figure>

**Check it:** the measured height moves up onto the 1 m setpoint on the graph and stays there. Press **25%** (0.5 m), then **75%** (1.5 m): the carriage holds each one without sagging.
{% endstep %}

{% step %}

### Tune kP and kD

`kP` is how hard the motor pushes for each meter of error. A `kP` of 4 is only 0.04 volts for each centimeter, which is why the carriage sagged so far.

1. Turn on **Alternate setpoints**, with **Setpoint A** at `0.5` and **Setpoint B** at `1`. The carriage now moves between them every 5 seconds.
2. Watch each move on the graph and change **kP** on the **Gains** tab:
   * It lags behind the setpoint, or stops a few centimeters short: double `kP` (8, then 16, and so on).
   * It overshoots and bounces: lower `kP` by about a third.
3. If it still overshoots a little at a `kP` that is quick enough, raise **kD** a little at a time, starting at `0.5`.

A change that made it worse? Press **was** under the value to put the last one back.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-0b29eba66df91e87b15d9d6a384185ec7c169348%2Flive-tuning-response.png?alt=media" alt="Three step responses: kP too low rises slowly and stops short, about right settles quickly on the setpoint, kP too high overshoots and rings"><figcaption><p>What the height looks like on the graph after each setpoint change.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-2c9c694a16d71b634f2a51153e506ff687a6ccda%2Flive-tuner-tutorial-elevator-alternate.png?alt=media" alt="Alternate setpoints on, switching between 0.5 and 1 m with kP at 40: the measured height follows each step up and back down"><figcaption><p>kP 40 and kD 1, alternating between 0.5 and 1 m.</p></figcaption></figure>

**Check it:** after each change of setpoint the carriage follows the setpoint closely and stops on it, within a centimeter or so, without bouncing.
{% endstep %}

{% step %}

### Tune the motion profile and kV

The motion profile limits how fast the carriage moves and speeds up. On the **Gains** tab, **Max velocity** and **Max acceleration** are 0.5 m/s and 0.5 m/s² from step 1.

1. Set **Setpoint B** to `1.5`, then raise **Max velocity** and **Max acceleration** a step at a time.
2. Stop raising them when the measured height falls behind the setpoint while it moves, or the stator current on the graph jumps. This NEO and 12:1 gearing can lift the carriage at about 1.1 m/s at most, so keep **Max velocity** well below that.
3. Raise **kV** until the measured height follows the setpoint during a move, instead of falling behind and catching up at the end. For this elevator it ends up near `10`: about 12 volts divided by the 1.1 m/s top speed.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-40eef9f0fd59e9b6a93ee2a6e966969f12bf7b92%2Flive-tuner-tutorial-elevator-gains.png?alt=media" alt="The Settings card&#x27;s Gains tab for the elevator: kP 40, kD 1, kV 10, kG 0.6 V, Max velocity 0.8 m/s and Max accel 1 m/s squared, each with was under it"><figcaption><p>Max velocity raised to 0.8 m/s and max acceleration to 1 m/s², with kV at 10.</p></figcaption></figure>

**Check it:** the carriage follows the setpoint through each move and arrives without lagging. Press **Space** to stop when you are done.
{% endstep %}
{% endstepper %}
{% endtab %}

{% tab title="AdvantageScope and Elastic" %}
You type each value into its NetworkTables key yourself, and graph the elevator in AdvantageScope.

Open [AdvantageScope](https://docs.advantagescope.org/) and connect it to the simulation (**File > Connect to Simulator**).

{% stepper %}
{% step %}

### Start live tuning

YAMS gives the elevator a `Live Tuning` command. While it runs, numbers you type on the dashboard are applied to the elevator straight away.

* **Commands v2 and C++:** the command is published at `NT:/Tuning/ElevatorSubsystem/Live Tuning`, named after the subsystem. In [Elastic](https://frc-elastic.gitbook.io/docs), add `Tuning/ElevatorSubsystem/Live Tuning` to a tab and press its button.
* **Commands v3:** the command is published at `NT:/Tuning/ElevatorMechanism/Live Tuning`, named after the mechanism. Set the boolean `NT:/Tuning/ElevatorMechanism/Live Tuning/running` to `true`. In AdvantageScope, first turn on tuning mode (step 2), then click the value to change it.

**Check it:** the command shows as running. The carriage stays at 0 m.
{% endstep %}

{% step %}

### Find the numbers and graph the elevator

The elevator's values are under two tables. Both use the names from `withTelemetry`: `Elevator` for the elevator and `ElevatorMotor` for its motor.

|                  | Where                                    | Used for                                          |
| ---------------- | ---------------------------------------- | ------------------------------------------------- |
| Values you type  | `NT:/Tuning/Elevator/ElevatorMotor/`     | Gains, setpoints, limits                          |
| Values you watch | `NT:/Mechanisms/Elevator/ElevatorMotor/` | Where the carriage is and what the motor is doing |

1. In AdvantageScope, turn on **tuning mode**: the sliders icon beside the search box at the top of the sidebar. Without it, typed values are ignored.
2. Make a **Line Graph** and drag in, from `NT:/Mechanisms/Elevator/ElevatorMotor/`:
   * `measurement/position`: how high the carriage is, in meters.
   * `closedloop/setpoint/position`: how high the carriage is asked to be, in meters.
   * `motor/outputVoltage`: the voltage the motor is given.

Heights are in meters both where you type and where you read, so there is nothing to convert.

**Check it:** both position lines are at 0, and the output voltage is about 0.
{% endstep %}

{% step %}

### kG: hold the carriage up

`kG` is the voltage it takes to hold the carriage still against gravity. Gravity pulls the carriage down just as hard at every height, so one `kG` is right everywhere. You only need to find it once, at any height away from the stops.

With `kG` at 0, only `kP` holds the carriage up. `kP` only pushes when there is an error, so the carriage has to sag before the motor pushes hard enough. The voltage it settles at is the voltage gravity needs.

1. Type `1` into `NT:/Tuning/Elevator/ElevatorMotor/closedloop/setpoint/position`. The carriage rises, then settles below 1 m: about 0.85 m with the placeholder `kP`.
2. Once it has stopped, read `motor/outputVoltage`. For this elevator it reads about `0.6`.
3. Type that voltage into `NT:/Tuning/Elevator/ElevatorMotor/closedloop/feedforward/kG`.

**Check it:** the measured position moves up onto the 1 m setpoint and stays there. The output voltage stays about the same, because `kG` now supplies it instead of `kP`. Type `0.5`, then `1.5`: the carriage holds each one without sagging, because `kG` is the same at every height.

If the carriage drifts, adjust `kG` a little: up if it sits low, down if it sits high.
{% endstep %}

{% step %}

### kP and kD: reach a setpoint

`kP` is how hard the motor pushes for each meter of error. A `kP` of 4 is 4 volts per meter, only 0.04 volts for each centimeter, which is why the carriage sagged so far.

1. Type `0.5` into `closedloop/setpoint/position`, then `1`, and watch the position line each time. Move between those two for the rest of this part.
2. Compare the line with the picture below and change `NT:/Tuning/Elevator/ElevatorMotor/closedloop/feedback/kP`:
   * It lags behind the setpoint, or stops a few centimeters short: double `kP` (8, then 16, and so on).
   * It overshoots and bounces: lower `kP` by about a third.
3. If it still overshoots a little at a `kP` that is quick enough, raise `closedloop/feedback/kD` a little at a time, starting at `0.5`.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-0b29eba66df91e87b15d9d6a384185ec7c169348%2Flive-tuning-response.png?alt=media" alt="Three step responses: kP too low rises slowly and stops short, about right settles quickly on the setpoint, kP too high overshoots and rings"><figcaption><p>What the position line looks like after a setpoint change.</p></figcaption></figure>

**Check it:** after each setpoint change the carriage follows the setpoint line closely and stops on it, within a centimeter or so, without bouncing.

The carriage cannot go past the soft limits from step 1, 0 and 2 meters. A setpoint beyond them is held at the limit.
{% endstep %}

{% step %}

### The motion profile and kV

The motion profile limits how fast the carriage moves and speeds up: 0.5 m/s and 0.5 m/s² from step 1. On the dashboard they are in the same units.

1. Raise `NT:/Tuning/Elevator/ElevatorMotor/closedloop/motionprofile/maxVelocity` and `maxAcceleration` a step at a time while moving between `0.5` and `1.5`.
2. Stop raising them when the measured position falls behind the setpoint while it moves, or `current/stator` jumps. This NEO and 12:1 gearing can lift the carriage at about 1.1 m/s at most, so keep `maxVelocity` well below that.
3. Add `measurement/velocity` and `closedloop/setpoint/velocity` (both in m/s) to the graph. Raise `closedloop/feedforward/kV` until the measured velocity follows the setpoint velocity during a move. `kV` only acts while the carriage moves. For this elevator it ends up near `10`: about 12 volts divided by the 1.1 m/s top speed.

**Check it:** the measured velocity sits on top of the setpoint velocity, and the carriage arrives without lagging behind.

For more on each value, see [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order).
{% endstep %}
{% endstepper %}
{% endtab %}
{% endtabs %}

## Copy the numbers into your code

Dashboard changes are lost when the code restarts. Write the numbers you ended up with into the config from step 1. In simulation they go into the `Sim` versions.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ElevatorSubsystem.java" %}

```java
// Before
.withSimClosedLoopController(4, 0, 0)
.withSimFeedforward(new ElevatorFeedforward(0, 0, 0))

// After: your numbers. ElevatorFeedforward takes kS, kG, kV.
.withSimClosedLoopController(40, 0, 1)
.withSimFeedforward(new ElevatorFeedforward(0, 0.6, 10))
```

{% endcode %}

Copy the motion profile limits into `withTrapezoidalProfile` too.
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ElevatorMechanism.java" %}

```java
// Before
.withSimClosedLoopController(4, 0, 0)
.withSimFeedforward(new ElevatorFeedforward(0, 0, 0))

// After: your numbers. ElevatorFeedforward takes kS, kG, kV.
.withSimClosedLoopController(40, 0, 1)
.withSimFeedforward(new ElevatorFeedforward(0, 0.6, 10))
```

{% endcode %}

Copy the motion profile limits into `withTrapezoidalProfile` too.
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp" %}

```cpp
// Before
.WithSimClosedLoopController(4, 0, 0)
.WithSimFeedforward(wpi::math::ElevatorFeedforward{
    0_V, 0_V, wpi::units::unit_t<wpi::math::ElevatorFeedforward::kv_unit>{0}})

// After: your numbers. kP, kI, kD, then kS, kG and kV.
.WithSimClosedLoopController(40, 0, 1)
.WithSimFeedforward(wpi::math::ElevatorFeedforward{
    0_V, 0.6_V, wpi::units::unit_t<wpi::math::ElevatorFeedforward::kv_unit>{10}})
```

{% endcode %}

Copy the motion profile limits into `WithLinearTrapezoidProfile` too.
{% endtab %}
{% endtabs %}

The numbers above are an example. Use the ones you found.

**Check it:** restart the simulation and enable it. Hold **A** and **B**: the carriage goes to 0.5 m and 1 m smoothly and stops on each without sagging.

## If it did not work

* **AdvantageScope: typing a value does nothing.** Turn on AdvantageScope's tuning mode, check the `Live Tuning` command is still running, and check you typed under `NT:/Tuning`, not `NT:/Mechanisms`.
* **Live Tuner: the elevator is not in the Telemetry name list.** Check the simulation is running and you connected to **Simulation**. The list only fills in once the robot code has started.
* **Live tuning stopped on its own.** A button press, or the default command, took over the elevator. On the Live Tuner, the current trip, leaving the range of motion, or pressing Space also stops it. Start it again.
* **The carriage sits on the bottom stop and will not rise.** The setpoint is still 0 m. Type a height first, then read the voltage.
* **The carriage bounces harder and harder.** `kP` is too high. Lower it, or disable and restart the simulation.
* **The numbers were gone after a restart.** They only last until the code stops. Copy them into your code, as in [Copy the numbers into your code](#copy-the-numbers-into-your-code).

More problems and fixes: [Troubleshooting](/documentation/tutorials/troubleshooting).

## Step 6: Run it on the robot

Step 6 puts the code on the real robot. Follow [the arm's step 6: Run it on the robot](/documentation/tutorials/arm/robot). Everything there works the same for the elevator, with these differences:

* The CAN ID is the elevator's `SparkMax`, 4 in this tutorial.
* Before each time the code starts, rest the carriage at its starting position, 0 m: all the way down.
* For the direction check, positive should move the carriage **up**.
* Tune `kG` again on the robot: a real carriage usually needs more than the simulation, and some `kS` for friction. Copy the robot's numbers into `withClosedLoopController` and `withFeedforward`.
* Check the soft limits with `2` (the top one) and `0`.


# Shooter/FlyWheels

Learn how to program a shooter flywheel.

{% hint style="info" %}
Two motors on one shaft or gearbox? Add the second as a follower with `withFollowers`. Two motors that aren't on the same shaft or gearbox, such as one on each side of the mechanism? Make the second a loosely coupled follower with `withLooselyCoupledFollowers`: the mechanism still works as this tutorial shows. [Followers](/documentation/reference/editor/config/followers) explains both.
{% endhint %}

## Intro

At the end of this tutorial you will have a `Shooter` that works in both real life and simulation with the same code!

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fm1fTYlG5CKbyeFcWOu0M%2FRobot%20Simulation%202025-09-09%2009-07-39.gif?alt=media&amp;token=dc5b2f29-9c49-4cb6-88a5-33e7c8d2a700" alt="The simulated shooter in its Mechanism2d window: a line that spins with the flywheel while a button is held"><figcaption></figcaption></figure>

## Details

This `Shooter` uses the following hardware and controls:

* A `SparkMax` driving one NEO controls the `Shooter`
* A `1.5:1` gearbox on the `Shooter`, so its top speed is about 5676 RPM (a NEO's free speed) / 1.5 = 3784 RPM
* Two 4 inch flywheel wheels on one shaft, 1.5 lb in all
* Holding the bottom face button (`A` on an Xbox controller) spins the `Shooter` at 2000 RPM
* Holding the right face button (`B` on an Xbox controller) spins the `Shooter` at 3000 RPM
* Holding the left face button (`X` on an Xbox controller) drives the `Shooter` forward
* Holding the top face button (`Y` on an Xbox controller) drives the `Shooter` backward
* With no button held, the `Shooter` coasts

## The steps

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-fe9535961456bee46cb151e5b076a9907ec181c0%2Ftutorial-shooter-steps.png?alt=media" alt="The four steps of the shooter tutorial, each building on the one before. Step 1, the motor controller: a SparkMax and a SmartMotorControllerConfig. Step 2, the flywheel: a FlyWheelConfig and the SmartMotorController. Step 3, commands and buttons: run and set commands bound to a controller. Step 4, simulation: the same code run on your computer."><figcaption><p>The first four steps, one page each. Then you tune it and run it on the robot.</p></figcaption></figure>

Every step has a tab for **Java with Commands v2**, **Java with Commands v3** and **C++**.

| Step                                                                                        | What you do                                                                                   |
| ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| [Before you start](/documentation/tutorials/project-setup)                                  | Create a WPILib project and install YAMS and REVLib. Skip this if you already have a project. |
| [Step 1: The motor controller](/documentation/tutorials/shooter-flywheels/motor-controller) | Configure the `SparkMax` and wrap it in a `SmartMotorController`.                             |
| [Step 2: The flywheel](/documentation/tutorials/shooter-flywheels/mechanism)                | Describe the flywheel with a `FlyWheelConfig` and create the `FlyWheel`.                      |
| [Step 3: Commands and buttons](/documentation/tutorials/shooter-flywheels/commands)         | Turn the `FlyWheel` into commands and bind them to controller buttons.                        |
| [Step 4: Simulate it](/documentation/tutorials/shooter-flywheels/simulate)                  | Run the code on your computer and drive the flywheel with a controller.                       |
| [Step 5: Tune it](/documentation/tutorials/shooter-flywheels/tune)                          | Find `kV` and `kP` while the simulation runs, and copy them into your code.                   |
| [Step 6: Run it on the robot](/documentation/tutorials/arm/robot)                           | The arm's robot step, with the flywheel differences listed at the end of step 5.              |

## Complete Example

The following files show a complete, working Shooter from the YAMS `simple_robot-2027` Commands v2 example. It is not the same hardware as this tutorial: it drives two Kraken X60s through `TalonFX` motor controllers instead of a NEO through a `SparkMax`, with different gearing and gains. The YAMS parts work the same way.

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/ShooterSubsystem.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/RobotContainer.java>" %}

The same robot in the other two flavors:

* **Java, Commands v3:** [`mechanisms/ShooterMechanism.java`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/simple_robot-2027/src/main/java/first/robot/mechanisms/ShooterMechanism.java) in `examples/commands3/simple_robot-2027`
* **C++:** [`ShooterSubsystem.h`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/include/subsystems/ShooterSubsystem.h) and [`ShooterSubsystem.cpp`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/cpp/subsystems/ShooterSubsystem.cpp) in `examples/cpptest`


# Step 1: The motor controller

Configure the SparkMax and wrap it in a SmartMotorController.

{% hint style="info" %}
This page assumes a project with YAMS and REVLib installed. If you do not have one yet, start at [Create a project and install YAMS](/documentation/tutorials/project-setup).
{% endhint %}

A `SmartMotorController` is how YAMS talks to a motor controller. It takes three things:

1. **The vendor's motor controller object**, here a `SparkMax`.
2. **The motor** that is plugged into it, here one NEO.
3. **A `SmartMotorControllerConfig`** that says what the motor controller should do: its control mode, its PID and feedforward gains, the gearing between the motor and the flywheel, and how heavy the wheel is for the simulation.

YAMS applies the config to the `SparkMax` for you, and uses the same config to build the simulation.

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

## Create the file

{% tabs %}
{% tab title="Java, Commands v2" %}
Create `ShooterSubsystem.java` in the `subsystems` folder, next to the template's `ExampleSubsystem.java`.
{% endtab %}

{% tab title="Java, Commands v3" %}
Create `ShooterMechanism.java` in the `mechanisms` folder, next to the template's `ExampleMechanism.java`.

The config comes from `yams.commands3.config`, and it takes the `Mechanism` where Commands v2 passes the subsystem.
{% endtab %}

{% tab title="C++" %}
Create `ShooterSubsystem.hpp` in `src/main/include/subsystems` and `ShooterSubsystem.cpp` in `src/main/cpp/subsystems`.

YAMS keeps a pointer to the config and to the `SparkMax`, so in C++ both are members of the subsystem. The constructor fills in the config and then creates the `SmartMotorController`, which is why that one is a `std::optional`.

`WithFeedback` is the C++ name of `withClosedLoopController`, and `WithMotorGearing` of `withGearing`.
{% endtab %}
{% endtabs %}

{% stepper %}
{% step %}

### Start the config

Everything the motor controller should do goes into one `SmartMotorControllerConfig`. Start it, and put it in closed loop mode so that it can hold a speed. A flywheel holds a speed and has no position to protect, so this config has no motion profile, no starting position and no soft limits. It coasts at zero power, so that the wheel is not braked to a stop every time a command ends.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
// What the motor controller should do: its control mode, gains and gearing.
private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
// What the motor controller should do: its control mode, gains and gearing.
private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ShooterSubsystem.hpp" %}

```cpp
// What the motor controller should do. It is filled in by the constructor.
yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;
```

{% endcode %}

{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
// What the motor controller should do: its control mode, gains and gearing.
m_smcConfig
    .WithSubsystem(this)
    .WithClosedLoopMode()
```

{% endcode %}
{% endtab %}
{% endtabs %}

Want the details? [Motor basics](/documentation/reference/editor/config/motor-basics)
{% endstep %}

{% step %}

### PID and feedforward

An arm or an elevator uses **position control**: you ask for an angle or a height, and the motor stops once it gets there. A flywheel uses **velocity control**: you ask for a speed, and the motor has to keep pushing the whole time to hold it. Most of that push is predictable, because a motor's speed is close to proportional to its voltage. So the feedforward gain `kV` (volts for each rotation per second) does most of the work, and the PID gain `kP` only fixes the small error left over, such as the drop when a game piece goes through. There is no motion profile: the wheel can spin up as fast as the motor allows.

The `Sim` options are used only in simulation, so the simulation can be tuned without touching the real robot's gains.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
// Feedback constants (PID), on the real robot and in simulation.
// A flywheel holds a speed, so it gets no motion profile.
.withClosedLoopController(0.2, 0, 0)
.withSimClosedLoopController(0.2, 0, 0)
// Feedforward constants, on the real robot and in simulation.
.withFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
.withSimFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
// Feedback constants (PID), on the real robot and in simulation.
// A flywheel holds a speed, so it gets no motion profile.
.withClosedLoopController(0.2, 0, 0)
.withSimClosedLoopController(0.2, 0, 0)
// Feedforward constants, on the real robot and in simulation.
.withFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
.withSimFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
// Feedback constants (PID), on the real robot and in simulation.
// A flywheel holds a speed, so it gets no motion profile.
.WithFeedback(0.2, 0, 0)
.WithSimClosedLoopController(0.2, 0, 0)
// Feedforward constants (kS and kV), on the real robot and in simulation.
.WithFeedforward(Feedforward{0_V, wpi::units::unit_t<Feedforward::kv_unit>{0.19}})
.WithSimFeedforward(Feedforward{0_V, wpi::units::unit_t<Feedforward::kv_unit>{0.19}})
```

{% endcode %}
{% endtab %}
{% endtabs %}

These gains are **placeholders**, worked out from the motor rather than tuned. A NEO turns at most about 5676 RPM on 12 volts. Through the 1.5:1 gearing below, that is about 3784 RPM, or 63 rotations per second, at the wheel. 12 volts divided by 63 rotations per second is about `0.19` volts for each rotation per second, which is the `kV` here. `kP` of `0.2` adds 0.2 volts for each rotation per second (60 RPM) the wheel is too slow.

**What to expect with them:** in simulation the wheel reaches a 3000 RPM setpoint in well under a second and holds it within a few tens of RPM, inside the 50 RPM band you use in step 3. A real wheel has friction, so it settles a little below the setpoint until you tune it in [Step 5: Tune it](/documentation/tutorials/shooter-flywheels/tune).

**For your robot:** Work out your own starting `kV` the same way: 12 divided by your wheel's top speed in rotations per second. Then tune both gains in step 5.

Want the details? [Closed loop control](/documentation/reference/editor/config/closed-loop-control) and [Feedforward](/documentation/reference/editor/config/feedforward)
{% endstep %}

{% step %}

### Gearing and the wheel's weight

The gearing tells YAMS how many turns of the motor make one turn of the flywheel. A shooter usually has little or no reduction, because it needs speed more than force: here one turn of the wheel is 1.5 turns of the motor.

**Top speed = motor free speed / reduction.** A NEO's free speed is about 5676 RPM, so 1.5:1 gives about 3784 RPM at the wheel. Keep your setpoints below that, with some room spare: this tutorial uses 2000 and 3000 RPM. A 12:1 gearbox would cap the same wheel at about 470 RPM.

The moment of inertia says how hard the wheel is to spin up, and only the simulation uses it. For a solid wheel it is 0.5 x mass x radius squared, in kilograms and meters. With it, the simulated wheel spins up in well under a second, like a real one. Leave it out and YAMS uses 0.02 kg m², more than twenty times this wheel, so the simulated wheel takes several seconds to reach speed.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
// Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
.withGearing(new MechanismGearing(GearBox.fromReductionStages(1.5)))
// How hard the wheel is to spin up, used by the simulation: two 4 inch
// wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
.withMomentOfInertia(KilogramSquareMeters.of(0.0009))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
// Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
.withGearing(new MechanismGearing(GearBox.fromReductionStages(1.5)))
// How hard the wheel is to spin up, used by the simulation: two 4 inch
// wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
.withMomentOfInertia(KilogramSquareMeters.of(0.0009))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
// Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
.WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.5})})
// How hard the wheel is to spin up, used by the simulation: two 4 inch
// wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
.WithMOI(wpi::units::kilogram_square_meter_t{0.0009})
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** List your gearbox stages in order, from the motor outward, such as `3, 4` for a 3:1 stage followed by a 4:1 stage. Use `1` if the wheel is on the motor's shaft. Work out your wheel's moment of inertia from its mass and radius, adding the shaft and any pulleys if they are heavy.

Want the details? [Gearing and units](/documentation/reference/editor/config/gearing-and-units)
{% endstep %}

{% step %}

### Direction, idle mode and current limit

Which way is positive, what the motor does when it is given no power, and the most current it may draw.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
.withMotorInverted(false)
// Coast, so that the wheel spins down by itself instead of being braked to a stop.
.withZeroPower(MotorMode.COAST)
.withStatorCurrentLimit(Amps.of(40))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
.withMotorInverted(false)
// Coast, so that the wheel spins down by itself instead of being braked to a stop.
.withZeroPower(MotorMode.COAST)
.withStatorCurrentLimit(Amps.of(40))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
.WithMotorInverted(false)
// Coast, so that the wheel spins down by itself instead of being braked to a stop.
.WithZeroPower(Cfg::MotorMode::COAST)
.WithStatorCurrentLimit(40_A)
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Flip the inversion if a positive output moves your flywheel the wrong way. Keep the current limit within what your wiring and breaker allow.

Want the details? [Motor basics](/documentation/reference/editor/config/motor-basics) and [Limits and protection](/documentation/reference/editor/config/limits-and-protection)
{% endstep %}

{% step %}

### Telemetry

The name the motor gets on your dashboard, and how much it publishes. `HIGH` publishes everything, which is what you want while tuning.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
// Telemetry name and how much to publish.
.withTelemetry("ShooterMotor", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
// Telemetry name and how much to publish.
.withTelemetry("ShooterMotor", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
// Telemetry name and how much to publish.
.WithTelemetry("ShooterMotor", Cfg::TelemetryVerbosity::HIGH);
```

{% endcode %}
{% endtab %}
{% endtabs %}

Want the details? [Telemetry](/documentation/understanding/telemetry)
{% endstep %}

{% step %}

### The motor controller object

This is the vendor's own object, exactly as you would create it without YAMS.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
// The vendor motor controller object: a SPARK MAX with CAN ID 4.
private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
// The vendor motor controller object: a SPARK MAX with CAN ID 4.
private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ShooterSubsystem.hpp" %}

```cpp
// The vendor motor controller object: a SPARK MAX with CAN ID 4.
rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the CAN ID to yours. Using a different motor controller? See the [feature matrix](/documentation/reference/editor/feature-matrix) for the wrapper that goes with it.
{% endstep %}

{% step %}

### The SmartMotorController

The wrapper brings the three together: the motor controller object, the motor plugged into it, and the config.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
// The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
// The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ShooterSubsystem.hpp" %}

```cpp
// The SmartMotorController, created in the constructor once the config is ready.
std::optional<yams::motorcontrollers::local::SparkWrapper> m_motor;
```

{% endcode %}

{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
// The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
m_motor.emplace(&m_spark, wpi::math::DCMotor::NEO(1), &m_smcConfig);
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the motor to the kind and the number of motors you have.

Want the details? [Smart motor controllers](/documentation/reference/editor)
{% endstep %}
{% endstepper %}

## The complete file

Every part above, in one file, with its imports.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" lineNumbers="true" %}

```java
package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.KilogramSquareMeters;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ShooterSubsystem extends SubsystemBase {

  // What the motor controller should do: its control mode, gains and gearing.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      // A flywheel holds a speed, so it gets no motion profile.
      .withClosedLoopController(0.2, 0, 0)
      .withSimClosedLoopController(0.2, 0, 0)
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      // Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1.5)))
      // How hard the wheel is to spin up, used by the simulation: two 4 inch
      // wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0009))
      .withMotorInverted(false)
      // Coast, so that the wheel spins down by itself instead of being braked to a stop.
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      // Telemetry name and how much to publish.
      .withTelemetry("ShooterMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" lineNumbers="true" %}

```java
package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.KilogramSquareMeters;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands3.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ShooterMechanism implements Mechanism {

  // What the motor controller should do: its control mode, gains and gearing.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      // A flywheel holds a speed, so it gets no motion profile.
      .withClosedLoopController(0.2, 0, 0)
      .withSimClosedLoopController(0.2, 0, 0)
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      // Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1.5)))
      // How hard the wheel is to spin up, used by the simulation: two 4 inch
      // wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0009))
      .withMotorInverted(false)
      // Coast, so that the wheel spins down by itself instead of being braked to a stop.
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      // Telemetry name and how much to publish.
      .withTelemetry("ShooterMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ShooterSubsystem.hpp" lineNumbers="true" %}

```cpp
#pragma once

#include <optional>

#include <rev/SparkMax.h>
#include <wpi/commands2/SubsystemBase.hpp>
#include <wpi/hardware/bus/CANPort.hpp>

#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/local/SparkWrapper.hpp"

class ShooterSubsystem : public wpi::cmd::SubsystemBase {
 public:
  ShooterSubsystem();

 private:
  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};

  // What the motor controller should do. It is filled in by the constructor.
  yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;

  // The SmartMotorController, created in the constructor once the config is ready.
  std::optional<yams::motorcontrollers::local::SparkWrapper> m_motor;
};
```

{% endcode %}

{% code title="cpp/subsystems/ShooterSubsystem.cpp" lineNumbers="true" %}

```cpp
#include "subsystems/ShooterSubsystem.hpp"

#include <wpi/math/controller/SimpleMotorFeedforward.hpp>
#include <wpi/math/system/DCMotor.hpp>
#include <wpi/units/angle.hpp>
#include <wpi/units/current.hpp>
#include <wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;
using Feedforward = wpi::math::SimpleMotorFeedforward<wpi::units::turns>;

ShooterSubsystem::ShooterSubsystem() {
  // What the motor controller should do: its control mode, gains and gearing.
  m_smcConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // Feedback constants (PID), on the real robot and in simulation.
      // A flywheel holds a speed, so it gets no motion profile.
      .WithFeedback(0.2, 0, 0)
      .WithSimClosedLoopController(0.2, 0, 0)
      // Feedforward constants (kS and kV), on the real robot and in simulation.
      .WithFeedforward(Feedforward{0_V, wpi::units::unit_t<Feedforward::kv_unit>{0.19}})
      .WithSimFeedforward(Feedforward{0_V, wpi::units::unit_t<Feedforward::kv_unit>{0.19}})
      // Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.5})})
      // How hard the wheel is to spin up, used by the simulation: two 4 inch
      // wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
      .WithMOI(wpi::units::kilogram_square_meter_t{0.0009})
      .WithMotorInverted(false)
      // Coast, so that the wheel spins down by itself instead of being braked to a stop.
      .WithZeroPower(Cfg::MotorMode::COAST)
      .WithStatorCurrentLimit(40_A)
      // Telemetry name and how much to publish.
      .WithTelemetry("ShooterMotor", Cfg::TelemetryVerbosity::HIGH);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  m_motor.emplace(&m_spark, wpi::math::DCMotor::NEO(1), &m_smcConfig);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Read more

Every option used here has its own section in the `SmartMotorControllerConfig` pages:

* [Motor basics](/documentation/reference/editor/config/motor-basics): control mode, inversion, what the motor does at zero power
* [Gearing and units](/documentation/reference/editor/config/gearing-and-units): gearing, and how rotations become distance
* [Closed loop control](/documentation/reference/editor/config/closed-loop-control), [Feedforward](/documentation/reference/editor/config/feedforward) and [Motion profiles](/documentation/reference/editor/config/motion-profiles)
* [Limits and protection](/documentation/reference/editor/config/limits-and-protection): soft limits and current limits
* [Simulation](/documentation/reference/editor/config/simulation): the simulation only gains

The PID and feedforward numbers on this page are a place to start, not tuned values. You tune them in [Step 5: Tune it](/documentation/tutorials/shooter-flywheels/tune).

## Check it

Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Build Robot Code**. It should build. Nothing moves yet, because nothing tells the motor what to do.

* **`SparkMax` or `SparkWrapper` cannot be found:** REVLib is not installed. See [Install your motor controller's library](/documentation/tutorials/project-setup#install-your-motor-controllers-library).
* **`SmartMotorControllerConfig` cannot be found:** YAMS is not installed, or the import is from the other command framework (`yams.commands2` or `yams.commands3`).


# Step 2: The flywheel

Describe the flywheel and create the FlyWheel mechanism.

The `SmartMotorController` from step 1 is configured, but nothing tells it to move yet. A `FlyWheel` adds what makes it a flywheel: a physics simulation, a drawing of the mechanism for your dashboard, and the commands and triggers you will use in step 3.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-9ac4402ed53c7caf15787f40f7a6245c3ef8a7c2%2Fmech-two-configs.png?alt=media" alt="A diagram. A mechanism config, which says what the mechanism is, such as its length, mass, hard stops and how it is drawn, and a SmartMotorControllerConfig, which says how its motor behaves, such as gearing, PID, feedforward, soft limits and current, both go into the mechanism class. The mechanism then drives the simulation&#x27;s physics and Mechanism2d, and the real robot&#x27;s commands and telemetry."><figcaption><p>Two configs go into one mechanism.</p></figcaption></figure>

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

{% stepper %}
{% step %}

### Describe the flywheel

`FlyWheelConfig` describes the flywheel itself. Its diameter sets the size of the drawing on your dashboard, and it is what lets you ask for a surface speed in meters per second as well as a rotation speed. The simulation does not use the diameter to spin the wheel: it uses the moment of inertia you gave the motor controller config in step 1.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-babbb75421fd9c4ce31766c309aa5ef9e853b193%2Fmech-flywheel-diameter.png?alt=media" alt="A flywheel with its diameter marked, spinning at 3000 RPM and throwing a game piece from its surface. For a 4 inch wheel the circumference is 0.319 meters, 3000 RPM is 50 rotations per second, and the surface speed is 16 meters per second. getLinearVelocity and getAngularVelocity on the config convert between the two."><figcaption><p>The diameter converts rotation speed to surface speed.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
private final FlyWheelConfig shooterConfig = new FlyWheelConfig()
    // The diameter of the flywheel: the size of its drawing, and what turns RPM into surface speed.
    .withDiameter(Inches.of(4))
    // Telemetry name and how much to publish.
    .withTelemetry("Shooter", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
private final FlyWheelConfig shooterConfig = new FlyWheelConfig()
    // The diameter of the flywheel: the size of its drawing, and what turns RPM into surface speed.
    .withDiameter(Inches.of(4))
    // Telemetry name and how much to publish.
    .withTelemetry("Shooter", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ShooterSubsystem.hpp" %}

```cpp
// The flywheel mechanism and its config, also set up in the constructor.
yams::mechanisms::config::FlyWheelConfig m_shooterConfig;
std::optional<yams::mechanisms::velocity::FlyWheel> m_shooter;
```

{% endcode %}

{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
m_shooterConfig
    // The diameter of the flywheel: the size of its drawing, and what turns RPM into surface speed.
    .WithRollerDiameter(4_in)
    // Telemetry name.
    .WithTelemetryName("Shooter");
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Set the diameter of your wheel.

Want the details? [Shooters](/documentation/understanding/shooters) and [FlyWheelConfig](/documentation/reference/mechanism-configs/flywheel-config)
{% endstep %}

{% step %}

### Create the FlyWheel

Hand the config, and the `SmartMotorController` from step 1, to the `FlyWheel`.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
// The flywheel mechanism.
private final FlyWheel shooter = new FlyWheel(shooterConfig, motor);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
// The flywheel mechanism.
private final FlyWheel shooter = new FlyWheel(shooterConfig, motor);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
// The flywheel mechanism.
m_shooter.emplace(&m_shooterConfig, &m_motor.value());
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}

### Update it every loop

Two calls keep the mechanism alive. `updateTelemetry()` publishes its telemetry and applies anything you change through live tuning. `simIterate()` runs the physics simulation, and only needs to run in simulation.

In Commands v2 and C++ the scheduler calls a subsystem's periodic methods for you, so there is nothing more to do.

In Commands v3 nothing calls a `Mechanism` every loop, so `Robot.java` does it, the same way as in [the arm tutorial's step 2](/documentation/tutorials/arm/mechanism#update-it-every-loop), which explains each part. Every mechanism gets one line in `robotPeriodic()`, before `scheduler.run()`, and one in `simulationInit()`.

If your `Robot.java` already has `simulationInit()` and `startSimulation(...)` from the arm tutorial, add the lines below. If not, copy the whole `Robot.java` from the Commands v3 tab of [the complete file](#the-complete-file).

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
@Override
public void periodic() {
  // Publishes the flywheel's telemetry, and applies anything changed through live tuning.
  shooter.updateTelemetry();
}

@Override
public void simulationPeriodic() {
  // Runs the flywheel's physics simulation.
  shooter.simIterate();
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
/** Call this from Robot.robotPeriodic(), before the scheduler runs. */
public void periodic() {
  // Publishes the flywheel's telemetry, and applies anything changed through live tuning.
  shooter.updateTelemetry();
}

/** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
public void simulationPeriodic() {
  // Runs the flywheel's physics simulation.
  shooter.simIterate();
}
```

{% endcode %}

{% code title="Robot.java" %}

```java
import first.robot.mechanisms.ShooterMechanism;

// A field of Robot.
final ShooterMechanism shooter = new ShooterMechanism();

// In robotPeriodic(), before scheduler.run():
shooter.periodic();

// In simulationInit():
startSimulation("Shooter", shooter::simulationPeriodic);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ShooterSubsystem.hpp" %}

```cpp
void Periodic() override;
void SimulationPeriodic() override;
```

{% endcode %}

{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
void ShooterSubsystem::Periodic() {
  // Publishes the flywheel's telemetry, and applies anything changed through live tuning.
  m_shooter->UpdateTelemetry();
}

void ShooterSubsystem::SimulationPeriodic() {
  // Runs the flywheel's physics simulation.
  m_shooter->SimIterate();
}
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
The highlighted lines are new in this step.

`ShooterSubsystem` extends `SubsystemBase`, so the scheduler calls `periodic()` and `simulationPeriodic()` for you.

<pre class="language-java" data-title="subsystems/ShooterSubsystem.java" data-line-numbers><code class="lang-java">package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
<strong>import static org.wpilib.units.Units.Inches;
</strong>import static org.wpilib.units.Units.KilogramSquareMeters;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands2.config.SmartMotorControllerConfig;
<strong>import yams.commands2.mechanisms.FlyWheel;
</strong>import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
<strong>import yams.core.mechanisms.config.FlyWheelConfig;
</strong>import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ShooterSubsystem extends SubsystemBase {

  // What the motor controller should do: its control mode, gains and gearing.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      // A flywheel holds a speed, so it gets no motion profile.
      .withClosedLoopController(0.2, 0, 0)
      .withSimClosedLoopController(0.2, 0, 0)
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      // Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1.5)))
      // How hard the wheel is to spin up, used by the simulation: two 4 inch
      // wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0009))
      .withMotorInverted(false)
      // Coast, so that the wheel spins down by itself instead of being braked to a stop.
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      // Telemetry name and how much to publish.
      .withTelemetry("ShooterMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

<strong>  private final FlyWheelConfig shooterConfig = new FlyWheelConfig()
</strong><strong>      // The diameter of the flywheel: the size of its drawing, and what turns RPM into surface speed.
</strong><strong>      .withDiameter(Inches.of(4))
</strong><strong>      // Telemetry name and how much to publish.
</strong><strong>      .withTelemetry("Shooter", TelemetryVerbosity.HIGH);
</strong>
<strong>  // The flywheel mechanism.
</strong><strong>  private final FlyWheel shooter = new FlyWheel(shooterConfig, motor);
</strong>
<strong>  @Override
</strong><strong>  public void periodic() {
</strong><strong>    // Publishes the flywheel's telemetry, and applies anything changed through live tuning.
</strong><strong>    shooter.updateTelemetry();
</strong><strong>  }
</strong>
<strong>  @Override
</strong><strong>  public void simulationPeriodic() {
</strong><strong>    // Runs the flywheel's physics simulation.
</strong><strong>    shooter.simIterate();
</strong><strong>  }
</strong>}
</code></pre>

{% endtab %}

{% tab title="Java, Commands v3" %}
The highlighted lines are new in this step.

Nothing calls a periodic method on a Commands v3 `Mechanism`, so give the class its own `periodic()` and `simulationPeriodic()` and create the mechanism in `Robot.java`. Then call its `periodic()` from `Robot.robotPeriodic()`, before the scheduler runs, and start its `simulationPeriodic()` in its own `Notifier` from `Robot.simulationInit()`.

<pre class="language-java" data-title="mechanisms/ShooterMechanism.java" data-line-numbers><code class="lang-java">package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
<strong>import static org.wpilib.units.Units.Inches;
</strong>import static org.wpilib.units.Units.KilogramSquareMeters;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands3.config.SmartMotorControllerConfig;
<strong>import yams.commands3.mechanisms.FlyWheel;
</strong>import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
<strong>import yams.core.mechanisms.config.FlyWheelConfig;
</strong>import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ShooterMechanism implements Mechanism {

  // What the motor controller should do: its control mode, gains and gearing.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      // A flywheel holds a speed, so it gets no motion profile.
      .withClosedLoopController(0.2, 0, 0)
      .withSimClosedLoopController(0.2, 0, 0)
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      // Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1.5)))
      // How hard the wheel is to spin up, used by the simulation: two 4 inch
      // wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0009))
      .withMotorInverted(false)
      // Coast, so that the wheel spins down by itself instead of being braked to a stop.
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      // Telemetry name and how much to publish.
      .withTelemetry("ShooterMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

<strong>  private final FlyWheelConfig shooterConfig = new FlyWheelConfig()
</strong><strong>      // The diameter of the flywheel: the size of its drawing, and what turns RPM into surface speed.
</strong><strong>      .withDiameter(Inches.of(4))
</strong><strong>      // Telemetry name and how much to publish.
</strong><strong>      .withTelemetry("Shooter", TelemetryVerbosity.HIGH);
</strong>
<strong>  // The flywheel mechanism.
</strong><strong>  private final FlyWheel shooter = new FlyWheel(shooterConfig, motor);
</strong>
<strong>  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
</strong><strong>  public void periodic() {
</strong><strong>    // Publishes the flywheel's telemetry, and applies anything changed through live tuning.
</strong><strong>    shooter.updateTelemetry();
</strong><strong>  }
</strong>
<strong>  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
</strong><strong>  public void simulationPeriodic() {
</strong><strong>    // Runs the flywheel's physics simulation.
</strong><strong>    shooter.simIterate();
</strong><strong>  }
</strong>}
</code></pre>

<pre class="language-java" data-title="Robot.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import java.util.ArrayList;
</strong><strong>import java.util.List;
</strong>import org.wpilib.command3.Scheduler;
import org.wpilib.command3.button.CommandGamepad;
import org.wpilib.framework.OpModeRobot;
<strong>import org.wpilib.system.Notifier;
</strong><strong>import org.wpilib.telemetry.Telemetry;
</strong>import first.robot.constants.DriverConstants;
<strong>import first.robot.mechanisms.ShooterMechanism;
</strong>import first.robot.mechanisms.ExampleMechanism;

public class Robot extends OpModeRobot {
  final ExampleMechanism exampleMechanism = new ExampleMechanism();
<strong>  final ShooterMechanism shooter = new ShooterMechanism();
</strong>  final CommandGamepad exampleController =
      new CommandGamepad(DriverConstants.DRIVER_CONTROLLER_PORT);

<strong>  // The scheduler that runs every command.
</strong><strong>  private final Scheduler scheduler = Scheduler.getDefault();
</strong><strong>  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
</strong><strong>  private final List&#x3C;Notifier> simulationNotifiers = new ArrayList&#x3C;>();
</strong>
  public Robot() {}

  @Override
  public void robotPeriodic() {
<strong>    // Runs every loop, on the robot and in simulation.
</strong><strong>    // Update the mechanism before the scheduler runs its commands.
</strong><strong>    shooter.periodic();
</strong><strong>    scheduler.run();
</strong><strong>    // Publish the scheduler, so that a dashboard shows which commands are running.
</strong><strong>    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
</strong><strong>  }
</strong>
<strong>  @Override
</strong><strong>  public void simulationInit() {
</strong><strong>    // Runs once, when the simulation starts.
</strong><strong>    // Run each mechanism's simulation in its own Notifier, every robot loop.
</strong><strong>    startSimulation("Shooter", shooter::simulationPeriodic);
</strong><strong>  }
</strong>
<strong>  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
</strong><strong>  private void startSimulation(String name, Runnable simulationPeriodic) {
</strong><strong>    Notifier notifier = new Notifier(simulationPeriodic);
</strong><strong>    notifier.setName(name + " Simulation");
</strong><strong>    notifier.startPeriodic(getPeriod());
</strong><strong>    simulationNotifiers.add(notifier);
</strong><strong>  }
</strong>}
</code></pre>

{% endtab %}

{% tab title="C++" %}
The highlighted lines are new in this step.

`WithRollerDiameter` is the C++ name of `withDiameter`. The C++ mechanism configs take a telemetry name only.

<pre class="language-cpp" data-title="include/subsystems/ShooterSubsystem.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include &#x3C;optional>

#include &#x3C;rev/SparkMax.h>
#include &#x3C;wpi/commands2/SubsystemBase.hpp>
#include &#x3C;wpi/hardware/bus/CANPort.hpp>

<strong>#include "yams/mechanisms/config/FlyWheelConfig.hpp"
</strong><strong>#include "yams/mechanisms/velocity/FlyWheel.hpp"
</strong>#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/local/SparkWrapper.hpp"

class ShooterSubsystem : public wpi::cmd::SubsystemBase {
 public:
  ShooterSubsystem();

<strong>  void Periodic() override;
</strong><strong>  void SimulationPeriodic() override;
</strong>
 private:
  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};

  // What the motor controller should do. It is filled in by the constructor.
  yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;

  // The SmartMotorController, created in the constructor once the config is ready.
  std::optional&#x3C;yams::motorcontrollers::local::SparkWrapper> m_motor;

<strong>  // The flywheel mechanism and its config, also set up in the constructor.
</strong><strong>  yams::mechanisms::config::FlyWheelConfig m_shooterConfig;
</strong><strong>  std::optional&#x3C;yams::mechanisms::velocity::FlyWheel> m_shooter;
</strong>};
</code></pre>

<pre class="language-cpp" data-title="cpp/subsystems/ShooterSubsystem.cpp" data-line-numbers><code class="lang-cpp">#include "subsystems/ShooterSubsystem.hpp"

#include &#x3C;wpi/math/controller/SimpleMotorFeedforward.hpp>
#include &#x3C;wpi/math/system/DCMotor.hpp>
#include &#x3C;wpi/units/angle.hpp>
#include &#x3C;wpi/units/current.hpp>
<strong>#include &#x3C;wpi/units/length.hpp>
</strong>#include &#x3C;wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;
using Feedforward = wpi::math::SimpleMotorFeedforward&#x3C;wpi::units::turns>;

ShooterSubsystem::ShooterSubsystem() {
  // What the motor controller should do: its control mode, gains and gearing.
  m_smcConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // Feedback constants (PID), on the real robot and in simulation.
      // A flywheel holds a speed, so it gets no motion profile.
      .WithFeedback(0.2, 0, 0)
      .WithSimClosedLoopController(0.2, 0, 0)
      // Feedforward constants (kS and kV), on the real robot and in simulation.
      .WithFeedforward(Feedforward{0_V, wpi::units::unit_t&#x3C;Feedforward::kv_unit>{0.19}})
      .WithSimFeedforward(Feedforward{0_V, wpi::units::unit_t&#x3C;Feedforward::kv_unit>{0.19}})
      // Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.5})})
      // How hard the wheel is to spin up, used by the simulation: two 4 inch
      // wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
      .WithMOI(wpi::units::kilogram_square_meter_t{0.0009})
      .WithMotorInverted(false)
      // Coast, so that the wheel spins down by itself instead of being braked to a stop.
      .WithZeroPower(Cfg::MotorMode::COAST)
      .WithStatorCurrentLimit(40_A)
      // Telemetry name and how much to publish.
      .WithTelemetry("ShooterMotor", Cfg::TelemetryVerbosity::HIGH);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  m_motor.emplace(&#x26;m_spark, wpi::math::DCMotor::NEO(1), &#x26;m_smcConfig);

<strong>  m_shooterConfig
</strong><strong>      // The diameter of the flywheel: the size of its drawing, and what turns RPM into surface speed.
</strong><strong>      .WithRollerDiameter(4_in)
</strong><strong>      // Telemetry name.
</strong><strong>      .WithTelemetryName("Shooter");
</strong>
<strong>  // The flywheel mechanism.
</strong><strong>  m_shooter.emplace(&#x26;m_shooterConfig, &#x26;m_motor.value());
</strong>}

<strong>void ShooterSubsystem::Periodic() {
</strong><strong>  // Publishes the flywheel's telemetry, and applies anything changed through live tuning.
</strong><strong>  m_shooter->UpdateTelemetry();
</strong><strong>}
</strong>
<strong>void ShooterSubsystem::SimulationPeriodic() {
</strong><strong>  // Runs the flywheel's physics simulation.
</strong><strong>  m_shooter->SimIterate();
</strong><strong>}
</strong></code></pre>

{% endtab %}
{% endtabs %}

## Check it

Build the code again. You can already run the simulation as in [step 4](/documentation/tutorials/shooter-flywheels/simulate): the flywheel is drawn, standing still. It does not spin yet, because nothing gives it a setpoint.

* **`FlyWheel` cannot be found:** the import is from the other command framework. Commands v2 uses `yams.commands2.mechanisms.FlyWheel`, Commands v3 uses `yams.commands3.mechanisms.FlyWheel`.


# Step 3: Commands and buttons

Make commands from the FlyWheel and bind them to controller buttons.

The `FlyWheel` makes commands for you. Your class hands them out, and the buttons schedule them.

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

{% stepper %}
{% step %}

### Make the commands

The `FlyWheel` makes the commands. Your class only hands them out, so that the rest of the robot code never touches the motor directly.

| What it does                                                  | Java, Commands v2                | Java, Commands v3                | C++                                   |
| ------------------------------------------------------------- | -------------------------------- | -------------------------------- | ------------------------------------- |
| Spin at a speed and hold it. It never ends on its own.        | `shooter.run(speed)`             | `shooter.run(speed)`             | `m_shooter->Run(speed)`               |
| Drive at a duty cycle from -1 to 1, with the closed loop off. | `shooter.set(dutycycle)`         | `shooter.set(dutycycle)`         | `m_shooter->Set(dutycycle)`           |
| A `Trigger` that is true while the flywheel is near a speed.  | `shooter.near(speed, tolerance)` | `shooter.near(speed, tolerance)` | `m_shooter->IsNear(speed, tolerance)` |

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
/** Spin at a speed and hold it. This command does not end on its own. */
public Command run(AngularVelocity speed) {
  return shooter.run(speed);
}

/** Drive the flywheel with a duty cycle from -1 to 1. The closed loop is not used. */
public Command set(double dutycycle) {
  return shooter.set(dutycycle);
}

/** True while the flywheel is within 50 RPM of a speed. */
public Trigger atSpeed(AngularVelocity speed) {
  return shooter.near(speed, RPM.of(50));
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
/** Spin at a speed and hold it. This command does not end on its own. */
public Command setVelocity(AngularVelocity speed) {
  return shooter.run(speed);
}

/** Drive the flywheel with a duty cycle from -1 to 1. The closed loop is not used. */
public Command set(double dutycycle) {
  return shooter.set(dutycycle);
}

/** True while the flywheel is within 50 RPM of a speed. */
public Trigger atSpeed(AngularVelocity speed) {
  return shooter.near(speed, RPM.of(50));
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ShooterSubsystem.hpp" %}

```cpp
/** Spin at a speed and hold it. This command does not end on its own. */
wpi::cmd::CommandPtr Run(wpi::units::revolutions_per_minute_t speed);

/** Drive the flywheel with a duty cycle from -1 to 1. The closed loop is not used. */
wpi::cmd::CommandPtr Set(double dutycycle);

/** True while the flywheel is within 50 RPM of a speed. */
wpi::cmd::Trigger AtSpeed(wpi::units::revolutions_per_minute_t speed);
```

{% endcode %}

{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
wpi::cmd::CommandPtr ShooterSubsystem::Run(wpi::units::revolutions_per_minute_t speed) {
  return m_shooter->Run(wpi::units::degrees_per_second_t{speed});
}

wpi::cmd::CommandPtr ShooterSubsystem::Set(double dutycycle) {
  return m_shooter->Set(dutycycle);
}

wpi::cmd::Trigger ShooterSubsystem::AtSpeed(wpi::units::revolutions_per_minute_t speed) {
  return m_shooter->IsNear(speed, 50_rpm);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Rename these to suit your robot, or add more. Each one is a single line.

Want the details? [When mechanism commands end](/documentation/understanding/run-vs-runto)
{% endstep %}

{% step %}

### Set the default command

The **default command** runs whenever no other command is using the shooter. Here it sets a duty cycle of 0, so the flywheel coasts. In Commands v3 the default command is given the lowest priority, so that any other command for the mechanism can interrupt it.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="RobotContainer.java" %}

```java
import first.robot.subsystems.ShooterSubsystem;

private final ShooterSubsystem shooter = new ShooterSubsystem();

// When no other command is using the shooter, let the flywheel coast.
shooter.setDefaultCommand(shooter.set(0));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
/** Let the flywheel coast at the lowest priority, so that any other shooter command can interrupt it. */
public Command idle() {
  return run(coroutine -> coroutine.await(shooter.set(0)))
      .withPriority(Command.LOWEST_PRIORITY)
      .named("Shooter Idle");
}
```

{% endcode %}

{% code title="Robot.java" %}

```java
public class Robot extends OpModeRobot {
  // ...

  public Robot() {
    // When no other command is using the shooter, let the flywheel coast.
    shooter.setDefaultCommand(shooter.idle());
  }

  // ...
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/RobotContainer.hpp" %}

```cpp
#include "subsystems/ShooterSubsystem.hpp"

ShooterSubsystem shooter;
```

{% endcode %}

{% code title="cpp/RobotContainer.cpp" %}

```cpp
// When no other command is using the shooter, let the flywheel coast.
shooter.SetDefaultCommand(shooter.Set(0));
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Choose what your mechanism should do when nobody is asking anything of it.
{% endstep %}

{% step %}

### Bind the buttons

`whileTrue` runs a command for as long as its button is held, and cancels it on release. The default command then takes back over.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-0fc5e90d8bfb48b6d8993524dec3f62a7fb75d70%2Ftutorial-shooter-buttons.gif?alt=media" alt="Animation of the four face buttons of a controller, the flywheel, and the command that is running. With no button held the default command runs: a duty cycle of 0, so the flywheel coasts. While A is held its command runs: hold the flywheel at a speed, shown as 60 RPM. While B is held: hold it at a faster speed, shown as 300 RPM. While X is held the flywheel is driven at a 30 percent duty cycle with the closed loop off. Each time a button is released the default command takes back over."><figcaption><p>A held button owns the flywheel. Let go, and the default command lets it coast down. The animation shows slower speeds than the 2000 and 3000 RPM used on this page; the buttons work the same way.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="RobotContainer.java" %}

```java
// Hold a speed while the bottom (A) or right (B) face button is held.
driverController.faceDown().whileTrue(shooter.run(RPM.of(2000)));
driverController.faceRight().whileTrue(shooter.run(RPM.of(3000)));
// Drive the flywheel forward or backward while the left (X) or top (Y) face button is held.
driverController.faceLeft().whileTrue(shooter.set(0.3));
driverController.faceUp().whileTrue(shooter.set(-0.3));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="ExampleTeleop.java" %}

```java
// Hold a speed while the bottom (A) or right (B) face button is held.
robot.exampleController.faceDown().whileTrue(robot.shooter.setVelocity(RPM.of(2000)));
robot.exampleController.faceRight().whileTrue(robot.shooter.setVelocity(RPM.of(3000)));
// Drive the flywheel forward or backward while the left (X) or top (Y) face button is held.
robot.exampleController.faceLeft().whileTrue(robot.shooter.set(0.3));
robot.exampleController.faceUp().whileTrue(robot.shooter.set(-0.3));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/RobotContainer.cpp" %}

```cpp
// Hold a speed while the bottom (A) or right (B) face button is held.
driverController.FaceDown().WhileTrue(shooter.Run(2000_rpm));
driverController.FaceRight().WhileTrue(shooter.Run(3000_rpm));
// Drive the flywheel forward or backward while the left (X) or top (Y) face button is held.
driverController.FaceLeft().WhileTrue(shooter.Set(0.3));
driverController.FaceUp().WhileTrue(shooter.Set(-0.3));
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Pick your own buttons and setpoints. Use `onTrue` instead if one press should start a command that keeps running after the button is released.
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
The highlighted lines are new in this step.

Add the commands to `ShooterSubsystem.java`, then create the subsystem and bind the buttons in `RobotContainer.java`. The template bound the right face button to its example command; that binding is replaced.

<pre class="language-java" data-title="subsystems/ShooterSubsystem.java" data-line-numbers><code class="lang-java">package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.KilogramSquareMeters;
<strong>import static org.wpilib.units.Units.RPM;
</strong>
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
<strong>import org.wpilib.command2.Command;
</strong>import org.wpilib.command2.SubsystemBase;
<strong>import org.wpilib.command2.button.Trigger;
</strong>import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
<strong>import org.wpilib.units.measure.AngularVelocity;
</strong>import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.mechanisms.FlyWheel;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.FlyWheelConfig;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ShooterSubsystem extends SubsystemBase {

  // What the motor controller should do: its control mode, gains and gearing.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      // A flywheel holds a speed, so it gets no motion profile.
      .withClosedLoopController(0.2, 0, 0)
      .withSimClosedLoopController(0.2, 0, 0)
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      // Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1.5)))
      // How hard the wheel is to spin up, used by the simulation: two 4 inch
      // wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0009))
      .withMotorInverted(false)
      // Coast, so that the wheel spins down by itself instead of being braked to a stop.
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      // Telemetry name and how much to publish.
      .withTelemetry("ShooterMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

  private final FlyWheelConfig shooterConfig = new FlyWheelConfig()
      // The diameter of the flywheel: the size of its drawing, and what turns RPM into surface speed.
      .withDiameter(Inches.of(4))
      // Telemetry name and how much to publish.
      .withTelemetry("Shooter", TelemetryVerbosity.HIGH);

  // The flywheel mechanism.
  private final FlyWheel shooter = new FlyWheel(shooterConfig, motor);

<strong>  /** Spin at a speed and hold it. This command does not end on its own. */
</strong><strong>  public Command run(AngularVelocity speed) {
</strong><strong>    return shooter.run(speed);
</strong><strong>  }
</strong>
<strong>  /** Drive the flywheel with a duty cycle from -1 to 1. The closed loop is not used. */
</strong><strong>  public Command set(double dutycycle) {
</strong><strong>    return shooter.set(dutycycle);
</strong><strong>  }
</strong>
<strong>  /** True while the flywheel is within 50 RPM of a speed. */
</strong><strong>  public Trigger atSpeed(AngularVelocity speed) {
</strong><strong>    return shooter.near(speed, RPM.of(50));
</strong><strong>  }
</strong>
  @Override
  public void periodic() {
    // Publishes the flywheel's telemetry, and applies anything changed through live tuning.
    shooter.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    // Runs the flywheel's physics simulation.
    shooter.simIterate();
  }
}
</code></pre>

<pre class="language-java" data-title="RobotContainer.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.RPM;
</strong>
import org.wpilib.command2.Command;
import org.wpilib.command2.button.CommandGamepad;
import org.wpilib.command2.button.Trigger;
import first.robot.Constants.OperatorConstants;
import first.robot.commands.Autos;
import first.robot.commands.ExampleCommand;
<strong>import first.robot.subsystems.ShooterSubsystem;
</strong>import first.robot.subsystems.ExampleSubsystem;

/**
 * This class is where the bulk of the robot should be declared. Since Command-based is a
 * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
 * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
 * subsystems, commands, and trigger mappings) should be declared here.
 */
public class RobotContainer {
  // The robot's subsystems and commands are defined here...
  private final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
<strong>  private final ShooterSubsystem shooter = new ShooterSubsystem();
</strong>
  private final CommandGamepad driverController =
      new CommandGamepad(OperatorConstants.DRIVER_CONTROLLER_PORT);

  /** The container for the robot. Contains subsystems, OI devices, and commands. */
  public RobotContainer() {
    // Configure the trigger bindings
    configureBindings();

<strong>    // When no other command is using the shooter, let the flywheel coast.
</strong><strong>    shooter.setDefaultCommand(shooter.set(0));
</strong>  }

  /**
   * Use this method to define your trigger->command mappings. Triggers can be created via the
   * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary
   * predicate, or via the named factories in {@link org.wpilib.command2.button.CommandGenericHID}'s
   * subclasses for {@link CommandGamepad Gamepad} gamepads or {@link
   * org.wpilib.command2.button.CommandJoystick Flight joysticks}.
   */
  private void configureBindings() {
    // Schedule `ExampleCommand` when `exampleCondition` changes to `true`
    new Trigger(exampleSubsystem::exampleCondition).onTrue(new ExampleCommand(exampleSubsystem));

<strong>    // Hold a speed while the bottom (A) or right (B) face button is held.
</strong><strong>    driverController.faceDown().whileTrue(shooter.run(RPM.of(2000)));
</strong><strong>    driverController.faceRight().whileTrue(shooter.run(RPM.of(3000)));
</strong><strong>    // Drive the flywheel forward or backward while the left (X) or top (Y) face button is held.
</strong><strong>    driverController.faceLeft().whileTrue(shooter.set(0.3));
</strong><strong>    driverController.faceUp().whileTrue(shooter.set(-0.3));
</strong>  }

  /**
   * Use this to pass the autonomous command to the main {@link Robot} class.
   *
   * @return the command to run in autonomous
   */
  public Command getAutonomousCommand() {
    // An example command will be run in autonomous
    return Autos.exampleAuto(exampleSubsystem);
  }
}
</code></pre>

{% endtab %}

{% tab title="Java, Commands v3" %}
The highlighted lines are new in this step.

Add the commands to `ShooterMechanism.java`, set the default command in `Robot.java`, and bind the buttons in `ExampleTeleop.java`.

A `Mechanism` already has a `run(...)` method that takes a coroutine, so the commands here have their own names. The default command is wrapped with `Command.LOWEST_PRIORITY`, so that any other command for the flywheel can interrupt it.

<pre class="language-java" data-title="mechanisms/ShooterMechanism.java" data-line-numbers><code class="lang-java">package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.KilogramSquareMeters;
<strong>import static org.wpilib.units.Units.RPM;
</strong>
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
<strong>import org.wpilib.command3.Command;
</strong>import org.wpilib.command3.Mechanism;
<strong>import org.wpilib.command3.Trigger;
</strong>import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
<strong>import org.wpilib.units.measure.AngularVelocity;
</strong>import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.mechanisms.FlyWheel;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.FlyWheelConfig;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ShooterMechanism implements Mechanism {

  // What the motor controller should do: its control mode, gains and gearing.
  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback constants (PID), on the real robot and in simulation.
      // A flywheel holds a speed, so it gets no motion profile.
      .withClosedLoopController(0.2, 0, 0)
      .withSimClosedLoopController(0.2, 0, 0)
      // Feedforward constants, on the real robot and in simulation.
      .withFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))
      // Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1.5)))
      // How hard the wheel is to spin up, used by the simulation: two 4 inch
      // wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0009))
      .withMotorInverted(false)
      // Coast, so that the wheel spins down by itself instead of being braked to a stop.
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      // Telemetry name and how much to publish.
      .withTelemetry("ShooterMotor", TelemetryVerbosity.HIGH);

  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

  private final FlyWheelConfig shooterConfig = new FlyWheelConfig()
      // The diameter of the flywheel: the size of its drawing, and what turns RPM into surface speed.
      .withDiameter(Inches.of(4))
      // Telemetry name and how much to publish.
      .withTelemetry("Shooter", TelemetryVerbosity.HIGH);

  // The flywheel mechanism.
  private final FlyWheel shooter = new FlyWheel(shooterConfig, motor);

<strong>  /** Spin at a speed and hold it. This command does not end on its own. */
</strong><strong>  public Command setVelocity(AngularVelocity speed) {
</strong><strong>    return shooter.run(speed);
</strong><strong>  }
</strong>
<strong>  /** Drive the flywheel with a duty cycle from -1 to 1. The closed loop is not used. */
</strong><strong>  public Command set(double dutycycle) {
</strong><strong>    return shooter.set(dutycycle);
</strong><strong>  }
</strong>
<strong>  /** True while the flywheel is within 50 RPM of a speed. */
</strong><strong>  public Trigger atSpeed(AngularVelocity speed) {
</strong><strong>    return shooter.near(speed, RPM.of(50));
</strong><strong>  }
</strong>
<strong>  /** Let the flywheel coast at the lowest priority, so that any other shooter command can interrupt it. */
</strong><strong>  public Command idle() {
</strong><strong>    return run(coroutine -> coroutine.await(shooter.set(0)))
</strong><strong>        .withPriority(Command.LOWEST_PRIORITY)
</strong><strong>        .named("Shooter Idle");
</strong><strong>  }
</strong>
  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
  public void periodic() {
    // Publishes the flywheel's telemetry, and applies anything changed through live tuning.
    shooter.updateTelemetry();
  }

  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
  public void simulationPeriodic() {
    // Runs the flywheel's physics simulation.
    shooter.simIterate();
  }
}
</code></pre>

<pre class="language-java" data-title="Robot.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.RPM;
</strong>
import java.util.ArrayList;
import java.util.List;
import org.wpilib.command3.Scheduler;
import org.wpilib.command3.button.CommandGamepad;
import org.wpilib.framework.OpModeRobot;
import org.wpilib.system.Notifier;
import org.wpilib.telemetry.Telemetry;
import first.robot.constants.DriverConstants;
import first.robot.mechanisms.ShooterMechanism;
import first.robot.mechanisms.ExampleMechanism;

public class Robot extends OpModeRobot {
  final ExampleMechanism exampleMechanism = new ExampleMechanism();
  final ShooterMechanism shooter = new ShooterMechanism();
  final CommandGamepad exampleController =
      new CommandGamepad(DriverConstants.DRIVER_CONTROLLER_PORT);

  // The scheduler that runs every command.
  private final Scheduler scheduler = Scheduler.getDefault();
  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
  private final List&#x3C;Notifier> simulationNotifiers = new ArrayList&#x3C;>();

<strong>  public Robot() {
</strong><strong>    // When no other command is using the shooter, let the flywheel coast.
</strong><strong>    shooter.setDefaultCommand(shooter.idle());
</strong><strong>  }
</strong>
  @Override
  public void robotPeriodic() {
    // Runs every loop, on the robot and in simulation.
    // Update the mechanism before the scheduler runs its commands.
    shooter.periodic();
    scheduler.run();
    // Publish the scheduler, so that a dashboard shows which commands are running.
    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
  }

  @Override
  public void simulationInit() {
    // Runs once, when the simulation starts.
    // Run each mechanism's simulation in its own Notifier, every robot loop.
    startSimulation("Shooter", shooter::simulationPeriodic);
  }

  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
  private void startSimulation(String name, Runnable simulationPeriodic) {
    Notifier notifier = new Notifier(simulationPeriodic);
    notifier.setName(name + " Simulation");
    notifier.startPeriodic(getPeriod());
    simulationNotifiers.add(notifier);
  }
}
</code></pre>

<pre class="language-java" data-title="ExampleTeleop.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.RPM;
</strong>
import org.wpilib.opmode.OpMode;
import org.wpilib.opmode.Teleop;

@Teleop
public class ExampleTeleop implements OpMode {
  public ExampleTeleop(Robot robot) {
    robot.exampleController.rightStick().whileTrue(robot.exampleMechanism.exampleCommand());

<strong>    // Hold a speed while the bottom (A) or right (B) face button is held.
</strong><strong>    robot.exampleController.faceDown().whileTrue(robot.shooter.setVelocity(RPM.of(2000)));
</strong><strong>    robot.exampleController.faceRight().whileTrue(robot.shooter.setVelocity(RPM.of(3000)));
</strong><strong>    // Drive the flywheel forward or backward while the left (X) or top (Y) face button is held.
</strong><strong>    robot.exampleController.faceLeft().whileTrue(robot.shooter.set(0.3));
</strong><strong>    robot.exampleController.faceUp().whileTrue(robot.shooter.set(-0.3));
</strong>  }
}
</code></pre>

{% endtab %}

{% tab title="C++" %}
The highlighted lines are new in this step.

Declare the commands in `ShooterSubsystem.hpp`, define them in `ShooterSubsystem.cpp`, then create the subsystem and bind the buttons in `RobotContainer`. The template bound the right face button to its example command; that binding is replaced.

<pre class="language-cpp" data-title="include/subsystems/ShooterSubsystem.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include &#x3C;optional>

#include &#x3C;rev/SparkMax.h>
<strong>#include &#x3C;wpi/commands2/CommandPtr.hpp>
</strong>#include &#x3C;wpi/commands2/SubsystemBase.hpp>
<strong>#include &#x3C;wpi/commands2/button/Trigger.hpp>
</strong>#include &#x3C;wpi/hardware/bus/CANPort.hpp>
<strong>#include &#x3C;wpi/units/angular_velocity.hpp>
</strong>
#include "yams/mechanisms/config/FlyWheelConfig.hpp"
#include "yams/mechanisms/velocity/FlyWheel.hpp"
#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/local/SparkWrapper.hpp"

class ShooterSubsystem : public wpi::cmd::SubsystemBase {
 public:
  ShooterSubsystem();

<strong>  /** Spin at a speed and hold it. This command does not end on its own. */
</strong><strong>  wpi::cmd::CommandPtr Run(wpi::units::revolutions_per_minute_t speed);
</strong>
<strong>  /** Drive the flywheel with a duty cycle from -1 to 1. The closed loop is not used. */
</strong><strong>  wpi::cmd::CommandPtr Set(double dutycycle);
</strong>
<strong>  /** True while the flywheel is within 50 RPM of a speed. */
</strong><strong>  wpi::cmd::Trigger AtSpeed(wpi::units::revolutions_per_minute_t speed);
</strong>
  void Periodic() override;
  void SimulationPeriodic() override;

 private:
  // The vendor motor controller object: a SPARK MAX with CAN ID 4.
  rev::spark::SparkMax m_spark{wpi::CANPort::CAN_S0, 4, rev::spark::SparkMax::MotorType::kBrushless};

  // What the motor controller should do. It is filled in by the constructor.
  yams::motorcontrollers::SmartMotorControllerConfig m_smcConfig;

  // The SmartMotorController, created in the constructor once the config is ready.
  std::optional&#x3C;yams::motorcontrollers::local::SparkWrapper> m_motor;

  // The flywheel mechanism and its config, also set up in the constructor.
  yams::mechanisms::config::FlyWheelConfig m_shooterConfig;
  std::optional&#x3C;yams::mechanisms::velocity::FlyWheel> m_shooter;
};
</code></pre>

<pre class="language-cpp" data-title="cpp/subsystems/ShooterSubsystem.cpp" data-line-numbers><code class="lang-cpp">#include "subsystems/ShooterSubsystem.hpp"

#include &#x3C;wpi/math/controller/SimpleMotorFeedforward.hpp>
#include &#x3C;wpi/math/system/DCMotor.hpp>
#include &#x3C;wpi/units/angle.hpp>
#include &#x3C;wpi/units/current.hpp>
#include &#x3C;wpi/units/length.hpp>
#include &#x3C;wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;
using Feedforward = wpi::math::SimpleMotorFeedforward&#x3C;wpi::units::turns>;

ShooterSubsystem::ShooterSubsystem() {
  // What the motor controller should do: its control mode, gains and gearing.
  m_smcConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // Feedback constants (PID), on the real robot and in simulation.
      // A flywheel holds a speed, so it gets no motion profile.
      .WithFeedback(0.2, 0, 0)
      .WithSimClosedLoopController(0.2, 0, 0)
      // Feedforward constants (kS and kV), on the real robot and in simulation.
      .WithFeedforward(Feedforward{0_V, wpi::units::unit_t&#x3C;Feedforward::kv_unit>{0.19}})
      .WithSimFeedforward(Feedforward{0_V, wpi::units::unit_t&#x3C;Feedforward::kv_unit>{0.19}})
      // Gearing from the motor rotor to the flywheel: one 1.5:1 stage.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.5})})
      // How hard the wheel is to spin up, used by the simulation: two 4 inch
      // wheels, 0.68 kg (1.5 lb) in all, as solid discs: 0.5 x 0.68 kg x (0.0508 m)^2.
      .WithMOI(wpi::units::kilogram_square_meter_t{0.0009})
      .WithMotorInverted(false)
      // Coast, so that the wheel spins down by itself instead of being braked to a stop.
      .WithZeroPower(Cfg::MotorMode::COAST)
      .WithStatorCurrentLimit(40_A)
      // Telemetry name and how much to publish.
      .WithTelemetry("ShooterMotor", Cfg::TelemetryVerbosity::HIGH);

  // The SmartMotorController applies the config to the SPARK MAX, which drives one NEO.
  m_motor.emplace(&#x26;m_spark, wpi::math::DCMotor::NEO(1), &#x26;m_smcConfig);

  m_shooterConfig
      // The diameter of the flywheel: the size of its drawing, and what turns RPM into surface speed.
      .WithRollerDiameter(4_in)
      // Telemetry name.
      .WithTelemetryName("Shooter");

  // The flywheel mechanism.
  m_shooter.emplace(&#x26;m_shooterConfig, &#x26;m_motor.value());
}

<strong>wpi::cmd::CommandPtr ShooterSubsystem::Run(wpi::units::revolutions_per_minute_t speed) {
</strong><strong>  return m_shooter->Run(wpi::units::degrees_per_second_t{speed});
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr ShooterSubsystem::Set(double dutycycle) {
</strong><strong>  return m_shooter->Set(dutycycle);
</strong><strong>}
</strong>
<strong>wpi::cmd::Trigger ShooterSubsystem::AtSpeed(wpi::units::revolutions_per_minute_t speed) {
</strong><strong>  return m_shooter->IsNear(speed, 50_rpm);
</strong><strong>}
</strong>
void ShooterSubsystem::Periodic() {
  // Publishes the flywheel's telemetry, and applies anything changed through live tuning.
  m_shooter->UpdateTelemetry();
}

void ShooterSubsystem::SimulationPeriodic() {
  // Runs the flywheel's physics simulation.
  m_shooter->SimIterate();
}
</code></pre>

<pre class="language-cpp" data-title="include/RobotContainer.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include "Constants.hpp"
<strong>#include "subsystems/ShooterSubsystem.hpp"
</strong>#include "subsystems/ExampleSubsystem.hpp"
#include "wpi/commands2/CommandPtr.hpp"
#include "wpi/commands2/button/CommandGamepad.hpp"

/**
 * This class is where the bulk of the robot should be declared.  Since
 * Command-based is a "declarative" paradigm, very little robot logic should
 * actually be handled in the {@link Robot} periodic methods (other than the
 * scheduler calls).  Instead, the structure of the robot (including subsystems,
 * commands, and trigger mappings) should be declared here.
 */
class RobotContainer {
 public:
  RobotContainer();

  wpi::cmd::CommandPtr GetAutonomousCommand();

 private:
  // Replace with CommandPS4Controller or CommandJoystick if needed
  wpi::cmd::CommandGamepad driverController{
      OperatorConstants::DRIVER_CONTROLLER_PORT};

  // The robot's subsystems are defined here...
  ExampleSubsystem subsystem;
<strong>  ShooterSubsystem shooter;
</strong>
  void ConfigureBindings();
};
</code></pre>

<pre class="language-cpp" data-title="cpp/RobotContainer.cpp" data-line-numbers><code class="lang-cpp">#include "RobotContainer.hpp"

#include "commands/Autos.hpp"
#include "commands/ExampleCommand.hpp"
#include "wpi/commands2/button/Trigger.hpp"
<strong>#include "wpi/units/angular_velocity.hpp"
</strong>
RobotContainer::RobotContainer() {
  // Initialize all of your commands and subsystems here

<strong>  // When no other command is using the shooter, let the flywheel coast.
</strong><strong>  shooter.SetDefaultCommand(shooter.Set(0));
</strong>
  // Configure the button bindings
  ConfigureBindings();
}

void RobotContainer::ConfigureBindings() {
  // Configure your trigger bindings here

  // Schedule `ExampleCommand` when `exampleCondition` changes to `true`
  wpi::cmd::Trigger([this] {
    return subsystem.ExampleCondition();
  }).OnTrue(ExampleCommand(&#x26;subsystem).ToPtr());

<strong>  // Hold a speed while the bottom (A) or right (B) face button is held.
</strong><strong>  driverController.FaceDown().WhileTrue(shooter.Run(2000_rpm));
</strong><strong>  driverController.FaceRight().WhileTrue(shooter.Run(3000_rpm));
</strong><strong>  // Drive the flywheel forward or backward while the left (X) or top (Y) face button is held.
</strong><strong>  driverController.FaceLeft().WhileTrue(shooter.Set(0.3));
</strong><strong>  driverController.FaceUp().WhileTrue(shooter.Set(-0.3));
</strong>}

wpi::cmd::CommandPtr RobotContainer::GetAutonomousCommand() {
  // An example command will be run in autonomous
  return autos::ExampleAuto(&#x26;subsystem);
}
</code></pre>

{% endtab %}
{% endtabs %}

{% hint style="info" %}
These commands are helpers that start and stop the closed loop for you. If you would rather set setpoints from your own command or state machine, see [How do I write my own mechanism command?](/documentation/how-to-mechanisms/how-do-i-write-my-own-mechanism-command).
{% endhint %}

## Knowing when it is up to speed

The `atSpeed` method added in this step returns a `Trigger`. Nothing in this tutorial uses it yet: it is there for the next thing you will want, which is to feed a game piece only once the flywheel is ready.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b7c09583292da1d92654951d57a0bdc8f656350d%2Fhowto-shooter-at-speed.gif?alt=media" alt="Animation of a flywheel spinning up to 3000 RPM and shooting two balls, with a band of 100 RPM around the setpoint. Each shot drops the speed by several hundred RPM, and it overshoots and rings as it recovers. A lane for the at speed trigger is true inside the band, including for an instant each time the speed passes through it. A lane for the feeder, which uses the trigger with a 0.1 second debounce, is only true once the speed has stayed in the band, so the second ball is not fed until the wheel has settled."><figcaption><p>Each shot slows the wheel and it rings as it recovers. The tolerance band and a debounce keep the feeder off until it has settled.</p></figcaption></figure>

[How do I shoot with a shooter?](/documentation/how-to-mechanisms/how-to-shoot-with-a-shooter) shows how to bind a feeder to it.

## Check it

Build the code. If it builds, every button is bound. Next you run it and press them.


# Step 4: Simulate it

Run the flywheel in simulation and drive it with a controller.

The code from the first three steps runs on your computer exactly as it will on the robot. YAMS simulates the motor, the gearing and the weight of the wheel, so the closed loop and the commands behave the way they will on the real flywheel.

{% stepper %}
{% step %}

### Start the simulation

{% tabs %}
{% tab title="Java, Commands v2" %}
Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Simulate Robot Code**. If you are asked which extensions to run, tick **Sim GUI**.
{% endtab %}

{% tab title="Java, Commands v3" %}
Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Simulate Robot Code**. If you are asked which extensions to run, tick **Sim GUI**.

The buttons are bound in the `ExampleTeleop` op mode, so that is the op mode to run when you enable.

If the simulated mechanism never moves, check that `Robot.java` has a `simulationInit()` that calls `startSimulation(...)` for the mechanism.
{% endtab %}

{% tab title="C++" %}
Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Simulate Robot Code**. If you are asked which extensions to run, tick **Sim GUI**.

The first C++ build compiles the whole project, so it takes a few minutes. Later builds are much faster.
{% endtab %}
{% endtabs %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2F04lmc9ZfMo9DPRuEp9gh%2Fimage.png?alt=media&amp;token=de5c8905-4617-4c86-bfd9-2c4acdccac09" alt="The Sim GUI, the window that opens with the simulation, with the Robot State, System Joysticks, Joysticks and NetworkTables panels"><figcaption><p>The Sim GUI.</p></figcaption></figure>
{% endstep %}

{% step %}

### Drive it

1. Connect a controller to your computer, then drag it from **System Joysticks** to **Joystick\[0]**.
2. Open the simulated mechanism with **NetworkTables -> Mechanisms -> Shooter -> mechanism**. It is named after the `withTelemetry("Shooter", ...)` on the `FlyWheelConfig`. It shows the wheel as a line from its center that turns as the wheel turns.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FcufWQatcQViVu5mEOyVw%2FRobot%20Simulation%209_9_2025%209_12_17%20AM.png?alt=media&amp;token=f1795431-782b-4bf2-98e1-e3dc5d7c670e" alt="The Sim GUI with the shooter&#x27;s Mechanism2d window open: a single line from the center of the window, which turns with the flywheel"><figcaption></figcaption></figure>

3. Resize **Shooter/mechanism** to your liking.
4. Commands v3: pick the `ExampleTeleop` op mode first. Then press **Teleoperated** in **Robot State**. The controller now drives the simulated flywheel just as it would the real one.

No controller? The Sim GUI can use the keyboard as a joystick: drag **Keyboard 0** to **Joystick\[0]**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FvjOotyuG42754B8HsLoF%2FRobot%20Simulation%202025-09-09%2009-05-32.gif?alt=media&amp;token=678777db-d986-4f43-860c-be74413155b0" alt="The simulated flywheel in its Mechanism2d window, the line spinning while a button is held and slowing to a stop after it is released"><figcaption></figcaption></figure>

#### Watch the speed, not the drawing

The drawing is only updated 50 times a second. At shooter speeds the line turns most of a rotation between updates, so it can look slow, frozen, or even turning backward. To see the real speed, graph it:

* In the Sim GUI, open **NetworkTables -> Mechanisms -> Shooter -> ShooterMotor -> mechanism** and find **velocity**. Or graph `NT:/Mechanisms/Shooter/ShooterMotor/mechanism/velocity` in [AdvantageScope](https://docs.advantagescope.org/).
* It is in **rotations per second**. Multiply by 60 for RPM: 3000 RPM reads as `50`.
  {% endstep %}
  {% endstepper %}

## What you should see

* Before you enable, and with no button held, the speed is 0.
* Holding **A** spins the wheel up to 2000 RPM (about `33` on the graph), and holding **B** to 3000 RPM (`50`). It gets there in well under a second and stays within a few tens of RPM.
* Holding **X** drives it forward, and **Y** backward, at 30% duty cycle, with the closed loop off.
* Let go of any button, and the default command sets a duty cycle of 0, so the wheel spins down.

## If it did not work

* **The shooter is not in the NetworkTables menu.** Look under **Mechanisms**, not **SmartDashboard**.
* **The wheel does not spin.** Check the robot is enabled in **Teleoperated** and the controller is on **Joystick\[0]**. Commands v3: check you picked `ExampleTeleop`, and that `Robot.simulationInit()` starts the shooter's simulation with `startSimulation(...)`.
* **The wheel takes many seconds to reach speed.** The motor controller config is missing `withMomentOfInertia`, so the simulation uses a much heavier wheel. See step 1, part 3.
* **The speed settles well below the setpoint.** `kV` is too low, or 0. See step 1, part 2.

More problems and fixes: [Troubleshooting](/documentation/tutorials/troubleshooting).


# Step 5: Tune it

Tune the flywheel's gains while the simulation runs, then copy them into your code.

The gains from step 1 are placeholders worked out from the motor: `kV` is 0.19 and `kP` is 0.2. On this page you find your own, while the simulation runs, the same way you will tune the real flywheel on the robot. You change one number at a time on a dashboard and watch a graph. Nothing is saved until you copy the numbers into your code at the end.

A flywheel is tuned differently from [an arm](/documentation/tutorials/arm/tune) or an elevator. There is no gravity to hold up and no motion profile. `kV` does most of the work, so you find it first, with `kP` turned off, then add a little `kP` to fix what is left.

{% hint style="info" %}
**In simulation you are tuning the simulation's gains.** While the code runs in simulation, live tuning changes the `withSimClosedLoopController` and `withSimFeedforward` values. On the real robot it changes `withClosedLoopController` and `withFeedforward`. The two sets are kept apart because a simulated flywheel is never exactly like the real one.
{% endhint %}

## Before you start

* Start the simulation and enable **Teleoperated**, as in [step 4](/documentation/tutorials/shooter-flywheels/simulate). The wheel is still.
* Do not press any of the shooter's buttons while you tune. A button runs another shooter command, which stops live tuning. If that happens, start live tuning again.

Then tune with the YAMS Live Tuner, or by typing the values in AdvantageScope and Elastic. Both change the same values, so pick one.

{% tabs %}
{% tab title="YAMS Live Tuner" %}
The [YAMS Live Tuner](/documentation/how-to-tuning/live-tuning/live-tuner) is a web page that walks you through it: it checks the flywheel before anything moves, then you send setpoints and change gains while watching a graph.

{% stepper %}
{% step %}

### Connect

Open [tuning.yassrobotics.com](https://tuning.yassrobotics.com/), pick **Simulation**, and press **Connect**. If your browser asks whether the page may connect to devices on your local network, allow it.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-a69700cfe54cd00a2f7ec8e514840bf783ce65f6%2Flive-tuner-connect.png?alt=media" alt="The Live Tuner header connected to a simulation on localhost, with the robot in Teleop and enabled"><figcaption><p>Connected to the simulation, with the robot enabled in Teleop.</p></figcaption></figure>

**Check it:** the badge in the header shows `localhost`, with the robot enabled in Teleop.
{% endstep %}

{% step %}

### Pick the flywheel

1. Under **Telemetry name**, choose `Shooter/ShooterMotor`: the names from the flywheel's and the motor's `withTelemetry`.
2. Under **Live Tuning command**, choose `ShooterSubsystem` (Commands v2 and C++) or `ShooterMechanism` (Commands v3).
3. Set **Type** to **Flywheel**, and leave **Second flywheel** at **None**. Speeds are in RPM, both on the slider and on the graph.
4. Press **Continue**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-f331f3ab7194c779fc84a1613574192671ee3da5%2Flive-tuner-tutorial-flywheel-mechanism.png?alt=media" alt="The Mechanism step with Shooter/ShooterMotor as the telemetry name, ShooterSubsystem as the Live Tuning command, Flywheel as the type and None as the second flywheel"><figcaption><p>The tutorial shooter: its motor, its subsystem's <code>Live Tuning</code> command, and the Flywheel type.</p></figcaption></figure>

**Check it:** the telemetry card shows the wheel at 0 RPM.
{% endstep %}

{% step %}

### Checklist and inversions

1. Tick every item on the pre-motion checklist, leave **Current trip (A)** at 40, and press **Continue**.
2. Tick the confirmation and press **Start voltage control**.
3. Drag the voltage slider to the right and hold it. The wheel spins up. Let go once **Positive voltage moves forward** is ticked: the slider goes back to 0 V and the wheel coasts down.
4. If the wheel does not move with the slider all the way to the right, select the number at the slider's right end, 1.00 V to start with, and raise it a little. The number at the left end sets how far the slider goes the other way.
5. Press **Finish check**.

A flywheel has no range of motion, so the Live tune card opens next.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d60d22dde8e08b851c0d2c1073eb9294b9b28b92%2Flive-tuner-tutorial-flywheel-inversions.png?alt=media" alt="Holding 0.5 V: the speed reads 160 RPM, Positive voltage moves forward is ticked, and Finish check is enabled"><figcaption><p>At 0.5 V the wheel spins forward.</p></figcaption></figure>

**Check it:** **Positive voltage moves forward** was ticked when the wheel spun up. If the Live Tuner warns that the speed went the wrong way, the motor or encoder inversion in step 1 is wrong.
{% endstep %}

{% step %}

### Start live tuning and find kV

Press **Start Live Tuning**. The speeds and gains you send are now applied to the flywheel every loop.

`kV` is how many volts the motor needs for each rotation per second of wheel speed. Get it right and the wheel reaches the setpoint on feedforward alone.

1. On the Settings card's **Gains** tab, type `0` into **kP** and `0` into **kV**. Now nothing drives the wheel.
2. On the **Setpoints** tab, press **3000 RPM**. The wheel stays still.
3. Type `0.1` into **kV**. The wheel spins up, but settles well below 3000 RPM.
4. Raise **kV** a little at a time until the measured speed settles on the setpoint. For this NEO and 1.5:1 gearing it ends up near `0.19`. If the wheel settles above the setpoint, `kV` is too high: lower it.
5. Press **2000 RPM**. The wheel should settle on it too, with the same `kV`.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-9e6e1323921776d95197633dfeb94fecd9d6522c%2Flive-tuner-tutorial-flywheel-kv.png?alt=media" alt="Live tuning the flywheel at a 3000 RPM setpoint with kP at 0: after kV is raised from 0.1 to 0.19 the speed jumps from about 1600 RPM to 3048 RPM, just above the setpoint"><figcaption><p>kV raised from 0.1 to 0.19: the speed climbs from about 1600 RPM to just above 3000 RPM. A little lower and it settles on it.</p></figcaption></figure>

**Check it:** at both 2000 and 3000 RPM the measured speed settles on the setpoint, with `kP` still at 0.

`kS` is the voltage that just overcomes friction. The simulation has no friction, so leave it at 0 here.
{% endstep %}

{% step %}

### Tune kP

`kP` adds a push when the wheel is slower or faster than the setpoint, such as when a game piece goes through and drags it down. It is volts for each rotation per second of error.

1. Type `0.1` into **kP**.
2. Turn on **Alternate setpoints**, with **Setpoint A** at `2000` and **Setpoint B** at `3000`. The wheel now changes speed every 5 seconds.
3. Raise **kP** a step at a time (0.2, 0.3, ...). Each step should make the wheel reach the new speed a little faster.
4. Stop, and press **was** to go back one step, when the speed overshoots the setpoint or the line gets jittery.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-80b35664edf7a3829c710503992b098fc6c6aab7%2Flive-tuner-tutorial-flywheel-alternate.png?alt=media" alt="Alternate setpoints on, switching between 2000 and 3000 RPM with kP at 0.3: the measured speed follows each step"><figcaption><p>kP 0.3, alternating between 2000 and 3000 RPM: the speed reaches each setpoint straight away.</p></figcaption></figure>

**Check it:** the speed reaches each new setpoint quickly and settles on it without bouncing around it. Press **Space** to stop when you are done.

A flywheel needs no `kD` and no motion profile: the wheel may speed up as fast as the motor allows.
{% endstep %}
{% endstepper %}
{% endtab %}

{% tab title="AdvantageScope and Elastic" %}
You type each value into its NetworkTables key yourself, and graph the flywheel in AdvantageScope.

Open [AdvantageScope](https://docs.advantagescope.org/) and connect it to the simulation (**File > Connect to Simulator**).

{% stepper %}
{% step %}

### Start live tuning

YAMS gives the flywheel a `Live Tuning` command. While it runs, numbers you type on the dashboard are applied to the flywheel straight away.

* **Commands v2 and C++:** the command is published at `NT:/Tuning/ShooterSubsystem/Live Tuning`, named after the subsystem. In [Elastic](https://frc-elastic.gitbook.io/docs), add `Tuning/ShooterSubsystem/Live Tuning` to a tab and press its button.
* **Commands v3:** the command is published at `NT:/Tuning/ShooterMechanism/Live Tuning`, named after the mechanism. Set the boolean `NT:/Tuning/ShooterMechanism/Live Tuning/running` to `true`. In AdvantageScope, first turn on tuning mode (step 2), then click the value to change it.

**Check it:** the command shows as running. The wheel is still.
{% endstep %}

{% step %}

### Find the numbers and graph the flywheel

The flywheel's values are under two tables. Both use the names from `withTelemetry`: `Shooter` for the flywheel and `ShooterMotor` for its motor.

|                  | Where                                  | Used for                                             |
| ---------------- | -------------------------------------- | ---------------------------------------------------- |
| Values you type  | `NT:/Tuning/Shooter/ShooterMotor/`     | Gains, setpoints, limits                             |
| Values you watch | `NT:/Mechanisms/Shooter/ShooterMotor/` | How fast the wheel spins and what the motor is doing |

1. In AdvantageScope, turn on **tuning mode**: the sliders icon beside the search box at the top of the sidebar. Without it, typed values are ignored.
2. Make a **Line Graph** and drag in, from `NT:/Mechanisms/Shooter/ShooterMotor/`:
   * `mechanism/velocity`: how fast the wheel spins.
   * `closedloop/setpoint/velocity`: how fast it is asked to spin.
   * `motor/outputVoltage`: the voltage the motor is given.

{% hint style="warning" %}
**You type RPM, you read rotations per second.** A setpoint typed as `3000` (RPM) is graphed as `50` (rotations per second). Divide RPM by 60 to compare. To graph in RPM, see [See both in the same units with AdvantageScope](/documentation/reference/keys-and-units#see-both-in-the-same-units-with-advantagescope).
{% endhint %}

**Check it:** the velocity lines are at 0.
{% endstep %}

{% step %}

### kV: the voltage for each speed

`kV` is how many volts the motor needs for each rotation per second of wheel speed. Get it right and the wheel reaches the setpoint on feedforward alone.

1. Type `0` into `NT:/Tuning/Shooter/ShooterMotor/closedloop/feedback/kP` and `0` into `closedloop/feedforward/kV`. Now nothing drives the wheel.
2. Type `3000` into `closedloop/setpoint/velocity`. The setpoint line jumps to 50, and the wheel stays still.
3. Type `0.1` into `closedloop/feedforward/kV`. The wheel spins up, but settles well below 50.
4. Raise `kV` a little at a time until `mechanism/velocity` settles on the setpoint line. For this NEO and 1.5:1 gearing it ends up near `0.19`. If the wheel settles above the setpoint, `kV` is too high: lower it.
5. Type `2000` into the setpoint (33 on the graph). The wheel should settle on it too, with the same `kV`.

**Check it:** at both 2000 and 3000 RPM the measured speed settles on the setpoint, with `kP` still at 0.

`kS` is the voltage that just overcomes friction. The simulation has no friction, so leave it at 0 here. On the real robot, raise `closedloop/feedforward/kS` until the wheel only just starts to turn, then back it off a little, before you tune `kV`.
{% endstep %}

{% step %}

### kP: recover faster

`kV` gets the wheel to speed. `kP` adds a push when the wheel is slower or faster than the setpoint, such as when a game piece goes through and drags it down. It is volts for each rotation per second of error.

1. Type `0.1` into `closedloop/feedback/kP`.
2. Move the setpoint between `2000` and `3000` and watch how fast the speed gets there.
3. Raise `kP` a step at a time (0.2, 0.3, ...). Each step should make the wheel reach the new speed a little faster.
4. Stop, and go back one step, when the speed overshoots the setpoint or the line gets jittery.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b7c09583292da1d92654951d57a0bdc8f656350d%2Fhowto-shooter-at-speed.gif?alt=media" alt="Animation of a flywheel spinning up to 3000 RPM and shooting two balls. Each shot drops the speed by several hundred RPM, and it overshoots and rings as it recovers. The feeder only runs once the speed has stayed inside a band around the setpoint."><figcaption><p>On the real robot each shot slows the wheel. A good kP brings it back quickly without ringing.</p></figcaption></figure>

**Check it:** the speed reaches each new setpoint quickly and settles on it without bouncing around it.

A flywheel needs no `kD` and no motion profile: the wheel may speed up as fast as the motor allows.

For more on each value, see [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order).
{% endstep %}
{% endstepper %}
{% endtab %}
{% endtabs %}

## Copy the numbers into your code

Dashboard changes are lost when the code restarts. Write the numbers you ended up with into the config from step 1. In simulation they go into the `Sim` versions.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" %}

```java
// Before
.withSimClosedLoopController(0.2, 0, 0)
.withSimFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))

// After: your numbers. SimpleMotorFeedforward takes kS, kV, kA.
.withSimClosedLoopController(0.3, 0, 0)
.withSimFeedforward(new SimpleMotorFeedforward(0, 0.188, 0))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" %}

```java
// Before
.withSimClosedLoopController(0.2, 0, 0)
.withSimFeedforward(new SimpleMotorFeedforward(0, 0.19, 0))

// After: your numbers. SimpleMotorFeedforward takes kS, kV, kA.
.withSimClosedLoopController(0.3, 0, 0)
.withSimFeedforward(new SimpleMotorFeedforward(0, 0.188, 0))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ShooterSubsystem.cpp" %}

```cpp
// Before
.WithSimClosedLoopController(0.2, 0, 0)
.WithSimFeedforward(Feedforward{0_V, wpi::units::unit_t<Feedforward::kv_unit>{0.19}})

// After: your numbers. kP, kI, kD, then kS and kV.
.WithSimClosedLoopController(0.3, 0, 0)
.WithSimFeedforward(Feedforward{0_V, wpi::units::unit_t<Feedforward::kv_unit>{0.188}})
```

{% endcode %}
{% endtab %}
{% endtabs %}

The numbers above are an example. Use the ones you found.

**Check it:** restart the simulation and enable it. Hold **A** and **B**: the wheel reaches 2000 and 3000 RPM quickly and holds each one.

## If it did not work

* **AdvantageScope: typing a value does nothing.** Turn on AdvantageScope's tuning mode, check the `Live Tuning` command is still running, and check you typed under `NT:/Tuning`, not `NT:/Mechanisms`.
* **Typing `0` as the setpoint does not stop the wheel.** Live tuning ignores a velocity setpoint of 0. To stop the wheel, disable the robot, or press a shooter button (which also stops live tuning).
* **Live Tuner: the flywheel is not in the Telemetry name list.** Check the simulation is running and you connected to **Simulation**. The list only fills in once the robot code has started.
* **Live tuning stopped on its own.** A button press, or the default command, took over the flywheel. On the Live Tuner, the current trip, leaving the range of motion, or pressing Space also stops it. Start it again.
* **The speed swings above and below the setpoint.** `kP` is too high. Lower it.
* **The numbers were gone after a restart.** They only last until the code stops. Copy them into your code, as in [Copy the numbers into your code](#copy-the-numbers-into-your-code).

More problems and fixes: [Troubleshooting](/documentation/tutorials/troubleshooting).

## Step 6: Run it on the robot

Step 6 puts the code on the real robot. Follow [the arm's step 6: Run it on the robot](/documentation/tutorials/arm/robot). It works the same for the flywheel, with these differences:

* The CAN ID is the shooter's `SparkMax`, 4 in this tutorial.
* A flywheel has no starting position and no soft limits, so skip those parts.
* For the direction check, positive should spin the wheel the way that throws a game piece **out**.
* On the first enable, hold **A** (2000 RPM) before you try **B**.
* Tune `kS`, then `kV`, then `kP` again on the robot, as in the kV and kP steps above. Friction means a real wheel needs some `kS`. Copy the robot's numbers into `withClosedLoopController` and `withFeedforward`.


# Double FlyWheel

Learn how to program a double flywheel shooter, with a separate speed for each wheel.

## Intro

At the end of this tutorial you will have a **Double FlyWheel** shooter with two independently controlled flywheels that works in both real life and simulation with the same code! Double flywheels are used where the spin on the game piece matters: running one wheel faster than the other adds backspin or topspin to a shot.

{% hint style="info" %}
This tutorial does not use the `FlyWheel` class from the [Shooter/FlyWheels](/documentation/tutorials/shooter-flywheels) tutorial. A `FlyWheel` drives one wheel, or several motors that always turn together, at one speed. Here each wheel needs its own speed, so the subsystem controls the two motor controllers directly. If you have not done the Shooter/FlyWheels tutorial, it is the easier place to start.
{% endhint %}

## What is a Double FlyWheel?

A double flywheel is a shooter with two separate flywheels, one on each side of the game piece:

* **Upper FlyWheel**: drives the top surface of the game piece
* **Lower FlyWheel**: drives the bottom surface of the game piece

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-82aa007e5ddc538d862713f91c45e15a014bd45d%2Ftutorial-double-flywheel-spin.gif?alt=media" alt="Animation of a ball passing between an upper and a lower flywheel, three times. With both at 3000 RPM the ball leaves with no spin and flies straight. With the lower flywheel faster, 3500 against 2500 RPM, it leaves with backspin and its path lifts. With the upper flywheel faster it leaves with topspin and its path dips."><figcaption><p>The faster wheel drags its side of the ball forward. Lower wheel faster is backspin; upper wheel faster is topspin.</p></figcaption></figure>

By running them at different speeds, you can:

* Add **backspin** (lower faster than upper)
* Add **topspin** (upper faster than lower)
* Shoot with **no spin** (equal speeds)

## Details

This double flywheel uses the following hardware and controls:

* Two `TalonFX` (Kraken X60), one for each flywheel
* No gearbox: each wheel is driven 1:1 from its motor. **Top speed = motor free speed / reduction**, so each wheel can reach about 6000 RPM (a Kraken X60's free speed) / 1 = 6000 RPM, comfortably above the 3500 RPM fastest preset. A 3:1 gearbox would cap it at 2000 RPM, too slow for these presets.
* 4 inch diameter, 1 pound flywheels
* Pressing the bottom face button (`A` on an Xbox controller) sets both flywheels to 3000 RPM (no spin)
* Pressing the right face button (`B` on an Xbox controller) sets the upper to 2500 RPM and the lower to 3500 RPM (backspin)
* Pressing the left face button (`X` on an Xbox controller) sets the upper to 3500 RPM and the lower to 2500 RPM (topspin)
* Pressing the top face button (`Y` on an Xbox controller) lets both flywheels coast to a stop

## The steps

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-566f3b4aca1e4516c9689be858992e904424ff9e%2Ftutorial-double-flywheel-steps.png?alt=media" alt="The three steps of the double flywheel tutorial. Step 1, two motor controllers: one config and one SmartMotorController for each flywheel. Step 2, commands and buttons: one command sets both speeds, with presets for no spin, backspin and topspin. Step 3, spin control and followers: a spin ratio between the wheels, and what to do when they share a shaft."><figcaption><p>Three steps, one page each. Then you tune it and run it on the robot.</p></figcaption></figure>

Every step has a tab for **Java with Commands v2**, **Java with Commands v3** and **C++**.

| Step                                                                                                | What you do                                                                                               |
| --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| [Before you start](/documentation/tutorials/project-setup)                                          | Create a WPILib project and install YAMS and Phoenix 6. Skip this if you already have a project.          |
| [Step 1: Two motor controllers](/documentation/tutorials/double-flywheel/motor-controllers)         | One config and one `SmartMotorController` for each flywheel.                                              |
| [Step 2: Commands and buttons](/documentation/tutorials/double-flywheel/commands)                   | One command that sets both speeds, presets for each kind of shot, the buttons, and a check in simulation. |
| [Step 3: Spin ratio and shared shafts](/documentation/tutorials/double-flywheel/spin-and-followers) | A spin ratio between the wheels, and what to change when two motors drive one wheel.                      |
| [Step 4: Tune it](/documentation/tutorials/double-flywheel/tune)                                    | Tune one wheel with the YAMS Live Tuner, copy its gains to the other, then put it on the robot.           |

{% hint style="info" %}
A subsystem should hold at most one YAMS mechanism class, so that live tuning keeps working. Both flywheels here are driven together by one subsystem, so this tutorial controls the two `SmartMotorController`s directly instead of creating two `FlyWheel` mechanisms. This is the same approach as the `DoubleFlyWheelSubsystem` in the YAMS examples.

If you would rather have a `FlyWheel` mechanism (with its `Mechanism2d` and Trigger factories) for each wheel, give each wheel its own subsystem and follow the [Shooter/FlyWheels](/documentation/tutorials/shooter-flywheels) tutorial for both.
{% endhint %}

## Complete Example

The following files from the YAMS `simple_robot-2027` Commands v2 example show a complete double flywheel subsystem with two independent flywheels, and a hood pivot in its own subsystem. Its CAN IDs, gearing and gains differ from this tutorial's.

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/doubleflywheel/DoubleFlyWheelSubsystem.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/HoodSubsystem.java>" %}

The same subsystem in the other two flavors:

* **Java, Commands v3:** [`DoubleFlyWheelMechanism.java`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/simple_robot-2027/src/main/java/first/robot/mechanisms/doubleflywheel/DoubleFlyWheelMechanism.java) in `examples/commands3/simple_robot-2027`
* **C++:** [`DoubleFlyWheelSubsystem.h`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/include/subsystems/doubleflywheel/DoubleFlyWheelSubsystem.h) and [`DoubleFlyWheelSubsystem.cpp`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/cpp/subsystems/doubleflywheel/DoubleFlyWheelSubsystem.cpp) in `examples/cpptest`


# Step 1: Two motor controllers

One config and one SmartMotorController for each flywheel.

{% hint style="info" %}
This page assumes a project with YAMS and Phoenix 6 installed. If you do not have one yet, start at [Create a project and install YAMS](/documentation/tutorials/project-setup).
{% endhint %}

Each flywheel gets its own `SmartMotorControllerConfig` and its own `SmartMotorController`, so that each can be given its own speed. The two configs are the same except for the telemetry name and the direction of the motor.

There is no `FlyWheel` mechanism in this tutorial, so three jobs a mechanism class would do fall to the subsystem:

* **Describe the wheel.** `withMomentOfInertia(...)` on the config tells the simulation how hard the wheel is to spin up. Without it the simulated wheel is far too heavy.
* **Set up the telemetry.** `setupTelemetry()` on each `SmartMotorController`, once, in the constructor. This is also what makes live tuning work.
* **Update every loop.** `updateTelemetry()` on each, and `simIterate()` on each in simulation.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-8fdf189e915651eb7bf985c14d6f3e6c63613df0%2Fsmc-followers.png?alt=media" alt="Two panels. Tightly coupled, withFollowers: a leader and a follower are on one shaft or gearbox and the follower copies the leader&#x27;s output. The motors are mechanically locked, there is one closed loop and one config, the followers are the same vendor as the leader, and voltage and duty cycle reach every motor. Loosely coupled, withLooselyCoupledFollowers: two separate motors joined only by the mechanism get the same setpoint and each runs its own PID. They are not mechanically locked, each has its own closed loop and config, vendors can be mixed, and voltage and duty cycle are not forwarded, so the leader moves alone."><figcaption><p>Tightly coupled followers share a shaft. Loosely coupled followers are separate motors.</p></figcaption></figure>

The two wheels here are separate motors on separate shafts, each given its own setpoint. If two motors drive the same wheel, see [step 3](/documentation/tutorials/double-flywheel/spin-and-followers#two-motors-on-one-wheel).

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

Create `DoubleFlywheelSubsystem` in your `subsystems` folder, or `DoubleFlywheelMechanism` in your `mechanisms` folder for Commands v3. In C++ that is a header in `src/main/include/subsystems` and a source file in `src/main/cpp/subsystems`.

{% stepper %}
{% step %}

### The upper flywheel's config

One `SmartMotorControllerConfig` says what the upper flywheel's motor controller should do: closed loop control, its gains, its gearing, and the size and weight of the wheel for the simulation.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
// Each flywheel gets its own config, so that each can be given its own speed.
private final SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    // Feedback and feedforward constants, on the real robot and in simulation.
    .withClosedLoopController(0.1, 0, 0)
    .withSimClosedLoopController(0.1, 0, 0)
    .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
    .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
    // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
    // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
    // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
    // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
    .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
    .withMotorInverted(false)
    .withZeroPower(MotorMode.COAST)
    .withStatorCurrentLimit(Amps.of(40))
    .withTelemetry("UpperFlyWheel", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
// Each flywheel gets its own config, so that each can be given its own speed.
private final SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    // Feedback and feedforward constants, on the real robot and in simulation.
    .withClosedLoopController(0.1, 0, 0)
    .withSimClosedLoopController(0.1, 0, 0)
    .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
    .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
    // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
    // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
    // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
    // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
    .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
    .withMotorInverted(false)
    .withZeroPower(MotorMode.COAST)
    .withStatorCurrentLimit(Amps.of(40))
    .withTelemetry("UpperFlyWheel", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/DoubleFlywheelSubsystem.hpp" %}

```cpp
// Each flywheel gets its own config, so that each can be given its own speed.
yams::motorcontrollers::SmartMotorControllerConfig m_upperConfig;
yams::motorcontrollers::SmartMotorControllerConfig m_lowerConfig;
```

{% endcode %}

{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" %}

```cpp
// The feedforward constants of both flywheels: kS and kV.
const Feedforward feedforward{0.1_V, wpi::units::unit_t<Feedforward::kv_unit>{0.12}};

m_upperConfig
    .WithSubsystem(this)
    .WithClosedLoopMode()
    // Feedback and feedforward constants, on the real robot and in simulation.
    .WithFeedback(0.1, 0, 0)
    .WithSimClosedLoopController(0.1, 0, 0)
    .WithFeedforward(feedforward)
    .WithSimFeedforward(feedforward)
    // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
    .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.0})})
    // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
    // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
    // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
    .WithMOI(wpi::units::kilogram_square_meter_t{0.0006})
    .WithMotorInverted(false)
    .WithZeroPower(Cfg::MotorMode::COAST)
    .WithStatorCurrentLimit(40_A)
    .WithTelemetry("UpperFlyWheel", Cfg::TelemetryVerbosity::HIGH);
```

{% endcode %}
{% endtab %}
{% endtabs %}

The gains are **placeholders** worked out from the motor. A Kraken X60 turns at most about 6000 RPM, 100 rotations per second, on 12 volts. With no gearbox the wheel does too, so `kV` is 12 / 100 = `0.12` volts for each rotation per second. `kS` of `0.1` is a guess at the voltage friction takes. The [Shooter/FlyWheels](/documentation/tutorials/shooter-flywheels/motor-controller) tutorial has a different `kV` (0.19) because it uses a different motor (a NEO, about 5676 RPM) through 1.5:1 gearing: its wheel tops out near 63 rotations per second, and 12 / 63 = 0.19.

**What to expect with them:** in simulation each wheel reaches its preset in well under a second and holds it close to the setpoint. Tune them for your robot with [the shooter tutorial's tune step](/documentation/tutorials/shooter-flywheels/tune).

`withMomentOfInertia` takes the wheel's moment of inertia in kg m². For a solid wheel it is 0.5 x mass x radius squared: 0.5 x 0.45 kg x (0.0508 m)² for a 4 inch, 1 pound wheel. (There is also a `withMomentOfInertia(length, mass)` overload, but it treats the length as an arm swinging from one end, 1/3 x mass x length², so it does not fit a wheel.)

**For your robot:** Set your own gearing (top speed = motor free speed / reduction, and keep your fastest shot below it), and your wheel's moment of inertia from its mass and radius. Work out a starting `kV` as 12 divided by the wheel's top speed in rotations per second.

Want the details? [SmartMotorControllerConfig](/documentation/reference/editor/config)
{% endstep %}

{% step %}

### The lower flywheel's config

The same again for the lower flywheel, with its own telemetry name and the motor inverted.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
// The lower flywheel is the same, except that its motor faces the other way.
private final SmartMotorControllerConfig lowerConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(0.1, 0, 0)
    .withSimClosedLoopController(0.1, 0, 0)
    .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
    .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
    .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
    .withMotorInverted(true)
    .withZeroPower(MotorMode.COAST)
    .withStatorCurrentLimit(Amps.of(40))
    .withTelemetry("LowerFlyWheel", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
// The lower flywheel is the same, except that its motor faces the other way.
private final SmartMotorControllerConfig lowerConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(0.1, 0, 0)
    .withSimClosedLoopController(0.1, 0, 0)
    .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
    .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
    .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
    .withMotorInverted(true)
    .withZeroPower(MotorMode.COAST)
    .withStatorCurrentLimit(Amps.of(40))
    .withTelemetry("LowerFlyWheel", TelemetryVerbosity.HIGH);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" %}

```cpp
// The lower flywheel is the same, except that its motor faces the other way.
m_lowerConfig
    .WithSubsystem(this)
    .WithClosedLoopMode()
    .WithFeedback(0.1, 0, 0)
    .WithSimClosedLoopController(0.1, 0, 0)
    .WithFeedforward(feedforward)
    .WithSimFeedforward(feedforward)
    .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.0})})
    .WithMOI(wpi::units::kilogram_square_meter_t{0.0006})
    .WithMotorInverted(true)
    .WithZeroPower(Cfg::MotorMode::COAST)
    .WithStatorCurrentLimit(40_A)
    .WithTelemetry("LowerFlyWheel", Cfg::TelemetryVerbosity::HIGH);
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Flip the inversion of whichever wheel spins the wrong way. Both wheels should throw the game piece out when given a positive speed.
{% endstep %}

{% step %}

### The motor controller objects

These are the vendor's own objects, exactly as you would create them without YAMS.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
// The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
private final TalonFX upperTalon = new TalonFX(1, new CANBus(CANPort.CAN_S0));
private final TalonFX lowerTalon = new TalonFX(2, new CANBus(CANPort.CAN_S0));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
// The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
private final TalonFX upperTalon = new TalonFX(1, new CANBus(CANPort.CAN_S0));
private final TalonFX lowerTalon = new TalonFX(2, new CANBus(CANPort.CAN_S0));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/DoubleFlywheelSubsystem.hpp" %}

```cpp
// The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
ctre::phoenix6::hardware::TalonFX m_upperTalon{1, ctre::phoenix6::CANBus{}};
ctre::phoenix6::hardware::TalonFX m_lowerTalon{2, ctre::phoenix6::CANBus{}};
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the CAN IDs to yours.
{% endstep %}

{% step %}

### The SmartMotorControllers

One wrapper for each flywheel brings together its motor controller object, its motor and its config.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
// One SmartMotorController for each flywheel, each driving one Kraken X60.
private final SmartMotorController upperMotor = new TalonFXWrapper(upperTalon, DCMotor.getKrakenX60(1), upperConfig);
private final SmartMotorController lowerMotor = new TalonFXWrapper(lowerTalon, DCMotor.getKrakenX60(1), lowerConfig);
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
// One SmartMotorController for each flywheel, each driving one Kraken X60.
private final SmartMotorController upperMotor = new TalonFXWrapper(upperTalon, DCMotor.getKrakenX60(1), upperConfig);
private final SmartMotorController lowerMotor = new TalonFXWrapper(lowerTalon, DCMotor.getKrakenX60(1), lowerConfig);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/DoubleFlywheelSubsystem.hpp" %}

```cpp
// One SmartMotorController for each flywheel, created in the constructor.
std::optional<yams::motorcontrollers::remote::TalonFXWrapper> m_upperMotor;
std::optional<yams::motorcontrollers::remote::TalonFXWrapper> m_lowerMotor;
```

{% endcode %}

{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" %}

```cpp
// One SmartMotorController for each flywheel, each driving one Kraken X60.
m_upperMotor.emplace(&m_upperTalon, wpi::math::DCMotor::KrakenX60(1), &m_upperConfig);
m_lowerMotor.emplace(&m_lowerTalon, wpi::math::DCMotor::KrakenX60(1), &m_lowerConfig);
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the motor to the kind and the number of motors on each wheel.

Want the details? [Smart motor controllers](/documentation/reference/editor)
{% endstep %}

{% step %}

### Set up the telemetry

A mechanism class would do this for you. Without one, call `setupTelemetry()` on each `SmartMotorController` once. This is also what makes live tuning work.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
public DoubleFlywheelSubsystem() {
  // A mechanism class would do this for us. Without one, set up the telemetry
  // (and live tuning) of each motor controller ourselves.
  upperMotor.setupTelemetry();
  lowerMotor.setupTelemetry();
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
public DoubleFlywheelMechanism() {
  // A mechanism class would do this for us. Without one, set up the telemetry
  // (and live tuning) of each motor controller ourselves.
  upperMotor.setupTelemetry();
  lowerMotor.setupTelemetry();
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" %}

```cpp
// A mechanism class would do this for us. Without one, set up the telemetry
// (and live tuning) of each motor controller ourselves.
m_upperMotor->SetupTelemetry();
m_lowerMotor->SetupTelemetry();
```

{% endcode %}
{% endtab %}
{% endtabs %}

Want the details? [Telemetry](/documentation/understanding/telemetry)
{% endstep %}

{% step %}

### Update both every loop

`updateTelemetry()` on each wheel publishes its telemetry, and `simIterate()` on each runs its simulation.

In Commands v2 and C++ the scheduler calls a subsystem's periodic methods for you, so there is nothing more to do.

In Commands v3 nothing calls a `Mechanism` every loop, so `Robot.java` does it, the same way as in [the arm tutorial's step 2](/documentation/tutorials/arm/mechanism#update-it-every-loop), which explains each part. Every mechanism gets one line in `robotPeriodic()`, before `scheduler.run()`, and one in `simulationInit()`.

If your `Robot.java` already has `simulationInit()` and `startSimulation(...)` from the arm tutorial, add the lines below. If not, copy the whole `Robot.java` from the Commands v3 tab of [the complete file](#the-complete-file).

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
@Override
public void periodic() {
  // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
  upperMotor.updateTelemetry();
  lowerMotor.updateTelemetry();
}

@Override
public void simulationPeriodic() {
  // Runs each flywheel's physics simulation.
  upperMotor.simIterate();
  lowerMotor.simIterate();
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
/** Call this from Robot.robotPeriodic(), before the scheduler runs. */
public void periodic() {
  // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
  upperMotor.updateTelemetry();
  lowerMotor.updateTelemetry();
}

/** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
public void simulationPeriodic() {
  // Runs each flywheel's physics simulation.
  upperMotor.simIterate();
  lowerMotor.simIterate();
}
```

{% endcode %}

{% code title="Robot.java" %}

```java
import first.robot.mechanisms.DoubleFlywheelMechanism;

// A field of Robot.
final DoubleFlywheelMechanism doubleFlywheel = new DoubleFlywheelMechanism();

// In robotPeriodic(), before scheduler.run():
doubleFlywheel.periodic();

// In simulationInit():
startSimulation("Double Flywheel", doubleFlywheel::simulationPeriodic);
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/DoubleFlywheelSubsystem.hpp" %}

```cpp
void Periodic() override;
void SimulationPeriodic() override;
```

{% endcode %}

{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" %}

```cpp
void DoubleFlywheelSubsystem::Periodic() {
  // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
  m_upperMotor->UpdateTelemetry();
  m_lowerMotor->UpdateTelemetry();
}

void DoubleFlywheelSubsystem::SimulationPeriodic() {
  // Runs each flywheel's physics simulation.
  m_upperMotor->SimIterate();
  m_lowerMotor->SimIterate();
}
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" lineNumbers="true" %}

```java
package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.KilogramSquareMeters;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.remote.TalonFXWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class DoubleFlywheelSubsystem extends SubsystemBase {

  // Each flywheel gets its own config, so that each can be given its own speed.
  private final SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback and feedforward constants, on the real robot and in simulation.
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
      // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
      // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("UpperFlyWheel", TelemetryVerbosity.HIGH);

  // The lower flywheel is the same, except that its motor faces the other way.
  private final SmartMotorControllerConfig lowerConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(true)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("LowerFlyWheel", TelemetryVerbosity.HIGH);

  // The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
  private final TalonFX upperTalon = new TalonFX(1, new CANBus(CANPort.CAN_S0));
  private final TalonFX lowerTalon = new TalonFX(2, new CANBus(CANPort.CAN_S0));

  // One SmartMotorController for each flywheel, each driving one Kraken X60.
  private final SmartMotorController upperMotor = new TalonFXWrapper(upperTalon, DCMotor.getKrakenX60(1), upperConfig);
  private final SmartMotorController lowerMotor = new TalonFXWrapper(lowerTalon, DCMotor.getKrakenX60(1), lowerConfig);

  public DoubleFlywheelSubsystem() {
    // A mechanism class would do this for us. Without one, set up the telemetry
    // (and live tuning) of each motor controller ourselves.
    upperMotor.setupTelemetry();
    lowerMotor.setupTelemetry();
  }

  @Override
  public void periodic() {
    // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
    upperMotor.updateTelemetry();
    lowerMotor.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    // Runs each flywheel's physics simulation.
    upperMotor.simIterate();
    lowerMotor.simIterate();
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" lineNumbers="true" %}

```java
package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.KilogramSquareMeters;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands3.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.remote.TalonFXWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class DoubleFlywheelMechanism implements Mechanism {

  // Each flywheel gets its own config, so that each can be given its own speed.
  private final SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback and feedforward constants, on the real robot and in simulation.
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
      // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
      // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("UpperFlyWheel", TelemetryVerbosity.HIGH);

  // The lower flywheel is the same, except that its motor faces the other way.
  private final SmartMotorControllerConfig lowerConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(true)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("LowerFlyWheel", TelemetryVerbosity.HIGH);

  // The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
  private final TalonFX upperTalon = new TalonFX(1, new CANBus(CANPort.CAN_S0));
  private final TalonFX lowerTalon = new TalonFX(2, new CANBus(CANPort.CAN_S0));

  // One SmartMotorController for each flywheel, each driving one Kraken X60.
  private final SmartMotorController upperMotor = new TalonFXWrapper(upperTalon, DCMotor.getKrakenX60(1), upperConfig);
  private final SmartMotorController lowerMotor = new TalonFXWrapper(lowerTalon, DCMotor.getKrakenX60(1), lowerConfig);

  public DoubleFlywheelMechanism() {
    // A mechanism class would do this for us. Without one, set up the telemetry
    // (and live tuning) of each motor controller ourselves.
    upperMotor.setupTelemetry();
    lowerMotor.setupTelemetry();
  }

  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
  public void periodic() {
    // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
    upperMotor.updateTelemetry();
    lowerMotor.updateTelemetry();
  }

  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
  public void simulationPeriodic() {
    // Runs each flywheel's physics simulation.
    upperMotor.simIterate();
    lowerMotor.simIterate();
  }
}
```

{% endcode %}

<pre class="language-java" data-title="Robot.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import java.util.ArrayList;
</strong><strong>import java.util.List;
</strong>import org.wpilib.command3.Scheduler;
import org.wpilib.command3.button.CommandGamepad;
import org.wpilib.framework.OpModeRobot;
<strong>import org.wpilib.system.Notifier;
</strong><strong>import org.wpilib.telemetry.Telemetry;
</strong>import first.robot.constants.DriverConstants;
<strong>import first.robot.mechanisms.DoubleFlywheelMechanism;
</strong>import first.robot.mechanisms.ExampleMechanism;

public class Robot extends OpModeRobot {
  final ExampleMechanism exampleMechanism = new ExampleMechanism();
<strong>  final DoubleFlywheelMechanism doubleFlywheel = new DoubleFlywheelMechanism();
</strong>  final CommandGamepad exampleController =
      new CommandGamepad(DriverConstants.DRIVER_CONTROLLER_PORT);

<strong>  // The scheduler that runs every command.
</strong><strong>  private final Scheduler scheduler = Scheduler.getDefault();
</strong><strong>  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
</strong><strong>  private final List&#x3C;Notifier> simulationNotifiers = new ArrayList&#x3C;>();
</strong>
  public Robot() {}

  @Override
  public void robotPeriodic() {
<strong>    // Runs every loop, on the robot and in simulation.
</strong><strong>    // Update the mechanism before the scheduler runs its commands.
</strong><strong>    doubleFlywheel.periodic();
</strong><strong>    scheduler.run();
</strong><strong>    // Publish the scheduler, so that a dashboard shows which commands are running.
</strong><strong>    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
</strong><strong>  }
</strong>
<strong>  @Override
</strong><strong>  public void simulationInit() {
</strong><strong>    // Runs once, when the simulation starts.
</strong><strong>    // Run each mechanism's simulation in its own Notifier, every robot loop.
</strong><strong>    startSimulation("Double Flywheel", doubleFlywheel::simulationPeriodic);
</strong><strong>  }
</strong>
<strong>  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
</strong><strong>  private void startSimulation(String name, Runnable simulationPeriodic) {
</strong><strong>    Notifier notifier = new Notifier(simulationPeriodic);
</strong><strong>    notifier.setName(name + " Simulation");
</strong><strong>    notifier.startPeriodic(getPeriod());
</strong><strong>    simulationNotifiers.add(notifier);
</strong><strong>  }
</strong>}
</code></pre>

{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/DoubleFlywheelSubsystem.hpp" lineNumbers="true" %}

```cpp
#pragma once

#include <optional>

#include <ctre/phoenix6/TalonFX.hpp>
#include <wpi/commands2/SubsystemBase.hpp>

#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/remote/TalonFXWrapper.hpp"

class DoubleFlywheelSubsystem : public wpi::cmd::SubsystemBase {
 public:
  DoubleFlywheelSubsystem();

  void Periodic() override;
  void SimulationPeriodic() override;

 private:
  // The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
  ctre::phoenix6::hardware::TalonFX m_upperTalon{1, ctre::phoenix6::CANBus{}};
  ctre::phoenix6::hardware::TalonFX m_lowerTalon{2, ctre::phoenix6::CANBus{}};

  // Each flywheel gets its own config, so that each can be given its own speed.
  yams::motorcontrollers::SmartMotorControllerConfig m_upperConfig;
  yams::motorcontrollers::SmartMotorControllerConfig m_lowerConfig;

  // One SmartMotorController for each flywheel, created in the constructor.
  std::optional<yams::motorcontrollers::remote::TalonFXWrapper> m_upperMotor;
  std::optional<yams::motorcontrollers::remote::TalonFXWrapper> m_lowerMotor;
};
```

{% endcode %}

{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" lineNumbers="true" %}

```cpp
#include "subsystems/DoubleFlywheelSubsystem.hpp"

#include <wpi/math/controller/SimpleMotorFeedforward.hpp>
#include <wpi/math/system/DCMotor.hpp>
#include <wpi/units/angle.hpp>
#include <wpi/units/current.hpp>
#include <wpi/units/moment_of_inertia.hpp>
#include <wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;
using Feedforward = wpi::math::SimpleMotorFeedforward<wpi::units::turns>;

DoubleFlywheelSubsystem::DoubleFlywheelSubsystem() {
  // The feedforward constants of both flywheels: kS and kV.
  const Feedforward feedforward{0.1_V, wpi::units::unit_t<Feedforward::kv_unit>{0.12}};

  m_upperConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // Feedback and feedforward constants, on the real robot and in simulation.
      .WithFeedback(0.1, 0, 0)
      .WithSimClosedLoopController(0.1, 0, 0)
      .WithFeedforward(feedforward)
      .WithSimFeedforward(feedforward)
      // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.0})})
      // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
      // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
      // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
      .WithMOI(wpi::units::kilogram_square_meter_t{0.0006})
      .WithMotorInverted(false)
      .WithZeroPower(Cfg::MotorMode::COAST)
      .WithStatorCurrentLimit(40_A)
      .WithTelemetry("UpperFlyWheel", Cfg::TelemetryVerbosity::HIGH);

  // The lower flywheel is the same, except that its motor faces the other way.
  m_lowerConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      .WithFeedback(0.1, 0, 0)
      .WithSimClosedLoopController(0.1, 0, 0)
      .WithFeedforward(feedforward)
      .WithSimFeedforward(feedforward)
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.0})})
      .WithMOI(wpi::units::kilogram_square_meter_t{0.0006})
      .WithMotorInverted(true)
      .WithZeroPower(Cfg::MotorMode::COAST)
      .WithStatorCurrentLimit(40_A)
      .WithTelemetry("LowerFlyWheel", Cfg::TelemetryVerbosity::HIGH);

  // One SmartMotorController for each flywheel, each driving one Kraken X60.
  m_upperMotor.emplace(&m_upperTalon, wpi::math::DCMotor::KrakenX60(1), &m_upperConfig);
  m_lowerMotor.emplace(&m_lowerTalon, wpi::math::DCMotor::KrakenX60(1), &m_lowerConfig);

  // A mechanism class would do this for us. Without one, set up the telemetry
  // (and live tuning) of each motor controller ourselves.
  m_upperMotor->SetupTelemetry();
  m_lowerMotor->SetupTelemetry();
}

void DoubleFlywheelSubsystem::Periodic() {
  // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
  m_upperMotor->UpdateTelemetry();
  m_lowerMotor->UpdateTelemetry();
}

void DoubleFlywheelSubsystem::SimulationPeriodic() {
  // Runs each flywheel's physics simulation.
  m_upperMotor->SimIterate();
  m_lowerMotor->SimIterate();
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Read more

Every option used here has its own section in the `SmartMotorControllerConfig` pages:

* [Motor basics](/documentation/reference/editor/config/motor-basics): control mode, inversion, what the motor does at zero power
* [Gearing and units](/documentation/reference/editor/config/gearing-and-units): gearing, and how rotations become distance
* [Closed loop control](/documentation/reference/editor/config/closed-loop-control), [Feedforward](/documentation/reference/editor/config/feedforward) and [Motion profiles](/documentation/reference/editor/config/motion-profiles)
* [Limits and protection](/documentation/reference/editor/config/limits-and-protection): soft limits and current limits
* [Simulation](/documentation/reference/editor/config/simulation): the simulation only gains

The PID and feedforward numbers on this page are a place to start, not tuned values. Tune them with [the shooter tutorial's tune step](/documentation/tutorials/shooter-flywheels/tune), once for each wheel.

## Check it

Open the command palette with <kbd>Ctrl+Shift+P</kbd> and run **WPILib: Build Robot Code**. It should build. Nothing moves yet, because nothing gives the wheels a speed.

* **`TalonFX` or `TalonFXWrapper` cannot be found:** Phoenix 6 is not installed. See [Install your motor controller's library](/documentation/tutorials/project-setup#install-your-motor-controllers-library).
* **`SmartMotorControllerConfig` cannot be found:** YAMS is not installed, or the import is from the other command framework (`yams.commands2` or `yams.commands3`).


# Step 2: Commands and buttons

One command sets both flywheel speeds. Presets give no spin, backspin or topspin.

One command sets both velocity setpoints, so the two wheels always change together. Everything else is a preset built on that one command.

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

{% stepper %}
{% step %}

### One command for both wheels

A single command sets both velocity setpoints every loop, so the two wheels always change together.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
/** Spin both flywheels. One command sets both speeds, so the two always change together. */
public Command setFlywheelSpeeds(AngularVelocity upperSpeed, AngularVelocity lowerSpeed) {
  return run(() -> {
    upperMotor.setVelocity(upperSpeed);
    lowerMotor.setVelocity(lowerSpeed);
  }).withName("Set FlyWheel Speeds");
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
/** Spin both flywheels. One command sets both speeds, so the two always change together. */
public Command setFlywheelSpeeds(AngularVelocity upperSpeed, AngularVelocity lowerSpeed) {
  return run(coroutine -> {
    while (true) {
      upperMotor.setVelocity(upperSpeed);
      lowerMotor.setVelocity(lowerSpeed);
      coroutine.yield();
    }
  }).named("Set FlyWheel Speeds");
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/DoubleFlywheelSubsystem.hpp" %}

```cpp
/** Spin both flywheels. One command sets both speeds, so the two always change together. */
wpi::cmd::CommandPtr SetFlywheelSpeeds(wpi::units::revolutions_per_minute_t upperSpeed,
                                       wpi::units::revolutions_per_minute_t lowerSpeed);
```

{% endcode %}

{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" %}

```cpp
wpi::cmd::CommandPtr DoubleFlywheelSubsystem::SetFlywheelSpeeds(
    wpi::units::revolutions_per_minute_t upperSpeed, wpi::units::revolutions_per_minute_t lowerSpeed) {
  return Run([this, upperSpeed, lowerSpeed] {
           m_upperMotor->SetVelocity(wpi::units::turns_per_second_t{upperSpeed});
           m_lowerMotor->SetVelocity(wpi::units::turns_per_second_t{lowerSpeed});
         })
      .WithName("Set FlyWheel Speeds");
}
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}

### Preset shots

Each preset is that one command with two speeds filled in. Stop is different: it sets a duty cycle of 0, so the wheels coast down. A 0 RPM setpoint would also stop them, but the closed loop would brake them hard to get there.

| Preset        | Upper    | Lower    | Spin     |
| ------------- | -------- | -------- | -------- |
| Neutral shot  | 3000 RPM | 3000 RPM | none     |
| Backspin shot | 2500 RPM | 3500 RPM | backspin |
| Topspin shot  | 3500 RPM | 2500 RPM | topspin  |
| Stop          | coast    | coast    |          |

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-82aa007e5ddc538d862713f91c45e15a014bd45d%2Ftutorial-double-flywheel-spin.gif?alt=media" alt="Animation of a ball passing between an upper and a lower flywheel, three times. With both at 3000 RPM the ball leaves with no spin and flies straight. With the lower flywheel faster, 3500 against 2500 RPM, it leaves with backspin and its path lifts. With the upper flywheel faster it leaves with topspin and its path dips."><figcaption><p>The faster wheel drags its side of the ball forward. Lower wheel faster is backspin; upper wheel faster is topspin.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
/** Both flywheels at the same speed: no spin. */
public Command neutralSpinShot() {
  return setFlywheelSpeeds(RPM.of(3000), RPM.of(3000));
}

/** The lower flywheel faster: backspin. */
public Command backspinShot() {
  return setFlywheelSpeeds(RPM.of(2500), RPM.of(3500));
}

/** The upper flywheel faster: topspin. */
public Command topspinShot() {
  return setFlywheelSpeeds(RPM.of(3500), RPM.of(2500));
}

/** Let both flywheels coast to a stop. */
public Command stopFlywheels() {
  return runOnce(() -> {
    // A duty cycle of 0 lets the wheels coast down. A 0 RPM setpoint would brake them hard.
    upperMotor.setDutyCycle(0);
    lowerMotor.setDutyCycle(0);
  }).withName("Stop FlyWheels");
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
/** Both flywheels at the same speed: no spin. */
public Command neutralSpinShot() {
  return setFlywheelSpeeds(RPM.of(3000), RPM.of(3000));
}

/** The lower flywheel faster: backspin. */
public Command backspinShot() {
  return setFlywheelSpeeds(RPM.of(2500), RPM.of(3500));
}

/** The upper flywheel faster: topspin. */
public Command topspinShot() {
  return setFlywheelSpeeds(RPM.of(3500), RPM.of(2500));
}

/** Let both flywheels coast to a stop. */
public Command stopFlywheels() {
  return run(coroutine -> {
    // A duty cycle of 0 lets the wheels coast down. A 0 RPM setpoint would brake them hard.
    upperMotor.setDutyCycle(0);
    lowerMotor.setDutyCycle(0);
  }).named("Stop FlyWheels");
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/DoubleFlywheelSubsystem.hpp" %}

```cpp
/** Both flywheels at the same speed: no spin. */
wpi::cmd::CommandPtr NeutralSpinShot();

/** The lower flywheel faster: backspin. */
wpi::cmd::CommandPtr BackspinShot();

/** The upper flywheel faster: topspin. */
wpi::cmd::CommandPtr TopspinShot();

/** Let both flywheels coast to a stop. */
wpi::cmd::CommandPtr StopFlywheels();
```

{% endcode %}

{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" %}

```cpp
wpi::cmd::CommandPtr DoubleFlywheelSubsystem::NeutralSpinShot() {
  return SetFlywheelSpeeds(3000_rpm, 3000_rpm);
}

wpi::cmd::CommandPtr DoubleFlywheelSubsystem::BackspinShot() {
  return SetFlywheelSpeeds(2500_rpm, 3500_rpm);
}

wpi::cmd::CommandPtr DoubleFlywheelSubsystem::TopspinShot() {
  return SetFlywheelSpeeds(3500_rpm, 2500_rpm);
}

wpi::cmd::CommandPtr DoubleFlywheelSubsystem::StopFlywheels() {
  return RunOnce([this] {
    // A duty cycle of 0 lets the wheels coast down. A 0 RPM setpoint would brake them hard.
    m_upperMotor->SetDutyCycle(0);
    m_lowerMotor->SetDutyCycle(0);
  }).WithName("Stop FlyWheels");
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the speeds to the shots your robot needs, and add a preset for each one.
{% endstep %}

{% step %}

### Know when it is ready

This `Trigger` is true while both wheels are at their speeds, so that you can hold the feeder back until the shooter is ready. It works like `atSpeed` in [the shooter tutorial](/documentation/tutorials/shooter-flywheels/commands#knowing-when-it-is-up-to-speed): bind a feeder command to it, or use it in a command sequence. Nothing in this tutorial uses it yet.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
/** A Trigger that is true while both flywheels are within the tolerance of their target speeds. */
public Trigger atTargetVelocity(AngularVelocity upperTarget, AngularVelocity lowerTarget, AngularVelocity tolerance) {
  return new Trigger(() -> upperMotor.getMechanismVelocity().isNear(upperTarget, tolerance)
      && lowerMotor.getMechanismVelocity().isNear(lowerTarget, tolerance));
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
/** A Trigger that is true while both flywheels are within the tolerance of their target speeds. */
public Trigger atTargetVelocity(AngularVelocity upperTarget, AngularVelocity lowerTarget, AngularVelocity tolerance) {
  return new Trigger(() -> upperMotor.getMechanismVelocity().isNear(upperTarget, tolerance)
      && lowerMotor.getMechanismVelocity().isNear(lowerTarget, tolerance));
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/DoubleFlywheelSubsystem.hpp" %}

```cpp
/** A Trigger that is true while both flywheels are within the tolerance of their target speeds. */
wpi::cmd::Trigger AtTargetVelocity(wpi::units::revolutions_per_minute_t upperTarget,
                                   wpi::units::revolutions_per_minute_t lowerTarget,
                                   wpi::units::revolutions_per_minute_t tolerance);
```

{% endcode %}

{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" %}

```cpp
wpi::cmd::Trigger DoubleFlywheelSubsystem::AtTargetVelocity(wpi::units::revolutions_per_minute_t upperTarget,
                                                            wpi::units::revolutions_per_minute_t lowerTarget,
                                                            wpi::units::revolutions_per_minute_t tolerance) {
  return wpi::cmd::Trigger([this, upperTarget, lowerTarget, tolerance] {
    return wpi::units::math::abs(m_upperMotor->GetMechanismVelocity() - upperTarget) <= tolerance &&
           wpi::units::math::abs(m_lowerMotor->GetMechanismVelocity() - lowerTarget) <= tolerance;
  });
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

Want the details? [How do I shoot with a shooter?](/documentation/how-to-mechanisms/how-to-shoot-with-a-shooter) does the same for one flywheel.
{% endstep %}

{% step %}

### Create it and bind the buttons

`onTrue` starts a shot with one press. The shot keeps running after the button is released, until another shot or the stop button replaces it.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="RobotContainer.java" %}

```java
import first.robot.subsystems.DoubleFlywheelSubsystem;

private final DoubleFlywheelSubsystem doubleFlywheel = new DoubleFlywheelSubsystem();

// Bottom (A): no spin. Right (B): backspin. Left (X): topspin. Top (Y): stop.
driverController.faceDown().onTrue(doubleFlywheel.neutralSpinShot());
driverController.faceRight().onTrue(doubleFlywheel.backspinShot());
driverController.faceLeft().onTrue(doubleFlywheel.topspinShot());
driverController.faceUp().onTrue(doubleFlywheel.stopFlywheels());
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="ExampleTeleop.java" %}

```java
// Bottom (A): no spin. Right (B): backspin. Left (X): topspin. Top (Y): stop.
robot.exampleController.faceDown().onTrue(robot.doubleFlywheel.neutralSpinShot());
robot.exampleController.faceRight().onTrue(robot.doubleFlywheel.backspinShot());
robot.exampleController.faceLeft().onTrue(robot.doubleFlywheel.topspinShot());
robot.exampleController.faceUp().onTrue(robot.doubleFlywheel.stopFlywheels());
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/RobotContainer.hpp" %}

```cpp
#include "subsystems/DoubleFlywheelSubsystem.hpp"

DoubleFlywheelSubsystem doubleFlywheel;
```

{% endcode %}

{% code title="cpp/RobotContainer.cpp" %}

```cpp
// Bottom (A): no spin. Right (B): backspin. Left (X): topspin. Top (Y): stop.
driverController.FaceDown().OnTrue(doubleFlywheel.NeutralSpinShot());
driverController.FaceRight().OnTrue(doubleFlywheel.BackspinShot());
driverController.FaceLeft().OnTrue(doubleFlywheel.TopspinShot());
driverController.FaceUp().OnTrue(doubleFlywheel.StopFlywheels());
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Pick your own buttons.
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
The highlighted lines are new in this step.

Add the commands to `DoubleFlywheelSubsystem.java`, then create the subsystem and bind the buttons in `RobotContainer.java`. The template bound the right face button to its example command; that binding is replaced.

<pre class="language-java" data-title="subsystems/DoubleFlywheelSubsystem.java" data-line-numbers><code class="lang-java">package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.KilogramSquareMeters;
<strong>import static org.wpilib.units.Units.RPM;
</strong>
import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
<strong>import org.wpilib.command2.Command;
</strong>import org.wpilib.command2.SubsystemBase;
<strong>import org.wpilib.command2.button.Trigger;
</strong>import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
<strong>import org.wpilib.units.measure.AngularVelocity;
</strong>import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.remote.TalonFXWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class DoubleFlywheelSubsystem extends SubsystemBase {

  // Each flywheel gets its own config, so that each can be given its own speed.
  private final SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback and feedforward constants, on the real robot and in simulation.
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
      // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
      // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("UpperFlyWheel", TelemetryVerbosity.HIGH);

  // The lower flywheel is the same, except that its motor faces the other way.
  private final SmartMotorControllerConfig lowerConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(true)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("LowerFlyWheel", TelemetryVerbosity.HIGH);

  // The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
  private final TalonFX upperTalon = new TalonFX(1, new CANBus(CANPort.CAN_S0));
  private final TalonFX lowerTalon = new TalonFX(2, new CANBus(CANPort.CAN_S0));

  // One SmartMotorController for each flywheel, each driving one Kraken X60.
  private final SmartMotorController upperMotor = new TalonFXWrapper(upperTalon, DCMotor.getKrakenX60(1), upperConfig);
  private final SmartMotorController lowerMotor = new TalonFXWrapper(lowerTalon, DCMotor.getKrakenX60(1), lowerConfig);

  public DoubleFlywheelSubsystem() {
    // A mechanism class would do this for us. Without one, set up the telemetry
    // (and live tuning) of each motor controller ourselves.
    upperMotor.setupTelemetry();
    lowerMotor.setupTelemetry();
  }

<strong>  /** Spin both flywheels. One command sets both speeds, so the two always change together. */
</strong><strong>  public Command setFlywheelSpeeds(AngularVelocity upperSpeed, AngularVelocity lowerSpeed) {
</strong><strong>    return run(() -> {
</strong><strong>      upperMotor.setVelocity(upperSpeed);
</strong><strong>      lowerMotor.setVelocity(lowerSpeed);
</strong><strong>    }).withName("Set FlyWheel Speeds");
</strong><strong>  }
</strong>
<strong>  /** Both flywheels at the same speed: no spin. */
</strong><strong>  public Command neutralSpinShot() {
</strong><strong>    return setFlywheelSpeeds(RPM.of(3000), RPM.of(3000));
</strong><strong>  }
</strong>
<strong>  /** The lower flywheel faster: backspin. */
</strong><strong>  public Command backspinShot() {
</strong><strong>    return setFlywheelSpeeds(RPM.of(2500), RPM.of(3500));
</strong><strong>  }
</strong>
<strong>  /** The upper flywheel faster: topspin. */
</strong><strong>  public Command topspinShot() {
</strong><strong>    return setFlywheelSpeeds(RPM.of(3500), RPM.of(2500));
</strong><strong>  }
</strong>
<strong>  /** Let both flywheels coast to a stop. */
</strong><strong>  public Command stopFlywheels() {
</strong><strong>    return runOnce(() -> {
</strong><strong>      // A duty cycle of 0 lets the wheels coast down. A 0 RPM setpoint would brake them hard.
</strong><strong>      upperMotor.setDutyCycle(0);
</strong><strong>      lowerMotor.setDutyCycle(0);
</strong><strong>    }).withName("Stop FlyWheels");
</strong><strong>  }
</strong>
<strong>  /** A Trigger that is true while both flywheels are within the tolerance of their target speeds. */
</strong><strong>  public Trigger atTargetVelocity(AngularVelocity upperTarget, AngularVelocity lowerTarget, AngularVelocity tolerance) {
</strong><strong>    return new Trigger(() -> upperMotor.getMechanismVelocity().isNear(upperTarget, tolerance)
</strong><strong>        &#x26;&#x26; lowerMotor.getMechanismVelocity().isNear(lowerTarget, tolerance));
</strong><strong>  }
</strong>
  @Override
  public void periodic() {
    // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
    upperMotor.updateTelemetry();
    lowerMotor.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    // Runs each flywheel's physics simulation.
    upperMotor.simIterate();
    lowerMotor.simIterate();
  }
}
</code></pre>

<pre class="language-java" data-title="RobotContainer.java" data-line-numbers><code class="lang-java">package first.robot;

import org.wpilib.command2.Command;
import org.wpilib.command2.button.CommandGamepad;
import org.wpilib.command2.button.Trigger;
import first.robot.Constants.OperatorConstants;
import first.robot.commands.Autos;
import first.robot.commands.ExampleCommand;
<strong>import first.robot.subsystems.DoubleFlywheelSubsystem;
</strong>import first.robot.subsystems.ExampleSubsystem;

/**
 * This class is where the bulk of the robot should be declared. Since Command-based is a
 * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
 * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
 * subsystems, commands, and trigger mappings) should be declared here.
 */
public class RobotContainer {
  // The robot's subsystems and commands are defined here...
  private final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
<strong>  private final DoubleFlywheelSubsystem doubleFlywheel = new DoubleFlywheelSubsystem();
</strong>
  private final CommandGamepad driverController =
      new CommandGamepad(OperatorConstants.DRIVER_CONTROLLER_PORT);

  /** The container for the robot. Contains subsystems, OI devices, and commands. */
  public RobotContainer() {
    // Configure the trigger bindings
    configureBindings();
  }

  /**
   * Use this method to define your trigger->command mappings. Triggers can be created via the
   * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary
   * predicate, or via the named factories in {@link org.wpilib.command2.button.CommandGenericHID}'s
   * subclasses for {@link CommandGamepad Gamepad} gamepads or {@link
   * org.wpilib.command2.button.CommandJoystick Flight joysticks}.
   */
  private void configureBindings() {
    // Schedule `ExampleCommand` when `exampleCondition` changes to `true`
    new Trigger(exampleSubsystem::exampleCondition).onTrue(new ExampleCommand(exampleSubsystem));

<strong>    // Bottom (A): no spin. Right (B): backspin. Left (X): topspin. Top (Y): stop.
</strong><strong>    driverController.faceDown().onTrue(doubleFlywheel.neutralSpinShot());
</strong><strong>    driverController.faceRight().onTrue(doubleFlywheel.backspinShot());
</strong><strong>    driverController.faceLeft().onTrue(doubleFlywheel.topspinShot());
</strong><strong>    driverController.faceUp().onTrue(doubleFlywheel.stopFlywheels());
</strong>  }

  /**
   * Use this to pass the autonomous command to the main {@link Robot} class.
   *
   * @return the command to run in autonomous
   */
  public Command getAutonomousCommand() {
    // An example command will be run in autonomous
    return Autos.exampleAuto(exampleSubsystem);
  }
}
</code></pre>

{% endtab %}

{% tab title="Java, Commands v3" %}
The highlighted lines are new in this step.

Add the commands to `DoubleFlywheelMechanism.java` and bind the buttons in `ExampleTeleop.java`. A Commands v3 command is a coroutine: it sets both speeds, yields until the next loop, and repeats until something interrupts it.

<pre class="language-java" data-title="mechanisms/DoubleFlywheelMechanism.java" data-line-numbers><code class="lang-java">package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.KilogramSquareMeters;
<strong>import static org.wpilib.units.Units.RPM;
</strong>
import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
<strong>import org.wpilib.command3.Command;
</strong>import org.wpilib.command3.Mechanism;
<strong>import org.wpilib.command3.Trigger;
</strong>import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
<strong>import org.wpilib.units.measure.AngularVelocity;
</strong>import yams.commands3.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.remote.TalonFXWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class DoubleFlywheelMechanism implements Mechanism {

  // Each flywheel gets its own config, so that each can be given its own speed.
  private final SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback and feedforward constants, on the real robot and in simulation.
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
      // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
      // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("UpperFlyWheel", TelemetryVerbosity.HIGH);

  // The lower flywheel is the same, except that its motor faces the other way.
  private final SmartMotorControllerConfig lowerConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(true)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("LowerFlyWheel", TelemetryVerbosity.HIGH);

  // The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
  private final TalonFX upperTalon = new TalonFX(1, new CANBus(CANPort.CAN_S0));
  private final TalonFX lowerTalon = new TalonFX(2, new CANBus(CANPort.CAN_S0));

  // One SmartMotorController for each flywheel, each driving one Kraken X60.
  private final SmartMotorController upperMotor = new TalonFXWrapper(upperTalon, DCMotor.getKrakenX60(1), upperConfig);
  private final SmartMotorController lowerMotor = new TalonFXWrapper(lowerTalon, DCMotor.getKrakenX60(1), lowerConfig);

  public DoubleFlywheelMechanism() {
    // A mechanism class would do this for us. Without one, set up the telemetry
    // (and live tuning) of each motor controller ourselves.
    upperMotor.setupTelemetry();
    lowerMotor.setupTelemetry();
  }

<strong>  /** Spin both flywheels. One command sets both speeds, so the two always change together. */
</strong><strong>  public Command setFlywheelSpeeds(AngularVelocity upperSpeed, AngularVelocity lowerSpeed) {
</strong><strong>    return run(coroutine -> {
</strong><strong>      while (true) {
</strong><strong>        upperMotor.setVelocity(upperSpeed);
</strong><strong>        lowerMotor.setVelocity(lowerSpeed);
</strong><strong>        coroutine.yield();
</strong><strong>      }
</strong><strong>    }).named("Set FlyWheel Speeds");
</strong><strong>  }
</strong>
<strong>  /** Both flywheels at the same speed: no spin. */
</strong><strong>  public Command neutralSpinShot() {
</strong><strong>    return setFlywheelSpeeds(RPM.of(3000), RPM.of(3000));
</strong><strong>  }
</strong>
<strong>  /** The lower flywheel faster: backspin. */
</strong><strong>  public Command backspinShot() {
</strong><strong>    return setFlywheelSpeeds(RPM.of(2500), RPM.of(3500));
</strong><strong>  }
</strong>
<strong>  /** The upper flywheel faster: topspin. */
</strong><strong>  public Command topspinShot() {
</strong><strong>    return setFlywheelSpeeds(RPM.of(3500), RPM.of(2500));
</strong><strong>  }
</strong>
<strong>  /** Let both flywheels coast to a stop. */
</strong><strong>  public Command stopFlywheels() {
</strong><strong>    return run(coroutine -> {
</strong><strong>      // A duty cycle of 0 lets the wheels coast down. A 0 RPM setpoint would brake them hard.
</strong><strong>      upperMotor.setDutyCycle(0);
</strong><strong>      lowerMotor.setDutyCycle(0);
</strong><strong>    }).named("Stop FlyWheels");
</strong><strong>  }
</strong>
<strong>  /** A Trigger that is true while both flywheels are within the tolerance of their target speeds. */
</strong><strong>  public Trigger atTargetVelocity(AngularVelocity upperTarget, AngularVelocity lowerTarget, AngularVelocity tolerance) {
</strong><strong>    return new Trigger(() -> upperMotor.getMechanismVelocity().isNear(upperTarget, tolerance)
</strong><strong>        &#x26;&#x26; lowerMotor.getMechanismVelocity().isNear(lowerTarget, tolerance));
</strong><strong>  }
</strong>
  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
  public void periodic() {
    // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
    upperMotor.updateTelemetry();
    lowerMotor.updateTelemetry();
  }

  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
  public void simulationPeriodic() {
    // Runs each flywheel's physics simulation.
    upperMotor.simIterate();
    lowerMotor.simIterate();
  }
}
</code></pre>

<pre class="language-java" data-title="ExampleTeleop.java" data-line-numbers><code class="lang-java">package first.robot;

import org.wpilib.opmode.OpMode;
import org.wpilib.opmode.Teleop;

@Teleop
public class ExampleTeleop implements OpMode {
  public ExampleTeleop(Robot robot) {
    robot.exampleController.rightStick().whileTrue(robot.exampleMechanism.exampleCommand());

<strong>    // Bottom (A): no spin. Right (B): backspin. Left (X): topspin. Top (Y): stop.
</strong><strong>    robot.exampleController.faceDown().onTrue(robot.doubleFlywheel.neutralSpinShot());
</strong><strong>    robot.exampleController.faceRight().onTrue(robot.doubleFlywheel.backspinShot());
</strong><strong>    robot.exampleController.faceLeft().onTrue(robot.doubleFlywheel.topspinShot());
</strong><strong>    robot.exampleController.faceUp().onTrue(robot.doubleFlywheel.stopFlywheels());
</strong>  }
}
</code></pre>

{% endtab %}

{% tab title="C++" %}
The highlighted lines are new in this step.

Declare the commands in `DoubleFlywheelSubsystem.hpp`, define them in `DoubleFlywheelSubsystem.cpp`, then create the subsystem and bind the buttons in `RobotContainer`. The template bound the right face button to its example command; that binding is replaced.

<pre class="language-cpp" data-title="include/subsystems/DoubleFlywheelSubsystem.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include &#x3C;optional>

#include &#x3C;ctre/phoenix6/TalonFX.hpp>
<strong>#include &#x3C;wpi/commands2/CommandPtr.hpp>
</strong>#include &#x3C;wpi/commands2/SubsystemBase.hpp>
<strong>#include &#x3C;wpi/commands2/button/Trigger.hpp>
</strong><strong>#include &#x3C;wpi/units/angular_velocity.hpp>
</strong>
#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/remote/TalonFXWrapper.hpp"

class DoubleFlywheelSubsystem : public wpi::cmd::SubsystemBase {
 public:
  DoubleFlywheelSubsystem();

<strong>  /** Spin both flywheels. One command sets both speeds, so the two always change together. */
</strong><strong>  wpi::cmd::CommandPtr SetFlywheelSpeeds(wpi::units::revolutions_per_minute_t upperSpeed,
</strong><strong>                                         wpi::units::revolutions_per_minute_t lowerSpeed);
</strong>
<strong>  /** Both flywheels at the same speed: no spin. */
</strong><strong>  wpi::cmd::CommandPtr NeutralSpinShot();
</strong>
<strong>  /** The lower flywheel faster: backspin. */
</strong><strong>  wpi::cmd::CommandPtr BackspinShot();
</strong>
<strong>  /** The upper flywheel faster: topspin. */
</strong><strong>  wpi::cmd::CommandPtr TopspinShot();
</strong>
<strong>  /** Let both flywheels coast to a stop. */
</strong><strong>  wpi::cmd::CommandPtr StopFlywheels();
</strong>
<strong>  /** A Trigger that is true while both flywheels are within the tolerance of their target speeds. */
</strong><strong>  wpi::cmd::Trigger AtTargetVelocity(wpi::units::revolutions_per_minute_t upperTarget,
</strong><strong>                                     wpi::units::revolutions_per_minute_t lowerTarget,
</strong><strong>                                     wpi::units::revolutions_per_minute_t tolerance);
</strong>
  void Periodic() override;
  void SimulationPeriodic() override;

 private:
  // The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
  ctre::phoenix6::hardware::TalonFX m_upperTalon{1, ctre::phoenix6::CANBus{}};
  ctre::phoenix6::hardware::TalonFX m_lowerTalon{2, ctre::phoenix6::CANBus{}};

  // Each flywheel gets its own config, so that each can be given its own speed.
  yams::motorcontrollers::SmartMotorControllerConfig m_upperConfig;
  yams::motorcontrollers::SmartMotorControllerConfig m_lowerConfig;

  // One SmartMotorController for each flywheel, created in the constructor.
  std::optional&#x3C;yams::motorcontrollers::remote::TalonFXWrapper> m_upperMotor;
  std::optional&#x3C;yams::motorcontrollers::remote::TalonFXWrapper> m_lowerMotor;
};
</code></pre>

<pre class="language-cpp" data-title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" data-line-numbers><code class="lang-cpp">#include "subsystems/DoubleFlywheelSubsystem.hpp"

#include &#x3C;wpi/math/controller/SimpleMotorFeedforward.hpp>
#include &#x3C;wpi/math/system/DCMotor.hpp>
#include &#x3C;wpi/units/angle.hpp>
#include &#x3C;wpi/units/current.hpp>
#include &#x3C;wpi/units/moment_of_inertia.hpp>
<strong>#include &#x3C;wpi/units/math.hpp>
</strong>#include &#x3C;wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;
using Feedforward = wpi::math::SimpleMotorFeedforward&#x3C;wpi::units::turns>;

DoubleFlywheelSubsystem::DoubleFlywheelSubsystem() {
  // The feedforward constants of both flywheels: kS and kV.
  const Feedforward feedforward{0.1_V, wpi::units::unit_t&#x3C;Feedforward::kv_unit>{0.12}};

  m_upperConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // Feedback and feedforward constants, on the real robot and in simulation.
      .WithFeedback(0.1, 0, 0)
      .WithSimClosedLoopController(0.1, 0, 0)
      .WithFeedforward(feedforward)
      .WithSimFeedforward(feedforward)
      // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.0})})
      // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
      // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
      // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
      .WithMOI(wpi::units::kilogram_square_meter_t{0.0006})
      .WithMotorInverted(false)
      .WithZeroPower(Cfg::MotorMode::COAST)
      .WithStatorCurrentLimit(40_A)
      .WithTelemetry("UpperFlyWheel", Cfg::TelemetryVerbosity::HIGH);

  // The lower flywheel is the same, except that its motor faces the other way.
  m_lowerConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      .WithFeedback(0.1, 0, 0)
      .WithSimClosedLoopController(0.1, 0, 0)
      .WithFeedforward(feedforward)
      .WithSimFeedforward(feedforward)
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.0})})
      .WithMOI(wpi::units::kilogram_square_meter_t{0.0006})
      .WithMotorInverted(true)
      .WithZeroPower(Cfg::MotorMode::COAST)
      .WithStatorCurrentLimit(40_A)
      .WithTelemetry("LowerFlyWheel", Cfg::TelemetryVerbosity::HIGH);

  // One SmartMotorController for each flywheel, each driving one Kraken X60.
  m_upperMotor.emplace(&#x26;m_upperTalon, wpi::math::DCMotor::KrakenX60(1), &#x26;m_upperConfig);
  m_lowerMotor.emplace(&#x26;m_lowerTalon, wpi::math::DCMotor::KrakenX60(1), &#x26;m_lowerConfig);

  // A mechanism class would do this for us. Without one, set up the telemetry
  // (and live tuning) of each motor controller ourselves.
  m_upperMotor->SetupTelemetry();
  m_lowerMotor->SetupTelemetry();
}

<strong>wpi::cmd::CommandPtr DoubleFlywheelSubsystem::SetFlywheelSpeeds(
</strong><strong>    wpi::units::revolutions_per_minute_t upperSpeed, wpi::units::revolutions_per_minute_t lowerSpeed) {
</strong><strong>  return Run([this, upperSpeed, lowerSpeed] {
</strong><strong>           m_upperMotor->SetVelocity(wpi::units::turns_per_second_t{upperSpeed});
</strong><strong>           m_lowerMotor->SetVelocity(wpi::units::turns_per_second_t{lowerSpeed});
</strong><strong>         })
</strong><strong>      .WithName("Set FlyWheel Speeds");
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr DoubleFlywheelSubsystem::NeutralSpinShot() {
</strong><strong>  return SetFlywheelSpeeds(3000_rpm, 3000_rpm);
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr DoubleFlywheelSubsystem::BackspinShot() {
</strong><strong>  return SetFlywheelSpeeds(2500_rpm, 3500_rpm);
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr DoubleFlywheelSubsystem::TopspinShot() {
</strong><strong>  return SetFlywheelSpeeds(3500_rpm, 2500_rpm);
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr DoubleFlywheelSubsystem::StopFlywheels() {
</strong><strong>  return RunOnce([this] {
</strong><strong>    // A duty cycle of 0 lets the wheels coast down. A 0 RPM setpoint would brake them hard.
</strong><strong>    m_upperMotor->SetDutyCycle(0);
</strong><strong>    m_lowerMotor->SetDutyCycle(0);
</strong><strong>  }).WithName("Stop FlyWheels");
</strong><strong>}
</strong>
<strong>wpi::cmd::Trigger DoubleFlywheelSubsystem::AtTargetVelocity(wpi::units::revolutions_per_minute_t upperTarget,
</strong><strong>                                                            wpi::units::revolutions_per_minute_t lowerTarget,
</strong><strong>                                                            wpi::units::revolutions_per_minute_t tolerance) {
</strong><strong>  return wpi::cmd::Trigger([this, upperTarget, lowerTarget, tolerance] {
</strong><strong>    return wpi::units::math::abs(m_upperMotor->GetMechanismVelocity() - upperTarget) &#x3C;= tolerance &#x26;&#x26;
</strong><strong>           wpi::units::math::abs(m_lowerMotor->GetMechanismVelocity() - lowerTarget) &#x3C;= tolerance;
</strong><strong>  });
</strong><strong>}
</strong>
void DoubleFlywheelSubsystem::Periodic() {
  // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
  m_upperMotor->UpdateTelemetry();
  m_lowerMotor->UpdateTelemetry();
}

void DoubleFlywheelSubsystem::SimulationPeriodic() {
  // Runs each flywheel's physics simulation.
  m_upperMotor->SimIterate();
  m_lowerMotor->SimIterate();
}
</code></pre>

<pre class="language-cpp" data-title="include/RobotContainer.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include "Constants.hpp"
<strong>#include "subsystems/DoubleFlywheelSubsystem.hpp"
</strong>#include "subsystems/ExampleSubsystem.hpp"
#include "wpi/commands2/CommandPtr.hpp"
#include "wpi/commands2/button/CommandGamepad.hpp"

/**
 * This class is where the bulk of the robot should be declared.  Since
 * Command-based is a "declarative" paradigm, very little robot logic should
 * actually be handled in the {@link Robot} periodic methods (other than the
 * scheduler calls).  Instead, the structure of the robot (including subsystems,
 * commands, and trigger mappings) should be declared here.
 */
class RobotContainer {
 public:
  RobotContainer();

  wpi::cmd::CommandPtr GetAutonomousCommand();

 private:
  // Replace with CommandPS4Controller or CommandJoystick if needed
  wpi::cmd::CommandGamepad driverController{
      OperatorConstants::DRIVER_CONTROLLER_PORT};

  // The robot's subsystems are defined here...
  ExampleSubsystem subsystem;
<strong>  DoubleFlywheelSubsystem doubleFlywheel;
</strong>
  void ConfigureBindings();
};
</code></pre>

<pre class="language-cpp" data-title="cpp/RobotContainer.cpp" data-line-numbers><code class="lang-cpp">#include "RobotContainer.hpp"

#include "commands/Autos.hpp"
#include "commands/ExampleCommand.hpp"
#include "wpi/commands2/button/Trigger.hpp"

RobotContainer::RobotContainer() {
  // Initialize all of your commands and subsystems here

  // Configure the button bindings
  ConfigureBindings();
}

void RobotContainer::ConfigureBindings() {
  // Configure your trigger bindings here

  // Schedule `ExampleCommand` when `exampleCondition` changes to `true`
  wpi::cmd::Trigger([this] {
    return subsystem.ExampleCondition();
  }).OnTrue(ExampleCommand(&#x26;subsystem).ToPtr());

<strong>  // Bottom (A): no spin. Right (B): backspin. Left (X): topspin. Top (Y): stop.
</strong><strong>  driverController.FaceDown().OnTrue(doubleFlywheel.NeutralSpinShot());
</strong><strong>  driverController.FaceRight().OnTrue(doubleFlywheel.BackspinShot());
</strong><strong>  driverController.FaceLeft().OnTrue(doubleFlywheel.TopspinShot());
</strong><strong>  driverController.FaceUp().OnTrue(doubleFlywheel.StopFlywheels());
</strong>}

wpi::cmd::CommandPtr RobotContainer::GetAutonomousCommand() {
  // An example command will be run in autonomous
  return autos::ExampleAuto(&#x26;subsystem);
}
</code></pre>

{% endtab %}
{% endtabs %}

## Check it in simulation

There is no `FlyWheel` mechanism here, so there is no drawing of the wheels. Watch their speeds on a graph instead.

1. Start the simulation as in [the shooter's step 4](/documentation/tutorials/shooter-flywheels/simulate), with the controller on **Joystick\[0]**. Commands v3: pick the `ExampleTeleop` op mode, and check that `Robot.simulationInit()` starts the double flywheel's simulation.
2. Open [AdvantageScope](https://docs.advantagescope.org/), connect it to the simulation (**File > Connect to Simulator**), and make a **Line Graph** of:

   * `NT:/Mechanisms/UpperFlyWheel/mechanism/velocity`
   * `NT:/Mechanisms/LowerFlyWheel/mechanism/velocity`

   Each motor's values are under the name from its `withTelemetry`. The speeds are in rotations per second: divide RPM by 60.
3. Enable **Teleoperated** and press the buttons.

**What you should see:**

* **A** (no spin): both lines rise to 50 (3000 RPM) and stay together.
* **B** (backspin): the upper line settles at about 42 (2500 RPM) and the lower at about 58 (3500 RPM).
* **X** (topspin): the other way round.
* **Y**: both lines fall back toward 0 as the wheels coast down.

If a line stays at 0, check that `setupTelemetry()` and `simIterate()` are called for that motor, as in step 1. More problems and fixes: [Troubleshooting](/documentation/tutorials/troubleshooting).


# Step 3: Spin control and followers

A spin ratio between the two flywheels, and what to change when two motors drive one wheel.

## A spin ratio

Three presets are enough to start with. For finer control, let the caller choose a base speed and how much spin to put on it:

* A ratio of **0** runs both wheels at the base speed: no spin.
* A ratio of **1** runs the lower wheel 25% faster and the upper wheel 25% slower: the most backspin.
* A ratio of **-1** does the opposite: the most topspin.

The average of the two speeds stays at the base speed, so changing the spin does not change how fast the ball leaves.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
/**
 * Spin both flywheels around a base speed, with a spin ratio between them.
 *
 * @param baseSpeed The average speed of the two flywheels.
 * @param spinRatio From -1 (the most topspin) to 1 (the most backspin). 0 is no spin.
 */
public Command setSpinShot(AngularVelocity baseSpeed, double spinRatio) {
  double ratio = Math.max(-1.0, Math.min(1.0, spinRatio));
  // At a ratio of 1 the lower flywheel runs 25% faster and the upper one 25% slower.
  double upperMultiplier = 1.0 - ratio * 0.25;
  double lowerMultiplier = 1.0 + ratio * 0.25;
  return setFlywheelSpeeds(baseSpeed.times(upperMultiplier), baseSpeed.times(lowerMultiplier));
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
/**
 * Spin both flywheels around a base speed, with a spin ratio between them.
 *
 * @param baseSpeed The average speed of the two flywheels.
 * @param spinRatio From -1 (the most topspin) to 1 (the most backspin). 0 is no spin.
 */
public Command setSpinShot(AngularVelocity baseSpeed, double spinRatio) {
  double ratio = Math.max(-1.0, Math.min(1.0, spinRatio));
  // At a ratio of 1 the lower flywheel runs 25% faster and the upper one 25% slower.
  double upperMultiplier = 1.0 - ratio * 0.25;
  double lowerMultiplier = 1.0 + ratio * 0.25;
  return setFlywheelSpeeds(baseSpeed.times(upperMultiplier), baseSpeed.times(lowerMultiplier));
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/DoubleFlywheelSubsystem.hpp" %}

```cpp
/**
 * Spin both flywheels around a base speed, with a spin ratio between them.
 *
 * @param baseSpeed The average speed of the two flywheels.
 * @param spinRatio From -1 (the most topspin) to 1 (the most backspin). 0 is no spin.
 */
wpi::cmd::CommandPtr SetSpinShot(wpi::units::revolutions_per_minute_t baseSpeed, double spinRatio);
```

{% endcode %}

{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" %}

```cpp
wpi::cmd::CommandPtr DoubleFlywheelSubsystem::SetSpinShot(wpi::units::revolutions_per_minute_t baseSpeed,
                                                          double spinRatio) {
  double ratio = std::clamp(spinRatio, -1.0, 1.0);
  // At a ratio of 1 the lower flywheel runs 25% faster and the upper one 25% slower.
  double upperMultiplier = 1.0 - ratio * 0.25;
  double lowerMultiplier = 1.0 + ratio * 0.25;
  return SetFlywheelSpeeds(baseSpeed * upperMultiplier, baseSpeed * lowerMultiplier);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** the 25% is how much the two wheels may differ at most. Raise it for more spin.

### Try it

Bind it to a button to see it work. The right bumper here shoots at 3000 RPM with half the most backspin: the upper wheel at 2625 RPM and the lower at 3375 RPM.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="RobotContainer.java" %}

```java
// Right bumper: 3000 RPM with some backspin.
driverController.rightBumper().onTrue(doubleFlywheel.setSpinShot(RPM.of(3000), 0.5));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="ExampleTeleop.java" %}

```java
// Right bumper: 3000 RPM with some backspin.
robot.exampleController.rightBumper().onTrue(robot.doubleFlywheel.setSpinShot(RPM.of(3000), 0.5));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/RobotContainer.cpp" %}

```cpp
// Right bumper: 3000 RPM with some backspin.
driverController.RightBumper().OnTrue(doubleFlywheel.SetSpinShot(3000_rpm, 0.5));
```

{% endcode %}
{% endtab %}
{% endtabs %}

**Check it:** in simulation, graph the two speeds as in [step 2](/documentation/tutorials/double-flywheel/commands#check-it-in-simulation) and press the right bumper. The upper line settles at about 44 rotations per second (2625 RPM) and the lower at about 56 (3375 RPM).

### The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
The highlighted lines are new in this step.

<pre class="language-java" data-title="subsystems/DoubleFlywheelSubsystem.java" data-line-numbers><code class="lang-java">package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.KilogramSquareMeters;
import static org.wpilib.units.Units.RPM;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
import org.wpilib.command2.Command;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.command2.button.Trigger;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import org.wpilib.units.measure.AngularVelocity;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.remote.TalonFXWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class DoubleFlywheelSubsystem extends SubsystemBase {

  // Each flywheel gets its own config, so that each can be given its own speed.
  private final SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback and feedforward constants, on the real robot and in simulation.
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
      // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
      // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("UpperFlyWheel", TelemetryVerbosity.HIGH);

  // The lower flywheel is the same, except that its motor faces the other way.
  private final SmartMotorControllerConfig lowerConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(true)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("LowerFlyWheel", TelemetryVerbosity.HIGH);

  // The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
  private final TalonFX upperTalon = new TalonFX(1, new CANBus(CANPort.CAN_S0));
  private final TalonFX lowerTalon = new TalonFX(2, new CANBus(CANPort.CAN_S0));

  // One SmartMotorController for each flywheel, each driving one Kraken X60.
  private final SmartMotorController upperMotor = new TalonFXWrapper(upperTalon, DCMotor.getKrakenX60(1), upperConfig);
  private final SmartMotorController lowerMotor = new TalonFXWrapper(lowerTalon, DCMotor.getKrakenX60(1), lowerConfig);

  public DoubleFlywheelSubsystem() {
    // A mechanism class would do this for us. Without one, set up the telemetry
    // (and live tuning) of each motor controller ourselves.
    upperMotor.setupTelemetry();
    lowerMotor.setupTelemetry();
  }

  /** Spin both flywheels. One command sets both speeds, so the two always change together. */
  public Command setFlywheelSpeeds(AngularVelocity upperSpeed, AngularVelocity lowerSpeed) {
    return run(() -> {
      upperMotor.setVelocity(upperSpeed);
      lowerMotor.setVelocity(lowerSpeed);
    }).withName("Set FlyWheel Speeds");
  }

  /** Both flywheels at the same speed: no spin. */
  public Command neutralSpinShot() {
    return setFlywheelSpeeds(RPM.of(3000), RPM.of(3000));
  }

  /** The lower flywheel faster: backspin. */
  public Command backspinShot() {
    return setFlywheelSpeeds(RPM.of(2500), RPM.of(3500));
  }

  /** The upper flywheel faster: topspin. */
  public Command topspinShot() {
    return setFlywheelSpeeds(RPM.of(3500), RPM.of(2500));
  }

  /** Let both flywheels coast to a stop. */
  public Command stopFlywheels() {
    return runOnce(() -> {
      // A duty cycle of 0 lets the wheels coast down. A 0 RPM setpoint would brake them hard.
      upperMotor.setDutyCycle(0);
      lowerMotor.setDutyCycle(0);
    }).withName("Stop FlyWheels");
  }

  /** A Trigger that is true while both flywheels are within the tolerance of their target speeds. */
  public Trigger atTargetVelocity(AngularVelocity upperTarget, AngularVelocity lowerTarget, AngularVelocity tolerance) {
    return new Trigger(() -> upperMotor.getMechanismVelocity().isNear(upperTarget, tolerance)
        &#x26;&#x26; lowerMotor.getMechanismVelocity().isNear(lowerTarget, tolerance));
  }

<strong>  /**
</strong><strong>   * Spin both flywheels around a base speed, with a spin ratio between them.
</strong><strong>   *
</strong><strong>   * @param baseSpeed The average speed of the two flywheels.
</strong><strong>   * @param spinRatio From -1 (the most topspin) to 1 (the most backspin). 0 is no spin.
</strong><strong>   */
</strong><strong>  public Command setSpinShot(AngularVelocity baseSpeed, double spinRatio) {
</strong><strong>    double ratio = Math.max(-1.0, Math.min(1.0, spinRatio));
</strong><strong>    // At a ratio of 1 the lower flywheel runs 25% faster and the upper one 25% slower.
</strong><strong>    double upperMultiplier = 1.0 - ratio * 0.25;
</strong><strong>    double lowerMultiplier = 1.0 + ratio * 0.25;
</strong><strong>    return setFlywheelSpeeds(baseSpeed.times(upperMultiplier), baseSpeed.times(lowerMultiplier));
</strong><strong>  }
</strong>
  @Override
  public void periodic() {
    // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
    upperMotor.updateTelemetry();
    lowerMotor.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    // Runs each flywheel's physics simulation.
    upperMotor.simIterate();
    lowerMotor.simIterate();
  }
}
</code></pre>

{% endtab %}

{% tab title="Java, Commands v3" %}
The highlighted lines are new in this step.

<pre class="language-java" data-title="mechanisms/DoubleFlywheelMechanism.java" data-line-numbers><code class="lang-java">package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.KilogramSquareMeters;
import static org.wpilib.units.Units.RPM;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
import org.wpilib.command3.Command;
import org.wpilib.command3.Mechanism;
import org.wpilib.command3.Trigger;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import org.wpilib.units.measure.AngularVelocity;
import yams.commands3.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.remote.TalonFXWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class DoubleFlywheelMechanism implements Mechanism {

  // Each flywheel gets its own config, so that each can be given its own speed.
  private final SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      // Feedback and feedforward constants, on the real robot and in simulation.
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
      // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
      // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("UpperFlyWheel", TelemetryVerbosity.HIGH);

  // The lower flywheel is the same, except that its motor faces the other way.
  private final SmartMotorControllerConfig lowerConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withClosedLoopController(0.1, 0, 0)
      .withSimClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
      .withMomentOfInertia(KilogramSquareMeters.of(0.0006))
      .withMotorInverted(true)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("LowerFlyWheel", TelemetryVerbosity.HIGH);

  // The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
  private final TalonFX upperTalon = new TalonFX(1, new CANBus(CANPort.CAN_S0));
  private final TalonFX lowerTalon = new TalonFX(2, new CANBus(CANPort.CAN_S0));

  // One SmartMotorController for each flywheel, each driving one Kraken X60.
  private final SmartMotorController upperMotor = new TalonFXWrapper(upperTalon, DCMotor.getKrakenX60(1), upperConfig);
  private final SmartMotorController lowerMotor = new TalonFXWrapper(lowerTalon, DCMotor.getKrakenX60(1), lowerConfig);

  public DoubleFlywheelMechanism() {
    // A mechanism class would do this for us. Without one, set up the telemetry
    // (and live tuning) of each motor controller ourselves.
    upperMotor.setupTelemetry();
    lowerMotor.setupTelemetry();
  }

  /** Spin both flywheels. One command sets both speeds, so the two always change together. */
  public Command setFlywheelSpeeds(AngularVelocity upperSpeed, AngularVelocity lowerSpeed) {
    return run(coroutine -> {
      while (true) {
        upperMotor.setVelocity(upperSpeed);
        lowerMotor.setVelocity(lowerSpeed);
        coroutine.yield();
      }
    }).named("Set FlyWheel Speeds");
  }

  /** Both flywheels at the same speed: no spin. */
  public Command neutralSpinShot() {
    return setFlywheelSpeeds(RPM.of(3000), RPM.of(3000));
  }

  /** The lower flywheel faster: backspin. */
  public Command backspinShot() {
    return setFlywheelSpeeds(RPM.of(2500), RPM.of(3500));
  }

  /** The upper flywheel faster: topspin. */
  public Command topspinShot() {
    return setFlywheelSpeeds(RPM.of(3500), RPM.of(2500));
  }

  /** Let both flywheels coast to a stop. */
  public Command stopFlywheels() {
    return run(coroutine -> {
      // A duty cycle of 0 lets the wheels coast down. A 0 RPM setpoint would brake them hard.
      upperMotor.setDutyCycle(0);
      lowerMotor.setDutyCycle(0);
    }).named("Stop FlyWheels");
  }

  /** A Trigger that is true while both flywheels are within the tolerance of their target speeds. */
  public Trigger atTargetVelocity(AngularVelocity upperTarget, AngularVelocity lowerTarget, AngularVelocity tolerance) {
    return new Trigger(() -> upperMotor.getMechanismVelocity().isNear(upperTarget, tolerance)
        &#x26;&#x26; lowerMotor.getMechanismVelocity().isNear(lowerTarget, tolerance));
  }

<strong>  /**
</strong><strong>   * Spin both flywheels around a base speed, with a spin ratio between them.
</strong><strong>   *
</strong><strong>   * @param baseSpeed The average speed of the two flywheels.
</strong><strong>   * @param spinRatio From -1 (the most topspin) to 1 (the most backspin). 0 is no spin.
</strong><strong>   */
</strong><strong>  public Command setSpinShot(AngularVelocity baseSpeed, double spinRatio) {
</strong><strong>    double ratio = Math.max(-1.0, Math.min(1.0, spinRatio));
</strong><strong>    // At a ratio of 1 the lower flywheel runs 25% faster and the upper one 25% slower.
</strong><strong>    double upperMultiplier = 1.0 - ratio * 0.25;
</strong><strong>    double lowerMultiplier = 1.0 + ratio * 0.25;
</strong><strong>    return setFlywheelSpeeds(baseSpeed.times(upperMultiplier), baseSpeed.times(lowerMultiplier));
</strong><strong>  }
</strong>
  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
  public void periodic() {
    // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
    upperMotor.updateTelemetry();
    lowerMotor.updateTelemetry();
  }

  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
  public void simulationPeriodic() {
    // Runs each flywheel's physics simulation.
    upperMotor.simIterate();
    lowerMotor.simIterate();
  }
}
</code></pre>

{% endtab %}

{% tab title="C++" %}
The highlighted lines are new in this step.

<pre class="language-cpp" data-title="include/subsystems/DoubleFlywheelSubsystem.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include &#x3C;optional>

#include &#x3C;ctre/phoenix6/TalonFX.hpp>
#include &#x3C;wpi/commands2/CommandPtr.hpp>
#include &#x3C;wpi/commands2/SubsystemBase.hpp>
#include &#x3C;wpi/commands2/button/Trigger.hpp>
#include &#x3C;wpi/units/angular_velocity.hpp>

#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/remote/TalonFXWrapper.hpp"

class DoubleFlywheelSubsystem : public wpi::cmd::SubsystemBase {
 public:
  DoubleFlywheelSubsystem();

  /** Spin both flywheels. One command sets both speeds, so the two always change together. */
  wpi::cmd::CommandPtr SetFlywheelSpeeds(wpi::units::revolutions_per_minute_t upperSpeed,
                                         wpi::units::revolutions_per_minute_t lowerSpeed);

  /** Both flywheels at the same speed: no spin. */
  wpi::cmd::CommandPtr NeutralSpinShot();

  /** The lower flywheel faster: backspin. */
  wpi::cmd::CommandPtr BackspinShot();

  /** The upper flywheel faster: topspin. */
  wpi::cmd::CommandPtr TopspinShot();

  /** Let both flywheels coast to a stop. */
  wpi::cmd::CommandPtr StopFlywheels();

  /** A Trigger that is true while both flywheels are within the tolerance of their target speeds. */
  wpi::cmd::Trigger AtTargetVelocity(wpi::units::revolutions_per_minute_t upperTarget,
                                     wpi::units::revolutions_per_minute_t lowerTarget,
                                     wpi::units::revolutions_per_minute_t tolerance);

<strong>  /**
</strong><strong>   * Spin both flywheels around a base speed, with a spin ratio between them.
</strong><strong>   *
</strong><strong>   * @param baseSpeed The average speed of the two flywheels.
</strong><strong>   * @param spinRatio From -1 (the most topspin) to 1 (the most backspin). 0 is no spin.
</strong><strong>   */
</strong><strong>  wpi::cmd::CommandPtr SetSpinShot(wpi::units::revolutions_per_minute_t baseSpeed, double spinRatio);
</strong>
  void Periodic() override;
  void SimulationPeriodic() override;

 private:
  // The vendor motor controller objects: two TalonFX, with CAN IDs 1 and 2.
  ctre::phoenix6::hardware::TalonFX m_upperTalon{1, ctre::phoenix6::CANBus{}};
  ctre::phoenix6::hardware::TalonFX m_lowerTalon{2, ctre::phoenix6::CANBus{}};

  // Each flywheel gets its own config, so that each can be given its own speed.
  yams::motorcontrollers::SmartMotorControllerConfig m_upperConfig;
  yams::motorcontrollers::SmartMotorControllerConfig m_lowerConfig;

  // One SmartMotorController for each flywheel, created in the constructor.
  std::optional&#x3C;yams::motorcontrollers::remote::TalonFXWrapper> m_upperMotor;
  std::optional&#x3C;yams::motorcontrollers::remote::TalonFXWrapper> m_lowerMotor;
};
</code></pre>

<pre class="language-cpp" data-title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" data-line-numbers><code class="lang-cpp">#include "subsystems/DoubleFlywheelSubsystem.hpp"

<strong>#include &#x3C;algorithm>
</strong>#include &#x3C;wpi/math/controller/SimpleMotorFeedforward.hpp>
#include &#x3C;wpi/math/system/DCMotor.hpp>
#include &#x3C;wpi/units/angle.hpp>
#include &#x3C;wpi/units/current.hpp>
#include &#x3C;wpi/units/moment_of_inertia.hpp>
#include &#x3C;wpi/units/math.hpp>
#include &#x3C;wpi/units/voltage.hpp>

#include "yams/gearing/GearBox.hpp"
#include "yams/gearing/MechanismGearing.hpp"

using namespace yams::gearing;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;
using Feedforward = wpi::math::SimpleMotorFeedforward&#x3C;wpi::units::turns>;

DoubleFlywheelSubsystem::DoubleFlywheelSubsystem() {
  // The feedforward constants of both flywheels: kS and kV.
  const Feedforward feedforward{0.1_V, wpi::units::unit_t&#x3C;Feedforward::kv_unit>{0.12}};

  m_upperConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      // Feedback and feedforward constants, on the real robot and in simulation.
      .WithFeedback(0.1, 0, 0)
      .WithSimClosedLoopController(0.1, 0, 0)
      .WithFeedforward(feedforward)
      .WithSimFeedforward(feedforward)
      // Gearing from the motor rotor to the flywheel: 1:1, the wheel is on the motor's shaft.
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.0})})
      // There is no FlyWheel mechanism, so the simulation gets the wheel's moment of
      // inertia from here: a 4 inch, 1 lb (0.45 kg) wheel as a solid disc is
      // 0.5 x 0.45 kg x (0.0508 m)^2, about 0.0006 kg m^2.
      .WithMOI(wpi::units::kilogram_square_meter_t{0.0006})
      .WithMotorInverted(false)
      .WithZeroPower(Cfg::MotorMode::COAST)
      .WithStatorCurrentLimit(40_A)
      .WithTelemetry("UpperFlyWheel", Cfg::TelemetryVerbosity::HIGH);

  // The lower flywheel is the same, except that its motor faces the other way.
  m_lowerConfig
      .WithSubsystem(this)
      .WithClosedLoopMode()
      .WithFeedback(0.1, 0, 0)
      .WithSimClosedLoopController(0.1, 0, 0)
      .WithFeedforward(feedforward)
      .WithSimFeedforward(feedforward)
      .WithMotorGearing(MechanismGearing{GearBox::FromReductionStages({1.0})})
      .WithMOI(wpi::units::kilogram_square_meter_t{0.0006})
      .WithMotorInverted(true)
      .WithZeroPower(Cfg::MotorMode::COAST)
      .WithStatorCurrentLimit(40_A)
      .WithTelemetry("LowerFlyWheel", Cfg::TelemetryVerbosity::HIGH);

  // One SmartMotorController for each flywheel, each driving one Kraken X60.
  m_upperMotor.emplace(&#x26;m_upperTalon, wpi::math::DCMotor::KrakenX60(1), &#x26;m_upperConfig);
  m_lowerMotor.emplace(&#x26;m_lowerTalon, wpi::math::DCMotor::KrakenX60(1), &#x26;m_lowerConfig);

  // A mechanism class would do this for us. Without one, set up the telemetry
  // (and live tuning) of each motor controller ourselves.
  m_upperMotor->SetupTelemetry();
  m_lowerMotor->SetupTelemetry();
}

wpi::cmd::CommandPtr DoubleFlywheelSubsystem::SetFlywheelSpeeds(
    wpi::units::revolutions_per_minute_t upperSpeed, wpi::units::revolutions_per_minute_t lowerSpeed) {
  return Run([this, upperSpeed, lowerSpeed] {
           m_upperMotor->SetVelocity(wpi::units::turns_per_second_t{upperSpeed});
           m_lowerMotor->SetVelocity(wpi::units::turns_per_second_t{lowerSpeed});
         })
      .WithName("Set FlyWheel Speeds");
}

wpi::cmd::CommandPtr DoubleFlywheelSubsystem::NeutralSpinShot() {
  return SetFlywheelSpeeds(3000_rpm, 3000_rpm);
}

wpi::cmd::CommandPtr DoubleFlywheelSubsystem::BackspinShot() {
  return SetFlywheelSpeeds(2500_rpm, 3500_rpm);
}

wpi::cmd::CommandPtr DoubleFlywheelSubsystem::TopspinShot() {
  return SetFlywheelSpeeds(3500_rpm, 2500_rpm);
}

wpi::cmd::CommandPtr DoubleFlywheelSubsystem::StopFlywheels() {
  return RunOnce([this] {
    // A duty cycle of 0 lets the wheels coast down. A 0 RPM setpoint would brake them hard.
    m_upperMotor->SetDutyCycle(0);
    m_lowerMotor->SetDutyCycle(0);
  }).WithName("Stop FlyWheels");
}

wpi::cmd::Trigger DoubleFlywheelSubsystem::AtTargetVelocity(wpi::units::revolutions_per_minute_t upperTarget,
                                                            wpi::units::revolutions_per_minute_t lowerTarget,
                                                            wpi::units::revolutions_per_minute_t tolerance) {
  return wpi::cmd::Trigger([this, upperTarget, lowerTarget, tolerance] {
    return wpi::units::math::abs(m_upperMotor->GetMechanismVelocity() - upperTarget) &#x3C;= tolerance &#x26;&#x26;
           wpi::units::math::abs(m_lowerMotor->GetMechanismVelocity() - lowerTarget) &#x3C;= tolerance;
  });
}

<strong>wpi::cmd::CommandPtr DoubleFlywheelSubsystem::SetSpinShot(wpi::units::revolutions_per_minute_t baseSpeed,
</strong><strong>                                                          double spinRatio) {
</strong><strong>  double ratio = std::clamp(spinRatio, -1.0, 1.0);
</strong><strong>  // At a ratio of 1 the lower flywheel runs 25% faster and the upper one 25% slower.
</strong><strong>  double upperMultiplier = 1.0 - ratio * 0.25;
</strong><strong>  double lowerMultiplier = 1.0 + ratio * 0.25;
</strong><strong>  return SetFlywheelSpeeds(baseSpeed * upperMultiplier, baseSpeed * lowerMultiplier);
</strong><strong>}
</strong>
void DoubleFlywheelSubsystem::Periodic() {
  // Publishes each flywheel's telemetry, and applies anything changed through live tuning.
  m_upperMotor->UpdateTelemetry();
  m_lowerMotor->UpdateTelemetry();
}

void DoubleFlywheelSubsystem::SimulationPeriodic() {
  // Runs each flywheel's physics simulation.
  m_upperMotor->SimIterate();
  m_lowerMotor->SimIterate();
}
</code></pre>

{% endtab %}
{% endtabs %}

## Two motors on one wheel

So far each wheel has one motor. If a wheel is driven by two motors on the same shaft or gearbox, the second motor must always turn with the first. Make it a **follower**: it copies the leader's output, and you do not give it a config or a `SmartMotorController` of its own.

{% tabs %}
{% tab title="Java, Commands v2" %}

```java
private final SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
    // ... config options from step 1
    // A second Kraken X60 on the upper wheel's shaft, CAN ID 3. true: it faces the other way.
    .withFollowers(Pair.of(new TalonFX(3, new CANBus(CANPort.CAN_S0)), true));
```

{% endtab %}

{% tab title="Java, Commands v3" %}
The same as Commands v2, with `SmartMotorControllerConfig` from `yams.commands3.config`.

```java
private final SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
    // ... config options from step 1
    // A second Kraken X60 on the upper wheel's shaft, CAN ID 3. true: it faces the other way.
    .withFollowers(Pair.of(new TalonFX(3, new CANBus(CANPort.CAN_S0)), true));
```

{% endtab %}

{% tab title="C++" %}
Keep the follower's `TalonFX` as a member, next to the leader's, and name it in the leader's config:

```cpp
// In the header: a second Kraken X60 on the upper wheel's shaft, CAN ID 3.
ctre::phoenix6::hardware::TalonFX m_upperFollowerTalon{3, ctre::phoenix6::CANBus{}};

// In the constructor. true: it faces the other way.
m_upperConfig
    // ... config options from step 1
    .WithFollowers({{&m_upperFollowerTalon, true}});
```

{% endtab %}
{% endtabs %}

`Pair` is `org.wpilib.util.Pair`. Change the `DCMotor` in that wheel's `SmartMotorController` to two motors, `DCMotor.getKrakenX60(2)`, so the simulation knows. The follower must be the same vendor as the leader. [Followers](/documentation/reference/editor/config/followers#withfollowers) has the details.

## Both wheels at the same speed

If you want both wheels to always get the **same** setpoint, you do not need to command each one yourself. Make one a **loosely coupled follower** of the other, and command only the leader. Unlike a follower above, it keeps its own config and runs its own closed loop, because it is on a different shaft:

{% tabs %}
{% tab title="Java, Commands v2" %}

```java
SmartMotorControllerConfig lowerConfig = new SmartMotorControllerConfig(this)
    // ... config options
    ;

SmartMotorController lowerMotor = new TalonFXWrapper(lowerTalon, DCMotor.getKrakenX60(1), lowerConfig);

SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
    // ... config options
    .withLooselyCoupledFollowers(lowerMotor); // the lower motor is given the upper motor's setpoints

SmartMotorController upperMotor = new TalonFXWrapper(upperTalon, DCMotor.getKrakenX60(1), upperConfig);
```

{% endtab %}

{% tab title="Java, Commands v3" %}
The same as Commands v2, with `SmartMotorControllerConfig` from `yams.commands3.config`.

```java
SmartMotorControllerConfig lowerConfig = new SmartMotorControllerConfig(this)
    // ... config options
    ;

SmartMotorController lowerMotor = new TalonFXWrapper(lowerTalon, DCMotor.getKrakenX60(1), lowerConfig);

SmartMotorControllerConfig upperConfig = new SmartMotorControllerConfig(this)
    // ... config options
    .withLooselyCoupledFollowers(lowerMotor); // the lower motor is given the upper motor's setpoints

SmartMotorController upperMotor = new TalonFXWrapper(upperTalon, DCMotor.getKrakenX60(1), upperConfig);
```

{% endtab %}

{% tab title="C++" %}
In the constructor, create the lower motor first, then name it in the upper motor's config:

```cpp
m_lowerMotor.emplace(&m_lowerTalon, wpi::math::DCMotor::KrakenX60(1), &m_lowerConfig);

m_upperConfig
    // ... config options
    .WithLooselyCoupledFollowers({&m_lowerMotor.value()});  // the lower motor is given the upper motor's setpoints

m_upperMotor.emplace(&m_upperTalon, wpi::math::DCMotor::KrakenX60(1), &m_upperConfig);
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Loosely coupled followers are only given velocity and position requests, **NOT** duty cycle or voltage requests. Command each `SmartMotorController` yourself when you need fully independent control, as the rest of this tutorial does.
{% endhint %}

[Followers](/documentation/reference/editor/config/followers) explains the difference between loosely and tightly coupled followers.

## Summary

You now have a double flywheel shooter with:

* Independent velocity control of the upper and lower flywheels
* Preset shots for no spin, backspin and topspin, and a spin ratio for anything in between
* Simulation of both wheels, which you can graph
* Telemetry and live tuning for both flywheels

The differences from a single flywheel are:

1. Two `SmartMotorControllerConfig`s and two `SmartMotorController`s, controlled directly instead of through a `FlyWheel` mechanism
2. The subsystem calls `setupTelemetry()`, `updateTelemetry()` and `simIterate()` on each `SmartMotorController` itself
3. One command sets both velocity setpoints


# Step 4: Tune it

Tune both flywheels while the simulation runs, then copy the gains into your code.

The gains from step 1 are placeholders: `kS` is 0.1, `kV` is 0.12 and `kP` is 0.1 on both wheels. On this page you tune them while the simulation runs, the same way you will tune the real wheels on the robot. Nothing is saved until you copy the numbers into your code at the end.

A flywheel is tuned the way [the shooter's tune step](/documentation/tutorials/shooter-flywheels/tune) does it: `kV` first, with `kP` turned off, then a little `kP`. The difference here is that there are two wheels. This tutorial's wheels are alike, a Kraken X60 on each at 1:1, so you tune one and copy its gains to the other.

{% hint style="info" %}
**In simulation you are tuning the simulation's gains.** While the code runs in simulation, live tuning changes the `withSimClosedLoopController` and `withSimFeedforward` values. On the real robot it changes `withClosedLoopController` and `withFeedforward`.
{% endhint %}

## Before you start

* Start the simulation and enable **Teleoperated**, as in [step 2's check](/documentation/tutorials/double-flywheel/commands#check-it-in-simulation). Both wheels are still.
* Do not press any of the shooter's buttons while you tune. A button runs another command on the subsystem, which stops live tuning. If that happens, start live tuning again.

Then tune with the YAMS Live Tuner, or by typing the values in AdvantageScope and Elastic. Both change the same values, so pick one.

{% tabs %}
{% tab title="YAMS Live Tuner" %}
The [YAMS Live Tuner](/documentation/how-to-tuning/live-tuning/live-tuner) tunes both wheels of a double flywheel together: it checks each wheel before anything spins, then you send speeds and change gains while watching both on one graph.

{% stepper %}
{% step %}

### Connect

Open [tuning.yassrobotics.com](https://tuning.yassrobotics.com/), pick **Simulation**, and press **Connect**. If your browser asks whether the page may connect to devices on your local network, allow it.

**Check it:** the badge in the header shows `localhost`, with the robot enabled in Teleop.
{% endstep %}

{% step %}

### Pick both wheels

1. Under **Telemetry name**, choose `UpperFlyWheel`: the name from the upper motor's `withTelemetry`.
2. Under **Live Tuning command**, choose `DoubleFlywheelSubsystem` (Commands v2 and C++) or `DoubleFlywheelMechanism` (Commands v3). Both wheels share it.
3. Set **Type** to **Flywheel**, and **Second flywheel** to `LowerFlyWheel`.
4. Press **Continue**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-505c7e96a2d7adc5baef63fe794fa5420aaf70ad%2Flive-tuner-tutorial-double-flywheel-mechanism.png?alt=media" alt="The Mechanism step with UpperFlyWheel as the telemetry name, DoubleFlywheelSubsystem as the Live Tuning command, Flywheel as the type and LowerFlyWheel as the second flywheel"><figcaption><p>Both wheels of the tutorial's shooter, tuned through one <code>Live Tuning</code> command.</p></figcaption></figure>

**Check it:** the telemetry card shows both wheels at 0 RPM.
{% endstep %}

{% step %}

### Checklist and inversions

The inversions are checked one wheel at a time, starting with `UpperFlyWheel`.

1. Tick every item on the pre-motion checklist, leave **Current trip (A)** at 40, and press **Continue**.
2. Tick the confirmation and press **Start voltage control**.
3. Drag the voltage slider to the right and hold it. The upper wheel spins up. Let go once **Positive voltage moves forward** is ticked: the slider goes back to 0 V.
4. If the wheel does not spin with the slider all the way to the right, select the number at the slider's right end, 1.00 V to start with, and raise it a little.
5. Press **Finish check**. `UpperFlyWheel` now reads **passed**.
6. Choose `LowerFlyWheel` under **Wheel**, press **Start voltage control**, and do the same.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-670f476ce196988e68e75895a315fd735419ff34%2Flive-tuner-tutorial-double-flywheel-inversions-upper.png?alt=media" alt="Checking the upper wheel: the slider held at 1.00 V, the speed at 502 RPM, and Positive voltage moves forward ticked"><figcaption><p>The upper wheel spins forward at 1 V. The lower wheel is checked the same way next.</p></figcaption></figure>

**Check it:** both wheels read **passed**, and the Live tune card opens. If the Live Tuner warns that a wheel's speed went the wrong way, that wheel's `withMotorInverted` in step 1 is wrong.
{% endstep %}

{% step %}

### Start live tuning and find kV

Press **Start Live Tuning**. The speeds and gains you send are now applied to both wheels every loop.

`kV` is how many volts the motor needs for each rotation per second of wheel speed. Get it right and the wheel reaches its speed on feedforward alone.

1. On the Settings card, choose `UpperFlyWheel` under **Wheel**. On its **Gains** tab, type `0` into **kP** and `0` into **kS**. The simulation has no friction, so it needs no `kS`.
2. On the **Setpoints** tab, press **Both 3000 RPM**.
3. Watch the upper wheel, the solid line on the graph. Type `0.1` into **kV**: the wheel settles well below 3000 RPM.
4. Raise **kV** a little at a time until the measured speed settles on the setpoint. For a Kraken X60 at 1:1 it ends up near `0.12`. If the wheel settles above the setpoint, lower it.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-126a3062c1226cc69b061328288f2d3898ad7758%2Flive-tuner-tutorial-double-flywheel-kv.png?alt=media" alt="Both wheels at a 3000 RPM setpoint. The upper wheel, solid, sat near 2500 RPM with kV at 0.1, then rose to 3016 RPM when kV was raised to 0.12. The lower wheel, dashed, still has its starting gains and runs at 3035 RPM"><figcaption><p>The upper wheel's <code>kV</code> raised from 0.1 to 0.12: it climbs from about 2500 RPM onto 3000 RPM.</p></figcaption></figure>

**Check it:** the upper wheel settles within a few RPM of 3000, with `kP` still at 0.
{% endstep %}

{% step %}

### Copy the gains to the other wheel

The two wheels are alike, so the lower wheel needs the same gains.

1. With `UpperFlyWheel` still chosen on the Settings card, press **Copy these gains to LowerFlyWheel**. It copies the feedback, the feedforward and the motion profile, but not the current limits.
2. Press **Both 2000 RPM**, then **Both 3000 RPM**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-e53c6573b2dda3b3e949c680bf377e55aa51945f%2Flive-tuner-tutorial-double-flywheel-gains-copy.png?alt=media" alt="The Settings card with UpperFlyWheel chosen: kP 0, kS 0 and kV 0.12, each with its old value under it, and the Copy these gains to LowerFlyWheel button"><figcaption><p>The upper wheel's gains, ready to copy to the lower wheel.</p></figcaption></figure>

**Check it:** both wheels settle on each setpoint with the same `kV`. If your wheels are not alike, such as different gearing or motors, tune the lower wheel the same way instead of copying.
{% endstep %}

{% step %}

### Tune kP

`kP` adds a push when a wheel is slower or faster than its setpoint, such as when a game piece goes through and drags it down.

1. Type `0.1` into the upper wheel's **kP**, and copy the gains to the lower wheel again.
2. Turn on **Alternate setpoints**, with **Setpoint A** at `2000` and **Setpoint B** at `3000`. Both wheels now change speed every 5 seconds.
3. Raise **kP** a step at a time (0.2, 0.3, ...), copying it to the lower wheel each time. Each step should make the wheels reach the new speed a little faster.
4. Stop, and press **was** to go back one step, when the speed overshoots the setpoint or the line gets jittery.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-22e15d8e70af12d42b54037a1859be81e4b6188b%2Flive-tuner-tutorial-double-flywheel-alternate.png?alt=media" alt="Alternate setpoints on, switching both wheels between 2000 and 3000 RPM with kP at 0.2: both lines follow each step"><figcaption><p><code>kP</code> 0.2 on both wheels, alternating between 2000 and 3000 RPM.</p></figcaption></figure>

**Check it:** both wheels reach each new speed quickly and settle on it without bouncing around it. Press **Space** to stop when you are done.
{% endstep %}
{% endstepper %}
{% endtab %}

{% tab title="AdvantageScope and Elastic" %}
You type each value into its NetworkTables key yourself, and graph both wheels in AdvantageScope. The steps are [the shooter's tune step](/documentation/tutorials/shooter-flywheels/tune), done once for each wheel. Only the names differ:

|                                          | Shooter tutorial                          | This tutorial                                                       |
| ---------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------- |
| Live Tuning command, Commands v2 and C++ | `NT:/Tuning/ShooterSubsystem/Live Tuning` | `NT:/Tuning/DoubleFlywheelSubsystem/Live Tuning`                    |
| Live Tuning command, Commands v3         | `NT:/Tuning/ShooterMechanism/Live Tuning` | `NT:/Tuning/DoubleFlywheelMechanism/Live Tuning`                    |
| Values you type                          | `NT:/Tuning/Shooter/ShooterMotor/`        | `NT:/Tuning/UpperFlyWheel/` and `NT:/Tuning/LowerFlyWheel/`         |
| Values you watch                         | `NT:/Mechanisms/Shooter/ShooterMotor/`    | `NT:/Mechanisms/UpperFlyWheel/` and `NT:/Mechanisms/LowerFlyWheel/` |

One `Live Tuning` command covers both wheels, so start it once. Then:

1. Type `0` into `closedloop/feedback/kP` and `closedloop/feedforward/kS` under both wheels.
2. Type `3000` into `closedloop/setpoint/velocity` under both wheels.
3. Raise `closedloop/feedforward/kV` under `UpperFlyWheel` until its `mechanism/velocity` settles on 50 (3000 RPM is 50 rotations per second). Type the same `kV` under `LowerFlyWheel`.
4. Raise `closedloop/feedback/kP` on both wheels, a step at a time, while you move the setpoints between `2000` and `3000`.
   {% endtab %}
   {% endtabs %}

## Copy the numbers into your code

Dashboard changes are lost when the code restarts. Write the numbers you ended up with into both configs from step 1. In simulation they go into the `Sim` versions.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/DoubleFlywheelSubsystem.java" %}

```java
// Before, in both upperConfig and lowerConfig
.withSimClosedLoopController(0.1, 0, 0)
.withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))

// After: your numbers. SimpleMotorFeedforward takes kS, kV, kA.
.withSimClosedLoopController(0.2, 0, 0)
.withSimFeedforward(new SimpleMotorFeedforward(0, 0.12, 0))
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/DoubleFlywheelMechanism.java" %}

```java
// Before, in both upperConfig and lowerConfig
.withSimClosedLoopController(0.1, 0, 0)
.withSimFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0))

// After: your numbers. SimpleMotorFeedforward takes kS, kV, kA.
.withSimClosedLoopController(0.2, 0, 0)
.withSimFeedforward(new SimpleMotorFeedforward(0, 0.12, 0))
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
Both configs share one `feedforward` for the real robot and simulation. Give the simulation its own:

{% code title="cpp/subsystems/DoubleFlywheelSubsystem.cpp" %}

```cpp
// Your simulation numbers: kS and kV.
const Feedforward simFeedforward{0_V, wpi::units::unit_t<Feedforward::kv_unit>{0.12}};

// Then, in both m_upperConfig and m_lowerConfig: kP, kI, kD, and the feedforward.
.WithSimClosedLoopController(0.2, 0, 0)
.WithSimFeedforward(simFeedforward)
```

{% endcode %}
{% endtab %}
{% endtabs %}

The numbers above are an example. Use the ones you found.

**Check it:** restart the simulation and enable it. Press **A**: both wheels reach 3000 RPM quickly and hold it. Press **B** and **X**: each wheel reaches its own speed of the backspin or topspin shot.

## If it did not work

* **Only one wheel is in the Telemetry name list.** Check that `setupTelemetry()` is called on both `SmartMotorController`s, as in step 1.
* **AdvantageScope: typing a value does nothing.** Turn on AdvantageScope's tuning mode, check the `Live Tuning` command is still running, and check you typed under `NT:/Tuning`, not `NT:/Mechanisms`.
* **Live tuning stopped on its own.** A button press took over the subsystem. On the Live Tuner, the current trip or pressing Space also stops it. Start it again.
* **The two wheels settle at different speeds with the same gains.** The wheels are not alike after all. Tune each one on its own.
* **The numbers were gone after a restart.** They only last until the code stops. Copy them into your code, as in [Copy the numbers into your code](#copy-the-numbers-into-your-code).

More problems and fixes: [Troubleshooting](/documentation/tutorials/troubleshooting).

## Run it on the robot

Put it on the robot with [the arm's step 6: Run it on the robot](/documentation/tutorials/arm/robot), with these differences:

* The CAN IDs are the two `TalonFX`s from step 1.
* A flywheel has no starting position and no soft limits, so skip those parts.
* For the direction check, positive should spin each wheel the way that throws a game piece **out**.
* On the first enable, press **A** (3000 RPM on both wheels) before you try the spin shots.
* Tune `kS`, then `kV`, then `kP` again on the robot. Friction means real wheels need some `kS`. Copy the robot's numbers into `withClosedLoopController` and `withFeedforward`.


# Swerve Drive

Learn how to program a Swerve Drive.

{% hint style="info" %}
This tutorial needs three libraries: YAMS, REVLib (for the `SparkMax` motor controllers) and Phoenix 6 (for the `CANcoder`s and the `Pigeon2`). [Create a project and install YAMS](/documentation/tutorials/project-setup) walks through installing them.
{% endhint %}

## Intro

This tutorial builds a swerve drive that works in real life and simulation with the same code.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-8314f33fa57f8b964ff714ce3dd6c1f50bb70505%2Ftutorial-swerve-modules.gif?alt=media" alt="Animation of two controller sticks and a top view of a swerve drive with its four modules. Left stick forward: every module points forward at the same speed. Left stick left: every module turns to point left and the robot does not rotate. Right stick left: the modules form a circle and the robot spins in place. Both sticks: each module gets its own angle and speed."><figcaption><p>You ask for a chassis speed. <code>SwerveDrive</code> works out the four modules.</p></figcaption></figure>

## Details

This swerve drive uses the following hardware and controls:

* 4x `SparkMax` (NEO) drive motors, CAN IDs 1, 4, 7, 10
* 4x `SparkMax` (NEO) azimuth motors, CAN IDs 2, 5, 8, 11
* 4x `CANcoder` absolute encoders, CAN IDs 3, 6, 9, 12
* `Pigeon2` gyro, CAN ID 14
* SDS MK4 L2 modules: drive gear ratio `6.75:1`, azimuth gear ratio `12.8:1`, 4 inch wheels
* The left stick translates, and the right stick's X axis rotates
* Holding the left bumper drives to a pose on the field, and the top face button zeroes the gyro

{% hint style="info" %}
YAMS simulates all eight motors, so a swerve simulation uses more of your computer than a single mechanism does. If it runs slowly, close other programs while it runs.
{% endhint %}

## The steps

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-4d6d7e3aeadd15082c70ba3fdabcffe9552eee3a%2Ftutorial-swerve-steps.png?alt=media" alt="The three steps of the swerve drive tutorial. Step 1, the module motors: a config for the drive motors and a config for the azimuth motors. Step 2, the modules and the drive: four SwerveModules, a gyro and a SwerveDrive. Step 3, driving: drive commands, and a SwerveInputStream that reads the controller."><figcaption><p>The three coding steps, one page each. Step 4 then tunes it in simulation, and step 5 runs it on the real robot.</p></figcaption></figure>

Every step has a tab for **Java with Commands v2**, **Java with Commands v3** and **C++**. Steps 1 to 3 each end with a check you can run, and each check names the likely failures. [Troubleshooting](/documentation/tutorials/troubleshooting) has more.

| Step                                                                                         | What you do                                                                                              |
| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| [Before you start](/documentation/tutorials/project-setup)                                   | Create a WPILib project and install YAMS, REVLib and Phoenix 6. Skip this if you already have a project. |
| [Step 1: The module motors](/documentation/tutorials/swerve-drive/module-motors)             | A config for the drive motors and a config for the azimuth motors.                                       |
| [Step 2: The modules and the drive](/documentation/tutorials/swerve-drive/modules-and-drive) | Build four `SwerveModule`s, add the gyro, and create the `SwerveDrive`.                                  |
| [Step 3: Driving](/documentation/tutorials/swerve-drive/driving)                             | Drive commands, a `SwerveInputStream` for the sticks, and the bindings.                                  |
| [Step 4: Tune it](/documentation/tutorials/swerve-drive/tune)                                | Practice tuning the azimuth and drive motors in simulation with AdvantageScope.                          |
| [Step 5: On the real robot](/documentation/tutorials/swerve-drive/real-robot)                | Set the encoder offsets, check every direction, tune the modules and drive on the ground.                |

## Complete example

The following files from the YAMS `simple_robot-2027` Commands v2 example are a complete swerve drive for the same hardware. The example has no encoder offsets or tuned gains, so it is a reference for the code, not for your robot's numbers.

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/SwerveSubsystem.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/RobotContainer.java>" %}

The same drive in the other two flavors:

* **Java, Commands v3:** [`SwerveMechanism.java`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/simple_robot-2027/src/main/java/first/robot/mechanisms/SwerveMechanism.java) in `examples/commands3/simple_robot-2027`
* **C++:** [`SwerveSubsystem.h`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/include/subsystems/SwerveSubsystem.h) and [`SwerveSubsystem.cpp`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/cpp/subsystems/SwerveSubsystem.cpp) in `examples/cpptest`

## Read more

* [AdvantageKit Integration](/documentation/tutorials/advantagekit-integration) for swerve
* [Organizing Configs in Constants](/documentation/understanding/config-organization) for cleaner code
* [How do I view my DataLog in AdvantageScope?](/documentation/how-to-simulation-and-logging/how-do-i-view-my-datalog-in-advantagescope), to review this drive's telemetry after a match


# Step 1: The module motors

A SmartMotorControllerConfig for the drive motors and one for the azimuth motors.

{% hint style="info" %}
This page assumes a project with YAMS and REVLib and Phoenix 6 installed. If you do not have one yet, start at [Create a project and install YAMS](/documentation/tutorials/project-setup).
{% endhint %}

Every swerve module has two motors, and they do different jobs:

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-334ca718dfc3af013b0986833ea5b5326ba2a2dc%2Fmech-module-how.png?alt=media" alt="A swerve module seen from above, with its speed along the wheel and its angle. The drive motor uses velocity control to set how fast the wheel rolls. The azimuth motor uses position control with wrapping to set which way the wheel points. An absolute encoder tells the azimuth where the wheel is at startup. The module&#x27;s state is a SwerveModuleVelocity, a speed and an angle."><figcaption><p>One module is a drive motor, an azimuth motor and an absolute encoder.</p></figcaption></figure>

* The **drive** motor turns the wheel. It is **velocity** controlled, so it gets a PID controller and a feedforward, and it needs the wheel diameter to turn rotations into distance.
* The **azimuth** motor steers the module. It is **position** controlled.

All four modules are built the same, so you write each config once and reuse it.

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

## Create the file

{% tabs %}
{% tab title="Java, Commands v2" %}
Create `SwerveSubsystem.java` in the `subsystems` folder. Each method builds a fresh config, because every motor needs a config of its own.
{% endtab %}

{% tab title="Java, Commands v3" %}
Create `SwerveMechanism.java` in the `mechanisms` folder. Each method builds a fresh config, because every motor needs a config of its own.

The config comes from `yams.commands3.config`, and it takes the `Mechanism` where Commands v2 passes the subsystem.
{% endtab %}

{% tab title="C++" %}
Create `SwerveSubsystem.hpp` in `src/main/include/subsystems` and `SwerveSubsystem.cpp` in `src/main/cpp/subsystems`.

YAMS keeps a pointer to each config, so in C++ a config cannot be a temporary. These two methods fill in a config that someone else owns; step 2 gives every module its own.

`WithFeedback` is the C++ name of `withClosedLoopController`, `WithMotorGearing` of `withGearing`, and `WithMechanismDiameter` of `withWheelDiameter`.
{% endtab %}
{% endtabs %}

{% stepper %}
{% step %}

### The drive motor config

The drive motor turns the wheel and is **velocity** controlled. It needs the wheel diameter to turn rotations into distance, a PID controller, and a feedforward whose `kV` does most of the work of holding a speed.

The gains are placeholders. `kV` is the voltage for each wheel rotation per second: a NEO turns a 6.75:1 wheel about 14 times a second at 12 volts, so `12 / 14`, about `0.85`, is close. With it the robot drives at roughly the speed you ask for. If it drives noticeably slower than the stick asks, `kV` is too low; if it lurches past the speed, it is too high. [Step 5](/documentation/tutorials/swerve-drive/real-robot) tunes it properly.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java" %}

```java
/** The config of one drive motor. Drive motors are velocity controlled. */
private SmartMotorControllerConfig buildDriveCfg() {
  return new SmartMotorControllerConfig(this)
      // The wheel diameter turns wheel rotations into distance driven.
      .withWheelDiameter(Inches.of(4))
      // kP trims the velocity error that is left after the feedforward.
      .withClosedLoopController(0.3, 0, 0)
      // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
      .withGearing(new MechanismGearing(6.75))
      // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
      // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
      .withFeedforward(new SimpleMotorFeedforward(0, 0.85))
      // Set this to true if the wheel spins backward when it is told to drive forward.
      .withMotorInverted(false)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("driveMotor", TelemetryVerbosity.HIGH);
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java" %}

```java
/** The config of one drive motor. Drive motors are velocity controlled. */
private SmartMotorControllerConfig buildDriveCfg() {
  return new SmartMotorControllerConfig(this)
      // The wheel diameter turns wheel rotations into distance driven.
      .withWheelDiameter(Inches.of(4))
      // kP trims the velocity error that is left after the feedforward.
      .withClosedLoopController(0.3, 0, 0)
      // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
      .withGearing(new MechanismGearing(6.75))
      // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
      // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
      .withFeedforward(new SimpleMotorFeedforward(0, 0.85))
      // Set this to true if the wheel spins backward when it is told to drive forward.
      .withMotorInverted(false)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("driveMotor", TelemetryVerbosity.HIGH);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/SwerveSubsystem.hpp" %}

```cpp
/** Fill in the config of one drive motor. Drive motors are velocity controlled. */
void ConfigureDrive(yams::motorcontrollers::SmartMotorControllerConfig& config);
```

{% endcode %}

{% code title="cpp/subsystems/SwerveSubsystem.cpp" %}

```cpp
void SwerveSubsystem::ConfigureDrive(Cfg& config) {
  config
      .WithSubsystem(this)
      // The wheel diameter turns wheel rotations into distance driven.
      .WithMechanismDiameter(4_in)
      // kP trims the velocity error that is left after the feedforward.
      .WithFeedback(0.3, 0, 0)
      // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
      .WithMotorGearing(6.75)
      // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
      // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
      .WithFeedforward(Feedforward{0_V, wpi::units::unit_t<Feedforward::kv_unit>{0.85}})
      // Set this to true if the wheel spins backward when it is told to drive forward.
      .WithMotorInverted(false)
      .WithStatorCurrentLimit(40_A)
      .WithTelemetry("driveMotor", Cfg::TelemetryVerbosity::HIGH);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Set your wheel diameter and your module's drive gear ratio. Your module's maker publishes the ratio: this tutorial uses an MK4 L2, which is 6.75:1. Leave `withMotorInverted(false)` for now: [Step 5](/documentation/tutorials/swerve-drive/real-robot#check-the-directions) checks which way the wheel spins and tells you when to change it.

Want the details? [Live tuning](/documentation/how-to-tuning/live-tuning) has a section on tuning a swerve module's drive motor.
{% endstep %}

{% step %}

### The azimuth motor config

The azimuth motor steers the module and is **position** controlled. Two settings matter here:

* **`withContinuousWrapping`** tells the controller that the wheel can turn all the way round, so -180 and +180 degrees are the same angle. Without it a wheel at 170 degrees asked for -170 degrees spins nearly a full turn the long way, instead of 20 degrees the short way. It must come after `withClosedLoopController`.
* **`withMotorInverted`** sets which way the motor turns. Angles are counter-clockwise positive, seen from above, so a positive command must turn the wheel counter-clockwise. [Step 5](/documentation/tutorials/swerve-drive/real-robot#check-the-directions) checks it.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java" %}

```java
/** The config of one azimuth (steering) motor. Azimuth motors are position controlled. */
private SmartMotorControllerConfig buildAzimuthCfg() {
  return new SmartMotorControllerConfig(this)
      // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
      .withClosedLoopController(4, 0, 0)
      // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
      // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
      .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
      // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
      .withGearing(new MechanismGearing(12.8))
      // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
      .withMotorInverted(false)
      // The azimuth motor rarely works hard, so it gets a lower limit.
      .withStatorCurrentLimit(Amps.of(20))
      .withTelemetry("angleMotor", TelemetryVerbosity.HIGH);
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java" %}

```java
/** The config of one azimuth (steering) motor. Azimuth motors are position controlled. */
private SmartMotorControllerConfig buildAzimuthCfg() {
  return new SmartMotorControllerConfig(this)
      // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
      .withClosedLoopController(4, 0, 0)
      // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
      // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
      .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
      // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
      .withGearing(new MechanismGearing(12.8))
      // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
      .withMotorInverted(false)
      // The azimuth motor rarely works hard, so it gets a lower limit.
      .withStatorCurrentLimit(Amps.of(20))
      .withTelemetry("angleMotor", TelemetryVerbosity.HIGH);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/SwerveSubsystem.hpp" %}

```cpp
/** Fill in the config of one azimuth (steering) motor. Azimuth motors are position controlled. */
void ConfigureAzimuth(yams::motorcontrollers::SmartMotorControllerConfig& config);
```

{% endcode %}

{% code title="cpp/subsystems/SwerveSubsystem.cpp" %}

```cpp
void SwerveSubsystem::ConfigureAzimuth(Cfg& config) {
  config
      .WithSubsystem(this)
      // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
      .WithFeedback(4, 0, 0)
      // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
      // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
      .WithContinuousWrapping(-0.5_tr, 0.5_tr)
      // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
      .WithMotorGearing(12.8)
      // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
      .WithMotorInverted(false)
      // The azimuth motor rarely works hard, so it gets a lower limit.
      .WithStatorCurrentLimit(20_A)
      .WithTelemetry("angleMotor", Cfg::TelemetryVerbosity::HIGH);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Set your module's steering gear ratio. An MK4 steers at 12.8:1. Other modules, such as an MK4i, use a different ratio: check your module maker's page.

Want the details? [Swerve Module](/documentation/understanding/swerve-drive/swerve-module)
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java" lineNumbers="true" %}

```java
package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Rotations;

import org.wpilib.command2.SubsystemBase;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.MechanismGearing;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class SwerveSubsystem extends SubsystemBase {

  /** The config of one drive motor. Drive motors are velocity controlled. */
  private SmartMotorControllerConfig buildDriveCfg() {
    return new SmartMotorControllerConfig(this)
        // The wheel diameter turns wheel rotations into distance driven.
        .withWheelDiameter(Inches.of(4))
        // kP trims the velocity error that is left after the feedforward.
        .withClosedLoopController(0.3, 0, 0)
        // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
        .withGearing(new MechanismGearing(6.75))
        // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
        // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
        .withFeedforward(new SimpleMotorFeedforward(0, 0.85))
        // Set this to true if the wheel spins backward when it is told to drive forward.
        .withMotorInverted(false)
        .withStatorCurrentLimit(Amps.of(40))
        .withTelemetry("driveMotor", TelemetryVerbosity.HIGH);
  }

  /** The config of one azimuth (steering) motor. Azimuth motors are position controlled. */
  private SmartMotorControllerConfig buildAzimuthCfg() {
    return new SmartMotorControllerConfig(this)
        // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
        .withClosedLoopController(4, 0, 0)
        // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
        // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
        .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
        // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
        .withGearing(new MechanismGearing(12.8))
        // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
        .withMotorInverted(false)
        // The azimuth motor rarely works hard, so it gets a lower limit.
        .withStatorCurrentLimit(Amps.of(20))
        .withTelemetry("angleMotor", TelemetryVerbosity.HIGH);
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java" lineNumbers="true" %}

```java
package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Rotations;

import org.wpilib.command3.Mechanism;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import yams.commands3.config.SmartMotorControllerConfig;
import yams.core.gearing.MechanismGearing;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class SwerveMechanism implements Mechanism {

  /** The config of one drive motor. Drive motors are velocity controlled. */
  private SmartMotorControllerConfig buildDriveCfg() {
    return new SmartMotorControllerConfig(this)
        // The wheel diameter turns wheel rotations into distance driven.
        .withWheelDiameter(Inches.of(4))
        // kP trims the velocity error that is left after the feedforward.
        .withClosedLoopController(0.3, 0, 0)
        // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
        .withGearing(new MechanismGearing(6.75))
        // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
        // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
        .withFeedforward(new SimpleMotorFeedforward(0, 0.85))
        // Set this to true if the wheel spins backward when it is told to drive forward.
        .withMotorInverted(false)
        .withStatorCurrentLimit(Amps.of(40))
        .withTelemetry("driveMotor", TelemetryVerbosity.HIGH);
  }

  /** The config of one azimuth (steering) motor. Azimuth motors are position controlled. */
  private SmartMotorControllerConfig buildAzimuthCfg() {
    return new SmartMotorControllerConfig(this)
        // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
        .withClosedLoopController(4, 0, 0)
        // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
        // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
        .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
        // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
        .withGearing(new MechanismGearing(12.8))
        // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
        .withMotorInverted(false)
        // The azimuth motor rarely works hard, so it gets a lower limit.
        .withStatorCurrentLimit(Amps.of(20))
        .withTelemetry("angleMotor", TelemetryVerbosity.HIGH);
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/SwerveSubsystem.hpp" lineNumbers="true" %}

```cpp
#pragma once

#include <wpi/commands2/SubsystemBase.hpp>

#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"

class SwerveSubsystem : public wpi::cmd::SubsystemBase {
 public:
  SwerveSubsystem();

 private:
  /** Fill in the config of one drive motor. Drive motors are velocity controlled. */
  void ConfigureDrive(yams::motorcontrollers::SmartMotorControllerConfig& config);

  /** Fill in the config of one azimuth (steering) motor. Azimuth motors are position controlled. */
  void ConfigureAzimuth(yams::motorcontrollers::SmartMotorControllerConfig& config);
};
```

{% endcode %}

{% code title="cpp/subsystems/SwerveSubsystem.cpp" lineNumbers="true" %}

```cpp
#include "subsystems/SwerveSubsystem.hpp"

#include <wpi/math/controller/SimpleMotorFeedforward.hpp>
#include <wpi/units/angle.hpp>
#include <wpi/units/current.hpp>
#include <wpi/units/length.hpp>
#include <wpi/units/voltage.hpp>

using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;
using Feedforward = wpi::math::SimpleMotorFeedforward<wpi::units::turns>;

void SwerveSubsystem::ConfigureDrive(Cfg& config) {
  config
      .WithSubsystem(this)
      // The wheel diameter turns wheel rotations into distance driven.
      .WithMechanismDiameter(4_in)
      // kP trims the velocity error that is left after the feedforward.
      .WithFeedback(0.3, 0, 0)
      // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
      .WithMotorGearing(6.75)
      // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
      // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
      .WithFeedforward(Feedforward{0_V, wpi::units::unit_t<Feedforward::kv_unit>{0.85}})
      // Set this to true if the wheel spins backward when it is told to drive forward.
      .WithMotorInverted(false)
      .WithStatorCurrentLimit(40_A)
      .WithTelemetry("driveMotor", Cfg::TelemetryVerbosity::HIGH);
}

void SwerveSubsystem::ConfigureAzimuth(Cfg& config) {
  config
      .WithSubsystem(this)
      // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
      .WithFeedback(4, 0, 0)
      // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
      // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
      .WithContinuousWrapping(-0.5_tr, 0.5_tr)
      // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
      .WithMotorGearing(12.8)
      // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
      .WithMotorInverted(false)
      // The azimuth motor rarely works hard, so it gets a lower limit.
      .WithStatorCurrentLimit(20_A)
      .WithTelemetry("angleMotor", Cfg::TelemetryVerbosity::HIGH);
}

SwerveSubsystem::SwerveSubsystem() {
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
The gains here are a place to start. [Step 4: Tune it](/documentation/tutorials/swerve-drive/tune) practices tuning them in simulation with the swerve tuning command, and [Step 5: On the real robot](/documentation/tutorials/swerve-drive/real-robot) tunes the real modules.
{% endhint %}

## Check it

Build the code: **WPILib: Build Robot Code** from the command palette (<kbd>Ctrl+Shift+P</kbd>). It should end with `BUILD SUCCESSFUL`. Nothing moves yet: the configs are not used until step 2.

If it does not build:

* **A REV or CTRE class cannot be found.** REVLib or Phoenix 6 is not installed. See [Create a project and install YAMS](/documentation/tutorials/project-setup).
* **`Rotations` or `Inches` cannot be found.** An `import static org.wpilib.units.Units...` line is missing. Copy the imports from the complete file.

More fixes are on [Troubleshooting](/documentation/tutorials/troubleshooting).

Next: [Step 2: The modules and the drive](/documentation/tutorials/swerve-drive/modules-and-drive).


# Step 2: The modules and the drive

Build four SwerveModules, add the gyro, and create the SwerveDrive.

Four `SwerveModule`s, a gyro and a `SwerveDriveConfig` make a `SwerveDrive`.

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

{% stepper %}
{% step %}

### Build one module

One helper builds a module from its two `SparkMax`, its `CANcoder`, a name and a location. It wraps each `SparkMax` in a `SmartMotorController` using the configs from step 1, and describes the module with a `SwerveModuleConfig`:

* **`withAbsoluteEncoder`** gives the module the `CANcoder`'s angle, so that it knows which way it points as soon as the robot turns on.
* **`withAbsoluteEncoderOffset`** is the `CANcoder`'s reading when the wheel points straight forward with its bevel gear to the left. Every `CANcoder` is mounted at a different angle, so every module has its own offset. It is a parameter of the helper, and it is 0 until you measure it on the real robot in [Step 5](/documentation/tutorials/swerve-drive/real-robot#set-the-absolute-encoder-offsets). Simulation does not need it.
* **`withLocation`** says where the module is on the robot.
* **`withOptimization(true)`** lets the module reverse its wheel instead of turning more than 90 degrees.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java" %}

```java
/** All four modules share their gearing and gains, so one method builds each of them. */
private SwerveModule createModule(SparkMax drive, SparkMax azimuth, CANcoder absoluteEncoder,
                                  Angle encoderOffset, String moduleName, Translation2d location) {
  SmartMotorController driveMotor = new SparkWrapper(drive, DCMotor.getNEO(1), buildDriveCfg());
  SmartMotorController azimuthMotor = new SparkWrapper(azimuth, DCMotor.getNEO(1), buildAzimuthCfg());

  return new SwerveModule(new SwerveModuleConfig(driveMotor, azimuthMotor)
      // The CANcoder tells the module which way it points when the robot turns on.
      .withAbsoluteEncoder(absoluteEncoder.getAbsolutePosition().asSupplier())
      // The CANcoder's raw reading when the wheel points forward with its bevel gear to the left.
      // Every module has its own. Step 5 measures it on the real robot.
      .withAbsoluteEncoderOffset(encoderOffset)
      .withTelemetry(moduleName, TelemetryVerbosity.HIGH)
      // Where the module is on the robot: +X is forward, +Y is left.
      .withLocation(location)
      // Turn the module at most 90 degrees, reversing the wheel instead of turning further.
      .withOptimization(true));
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java" %}

```java
/** All four modules share their gearing and gains, so one method builds each of them. */
private SwerveModule createModule(SparkMax drive, SparkMax azimuth, CANcoder absoluteEncoder,
                                  Angle encoderOffset, String moduleName, Translation2d location) {
  SmartMotorController driveMotor = new SparkWrapper(drive, DCMotor.getNEO(1), buildDriveCfg());
  SmartMotorController azimuthMotor = new SparkWrapper(azimuth, DCMotor.getNEO(1), buildAzimuthCfg());

  return new SwerveModule(new SwerveModuleConfig(driveMotor, azimuthMotor)
      // The CANcoder tells the module which way it points when the robot turns on.
      .withAbsoluteEncoder(absoluteEncoder.getAbsolutePosition().asSupplier())
      // The CANcoder's raw reading when the wheel points forward with its bevel gear to the left.
      // Every module has its own. Step 5 measures it on the real robot.
      .withAbsoluteEncoderOffset(encoderOffset)
      .withTelemetry(moduleName, TelemetryVerbosity.HIGH)
      // Where the module is on the robot: +X is forward, +Y is left.
      .withLocation(location)
      // Turn the module at most 90 degrees, reversing the wheel instead of turning further.
      .withOptimization(true));
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/SwerveSubsystem.hpp" %}

```cpp
// Everything one module is made of. YAMS keeps pointers to the configs and the
// motor controllers, so they live here, next to the module that uses them.
struct Module {
  Module(int driveId, int azimuthId, int encoderId)
      : drive{wpi::CANPort::CAN_S0, driveId, rev::spark::SparkMax::MotorType::kBrushless},
        azimuth{wpi::CANPort::CAN_S0, azimuthId, rev::spark::SparkMax::MotorType::kBrushless},
        encoder{encoderId, ctre::phoenix6::CANBus{}} {}

  rev::spark::SparkMax drive;
  rev::spark::SparkMax azimuth;
  ctre::phoenix6::hardware::CANcoder encoder;
  yams::motorcontrollers::SmartMotorControllerConfig driveConfig;
  yams::motorcontrollers::SmartMotorControllerConfig azimuthConfig;
  std::optional<yams::motorcontrollers::local::SparkWrapper> driveMotor;
  std::optional<yams::motorcontrollers::local::SparkWrapper> azimuthMotor;
  yams::mechanisms::config::SwerveModuleConfig config;
  std::optional<yams::mechanisms::swerve::SwerveModule> module;
};

/** All four modules share their gearing and gains, so one method sets up each of them. */
void SetupModule(Module& module, const std::string& name, wpi::math::Translation2d location,
                 wpi::units::degree_t encoderOffset);
```

{% endcode %}

{% code title="cpp/subsystems/SwerveSubsystem.cpp" %}

```cpp
void SwerveSubsystem::SetupModule(Module& module, const std::string& name,
                                  wpi::math::Translation2d location,
                                  wpi::units::degree_t encoderOffset) {
  ConfigureDrive(module.driveConfig);
  ConfigureAzimuth(module.azimuthConfig);
  module.driveMotor.emplace(&module.drive, wpi::math::DCMotor::NEO(1), &module.driveConfig);
  module.azimuthMotor.emplace(&module.azimuth, wpi::math::DCMotor::NEO(1), &module.azimuthConfig);

  module.config = SwerveModuleConfig{&module.driveMotor.value(), &module.azimuthMotor.value()};
  module.config
      // The CANcoder tells the module which way it points when the robot turns on.
      .WithAbsoluteEncoder([&module]() -> wpi::units::degree_t {
        return wpi::units::turn_t{module.encoder.GetAbsolutePosition().GetValue()};
      })
      // The CANcoder's raw reading when the wheel points forward with its bevel gear to the left.
      // Every module has its own. Step 5 measures it on the real robot.
      .WithAbsoluteEncoderOffset(encoderOffset)
      .WithTelemetry(name, Cfg::TelemetryVerbosity::HIGH)
      // Where the module is on the robot: +X is forward, +Y is left.
      .WithLocation(location)
      // Turn the module at most 90 degrees, reversing the wheel instead of turning further.
      .WithOptimization(true);

  module.module.emplace(&module.config);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change `DCMotor.getNEO(1)` if your motors are not NEOs. Leave every offset at 0 for now: [Step 5](/documentation/tutorials/swerve-drive/real-robot#set-the-absolute-encoder-offsets) shows how to read each module's offset from the dashboard and put it in. A robot with offsets of 0 drives in simulation, but on the real robot every wheel points a different way.

Want the details? [SwerveModuleConfig](/documentation/reference/mechanism-configs/swerve-module-config)
{% endstep %}

{% step %}

### The gyro, and a place for the drive

The drive needs a gyro for its heading.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java" %}

```java
private final SwerveDrive drive;

// The gyro: a Pigeon2 with CAN ID 14.
private final Pigeon2 gyro = new Pigeon2(14, new CANBus(CANPort.CAN_S0));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java" %}

```java
private final SwerveDrive drive;

// The gyro: a Pigeon2 with CAN ID 14.
private final Pigeon2 gyro = new Pigeon2(14, new CANBus(CANPort.CAN_S0));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/SwerveSubsystem.hpp" %}

```cpp
// The gyro: a Pigeon2 with CAN ID 14.
ctre::phoenix6::hardware::Pigeon2 m_gyro{14, ctre::phoenix6::CANBus{}};

// CAN IDs are grouped by module: drive, azimuth, CANcoder.
Module m_frontLeft{1, 2, 3};
Module m_frontRight{4, 5, 6};
Module m_backLeft{7, 8, 9};
Module m_backRight{10, 11, 12};

yams::mechanisms::swerve::SwerveDriveConfig m_driveConfig;
std::optional<yams::mechanisms::swerve::SwerveDrive<4>> m_drive;
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the CAN ID to your gyro's. In C++ this is also where the four modules get their CAN IDs.
{% endstep %}

{% step %}

### Create the four modules

Locations use WPILib's convention: **+X is toward the front of the robot and +Y is toward its left side**.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-21ed773ea125aee961a5c8a5f965de9813292141%2Fmech-module-location.png?alt=media" alt="A top view of a robot with the center at zero, plus X pointing forward and plus Y pointing left. The front left module is at 0.3, 0.3; front right at 0.3, minus 0.3; back left at minus 0.3, 0.3; back right at minus 0.3, minus 0.3, in meters."><figcaption><p>Module locations: X is forward and Y is left.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java" %}

```java
public SwerveSubsystem() {
  // Each module is 24 inches forward or back and 24 inches left or right of the robot center.
  // CAN IDs are grouped by module: drive, azimuth, CANcoder.
  // Every encoder offset is 0 until Step 5 measures the real ones.
  var frontLeft = createModule(new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless),
                               new SparkMax(CANPort.CAN_S0, 2, MotorType.kBrushless),
                               new CANcoder(3, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontleft",
                               new Translation2d(Inches.of(24), Inches.of(24)));
  var frontRight = createModule(new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless),
                                new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless),
                                new CANcoder(6, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontright",
                                new Translation2d(Inches.of(24), Inches.of(-24)));
  var backLeft = createModule(new SparkMax(CANPort.CAN_S0, 7, MotorType.kBrushless),
                              new SparkMax(CANPort.CAN_S0, 8, MotorType.kBrushless),
                              new CANcoder(9, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backleft",
                              new Translation2d(Inches.of(-24), Inches.of(24)));
  var backRight = createModule(new SparkMax(CANPort.CAN_S0, 10, MotorType.kBrushless),
                               new SparkMax(CANPort.CAN_S0, 11, MotorType.kBrushless),
                               new CANcoder(12, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backright",
                               new Translation2d(Inches.of(-24), Inches.of(-24)));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java" %}

```java
public SwerveMechanism() {
  // Each module is 24 inches forward or back and 24 inches left or right of the robot center.
  // CAN IDs are grouped by module: drive, azimuth, CANcoder.
  // Every encoder offset is 0 until Step 5 measures the real ones.
  var frontLeft = createModule(new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless),
                               new SparkMax(CANPort.CAN_S0, 2, MotorType.kBrushless),
                               new CANcoder(3, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontleft",
                               new Translation2d(Inches.of(24), Inches.of(24)));
  var frontRight = createModule(new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless),
                                new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless),
                                new CANcoder(6, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontright",
                                new Translation2d(Inches.of(24), Inches.of(-24)));
  var backLeft = createModule(new SparkMax(CANPort.CAN_S0, 7, MotorType.kBrushless),
                              new SparkMax(CANPort.CAN_S0, 8, MotorType.kBrushless),
                              new CANcoder(9, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backleft",
                              new Translation2d(Inches.of(-24), Inches.of(24)));
  var backRight = createModule(new SparkMax(CANPort.CAN_S0, 10, MotorType.kBrushless),
                               new SparkMax(CANPort.CAN_S0, 11, MotorType.kBrushless),
                               new CANcoder(12, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backright",
                               new Translation2d(Inches.of(-24), Inches.of(-24)));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/SwerveSubsystem.cpp" %}

```cpp
// Each module is 24 inches forward or back and 24 inches left or right of the robot center.
// Every encoder offset is 0 until Step 5 measures the real ones.
SetupModule(m_frontLeft, "frontleft", wpi::math::Translation2d{24_in, 24_in}, 0_deg);
SetupModule(m_frontRight, "frontright", wpi::math::Translation2d{24_in, -24_in}, 0_deg);
SetupModule(m_backLeft, "backleft", wpi::math::Translation2d{-24_in, 24_in}, 0_deg);
SetupModule(m_backRight, "backright", wpi::math::Translation2d{-24_in, -24_in}, 0_deg);
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the CAN IDs, and change the 24 inches to how far your modules really are from the center of your robot.
{% endstep %}

{% step %}

### Configure and create the drive

`SwerveDriveConfig` takes the four modules, the gyro's attitude, where on the field the robot starts, and the two PID controllers that `driveToPose()` uses in step 3. `withTelemetry("swerve", TelemetryVerbosity.HIGH)` names the drive: everything it publishes is under `NT:/Mechanisms/swerve`, and `HIGH` also publishes the keys that [live tuning](/documentation/how-to-tuning/live-tuning/swerve-drive) uses in Step 4. `swerve` is also the default name, but setting it here makes it easy to find.

The starting pose of `0` degrees means the robot thinks it faces away from the blue driver station when the code starts. For now, always turn the robot on facing away from you: [Step 3](/documentation/tutorials/swerve-drive/driving#what-forward-means) explains why.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-1173a038385c1e461d064705d38501d5f65df7ae%2Fmech-swerve-how.png?alt=media" alt="A flow diagram. You ask for a ChassisVelocities with vx, vy and omega. The kinematics, built from the module locations, turn it into four module states, a speed and an angle each. Odometry combines wheel travel and the gyro into the robot&#x27;s pose, which feeds field relative driving, auto-align and paths."><figcaption><p>From one chassis velocity to four wheels, and back to a pose.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java" %}

```java
  SwerveDriveConfig config = new SwerveDriveConfig(this, frontLeft, frontRight, backLeft, backRight)
      // The gyro's attitude. Its yaw is the heading used for field relative driving.
      .withGyro(gyro::getRotation3d)
      .withStartingPose(new Pose2d(0, 0, Rotation2d.fromDegrees(0)))
      // Used by driveToPose(). A kP of 1 is a careful place to start.
      .withTranslationController(new PIDController(1, 0, 0))
      .withRotationController(new PIDController(1, 0, 0))
      // Publishes under NT:/Mechanisms/swerve. HIGH also publishes the live tuning keys.
      .withTelemetry("swerve", TelemetryVerbosity.HIGH);

  drive = new SwerveDrive(config);
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java" %}

```java
  SwerveDriveConfig config = new SwerveDriveConfig(this, frontLeft, frontRight, backLeft, backRight)
      // The gyro's attitude. Its yaw is the heading used for field relative driving.
      .withGyro(gyro::getRotation3d)
      .withStartingPose(new Pose2d(0, 0, Rotation2d.fromDegrees(0)))
      // Used by driveToPose(). A kP of 1 is a careful place to start.
      .withTranslationController(new PIDController(1, 0, 0))
      .withRotationController(new PIDController(1, 0, 0))
      // Publishes under NT:/Mechanisms/swerve. HIGH also publishes the live tuning keys.
      .withTelemetry("swerve", TelemetryVerbosity.HIGH);

  drive = new SwerveDrive(config);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/SwerveSubsystem.cpp" %}

```cpp
m_driveConfig
    .WithSubsystem(this)
    .WithModules({&m_frontLeft.module.value(), &m_frontRight.module.value(),
                  &m_backLeft.module.value(), &m_backRight.module.value()})
    // The gyro's attitude. Its yaw is the heading used for field relative driving.
    .WithGyro([this]() -> wpi::math::Rotation3d { return m_gyro.GetRotation3d(); })
    .WithStartingPose(wpi::math::Pose2d{})
    // Used by DriveToPose(). A kP of 1 is a careful place to start.
    .WithTranslationController(wpi::math::PIDController{1, 0, 0})
    .WithRotationController(wpi::math::PIDController{1, 0, 0})
    // Publishes under NT:/Mechanisms/swerve. HIGH also publishes the live tuning keys.
    .WithTelemetry("swerve", Cfg::TelemetryVerbosity::HIGH);

m_drive.emplace(&m_driveConfig);
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** The two controllers are only a place to start. Tune them once the robot drives well by hand.

Want the details? [SwerveDriveConfig](/documentation/reference/mechanism-configs/swerve-drive-config)
{% endstep %}

{% step %}

### Update it every loop

`updateTelemetry()` must run every loop: it updates the pose estimate as well as the telemetry. `simIterate()` runs the physics simulation. In simulation the drive takes its heading from the simulated robot, not from the `Pigeon2`, so the line after it is optional: it copies the simulated heading into the `Pigeon2`, for any other code that reads the `Pigeon2` directly.

In Commands v2 and C++ the scheduler calls a subsystem's periodic methods for you, so there is nothing more to do.

In Commands v3 nothing calls a `Mechanism` every loop, so `Robot.java` does it. `Robot.java` has the two functions you need:

* **`robotPeriodic()`** runs every loop, on the robot and in simulation. Call the mechanism's `periodic()` here, before `scheduler.run()`, so that the commands see fresh values.
* **`simulationInit()`** runs once, when the simulation starts. The template does not have it yet, so add it, and start the mechanism's `simulationPeriodic()` here with `startSimulation(...)`, which runs it in its own `Notifier` every loop, in simulation only. That keeps the simulation from adding to the robot loop's time, as [Where the tutorials put things](/documentation/tutorials/project-setup#where-the-tutorials-put-things) explains.

Every mechanism you add to the robot gets one line in each of the two.

Two smaller changes tidy up the template while you are here. Keep `Scheduler.getDefault()` in a `scheduler` attribute instead of asking for it every loop, and publish the scheduler with `Telemetry.log(...)` after it runs, so that a dashboard shows which commands are running and which mechanisms they hold.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java" %}

```java
@Override
public void periodic() {
  // Updates the pose estimate, the telemetry and the drive's Field2d.
  drive.updateTelemetry();
}

@Override
public void simulationPeriodic() {
  // Runs the physics simulation of all eight motors.
  drive.simIterate();
  // Optional: in simulation the drive's heading comes from the simulated robot, not the
  // Pigeon2. This keeps the Pigeon2's own reading in step, for code that reads it directly.
  gyro.getSimState().setRawYaw(drive.getSimPose().getRotation().getMeasure());
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java" %}

```java
/** Call this from Robot.robotPeriodic(), before the scheduler runs. */
public void periodic() {
  // Updates the pose estimate, the telemetry and the drive's Field2d.
  drive.updateTelemetry();
}

/** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
public void simulationPeriodic() {
  // Runs the physics simulation of all eight motors.
  drive.simIterate();
  // Optional: in simulation the drive's heading comes from the simulated robot, not the
  // Pigeon2. This keeps the Pigeon2's own reading in step, for code that reads it directly.
  gyro.getSimState().setRawYaw(drive.getSimPose().getRotation().getMeasure());
}
```

{% endcode %}

{% code title="Robot.java" %}

```java
import java.util.ArrayList;
import java.util.List;
import org.wpilib.system.Notifier;
import org.wpilib.telemetry.Telemetry;
import first.robot.mechanisms.SwerveMechanism;

public class Robot extends OpModeRobot {
  // ...
  final SwerveMechanism drive = new SwerveMechanism();
  // ...

  // The scheduler that runs every command.
  private final Scheduler scheduler = Scheduler.getDefault();
  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
  private final List<Notifier> simulationNotifiers = new ArrayList<>();

  // ...

  @Override
  public void robotPeriodic() {
    // Runs every loop, on the robot and in simulation.
    // Update the mechanism before the scheduler runs its commands.
    drive.periodic();
    scheduler.run();
    // Publish the scheduler, so that a dashboard shows which commands are running.
    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
  }

  @Override
  public void simulationInit() {
    // Runs once, when the simulation starts.
    // Run each mechanism's simulation in its own Notifier, every robot loop.
    startSimulation("Drive", drive::simulationPeriodic);
  }

  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
  private void startSimulation(String name, Runnable simulationPeriodic) {
    Notifier notifier = new Notifier(simulationPeriodic);
    notifier.setName(name + " Simulation");
    notifier.startPeriodic(getPeriod());
    simulationNotifiers.add(notifier);
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/SwerveSubsystem.hpp" %}

```cpp
void Periodic() override;
void SimulationPeriodic() override;
```

{% endcode %}

{% code title="cpp/subsystems/SwerveSubsystem.cpp" %}

```cpp
void SwerveSubsystem::Periodic() {
  // Updates the pose estimate, the telemetry and the drive's Field2d.
  m_drive->UpdateTelemetry();
}

void SwerveSubsystem::SimulationPeriodic() {
  // Runs the physics simulation of all eight motors.
  m_drive->SimIterate();
  // Optional: in simulation the drive's heading comes from the simulated robot, not the
  // Pigeon2. This keeps the Pigeon2's own reading in step, for code that reads it directly.
  m_gyro.GetSimState().SetRawYaw(m_drive->GetSimPose().Rotation().Degrees());
}
```

{% endcode %}
{% endtab %}
{% endtabs %}
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
The highlighted lines are new in this step.

`SwerveSubsystem` extends `SubsystemBase`, so the scheduler calls `periodic()` and `simulationPeriodic()` for you.

<pre class="language-java" data-title="subsystems/SwerveSubsystem.java" data-line-numbers><code class="lang-java">package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
<strong>import static org.wpilib.units.Units.Degrees;
</strong>import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Rotations;

<strong>import com.ctre.phoenix6.CANBus;
</strong><strong>import com.ctre.phoenix6.hardware.CANcoder;
</strong><strong>import com.ctre.phoenix6.hardware.Pigeon2;
</strong><strong>import com.revrobotics.spark.SparkLowLevel.MotorType;
</strong><strong>import com.revrobotics.spark.SparkMax;
</strong>import org.wpilib.command2.SubsystemBase;
<strong>import org.wpilib.hardware.bus.CANPort;
</strong><strong>import org.wpilib.math.controller.PIDController;
</strong>import org.wpilib.math.controller.SimpleMotorFeedforward;
<strong>import org.wpilib.math.geometry.Pose2d;
</strong><strong>import org.wpilib.math.geometry.Rotation2d;
</strong><strong>import org.wpilib.math.geometry.Translation2d;
</strong><strong>import org.wpilib.math.system.DCMotor;
</strong><strong>import org.wpilib.units.measure.Angle;
</strong>import yams.commands2.config.SmartMotorControllerConfig;
<strong>import yams.commands2.config.SwerveDriveConfig;
</strong><strong>import yams.commands2.swerve.SwerveDrive;
</strong>import yams.core.gearing.MechanismGearing;
<strong>import yams.core.mechanisms.config.SwerveModuleConfig;
</strong><strong>import yams.core.mechanisms.swerve.SwerveModule;
</strong><strong>import yams.core.motorcontrollers.SmartMotorController;
</strong><strong>import yams.core.motorcontrollers.local.SparkWrapper;
</strong>import yams.core.telemetry.enums.TelemetryVerbosity;

public class SwerveSubsystem extends SubsystemBase {

<strong>  private final SwerveDrive drive;
</strong>
<strong>  // The gyro: a Pigeon2 with CAN ID 14.
</strong><strong>  private final Pigeon2 gyro = new Pigeon2(14, new CANBus(CANPort.CAN_S0));
</strong>
  /** The config of one drive motor. Drive motors are velocity controlled. */
  private SmartMotorControllerConfig buildDriveCfg() {
    return new SmartMotorControllerConfig(this)
        // The wheel diameter turns wheel rotations into distance driven.
        .withWheelDiameter(Inches.of(4))
        // kP trims the velocity error that is left after the feedforward.
        .withClosedLoopController(0.3, 0, 0)
        // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
        .withGearing(new MechanismGearing(6.75))
        // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
        // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
        .withFeedforward(new SimpleMotorFeedforward(0, 0.85))
        // Set this to true if the wheel spins backward when it is told to drive forward.
        .withMotorInverted(false)
        .withStatorCurrentLimit(Amps.of(40))
        .withTelemetry("driveMotor", TelemetryVerbosity.HIGH);
  }

  /** The config of one azimuth (steering) motor. Azimuth motors are position controlled. */
  private SmartMotorControllerConfig buildAzimuthCfg() {
    return new SmartMotorControllerConfig(this)
        // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
        .withClosedLoopController(4, 0, 0)
        // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
        // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
        .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
        // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
        .withGearing(new MechanismGearing(12.8))
        // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
        .withMotorInverted(false)
        // The azimuth motor rarely works hard, so it gets a lower limit.
        .withStatorCurrentLimit(Amps.of(20))
        .withTelemetry("angleMotor", TelemetryVerbosity.HIGH);
  }

<strong>  /** All four modules share their gearing and gains, so one method builds each of them. */
</strong><strong>  private SwerveModule createModule(SparkMax drive, SparkMax azimuth, CANcoder absoluteEncoder,
</strong><strong>                                    Angle encoderOffset, String moduleName, Translation2d location) {
</strong><strong>    SmartMotorController driveMotor = new SparkWrapper(drive, DCMotor.getNEO(1), buildDriveCfg());
</strong><strong>    SmartMotorController azimuthMotor = new SparkWrapper(azimuth, DCMotor.getNEO(1), buildAzimuthCfg());
</strong>
<strong>    return new SwerveModule(new SwerveModuleConfig(driveMotor, azimuthMotor)
</strong><strong>        // The CANcoder tells the module which way it points when the robot turns on.
</strong><strong>        .withAbsoluteEncoder(absoluteEncoder.getAbsolutePosition().asSupplier())
</strong><strong>        // The CANcoder's raw reading when the wheel points forward with its bevel gear to the left.
</strong><strong>        // Every module has its own. Step 5 measures it on the real robot.
</strong><strong>        .withAbsoluteEncoderOffset(encoderOffset)
</strong><strong>        .withTelemetry(moduleName, TelemetryVerbosity.HIGH)
</strong><strong>        // Where the module is on the robot: +X is forward, +Y is left.
</strong><strong>        .withLocation(location)
</strong><strong>        // Turn the module at most 90 degrees, reversing the wheel instead of turning further.
</strong><strong>        .withOptimization(true));
</strong><strong>  }
</strong>
<strong>  public SwerveSubsystem() {
</strong><strong>    // Each module is 24 inches forward or back and 24 inches left or right of the robot center.
</strong><strong>    // CAN IDs are grouped by module: drive, azimuth, CANcoder.
</strong><strong>    // Every encoder offset is 0 until Step 5 measures the real ones.
</strong><strong>    var frontLeft = createModule(new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless),
</strong><strong>                                 new SparkMax(CANPort.CAN_S0, 2, MotorType.kBrushless),
</strong><strong>                                 new CANcoder(3, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontleft",
</strong><strong>                                 new Translation2d(Inches.of(24), Inches.of(24)));
</strong><strong>    var frontRight = createModule(new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless),
</strong><strong>                                  new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless),
</strong><strong>                                  new CANcoder(6, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontright",
</strong><strong>                                  new Translation2d(Inches.of(24), Inches.of(-24)));
</strong><strong>    var backLeft = createModule(new SparkMax(CANPort.CAN_S0, 7, MotorType.kBrushless),
</strong><strong>                                new SparkMax(CANPort.CAN_S0, 8, MotorType.kBrushless),
</strong><strong>                                new CANcoder(9, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backleft",
</strong><strong>                                new Translation2d(Inches.of(-24), Inches.of(24)));
</strong><strong>    var backRight = createModule(new SparkMax(CANPort.CAN_S0, 10, MotorType.kBrushless),
</strong><strong>                                 new SparkMax(CANPort.CAN_S0, 11, MotorType.kBrushless),
</strong><strong>                                 new CANcoder(12, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backright",
</strong><strong>                                 new Translation2d(Inches.of(-24), Inches.of(-24)));
</strong>
<strong>    SwerveDriveConfig config = new SwerveDriveConfig(this, frontLeft, frontRight, backLeft, backRight)
</strong><strong>        // The gyro's attitude. Its yaw is the heading used for field relative driving.
</strong><strong>        .withGyro(gyro::getRotation3d)
</strong><strong>        .withStartingPose(new Pose2d(0, 0, Rotation2d.fromDegrees(0)))
</strong><strong>        // Used by driveToPose(). A kP of 1 is a careful place to start.
</strong><strong>        .withTranslationController(new PIDController(1, 0, 0))
</strong><strong>        .withRotationController(new PIDController(1, 0, 0))
</strong><strong>        // Publishes under NT:/Mechanisms/swerve. HIGH also publishes the live tuning keys.
</strong><strong>        .withTelemetry("swerve", TelemetryVerbosity.HIGH);
</strong>
<strong>    drive = new SwerveDrive(config);
</strong><strong>  }
</strong>
<strong>  @Override
</strong><strong>  public void periodic() {
</strong><strong>    // Updates the pose estimate, the telemetry and the drive's Field2d.
</strong><strong>    drive.updateTelemetry();
</strong><strong>  }
</strong>
<strong>  @Override
</strong><strong>  public void simulationPeriodic() {
</strong><strong>    // Runs the physics simulation of all eight motors.
</strong><strong>    drive.simIterate();
</strong><strong>    // Optional: in simulation the drive's heading comes from the simulated robot, not the
</strong><strong>    // Pigeon2. This keeps the Pigeon2's own reading in step, for code that reads it directly.
</strong><strong>    gyro.getSimState().setRawYaw(drive.getSimPose().getRotation().getMeasure());
</strong><strong>  }
</strong>}
</code></pre>

{% endtab %}

{% tab title="Java, Commands v3" %}
The highlighted lines are new in this step.

Nothing calls a periodic method on a Commands v3 `Mechanism`, so give the class its own `periodic()` and `simulationPeriodic()` and create the mechanism in `Robot.java`. Then call its `periodic()` from `Robot.robotPeriodic()`, before the scheduler runs, and start its `simulationPeriodic()` in its own `Notifier` from `Robot.simulationInit()`.

<pre class="language-java" data-title="mechanisms/SwerveMechanism.java" data-line-numbers><code class="lang-java">package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
<strong>import static org.wpilib.units.Units.Degrees;
</strong>import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Rotations;

<strong>import com.ctre.phoenix6.CANBus;
</strong><strong>import com.ctre.phoenix6.hardware.CANcoder;
</strong><strong>import com.ctre.phoenix6.hardware.Pigeon2;
</strong><strong>import com.revrobotics.spark.SparkLowLevel.MotorType;
</strong><strong>import com.revrobotics.spark.SparkMax;
</strong>import org.wpilib.command3.Mechanism;
<strong>import org.wpilib.hardware.bus.CANPort;
</strong><strong>import org.wpilib.math.controller.PIDController;
</strong>import org.wpilib.math.controller.SimpleMotorFeedforward;
<strong>import org.wpilib.math.geometry.Pose2d;
</strong><strong>import org.wpilib.math.geometry.Rotation2d;
</strong><strong>import org.wpilib.math.geometry.Translation2d;
</strong><strong>import org.wpilib.math.system.DCMotor;
</strong><strong>import org.wpilib.units.measure.Angle;
</strong>import yams.commands3.config.SmartMotorControllerConfig;
<strong>import yams.commands3.config.SwerveDriveConfig;
</strong><strong>import yams.commands3.swerve.SwerveDrive;
</strong>import yams.core.gearing.MechanismGearing;
<strong>import yams.core.mechanisms.config.SwerveModuleConfig;
</strong><strong>import yams.core.mechanisms.swerve.SwerveModule;
</strong><strong>import yams.core.motorcontrollers.SmartMotorController;
</strong><strong>import yams.core.motorcontrollers.local.SparkWrapper;
</strong>import yams.core.telemetry.enums.TelemetryVerbosity;

public class SwerveMechanism implements Mechanism {

<strong>  private final SwerveDrive drive;
</strong>
<strong>  // The gyro: a Pigeon2 with CAN ID 14.
</strong><strong>  private final Pigeon2 gyro = new Pigeon2(14, new CANBus(CANPort.CAN_S0));
</strong>
  /** The config of one drive motor. Drive motors are velocity controlled. */
  private SmartMotorControllerConfig buildDriveCfg() {
    return new SmartMotorControllerConfig(this)
        // The wheel diameter turns wheel rotations into distance driven.
        .withWheelDiameter(Inches.of(4))
        // kP trims the velocity error that is left after the feedforward.
        .withClosedLoopController(0.3, 0, 0)
        // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
        .withGearing(new MechanismGearing(6.75))
        // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
        // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
        .withFeedforward(new SimpleMotorFeedforward(0, 0.85))
        // Set this to true if the wheel spins backward when it is told to drive forward.
        .withMotorInverted(false)
        .withStatorCurrentLimit(Amps.of(40))
        .withTelemetry("driveMotor", TelemetryVerbosity.HIGH);
  }

  /** The config of one azimuth (steering) motor. Azimuth motors are position controlled. */
  private SmartMotorControllerConfig buildAzimuthCfg() {
    return new SmartMotorControllerConfig(this)
        // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
        .withClosedLoopController(4, 0, 0)
        // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
        // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
        .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
        // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
        .withGearing(new MechanismGearing(12.8))
        // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
        .withMotorInverted(false)
        // The azimuth motor rarely works hard, so it gets a lower limit.
        .withStatorCurrentLimit(Amps.of(20))
        .withTelemetry("angleMotor", TelemetryVerbosity.HIGH);
  }

<strong>  /** All four modules share their gearing and gains, so one method builds each of them. */
</strong><strong>  private SwerveModule createModule(SparkMax drive, SparkMax azimuth, CANcoder absoluteEncoder,
</strong><strong>                                    Angle encoderOffset, String moduleName, Translation2d location) {
</strong><strong>    SmartMotorController driveMotor = new SparkWrapper(drive, DCMotor.getNEO(1), buildDriveCfg());
</strong><strong>    SmartMotorController azimuthMotor = new SparkWrapper(azimuth, DCMotor.getNEO(1), buildAzimuthCfg());
</strong>
<strong>    return new SwerveModule(new SwerveModuleConfig(driveMotor, azimuthMotor)
</strong><strong>        // The CANcoder tells the module which way it points when the robot turns on.
</strong><strong>        .withAbsoluteEncoder(absoluteEncoder.getAbsolutePosition().asSupplier())
</strong><strong>        // The CANcoder's raw reading when the wheel points forward with its bevel gear to the left.
</strong><strong>        // Every module has its own. Step 5 measures it on the real robot.
</strong><strong>        .withAbsoluteEncoderOffset(encoderOffset)
</strong><strong>        .withTelemetry(moduleName, TelemetryVerbosity.HIGH)
</strong><strong>        // Where the module is on the robot: +X is forward, +Y is left.
</strong><strong>        .withLocation(location)
</strong><strong>        // Turn the module at most 90 degrees, reversing the wheel instead of turning further.
</strong><strong>        .withOptimization(true));
</strong><strong>  }
</strong>
<strong>  public SwerveMechanism() {
</strong><strong>    // Each module is 24 inches forward or back and 24 inches left or right of the robot center.
</strong><strong>    // CAN IDs are grouped by module: drive, azimuth, CANcoder.
</strong><strong>    // Every encoder offset is 0 until Step 5 measures the real ones.
</strong><strong>    var frontLeft = createModule(new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless),
</strong><strong>                                 new SparkMax(CANPort.CAN_S0, 2, MotorType.kBrushless),
</strong><strong>                                 new CANcoder(3, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontleft",
</strong><strong>                                 new Translation2d(Inches.of(24), Inches.of(24)));
</strong><strong>    var frontRight = createModule(new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless),
</strong><strong>                                  new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless),
</strong><strong>                                  new CANcoder(6, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontright",
</strong><strong>                                  new Translation2d(Inches.of(24), Inches.of(-24)));
</strong><strong>    var backLeft = createModule(new SparkMax(CANPort.CAN_S0, 7, MotorType.kBrushless),
</strong><strong>                                new SparkMax(CANPort.CAN_S0, 8, MotorType.kBrushless),
</strong><strong>                                new CANcoder(9, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backleft",
</strong><strong>                                new Translation2d(Inches.of(-24), Inches.of(24)));
</strong><strong>    var backRight = createModule(new SparkMax(CANPort.CAN_S0, 10, MotorType.kBrushless),
</strong><strong>                                 new SparkMax(CANPort.CAN_S0, 11, MotorType.kBrushless),
</strong><strong>                                 new CANcoder(12, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backright",
</strong><strong>                                 new Translation2d(Inches.of(-24), Inches.of(-24)));
</strong>
<strong>    SwerveDriveConfig config = new SwerveDriveConfig(this, frontLeft, frontRight, backLeft, backRight)
</strong><strong>        // The gyro's attitude. Its yaw is the heading used for field relative driving.
</strong><strong>        .withGyro(gyro::getRotation3d)
</strong><strong>        .withStartingPose(new Pose2d(0, 0, Rotation2d.fromDegrees(0)))
</strong><strong>        // Used by driveToPose(). A kP of 1 is a careful place to start.
</strong><strong>        .withTranslationController(new PIDController(1, 0, 0))
</strong><strong>        .withRotationController(new PIDController(1, 0, 0))
</strong><strong>        // Publishes under NT:/Mechanisms/swerve. HIGH also publishes the live tuning keys.
</strong><strong>        .withTelemetry("swerve", TelemetryVerbosity.HIGH);
</strong>
<strong>    drive = new SwerveDrive(config);
</strong><strong>  }
</strong>
<strong>  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
</strong><strong>  public void periodic() {
</strong><strong>    // Updates the pose estimate, the telemetry and the drive's Field2d.
</strong><strong>    drive.updateTelemetry();
</strong><strong>  }
</strong>
<strong>  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
</strong><strong>  public void simulationPeriodic() {
</strong><strong>    // Runs the physics simulation of all eight motors.
</strong><strong>    drive.simIterate();
</strong><strong>    // Optional: in simulation the drive's heading comes from the simulated robot, not the
</strong><strong>    // Pigeon2. This keeps the Pigeon2's own reading in step, for code that reads it directly.
</strong><strong>    gyro.getSimState().setRawYaw(drive.getSimPose().getRotation().getMeasure());
</strong><strong>  }
</strong>}
</code></pre>

<pre class="language-java" data-title="Robot.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import java.util.ArrayList;
</strong><strong>import java.util.List;
</strong>import org.wpilib.command3.Scheduler;
import org.wpilib.command3.button.CommandGamepad;
import org.wpilib.framework.OpModeRobot;
<strong>import org.wpilib.system.Notifier;
</strong><strong>import org.wpilib.telemetry.Telemetry;
</strong>import first.robot.constants.DriverConstants;
<strong>import first.robot.mechanisms.SwerveMechanism;
</strong>import first.robot.mechanisms.ExampleMechanism;

public class Robot extends OpModeRobot {
  final ExampleMechanism exampleMechanism = new ExampleMechanism();
<strong>  final SwerveMechanism drive = new SwerveMechanism();
</strong>  final CommandGamepad exampleController =
      new CommandGamepad(DriverConstants.DRIVER_CONTROLLER_PORT);

<strong>  // The scheduler that runs every command.
</strong><strong>  private final Scheduler scheduler = Scheduler.getDefault();
</strong><strong>  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
</strong><strong>  private final List&#x3C;Notifier> simulationNotifiers = new ArrayList&#x3C;>();
</strong>
  public Robot() {}

  @Override
  public void robotPeriodic() {
<strong>    // Runs every loop, on the robot and in simulation.
</strong><strong>    // Update the mechanism before the scheduler runs its commands.
</strong><strong>    drive.periodic();
</strong><strong>    scheduler.run();
</strong><strong>    // Publish the scheduler, so that a dashboard shows which commands are running.
</strong><strong>    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
</strong><strong>  }
</strong>
<strong>  @Override
</strong><strong>  public void simulationInit() {
</strong><strong>    // Runs once, when the simulation starts.
</strong><strong>    // Run each mechanism's simulation in its own Notifier, every robot loop.
</strong><strong>    startSimulation("Drive", drive::simulationPeriodic);
</strong><strong>  }
</strong>
<strong>  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
</strong><strong>  private void startSimulation(String name, Runnable simulationPeriodic) {
</strong><strong>    Notifier notifier = new Notifier(simulationPeriodic);
</strong><strong>    notifier.setName(name + " Simulation");
</strong><strong>    notifier.startPeriodic(getPeriod());
</strong><strong>    simulationNotifiers.add(notifier);
</strong><strong>  }
</strong>}
</code></pre>

{% endtab %}

{% tab title="C++" %}
The highlighted lines are new in this step.

In C++ everything a module is made of has to outlive the module, so a small `Module` struct holds the two `SparkMax`, the `CANcoder`, the two configs, the two `SmartMotorController`s and the `SwerveModule` itself. `SetupModule` fills one in. The `SwerveDrive` is a template on the number of modules: `SwerveDrive<4>`.

<pre class="language-cpp" data-title="include/subsystems/SwerveSubsystem.hpp" data-line-numbers><code class="lang-cpp">#pragma once

<strong>#include &#x3C;optional>
</strong><strong>#include &#x3C;string>
</strong>
<strong>#include &#x3C;ctre/phoenix6/CANcoder.hpp>
</strong><strong>#include &#x3C;ctre/phoenix6/Pigeon2.hpp>
</strong><strong>#include &#x3C;rev/SparkMax.h>
</strong>#include &#x3C;wpi/commands2/SubsystemBase.hpp>
<strong>#include &#x3C;wpi/hardware/bus/CANPort.hpp>
</strong><strong>#include &#x3C;wpi/math/geometry/Translation2d.hpp>
</strong><strong>#include &#x3C;wpi/units/angle.hpp>
</strong>
<strong>#include "yams/mechanisms/config/SwerveModuleConfig.hpp"
</strong><strong>#include "yams/mechanisms/swerve/SwerveDrive.hpp"
</strong><strong>#include "yams/mechanisms/swerve/SwerveDriveConfig.hpp"
</strong><strong>#include "yams/mechanisms/swerve/SwerveModule.hpp"
</strong>#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
<strong>#include "yams/motorcontrollers/local/SparkWrapper.hpp"
</strong>
class SwerveSubsystem : public wpi::cmd::SubsystemBase {
 public:
  SwerveSubsystem();

<strong>  void Periodic() override;
</strong><strong>  void SimulationPeriodic() override;
</strong>
 private:
  /** Fill in the config of one drive motor. Drive motors are velocity controlled. */
  void ConfigureDrive(yams::motorcontrollers::SmartMotorControllerConfig&#x26; config);

  /** Fill in the config of one azimuth (steering) motor. Azimuth motors are position controlled. */
  void ConfigureAzimuth(yams::motorcontrollers::SmartMotorControllerConfig&#x26; config);

<strong>  // Everything one module is made of. YAMS keeps pointers to the configs and the
</strong><strong>  // motor controllers, so they live here, next to the module that uses them.
</strong><strong>  struct Module {
</strong><strong>    Module(int driveId, int azimuthId, int encoderId)
</strong><strong>        : drive{wpi::CANPort::CAN_S0, driveId, rev::spark::SparkMax::MotorType::kBrushless},
</strong><strong>          azimuth{wpi::CANPort::CAN_S0, azimuthId, rev::spark::SparkMax::MotorType::kBrushless},
</strong><strong>          encoder{encoderId, ctre::phoenix6::CANBus{}} {}
</strong>
<strong>    rev::spark::SparkMax drive;
</strong><strong>    rev::spark::SparkMax azimuth;
</strong><strong>    ctre::phoenix6::hardware::CANcoder encoder;
</strong><strong>    yams::motorcontrollers::SmartMotorControllerConfig driveConfig;
</strong><strong>    yams::motorcontrollers::SmartMotorControllerConfig azimuthConfig;
</strong><strong>    std::optional&#x3C;yams::motorcontrollers::local::SparkWrapper> driveMotor;
</strong><strong>    std::optional&#x3C;yams::motorcontrollers::local::SparkWrapper> azimuthMotor;
</strong><strong>    yams::mechanisms::config::SwerveModuleConfig config;
</strong><strong>    std::optional&#x3C;yams::mechanisms::swerve::SwerveModule> module;
</strong><strong>  };
</strong>
<strong>  /** All four modules share their gearing and gains, so one method sets up each of them. */
</strong><strong>  void SetupModule(Module&#x26; module, const std::string&#x26; name, wpi::math::Translation2d location,
</strong><strong>                   wpi::units::degree_t encoderOffset);
</strong>
<strong>  // The gyro: a Pigeon2 with CAN ID 14.
</strong><strong>  ctre::phoenix6::hardware::Pigeon2 m_gyro{14, ctre::phoenix6::CANBus{}};
</strong>
<strong>  // CAN IDs are grouped by module: drive, azimuth, CANcoder.
</strong><strong>  Module m_frontLeft{1, 2, 3};
</strong><strong>  Module m_frontRight{4, 5, 6};
</strong><strong>  Module m_backLeft{7, 8, 9};
</strong><strong>  Module m_backRight{10, 11, 12};
</strong>
<strong>  yams::mechanisms::swerve::SwerveDriveConfig m_driveConfig;
</strong><strong>  std::optional&#x3C;yams::mechanisms::swerve::SwerveDrive&#x3C;4>> m_drive;
</strong>};
</code></pre>

<pre class="language-cpp" data-title="cpp/subsystems/SwerveSubsystem.cpp" data-line-numbers><code class="lang-cpp">#include "subsystems/SwerveSubsystem.hpp"

<strong>#include &#x3C;wpi/math/controller/PIDController.hpp>
</strong>#include &#x3C;wpi/math/controller/SimpleMotorFeedforward.hpp>
<strong>#include &#x3C;wpi/math/geometry/Rotation3d.hpp>
</strong><strong>#include &#x3C;wpi/math/system/DCMotor.hpp>
</strong>#include &#x3C;wpi/units/angle.hpp>
#include &#x3C;wpi/units/current.hpp>
#include &#x3C;wpi/units/length.hpp>
#include &#x3C;wpi/units/voltage.hpp>

<strong>using namespace yams::mechanisms::config;
</strong><strong>using namespace yams::mechanisms::swerve;
</strong>using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;
using Feedforward = wpi::math::SimpleMotorFeedforward&#x3C;wpi::units::turns>;

void SwerveSubsystem::ConfigureDrive(Cfg&#x26; config) {
  config
      .WithSubsystem(this)
      // The wheel diameter turns wheel rotations into distance driven.
      .WithMechanismDiameter(4_in)
      // kP trims the velocity error that is left after the feedforward.
      .WithFeedback(0.3, 0, 0)
      // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
      .WithMotorGearing(6.75)
      // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
      // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
      .WithFeedforward(Feedforward{0_V, wpi::units::unit_t&#x3C;Feedforward::kv_unit>{0.85}})
      // Set this to true if the wheel spins backward when it is told to drive forward.
      .WithMotorInverted(false)
      .WithStatorCurrentLimit(40_A)
      .WithTelemetry("driveMotor", Cfg::TelemetryVerbosity::HIGH);
}

void SwerveSubsystem::ConfigureAzimuth(Cfg&#x26; config) {
  config
      .WithSubsystem(this)
      // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
      .WithFeedback(4, 0, 0)
      // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
      // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
      .WithContinuousWrapping(-0.5_tr, 0.5_tr)
      // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
      .WithMotorGearing(12.8)
      // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
      .WithMotorInverted(false)
      // The azimuth motor rarely works hard, so it gets a lower limit.
      .WithStatorCurrentLimit(20_A)
      .WithTelemetry("angleMotor", Cfg::TelemetryVerbosity::HIGH);
}

<strong>void SwerveSubsystem::SetupModule(Module&#x26; module, const std::string&#x26; name,
</strong><strong>                                  wpi::math::Translation2d location,
</strong><strong>                                  wpi::units::degree_t encoderOffset) {
</strong><strong>  ConfigureDrive(module.driveConfig);
</strong><strong>  ConfigureAzimuth(module.azimuthConfig);
</strong><strong>  module.driveMotor.emplace(&#x26;module.drive, wpi::math::DCMotor::NEO(1), &#x26;module.driveConfig);
</strong><strong>  module.azimuthMotor.emplace(&#x26;module.azimuth, wpi::math::DCMotor::NEO(1), &#x26;module.azimuthConfig);
</strong>
<strong>  module.config = SwerveModuleConfig{&#x26;module.driveMotor.value(), &#x26;module.azimuthMotor.value()};
</strong><strong>  module.config
</strong><strong>      // The CANcoder tells the module which way it points when the robot turns on.
</strong><strong>      .WithAbsoluteEncoder([&#x26;module]() -> wpi::units::degree_t {
</strong><strong>        return wpi::units::turn_t{module.encoder.GetAbsolutePosition().GetValue()};
</strong><strong>      })
</strong><strong>      // The CANcoder's raw reading when the wheel points forward with its bevel gear to the left.
</strong><strong>      // Every module has its own. Step 5 measures it on the real robot.
</strong><strong>      .WithAbsoluteEncoderOffset(encoderOffset)
</strong><strong>      .WithTelemetry(name, Cfg::TelemetryVerbosity::HIGH)
</strong><strong>      // Where the module is on the robot: +X is forward, +Y is left.
</strong><strong>      .WithLocation(location)
</strong><strong>      // Turn the module at most 90 degrees, reversing the wheel instead of turning further.
</strong><strong>      .WithOptimization(true);
</strong>
<strong>  module.module.emplace(&#x26;module.config);
</strong><strong>}
</strong>
SwerveSubsystem::SwerveSubsystem() {
<strong>  // Each module is 24 inches forward or back and 24 inches left or right of the robot center.
</strong><strong>  // Every encoder offset is 0 until Step 5 measures the real ones.
</strong><strong>  SetupModule(m_frontLeft, "frontleft", wpi::math::Translation2d{24_in, 24_in}, 0_deg);
</strong><strong>  SetupModule(m_frontRight, "frontright", wpi::math::Translation2d{24_in, -24_in}, 0_deg);
</strong><strong>  SetupModule(m_backLeft, "backleft", wpi::math::Translation2d{-24_in, 24_in}, 0_deg);
</strong><strong>  SetupModule(m_backRight, "backright", wpi::math::Translation2d{-24_in, -24_in}, 0_deg);
</strong>
<strong>  m_driveConfig
</strong><strong>      .WithSubsystem(this)
</strong><strong>      .WithModules({&#x26;m_frontLeft.module.value(), &#x26;m_frontRight.module.value(),
</strong><strong>                    &#x26;m_backLeft.module.value(), &#x26;m_backRight.module.value()})
</strong><strong>      // The gyro's attitude. Its yaw is the heading used for field relative driving.
</strong><strong>      .WithGyro([this]() -> wpi::math::Rotation3d { return m_gyro.GetRotation3d(); })
</strong><strong>      .WithStartingPose(wpi::math::Pose2d{})
</strong><strong>      // Used by DriveToPose(). A kP of 1 is a careful place to start.
</strong><strong>      .WithTranslationController(wpi::math::PIDController{1, 0, 0})
</strong><strong>      .WithRotationController(wpi::math::PIDController{1, 0, 0})
</strong><strong>      // Publishes under NT:/Mechanisms/swerve. HIGH also publishes the live tuning keys.
</strong><strong>      .WithTelemetry("swerve", Cfg::TelemetryVerbosity::HIGH);
</strong>
<strong>  m_drive.emplace(&#x26;m_driveConfig);
</strong>}

<strong>void SwerveSubsystem::Periodic() {
</strong><strong>  // Updates the pose estimate, the telemetry and the drive's Field2d.
</strong><strong>  m_drive->UpdateTelemetry();
</strong><strong>}
</strong>
<strong>void SwerveSubsystem::SimulationPeriodic() {
</strong><strong>  // Runs the physics simulation of all eight motors.
</strong><strong>  m_drive->SimIterate();
</strong><strong>  // Optional: in simulation the drive's heading comes from the simulated robot, not the
</strong><strong>  // Pigeon2. This keeps the Pigeon2's own reading in step, for code that reads it directly.
</strong><strong>  m_gyro.GetSimState().SetRawYaw(m_drive->GetSimPose().Rotation().Degrees());
</strong><strong>}
</strong></code></pre>

{% endtab %}
{% endtabs %}

{% hint style="info" %}
If your gyro is mounted so that the robot turning shows up as its roll or pitch instead of its yaw, add `.withGyroHeadingAxis(GyroAxis.ROLL)` or `.withGyroHeadingAxis(GyroAxis.PITCH)` to the `SwerveDriveConfig`. The default is `GyroAxis.YAW`. See [How do I use a gyro mounted on its side?](/documentation/how-to-motor-controllers-and-sensors/how-do-i-use-a-gyro-mounted-on-its-side).
{% endhint %}

{% hint style="info" %}
`SwerveDrive` builds and publishes its own `Field2d` and updates it in `updateTelemetry()`, so do not create another one. Call `drive.getField2d()` when vision or autonomous code needs to plot extra objects onto the same widget.
{% endhint %}

## Check it

Nothing drives yet, but the drive already runs in simulation.

1. Run **WPILib: Simulate Robot Code** from the command palette (<kbd>Ctrl+Shift+P</kbd>). If you are asked which extensions to run, tick **Sim GUI**.
2. Open AdvantageScope and choose **File > Connect to Simulator**.
3. Open a **2D Field** tab and drag `NT:/Mechanisms/swerve/pose` onto it. That is the same pose `drive.getField2d()` shows, which is published at `NT:/Mechanisms/swerve/field` for a dashboard such as Elastic.
4. Open a **Swerve** tab and drag `NT:/Mechanisms/swerve/states/current` onto it.

**What you should see:** the robot sits at (0, 0) in the corner of the field, facing away from the blue alliance wall, and the Swerve tab shows four modules with no speed.

**If not:**

* **Nothing is under `NT:/Mechanisms/swerve`.** `updateTelemetry()` is not running. Commands v2 and C++: check `periodic()`. Commands v3: check that `Robot.robotPeriodic()` calls `drive.periodic()`.
* **The code stops at startup with `SwerveModuleConfig must have a telemetry name!` or `must have a position!`.** A module is missing `withTelemetry(...)` or `withLocation(...)`. Copy the helper from the complete file.

More fixes are on [Troubleshooting](/documentation/tutorials/troubleshooting).

Next: [Step 3: Driving](/documentation/tutorials/swerve-drive/driving).

## Read more

[Swerve Drive](/documentation/understanding/swerve-drive), [SwerveDriveConfig](/documentation/reference/mechanism-configs/swerve-drive-config), [Swerve Module](/documentation/understanding/swerve-drive/swerve-module) and [SwerveModuleConfig](/documentation/reference/mechanism-configs/swerve-module-config) cover everything the drive and its modules can do.


# Step 3: Driving

Drive commands, a SwerveInputStream for the sticks, and the bindings.

`SwerveDrive` takes a chassis speed (forward, sideways and rotation) and sets all four modules for you.

Four things are added in this step:

* **A drive command**, `driveFieldRelative`, that gives the drive field relative chassis speeds every loop.
* **A `SwerveInputStream`**, which turns the raw stick values into field relative chassis speeds, with the deadband and the cubing already applied.
* **`driveToPose(pose)`**, which uses the two PID controllers from step 2 to drive to a pose on the field.
* **`zeroGyro()`**, a button that makes the way the robot faces now its "forward".

{% hint style="success" %}
**In a hurry?** Jump to [the complete file](#the-complete-file), copy it, and change the values called out under **For your robot**. The numbered parts explain each piece in a sentence or two. You do not need to understand all of it to get moving: the pages under **Understanding** go deeper when you want them.
{% endhint %}

{% stepper %}
{% step %}

### Read the sticks, and drive with them

A `SwerveInputStream` turns the raw stick values into field relative chassis speeds, with the deadband and the cubing already applied. A drive command gives those speeds to the drive every loop.

The command is called `driveFieldRelative`, not `drive`, on purpose: `SwerveDrive` has its own `drive(...)` command, and that one takes **robot** relative speeds.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-3ee61c10559baa352ec85e34e455187fc161cfd6%2Fswerve-input-stream-sticks.gif?alt=media" alt="Animation of two controller sticks, the ChassisVelocities they produce, and a robot on a field. Left stick forward gives positive vx and the robot moves away from the driver station. Left stick left gives positive vy and the robot moves left. A diagonal push gives both. Right stick left gives a positive omega and the robot turns counter-clockwise"><figcaption><p>How each stick movement becomes a field relative velocity.</p></figcaption></figure>

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java" %}

```java
/** Drive with field relative chassis speeds. */
public Command driveFieldRelative(Supplier<ChassisVelocities> speedsSupplier) {
  return run(() -> drive.setFieldRelativeChassisSpeeds(speedsSupplier.get()))
      .withName("Field Oriented Drive");
}

/** Turn three controller axes into field relative chassis speeds. */
public SwerveInputStream getChassisSpeedsSupplier(DoubleSupplier translationX, DoubleSupplier translationY,
                                                  DoubleSupplier rotation) {
  return SwerveInputStream.of(drive, translationX, translationY)
      .withControllerRotationAxis(rotation)
      // What a full stick means. 1 m/s is slow on purpose, for the first drives.
      .withMaximumLinearVelocity(MetersPerSecond.of(1))
      .withMaximumAngularVelocity(DegreesPerSecond.of(360))
      // Ignore a stick that is barely off center.
      .withDeadband(0.05)
      // Cube the sticks, for finer control at low speed.
      .withCubeTranslationControllerAxis()
      .withCubeRotationControllerAxis()
      // Publish the stream's inputs and outputs, and allow live tuning of it.
      .withTelemetry("Driver", TelemetryVerbosity.HIGH);
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java" %}

```java
/** Drive with field relative chassis speeds. */
public Command driveFieldRelative(Supplier<ChassisVelocities> speedsSupplier) {
  return run(coroutine -> {
    while (true) {
      drive.setFieldRelativeChassisSpeeds(speedsSupplier.get());
      coroutine.yield();
    }
  }).named("Field Oriented Drive");
}

/** Turn three controller axes into field relative chassis speeds. */
public SwerveInputStream getChassisSpeedsSupplier(DoubleSupplier translationX, DoubleSupplier translationY,
                                                  DoubleSupplier rotation) {
  return SwerveInputStream.of(drive, translationX, translationY)
      .withControllerRotationAxis(rotation)
      // What a full stick means. 1 m/s is slow on purpose, for the first drives.
      .withMaximumLinearVelocity(MetersPerSecond.of(1))
      .withMaximumAngularVelocity(DegreesPerSecond.of(360))
      // Ignore a stick that is barely off center.
      .withDeadband(0.05)
      // Cube the sticks, for finer control at low speed.
      .withCubeTranslationControllerAxis()
      .withCubeRotationControllerAxis()
      // Publish the stream's inputs and outputs, and allow live tuning of it.
      .withTelemetry("Driver", TelemetryVerbosity.HIGH);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/SwerveSubsystem.hpp" %}

```cpp
/** Drive field relative from three controller axes. */
wpi::cmd::CommandPtr DriveWithSticks(std::function<double()> translationX,
                                     std::function<double()> translationY,
                                     std::function<double()> rotation);

// Turns the controller axes into field relative chassis speeds.
std::optional<yams::mechanisms::swerve::utility::SwerveInputStream<4>> m_inputStream;
```

{% endcode %}

{% code title="cpp/subsystems/SwerveSubsystem.cpp" %}

```cpp
wpi::cmd::CommandPtr SwerveSubsystem::DriveWithSticks(std::function<double()> translationX,
                                                      std::function<double()> translationY,
                                                      std::function<double()> rotation) {
  m_inputStream.emplace(
      utility::SwerveInputStream<4>::Of(m_drive.value(), translationX, translationY)
          .WithControllerRotationAxis(rotation)
          // What a full stick means. 1 m/s is slow on purpose, for the first drives.
          .WithMaximumLinearVelocity(1_mps)
          .WithMaximumAngularVelocity(360_deg_per_s)
          // Ignore a stick that is barely off center.
          .WithDeadband(0.05)
          // Cube the sticks, for finer control at low speed.
          .WithCubeTranslationControllerAxis()
          .WithCubeRotationControllerAxis()
          // Publish the stream's inputs and outputs, and allow live tuning of it.
          .WithTelemetry("Driver", Cfg::TelemetryVerbosity::HIGH));

  return Run([this] { m_drive->SetFieldRelativeChassisSpeeds(m_inputStream->Get()); })
      .WithName("Field Oriented Drive");
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Set the two maximum velocities to what a full stick should mean on your robot. Keep 1 m/s until the robot has driven on the ground in [Step 5](/documentation/tutorials/swerve-drive/real-robot), then raise it.

Want the details? [Swerve Input Stream](/documentation/reference/swerve-input-stream)

#### What forward means

Field relative means pushing the stick forward drives the robot **away from the driver station**, whichever way the robot itself faces. To know which way that is, the drive uses the gyro: a heading of 0 degrees is "facing away from the driver station".

The gyro starts at 0 when the code starts, and step 2 set the starting pose to 0 degrees too. So the drive assumes the robot faces away from you when it turns on. Two habits keep that true:

* **Turn the robot on facing away from the driver station.**
* **Press the zero gyro button** (bound in part 3) with the robot facing away from you, whenever forward on the stick stops matching forward on the field. That happens after the robot is turned on facing another way, or after the gyro drifts.

{% hint style="info" %}
This tutorial leaves out `withAllianceRelativeControl()`. It flips the sticks 180 degrees on the red alliance, which is only right when the robot's pose is a real field pose: on red, a robot facing away from its driver station has a heading of 180 degrees, not 0. Add it once your autonomous routine or vision sets the real pose. See [Alliance-relative control](/documentation/reference/swerve-input-stream#alliance-relative-control).
{% endhint %}
{% endstep %}

{% step %}

### Drive to a pose, lock the wheels and zero the gyro

`driveToPose(pose)` uses the two PID controllers from step 2 to drive to a pose on the field. `lock()` turns every module toward the robot center, the X pattern, and holds it there. `zeroGyro()` makes the way the robot faces now the new 0 degrees, so forward on the stick drives the way the robot faced when you pressed it.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java" %}

```java
/** Drive to a pose on the field. */
public Command driveToPose(Pose2d pose) {
  return drive.driveToPose(pose);
}

/** Turn the wheels into an X, which resists being pushed. */
public Command lock() {
  return run(drive::lockPose);
}

/** Make the way the robot faces now "forward" for field relative driving. */
public Command zeroGyro() {
  return runOnce(drive::zeroGyro).withName("Zero Gyro");
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java" %}

```java
/** Drive to a pose on the field. */
public Command driveToPose(Pose2d pose) {
  return drive.driveToPose(pose);
}

/** Turn the wheels into an X, which resists being pushed. */
public Command lock() {
  return run(coroutine -> {
    while (true) {
      drive.lockPose();
      coroutine.yield();
    }
  }).named("Swerve Lock");
}

/** Make the way the robot faces now "forward" for field relative driving. */
public Command zeroGyro() {
  return run(coroutine -> {
    drive.zeroGyro();
  }).named("Zero Gyro");
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/SwerveSubsystem.hpp" %}

```cpp
/** Drive to a pose on the field. */
wpi::cmd::CommandPtr DriveToPose(wpi::math::Pose2d pose);

/** Turn the wheels into an X, which resists being pushed. */
wpi::cmd::CommandPtr Lock();

/** Make the way the robot faces now "forward" for field relative driving. */
wpi::cmd::CommandPtr ZeroGyro();
```

{% endcode %}

{% code title="cpp/subsystems/SwerveSubsystem.cpp" %}

```cpp
wpi::cmd::CommandPtr SwerveSubsystem::DriveToPose(wpi::math::Pose2d pose) {
  return m_drive->DriveToPose(pose);
}

wpi::cmd::CommandPtr SwerveSubsystem::Lock() {
  return Run([this] { m_drive->LockPose(); });
}

wpi::cmd::CommandPtr SwerveSubsystem::ZeroGyro() {
  return RunOnce([this] { m_drive->ZeroGyro(); });
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

Want the details? [Auto-align](/documentation/understanding/swerve-drive#auto-align)
{% endstep %}

{% step %}

### Create it, set the default command and bind a button

Pushing a stick forward or to the left reads **negative** on a controller, so each axis is negated to match WPILib's convention: +X forward, +Y left, and counterclockwise positive.

{% tabs %}
{% tab title="Java, Commands v2" %}
These are three fragments of `RobotContainer.java`. [The complete file](#the-complete-file) shows where each goes, with its imports.

{% code title="RobotContainer.java: a field, next to the other subsystems" %}

```java
private final SwerveSubsystem drive = new SwerveSubsystem();
```

{% endcode %}

{% code title="RobotContainer.java: in the constructor, RobotContainer()" %}

```java
// The left stick translates and the right stick's X axis rotates.
// Pushing a stick forward or left reads negative, so negate each axis to match
// WPILib's convention: +X forward, +Y left, counterclockwise positive.
drive.setDefaultCommand(drive.driveFieldRelative(
    drive.getChassisSpeedsSupplier(
        () -> -driverController.getLeftY(),
        () -> -driverController.getLeftX(),
        () -> -driverController.getRightX())));
```

{% endcode %}

{% code title="RobotContainer.java: in configureBindings()" %}

```java
// Drive to a pose on the field while the left bumper is held.
driverController.leftBumper().whileTrue(drive.driveToPose(
    new Pose2d(Meters.of(3), Meters.of(3), Rotation2d.fromDegrees(30))));

// Press the top face button to make the way the robot faces now "forward".
driverController.faceUp().onTrue(drive.zeroGyro());
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="ExampleTeleop.java: in the constructor, ExampleTeleop(Robot robot)" %}

```java
// The left stick translates and the right stick's X axis rotates.
// Pushing a stick forward or left reads negative, so negate each axis to match
// WPILib's convention: +X forward, +Y left, counterclockwise positive.
robot.drive.setDefaultCommand(robot.drive.driveFieldRelative(
    robot.drive.getChassisSpeedsSupplier(
        () -> -robot.exampleController.getLeftY(),
        () -> -robot.exampleController.getLeftX(),
        () -> -robot.exampleController.getRightX())));

// Drive to a pose on the field while the left bumper is held.
robot.exampleController.leftBumper().whileTrue(robot.drive.driveToPose(
    new Pose2d(Meters.of(3), Meters.of(3), Rotation2d.fromDegrees(30))));

// Press the top face button to make the way the robot faces now "forward".
robot.exampleController.faceUp().onTrue(robot.drive.zeroGyro());
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="include/RobotContainer.hpp: a member, next to the other subsystems" %}

```cpp
SwerveSubsystem drive;
```

{% endcode %}

{% code title="cpp/RobotContainer.cpp: in the constructor, RobotContainer::RobotContainer()" %}

```cpp
// The left stick translates and the right stick's X axis rotates.
// Pushing a stick forward or left reads negative, so negate each axis to match
// WPILib's convention: +X forward, +Y left, counterclockwise positive.
drive.SetDefaultCommand(drive.DriveWithSticks(
    [this] { return -driverController.GetLeftY(); },
    [this] { return -driverController.GetLeftX(); },
    [this] { return -driverController.GetRightX(); }));
```

{% endcode %}

{% code title="cpp/RobotContainer.cpp: in ConfigureBindings()" %}

```cpp
// Drive to a pose on the field while the left bumper is held.
driverController.LeftBumper().WhileTrue(
    drive.DriveToPose(wpi::math::Pose2d{3_m, 3_m, wpi::math::Rotation2d{30_deg}}));

// Press the top face button to make the way the robot faces now "forward".
driverController.FaceUp().OnTrue(drive.ZeroGyro());
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For your robot:** Change the pose to somewhere useful on your field, and bind `lock()` to a button if you want it. The zero gyro button can be any button the driver will not press by accident.
{% endstep %}
{% endstepper %}

## The complete file

{% tabs %}
{% tab title="Java, Commands v2" %}
The highlighted lines are new in this step.

Add the commands and the input stream to `SwerveSubsystem.java`, then create the subsystem, set its default command and bind the left bumper and the zero gyro button in `RobotContainer.java`. The default command goes in the constructor, and the two buttons go in `configureBindings()`.

<pre class="language-java" data-title="subsystems/SwerveSubsystem.java" data-line-numbers><code class="lang-java">package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Degrees;
<strong>import static org.wpilib.units.Units.DegreesPerSecond;
</strong>import static org.wpilib.units.Units.Inches;
<strong>import static org.wpilib.units.Units.MetersPerSecond;
</strong>import static org.wpilib.units.Units.Rotations;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.CANcoder;
import com.ctre.phoenix6.hardware.Pigeon2;
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
<strong>import java.util.function.DoubleSupplier;
</strong><strong>import java.util.function.Supplier;
</strong><strong>import org.wpilib.command2.Command;
</strong>import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.PIDController;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.geometry.Pose2d;
import org.wpilib.math.geometry.Rotation2d;
import org.wpilib.math.geometry.Translation2d;
<strong>import org.wpilib.math.kinematics.ChassisVelocities;
</strong>import org.wpilib.math.system.DCMotor;
import org.wpilib.units.measure.Angle;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.config.SwerveDriveConfig;
import yams.commands2.swerve.SwerveDrive;
<strong>import yams.commands2.swerve.SwerveInputStream;
</strong>import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.SwerveModuleConfig;
import yams.core.mechanisms.swerve.SwerveModule;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class SwerveSubsystem extends SubsystemBase {

  private final SwerveDrive drive;

  // The gyro: a Pigeon2 with CAN ID 14.
  private final Pigeon2 gyro = new Pigeon2(14, new CANBus(CANPort.CAN_S0));

  /** The config of one drive motor. Drive motors are velocity controlled. */
  private SmartMotorControllerConfig buildDriveCfg() {
    return new SmartMotorControllerConfig(this)
        // The wheel diameter turns wheel rotations into distance driven.
        .withWheelDiameter(Inches.of(4))
        // kP trims the velocity error that is left after the feedforward.
        .withClosedLoopController(0.3, 0, 0)
        // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
        .withGearing(new MechanismGearing(6.75))
        // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
        // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
        .withFeedforward(new SimpleMotorFeedforward(0, 0.85))
        // Set this to true if the wheel spins backward when it is told to drive forward.
        .withMotorInverted(false)
        .withStatorCurrentLimit(Amps.of(40))
        .withTelemetry("driveMotor", TelemetryVerbosity.HIGH);
  }

  /** The config of one azimuth (steering) motor. Azimuth motors are position controlled. */
  private SmartMotorControllerConfig buildAzimuthCfg() {
    return new SmartMotorControllerConfig(this)
        // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
        .withClosedLoopController(4, 0, 0)
        // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
        // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
        .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
        // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
        .withGearing(new MechanismGearing(12.8))
        // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
        .withMotorInverted(false)
        // The azimuth motor rarely works hard, so it gets a lower limit.
        .withStatorCurrentLimit(Amps.of(20))
        .withTelemetry("angleMotor", TelemetryVerbosity.HIGH);
  }

  /** All four modules share their gearing and gains, so one method builds each of them. */
  private SwerveModule createModule(SparkMax drive, SparkMax azimuth, CANcoder absoluteEncoder,
                                    Angle encoderOffset, String moduleName, Translation2d location) {
    SmartMotorController driveMotor = new SparkWrapper(drive, DCMotor.getNEO(1), buildDriveCfg());
    SmartMotorController azimuthMotor = new SparkWrapper(azimuth, DCMotor.getNEO(1), buildAzimuthCfg());

    return new SwerveModule(new SwerveModuleConfig(driveMotor, azimuthMotor)
        // The CANcoder tells the module which way it points when the robot turns on.
        .withAbsoluteEncoder(absoluteEncoder.getAbsolutePosition().asSupplier())
        // The CANcoder's raw reading when the wheel points forward with its bevel gear to the left.
        // Every module has its own. Step 5 measures it on the real robot.
        .withAbsoluteEncoderOffset(encoderOffset)
        .withTelemetry(moduleName, TelemetryVerbosity.HIGH)
        // Where the module is on the robot: +X is forward, +Y is left.
        .withLocation(location)
        // Turn the module at most 90 degrees, reversing the wheel instead of turning further.
        .withOptimization(true));
  }

  public SwerveSubsystem() {
    // Each module is 24 inches forward or back and 24 inches left or right of the robot center.
    // CAN IDs are grouped by module: drive, azimuth, CANcoder.
    // Every encoder offset is 0 until Step 5 measures the real ones.
    var frontLeft = createModule(new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless),
                                 new SparkMax(CANPort.CAN_S0, 2, MotorType.kBrushless),
                                 new CANcoder(3, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontleft",
                                 new Translation2d(Inches.of(24), Inches.of(24)));
    var frontRight = createModule(new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless),
                                  new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless),
                                  new CANcoder(6, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontright",
                                  new Translation2d(Inches.of(24), Inches.of(-24)));
    var backLeft = createModule(new SparkMax(CANPort.CAN_S0, 7, MotorType.kBrushless),
                                new SparkMax(CANPort.CAN_S0, 8, MotorType.kBrushless),
                                new CANcoder(9, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backleft",
                                new Translation2d(Inches.of(-24), Inches.of(24)));
    var backRight = createModule(new SparkMax(CANPort.CAN_S0, 10, MotorType.kBrushless),
                                 new SparkMax(CANPort.CAN_S0, 11, MotorType.kBrushless),
                                 new CANcoder(12, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backright",
                                 new Translation2d(Inches.of(-24), Inches.of(-24)));

    SwerveDriveConfig config = new SwerveDriveConfig(this, frontLeft, frontRight, backLeft, backRight)
        // The gyro's attitude. Its yaw is the heading used for field relative driving.
        .withGyro(gyro::getRotation3d)
        .withStartingPose(new Pose2d(0, 0, Rotation2d.fromDegrees(0)))
        // Used by driveToPose(). A kP of 1 is a careful place to start.
        .withTranslationController(new PIDController(1, 0, 0))
        .withRotationController(new PIDController(1, 0, 0))
        // Publishes under NT:/Mechanisms/swerve. HIGH also publishes the live tuning keys.
        .withTelemetry("swerve", TelemetryVerbosity.HIGH);

    drive = new SwerveDrive(config);
  }

<strong>  /** Drive with field relative chassis speeds. */
</strong><strong>  public Command driveFieldRelative(Supplier&#x3C;ChassisVelocities> speedsSupplier) {
</strong><strong>    return run(() -> drive.setFieldRelativeChassisSpeeds(speedsSupplier.get()))
</strong><strong>        .withName("Field Oriented Drive");
</strong><strong>  }
</strong>
<strong>  /** Drive to a pose on the field. */
</strong><strong>  public Command driveToPose(Pose2d pose) {
</strong><strong>    return drive.driveToPose(pose);
</strong><strong>  }
</strong>
<strong>  /** Turn the wheels into an X, which resists being pushed. */
</strong><strong>  public Command lock() {
</strong><strong>    return run(drive::lockPose);
</strong><strong>  }
</strong>
<strong>  /** Make the way the robot faces now "forward" for field relative driving. */
</strong><strong>  public Command zeroGyro() {
</strong><strong>    return runOnce(drive::zeroGyro).withName("Zero Gyro");
</strong><strong>  }
</strong>
<strong>  /** Turn three controller axes into field relative chassis speeds. */
</strong><strong>  public SwerveInputStream getChassisSpeedsSupplier(DoubleSupplier translationX, DoubleSupplier translationY,
</strong><strong>                                                    DoubleSupplier rotation) {
</strong><strong>    return SwerveInputStream.of(drive, translationX, translationY)
</strong><strong>        .withControllerRotationAxis(rotation)
</strong><strong>        // What a full stick means. 1 m/s is slow on purpose, for the first drives.
</strong><strong>        .withMaximumLinearVelocity(MetersPerSecond.of(1))
</strong><strong>        .withMaximumAngularVelocity(DegreesPerSecond.of(360))
</strong><strong>        // Ignore a stick that is barely off center.
</strong><strong>        .withDeadband(0.05)
</strong><strong>        // Cube the sticks, for finer control at low speed.
</strong><strong>        .withCubeTranslationControllerAxis()
</strong><strong>        .withCubeRotationControllerAxis()
</strong><strong>        // Publish the stream's inputs and outputs, and allow live tuning of it.
</strong><strong>        .withTelemetry("Driver", TelemetryVerbosity.HIGH);
</strong><strong>  }
</strong>
  @Override
  public void periodic() {
    // Updates the pose estimate, the telemetry and the drive's Field2d.
    drive.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    // Runs the physics simulation of all eight motors.
    drive.simIterate();
    // Optional: in simulation the drive's heading comes from the simulated robot, not the
    // Pigeon2. This keeps the Pigeon2's own reading in step, for code that reads it directly.
    gyro.getSimState().setRawYaw(drive.getSimPose().getRotation().getMeasure());
  }
}
</code></pre>

<pre class="language-java" data-title="RobotContainer.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.Meters;
</strong>
import org.wpilib.command2.Command;
import org.wpilib.command2.button.CommandGamepad;
import org.wpilib.command2.button.Trigger;
<strong>import org.wpilib.math.geometry.Pose2d;
</strong><strong>import org.wpilib.math.geometry.Rotation2d;
</strong>import first.robot.Constants.OperatorConstants;
import first.robot.commands.Autos;
import first.robot.commands.ExampleCommand;
<strong>import first.robot.subsystems.SwerveSubsystem;
</strong>import first.robot.subsystems.ExampleSubsystem;

/**
 * This class is where the bulk of the robot should be declared. Since Command-based is a
 * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
 * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
 * subsystems, commands, and trigger mappings) should be declared here.
 */
public class RobotContainer {
  // The robot's subsystems and commands are defined here...
  private final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
<strong>  private final SwerveSubsystem drive = new SwerveSubsystem();
</strong>
  private final CommandGamepad driverController =
      new CommandGamepad(OperatorConstants.DRIVER_CONTROLLER_PORT);

  /** The container for the robot. Contains subsystems, OI devices, and commands. */
  public RobotContainer() {
    // Configure the trigger bindings
    configureBindings();

<strong>    // The left stick translates and the right stick's X axis rotates.
</strong><strong>    // Pushing a stick forward or left reads negative, so negate each axis to match
</strong><strong>    // WPILib's convention: +X forward, +Y left, counterclockwise positive.
</strong><strong>    drive.setDefaultCommand(drive.driveFieldRelative(
</strong><strong>        drive.getChassisSpeedsSupplier(
</strong><strong>            () -> -driverController.getLeftY(),
</strong><strong>            () -> -driverController.getLeftX(),
</strong><strong>            () -> -driverController.getRightX())));
</strong>  }

  /**
   * Use this method to define your trigger->command mappings. Triggers can be created via the
   * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary
   * predicate, or via the named factories in {@link org.wpilib.command2.button.CommandGenericHID}'s
   * subclasses for {@link CommandGamepad Gamepad} gamepads or {@link
   * org.wpilib.command2.button.CommandJoystick Flight joysticks}.
   */
  private void configureBindings() {
    // Schedule `ExampleCommand` when `exampleCondition` changes to `true`
    new Trigger(exampleSubsystem::exampleCondition).onTrue(new ExampleCommand(exampleSubsystem));

    // Schedule `exampleMethodCommand` when the Gamepad's right face button is pressed,
    // cancelling on release.
    driverController.faceRight().whileTrue(exampleSubsystem.exampleMethodCommand());

<strong>    // Drive to a pose on the field while the left bumper is held.
</strong><strong>    driverController.leftBumper().whileTrue(drive.driveToPose(
</strong><strong>        new Pose2d(Meters.of(3), Meters.of(3), Rotation2d.fromDegrees(30))));
</strong>
<strong>    // Press the top face button to make the way the robot faces now "forward".
</strong><strong>    driverController.faceUp().onTrue(drive.zeroGyro());
</strong>  }

  /**
   * Use this to pass the autonomous command to the main {@link Robot} class.
   *
   * @return the command to run in autonomous
   */
  public Command getAutonomousCommand() {
    // An example command will be run in autonomous
    return Autos.exampleAuto(exampleSubsystem);
  }
}
</code></pre>

{% endtab %}

{% tab title="Java, Commands v3" %}
The highlighted lines are new in this step.

Add the commands and the input stream to `SwerveMechanism.java`, then set the default command and bind the left bumper and the zero gyro button in `ExampleTeleop.java`. Setting the drive's default command in the teleop op mode means an autonomous op mode never reads the sticks.

`SwerveInputStream` comes from `yams.commands3.swerve`.

<pre class="language-java" data-title="mechanisms/SwerveMechanism.java" data-line-numbers><code class="lang-java">package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Degrees;
<strong>import static org.wpilib.units.Units.DegreesPerSecond;
</strong>import static org.wpilib.units.Units.Inches;
<strong>import static org.wpilib.units.Units.MetersPerSecond;
</strong>import static org.wpilib.units.Units.Rotations;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.CANcoder;
import com.ctre.phoenix6.hardware.Pigeon2;
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
<strong>import java.util.function.DoubleSupplier;
</strong><strong>import java.util.function.Supplier;
</strong><strong>import org.wpilib.command3.Command;
</strong>import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.PIDController;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.geometry.Pose2d;
import org.wpilib.math.geometry.Rotation2d;
import org.wpilib.math.geometry.Translation2d;
<strong>import org.wpilib.math.kinematics.ChassisVelocities;
</strong>import org.wpilib.math.system.DCMotor;
import org.wpilib.units.measure.Angle;
import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.config.SwerveDriveConfig;
import yams.commands3.swerve.SwerveDrive;
<strong>import yams.commands3.swerve.SwerveInputStream;
</strong>import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.SwerveModuleConfig;
import yams.core.mechanisms.swerve.SwerveModule;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class SwerveMechanism implements Mechanism {

  private final SwerveDrive drive;

  // The gyro: a Pigeon2 with CAN ID 14.
  private final Pigeon2 gyro = new Pigeon2(14, new CANBus(CANPort.CAN_S0));

  /** The config of one drive motor. Drive motors are velocity controlled. */
  private SmartMotorControllerConfig buildDriveCfg() {
    return new SmartMotorControllerConfig(this)
        // The wheel diameter turns wheel rotations into distance driven.
        .withWheelDiameter(Inches.of(4))
        // kP trims the velocity error that is left after the feedforward.
        .withClosedLoopController(0.3, 0, 0)
        // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
        .withGearing(new MechanismGearing(6.75))
        // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
        // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
        .withFeedforward(new SimpleMotorFeedforward(0, 0.85))
        // Set this to true if the wheel spins backward when it is told to drive forward.
        .withMotorInverted(false)
        .withStatorCurrentLimit(Amps.of(40))
        .withTelemetry("driveMotor", TelemetryVerbosity.HIGH);
  }

  /** The config of one azimuth (steering) motor. Azimuth motors are position controlled. */
  private SmartMotorControllerConfig buildAzimuthCfg() {
    return new SmartMotorControllerConfig(this)
        // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
        .withClosedLoopController(4, 0, 0)
        // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
        // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
        .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
        // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
        .withGearing(new MechanismGearing(12.8))
        // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
        .withMotorInverted(false)
        // The azimuth motor rarely works hard, so it gets a lower limit.
        .withStatorCurrentLimit(Amps.of(20))
        .withTelemetry("angleMotor", TelemetryVerbosity.HIGH);
  }

  /** All four modules share their gearing and gains, so one method builds each of them. */
  private SwerveModule createModule(SparkMax drive, SparkMax azimuth, CANcoder absoluteEncoder,
                                    Angle encoderOffset, String moduleName, Translation2d location) {
    SmartMotorController driveMotor = new SparkWrapper(drive, DCMotor.getNEO(1), buildDriveCfg());
    SmartMotorController azimuthMotor = new SparkWrapper(azimuth, DCMotor.getNEO(1), buildAzimuthCfg());

    return new SwerveModule(new SwerveModuleConfig(driveMotor, azimuthMotor)
        // The CANcoder tells the module which way it points when the robot turns on.
        .withAbsoluteEncoder(absoluteEncoder.getAbsolutePosition().asSupplier())
        // The CANcoder's raw reading when the wheel points forward with its bevel gear to the left.
        // Every module has its own. Step 5 measures it on the real robot.
        .withAbsoluteEncoderOffset(encoderOffset)
        .withTelemetry(moduleName, TelemetryVerbosity.HIGH)
        // Where the module is on the robot: +X is forward, +Y is left.
        .withLocation(location)
        // Turn the module at most 90 degrees, reversing the wheel instead of turning further.
        .withOptimization(true));
  }

  public SwerveMechanism() {
    // Each module is 24 inches forward or back and 24 inches left or right of the robot center.
    // CAN IDs are grouped by module: drive, azimuth, CANcoder.
    // Every encoder offset is 0 until Step 5 measures the real ones.
    var frontLeft = createModule(new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless),
                                 new SparkMax(CANPort.CAN_S0, 2, MotorType.kBrushless),
                                 new CANcoder(3, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontleft",
                                 new Translation2d(Inches.of(24), Inches.of(24)));
    var frontRight = createModule(new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless),
                                  new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless),
                                  new CANcoder(6, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "frontright",
                                  new Translation2d(Inches.of(24), Inches.of(-24)));
    var backLeft = createModule(new SparkMax(CANPort.CAN_S0, 7, MotorType.kBrushless),
                                new SparkMax(CANPort.CAN_S0, 8, MotorType.kBrushless),
                                new CANcoder(9, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backleft",
                                new Translation2d(Inches.of(-24), Inches.of(24)));
    var backRight = createModule(new SparkMax(CANPort.CAN_S0, 10, MotorType.kBrushless),
                                 new SparkMax(CANPort.CAN_S0, 11, MotorType.kBrushless),
                                 new CANcoder(12, new CANBus(CANPort.CAN_S0)), Degrees.of(0), "backright",
                                 new Translation2d(Inches.of(-24), Inches.of(-24)));

    SwerveDriveConfig config = new SwerveDriveConfig(this, frontLeft, frontRight, backLeft, backRight)
        // The gyro's attitude. Its yaw is the heading used for field relative driving.
        .withGyro(gyro::getRotation3d)
        .withStartingPose(new Pose2d(0, 0, Rotation2d.fromDegrees(0)))
        // Used by driveToPose(). A kP of 1 is a careful place to start.
        .withTranslationController(new PIDController(1, 0, 0))
        .withRotationController(new PIDController(1, 0, 0))
        // Publishes under NT:/Mechanisms/swerve. HIGH also publishes the live tuning keys.
        .withTelemetry("swerve", TelemetryVerbosity.HIGH);

    drive = new SwerveDrive(config);
  }

<strong>  /** Drive with field relative chassis speeds. */
</strong><strong>  public Command driveFieldRelative(Supplier&#x3C;ChassisVelocities> speedsSupplier) {
</strong><strong>    return run(coroutine -> {
</strong><strong>      while (true) {
</strong><strong>        drive.setFieldRelativeChassisSpeeds(speedsSupplier.get());
</strong><strong>        coroutine.yield();
</strong><strong>      }
</strong><strong>    }).named("Field Oriented Drive");
</strong><strong>  }
</strong>
<strong>  /** Drive to a pose on the field. */
</strong><strong>  public Command driveToPose(Pose2d pose) {
</strong><strong>    return drive.driveToPose(pose);
</strong><strong>  }
</strong>
<strong>  /** Turn the wheels into an X, which resists being pushed. */
</strong><strong>  public Command lock() {
</strong><strong>    return run(coroutine -> {
</strong><strong>      while (true) {
</strong><strong>        drive.lockPose();
</strong><strong>        coroutine.yield();
</strong><strong>      }
</strong><strong>    }).named("Swerve Lock");
</strong><strong>  }
</strong>
<strong>  /** Make the way the robot faces now "forward" for field relative driving. */
</strong><strong>  public Command zeroGyro() {
</strong><strong>    return run(coroutine -> {
</strong><strong>      drive.zeroGyro();
</strong><strong>    }).named("Zero Gyro");
</strong><strong>  }
</strong>
<strong>  /** Turn three controller axes into field relative chassis speeds. */
</strong><strong>  public SwerveInputStream getChassisSpeedsSupplier(DoubleSupplier translationX, DoubleSupplier translationY,
</strong><strong>                                                    DoubleSupplier rotation) {
</strong><strong>    return SwerveInputStream.of(drive, translationX, translationY)
</strong><strong>        .withControllerRotationAxis(rotation)
</strong><strong>        // What a full stick means. 1 m/s is slow on purpose, for the first drives.
</strong><strong>        .withMaximumLinearVelocity(MetersPerSecond.of(1))
</strong><strong>        .withMaximumAngularVelocity(DegreesPerSecond.of(360))
</strong><strong>        // Ignore a stick that is barely off center.
</strong><strong>        .withDeadband(0.05)
</strong><strong>        // Cube the sticks, for finer control at low speed.
</strong><strong>        .withCubeTranslationControllerAxis()
</strong><strong>        .withCubeRotationControllerAxis()
</strong><strong>        // Publish the stream's inputs and outputs, and allow live tuning of it.
</strong><strong>        .withTelemetry("Driver", TelemetryVerbosity.HIGH);
</strong><strong>  }
</strong>
  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
  public void periodic() {
    // Updates the pose estimate, the telemetry and the drive's Field2d.
    drive.updateTelemetry();
  }

  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
  public void simulationPeriodic() {
    // Runs the physics simulation of all eight motors.
    drive.simIterate();
    // Optional: in simulation the drive's heading comes from the simulated robot, not the
    // Pigeon2. This keeps the Pigeon2's own reading in step, for code that reads it directly.
    gyro.getSimState().setRawYaw(drive.getSimPose().getRotation().getMeasure());
  }
}
</code></pre>

<pre class="language-java" data-title="ExampleTeleop.java" data-line-numbers><code class="lang-java">package first.robot;

<strong>import static org.wpilib.units.Units.Meters;
</strong>
<strong>import org.wpilib.math.geometry.Pose2d;
</strong><strong>import org.wpilib.math.geometry.Rotation2d;
</strong>import org.wpilib.opmode.OpMode;
import org.wpilib.opmode.Teleop;

@Teleop
public class ExampleTeleop implements OpMode {
  public ExampleTeleop(Robot robot) {
    robot.exampleController.rightStick().whileTrue(robot.exampleMechanism.exampleCommand());

<strong>    // The left stick translates and the right stick's X axis rotates.
</strong><strong>    // Pushing a stick forward or left reads negative, so negate each axis to match
</strong><strong>    // WPILib's convention: +X forward, +Y left, counterclockwise positive.
</strong><strong>    robot.drive.setDefaultCommand(robot.drive.driveFieldRelative(
</strong><strong>        robot.drive.getChassisSpeedsSupplier(
</strong><strong>            () -> -robot.exampleController.getLeftY(),
</strong><strong>            () -> -robot.exampleController.getLeftX(),
</strong><strong>            () -> -robot.exampleController.getRightX())));
</strong>
<strong>    // Drive to a pose on the field while the left bumper is held.
</strong><strong>    robot.exampleController.leftBumper().whileTrue(robot.drive.driveToPose(
</strong><strong>        new Pose2d(Meters.of(3), Meters.of(3), Rotation2d.fromDegrees(30))));
</strong>
<strong>    // Press the top face button to make the way the robot faces now "forward".
</strong><strong>    robot.exampleController.faceUp().onTrue(robot.drive.zeroGyro());
</strong>  }
}
</code></pre>

{% endtab %}

{% tab title="C++" %}
The highlighted lines are new in this step.

In C++ the subsystem owns the `SwerveInputStream`, because the drive command reads it every loop. `DriveWithSticks` builds the stream from three functions that read the controller and returns the command that drives with it.

<pre class="language-cpp" data-title="include/subsystems/SwerveSubsystem.hpp" data-line-numbers><code class="lang-cpp">#pragma once

<strong>#include &#x3C;functional>
</strong>#include &#x3C;optional>
#include &#x3C;string>

#include &#x3C;ctre/phoenix6/CANcoder.hpp>
#include &#x3C;ctre/phoenix6/Pigeon2.hpp>
#include &#x3C;rev/SparkMax.h>
<strong>#include &#x3C;wpi/commands2/CommandPtr.hpp>
</strong>#include &#x3C;wpi/commands2/SubsystemBase.hpp>
#include &#x3C;wpi/hardware/bus/CANPort.hpp>
<strong>#include &#x3C;wpi/math/geometry/Pose2d.hpp>
</strong>#include &#x3C;wpi/math/geometry/Translation2d.hpp>
#include &#x3C;wpi/units/angle.hpp>

#include "yams/mechanisms/config/SwerveModuleConfig.hpp"
#include "yams/mechanisms/swerve/SwerveDrive.hpp"
#include "yams/mechanisms/swerve/SwerveDriveConfig.hpp"
#include "yams/mechanisms/swerve/SwerveModule.hpp"
<strong>#include "yams/mechanisms/swerve/utility/SwerveInputStream.hpp"
</strong>#include "yams/motorcontrollers/SmartMotorControllerConfig.hpp"
#include "yams/motorcontrollers/local/SparkWrapper.hpp"

class SwerveSubsystem : public wpi::cmd::SubsystemBase {
 public:
  SwerveSubsystem();

<strong>  /** Drive field relative from three controller axes. */
</strong><strong>  wpi::cmd::CommandPtr DriveWithSticks(std::function&#x3C;double()> translationX,
</strong><strong>                                       std::function&#x3C;double()> translationY,
</strong><strong>                                       std::function&#x3C;double()> rotation);
</strong>
<strong>  /** Drive to a pose on the field. */
</strong><strong>  wpi::cmd::CommandPtr DriveToPose(wpi::math::Pose2d pose);
</strong>
<strong>  /** Turn the wheels into an X, which resists being pushed. */
</strong><strong>  wpi::cmd::CommandPtr Lock();
</strong>
<strong>  /** Make the way the robot faces now "forward" for field relative driving. */
</strong><strong>  wpi::cmd::CommandPtr ZeroGyro();
</strong>
  void Periodic() override;
  void SimulationPeriodic() override;

 private:
  /** Fill in the config of one drive motor. Drive motors are velocity controlled. */
  void ConfigureDrive(yams::motorcontrollers::SmartMotorControllerConfig&#x26; config);

  /** Fill in the config of one azimuth (steering) motor. Azimuth motors are position controlled. */
  void ConfigureAzimuth(yams::motorcontrollers::SmartMotorControllerConfig&#x26; config);

  // Everything one module is made of. YAMS keeps pointers to the configs and the
  // motor controllers, so they live here, next to the module that uses them.
  struct Module {
    Module(int driveId, int azimuthId, int encoderId)
        : drive{wpi::CANPort::CAN_S0, driveId, rev::spark::SparkMax::MotorType::kBrushless},
          azimuth{wpi::CANPort::CAN_S0, azimuthId, rev::spark::SparkMax::MotorType::kBrushless},
          encoder{encoderId, ctre::phoenix6::CANBus{}} {}

    rev::spark::SparkMax drive;
    rev::spark::SparkMax azimuth;
    ctre::phoenix6::hardware::CANcoder encoder;
    yams::motorcontrollers::SmartMotorControllerConfig driveConfig;
    yams::motorcontrollers::SmartMotorControllerConfig azimuthConfig;
    std::optional&#x3C;yams::motorcontrollers::local::SparkWrapper> driveMotor;
    std::optional&#x3C;yams::motorcontrollers::local::SparkWrapper> azimuthMotor;
    yams::mechanisms::config::SwerveModuleConfig config;
    std::optional&#x3C;yams::mechanisms::swerve::SwerveModule> module;
  };

  /** All four modules share their gearing and gains, so one method sets up each of them. */
  void SetupModule(Module&#x26; module, const std::string&#x26; name, wpi::math::Translation2d location,
                   wpi::units::degree_t encoderOffset);

  // The gyro: a Pigeon2 with CAN ID 14.
  ctre::phoenix6::hardware::Pigeon2 m_gyro{14, ctre::phoenix6::CANBus{}};

  // CAN IDs are grouped by module: drive, azimuth, CANcoder.
  Module m_frontLeft{1, 2, 3};
  Module m_frontRight{4, 5, 6};
  Module m_backLeft{7, 8, 9};
  Module m_backRight{10, 11, 12};

  yams::mechanisms::swerve::SwerveDriveConfig m_driveConfig;
  std::optional&#x3C;yams::mechanisms::swerve::SwerveDrive&#x3C;4>> m_drive;

<strong>  // Turns the controller axes into field relative chassis speeds.
</strong><strong>  std::optional&#x3C;yams::mechanisms::swerve::utility::SwerveInputStream&#x3C;4>> m_inputStream;
</strong>};
</code></pre>

<pre class="language-cpp" data-title="cpp/subsystems/SwerveSubsystem.cpp" data-line-numbers><code class="lang-cpp">#include "subsystems/SwerveSubsystem.hpp"

#include &#x3C;wpi/math/controller/PIDController.hpp>
#include &#x3C;wpi/math/controller/SimpleMotorFeedforward.hpp>
#include &#x3C;wpi/math/geometry/Rotation3d.hpp>
#include &#x3C;wpi/math/system/DCMotor.hpp>
#include &#x3C;wpi/units/angle.hpp>
<strong>#include &#x3C;wpi/units/angular_velocity.hpp>
</strong>#include &#x3C;wpi/units/current.hpp>
#include &#x3C;wpi/units/length.hpp>
<strong>#include &#x3C;wpi/units/velocity.hpp>
</strong>#include &#x3C;wpi/units/voltage.hpp>

using namespace yams::mechanisms::config;
using namespace yams::mechanisms::swerve;
using Cfg = yams::motorcontrollers::SmartMotorControllerConfig;
using Feedforward = wpi::math::SimpleMotorFeedforward&#x3C;wpi::units::turns>;

void SwerveSubsystem::ConfigureDrive(Cfg&#x26; config) {
  config
      .WithSubsystem(this)
      // The wheel diameter turns wheel rotations into distance driven.
      .WithMechanismDiameter(4_in)
      // kP trims the velocity error that is left after the feedforward.
      .WithFeedback(0.3, 0, 0)
      // Gearing from the motor rotor to the wheel: 6.75:1, an MK4 L2 module.
      .WithMotorGearing(6.75)
      // kV, in volts per wheel rotation per second, does most of the work of holding a speed.
      // 0.85 is a placeholder, about right for a NEO on 6.75:1. Step 4 tunes it.
      .WithFeedforward(Feedforward{0_V, wpi::units::unit_t&#x3C;Feedforward::kv_unit>{0.85}})
      // Set this to true if the wheel spins backward when it is told to drive forward.
      .WithMotorInverted(false)
      .WithStatorCurrentLimit(40_A)
      .WithTelemetry("driveMotor", Cfg::TelemetryVerbosity::HIGH);
}

void SwerveSubsystem::ConfigureAzimuth(Cfg&#x26; config) {
  config
      .WithSubsystem(this)
      // kP, in volts per rotation of angle error. A placeholder: Step 4 tunes it.
      .WithFeedback(4, 0, 0)
      // The wheel turns all the way round, so -180 and +180 degrees are the same angle.
      // Without this, a wheel at 170 degrees asked for -170 turns the long way round.
      .WithContinuousWrapping(-0.5_tr, 0.5_tr)
      // Gearing from the motor rotor to the module's steering axis: 12.8:1, an MK4 module.
      .WithMotorGearing(12.8)
      // Set this to true if the wheel turns clockwise, seen from above, when told to turn counter-clockwise.
      .WithMotorInverted(false)
      // The azimuth motor rarely works hard, so it gets a lower limit.
      .WithStatorCurrentLimit(20_A)
      .WithTelemetry("angleMotor", Cfg::TelemetryVerbosity::HIGH);
}

void SwerveSubsystem::SetupModule(Module&#x26; module, const std::string&#x26; name,
                                  wpi::math::Translation2d location,
                                  wpi::units::degree_t encoderOffset) {
  ConfigureDrive(module.driveConfig);
  ConfigureAzimuth(module.azimuthConfig);
  module.driveMotor.emplace(&#x26;module.drive, wpi::math::DCMotor::NEO(1), &#x26;module.driveConfig);
  module.azimuthMotor.emplace(&#x26;module.azimuth, wpi::math::DCMotor::NEO(1), &#x26;module.azimuthConfig);

  module.config = SwerveModuleConfig{&#x26;module.driveMotor.value(), &#x26;module.azimuthMotor.value()};
  module.config
      // The CANcoder tells the module which way it points when the robot turns on.
      .WithAbsoluteEncoder([&#x26;module]() -> wpi::units::degree_t {
        return wpi::units::turn_t{module.encoder.GetAbsolutePosition().GetValue()};
      })
      // The CANcoder's raw reading when the wheel points forward with its bevel gear to the left.
      // Every module has its own. Step 5 measures it on the real robot.
      .WithAbsoluteEncoderOffset(encoderOffset)
      .WithTelemetry(name, Cfg::TelemetryVerbosity::HIGH)
      // Where the module is on the robot: +X is forward, +Y is left.
      .WithLocation(location)
      // Turn the module at most 90 degrees, reversing the wheel instead of turning further.
      .WithOptimization(true);

  module.module.emplace(&#x26;module.config);
}

SwerveSubsystem::SwerveSubsystem() {
  // Each module is 24 inches forward or back and 24 inches left or right of the robot center.
  // Every encoder offset is 0 until Step 5 measures the real ones.
  SetupModule(m_frontLeft, "frontleft", wpi::math::Translation2d{24_in, 24_in}, 0_deg);
  SetupModule(m_frontRight, "frontright", wpi::math::Translation2d{24_in, -24_in}, 0_deg);
  SetupModule(m_backLeft, "backleft", wpi::math::Translation2d{-24_in, 24_in}, 0_deg);
  SetupModule(m_backRight, "backright", wpi::math::Translation2d{-24_in, -24_in}, 0_deg);

  m_driveConfig
      .WithSubsystem(this)
      .WithModules({&#x26;m_frontLeft.module.value(), &#x26;m_frontRight.module.value(),
                    &#x26;m_backLeft.module.value(), &#x26;m_backRight.module.value()})
      // The gyro's attitude. Its yaw is the heading used for field relative driving.
      .WithGyro([this]() -> wpi::math::Rotation3d { return m_gyro.GetRotation3d(); })
      .WithStartingPose(wpi::math::Pose2d{})
      // Used by DriveToPose(). A kP of 1 is a careful place to start.
      .WithTranslationController(wpi::math::PIDController{1, 0, 0})
      .WithRotationController(wpi::math::PIDController{1, 0, 0})
      // Publishes under NT:/Mechanisms/swerve. HIGH also publishes the live tuning keys.
      .WithTelemetry("swerve", Cfg::TelemetryVerbosity::HIGH);

  m_drive.emplace(&#x26;m_driveConfig);
}

<strong>wpi::cmd::CommandPtr SwerveSubsystem::DriveWithSticks(std::function&#x3C;double()> translationX,
</strong><strong>                                                      std::function&#x3C;double()> translationY,
</strong><strong>                                                      std::function&#x3C;double()> rotation) {
</strong><strong>  m_inputStream.emplace(
</strong><strong>      utility::SwerveInputStream&#x3C;4>::Of(m_drive.value(), translationX, translationY)
</strong><strong>          .WithControllerRotationAxis(rotation)
</strong><strong>          // What a full stick means. 1 m/s is slow on purpose, for the first drives.
</strong><strong>          .WithMaximumLinearVelocity(1_mps)
</strong><strong>          .WithMaximumAngularVelocity(360_deg_per_s)
</strong><strong>          // Ignore a stick that is barely off center.
</strong><strong>          .WithDeadband(0.05)
</strong><strong>          // Cube the sticks, for finer control at low speed.
</strong><strong>          .WithCubeTranslationControllerAxis()
</strong><strong>          .WithCubeRotationControllerAxis()
</strong><strong>          // Publish the stream's inputs and outputs, and allow live tuning of it.
</strong><strong>          .WithTelemetry("Driver", Cfg::TelemetryVerbosity::HIGH));
</strong>
<strong>  return Run([this] { m_drive->SetFieldRelativeChassisSpeeds(m_inputStream->Get()); })
</strong><strong>      .WithName("Field Oriented Drive");
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr SwerveSubsystem::DriveToPose(wpi::math::Pose2d pose) {
</strong><strong>  return m_drive->DriveToPose(pose);
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr SwerveSubsystem::Lock() {
</strong><strong>  return Run([this] { m_drive->LockPose(); });
</strong><strong>}
</strong>
<strong>wpi::cmd::CommandPtr SwerveSubsystem::ZeroGyro() {
</strong><strong>  return RunOnce([this] { m_drive->ZeroGyro(); });
</strong><strong>}
</strong>
void SwerveSubsystem::Periodic() {
  // Updates the pose estimate, the telemetry and the drive's Field2d.
  m_drive->UpdateTelemetry();
}

void SwerveSubsystem::SimulationPeriodic() {
  // Runs the physics simulation of all eight motors.
  m_drive->SimIterate();
  // Optional: in simulation the drive's heading comes from the simulated robot, not the
  // Pigeon2. This keeps the Pigeon2's own reading in step, for code that reads it directly.
  m_gyro.GetSimState().SetRawYaw(m_drive->GetSimPose().Rotation().Degrees());
}
</code></pre>

<pre class="language-cpp" data-title="include/RobotContainer.hpp" data-line-numbers><code class="lang-cpp">#pragma once

#include "Constants.hpp"
<strong>#include "subsystems/SwerveSubsystem.hpp"
</strong>#include "subsystems/ExampleSubsystem.hpp"
#include "wpi/commands2/CommandPtr.hpp"
#include "wpi/commands2/button/CommandGamepad.hpp"

/**
 * This class is where the bulk of the robot should be declared.  Since
 * Command-based is a "declarative" paradigm, very little robot logic should
 * actually be handled in the {@link Robot} periodic methods (other than the
 * scheduler calls).  Instead, the structure of the robot (including subsystems,
 * commands, and trigger mappings) should be declared here.
 */
class RobotContainer {
 public:
  RobotContainer();

  wpi::cmd::CommandPtr GetAutonomousCommand();

 private:
  // Replace with CommandPS4Controller or CommandJoystick if needed
  wpi::cmd::CommandGamepad driverController{
      OperatorConstants::DRIVER_CONTROLLER_PORT};

  // The robot's subsystems are defined here...
  ExampleSubsystem subsystem;
<strong>  SwerveSubsystem drive;
</strong>
  void ConfigureBindings();
};
</code></pre>

<pre class="language-cpp" data-title="cpp/RobotContainer.cpp" data-line-numbers><code class="lang-cpp">#include "RobotContainer.hpp"

#include "commands/Autos.hpp"
#include "commands/ExampleCommand.hpp"
#include "wpi/commands2/button/Trigger.hpp"
<strong>#include "wpi/math/geometry/Pose2d.hpp"
</strong><strong>#include "wpi/math/geometry/Rotation2d.hpp"
</strong><strong>#include "wpi/units/angle.hpp"
</strong><strong>#include "wpi/units/length.hpp"
</strong>
RobotContainer::RobotContainer() {
  // Initialize all of your commands and subsystems here

<strong>  // The left stick translates and the right stick's X axis rotates.
</strong><strong>  // Pushing a stick forward or left reads negative, so negate each axis to match
</strong><strong>  // WPILib's convention: +X forward, +Y left, counterclockwise positive.
</strong><strong>  drive.SetDefaultCommand(drive.DriveWithSticks(
</strong><strong>      [this] { return -driverController.GetLeftY(); },
</strong><strong>      [this] { return -driverController.GetLeftX(); },
</strong><strong>      [this] { return -driverController.GetRightX(); }));
</strong>
  // Configure the button bindings
  ConfigureBindings();
}

void RobotContainer::ConfigureBindings() {
  // Configure your trigger bindings here

  // Schedule `ExampleCommand` when `exampleCondition` changes to `true`
  wpi::cmd::Trigger([this] {
    return subsystem.ExampleCondition();
  }).OnTrue(ExampleCommand(&#x26;subsystem).ToPtr());

  // Schedule `ExampleMethodCommand` when the Gamepad's Face Right button is
  // pressed, cancelling on release.
  driverController.FaceRight().WhileTrue(subsystem.ExampleMethodCommand());

<strong>  // Drive to a pose on the field while the left bumper is held.
</strong><strong>  driverController.LeftBumper().WhileTrue(
</strong><strong>      drive.DriveToPose(wpi::math::Pose2d{3_m, 3_m, wpi::math::Rotation2d{30_deg}}));
</strong>
<strong>  // Press the top face button to make the way the robot faces now "forward".
</strong><strong>  driverController.FaceUp().OnTrue(drive.ZeroGyro());
</strong>}

wpi::cmd::CommandPtr RobotContainer::GetAutonomousCommand() {
  // An example command will be run in autonomous
  return autos::ExampleAuto(&#x26;subsystem);
}
</code></pre>

{% endtab %}
{% endtabs %}

These methods use `ChassisVelocities`, which is WPILib 2027's name for `ChassisSpeeds`.

{% hint style="info" %}
In simulation, `drive.getSimPose()` returns a ground truth `Pose2d`, separate from `getPose()`'s fused odometry estimate. It is a convenient "known truth" for a simulated vision subsystem to generate target detections from. It only advances during `simIterate()` and stays at the starting pose on a real robot.
{% endhint %}

{% hint style="success" %}
**Tuning the `driveToPose()` gains live**: when both the translation and the rotation controller are configured, YAMS publishes a tuning command and a tunable target pose. See [auto-align](/documentation/understanding/swerve-drive#auto-align) for how to use it.
{% endhint %}

## Simulate it

1. Run **WPILib: Simulate Robot Code** from the command palette (<kbd>Ctrl+Shift+P</kbd>). If you are asked which extensions to run, tick **Sim GUI**.
2. Connect a controller, then in the Sim GUI drag it from **System Joysticks** to **Joystick\[0]**. The code reads port 0.
3. Show the field. In AdvantageScope (**File > Connect to Simulator**), drag `NT:/Mechanisms/swerve/pose` onto a **2D Field** tab. On an Elastic dashboard, add `NT:/Mechanisms/swerve/field` instead: it is the `Field2d` from `drive.getField2d()`.
4. Press **Teleoperated** in the Sim GUI's **Robot State**. In Commands v3, pick the `ExampleTeleop` op mode first.

**What you should see:** left stick forward drives the robot away from the blue alliance wall at up to 1 m/s. Left stick left drives it toward the left of the field as seen from the blue driver station, and right stick left turns it counter-clockwise. Hold the left bumper and it drives to (3, 3), facing 30 degrees.

**If not:**

* **The robot does not move.** The controller is not on **Joystick\[0]**, the robot is not in Teleoperated, or (Commands v3) `ExampleTeleop` is not the selected op mode.
* **Forward on the stick drives the wrong way, or the sticks are swapped.** An axis is missing its minus sign in the default command. Each axis must be negated.

More fixes are on [Troubleshooting](/documentation/tutorials/troubleshooting).

## Read more

* [Swerve Input Stream](/documentation/reference/swerve-input-stream): everything the stream can do, including heading control and aiming
* [Swerve Drive](/documentation/understanding/swerve-drive): vision measurements, odometry, auto-align and more


# Step 4: Tune it

Practice tuning the azimuth and drive motors in simulation with AdvantageScope, before you tune the real modules.

The module gains from step 1 are placeholders: the azimuth motors' `kP` is 4, and the drive motors have `kV` 0.85 and `kP` 0.3. On this page you go through the swerve tuning steps in simulation, so you know them before you tune the real modules on blocks in [step 5](/documentation/tutorials/swerve-drive/real-robot).

`SwerveDrive` has its own tuning command. It turns all four modules together, to an angle or at a speed you type, so you tune one set of azimuth gains and one set of drive gains for every module. The YAMS Live Tuner does not tune a swerve drive, so this page uses [AdvantageScope](https://docs.advantagescope.org/) to type the values and graph the result.

{% hint style="info" %}
**Simulation is practice, not tuning.** These configs use the same gains on the robot and in simulation, and a simulated module is never exactly like a real one. Do not copy the numbers you find here into your code: step 5 tunes the real modules the same way, and those are the numbers to keep.
{% endhint %}

{% hint style="info" %}
While it runs, the tuning command pauses the default drive command from step 3, so the sticks do nothing until you stop it.
{% endhint %}

## Before you start

* Start the simulation and enable **Teleoperated**, as in [step 3](/documentation/tutorials/swerve-drive/driving#simulate-it).
* Open AdvantageScope and connect it to the simulation (**File > Connect to Simulator**).
* Turn on **tuning mode**: the sliders icon beside the search box at the top of the sidebar. Without it, the values you type and the dots you click are not sent to the robot.

The names on this page come from the tutorial's code: `swerve` from `SwerveDriveConfig.withTelemetry`, `frontleft` from the module's, and `angleMotor` and `driveMotor` from the motors'.

{% stepper %}
{% step %}

### Set up the tabs

Make three tabs with the **+** button at the top right:

1. A **Swerve** tab. Drag `NT:/Mechanisms/swerve/states/current` and `NT:/Mechanisms/swerve/states/desired` into it. It draws each module's angle: where it points, and where it is told to point.
2. A **Line Graph** for the azimuth. Drag in, from `NT:/Mechanisms/swerve/modules/frontleft/angleMotor/`:
   * `mechanism/position`: where the module points, in rotations.
   * `closedloop/setpoint/position`: where it is told to point.
3. A **Line Graph** for the drive. Drag in, from `NT:/Mechanisms/swerve/modules/frontleft/driveMotor/`:
   * `mechanism/velocity`: how fast the wheel turns, in rotations per second.
   * `closedloop/setpoint/velocity`: how fast it is told to turn.

One module is enough to graph: the tuning command sends all four the same setpoint.

**Check it:** the Swerve tab shows four modules, all pointing forward.
{% endstep %}

{% step %}

### Start the tuning command

In the sidebar, open `Tuning/swerve/Live Tuning` and click the dot next to `running`, so that it turns green.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-e837465267e3f57ed42b62f9103ebeb67d1dec33%2Fadvantagescope-tutorial-swerve-start.png?alt=media" alt="AdvantageScope with the sidebar open at Tuning, swerve, Live Tuning, a Command, where the running dot is green, next to the Swerve tab"><figcaption><p>The tuning command running.</p></figcaption></figure>

**Check it:** `running` stays green, and the sticks no longer drive the robot. Nothing moves yet: no tuning mode is on.
{% endstep %}

{% step %}

### Turn the wheels

The azimuth values are under `Tuning/swerve/modules/azimuth`.

1. Type `0` into `angle` and press **Enter**.
2. Click the dot next to `enabled`, so that it turns green. The drive motors are held at 0, so the wheels only turn in place.
3. Type `45` into `angle`. Every module turns to 45 degrees.

Keep each change under 90 degrees. For a bigger one, YAMS may turn the wheel the short way round and run it backwards, which makes the graphs hard to read.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-ce4ec428355eaa50e6de9c2c8e600eff90f8d3b0%2Fadvantagescope-tutorial-swerve-azimuth-swerve.png?alt=media" alt="The Swerve tab with all four modules pointing at 45 degrees, and the sidebar with angle 45 and enabled green under Tuning, swerve, modules, azimuth"><figcaption><p>Every module at the 45 degrees typed into <code>angle</code>.</p></figcaption></figure>

**Check it:** on the Swerve tab, all four modules point at 45 degrees.
{% endstep %}

{% step %}

### Tune the azimuth kP

Open the azimuth graph. `feedback/p`, under `azimuth`, is the `kP` from step 1: volts for each rotation the module is away from its angle.

1. Type `0`, then `45`, into `angle`, and watch the position line. With `kP` at 4 it takes about a second to get there.
2. Raise `feedback/p`, and step the angle again each time:
   * It turns slowly, or stops short of the angle: raise `p`.
   * It overshoots and swings back: lower `p` by about a third.
3. If it still overshoots a little at a `p` that is quick enough, add a little `feedback/d`, starting at `0.1`.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d6c7ea8660d1006537059f851fc5ae54479c5cdc%2Fadvantagescope-tutorial-swerve-azimuth-graph.png?alt=media" alt="The azimuth line graph: the first two steps between 0 and 0.125 rotations, at kP 4, curve slowly onto the setpoint over about a second; the last steps, at kP 30, reach it almost at once with a small overshoot"><figcaption><p>45 degrees is 0.125 rotations. At <code>p</code> 4 (left) the module takes about a second. At 30 (right) it gets there almost at once.</p></figcaption></figure>

**Check it:** after each change of angle the modules snap to it and stop without shaking.
{% endstep %}

{% step %}

### Tune the drive kV and kP

Open the drive graph. The drive values are under `Tuning/swerve/modules/drive`.

1. Type `0` into `velocity`, then click the dot next to `enabled`. Azimuth tuning turns itself off, and every module points straight ahead.
2. Type `0` into `feedback/p`, so you can see what the feedforward does on its own.
3. Type `2` into `velocity`: 2 meters per second for every wheel. The graph shows it as about 6.3 rotations per second of the 4 inch wheel.
4. Raise `feedforward/v` until the wheel's speed settles on the setpoint. For a NEO on 6.75:1 it ends up near `0.85`. Below that, the wheel settles short.
5. Raise `feedback/p` until the speed gets there quickly. If it starts to buzz or overshoot, it is too high.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-61cf23d18d3d367525e6d7960131e5a5e4a7f742%2Fadvantagescope-tutorial-swerve-drive-graph.png?alt=media" alt="The drive line graph: with feedforward v at 0.5 the wheel speed settles near 3.7 rotations per second, short of the 6.3 setpoint; raising v to 0.85 brings it up onto the setpoint"><figcaption><p><code>feedforward/v</code> raised from 0.5 to 0.85: the wheel climbs from 3.7 onto the 6.3 rotations per second setpoint.</p></figcaption></figure>

**Check it:** at a `velocity` of `1` and of `2`, the wheel's speed settles on the setpoint.
{% endstep %}

{% step %}

### Stop

1. Click `enabled` under `drive` so that it turns red, and type `0` into `velocity`.
2. Click `running` under `Tuning/swerve/Live Tuning` so that it turns red.

**Check it:** the sticks drive the robot again.
{% endstep %}
{% endstepper %}

## If it did not work

* **Typing a value or clicking a dot does nothing.** Turn on AdvantageScope's tuning mode, and check that `running` under `Tuning/swerve/Live Tuning` is green.
* **`Tuning/swerve/Live Tuning` is missing.** The tuning command is only there when `SwerveDriveConfig` has both a translation and a rotation controller, as in step 2, and the drive's telemetry is `TelemetryVerbosity.HIGH`.
* **The modules do not turn to the angle.** Check that `enabled` under `azimuth` is green, and that `running` under `Tuning/swerve/Live Tuning` still is.
* **A wheel turns the other way and runs backwards.** The angle changed by 90 degrees or more. Step between closer angles, such as 0 and 45.

For every tuning value, including auto-align, see [Tune a swerve drive](/documentation/how-to-tuning/live-tuning/swerve-drive) on the Live tuning page. More problems and fixes: [Troubleshooting](/documentation/tutorials/troubleshooting).


# Step 5: On the real robot

Set the encoder offsets, check every direction, tune the modules and drive the real robot for the first time.

The code from steps 1 to 3 drives in simulation. A real swerve drive needs four more things before it can drive safely: the right CAN IDs, an absolute encoder offset for every module, every motor and the gyro turning the right way, and tuned gains. This step does them in that order, and ends with the first drive on the ground.

Do the checks in order. Each one ends with **What you should see** and **If not**. Do not go on to the next check until the one before it passes: a wrong offset makes the direction checks lie, and untuned modules make the first drive lie.

{% hint style="warning" %}
Keep one person at the Driver Station, ready to disable the robot, every time it is enabled. **Enter** disables it and **Space** stops it at once.
{% endhint %}

{% stepper %}
{% step %}

### Put the robot on blocks

Put the robot on blocks so that every wheel is clear of the blocks and of the ground, and can spin and steer freely. Use a charged battery. Deploy the code with **WPILib: Deploy Robot Code** from the command palette (<kbd>Ctrl+Shift+P</kbd>).

Connect AdvantageScope to the robot (**File > Connect to Robot**), or open an Elastic dashboard. Everything below is under `NT:/Mechanisms/swerve`, the name given to the drive's `withTelemetry` in step 2.

In Commands v3, pick the `ExampleTeleop` op mode before you enable.

**What you should see:** the code starts without errors in the Driver Station, and `NT:/Mechanisms/swerve/modules` has four modules: `frontleft`, `frontright`, `backleft` and `backright`.

**If not:** read the first error in the Driver Station. YAMS names the setting that is missing. [Troubleshooting](/documentation/tutorials/troubleshooting) has the common ones.
{% endstep %}

{% step %}

### Check the CAN IDs

Every device needs the CAN ID the code gives it:

| Device             | Front left | Front right | Back left | Back right |
| ------------------ | ---------- | ----------- | --------- | ---------- |
| Drive `SparkMax`   | 1          | 4           | 7         | 10         |
| Azimuth `SparkMax` | 2          | 5           | 8         | 11         |
| `CANcoder`         | 3          | 6           | 9         | 12         |

The `Pigeon2` is 14. Set the `SparkMax` IDs with the REV Hardware Client, and the `CANcoder` and `Pigeon2` IDs with Phoenix Tuner X.

The IDs must also be on the right module. Turn the front left wheel by hand, about a quarter turn of steering, and watch `NT:/Mechanisms/swerve/modules/frontleft/encoder`. Do the same for the other three.

**What you should see:** every device shows up in its tool with the ID in the table, no two devices share an ID, and turning a wheel changes only that module's `encoder`.

**If not:**

* **A device is missing.** Two devices share an ID, so only one answers. Give each its own ID.
* **Turning the front left wheel changes another module's `encoder`.** The `CANcoder`s are on the wrong modules. Change their IDs to match the table, or change the IDs in the code.
* **Every device is missing.** The code puts every device on `CANPort.CAN_S0`. If the robot is wired to another of the SystemCore's CAN ports, change `CAN_S0` in the code.
  {% endstep %}

{% step %}

### Set the absolute encoder offsets

Each `CANcoder` is mounted at its own angle, so each reads a different number with the wheel pointing forward. The offset is that number. YAMS subtracts it from the reading, so the module reads 0 when the wheel points forward.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-07248350cb5eba533b1f2c5fd94d3df7d4e25704%2Fmech-module-absolute-encoder.png?alt=media" alt="Two panels. Zero must be with the wheel pointing forward and its bevel gear facing the robot&#x27;s left. To find the offset, point every wheel forward with bevels to the left, read each absolute encoder, and use that reading, here 64 degrees, as that module&#x27;s offset."><figcaption><p>Point every wheel forward with its bevel gear to the left, then read each encoder.</p></figcaption></figure>

1. With the robot disabled, turn every wheel by hand so that it points straight forward with its **bevel gear facing the robot's left**. Lay a straight edge along each side of the robot to line the wheels up.
2. First, check the encoder's direction: turn one wheel a little counter-clockwise, seen from above. Its `encoder` value must go **up**. If it goes down, set that `CANcoder`'s sensor direction to clockwise positive in Phoenix Tuner X, then line the wheel up again.
3. Read `NT:/Mechanisms/swerve/modules/<module>/encoder` for each module. It is the raw `CANcoder` reading in degrees, with no offset applied.
4. Put each reading, sign and all, into that module's offset in the constructor, then deploy again.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java: in the constructor" %}

```java
// Each offset is that module's encoder reading with its wheel forward, bevel gear left.
var frontLeft = createModule(new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless),
                             new SparkMax(CANPort.CAN_S0, 2, MotorType.kBrushless),
                             new CANcoder(3, new CANBus(CANPort.CAN_S0)), Degrees.of(64.2), "frontleft",
                             new Translation2d(Inches.of(24), Inches.of(24)));
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/SwerveMechanism.java: in the constructor" %}

```java
// Each offset is that module's encoder reading with its wheel forward, bevel gear left.
var frontLeft = createModule(new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless),
                             new SparkMax(CANPort.CAN_S0, 2, MotorType.kBrushless),
                             new CANcoder(3, new CANBus(CANPort.CAN_S0)), Degrees.of(64.2), "frontleft",
                             new Translation2d(Inches.of(24), Inches.of(24)));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/SwerveSubsystem.cpp: in the constructor" %}

```cpp
// Each offset is that module's encoder reading with its wheel forward, bevel gear left.
SetupModule(m_frontLeft, "frontleft", wpi::math::Translation2d{24_in, 24_in}, 64.2_deg);
```

{% endcode %}
{% endtab %}
{% endtabs %}

`64.2` is an example. Use your own reading for each of the four modules.

**What you should see:** with the wheels still pointing forward, open an AdvantageScope **Swerve** tab with `NT:/Mechanisms/swerve/states/current`. All four arrows point forward. Turn the robot off and on again: they still point forward.

**If not:**

* **One module points backward.** Its bevel gear faced right when you read it. Add 180 to its offset, or turn the wheel round and read it again.
* **One module points somewhere else.** That offset is not its own reading: check that you put each reading on the right module.
* **Every module is off by a different amount after a restart.** The offsets are still 0, or the code was not deployed again.
  {% endstep %}

{% step %}

### Check the directions

Every angle in WPILib is counter-clockwise positive, seen from above, and every motor has to agree. The [swerve tuning command](/documentation/how-to-tuning/live-tuning/swerve-drive) makes this easy: it turns every wheel to an angle, or runs every wheel at a speed, that you type on the dashboard.

Enable the robot in Teleoperated, still on blocks, and start the tuning command `NT:/Tuning/swerve/Live Tuning` as [Start the tuning command](/documentation/how-to-tuning/live-tuning/swerve-drive#start-the-tuning-command) shows. The values you type are under `NT:/Tuning/swerve/`.

**Azimuth.** Type `0` into `modules/azimuth/angle`, set `modules/azimuth/enabled` to `true`, then type `90`.

**What you should see:** every wheel turns a quarter turn counter-clockwise, seen from above, and ends up pointing to the robot's left.

**If not:** if every wheel turns clockwise, set `withMotorInverted(true)` in the azimuth config from step 1. The four modules share the config, so one change fixes all four.

**Drive.** Set `modules/azimuth/enabled` to `false`. Type `0` into `modules/drive/velocity`, set `modules/drive/enabled` to `true`, then type `0.5`.

**What you should see:** every wheel points forward and rolls so that the robot would drive **forward**: the top of each wheel moves toward the front of the robot.

**If not:**

* **Every wheel rolls backward.** Set `withMotorInverted(true)` in the drive config from step 1.
* **One wheel rolls backward and the others forward.** That module's offset is 180 degrees off, because its bevel gear faced right when you read it. Add 180 to its offset.

Then set `modules/drive/inplace` to `true`. The wheels turn to form a circle, so the robot would spin counter-clockwise in place. If one wheel is not on the circle, its location in step 2 has the wrong sign.

Set `modules/drive/enabled` to `false` when you are done.
{% endstep %}

{% step %}

### Check the gyro

Disable the robot. Watch `NT:/Mechanisms/swerve/gyro`, the heading in degrees, and turn the whole robot counter-clockwise by hand, seen from above.

**What you should see:** the heading goes **up**.

**If not:**

* **It goes down.** Add `.withGyroInverted(true)` to the `SwerveDriveConfig` in step 2.
* **It does not change.** Check the `Pigeon2`'s CAN ID. If the ID is right, the gyro is mounted on its side: see [How do I use a gyro mounted on its side?](/documentation/how-to-motor-controllers-and-sensors/how-do-i-use-a-gyro-mounted-on-its-side).
  {% endstep %}

{% step %}

### Tune the modules

The gains from step 1 are placeholders. Tune the real modules on blocks, azimuth first so that the wheels point where they are told, then drive, the same way you practiced in [Step 4: Tune it](/documentation/tutorials/swerve-drive/tune). [Tune the swerve modules](/documentation/how-to-tuning/live-tuning/swerve-drive#tune-the-swerve-modules) has every value and what the graph should look like.

Copy the gains you find into `buildAzimuthCfg()` and `buildDriveCfg()` (C++: `ConfigureAzimuth` and `ConfigureDrive`), then deploy again. Values typed on the dashboard are lost when the code restarts.

**What you should see:** stepping `modules/azimuth/angle` between `0` and `90` snaps every wheel to the angle without shaking, and a `modules/drive/velocity` of `1` holds each wheel's measured speed at 1 m/s.

**If not:** the modules are still slow, or shake. See [When tuning does not help](/documentation/tutorials/troubleshooting#when-tuning-does-not-help).
{% endstep %}

{% step %}

### Drive on the ground

Take the robot off the blocks and put it in an open space. Keep the maximum speed at 1 m/s from step 3: it is slow on purpose.

1. Point the robot **away from the driver station**, then turn it on. If it is already on, point it away from you and press the zero gyro button (the top face button) to run `zeroGyro()`.
2. Enable Teleoperated and push the left stick forward gently.

**What you should see:** the robot drives straight away from you. Left stick left drives it to your left without turning. Right stick left turns it counter-clockwise in place.

**If not:**

* **It drives off at an angle, or the wrong way.** The robot was not facing away from you when it was turned on or zeroed. Point it away and press the zero gyro button.
* **The direction it drives changes as it turns.** The gyro is the wrong way round: go back to [Check the gyro](#check-the-gyro).
* **It curves, or a wheel fights the others.** An offset is wrong: go back to [Set the absolute encoder offsets](#set-the-absolute-encoder-offsets).

Once it drives well, raise the two maximum velocities in step 3 a little at a time.
{% endstep %}
{% endstepper %}

## After the first drive

These make a good drive better. Do them once the robot drives well by hand:

* **Speed limits.** Measure the real top speed by driving flat out, and set [`withMaximumModuleSpeed` and `withMaximumChassisSpeed`](/documentation/reference/mechanism-configs/swerve-drive-config#speed-limits) a little below it.
* **Drift while spinning.** Drive in a straight line while spinning. If the path bends, set [`withDiscretizationTime`](/documentation/reference/mechanism-configs/swerve-drive-config#withdiscretizationtime) to the loop time, then [`withGyroAngularVelocityScaleFactor`](/documentation/reference/mechanism-configs/swerve-drive-config#withgyroangularvelocityscalefactor) if some remains.
* **Odometry creep.** If the pose moves when the wheels only steer, set [`withCouplingRatio`](/documentation/reference/mechanism-configs/swerve-module-config#withcouplingratio).
* **Auto-align.** Tune the `driveToPose()` controllers last: see [Tune auto-align](/documentation/how-to-tuning/live-tuning/swerve-drive#tune-auto-align).

## Read more

* [Swerve Drive](/documentation/understanding/swerve-drive): vision measurements, auto-align and path following


# AdvantageKit

YAMS integrates seamlessly with [AdvantageKit](https://docs.advantagekit.org/), Team 6328's logging and replay framework. This guide shows how to use YAMS mechanisms with AdvantageKit's IO layer pattern for deterministic log replay.

## What is AdvantageKit?

[AdvantageKit](https://docs.advantagekit.org/getting-started/what-is-advantagekit) is a logging framework that records **all inputs** to your robot code, enabling deterministic replay in simulation. Unlike traditional logging that captures specific values, AdvantageKit captures everything flowing into your code, allowing you to:

* Replay matches exactly as they happened
* Add new logged fields after the fact
* Test code changes against real match data
* Debug issues that only occurred on the real robot

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-bbce743f274fdb3256742cf7d19c4a061e493885%2Fakit-loop-live-and-replay.gif?alt=media" alt="Animation of one loop of the robot shown twice. On the real robot and in simulation, the IO class reads the YAMS arm into the inputs, the inputs are written to the log, the subsystem logic runs on them, and its setpoint goes back through the IO class to the YAMS arm. In log replay the inputs come from the log file, the same subsystem logic runs on them, and the outputs go to an empty replay IO class that drops them."><figcaption><p>The subsystem only sees the inputs, so replaying the logged inputs replays its decisions.</p></figcaption></figure>

{% hint style="info" %}
AdvantageKit is optional. YAMS works perfectly without it using its built-in telemetry system. Consider AdvantageKit if you want deterministic log replay capabilities.
{% endhint %}

## Architecture overview

AdvantageKit uses an [IO interface pattern](https://docs.advantagekit.org/data-flow/recording-inputs/io-interfaces) to separate hardware interaction from business logic. Traditionally, this requires separate IO implementations for real hardware and simulation:

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d35a960b062321b6872e55ca09cb783f0727b0f1%2Fakit-io-classes.png?alt=media" alt="Two diagrams of a subsystem, its IO interface and the classes that implement it. Traditional AdvantageKit needs three IO classes for each mechanism: one with your motor and encoder code for the real robot, one with your physics simulation, and an empty one for log replay. With YAMS there are two: one class used on the real robot and in simulation, because the YAMS mechanism under it simulates itself, and the empty one for log replay."><figcaption><p>Traditional AdvantageKit needs three IO classes for each mechanism. With YAMS it is two.</p></figcaption></figure>

## YAMS simplification: one IO class for real and sim

**With YAMS, you don't need separate Real and Sim IO implementations.** Every `SmartMotorController` wrapper (TalonFXWrapper, SparkWrapper, etc.) and every Mechanism class (Arm, Elevator, FlyWheel, SwerveModule, SwerveDrive, etc.) includes **passive simulation** that runs automatically when `Robot.isSimulation()` returns true.

The YAMS mechanism under the IO class picks real hardware or its own simulation by itself, based on `Robot.isSimulation()`.

This means:

* **One IO class** handles both real robot and simulation
* **No duplicate code** - configuration is written once
* **No SimWrapper needed** - real hardware wrappers simulate themselves
* **Physics are automatic** - based on your DCMotor, gearing, and mass/MOI configuration

{% hint style="success" %}
**Key Insight**: When you create a `TalonFXWrapper`, `TalonFXSWrapper`, `SparkWrapper`, or any YAMS Mechanism, the simulation physics run automatically in sim mode. You write your IO class once using real hardware objects, and YAMS handles the rest.
{% endhint %}

## Tutorial

The tutorial builds an arm with the IO layer pattern, one step per page, and shows the elevator and shooter IO classes alongside it. Start with Step 0:

| Page                                                                                                                              | What it covers                                                             |
| --------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| [Step 0: Install AdvantageKit and set up Robot](/documentation/tutorials/advantagekit-integration/setup)                          | The vendor library, `build.gradle`, and `Robot` as a `LoggedRobot`.        |
| [Step 1: Define the IO interface](/documentation/tutorials/advantagekit-integration/io-interface)                                 | The inputs each mechanism logs.                                            |
| [Step 2: Implement the IO class](/documentation/tutorials/advantagekit-integration/io-implementation)                             | One IO class per mechanism that works on the real robot and in simulation. |
| [Steps 3 and 4: The subsystem and RobotContainer](/documentation/tutorials/advantagekit-integration/subsystem-and-robotcontainer) | The subsystem that uses the IO class, and wiring it up.                    |
| [Log replay](/documentation/tutorials/advantagekit-integration/log-replay)                                                        | Replaying a log, and the pattern in summary.                               |
| [Swerve drive with AdvantageKit](/documentation/tutorials/advantagekit-integration/swerve-drive)                                  | The same pattern for a YAMS swerve drive.                                  |
| [Without an IO layer](/documentation/tutorials/advantagekit-integration/direct-subsystem)                                         | A simpler pattern that logs straight from the subsystem.                   |

## Benefits of YAMS + AdvantageKit

| Feature                     | Benefit                                                   |
| --------------------------- | --------------------------------------------------------- |
| **No Duplicate IO Classes** | Single IO class works for real robot AND simulation       |
| **Deterministic Replay**    | Debug issues from real matches using log replay           |
| **Automatic Physics**       | YAMS uses DCMotor, gearing, and mass/MOI for accurate sim |
| **Less Boilerplate**        | 2 IO classes instead of 3 per mechanism                   |
| **Consistent Behavior**     | Same code paths execute in real and sim modes             |
| **Flexible Hardware**       | Swap vendors by changing one IO class                     |

## Further reading

* [AdvantageKit Documentation](https://docs.advantagekit.org/)
* [What is AdvantageKit?](https://docs.advantagekit.org/getting-started/what-is-advantagekit)
* [IO Interfaces](https://docs.advantagekit.org/data-flow/recording-inputs/io-interfaces)
* [Template Projects](https://docs.advantagekit.org/getting-started/template-projects)
* [YAMS AdvantageKit Example (Commands v2)](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands2/advantage_kit)
* [YAMS AdvantageKit Example (Commands v3)](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands3/advantage_kit)


# Step 0: Install AdvantageKit and set up Robot

Before the IO classes can log anything, the project needs the AdvantageKit library, its code generator in `build.gradle`, and a `Robot` class that starts the AdvantageKit logger. This page sets up a Commands v2 project that already builds with YAMS, the same way the [YAMS AdvantageKit example](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands2/advantage_kit) does.

{% hint style="info" %}
AdvantageKit is a separate library from Team 6328, and its 2027 releases are still alphas. If anything here does not match what you see, the [AdvantageKit installation docs for existing projects](https://docs.advantagekit.org/getting-started/installation/existing-projects) are the source of truth.
{% endhint %}

{% stepper %}
{% step %}

### Install the vendor library

In VS Code, open the WPILib command palette, choose **WPILib: Manage Vendor Libraries**, then **Install new library (online)**, and paste:

```
https://github.com/Mechanical-Advantage/AdvantageKit/releases/latest/download/AdvantageKit.json
```

This adds `vendordeps/AdvantageKit.json` to your project. The YAMS 2027 examples were built against AdvantageKit `27.0.0-alpha-5`.

**Check:** `vendordeps/AdvantageKit.json` exists in your project.
{% endstep %}

{% step %}

### Add the AutoLog code generator to `build.gradle`

The `@AutoLog` annotation used in [Step 1](/documentation/tutorials/advantagekit-integration/io-interface) generates a class for each inputs class when the code builds. That needs an annotation processor line in the `dependencies` block of `build.gradle`:

```groovy
dependencies {
    annotationProcessor wpi.java.deps.wpilibAnnotations()
    // AdvantageKit's @AutoLog code generator, at the same version as the vendor library.
    def akitJson = new groovy.json.JsonSlurper().parseText(
        new File(projectDir.getAbsolutePath() + "/vendordeps/AdvantageKit.json").text)
    annotationProcessor "org.littletonrobotics.akit:akit-autolog:$akitJson.version"

    // ... the rest of your dependencies stay as they are
}
```

This is the setup used by the YAMS AdvantageKit examples. AdvantageKit's own docs add more to `build.gradle` (such as recording git metadata); see the [AdvantageKit installation docs](https://docs.advantagekit.org/getting-started/installation/existing-projects) if you want those.

**Check:** the project still builds.
{% endstep %}

{% step %}

### Make `Robot` a `LoggedRobot`

`Robot` extends AdvantageKit's `LoggedRobot` instead of WPILib's `TimedRobot`, and starts the logger in its constructor before anything else is created. It also defines `currentMode`, which [Log replay](/documentation/tutorials/advantagekit-integration/log-replay) uses to choose the IO class.

```java
package first.robot;

import org.littletonrobotics.junction.LogFileUtil;
import org.littletonrobotics.junction.LoggedRobot;
import org.littletonrobotics.junction.Logger;
import org.littletonrobotics.junction.networktables.NT4Publisher;
import org.littletonrobotics.junction.wpilog.WPILOGReader;
import org.littletonrobotics.junction.wpilog.WPILOGWriter;
import org.wpilib.command2.CommandScheduler;
import org.wpilib.framework.RobotBase;

public class Robot extends LoggedRobot {
  public static enum Mode {
    /** Running on a real robot. */
    REAL,
    /** Running a physics simulator. */
    SIM,
    /** Replaying from a log file. */
    REPLAY
  }

  /** Change to Mode.REPLAY to replay a log in simulation. */
  public static final Mode simMode = Mode.SIM;
  public static final Mode currentMode = RobotBase.isReal() ? Mode.REAL : simMode;

  private final RobotContainer robotContainer;

  public Robot() {
    switch (currentMode) {
      case REAL:
        // On the SystemCore: write a log file and publish to NetworkTables.
        Logger.addDataReceiver(new WPILOGWriter());
        Logger.addDataReceiver(new NT4Publisher());
        break;

      case SIM:
        // In simulation: publish to NetworkTables.
        Logger.addDataReceiver(new NT4Publisher());
        break;

      case REPLAY:
        // Replaying a log: read it, and write the replayed values to a new log next to it.
        setUseTiming(false); // Run as fast as possible
        String logPath = LogFileUtil.findReplayLog();
        Logger.setReplaySource(new WPILOGReader(logPath));
        Logger.addDataReceiver(new WPILOGWriter(LogFileUtil.addPathSuffix(logPath, "_sim")));
        break;
    }

    // Start the AdvantageKit logger before creating the subsystems.
    Logger.start();

    robotContainer = new RobotContainer();
  }

  @Override
  public void robotPeriodic() {
    CommandScheduler.getInstance().run();
  }
}
```

Keep the rest of your `Robot` methods (autonomous, teleop and so on) as they are. `first/Main.java` does not change: it still starts `first.robot.Robot`.

{% hint style="info" %}
**Commands v3:** `Robot` extends `LoggedRobot` in the same way, with the same `Mode` and logger setup, and `robotPeriodic()` runs `Scheduler.getDefault().run()`. See the [Commands v3 AdvantageKit example](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands3/advantage_kit).
{% endhint %}

**Check:** run the code in simulation and open AdvantageScope. An `AdvantageKit` table appears in NetworkTables next to the YAMS `Mechanisms` table.
{% endstep %}
{% endstepper %}

## If it did not work

* **`org.littletonrobotics.junction` cannot be found:** the vendor library is not installed. Repeat [1. Install the vendor library](#install-the-vendor-library), then build again.
* **`ArmIOInputsAutoLogged` cannot be found later:** the annotation processor line is missing or wrong. Check step 2 above, clean the project with `gradlew clean` (Windows) or `./gradlew clean` (Linux/macOS) and build again.

Next: [Step 1: Define the IO interface](/documentation/tutorials/advantagekit-integration/io-interface)


# Step 1: Define the IO interface

Create an interface that defines what inputs your subsystem reads and what outputs it sends. Following AdvantageKit conventions, inputs are grouped in an `Inputs` class. This needs AdvantageKit installed, from [Step 0: Install AdvantageKit and set up Robot](/documentation/tutorials/advantagekit-integration/setup).

The inputs are plain numbers with the unit in the name, as AdvantageKit's own examples do. The methods that command the mechanism take WPILib units (`Angle`, `Distance`, `AngularVelocity`), so a caller cannot mix up degrees and rotations.

## Arm IO interface

```java
package first.robot.subsystems.akit;

import org.littletonrobotics.junction.AutoLog;
import org.wpilib.units.measure.Angle;

public interface ArmIO {

  /**
   * Inputs that will be logged and replayed.
   * The @AutoLog annotation generates ArmIOInputsAutoLogged class.
   */
  @AutoLog
  public static class ArmIOInputs {
    public double positionRotations = 0.0;
    public double velocityRotationsPerSec = 0.0;
    public double appliedVolts = 0.0;
    public double supplyCurrentAmps = 0.0;
    public double statorCurrentAmps = 0.0;
    public double temperatureCelsius = 0.0;
    public double targetPositionRotations = 0.0;
  }

  /** Update the inputs from hardware. Called every loop cycle. */
  default void updateInputs(ArmIOInputs inputs) {}

  /** Set the target angle for the arm. */
  default void setTargetAngle(Angle angle) {}

  /** Stop the arm motor. */
  default void stop() {}

  /** Update the sim telemetry */
  default void simIterate() {}

  /** Update the telemetry */
  default void updateTelemetry() {}
}
```

## Elevator IO interface

```java
package first.robot.subsystems.akit;

import org.littletonrobotics.junction.AutoLog;
import org.wpilib.units.measure.Distance;

public interface ElevatorIO {

  @AutoLog
  public static class ElevatorIOInputs {
    public double positionMeters = 0.0;
    public double velocityMetersPerSec = 0.0;
    public double appliedVolts = 0.0;
    public double supplyCurrentAmps = 0.0;
    public double statorCurrentAmps = 0.0;
    public double temperatureCelsius = 0.0;
    public double targetPositionMeters = 0.0;
  }

  default void updateInputs(ElevatorIOInputs inputs) {}

  default void setTargetHeight(Distance height) {}

  default void stop() {}

  /** Update the sim telemetry */
  default void simIterate() {}

  /** Update the telemetry */
  default void updateTelemetry() {}
}
```

## Shooter IO interface

```java
package first.robot.subsystems.akit;

import org.littletonrobotics.junction.AutoLog;
import org.wpilib.units.measure.AngularVelocity;

public interface ShooterIO {

  @AutoLog
  public static class ShooterIOInputs {
    public double velocityRotationsPerSec = 0.0;
    public double appliedVolts = 0.0;
    public double supplyCurrentAmps = 0.0;
    public double statorCurrentAmps = 0.0;
    public double temperatureCelsius = 0.0;
    public double targetVelocityRotationsPerSec = 0.0;
  }

  default void updateInputs(ShooterIOInputs inputs) {}

  default void setTargetVelocity(AngularVelocity velocity) {}

  default void stop() {}

  /** Update the sim telemetry */
  default void simIterate() {}

  /** Update the telemetry */
  default void updateTelemetry() {}
}
```

{% hint style="info" %}
The `@AutoLog` annotation from AdvantageKit generates a class (e.g., `ArmIOInputsAutoLogged`) that handles serialization for log replay. See [AdvantageKit AutoLog documentation](https://docs.advantagekit.org/data-flow/recording-inputs/io-interfaces#autolog) for details.

If the `AutoLogged` class is not generated, check the `annotationProcessor` lines from [Step 0](/documentation/tutorials/advantagekit-integration/setup), then clean the project with `gradlew clean` (Windows) or `./gradlew clean` (Linux/macOS) and build again. If the class still does not generate, try commenting out the `annotationProcessor wpi.java.deps.wpilibAnnotations()` line and clean again.
{% endhint %}

**Check:** build the project. It succeeds, and `ArmIOInputsAutoLogged`, `ElevatorIOInputsAutoLogged` and `ShooterIOInputsAutoLogged` can be imported (they are generated under `build/generated`).

Next: [Step 2: Implement the IO class](/documentation/tutorials/advantagekit-integration/io-implementation)


# Step 2: Implement the IO class

With YAMS, you only need **one IO implementation** that works for both real hardware and simulation. The `SmartMotorController` automatically detects when it's running in simulation and uses physics simulation instead of real hardware.

Each IO class takes the subsystem that owns it in its constructor, because the `SmartMotorControllerConfig` needs it. The subsystem builds its own IO class in [Step 3](/documentation/tutorials/advantagekit-integration/subsystem-and-robotcontainer), passing itself in. The CAN ID is a constant in the IO class.

## Arm IO implementation (works for real and sim)

```java
package first.robot.subsystems.akit;

import static org.wpilib.units.Units.*;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ArmFeedforward;
import org.wpilib.math.system.DCMotor;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.units.measure.Angle;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.ArmConfig;
import yams.commands2.mechanisms.Arm;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.remote.TalonFXWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

/**
 * Single IO implementation for the arm - works in BOTH real and simulation!
 * Uses YAMS Arm mechanism class while pulling telemetry from the underlying SmartMotorController.
 */
public class ArmIOTalonFX implements ArmIO {

  private static final int CAN_ID = 1;

  private final Arm arm;
  private final SmartMotorController motor;

  public ArmIOTalonFX(SubsystemBase subsystem) {
    TalonFX talonFX = new TalonFX(CAN_ID, new CANBus(CANPort.CAN_S0));
    
    // Step 1: Create SmartMotorControllerConfig
    SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(subsystem)
        .withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4, 3)))
        .withClosedLoopController(5, 0, 0.1)
        .withSoftLimits(Rotations.of(-0.25), Rotations.of(0.25))
        .withFeedforward(new ArmFeedforward(0.1, 0.3, 0.5, 0.01))
        .withTrapezoidalProfile(RotationsPerSecond.of(1.0), RotationsPerSecondPerSecond.of(2.0))
        .withStartingPosition(Rotations.of(0));  // Starting position lives on the SmartMotorControllerConfig
    
    // Step 2: Create SmartMotorController (TalonFXWrapper)
    SmartMotorController smc = new TalonFXWrapper(talonFX, DCMotor.getKrakenX60(1), smcConfig);
    
    // Step 3: Create ArmConfig
    ArmConfig armConfig = new ArmConfig()
        .withLength(Inches.of(18))           // Arm length, used for simulation physics
        .withHardLimits(Rotations.of(-0.3), Rotations.of(0.3))  // Physical hard stops for sim
        .withTelemetry("Arm", TelemetryVerbosity.HIGH);
    
    // Step 4: Create Arm mechanism, simulation is handled automatically
    this.arm = new Arm(armConfig, smc);
    
    // Get reference to underlying SmartMotorController for telemetry
    this.motor = arm.getMotor();
  }

  @Override
  public void updateInputs(ArmIOInputs inputs) {
    // Pull telemetry data from the underlying SmartMotorController
    inputs.positionRotations = motor.getMechanismPosition().in(Rotations);
    inputs.velocityRotationsPerSec = motor.getMechanismVelocity().in(RotationsPerSecond);
    inputs.appliedVolts = motor.getVoltage().in(Volts);
    inputs.supplyCurrentAmps = motor.getSupplyCurrent().map(c -> c.in(Amps)).orElse(0.0);
    inputs.statorCurrentAmps = motor.getStatorCurrent().in(Amps);
    inputs.temperatureCelsius = motor.getTemperature().in(Celsius);
    inputs.targetPositionRotations = motor.getMechanismPositionSetpoint()
        .map(a -> a.in(Rotations)).orElse(0.0);
  }

  @Override
  public void setTargetAngle(Angle angle) {
    // Use SmartMotorController's setPosition method
    motor.setPosition(angle);
  }

  @Override
  public void stop() {
    motor.setVoltage(Volts.of(0));
  }
  
  /** Access the Arm mechanism for command helpers like run() and runTo() */
  public Arm getArm() {
    return arm;
  }

  @Override
  public void simIterate() {
    arm.simIterate();
  }

  @Override
  public void updateTelemetry() {
    arm.updateTelemetry();
  }
}
```

## Elevator IO implementation (works for real and sim)

```java
package first.robot.subsystems.akit;

import static org.wpilib.units.Units.*;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ElevatorFeedforward;
import org.wpilib.math.system.DCMotor;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.units.measure.Distance;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.ElevatorConfig;
import yams.commands2.mechanisms.Elevator;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.remote.TalonFXWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

/**
 * Single IO implementation - uses YAMS Elevator mechanism with SmartMotorController telemetry.
 */
public class ElevatorIOTalonFX implements ElevatorIO {

  private static final int CAN_ID = 2;

  private final Elevator elevator;
  private final SmartMotorController motor;

  public ElevatorIOTalonFX(SubsystemBase subsystem) {
    TalonFX talonFX = new TalonFX(CAN_ID, new CANBus(CANPort.CAN_S0));
    
    // Step 1: Create SmartMotorControllerConfig
    SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(subsystem)
        .withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4)))
        .withDrumRadius(Inches.of(0.75))  // Drum radius
        .withStartingPosition(Meters.of(0.5))  // Starting height, used for simulation
        .withClosedLoopController(10, 0, 0.5)
        .withSoftLimits(Meters.of(0.02), Meters.of(1.2))
        .withFeedforward(new ElevatorFeedforward(0.1, 0.2, 0.5, 0.01))
        .withTrapezoidalProfile(MetersPerSecond.of(1.0), MetersPerSecondPerSecond.of(2.0));
    
    // Step 2: Create SmartMotorController (TalonFXWrapper)
    SmartMotorController smc = new TalonFXWrapper(talonFX, DCMotor.getKrakenX60(1), smcConfig);
    
    // Step 3: Create ElevatorConfig
    ElevatorConfig elevatorConfig = new ElevatorConfig()
        .withCarriageWeight(Pounds.of(10))                 // Carriage mass - used for simulation physics
        .withHardLimits(Meters.of(0), Meters.of(1.5))  // Physical hard stops for sim
        .withTelemetry("Elevator", TelemetryVerbosity.HIGH);
    
    // Step 4: Create Elevator mechanism, simulation is handled automatically
    this.elevator = new Elevator(elevatorConfig, smc);
    
    // Get reference to underlying SmartMotorController for telemetry
    this.motor = elevator.getMotor();
  }

  @Override
  public void updateInputs(ElevatorIOInputs inputs) {
    // Pull telemetry data from the underlying SmartMotorController
    inputs.positionMeters = motor.getMeasurementPosition().in(Meters);
    inputs.velocityMetersPerSec = motor.getMeasurementVelocity().in(MetersPerSecond);
    inputs.appliedVolts = motor.getVoltage().in(Volts);
    inputs.supplyCurrentAmps = motor.getSupplyCurrent().map(c -> c.in(Amps)).orElse(0.0);
    inputs.statorCurrentAmps = motor.getStatorCurrent().in(Amps);
    inputs.temperatureCelsius = motor.getTemperature().in(Celsius);
    // The setpoint is stored as a mechanism angle; convert it to a height with the config
    inputs.targetPositionMeters = motor.getMechanismPositionSetpoint()
        .map(a -> motor.getConfig().convertFromMechanism(a).in(Meters)).orElse(0.0);
  }

  @Override
  public void setTargetHeight(Distance height) {
    // Use SmartMotorController's setPosition method with Distance
    motor.setPosition(height);
  }

  @Override
  public void stop() {
    motor.setVoltage(Volts.of(0));
  }
  
  /** Access the Elevator mechanism for command helpers like run() and runTo() */
  public Elevator getElevator() {
    return elevator;
  }

  @Override
  public void simIterate() {
    elevator.simIterate();
  }

  @Override
  public void updateTelemetry() {
    elevator.updateTelemetry();
  }
}
```

## Shooter (FlyWheel) IO implementation (works for real and sim)

```java
package first.robot.subsystems.akit;

import static org.wpilib.units.Units.*;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.units.measure.AngularVelocity;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.FlyWheelConfig;
import yams.commands2.mechanisms.FlyWheel;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.remote.TalonFXWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

/**
 * Single IO implementation - uses YAMS FlyWheel mechanism with SmartMotorController telemetry.
 */
public class ShooterIOTalonFX implements ShooterIO {

  private static final int CAN_ID = 3;

  private final FlyWheel flywheel;
  private final SmartMotorController motor;

  public ShooterIOTalonFX(SubsystemBase subsystem) {
    TalonFX talonFX = new TalonFX(CAN_ID, new CANBus(CANPort.CAN_S0));
    
    // Step 1: Create SmartMotorControllerConfig
    SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(subsystem)
        .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))  // Direct drive
        .withClosedLoopController(0.5, 0, 0)
        .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0.01));
    
    // Step 2: Create SmartMotorController (TalonFXWrapper)
    SmartMotorController smc = new TalonFXWrapper(talonFX, DCMotor.getKrakenX60(1), smcConfig);
    
    // Step 3: Create FlyWheelConfig
    FlyWheelConfig flywheelConfig = new FlyWheelConfig()
        .withDiameter(Inches.of(4))              // Flywheel diameter
        .withTelemetry("Shooter", TelemetryVerbosity.HIGH);
    
    // Step 4: Create FlyWheel mechanism, simulation is handled automatically
    this.flywheel = new FlyWheel(flywheelConfig, smc);
    
    // Get reference to underlying SmartMotorController for telemetry
    this.motor = flywheel.getMotor();
  }

  @Override
  public void updateInputs(ShooterIOInputs inputs) {
    // Pull telemetry data from the underlying SmartMotorController
    inputs.velocityRotationsPerSec = motor.getMechanismVelocity().in(RotationsPerSecond);
    inputs.appliedVolts = motor.getVoltage().in(Volts);
    inputs.supplyCurrentAmps = motor.getSupplyCurrent().map(c -> c.in(Amps)).orElse(0.0);
    inputs.statorCurrentAmps = motor.getStatorCurrent().in(Amps);
    inputs.temperatureCelsius = motor.getTemperature().in(Celsius);
    inputs.targetVelocityRotationsPerSec = motor.getMechanismSetpointVelocity()
        .map(v -> v.in(RotationsPerSecond)).orElse(0.0);
  }

  @Override
  public void setTargetVelocity(AngularVelocity velocity) {
    // Use SmartMotorController's setVelocity method
    motor.setVelocity(velocity);
  }

  @Override
  public void stop() {
    motor.setVoltage(Volts.of(0));
  }
  
  /** Access the FlyWheel mechanism for command helpers like run() and runTo() */
  public FlyWheel getFlyWheel() {
    return flywheel;
  }

  @Override
  public void simIterate() {
    flywheel.simIterate();
  }

  @Override
  public void updateTelemetry() {
    flywheel.updateTelemetry();
  }
}
```

{% hint style="success" %}
**Why this works**: YAMS's passive simulation is built into every wrapper. When `Robot.isSimulation()` is true, the `TalonFXWrapper` (and all other wrappers) automatically uses the `DCMotor`, gearing, and mass/MOI you provided to simulate physics. You get accurate simulation without writing any simulation-specific code.
{% endhint %}

**Check:** the project builds. Nothing runs yet: no subsystem creates these classes until the next step.

Next: [Steps 3 and 4: The subsystem and RobotContainer](/documentation/tutorials/advantagekit-integration/subsystem-and-robotcontainer)


# Steps 3 and 4: The subsystem and RobotContainer

## Step 3: Create the subsystem

The subsystem uses the IO interface and doesn't know whether it's running on real hardware or in simulation. It builds its own IO class: the IO class needs the subsystem for its `SmartMotorControllerConfig`, and the subsystem does not exist yet while `RobotContainer` is still creating it. So the constructor takes a factory, a function that builds the IO class from the subsystem, such as `ArmIOTalonFX::new`.

```java
package first.robot.subsystems.akit;

import static org.wpilib.units.Units.*;

import java.util.function.Function;
import org.wpilib.command2.Command;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.units.measure.Angle;
import org.littletonrobotics.junction.Logger;

public class ArmSubsystem extends SubsystemBase {

  private final ArmIO io;
  private final ArmIOInputsAutoLogged inputs = new ArmIOInputsAutoLogged();

  /**
   * @param ioFactory Builds the IO class for this subsystem, for example ArmIOTalonFX::new.
   *                  The subsystem passes itself in, because the IO class's
   *                  SmartMotorControllerConfig needs the subsystem.
   */
  public ArmSubsystem(Function<SubsystemBase, ArmIO> ioFactory) {
    this.io = ioFactory.apply(this);
  }

  @Override
  public void periodic() {
    // Update the arm's telemetry
    io.updateTelemetry();
    // Update and log inputs every cycle
    io.updateInputs(inputs);
    Logger.processInputs("Arm", inputs);
  }

  @Override
  public void simulationPeriodic() {
    io.simIterate();
  }

  /**
   * Command to move the arm to a target angle and hold it.
   * This command does not end on its own.
   */
  public Command setAngle(Angle angle) {
    return run(() -> io.setTargetAngle(angle))
        .withName("Arm.setAngle(" + angle + ")");
  }

  /**
   * Command to move the arm to a target angle and finish when reached.
   * Be careful with default commands, see the hint below.
   */
  public Command goToAngle(Angle angle, Angle tolerance) {
    return run(() -> io.setTargetAngle(angle))
        .until(() -> isNear(angle, tolerance))
        .withName("Arm.goToAngle(" + angle + ")");
  }

  /** Returns true if the logged arm position is within tolerance of a target, using WPILib's isNear(). */
  public boolean isNear(Angle target, Angle tolerance) {
    return getAngle().isNear(target, tolerance);
  }

  /** The logged arm position, so it replays correctly. */
  public Angle getAngle() {
    return Rotations.of(inputs.positionRotations);
  }

  /** Command to stop the arm. */
  public Command stop() {
    return runOnce(() -> io.stop()).withName("Arm.stop");
  }

}
```

{% hint style="warning" %}
See [When mechanism commands end](/documentation/understanding/run-vs-runto) for important information about when commands end and how that interacts with default commands.
{% endhint %}

## Step 4: Wire it up in RobotContainer

With YAMS's passive simulation, you don't need conditional logic for real vs sim. The same IO class works for both.

```java
package first.robot;

import static org.wpilib.units.Units.Degrees;

import org.wpilib.command2.button.CommandNiDsXboxController;
import first.robot.subsystems.akit.ArmIOTalonFX;
import first.robot.subsystems.akit.ArmSubsystem;

public class RobotContainer {

  // Same IO class for the real robot and simulation. YAMS handles the difference.
  private final ArmSubsystem arm = new ArmSubsystem(ArmIOTalonFX::new);

  private final CommandNiDsXboxController controller = new CommandNiDsXboxController(0);

  public RobotContainer() {
    configureBindings();
  }

  private void configureBindings() {
    // Commands work identically on the real robot and in simulation
    controller.a().whileTrue(arm.setAngle(Degrees.of(45)));
    controller.b().whileTrue(arm.setAngle(Degrees.of(-45)));
  }
}
```

The elevator and shooter follow the same pattern: an `ElevatorSubsystem` and a `ShooterSubsystem` that take `Function<SubsystemBase, ElevatorIO>` and `Function<SubsystemBase, ShooterIO>`, log their inputs in `periodic()`, and have command methods that take a `Distance` and an `AngularVelocity`. Create them with `new ElevatorSubsystem(ElevatorIOTalonFX::new)` and `new ShooterSubsystem(ShooterIOTalonFX::new)`.

**Check:** run the code in simulation and hold A. The arm swings to 45 degrees on the simulation's `Mechanism2d`, and in AdvantageScope `AdvantageKit/Arm/positionRotations` rises to about `0.125`.

**If it did not work:**

* **`ArmIOInputsAutoLogged` cannot be found:** the AutoLog code generator is not set up. See [Step 0](/documentation/tutorials/advantagekit-integration/setup).
* **Nothing is logged under `Arm`:** `Robot` does not call `Logger.start()`, or it is not a `LoggedRobot`. See [Step 0](/documentation/tutorials/advantagekit-integration/setup).
* **The arm does not move:** check the hard limits in `ArmIOTalonFX` allow 45 degrees (the example's are ±0.3 rotations, about ±108 degrees).

{% hint style="info" %}
**Compare to Traditional AdvantageKit**: Without YAMS, you'd need separate `ArmIOReal` and `ArmIOSim` classes with duplicate configuration. YAMS eliminates this duplication entirely.
{% endhint %}

Next: [Log replay](/documentation/tutorials/advantagekit-integration/log-replay)


# Log replay

## Log replay mode

For [log replay](https://docs.advantagekit.org/getting-started/what-is-advantagekit), AdvantageKit provides a "replay" mode where inputs are read from a log file instead of hardware. This is the **one case** where you need a separate IO implementation: an empty one that does nothing.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-bbce743f274fdb3256742cf7d19c4a061e493885%2Fakit-loop-live-and-replay.gif?alt=media" alt="Animation of one loop of the robot shown twice. On the real robot and in simulation, the IO class reads the YAMS arm into the inputs, the inputs are written to the log, the subsystem logic runs on them, and its setpoint goes back through the IO class to the YAMS arm. In log replay the inputs come from the log file, the same subsystem logic runs on them, and the outputs go to an empty replay IO class that drops them."><figcaption><p>In replay the inputs come from the log, and the empty IO class drops the outputs.</p></figcaption></figure>

```java
package first.robot.subsystems.akit;

/**
 * Empty IO implementation for log replay.
 * AdvantageKit replays the logged inputs, so no hardware interaction needed.
 */
public class ArmIOReplay implements ArmIO {
  // All methods use default implementations (do nothing)
  // AdvantageKit will inject the logged values into inputs
}
```

In RobotContainer, only check for replay mode. `Robot.currentMode` comes from [Step 0](/documentation/tutorials/advantagekit-integration/setup):

```java
package first.robot;

import first.robot.subsystems.akit.ArmIOReplay;
import first.robot.subsystems.akit.ArmIOTalonFX;
import first.robot.subsystems.akit.ArmSubsystem;

public class RobotContainer {

  // Replay mode: the empty IO class, AdvantageKit fills the inputs from the log.
  // Real AND sim: the same IO class works for both.
  private final ArmSubsystem arm = new ArmSubsystem(
      Robot.currentMode == Robot.Mode.REPLAY ? subsystem -> new ArmIOReplay() : ArmIOTalonFX::new);

  // The elevator and shooter follow the same pattern with ElevatorIOReplay and ShooterIOReplay.
}
```

To replay a log, set `simMode` in `Robot` to `Mode.REPLAY` and run the simulation. `LogFileUtil.findReplayLog()` uses the log open in AdvantageScope, or asks you for one. See [How To: Traditional Replay](https://docs.advantagekit.org/getting-started/traditional-replay) in the AdvantageKit docs.

**Check:** a new log file ending in `_sim` appears next to the one you replayed. Open both in AdvantageScope: `Arm/positionRotations` is the same in both.

{% hint style="success" %}
**Summary**: With YAMS + AdvantageKit, you only need **2 IO classes** per mechanism:

1. **One real IO class** (e.g., `ArmIOTalonFX`): works for both real robot and simulation
2. **One empty replay IO class** (e.g., `ArmIOReplay`): for log replay only

Compare this to traditional AdvantageKit which requires **3 IO classes** (Real, Sim, Replay).
{% endhint %}

## Pattern summary: mechanism classes with SmartMotorController telemetry

The examples in this tutorial demonstrate the recommended pattern for using YAMS with AdvantageKit:

1. **Create Mechanism classes** (`Arm`, `Elevator`, `FlyWheel`, etc.) for high-level control
2. **Get the underlying `SmartMotorController`** via `mechanism.getMotor()`
3. **Pull telemetry from `SmartMotorController`** for AdvantageKit logging
4. **Send setpoints with the `SmartMotorController`**, such as `motor.setPosition(angle)` or `motor.setVelocity(velocity)`, as the IO classes in [Step 2](/documentation/tutorials/advantagekit-integration/io-implementation) do
5. **Optionally expose the Mechanism** via a getter for command helpers like `run()` and `runTo()`

This pattern gives you the best of both worlds:

* **Mechanism classes** provide convenient configuration and command helpers
* **SmartMotorController** provides detailed telemetry for AdvantageKit logging
* **Passive simulation** works automatically in both

{% hint style="info" %}
See the YAMS AdvantageKit examples for complete robot projects that log YAMS mechanisms with AdvantageKit: [Commands v2](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands2/advantage_kit) and [Commands v3](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands3/advantage_kit).
{% endhint %}

### Using WPILib's isNear() for tolerance checking

When checking if a mechanism is at its target, use the `isNear()` method from WPILib's unit classes (`Angle`, `Distance`, `AngularVelocity`):

```java
// In your subsystem, check if the logged position is near the target
Angle currentPosition = Rotations.of(inputs.positionRotations);
Angle targetPosition = Degrees.of(45);
Angle tolerance = Degrees.of(2);

boolean atTarget = currentPosition.isNear(targetPosition, tolerance);
```

This approach works with any unit type and handles conversions automatically.

To get a `Trigger` instead of a `boolean`, build it from the logged value so replay sees the same result. This is what the Commands v3 AdvantageKit example does in `ArmMechanism`:

```java
public Trigger near(Angle angle, Angle within) {
  return new Trigger(() -> getAngle().isNear(angle, within));
}
```

{% hint style="info" %}
YAMS mechanisms have their own `near(...)` Trigger factory (renamed from `isNear(...)`, the boolean check is still `isNear(...)`). Those read the live `SmartMotorController`, not your logged inputs, so prefer the logged value when the result must be replayed.
{% endhint %}

Next: [Swerve drive with AdvantageKit](/documentation/tutorials/advantagekit-integration/swerve-drive)


# Swerve drive with AdvantageKit

YAMS swerve integrates seamlessly with AdvantageKit. Here's a complete example based on the official YAMS AdvantageKit swerve examples ([Commands v2 `SwerveSubsystem`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/advantage_kit/java/first/robot/subsystems/SwerveSubsystem.java), [Commands v3 `SwerveMechanism`](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/advantage_kit/java/first/robot/mechanisms/SwerveMechanism.java)):

{% hint style="info" %}
WPILib 2027 renamed the swerve kinematics types: `ChassisSpeeds` is now `ChassisVelocities` and `SwerveModuleState` is now `SwerveModuleVelocity`. The YAMS swerve API uses the new names.
{% endhint %}

```java
package first.robot.subsystems;

import static org.wpilib.units.Units.*;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.CANcoder;
import com.ctre.phoenix6.hardware.Pigeon2;
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import com.revrobotics.util.CANPorts;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.PIDController;
import org.wpilib.math.geometry.Pose2d;
import org.wpilib.math.geometry.Rotation2d;
import org.wpilib.math.geometry.Rotation3d;
import org.wpilib.math.geometry.Translation2d;
import org.wpilib.math.kinematics.ChassisVelocities;
import org.wpilib.math.kinematics.SwerveModulePosition;
import org.wpilib.math.kinematics.SwerveModuleVelocity;
import org.wpilib.math.system.DCMotor;
import org.wpilib.units.measure.Angle;
import org.wpilib.units.measure.AngularVelocity;
import org.wpilib.units.measure.LinearVelocity;
import org.wpilib.command2.Command;
import org.wpilib.command2.SubsystemBase;
import java.util.function.DoubleSupplier;
import java.util.function.Supplier;
import org.littletonrobotics.junction.AutoLog;
import org.littletonrobotics.junction.Logger;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.config.SwerveDriveConfig;
import yams.commands2.swerve.SwerveDrive;
import yams.commands2.swerve.SwerveInputStream;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.SwerveModuleConfig;
import yams.core.mechanisms.swerve.SwerveModule;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class SwerveSubsystem extends SubsystemBase {

  private AngularVelocity maxAngularVelocity = DegreesPerSecond.of(720);
  private LinearVelocity maxLinearVelocity = MetersPerSecond.of(4);
  private Supplier<Angle> gyroAngleSupplier;
  private SwerveDriveConfig config;

  /** AdvantageKit inputs for the swerve drive */
  @AutoLog
  public static class SwerveInputs {
    public SwerveModulePosition[] positions = new SwerveModulePosition[4];
    public SwerveModuleVelocity[] states = new SwerveModuleVelocity[4];
    public Angle gyroRotation = Degrees.of(0);
    public ChassisVelocities robotRelativeSpeeds = new ChassisVelocities(0, 0, 0);
    public Pose2d estimatedPose = new Pose2d(0, 0, Rotation2d.fromDegrees(0));
  }

  private final SwerveInputsAutoLogged swerveInputs = new SwerveInputsAutoLogged();
  private final SwerveDrive drive;

  public SwerveModule createModule(SparkMax driveMotor, SparkMax azimuthMotor,
      CANcoder absoluteEncoder, String moduleName, Translation2d location) {

    MechanismGearing driveGearing = new MechanismGearing(GearBox.fromStages("12:1", "2:1"));
    MechanismGearing azimuthGearing = new MechanismGearing(GearBox.fromStages("21:1"));

    SmartMotorControllerConfig driveCfg = new SmartMotorControllerConfig(this)
        .withWheelDiameter(Inches.of(4))
        .withClosedLoopController(50, 0, 4)
        .withGearing(driveGearing)
        .withStatorCurrentLimit(Amps.of(40))
        .withTelemetry("driveMotor", TelemetryVerbosity.HIGH);

    SmartMotorControllerConfig azimuthCfg = new SmartMotorControllerConfig(this)
        .withClosedLoopController(50, 0, 4)
        .withContinuousWrapping(Radians.of(-Math.PI), Radians.of(Math.PI))
        .withGearing(azimuthGearing)
        .withStatorCurrentLimit(Amps.of(20))
        .withTelemetry("angleMotor", TelemetryVerbosity.HIGH);

    SmartMotorController driveSMC = new SparkWrapper(driveMotor, DCMotor.getNEO(1), driveCfg);
    SmartMotorController azimuthSMC = new SparkWrapper(azimuthMotor, DCMotor.getNEO(1), azimuthCfg);

    SwerveModuleConfig moduleConfig = new SwerveModuleConfig(driveSMC, azimuthSMC)
        .withAbsoluteEncoder(absoluteEncoder.getAbsolutePosition().asSupplier())
        .withTelemetry(moduleName, TelemetryVerbosity.HIGH)
        .withLocation(location)
        .withOptimization(true);

    return new SwerveModule(moduleConfig);
  }

  public SwerveInputStream getChassisSpeedsSupplier(DoubleSupplier x, DoubleSupplier y,
      DoubleSupplier rot) {
    return SwerveInputStream.of(drive, x, y, rot)
        .withMaximumAngularVelocity(maxAngularVelocity)
        .withMaximumLinearVelocity(maxLinearVelocity)
        .withDeadband(0.01)
        .withCubeRotationControllerAxis()
        .withCubeTranslationControllerAxis()
        .withAllianceRelativeControl();
  }

  public SwerveSubsystem() {
    Pigeon2 gyro = new Pigeon2(14, new CANBus(CANPort.CAN_S0));
    gyroAngleSupplier = gyro.getYaw().asSupplier();

    var fl = createModule(new SparkMax(CANPorts.fromBusId(1), 1, MotorType.kBrushless),
        new SparkMax(CANPorts.fromBusId(1), 2, MotorType.kBrushless),
        new CANcoder(3, new CANBus(CANPort.CAN_S0)),
        "frontleft", new Translation2d(Inches.of(12), Inches.of(12)));
    var fr = createModule(new SparkMax(CANPorts.fromBusId(1), 4, MotorType.kBrushless),
        new SparkMax(CANPorts.fromBusId(1), 5, MotorType.kBrushless),
        new CANcoder(6, new CANBus(CANPort.CAN_S0)),
        "frontright", new Translation2d(Inches.of(12), Inches.of(-12)));
    var bl = createModule(new SparkMax(CANPorts.fromBusId(1), 7, MotorType.kBrushless),
        new SparkMax(CANPorts.fromBusId(1), 8, MotorType.kBrushless),
        new CANcoder(9, new CANBus(CANPort.CAN_S0)),
        "backleft", new Translation2d(Inches.of(-12), Inches.of(12)));
    var br = createModule(new SparkMax(CANPorts.fromBusId(1), 10, MotorType.kBrushless),
        new SparkMax(CANPorts.fromBusId(1), 11, MotorType.kBrushless),
        new CANcoder(12, new CANBus(CANPort.CAN_S0)),
        "backright", new Translation2d(Inches.of(-12), Inches.of(-12)));

    config = new SwerveDriveConfig(this, fl, fr, bl, br)
        // The gyro supplier returns a Rotation3d built from the LOGGED yaw, so replay is deterministic
        .withGyro(() -> new Rotation3d(getGyroAngle()))
        .withStartingPose(swerveInputs.estimatedPose)
        .withTranslationController(new PIDController(1, 0, 0))
        .withRotationController(new PIDController(1, 0, 0));

    drive = new SwerveDrive(config);
  }

  private Rotation2d getGyroAngle() {
    return new Rotation2d(swerveInputs.gyroRotation);
  }

  private void updateInputs() {
    swerveInputs.estimatedPose = drive.getPose();
    swerveInputs.states = drive.getModuleStates();
    swerveInputs.positions = drive.getModulePositions();
    swerveInputs.robotRelativeSpeeds = drive.getRobotRelativeSpeed();
    swerveInputs.gyroRotation = gyroAngleSupplier.get();
  }

  /** Drive with field relative speeds (e.g. from a SwerveInputStream) using the logged gyro angle. */
  public Command setFieldRelativeChassisSpeeds(Supplier<ChassisVelocities> fieldRelativeSpeeds) {
    return run(() -> setRobotRelativeChassisSpeedsSetpoint(
        fieldRelativeSpeeds.get().toRobotRelative(getGyroAngle())))
        .withName("Set Field Relative Chassis Speeds Supplier");
  }

  private void setRobotRelativeChassisSpeedsSetpoint(ChassisVelocities speeds) {
    Logger.recordOutput("Swerve/DesiredChassisSpeeds", speeds);
    SwerveModuleVelocity[] states = drive.getStateFromRobotRelativeChassisSpeeds(speeds);
    Logger.recordOutput("Swerve/DesiredStates", states);
    drive.setSwerveModuleStates(states);
  }

  /** PID drive to a pose using the logged pose and gyro angle, so replay follows the same path. */
  public Command driveToPose(Pose2d pose) {
    return startRun(() -> {
      drive.resetTranslationPID();
      drive.resetRotationPID();
    }, () -> drive.setRobotRelativeChassisSpeeds(
        drive.driveToPoseSetpoint(pose, getPose(), getGyroAngle())))
        .withName("Drive to Pose");
  }

  /** Point every module at its corner (X pattern) without driving it, logging the desired states. */
  public Command lock() {
    return run(() -> {
      SwerveModule[] modules = config.getModules();
      SwerveModuleVelocity[] desiredStates = new SwerveModuleVelocity[modules.length];
      for (int i = 0; i < modules.length; i++) {
        // Each module points at its own corner, which makes the X.
        // setAzimuthAngle turns the wheel without driving it and returns the state it set.
        // A zero speed state through setSwerveModuleStates would be held where the wheel is
        // by the velocity deadband.
        desiredStates[i] = modules[i].setAzimuthAngle(
            modules[i].getConfig().getLocation().orElseThrow().getAngle().orElse(Rotation2d.ZERO));
      }
      Logger.recordOutput("Swerve/DesiredStates", desiredStates);
    }).withName("Lock");
  }

  public Pose2d getPose() { return swerveInputs.estimatedPose; }
  public ChassisVelocities getRobotRelativeSpeeds() { return swerveInputs.robotRelativeSpeeds; }

  @Override
  public void periodic() {
    drive.updateTelemetry();  // Updates pose estimator, call BEFORE updateInputs
    updateInputs();
    Logger.processInputs("Swerve", swerveInputs);
  }

  @Override
  public void simulationPeriodic() {
    drive.simIterate();
  }
}
```

The `SwerveInputStream` output is field relative, so bind it through `setFieldRelativeChassisSpeeds`. `withTelemetry(...)` on the stream publishes its mode and configuration, and at `HIGH` adds a `Live Tuning` command (see [SwerveInputStream](/documentation/reference/swerve-input-stream)):

```java
// In RobotContainer
drive.setDefaultCommand(drive.setFieldRelativeChassisSpeeds(
    drive.getChassisSpeedsSupplier(() -> -xboxController.getLeftY(),
                                   () -> -xboxController.getLeftX(),
                                   () -> -xboxController.getRightX())
         .withTelemetry("Driver", TelemetryVerbosity.HIGH)));
```

{% hint style="warning" %}
`SwerveDrive.lockPose()` turns every module to its corner (the X pattern) with zero drive speed, but it is marked as not compatible with AdvantageKit. The YAMS AdvantageKit example builds the same X pattern itself in `lock()`, turning each module with `SwerveModule.setAzimuthAngle(...)` so the [velocity deadband](/documentation/understanding/swerve-drive/swerve-module#velocity-deadband) doesn't hold the wheels where they are, and the desired states are recorded with `Logger.recordOutput()` like every other drive command.
{% endhint %}

**Check:** run the code in simulation and drive with the left stick. In AdvantageScope, `AdvantageKit/Swerve/estimatedPose` on a 2D field moves with the robot, and `AdvantageKit/RealOutputs/Swerve/DesiredStates` changes as you drive.

## Commands v3

The [Commands v3 AdvantageKit example](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands3/advantage_kit) uses the same inputs class and module setup, with these differences:

* The class implements `org.wpilib.command3.Mechanism` instead of extending `SubsystemBase`, and imports `yams.commands3.config.SmartMotorControllerConfig`, `yams.commands3.config.SwerveDriveConfig`, `yams.commands3.swerve.SwerveDrive` and `yams.commands3.swerve.SwerveInputStream`.
* Commands are coroutines (`while (true)` + `coroutine.yield()`).
* `periodic()` and `simulationPeriodic()` are plain methods that `Robot.robotPeriodic()` and `Robot.simulationPeriodic()` call before `scheduler.run()`.
* The teleop opmode creates the `SwerveInputStream` and hands it to the drive mechanism.

```java
// SwerveMechanism
private SwerveInputStream inputStream;

public Command driveInputStream() {
  return run(coroutine -> {
    while (true) {
      setFieldRelativeChassisSpeeds(inputStream.get());
      coroutine.yield();
    }
  }).named("Swerve Drive Input Stream");
}

public void setInputStream(SwerveInputStream inputStream) {
  // Stop publishing the old stream's telemetry before replacing it
  if (this.inputStream != null) {
    this.inputStream.getTelemetry().ifPresent(SwerveInputStreamTelemetry::close);
  }
  this.inputStream = inputStream;
}

public SwerveDrive getSwerveDrive() {
  return drive;
}
```

```java
// AngularVelocityTeleop, created from Robot.teleopInit()
robot.drive.setInputStream(SwerveInputStream.of(
        robot.drive.getSwerveDrive(),
        () -> -controller.getLeftY(),
        () -> -controller.getLeftX(),
        () -> -controller.getRightX())
    .withDeadband(0.01)
    .withCubeRotationControllerAxis()
    .withCubeTranslationControllerAxis()
    .withAllianceRelativeControl()
    .withTelemetry("Driver", TelemetryVerbosity.HIGH));
robot.drive.setDefaultCommand(robot.drive.driveInputStream());
```

## Key points for swerve with AdvantageKit

1. **Create an `@AutoLog` inputs class** with module states, positions, gyro, and pose
2. **Call `updateTelemetry()` BEFORE `updateInputs()`**: the pose estimator and internal state update in `updateTelemetry()`
3. **Feed the gyro from the logged yaw** (`withGyro(() -> new Rotation3d(getGyroAngle()))`) so odometry is deterministic in replay
4. **Log desired states and speeds** using `Logger.recordOutput()` for replay debugging
5. **Call `simIterate()` in `simulationPeriodic()`** for physics simulation

{% hint style="warning" %}
**Important: Replay Data Scope**

During AdvantageKit log replay, **only data inside the `@AutoLog` inputs classes is mutated**. YAMS's built-in telemetry (published via `withTelemetry()`) is NOT affected by replay: it will show live simulation values, not replayed values.

This means:

* **Inputs you define** (in `SwerveInputs`, `ArmInputs`, etc.): replayed correctly
* **YAMS telemetry** (from `.withTelemetry("Arm")`): shows live sim values during replay

To ensure accurate replay debugging, always pull the data you need into your `@AutoLog` inputs class rather than relying on YAMS telemetry during replay.
{% endhint %}

Next: [Without an IO layer](/documentation/tutorials/advantagekit-integration/direct-subsystem)


# Without an IO layer

For simpler projects, you can use YAMS mechanisms directly as shown in the official examples ([Commands v2 subsystems](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands2/advantage_kit/java/first/robot/subsystems), [Commands v3 mechanisms](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands3/advantage_kit/java/first/robot/mechanisms)):

{% tabs %}
{% tab title="Commands v2" %}

```java
package first.robot.subsystems;

import static org.wpilib.units.Units.*;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.ArmFeedforward;
import org.wpilib.math.system.DCMotor;
import org.wpilib.units.measure.Angle;
import org.wpilib.units.measure.AngularVelocity;
import org.wpilib.units.measure.Current;
import org.wpilib.units.measure.Voltage;
import org.wpilib.command2.Command;
import org.wpilib.command2.SubsystemBase;
import org.littletonrobotics.junction.AutoLog;
import org.littletonrobotics.junction.Logger;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.mechanisms.Arm;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.ArmConfig;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.remote.TalonFXWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ArmSubsystem extends SubsystemBase {

  @AutoLog
  public static class ArmInputs {
    public Angle pivotPosition = Degrees.of(0);
    public AngularVelocity pivotVelocity = DegreesPerSecond.of(0);
    public Voltage pivotAppliedVolts = Volts.of(0);
    public Current pivotCurrent = Amps.of(0);
  }

  private final ArmInputsAutoLogged armInputs = new ArmInputsAutoLogged();
  private final SmartMotorController armSMC;
  private final Arm arm;

  public ArmSubsystem() {
    SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
        .withControlMode(ControlMode.CLOSED_LOOP)
        .withClosedLoopController(18, 0, 0.2)
        .withTrapezoidalProfile(DegreesPerSecond.of(458), DegreesPerSecondPerSecond.of(688))
        .withFeedforward(new ArmFeedforward(-0.1, 1.2, 0, 0))
        .withGearing(new MechanismGearing(GearBox.fromReductionStages(12.5, 1)))
        .withZeroPower(MotorMode.BRAKE)
        .withStatorCurrentLimit(Amps.of(120))
        .withStartingPosition(Degrees.of(141));

    armSMC = new TalonFXWrapper(new TalonFX(40, new CANBus(CANPort.CAN_S0)), DCMotor.getFalcon500(1), smcConfig);

    ArmConfig armCfg = new ArmConfig()
        .withHardLimits(Degrees.of(-25), Degrees.of(141))
        .withLength(Feet.of(14.0 / 12))
        .withTelemetry("Arm", TelemetryVerbosity.HIGH);

    arm = new Arm(armCfg, armSMC);
  }

  public void updateInputs() {
    armInputs.pivotPosition = arm.getAngle();
    armInputs.pivotVelocity = armSMC.getMechanismVelocity();
    armInputs.pivotAppliedVolts = armSMC.getVoltage();
    armInputs.pivotCurrent = armSMC.getStatorCurrent();
  }

  public Command setAngle(Angle angle) {
    return arm.setAngle(angle);
  }

  @Override
  public void periodic() {
    updateInputs();
    Logger.processInputs("Arm", armInputs);
    arm.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    arm.simIterate();
  }
}
```

{% endtab %}

{% tab title="Commands v3" %}
In Commands v3 the class implements `Mechanism`, imports the `yams.commands3` bindings, and `Robot` calls `periodic()` and `simulationPeriodic()` itself. The inputs, configuration and `updateInputs()` are the same as the Commands v2 tab.

```java
package first.robot.mechanisms;

// Same static units, CTRE, WPILib math/units, AdvantageKit and yams.core imports as Commands v2, plus:
import org.wpilib.command3.Command;
import org.wpilib.command3.Mechanism;
import org.wpilib.command3.Trigger;
import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.mechanisms.Arm;

public class ArmMechanism implements Mechanism {

  // ArmInputs, armInputs, smcConfig, armSMC, armCfg, arm and updateInputs() as in Commands v2

  public Command setAngle(Angle angle) {
    return arm.setAngle(angle);
  }

  /** Trigger built from the logged angle, so it replays correctly. */
  public Trigger near(Angle angle, Angle within) {
    return new Trigger(() -> armInputs.pivotPosition.isNear(angle, within));
  }

  public void periodic() {
    updateInputs();
    Logger.processInputs("Arm", armInputs);
    arm.updateTelemetry();
  }

  public void simulationPeriodic() {
    arm.simIterate();
  }
}
```

```java
// Robot.java (extends LoggedRobot)
@Override
public void robotPeriodic() {
  drive.periodic();
  arm.periodic();
  elevator.periodic();
  shooter.periodic();
  indexer.periodic();
  scheduler.run();
}

@Override
public void simulationPeriodic() {
  drive.simulationPeriodic();
  arm.simulationPeriodic();
  elevator.simulationPeriodic();
  shooter.simulationPeriodic();
  indexer.simulationPeriodic();
}
```

{% endtab %}
{% endtabs %}

This pattern is simpler and **does support log replay**, but with a key difference: during replay, the full YAMS simulation runs alongside the logged data. This means:

* **Pro**: You get full simulation behavior during replay, which can help debug physics-related issues
* **Con**: Replay requires more processing power since every `SmartMotorController` and Mechanism simulates its physics

Choose the IO layer pattern if you need lightweight replay; choose this direct pattern if you prefer simplicity and don't mind the extra processing during replay.

**Check:** run the code in simulation and command the arm. In AdvantageScope, `AdvantageKit/Arm/pivotPosition` follows the arm.

Back to [AdvantageKit integration](/documentation/tutorials/advantagekit-integration).


# Troubleshooting

What to check when a YAMS mechanism does not build, does not move, or moves the wrong way.

Find what you see, then work down its list. The first check is the most likely cause.

## It does not build

**`SmartMotorController`, `Arm` or another YAMS class cannot be found**

* YAMS is not installed. Install it as in [Create a project and install YAMS](/documentation/tutorials/project-setup#install-yams).
* Both YAMS vendordeps are installed. Install only one: Commands v2 or Commands v3. Remove the other from the `vendordeps` folder.
* The import is from the wrong command framework. Commands v2 code imports `yams.commands2`, and Commands v3 code imports `yams.commands3`.

**`SparkMax`, `TalonFX` or another vendor class cannot be found**

* The vendor's own library is not installed. YAMS drives the vendor's objects, so install REVLib, Phoenix 6 or the other vendor library too. See [Install your motor controller's library](/documentation/tutorials/project-setup#install-your-motor-controllers-library).

## It crashes when the code starts

Read the first error in the Driver Station or the simulation console. YAMS names the setting that is missing and the method that sets it.

| The error says                                         | Fix                                                                                            |
| ------------------------------------------------------ | ---------------------------------------------------------------------------------------------- |
| `Arm starting angle is empty`                          | Add `withStartingPosition(...)` to the `SmartMotorControllerConfig`.                           |
| `Arm starting angle is outside hard limits`            | Make the starting position fall between the `ArmConfig` hard limits.                           |
| `Arm Length is empty`, `Arm lower hard limit is empty` | Add `withLength(...)` and `withHardLimits(...)` to the `ArmConfig`. The simulation needs them. |
| An elevator, pivot or flywheel error                   | The same idea: the error names the method to add.                                              |

## I can't find the mechanism on the dashboard

* It is not under `SmartDashboard`. The simulated mechanism is at **NetworkTables > Mechanisms >&#x20;*****name*****&#x20;> mechanism**, where *name* is the name given to the mechanism config's `withTelemetry`, such as `Arm`.
* The motor's values are at `NT:/Mechanisms/<mechanism name>/<motor name>/`, such as `NT:/Mechanisms/Arm/ArmMotor/`.
* Nothing publishes until the mechanism's `updateTelemetry()` runs. Commands v2: check that the subsystem's `periodic()` calls it. Commands v3: check that the mechanism's `periodic()` calls it, and that `Robot.robotPeriodic()` calls the mechanism's `periodic()`. See [Step 2: The arm](/documentation/tutorials/arm/mechanism#update-it-every-loop).

## It does not move in simulation

* The robot is disabled. Press **Teleoperated** in the Sim GUI.
* The controller is not on port 0. Drag it from **System Joysticks** to **Joystick\[0]**.
* Commands v3: the wrong op mode is selected. Pick `ExampleTeleop`, where the buttons are bound.
* Commands v3: the mechanism's simulation never runs. Check that `Robot.simulationInit()` starts it with `startSimulation(...)`.
* Commands v2: check that `simulationPeriodic()` in the subsystem calls the mechanism's `simIterate()`.
* The setpoint is outside the soft limits. The closed loop holds a setpoint at the nearest soft limit, so a target past the limit never moves the mechanism further.

## It moves, but not as it should

**It falls, or a flywheel coasts down, while the robot is disabled**

* That is expected. A disabled robot's motors get no power, so the simulation gives them 0 V. When you enable, the closed loop starts from wherever the mechanism ended up.

**It sags below its setpoint, or an elevator drifts down**

* `kG` is 0. Tune it as in [Step 5: Tune it](/documentation/tutorials/arm/tune#kg-hold-the-arm-up).

**It stops short of its setpoint (a flywheel never reaches speed)**

* `kP` is too low, or a flywheel has no `kV`. A velocity loop needs `kV` to do most of the work.

**It swings back and forth, or rings around the setpoint**

* `kP` is too high. Lower it by about a third, then add a little `kD` if it still overshoots.

**It moves the wrong way, or runs straight into a hard stop**

* The motor direction is wrong. Check it with the robot disabled as in [Step 6: Run it on the robot](/documentation/tutorials/arm/robot#check-the-direction-with-the-robot-disabled), and set `withMotorInverted(true)` if positive is the wrong way.

**It goes the wrong distance**

* The gearing does not match the mechanism. List each stage from the motor outward, as in [Step 1](/documentation/tutorials/arm/motor-controller#gearing).
* For an elevator or a wheel, the circumference is wrong. See [How do I find my mechanism's circumference?](/documentation/how-to-motor-controllers-and-sensors/how-to-find-your-mechanism-circumference)

**Angles are off by the same amount every time**

* The mechanism was not at its starting position when the code started. Rest it there before the code starts, or change `withStartingPosition` to where it really rests.

**A command that should end never ends**

* `run(...)` never ends on its own: it holds the setpoint until another command takes over. Use `runTo(...)` with a tolerance to end once the mechanism gets there.
* The `runTo(...)` tolerance is too tight, or the setpoint is past a soft limit, so the mechanism never gets close enough. Widen the tolerance, or move the setpoint inside the limits.

## Live tuning does nothing

* AdvantageScope's **tuning mode** is off. Turn it on with the sliders icon beside the search box.
* The `Live Tuning` command is not running. It is at `NT:/Tuning/<subsystem or mechanism name>/Live Tuning`, such as `NT:/Tuning/ArmSubsystem/Live Tuning`. Start it again after pressing any of the mechanism's buttons, which take over from it.
* The value was typed under `NT:/Mechanisms`. Type values under `NT:/Tuning`. `NT:/Mechanisms` only shows what the mechanism is doing.
* The motor's telemetry is not `TelemetryVerbosity.HIGH`.
* The config has no subsystem (`new SmartMotorControllerConfig(this)` or `withSubsystem(...)`, Commands v2) or mechanism (`new SmartMotorControllerConfig(this)` or `withMechanism(...)`, Commands v3), so YAMS has nothing to register the `Live Tuning` command with.
* The values were lost after a restart. Copy them into your code, as in [Step 5](/documentation/tutorials/arm/tune#copy-the-numbers-into-your-code).

See [Live tuning](/documentation/how-to-tuning/live-tuning) for more.

## On the real robot

**Nothing moves, and the Driver Station shows a CAN error**

* The CAN ID in the code does not match the motor controller. Check it in the vendor's tool (REV Hardware Client or Phoenix Tuner X).
* Two devices share an ID, or the CAN wiring is loose.

**The robot browns out, or the mechanism slows down under load**

* The current limits are too high. See [Limiting power consumption](/documentation/how-to-motor-controllers-and-sensors/limiting-power-consumption).
* The motor is hot. Watch `motor/temperature`; a hot motor backs off and looks like a gain problem.

**It worked in simulation but not on the robot**

* The real robot uses `withClosedLoopController` and `withFeedforward`. The simulation uses the `withSim...` versions. Tune the robot separately, as in [Step 6](/documentation/tutorials/arm/robot#tune-it-on-the-robot).

## When tuning does not help

Some mechanisms cannot be tuned, because the motor does not have enough torque for the job. No gain fixes that, and it is worth recognizing early so you stop chasing numbers.

{% tabs %}
{% tab title="Elevator" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-ae3666e29e0b020988f2420e30728403ac788380%2Flive-tuning-underpowered.gif?alt=media" alt="Animation of a heavy elevator trying to reach a setpoint with kP at 5, then 20, then 80. All three attempts rise slowly and stall short of the setpoint, and the motor output voltage is pinned at 12 volts each time"><figcaption><p>Sixteen times the gain, the same move. Illustrative, not a recording.</p></figcaption></figure>

Raising kP does nothing, because the motor was already at full voltage with the smaller gain.
{% endtab %}

{% tab title="Arm" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d33db6eabae633bafc852237f6a276dfa828b729%2Flive-tuning-underpowered-arm.gif?alt=media" alt="Animation of an arm given three setpoints. At 75 degrees, nearly upright, it holds easily. At 58 degrees it holds with the voltage near the maximum. At 25 degrees it falls straight through the setpoint and comes to rest on its hard stop with the voltage pinned at 12 volts"><figcaption><p>The same arm at three setpoints. Illustrative, not a recording.</p></figcaption></figure>

An arm needs the most torque when it is level and almost none when it is upright. An underpowered arm therefore looks fine at some setpoints and hopeless at others. If it only misbehaves near level, suspect torque before you suspect the gains.
{% endtab %}

{% tab title="Flywheel" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-909a208aee93d981fbc924ba9d093bbede718d8f%2Flive-tuning-underpowered-flywheel.gif?alt=media" alt="Animation of a flywheel given three speed setpoints. It reaches 2000 RPM easily, reaches 4000 RPM slowly with the voltage at the maximum for the whole spin up, and never reaches 6000 RPM, levelling off near 4800 RPM with the voltage pinned"><figcaption><p>The same flywheel at three setpoints. Illustrative, not a recording.</p></figcaption></figure>

A flywheel has a top speed set by the motor, the gearing and the battery voltage. Below it everything works, and the closer the setpoint gets to it the longer the spin up takes. Above it, no gain will ever get there. Remember that the battery sags under load, so the top speed in a match is lower than on a fresh battery on the bench.
{% endtab %}
{% endtabs %}

### It works at low setpoints

This is what makes an underpowered mechanism hard to spot. It tunes well on the easy moves, and then the same gains fail on the hard ones:

| Mechanism | Works                                         | Fails                                                         |
| --------- | --------------------------------------------- | ------------------------------------------------------------- |
| Elevator  | Short moves, slow profiles, an empty carriage | Long fast moves, or carrying a game piece                     |
| Arm       | Setpoints near upright                        | Setpoints near level, where gravity pulls hardest             |
| Flywheel  | Low speeds                                    | Speeds near the motor's top speed, and recovery between shots |

When that happens, do not retune for the hard case. Look at `motor/outputVoltage` during the move that fails. If it is at the maximum, the gains are not the problem.

### How to recognize an underpowered mechanism

| Watch (`NT:/Mechanisms`)                       | What you see                                                                        |
| ---------------------------------------------- | ----------------------------------------------------------------------------------- |
| `motor/outputVoltage`                          | Pinned at the maximum for most of the move, not just at the start.                  |
| `current/stator`                               | Sitting on the stator current limit.                                                |
| `mechanism/position` or `measurement/position` | The same slow curve whatever you set kP to, and it may stop short of the setpoint.  |
| `mechanism/velocity` or `measurement/velocity` | Far below the profile's `closedloop/setpoint/velocity`, however the profile is set. |
| `motor/temperature`                            | Climbing quickly while the mechanism holds a position.                              |

### What to do about it

The fix is mechanical or electrical, not a gain:

* **More gear reduction.** The most common fix. It trades top speed, which you are not reaching anyway, for torque.
* **More motors**, or a stronger motor.
* **Take load off the motor**: a lighter mechanism, a counterweight, or a [constant force spring](/documentation/how-to-tuning/live-tuning#elevators-with-a-constant-force-spring) on an elevator.
* **Check the current limit.** A stator limit set too low makes a capable motor look underpowered. Raise `current/limit/stator` and see whether the move changes. See [How do I limit power consumption?](/documentation/how-to-motor-controllers-and-sensors/limiting-power-consumption).
* **Check for binding.** Disable the robot and move the mechanism by hand through its whole travel.
* **Ask for less.** Lower the motion profile's `maxVelocity` and `maxAcceleration` to what the motor can deliver.

{% hint style="info" %}
Check this in simulation first. With the real motor, gearing and mass in the config, an underpowered mechanism shows the same pinned voltage in simulation, before anything is built.
{% endhint %}

### It gets slower every time

An overworked motor heats up, and a hot motor is weaker. The first few moves look fine, then each one takes a little longer, until the mechanism stops reaching its setpoint at all.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-529c27be4be22d26df6fbd74f992845607fe5188%2Flive-tuning-overheating.gif?alt=media" alt="Animation of the same move repeated five times on an overworked motor. The time to reach the setpoint grows from 0.55 seconds to 1.40 seconds and on the fifth repeat it never arrives, while the stator current climbs from 28 amps to the 60 amp limit and the motor temperature rises to 225 degrees Fahrenheit"><figcaption><p>Five repeats of one move. Illustrative numbers.</p></figcaption></figure>

| Watch (`NT:/Mechanisms`)                       | What you see                                                         |
| ---------------------------------------------- | -------------------------------------------------------------------- |
| `current/stator`                               | Higher on every repeat of the same move, until it sits on the limit. |
| `motor/temperature`                            | Climbing steadily and not coming back down between moves.            |
| `mechanism/velocity` or `measurement/velocity` | The peak speed of the same move dropping over time.                  |
| `mechanism/position` or `measurement/position` | Arriving later each time, then stopping short.                       |

{% hint style="danger" %}
If the gains that worked ten minutes ago no longer work, check `motor/temperature` before you touch them. Retuning to a hot motor gives you gains that are wrong once it cools, and running it harder is how motors burn out. Stop, let it cool, and fix the load.
{% endhint %}


# How do I set an arm's target angle?

**Goal:** send your `Arm` to an angle from a button, an autonomous routine or your own code.

This page assumes you already have an `Arm` in a subsystem. If you do not, build one with the [Arm tutorial](/documentation/tutorials/arm) first; it ends with complete files you can copy.

YAMS drives the arm to a target with **closed loop** control: you give it an angle, and its controller keeps adjusting the voltage until the encoder says the arm is there. **Open loop** commands (`set` and `setVoltage`) send an output straight to the motor instead. [Open loop and closed loop](/documentation/tutorials/how-yams-drives-a-motor#open-loop-and-closed-loop) explains both.

An arm's target is an `Angle` (`org.wpilib.units.measure.Angle`), for example `Degrees.of(25)`. YAMS gives you three ways to set it:

| Use                                       | When                                                                    | Ends?                                                                         |
| ----------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `arm.run(angle)`                          | Hold an angle for as long as a button is held, or as a default command. | No. It runs until something interrupts it.                                    |
| `arm.runTo(angle, tolerance)`             | A step in a sequence or autonomous routine: go there, then move on.     | Yes, once the arm has stayed within `tolerance` of the angle for 0.1 seconds. |
| `arm.setMechanismPositionSetpoint(angle)` | Your own code, inside a command you already wrote.                      | It is a method, not a command. It sets the target once.                       |

All three start the closed loop controller again if an open loop command stopped it. [When mechanism commands end](/documentation/understanding/run-vs-runto) explains `run` and `runTo` with the default command.

## Add the commands to your subsystem

These methods go in the subsystem (Commands v2) or mechanism (Commands v3) that owns the `arm` field. They are fragments: the rest of the class is in the [Arm tutorial](/documentation/tutorials/arm/commands).

{% tabs %}
{% tab title="Commands v2" %}
{% code title="ExampleSubsystem.java (fragment)" %}

```java
/** Go to an angle and hold it. Never ends on its own. */
public Command run(Angle angle) {
  return arm.run(angle);
}

/** Go to an angle, then end once the arm is within tolerance. */
public Command runTo(Angle angle, Angle tolerance) {
  return arm.runTo(angle, tolerance);
}

/** Set the target from your own code. */
public void setAngleSetpoint(Angle angle) {
  arm.setMechanismPositionSetpoint(angle);
}
```

{% endcode %}
{% endtab %}

{% tab title="Commands v3" %}
{% code title="ExampleMechanism.java (fragment)" %}

```java
/** Go to an angle and hold it. Never ends on its own. */
public Command setAngle(Angle angle) {
  return arm.run(angle);
}

/** Go to an angle, then end once the arm is within tolerance. */
public Command moveTo(Angle angle, Angle tolerance) {
  return arm.runTo(angle, tolerance);
}

/** Hold an angle at the lowest priority, so any other command can take over. For the default command. */
public Command hold(Angle angle) {
  return run(coroutine -> coroutine.await(arm.run(angle)))
      .withPriority(Command.LOWEST_PRIORITY)
      .named("Arm Hold");
}

/** Set the target from your own code. */
public void setAngleSetpoint(Angle angle) {
  arm.setMechanismPositionSetpoint(angle);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ArmSubsystem.cpp (fragment)" %}

```cpp
// Go to an angle and hold it. Never ends on its own.
wpi::cmd::CommandPtr ArmSubsystem::Run(wpi::units::degree_t angle) {
  return m_arm->Run(angle);
}

// Go to an angle, then end once the arm is within tolerance.
wpi::cmd::CommandPtr ArmSubsystem::RunTo(wpi::units::degree_t angle, wpi::units::degree_t tolerance) {
  return m_arm->RunTo(angle, tolerance);
}

// Set the target from your own code.
void ArmSubsystem::SetAngleSetpoint(wpi::units::degree_t angle) {
  m_arm->SetMechanismPositionSetpoint(angle);
}
```

{% endcode %}

Declare the three in `ArmSubsystem.hpp`, as the [Arm tutorial](/documentation/tutorials/arm/commands) does for `Run` and `RunTo`.
{% endtab %}
{% endtabs %}

## Bind them to buttons

Every target must be inside your soft limits. The [Arm tutorial](/documentation/tutorials/arm/motor-controller) sets `.withSoftLimits(Degrees.of(-20), Degrees.of(30))` in the `SmartMotorControllerConfig`, so -5 and 25 degrees are both reachable.

{% tabs %}
{% tab title="Commands v2" %}
{% code title="RobotContainer.java (fragment)" %}

```java
// Hold the arm at 0 degrees when nothing else is using it.
m_exampleSubsystem.setDefaultCommand(m_exampleSubsystem.run(Degrees.of(0)));

// Hold -5 or 25 degrees while A or B is held.
m_driverController.a().whileTrue(m_exampleSubsystem.run(Degrees.of(-5)));
m_driverController.b().whileTrue(m_exampleSubsystem.run(Degrees.of(25)));

// Go to 25 degrees, then (once within 2 degrees) do the next thing.
m_driverController.x().onTrue(
    m_exampleSubsystem.runTo(Degrees.of(25), Degrees.of(2))
        .andThen(Commands.print("Arm is at 25 degrees")));
```

{% endcode %}
{% endtab %}

{% tab title="Commands v3" %}
{% code title="ExampleTeleop.java (fragment)" %}

```java
// In Robot(): hold the arm at 0 degrees when nothing else is using it.
exampleMechanism.setDefaultCommand(exampleMechanism.hold(Degrees.of(0)));

// In the opmode constructor: hold -5 or 25 degrees while A or B is held.
controller.a().whileTrue(robot.exampleMechanism.setAngle(Degrees.of(-5)));
controller.b().whileTrue(robot.exampleMechanism.setAngle(Degrees.of(25)));

// Go to 25 degrees on a press of X. The command ends once the arm is within 2 degrees,
// and the default command takes over.
controller.x().onTrue(robot.exampleMechanism.moveTo(Degrees.of(25), Degrees.of(2)));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/RobotContainer.cpp (fragment)" %}

```cpp
// Hold the arm at 0 degrees when nothing else is using it.
arm.SetDefaultCommand(arm.Run(0_deg));

// Hold -5 or 25 degrees while A or B is held.
driverController.FaceDown().WhileTrue(arm.Run(-5_deg));
driverController.FaceRight().WhileTrue(arm.Run(25_deg));

// Go to 25 degrees on a press of X. The command ends once the arm is within 2 degrees.
driverController.FaceLeft().OnTrue(arm.RunTo(25_deg, 2_deg));
```

{% endcode %}
{% endtab %}
{% endtabs %}

In Commands v3 a `Mechanism` already has a `run(...)` method that takes a coroutine, so the wrappers are called `setAngle`, `moveTo` and `hold`, as in the tutorial.

If the target comes from a `Supplier<Angle>` (for example an aiming calculation), `run(supplier)` and `runTo(supplier, tolerance)` follow the supplier every loop. `runTo` ends once the arm has been within the tolerance of the supplier's current value for 0.1 seconds.

## Check it

1. Start the simulation (or enable the robot) and open **NetworkTables > Mechanisms > Arm > mechanism** in your dashboard. `Arm` is the name you gave `ArmConfig.withTelemetry`.
2. Hold B. The drawn arm should swing to 25 degrees and stay there.
3. Release B. The default command takes over and the arm returns to 0 degrees.

## If it did not work

* **The arm stops short of the target.** The target is outside your soft limits. YAMS clamps the setpoint to the nearest limit and prints a warning ("Setpoint is higher than Mechanism ... upper limit") in the Driver Station. Widen the soft limits or pick a target inside them. A `runTo` to a clamped target never ends, because the arm never gets within tolerance.
* **The arm sags below the target, or falls when you let go.** `kG` is still 0. The gains in the tutorial are placeholders; find `kG` and then `kP` with [Step 5: Tune it](/documentation/tutorials/arm/tune).
* **`runTo` never ends.** The tolerance is tighter than the arm can hold. Try 2 or 3 degrees, and tune `kP`.
* **Something else.** See [Troubleshooting](/documentation/tutorials/troubleshooting).

## Read more

Tune the arm so it reaches the target quickly and holds it: [Arm tutorial: Tune it](/documentation/tutorials/arm/tune).


# How do I set an elevator's target height?

**Goal:** send your `Elevator` to a height from a button, an autonomous routine or your own code.

This page assumes you already have an `Elevator` in a subsystem. If you do not, build one with the [Elevator tutorial](/documentation/tutorials/elevator) first; it ends with complete files you can copy.

An elevator works the same way as an arm: [How do I set an arm's target angle?](/documentation/how-to-mechanisms/how-to-set-an-arms-target-angle) explains `run`, `runTo` and the setpoint method, the default command and the Commands v3 names. This page covers only what differs.

## What differs from an arm

* **The target is a `Distance`** (`org.wpilib.units.measure.Distance`), such as `Meters.of(1)` or `Inches.of(30)`, not an `Angle`. The tolerance of `runTo` is a `Distance` too, such as `Centimeters.of(2)`.
* **The setpoint method is `setMeasurementPositionSetpoint(height)`**, the method for a distance, not `setMechanismPositionSetpoint`.
* **YAMS needs the drum or sprocket size** to turn meters into motor rotations: `withDrumRadius(...)` or `withMechanismCircumference(...)` in the `SmartMotorControllerConfig`. See [How do I tell YAMS my drum or sprocket size?](/documentation/how-to-motor-controllers-and-sensors/how-to-find-your-mechanism-circumference)
* **The carriage needs `kG` at every height,** since gravity pulls it down the same wherever it is, where an arm's `kG` is scaled by the cosine of its angle.

## Add the commands and bind them

The [Elevator tutorial](/documentation/tutorials/elevator/motor-controller) sets `.withSoftLimits(Meters.of(0), Meters.of(2))`, so every target here is between 0 and 2 meters.

{% tabs %}
{% tab title="Commands v2" %}
{% code title="ExampleSubsystem.java (fragment)" %}

```java
/** Go to a height and hold it. Never ends on its own. */
public Command run(Distance height) {
  return elevator.run(height);
}

/** Go to a height, then end once the carriage is within tolerance. */
public Command runTo(Distance height, Distance tolerance) {
  return elevator.runTo(height, tolerance);
}

/** Set the target from your own code. */
public void setHeightSetpoint(Distance height) {
  elevator.setMeasurementPositionSetpoint(height);
}
```

{% endcode %}

{% code title="RobotContainer.java (fragment)" %}

```java
m_exampleSubsystem.setDefaultCommand(m_exampleSubsystem.run(Meters.of(0)));
m_driverController.a().whileTrue(m_exampleSubsystem.run(Meters.of(0.5)));
m_driverController.b().whileTrue(m_exampleSubsystem.run(Meters.of(1)));
m_driverController.x().onTrue(m_exampleSubsystem.runTo(Meters.of(1), Centimeters.of(2)));
```

{% endcode %}
{% endtab %}

{% tab title="Commands v3" %}
{% code title="ExampleMechanism.java (fragment)" %}

```java
/** Go to a height and hold it. Never ends on its own. */
public Command setHeight(Distance height) {
  return elevator.run(height);
}

/** Go to a height, then end once the carriage is within tolerance. */
public Command moveTo(Distance height, Distance tolerance) {
  return elevator.runTo(height, tolerance);
}

/** Hold a height at the lowest priority, so any other command can take over. For the default command. */
public Command hold(Distance height) {
  return run(coroutine -> coroutine.await(elevator.run(height)))
      .withPriority(Command.LOWEST_PRIORITY)
      .named("Elevator Hold");
}

/** Set the target from your own code. */
public void setHeightSetpoint(Distance height) {
  elevator.setMeasurementPositionSetpoint(height);
}
```

{% endcode %}

{% code title="ExampleTeleop.java (fragment)" %}

```java
// In Robot():
exampleMechanism.setDefaultCommand(exampleMechanism.hold(Meters.of(0)));
// In the opmode constructor:
controller.a().whileTrue(robot.exampleMechanism.setHeight(Meters.of(0.5)));
controller.b().whileTrue(robot.exampleMechanism.setHeight(Meters.of(1)));
controller.x().onTrue(robot.exampleMechanism.moveTo(Meters.of(1), Centimeters.of(2)));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp (fragment)" %}

```cpp
wpi::cmd::CommandPtr ElevatorSubsystem::Run(wpi::units::meter_t height) {
  return m_elevator->Run(height);
}

wpi::cmd::CommandPtr ElevatorSubsystem::RunTo(wpi::units::meter_t height, wpi::units::meter_t tolerance) {
  return m_elevator->RunTo(height, tolerance);
}

void ElevatorSubsystem::SetHeightSetpoint(wpi::units::meter_t height) {
  m_elevator->SetMeasurementPositionSetpoint(height);
}
```

{% endcode %}

{% code title="cpp/RobotContainer.cpp (fragment)" %}

```cpp
elevator.SetDefaultCommand(elevator.Run(0_m));
driverController.FaceDown().WhileTrue(elevator.Run(0.5_m));
driverController.FaceRight().WhileTrue(elevator.Run(1_m));
driverController.FaceLeft().OnTrue(elevator.RunTo(1_m, 2_cm));
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Check it

1. Start the simulation (or enable the robot) and open **NetworkTables > Mechanisms > Elevator > mechanism** in your dashboard. `Elevator` is the name you gave `ElevatorConfig.withTelemetry`.
2. Hold B. The drawn carriage should rise to 1 meter and stay there.
3. Release B. The default command takes over and the carriage returns to the bottom.

## If it did not work

* **The carriage stops short of the target.** The target is outside your soft limits. YAMS clamps the setpoint to the nearest limit and prints a warning in the Driver Station. A `runTo` to a clamped target never ends.
* **The carriage sags below the target, or slides down when you let go.** `kG` is still 0. The tutorial's gains are placeholders. Find `kG` first (the voltage that holds the carriage still), then `kP`, with the [Elevator tutorial's Tune it step](/documentation/tutorials/elevator/tune).
* **The carriage goes to the wrong height, off by the same factor every time.** The drum radius, circumference or cascading stage count is wrong. See [How do I tell YAMS my drum or sprocket size?](/documentation/how-to-motor-controllers-and-sensors/how-to-find-your-mechanism-circumference)
* **Something else.** See [Troubleshooting](/documentation/tutorials/troubleshooting).


# How do I shoot with a shooter?

**Goal:** hold a button to spin the shooter up, and have the feeder push the game piece in only once the wheel is at speed.

A shot has three parts:

1. **Spin up:** the shooter `FlyWheel` goes to a speed and holds it.
2. **Wait for speed:** a `Trigger` turns true once the wheel has been near that speed for 0.1 seconds.
3. **Feed:** the feeder `FlyWheel` pushes the game piece into the wheel while the trigger is true.

**Before you start:** build the shooter as in the [Shooter/FlyWheels tutorial](/documentation/tutorials/shooter-flywheels), and a feeder the same way as the intake in [How do I set up an intake roller?](/documentation/how-to-mechanisms/how-do-i-set-up-an-intake-roller), with its `intake()` command renamed `feed()`. The feeder keeps the intake's default command that stops it: `stop()` in Commands v2, `idle()` in Commands v3. The shooter and the feeder are separate subsystems, one YAMS mechanism each, so each can run its own command at the same time.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b7c09583292da1d92654951d57a0bdc8f656350d%2Fhowto-shooter-at-speed.gif?alt=media" alt="Animation of a flywheel spinning up to 3000 RPM and shooting two balls, with a band of 100 RPM around the setpoint. Each shot drops the speed by several hundred RPM, and it overshoots and rings as it recovers. A lane for the at speed trigger is true inside the band, including for an instant each time the speed passes through it. A lane for the feeder, which uses the trigger with a 0.1 second debounce, is only true once the speed has stayed in the band, so the second ball is not fed until the wheel has settled."><figcaption><p>Each shot slows the wheel and it rings as it recovers. The tolerance band and a debounce keep the feeder off until it has settled.</p></figcaption></figure>

{% stepper %}
{% step %}

### Spin up

Use the tutorial's shooter config as it is. Its gearing and gains are what let the wheel reach the shot speed: a NEO through a 1.5:1 reduction tops out near 3800 RPM at the wheel, `kV` of 0.19 volts per rotation per second gets it close to the target on feedforward alone, and `kP` of 0.2 fixes the rest and recovers after each shot. If your shooter has different gearing, find your own `kV` as in the [tutorial's Tune it step](/documentation/tutorials/shooter-flywheels/tune): a first guess is 12 volts divided by the wheel's free speed in rotations per second.

Add these two methods to the shooter class:

{% tabs %}
{% tab title="Commands v2" %}
{% code title="ShooterSubsystem.java (fragment)" %}

```java
import static org.wpilib.units.Units.RPM;

import org.wpilib.command2.Command;
import org.wpilib.command2.button.Trigger;
import org.wpilib.units.measure.AngularVelocity;

/** Spin at a speed and hold it. Runs until interrupted. */
public Command spinUp(AngularVelocity speed) {
  return shooter.run(speed);
}

/** True once the wheel has stayed within 100 RPM of a speed for 0.1 seconds. */
public Trigger ready(AngularVelocity speed) {
  return shooter.near(speed, RPM.of(100)).debounce(0.1);
}
```

{% endcode %}
{% endtab %}

{% tab title="Commands v3" %}
{% code title="ShooterMechanism.java (fragment)" %}

```java
import static org.wpilib.units.Units.RPM;
import static org.wpilib.units.Units.Seconds;

import org.wpilib.command3.Command;
import org.wpilib.command3.Trigger;
import org.wpilib.units.measure.AngularVelocity;

/** Spin at a speed and hold it. Runs until interrupted. */
public Command spinUp(AngularVelocity speed) {
  return shooter.run(speed);
}

/** True once the wheel has stayed within 100 RPM of a speed for 0.1 seconds. */
public Trigger ready(AngularVelocity speed) {
  return shooter.near(speed, RPM.of(100)).debounce(Seconds.of(0.1));
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ShooterSubsystem.cpp (fragment)" %}

```cpp
// Spin at a speed and hold it. Runs until interrupted.
wpi::cmd::CommandPtr ShooterSubsystem::SpinUp(wpi::units::revolutions_per_minute_t speed) {
  return m_shooter->Run(wpi::units::degrees_per_second_t{speed});
}

// True once the wheel has stayed within 100 RPM of a speed for 0.1 seconds.
wpi::cmd::Trigger ShooterSubsystem::Ready(wpi::units::revolutions_per_minute_t speed) {
  return m_shooter->IsNear(speed, 100_rpm).Debounce(0.1_s);
}
```

{% endcode %}

Declare both in `ShooterSubsystem.hpp`, as the [tutorial's commands step](/documentation/tutorials/shooter-flywheels/commands) does for `Run` and `AtSpeed`.
{% endtab %}
{% endtabs %}

The tutorial's `atSpeed` uses a 50 RPM tolerance and no debounce, which is fine for watching the wheel. Feeding needs the wider tolerance and the debounce: see the next step.

**Check it:** the code builds.
{% endstep %}

{% step %}

### Wait for speed

Every shot takes speed out of the wheel, and the speed overshoots and rings as the closed loop brings it back. The 100 RPM tolerance keeps `ready` false while the wheel is too slow or too fast. The speed still passes through the tolerance for an instant on each swing, and the 0.1 second debounce ignores that: `ready` only turns true once the speed has stayed inside the tolerance. Without the debounce, the feeder pulses while the wheel is still ringing.

For a plain boolean outside of a `Trigger`, `FlyWheel` also has `isNear(speed, tolerance)`.

**Check it:** you know the shot speed you will use, and it is well below the wheel's top speed of about 3800 RPM.
{% endstep %}

{% step %}

### Feed

Bind both to the same button. The shooter spins up as soon as the button is held, and the feeder only runs while the button is held **and** the shooter is ready.

{% tabs %}
{% tab title="Commands v2" %}
{% code title="RobotContainer.java (fragment)" %}

```java
private static final AngularVelocity SHOT_SPEED = RPM.of(3000);

private final ShooterSubsystem shooter = new ShooterSubsystem();
private final FeederSubsystem feeder = new FeederSubsystem();

private void configureBindings() {
  // Hold the right trigger: spin up.
  m_driverController.rightTrigger().whileTrue(shooter.spinUp(SHOT_SPEED));

  // While the trigger is held and the wheel is ready: feed.
  m_driverController.rightTrigger()
      .and(shooter.ready(SHOT_SPEED))
      .whileTrue(feeder.feed());
}
```

{% endcode %}
{% endtab %}

{% tab title="Commands v3" %}
{% code title="ExampleTeleop.java (fragment)" %}

```java
// In the opmode constructor. SHOT_SPEED is RPM.of(3000).
var shoot = controller.rightTrigger();

// Hold the right trigger: spin up.
shoot.whileTrue(robot.shooter.spinUp(SHOT_SPEED));

// While the trigger is held and the wheel is ready: feed.
shoot.and(robot.shooter.ready(SHOT_SPEED)).whileTrue(robot.feeder.feed());
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/RobotContainer.cpp (fragment)" %}

```cpp
// Hold the right trigger: spin up.
driverController.RightTrigger().WhileTrue(shooter.SpinUp(3000_rpm));

// While the trigger is held and the wheel is ready: feed.
(driverController.RightTrigger() && shooter.Ready(3000_rpm)).WhileTrue(feeder.Feed());
```

{% endcode %}
{% endtab %}
{% endtabs %}

**Check it:** the code builds, and holding the right trigger in simulation spins the shooter up.
{% endstep %}
{% endstepper %}

## Check it

1. Start the simulation, and graph `NT:/Mechanisms/Shooter/ShooterMotor/mechanism/velocity` (rotations per second; 3000 RPM is 50) and the feeder's `NT:/Mechanisms/Feeder/FeederMotor/motor/outputVoltage` in AdvantageScope. `Feeder` and `FeederMotor` are the telemetry names you gave the feeder's configs.
2. Hold the right trigger. The shooter's speed should rise to about 50 rotations per second.
3. The feeder's voltage should go to 8 volts only after the shooter's speed has settled, not while it is still climbing.

## If it did not work

* **The wheel settles below 3000 RPM and the feeder never runs.** `kV` is too low (or 0). Raise it until the wheel gets close on its own, then tune `kP`.
* **The wheel never gets near 3000 RPM, even at full voltage.** The gearing is too slow. Check `withGearing`: the motor's free speed divided by the reduction must be well above the shot speed.
* **The feeder pulses on and off.** The tolerance is too tight, or the debounce is missing. Try 100 to 150 RPM and 0.1 seconds.
* **Something else.** See [Troubleshooting](/documentation/tutorials/troubleshooting).


# How do I shoot on the move?

Where to learn shooting on the move, which YAMS call does each part, and the worked example.

**Goal:** score while the robot is still driving, instead of stopping to line up first.

Start with [Shoot on the move: worked example](/documentation/how-to-mechanisms/how-do-i-shoot-on-the-move/shoot-on-the-move-example): it builds a robot that aims, sets its shooter speed from a lookup table, and feeds only when the shot is ready, in Java with Commands v2 and Commands v3. This page lists where to learn the math, and which YAMS call does each job the sources ask for. [Shooting on the move](/documentation/understanding/shooters#shooting-on-the-move) explains the idea, and what the [Swerve Input Stream](/documentation/reference/swerve-input-stream) does and does not do for you.

We covered this in a YASS Weekly Workshop, **How To Program Target Tracking And Shooting On The Fly for FRC**:

{% embed url="<https://www.youtube.com/watch?v=pa-HMLTHYvo>" %}

## Read these first

| Source                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              | Read it for                                                                                                                                                                                                                                                                                                                                                                               |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Shooting on the Fly](https://blog.eeshwark.com/robotblog/shooting-on-the-fly) and [Shooting on the Fly, Part 2: The LUT Approach](https://blog.eeshwark.com/robotblog/shooting-on-the-fly-pt2), by Eeshwar                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | The best place to start. Part 1 explains the idea as plain vector math, then covers what goes wrong on a real robot: latency, a flywheel that slows and slips, spin and drag, lobbed shots, and a shooter that is itself moving. Part 2 is the practical side: building the lookup table, getting the shot's speed from the time of flight, shooters with a hood, and tuning the latency. |
| WPILib's [Fire Control](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/index.html) pages: [Static Shooting via Look-Up Table](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/static-shooting.html), [Dynamic Shooting via Time-of-Flight Recursion](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/dynamic-shooting.html), [Newton's Method for Dynamic Shooting](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/newton-shooting.html) and [Linear Drag (First-Order Air Friction)](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/linear-drag.html) | Three firing strategies and a drag correction, with interactive simulations that show where each one converges and where it does not.                                                                                                                                                                                                                                                     |
| [Shoot on the move from the code perspective](https://www.chiefdelphi.com/t/shoot-on-the-move-from-the-code-perspective/511815) (Chief Delphi)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | A short explanation of the virtual target, with links to much of the rest.                                                                                                                                                                                                                                                                                                                |
| [Time of Flight Determination](https://www.chiefdelphi.com/t/time-of-flight-determination/512542) (Chief Delphi)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | The different ways teams measure or calculate the time of flight.                                                                                                                                                                                                                                                                                                                         |
| [Shoot While Move Code (1706)](https://www.chiefdelphi.com/t/shoot-while-move-code-1706/410494) (Chief Delphi)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Team 1706 walking through its 2022 code.                                                                                                                                                                                                                                                                                                                                                  |
| [Orbit 1690 Online Software Sessions](https://www.chiefdelphi.com/t/orbit-1690-online-software-sessions/467221) (Chief Delphi)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Recorded sessions from Team 1690 on their swerve and system control software.                                                                                                                                                                                                                                                                                                             |
| [Mechanical Advantage 6328's `LaunchCalculator.java`](https://github.com/Mechanical-Advantage/RobotCode2026Public/blob/main/src/main/java/org/littletonrobotics/frc2026/subsystems/launcher/LaunchCalculator.java)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | A complete launch calculator from a 2026 robot.                                                                                                                                                                                                                                                                                                                                           |
| [Hammerheads 5000's `TurretCalculator.java`](https://github.com/hammerheads5000/2026Rebuilt/blob/main/src/main/java/frc/robot/subsystems/turret/TurretCalculator.java), with a [build thread post](https://www.chiefdelphi.com/t/frc-5000-hammerheads-2026-build-thread-open-alliance/507502/129) that walks through it                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | A complete shot calculator for a turret from a 2026 robot.                                                                                                                                                                                                                                                                                                                                |

{% hint style="info" %}
The WPILib fire control pages are a work in progress in [wpilib-docs #3242](https://github.com/wpilibsuite/wpilib-docs/pull/3242). They have not been merged, so the links go to the pull request's preview and may move.
{% endhint %}

## How the sources' ideas apply to YAMS

Each row is a concept from the sources, where to read about it, and the YAMS piece that does that job.

| Concept                                                                            | Read about it in                                                                                                                                                                                                                                                                                                | In YAMS                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The robot's position and field velocity                                            | Eeshwar's [part 1](https://blog.eeshwark.com/robotblog/shooting-on-the-fly), "Prerequisites"                                                                                                                                                                                                                    | `drive.getPose()` and `drive.getFieldRelativeSpeed()` on the [Swerve Drive](/documentation/understanding/swerve-drive)                                                                                                                                                                                                                                                                                                                                              |
| A lookup table of shots that score, measured standing still                        | [Static Shooting via Look-Up Table](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/static-shooting.html), and Eeshwar's [part 2](https://blog.eeshwark.com/robotblog/shooting-on-the-fly-pt2)                                                                | WPILib's [`InterpolatingDoubleTreeMap`](https://github.wpilib.org/allwpilib/docs/development/java/org/wpilib/math/interpolation/InterpolatingDoubleTreeMap.html), with the result sent to a [FlyWheel](/documentation/understanding/shooters)                                                                                                                                                                                                                       |
| A flywheel speed that changes every loop                                           | Eeshwar's [part 1](https://blog.eeshwark.com/robotblog/shooting-on-the-fly), "Wait, The Shooter Speed Changed?"                                                                                                                                                                                                 | `FlyWheel.run(Supplier)`, which reads the supplier every loop                                                                                                                                                                                                                                                                                                                                                                                                       |
| Turning to face a point while the driver keeps driving                             | Every source                                                                                                                                                                                                                                                                                                    | [`withAim`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-at-a-target), which takes a supplier so the point can move every loop                                                                                                                                                                                                                                                                                                          |
| A time of flight lead, as a virtual target                                         | [Dynamic Shooting via Time-of-Flight Recursion](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/dynamic-shooting.html), and [Shoot on the move from the code perspective](https://www.chiefdelphi.com/t/shoot-on-the-move-from-the-code-perspective/511815)   | You calculate it. Give the result to `withAim`                                                                                                                                                                                                                                                                                                                                                                                                                      |
| A time of flight lead, as a shot vector with the robot's velocity subtracted       | Eeshwar's [part 1](https://blog.eeshwark.com/robotblog/shooting-on-the-fly), "The Math Implementation", and [part 2](https://blog.eeshwark.com/robotblog/shooting-on-the-fly-pt2), "Getting Horizontal Velocity from ToF"                                                                                       | You calculate it. Give its direction to `withAim`, [`withHeading`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#heading-snap-control) or a turret, and its speed to the flywheel                                                                                                                                                                                                                                                            |
| Latency compensation: aim from where the robot will be                             | Eeshwar's [part 1](https://blog.eeshwark.com/robotblog/shooting-on-the-fly), "Latency Compensation", and [part 2](https://blog.eeshwark.com/robotblog/shooting-on-the-fly-pt2), "The Latency Constant"                                                                                                          | [`withAimLookahead`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-lookahead)                                                                                                                                                                                                                                                                                                                                                            |
| A heading that keeps up with a moving aim point                                    | Specific to turning the whole robot. The sources mostly aim a turret                                                                                                                                                                                                                                            | [`withAimFeedforward`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-feedforward), and the rotation controller in [`SwerveDriveConfig`](/documentation/reference/mechanism-configs/swerve-drive-config)                                                                                                                                                                                                                                  |
| A shooter that does not point out of the front, or a small aim correction for spin | Eeshwar's [part 1](https://blog.eeshwark.com/robotblog/shooting-on-the-fly), "The Magnus Effect and Air Resistance"                                                                                                                                                                                             | [`withAimHeadingOffset`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-heading-offset)                                                                                                                                                                                                                                                                                                                                                   |
| Only shooting when the shot is trustworthy                                         | [Dynamic Shooting via Time-of-Flight Recursion](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/dynamic-shooting.html), "Shot Quality in Practice", and Eeshwar's [part 1](https://blog.eeshwark.com/robotblog/shooting-on-the-fly), "Shooter Wheel Dynamics" | [`aimLock`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-lock) for the heading. For the speed, compare the flywheel with the speed the shot needs right now, as the worked example's `atSpeed(Supplier)` does in [Add to the shooter](/documentation/how-to-mechanisms/how-do-i-shoot-on-the-move/shoot-on-the-move-example#add-to-the-shooter): `FlyWheel.near(...)` takes a fixed speed, which goes stale as the target speed changes |
| A hood, or a turret                                                                | Eeshwar's [part 2](https://blog.eeshwark.com/robotblog/shooting-on-the-fly-pt2), the hood variants, and the two team calculators                                                                                                                                                                                | An [Arm](/documentation/understanding/arms) or a [Pivot](/documentation/understanding/turrets-wrists), each in its own subsystem                                                                                                                                                                                                                                                                                                                                    |

## Tuning the YAMS side

The sources cover how to tune the shot itself. These are the YAMS settings that go with their advice:

| Their advice                                                                                                                                                                                                                                      | The YAMS setting                                                                                                                                                                                                                                                                   |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Get the standing shot consistent before anything else (Eeshwar's [part 1](https://blog.eeshwark.com/robotblog/shooting-on-the-fly), "Prerequisites")                                                                                              | The flywheel's gains: see WPILib's [Tuning a Flywheel Velocity Controller](https://docs.wpilib.org/en/stable/docs/software/advanced-controls/introduction/tuning-flywheel.html) and [How do I shoot with a shooter?](/documentation/how-to-mechanisms/how-to-shoot-with-a-shooter) |
| Tune the latency constant by driving straight across the front of the target (Eeshwar's [part 2](https://blog.eeshwark.com/robotblog/shooting-on-the-fly-pt2), "The Latency Constant")                                                            | The time you give [`withAimLookahead`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-lookahead). Start at 0.1 seconds                                                                                                                                   |
| A moving shot is only as good as the pose it starts from                                                                                                                                                                                          | Vision measurements into the drive's pose estimate: see WPILib's [Pose Estimators](https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-pose-estimators.html)                                                                                 |
| Watch whether the heading keeps up as you drive past                                                                                                                                                                                              | The rotation controller in [`SwerveDriveConfig`](/documentation/reference/mechanism-configs/swerve-drive-config), then [`withAimFeedforward`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-feedforward)                                                |
| Hold fire when the shot is not trustworthy ([Dynamic Shooting via Time-of-Flight Recursion](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/dynamic-shooting.html), "Shot Quality in Practice") | The tolerance you give [`aimLock`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-lock), and the speed tolerance in the worked example's `atSpeed(Supplier)`                                                                                             |

## WPILib building blocks

The released WPILib documentation covers the classes the example uses. These pages are written for WPILib 2026. The ideas are the same in 2027, though some classes were renamed: `ChassisSpeeds`, for example, is `ChassisVelocities`.

| Page                                                                                                                                                            | Why it matters here                                                            |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| [Coordinate System](https://docs.wpilib.org/en/stable/docs/software/basic-programming/coordinate-system.html)                                                   | Which way X, Y and a positive rotation point.                                  |
| [Translation, Rotation, and Pose](https://docs.wpilib.org/en/stable/docs/software/advanced-controls/geometry/pose.html)                                         | The classes that the distance and direction to the target are calculated with. |
| [Transformations](https://docs.wpilib.org/en/stable/docs/software/advanced-controls/geometry/transformations.html)                                              | Getting from the center of the robot to where the shooter really is.           |
| [Introduction to Kinematics and The ChassisSpeeds Class](https://docs.wpilib.org/en/stable/docs/software/kinematics-and-odometry/intro-and-chassis-speeds.html) | Robot relative and field relative velocity.                                    |


# Shoot on the move: worked example

A complete robot that aims, sets its shooter speed and feeds only when the shot is ready, while it drives.

**Goal:** turn the robots from the Swerve Drive and Shooter tutorials into one that aims, sets its shooter speed and feeds only when the shot is ready, while it drives.

Read [How do I shoot on the move?](/documentation/how-to-mechanisms/how-do-i-shoot-on-the-move) first for the sources this example is built from, and [Shooting on the move](/documentation/understanding/shooters#shooting-on-the-move) for the idea. This page is only the code, step by step.

**Before you start:** have the complete files from the [Swerve Drive tutorial's Driving step](/documentation/tutorials/swerve-drive/driving#the-complete-file) and the [Shooter tutorial's Commands and buttons step](/documentation/tutorials/shooter-flywheels/commands#the-complete-file) in one project, Commands v2 or Commands v3, and a feeder built as in [How do I set up an intake roller?](/documentation/how-to-mechanisms/how-do-i-set-up-an-intake-roller), with its telemetry named `Feeder` and `FeederMotor` and its `intake()` command renamed `feed()`. The steps below show only what to add to them.

{% hint style="info" %}
The code is shown for Java with Commands v2 and Commands v3. The C++ port has the same pieces, `SwerveInputStream::WithAim`, `WithAimLookahead` and `IsAimLocked`, and `FlyWheel::Run` with a function, so the same approach works there: start from the C++ tabs of the [Swerve Drive](/documentation/tutorials/swerve-drive) and [Shooter](/documentation/tutorials/shooter-flywheels) tutorials. Every file compiles against YAMS, but none of it has been run on a robot: the numbers in the tables are placeholders for your own measurements.
{% endhint %}

{% stepper %}
{% step %}

### Add to the swerve drive

Every calculation starts from where the robot is and how fast it is moving on the field. Add two methods to the tutorial's drive, each calling the `SwerveDrive` method of the same name:

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/SwerveSubsystem.java (fragment)" %}

```java
import org.wpilib.math.geometry.Pose2d;
import org.wpilib.math.kinematics.ChassisVelocities;

/** Where the robot is on the field. */
public Pose2d getPose() {
  return drive.getPose();
}

/** How fast the robot is moving on the field. */
public ChassisVelocities getFieldRelativeSpeed() {
  return drive.getFieldRelativeSpeed();
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
The same two methods go in `mechanisms/SwerveMechanism.java`.
{% endtab %}
{% endtabs %}

The tutorial's drive motors keep their `kV` of 0.85, and its rotation controller, `withRotationController(new PIDController(1, 0, 0))`, is what turns the robot to aim: tune it once the robot drives well.

**Check it:** the code builds.
{% endstep %}

{% step %}

### Add to the shooter

The tutorial's shooter, with its 1.5:1 gearing, `kV` of 0.19 and `kP` of 0.2, tops out near 3800 RPM, above every speed in the tables below. Add two methods for a shot whose speed changes every loop:

* **`track(Supplier)`** sets the flywheel's speed from a supplier, which `FlyWheel.run(Supplier)` reads every loop. This is how the shot's speed reaches the flywheel.
* **`atSpeed(Supplier)`** is true while the flywheel is within 100 RPM of that same changing speed. `FlyWheel.near(...)` takes a fixed speed, so it cannot follow a speed that changes. The 100 RPM and the 0.1 second debounce on the `ready` trigger in [Aim, set the shooter speed, and shoot safely](#aim-set-the-shooter-speed-and-shoot-safely) are the same as in [How do I shoot with a shooter?](/documentation/how-to-mechanisms/how-to-shoot-with-a-shooter)

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java (fragment)" %}

```java
import static org.wpilib.units.Units.RPM;

import java.util.function.Supplier;
import org.wpilib.command2.Command;
import org.wpilib.command2.button.Trigger;
import org.wpilib.units.measure.AngularVelocity;

/** Follow a speed that changes every loop. This command does not end on its own. */
public Command track(Supplier<AngularVelocity> speed) {
  return shooter.run(speed);
}

/** True while the flywheel is within 100 RPM of a speed that changes every loop. */
public Trigger atSpeed(Supplier<AngularVelocity> speed) {
  return new Trigger(() -> shooter.isNear(speed.get(), RPM.of(100)));
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java (fragment)" %}

```java
import static org.wpilib.units.Units.RPM;

import java.util.function.Supplier;
import org.wpilib.command3.Command;
import org.wpilib.command3.Trigger;
import org.wpilib.units.measure.AngularVelocity;

/** Follow a speed that changes every loop. This command does not end on its own. */
public Command track(Supplier<AngularVelocity> speed) {
  return shooter.run(speed);
}

/** True while the flywheel is within 100 RPM of a speed that changes every loop. */
public Trigger atSpeed(Supplier<AngularVelocity> speed) {
  return new Trigger(() -> shooter.isNear(speed.get(), RPM.of(100)));
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**Check it:** the code builds.
{% endstep %}

{% step %}

### Measure the lookup tables

**Read first:** [Static Shooting via Look-Up Table](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/static-shooting.html), and Eeshwar's [part 2](https://blog.eeshwark.com/robotblog/shooting-on-the-fly-pt2), which describes how to measure the table with a tape measure and a phone.

The tables hold what you measured standing still: the flywheel speed that scores from each distance, and how long that shot is in the air. WPILib's [`InterpolatingDoubleTreeMap`](https://github.wpilib.org/allwpilib/docs/development/java/org/wpilib/math/interpolation/InterpolatingDoubleTreeMap.html) fills in the distances in between. `inRange` says whether the robot is at a distance you measured, which the `ready` trigger uses. Create `ShotCalculator.java` with the start of the class, as in [The complete ShotCalculator file](#the-complete-shotcalculator-file) below without its three strategy methods.

**For your robot:** set `TARGET`, fill both tables with your own measurements, change the two distances in `inRange` to match, and flip the target for the red alliance. Keep every speed well below the shooter's top speed.

**Check it:** the code builds.
{% endstep %}

{% step %}

### Pick a firing strategy

Each tab is one method to add to `ShotCalculator`; the complete file below has all three. They are the three strategies of the WPILib fire control pages, written against the tables above. The two for a moving robot are **time of flight** methods: they get the lead from the time of flight you measured.

{% tabs %}
{% tab title="Standing still" %}
**Read first:** [Static Shooting via Look-Up Table](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/static-shooting.html).

Aim at the real target, and read the flywheel speed for the distance. Only right while the robot is not moving.

{% code title="ShotCalculator.java (fragment)" %}

```java
/** Aim at the real target. Only right while the robot is standing still. */
public static Shot standing(Pose2d robotPose) {
  return shotAt(robotPose, TARGET);
}
```

{% endcode %}
{% endtab %}

{% tab title="Time of flight recursion" %}
**Read first:** [Dynamic Shooting via Time-of-Flight Recursion](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/dynamic-shooting.html).

A time of flight method. It moves the target against the robot's velocity by the time of flight, which changes the distance and so the time of flight, and repeats until the time stops changing. This is the virtual target that most teams use.

{% code title="ShotCalculator.java (fragment)" %}

```java
/** Lead the target by the time of flight, and repeat until the time settles. */
public static Shot recursive(Pose2d robotPose, ChassisVelocities fieldVelocity) {
  Translation2d virtualTarget = TARGET;
  // Each pass uses the distance from the pass before, so the answer settles after a few.
  for (int i = 0; i < 3; i++) {
    double distance = robotPose.getTranslation().getDistance(virtualTarget);
    double timeOfFlight = TIME_OF_FLIGHT.get(distance);
    // The shot drifts by the robot's velocity times the time of flight, so aim that far the other way.
    virtualTarget = TARGET.minus(
        new Translation2d(fieldVelocity.vx * timeOfFlight, fieldVelocity.vy * timeOfFlight));
  }
  return shotAt(robotPose, virtualTarget);
}
```

{% endcode %}
{% endtab %}

{% tab title="Newton's method" %}
**Read first:** [Newton's Method for Dynamic Shooting](https://frc-docs--3242.org.readthedocs.build/en/3242/docs/software/advanced-controls/fire-control/newton-shooting.html).

A time of flight method. It finds the same time of flight as the recursion in fewer passes, which helps when driving fast toward or away from the target.

{% code title="ShotCalculator.java (fragment)" %}

```java
/** Find the same time of flight with Newton's method, which needs fewer passes. */
public static Shot newton(Pose2d robotPose, ChassisVelocities fieldVelocity) {
  Translation2d toTarget = TARGET.minus(robotPose.getTranslation());
  double distance = toTarget.getNorm();
  // How fast the game piece covers ground, from the standing shot at this distance.
  double projectileSpeed = distance / TIME_OF_FLIGHT.get(distance);
  // How fast the robot is closing on the target. Negative while it drives away.
  double closingSpeed = (toTarget.getX() * fieldVelocity.vx + toTarget.getY() * fieldVelocity.vy) / distance;

  // A first guess that already allows for the robot's motion toward or away from the target.
  double timeOfFlight = distance / (projectileSpeed + closingSpeed);
  for (int i = 0; i < 3; i++) {
    // The virtual target for this guess.
    double dx = toTarget.getX() - fieldVelocity.vx * timeOfFlight;
    double dy = toTarget.getY() - fieldVelocity.vy * timeOfFlight;
    double virtualDistance = Math.hypot(dx, dy);
    // How far the guess is from what the table says for that distance.
    double error = timeOfFlight - TIME_OF_FLIGHT.get(virtualDistance);
    // How fast that error changes as the guess changes.
    double slope = 1 + (dx * fieldVelocity.vx + dy * fieldVelocity.vy) / (projectileSpeed * virtualDistance);
    timeOfFlight -= error / slope;
  }
  Translation2d virtualTarget = TARGET.minus(
      new Translation2d(fieldVelocity.vx * timeOfFlight, fieldVelocity.vy * timeOfFlight));
  return shotAt(robotPose, virtualTarget);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

The strategy is chosen in one line, `shot()` in `RobotContainer` (Commands v2) or `Robot` (Commands v3) in the next step. It calls `ShotCalculator.recursive(drive.getPose(), drive.getFieldRelativeSpeed())`. For Newton's method, change it to `ShotCalculator.newton(...)` with the same arguments; for standing still, to `ShotCalculator.standing(drive.getPose())`.

**Check it:** the code builds with all three methods in `ShotCalculator`.
{% endstep %}

{% step %}

### Aim, set the shooter speed, and shoot safely

This is where it comes together. Replace the template's file with this one. It uses the commands from the tutorials and the additions above, and the feeder's `feed()` and default command from [How do I set up an intake roller?](/documentation/how-to-mechanisms/how-do-i-set-up-an-intake-roller)

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="RobotContainer.java" lineNumbers="true" %}

```java
package first.robot;

import static org.wpilib.units.Units.Degrees;
import static org.wpilib.units.Units.Seconds;

import first.robot.Constants.OperatorConstants;
import first.robot.subsystems.FeederSubsystem;
import first.robot.subsystems.ShooterSubsystem;
import first.robot.subsystems.SwerveSubsystem;
import org.wpilib.command2.Command;
import org.wpilib.command2.Commands;
import org.wpilib.command2.button.CommandGamepad;
import org.wpilib.command2.button.Trigger;
import yams.commands2.swerve.SwerveInputStream;

public class RobotContainer {
  private final SwerveSubsystem drive = new SwerveSubsystem();
  private final ShooterSubsystem shooter = new ShooterSubsystem();
  private final FeederSubsystem feeder = new FeederSubsystem();

  private final CommandGamepad driverController =
      new CommandGamepad(OperatorConstants.DRIVER_CONTROLLER_PORT);

  /** The shot for where the robot is, and how it is moving, right now. */
  private ShotCalculator.Shot shot() {
    return ShotCalculator.recursive(drive.getPose(), drive.getFieldRelativeSpeed());
  }

  public RobotContainer() {
    // The left stick translates and the right stick's X axis rotates.
    // Pushing a stick forward or left reads negative, so negate each axis to match
    // WPILib's convention: +X forward, +Y left, counterclockwise positive.
    SwerveInputStream input = drive.getChassisSpeedsSupplier(
            () -> -driverController.getLeftY(),
            () -> -driverController.getLeftX(),
            () -> -driverController.getRightX())
        // While the right bumper is held, face the shot's target instead of
        // turning with the right stick. The left stick keeps driving.
        .withAim(() -> shot().target(), driverController.rightBumper())
        // Aim from where the robot will be when the game piece leaves it.
        .withAimLookahead(Seconds.of(0.1));
    drive.setDefaultCommand(drive.driveFieldRelative(input));

    // With no button held, the flywheel coasts and the feeder is stopped.
    shooter.setDefaultCommand(shooter.set(0));
    feeder.setDefaultCommand(feeder.stop());

    // While the right bumper is held, keep the flywheel at the speed the shot needs.
    driverController.rightBumper().whileTrue(shooter.track(() -> shot().flywheelSpeed()));

    // The shot is ready when the robot faces the aim heading, the flywheel is at the shot's
    // speed, and the robot is at a distance the tables cover. All three must hold for a tenth
    // of a second, so that one lucky loop does not fire a shot.
    Trigger ready = input.aimLock(Degrees.of(2))
        .and(shooter.atSpeed(() -> shot().flywheelSpeed()))
        .and(() -> ShotCalculator.inRange(drive.getPose()))
        .debounce(0.1);

    // Feed only while the shot is ready. The moment it is not, the feeder stops.
    ready.whileTrue(feeder.feed());
  }

  public Command getAutonomousCommand() {
    return Commands.none();
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
{% code title="Robot.java" lineNumbers="true" %}

```java
package first.robot;

import first.robot.constants.DriverConstants;
import first.robot.mechanisms.ExampleMechanism;
import first.robot.mechanisms.FeederMechanism;
import first.robot.mechanisms.ShooterMechanism;
import first.robot.mechanisms.SwerveMechanism;
import java.util.ArrayList;
import java.util.List;
import org.wpilib.command3.Scheduler;
import org.wpilib.command3.button.CommandGamepad;
import org.wpilib.framework.OpModeRobot;
import org.wpilib.system.Notifier;
import org.wpilib.telemetry.Telemetry;

public class Robot extends OpModeRobot {
  // The template's ExampleAuto still uses this one.
  final ExampleMechanism exampleMechanism = new ExampleMechanism();
  final SwerveMechanism drive = new SwerveMechanism();
  final ShooterMechanism shooter = new ShooterMechanism();
  final FeederMechanism feeder = new FeederMechanism();
  final CommandGamepad exampleController =
      new CommandGamepad(DriverConstants.DRIVER_CONTROLLER_PORT);

  // The scheduler that runs every command.
  private final Scheduler scheduler = Scheduler.getDefault();
  // Each mechanism's simulation Notifier, kept so that it is not garbage collected.
  private final List<Notifier> simulationNotifiers = new ArrayList<>();

  /** The shot for where the robot is, and how it is moving, right now. */
  ShotCalculator.Shot shot() {
    return ShotCalculator.recursive(drive.getPose(), drive.getFieldRelativeSpeed());
  }

  public Robot() {
    // With no button held, the flywheel coasts and the feeder is stopped.
    shooter.setDefaultCommand(shooter.idle());
    feeder.setDefaultCommand(feeder.idle());
  }

  @Override
  public void robotPeriodic() {
    // Runs every loop, on the robot and in simulation.
    // Update every mechanism before the scheduler runs its commands.
    drive.periodic();
    shooter.periodic();
    feeder.periodic();
    scheduler.run();
    // Publish the scheduler, so that a dashboard shows which commands are running.
    Telemetry.log("Scheduler", scheduler, Scheduler.proto);
  }

  @Override
  public void simulationInit() {
    // Runs once, when the simulation starts.
    // Run each mechanism's simulation in its own Notifier, every robot loop.
    startSimulation("Drive", drive::simulationPeriodic);
    startSimulation("Shooter", shooter::simulationPeriodic);
    startSimulation("Feeder", feeder::simulationPeriodic);
  }

  /** Runs a mechanism's simulation in its own Notifier, every robot loop period. */
  private void startSimulation(String name, Runnable simulationPeriodic) {
    Notifier notifier = new Notifier(simulationPeriodic);
    notifier.setName(name + " Simulation");
    notifier.startPeriodic(getPeriod());
    simulationNotifiers.add(notifier);
  }
}
```

{% endcode %}

{% code title="ExampleTeleop.java" lineNumbers="true" %}

```java
package first.robot;

import static org.wpilib.units.Units.Degrees;
import static org.wpilib.units.Units.Seconds;

import org.wpilib.command3.Trigger;
import org.wpilib.opmode.OpMode;
import org.wpilib.opmode.Teleop;
import yams.commands3.swerve.SwerveInputStream;

@Teleop
public class ExampleTeleop implements OpMode {
  public ExampleTeleop(Robot robot) {
    // The left stick translates and the right stick's X axis rotates.
    // Pushing a stick forward or left reads negative, so negate each axis to match
    // WPILib's convention: +X forward, +Y left, counterclockwise positive.
    SwerveInputStream input = robot.drive.getChassisSpeedsSupplier(
            () -> -robot.exampleController.getLeftY(),
            () -> -robot.exampleController.getLeftX(),
            () -> -robot.exampleController.getRightX())
        // While the right bumper is held, face the shot's target instead of
        // turning with the right stick. The left stick keeps driving.
        .withAim(() -> robot.shot().target(), robot.exampleController.rightBumper())
        // Aim from where the robot will be when the game piece leaves it.
        .withAimLookahead(Seconds.of(0.1));
    robot.drive.setDefaultCommand(robot.drive.driveFieldRelative(input));

    // While the right bumper is held, keep the flywheel at the speed the shot needs.
    robot.exampleController.rightBumper()
        .whileTrue(robot.shooter.track(() -> robot.shot().flywheelSpeed()));

    // The shot is ready when the robot faces the aim heading, the flywheel is at the shot's
    // speed, and the robot is at a distance the tables cover. All three must hold for a tenth
    // of a second, so that one lucky loop does not fire a shot.
    Trigger ready = input.aimLock(Degrees.of(2))
        .and(robot.shooter.atSpeed(() -> robot.shot().flywheelSpeed()))
        .and(() -> ShotCalculator.inRange(robot.drive.getPose()))
        .debounce(Seconds.of(0.1));

    // Feed only while the shot is ready. The moment it is not, the feeder stops.
    ready.whileTrue(robot.feeder.feed());
  }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

Holding the right bumper does three things at once:

1. **Aims.** [`withAim`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-at-a-target) turns the robot to face the shot's target while the left stick keeps driving, and [`withAimLookahead`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-lookahead) covers the short delay before the game piece leaves.
2. **Sets the shooter speed.** `shooter.track(...)` keeps the flywheel at the speed the shot needs, which changes as the robot moves.
3. **Shoots, but only when it is safe to.** The feeder runs only while `ready` is true.

`ready` is what makes the shot safe. It is true only when all of these hold, and have held for a tenth of a second:

| Check                                                                                                                                                   | Why                                                                                                                                      |
| ------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| [`aimLock`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-lock): the robot is aiming and within 2 degrees of the aim heading | A shot fired while the robot is still turning goes wide. It is also false whenever the bumper is not held, so nothing feeds by accident. |
| `shooter.atSpeed(...)`: the flywheel is within 100 RPM of the shot's speed                                                                              | A flywheel that is still spinning up, or still recovering from the last shot, throws short.                                              |
| `ShotCalculator.inRange(...)`: the robot is at a distance you measured                                                                                  | Outside the tables, the lookup just repeats its last entry and the shot misses.                                                          |
| `debounce(0.1)`                                                                                                                                         | One loop where everything happens to line up is not a ready shot.                                                                        |

Releasing the bumper ends the aim and the flywheel command. `ready` goes false, the feeder stops, and the default commands let the flywheel coast.

**Check it:** the code builds, and in simulation the robot turns to face the target while you hold the right bumper.

**For your robot:** tune the lookahead, the 2 degree and 100 RPM tolerances, and the debounce. Tighter is more accurate and slower to fire. If your shooter does not point out of the front of the robot, add [`withAimHeadingOffset`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-heading-offset).
{% endstep %}

{% step %}

### Try it in simulation

Run **WPILib: Simulate Robot Code**, connect a controller, and enable teleop. The robot starts at (0, 0), about 6.1 m from the target at (4.6, 4.0), which is outside the 1.5 to 4.5 m that `inRange` allows, so nothing feeds there. Drive toward the target until it is between 1.5 and 4.5 m away, such as to (2, 2), about 3.3 m away; `NT:/Mechanisms/swerve/pose` shows where the robot is.

Hold the right bumper and drive. The robot keeps facing the shot's target, and the flywheel's setpoint follows the shot. Graph in AdvantageScope:

* `NT:/Mechanisms/Shooter/ShooterMotor/closedloop/setpoint/velocity` and `mechanism/velocity` beside it: the shot's speed, and the flywheel's.
* `NT:/Mechanisms/Feeder/FeederMotor/motor/outputVoltage`: the feeder, which only runs while `ready` is true.

The simulation does not model the game piece, so it shows that the logic works, and not whether shots land.

**Check it:** in range, with the bumper held and the robot facing the target, the feeder's voltage goes up once the flywheel's speed settles on the setpoint. Out of range, it stays at 0.
{% endstep %}
{% endstepper %}

## The complete ShotCalculator file

{% code title="ShotCalculator.java" lineNumbers="true" %}

```java
package first.robot;

import static org.wpilib.units.Units.RPM;

import org.wpilib.math.geometry.Pose2d;
import org.wpilib.math.geometry.Rotation2d;
import org.wpilib.math.geometry.Translation2d;
import org.wpilib.math.interpolation.InterpolatingDoubleTreeMap;
import org.wpilib.math.kinematics.ChassisVelocities;
import org.wpilib.units.measure.AngularVelocity;

/** Works out where to aim and how fast to spin the flywheel. */
public final class ShotCalculator {
  /** Where to aim, and the flywheel speed that reaches it. */
  public record Shot(Pose2d target, AngularVelocity flywheelSpeed) {}

  // Where the real target is on the field, in meters.
  private static final Translation2d TARGET = new Translation2d(4.6, 4.0);

  // Distance to the target in meters, to flywheel speed in RPM.
  private static final InterpolatingDoubleTreeMap FLYWHEEL_RPM = new InterpolatingDoubleTreeMap();
  // Distance to the target in meters, to how long the shot is in the air in seconds.
  private static final InterpolatingDoubleTreeMap TIME_OF_FLIGHT = new InterpolatingDoubleTreeMap();

  static {
    // Measure these on your own robot, standing still. Placeholders, all below the
    // tutorial shooter's top speed of about 3800 RPM.
    FLYWHEEL_RPM.put(1.5, 2000.0);
    FLYWHEEL_RPM.put(3.0, 2500.0);
    FLYWHEEL_RPM.put(4.5, 3000.0);

    TIME_OF_FLIGHT.put(1.5, 0.45);
    TIME_OF_FLIGHT.put(3.0, 0.70);
    TIME_OF_FLIGHT.put(4.5, 0.95);
  }

  private ShotCalculator() {}

  /** Whether the robot is at a distance the tables cover. Outside it they only repeat their last entry. */
  public static boolean inRange(Pose2d robotPose) {
    double distance = robotPose.getTranslation().getDistance(TARGET);
    return distance >= 1.5 && distance <= 4.5;
  }

  /** Aim at the real target. Only right while the robot is standing still. */
  public static Shot standing(Pose2d robotPose) {
    return shotAt(robotPose, TARGET);
  }

  /** Lead the target by the time of flight, and repeat until the time settles. */
  public static Shot recursive(Pose2d robotPose, ChassisVelocities fieldVelocity) {
    Translation2d virtualTarget = TARGET;
    // Each pass uses the distance from the pass before, so the answer settles after a few.
    for (int i = 0; i < 3; i++) {
      double distance = robotPose.getTranslation().getDistance(virtualTarget);
      double timeOfFlight = TIME_OF_FLIGHT.get(distance);
      // The shot drifts by the robot's velocity times the time of flight, so aim that far the other way.
      virtualTarget = TARGET.minus(
          new Translation2d(fieldVelocity.vx * timeOfFlight, fieldVelocity.vy * timeOfFlight));
    }
    return shotAt(robotPose, virtualTarget);
  }

  /** Find the same time of flight with Newton's method, which needs fewer passes. */
  public static Shot newton(Pose2d robotPose, ChassisVelocities fieldVelocity) {
    Translation2d toTarget = TARGET.minus(robotPose.getTranslation());
    double distance = toTarget.getNorm();
    // How fast the game piece covers ground, from the standing shot at this distance.
    double projectileSpeed = distance / TIME_OF_FLIGHT.get(distance);
    // How fast the robot is closing on the target. Negative while it drives away.
    double closingSpeed = (toTarget.getX() * fieldVelocity.vx + toTarget.getY() * fieldVelocity.vy) / distance;

    // A first guess that already allows for the robot's motion toward or away from the target.
    double timeOfFlight = distance / (projectileSpeed + closingSpeed);
    for (int i = 0; i < 3; i++) {
      // The virtual target for this guess.
      double dx = toTarget.getX() - fieldVelocity.vx * timeOfFlight;
      double dy = toTarget.getY() - fieldVelocity.vy * timeOfFlight;
      double virtualDistance = Math.hypot(dx, dy);
      // How far the guess is from what the table says for that distance.
      double error = timeOfFlight - TIME_OF_FLIGHT.get(virtualDistance);
      // How fast that error changes as the guess changes.
      double slope = 1 + (dx * fieldVelocity.vx + dy * fieldVelocity.vy) / (projectileSpeed * virtualDistance);
      timeOfFlight -= error / slope;
    }
    Translation2d virtualTarget = TARGET.minus(
        new Translation2d(fieldVelocity.vx * timeOfFlight, fieldVelocity.vy * timeOfFlight));
    return shotAt(robotPose, virtualTarget);
  }

  /** The shot that reaches a point on the field from where the robot is. */
  private static Shot shotAt(Pose2d robotPose, Translation2d aimPoint) {
    double distance = robotPose.getTranslation().getDistance(aimPoint);
    return new Shot(new Pose2d(aimPoint, new Rotation2d()), RPM.of(FLYWHEEL_RPM.get(distance)));
  }
}
```

{% endcode %}

## If it did not work

* **The robot does not turn to face the target.** The rotation controller in `SwerveDriveConfig` has no gain, or the aim command is not running. See the [Swerve Input Stream](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-at-a-target) page.
* **The feeder never runs.** The robot is out of range (see [Try it in simulation](#try-it-in-simulation)), or the flywheel never gets within its tolerance; tune it with [How do I shoot with a shooter?](/documentation/how-to-mechanisms/how-to-shoot-with-a-shooter)
* **The flywheel's speed stays below its setpoint.** A table asks for more than the shooter can reach: keep the speeds well below its top speed, or change its gearing.
* **Something else.** See [Troubleshooting](/documentation/tutorials/troubleshooting).

## Read more

Tune the YAMS side of the shot: [Tuning the YAMS side](/documentation/how-to-mechanisms/how-do-i-shoot-on-the-move#tuning-the-yams-side).


# How do I use absolute encoders on my arm?

**Goal:** have the arm know its angle the moment the robot turns on, with no homing, by closing its loop on an absolute encoder.

An absolute encoder keeps its reading through a power cycle, and YAMS maps that reading to your arm's angles with a zero offset and a wrapping range.

## Supported encoder types

Each `SmartMotorController` wrapper only accepts the encoders from its own vendor ecosystem. `SparkWrapper`, `NovaWrapper` and `A301Wrapper` throw an `IllegalArgumentException` when given an encoder type they do not support.

| Wrapper                               | Supported absolute encoders                                                               |
| ------------------------------------- | ----------------------------------------------------------------------------------------- |
| `SparkWrapper` (SparkMax / SparkFlex) | `SparkAbsoluteEncoder` (`armMotor.getAbsoluteEncoder()`), `DetachedEncoder`               |
| `TalonFXWrapper` (TalonFX / Kraken)   | `CANcoder`, `CANdi`                                                                       |
| `TalonFXSWrapper` (TalonFXS / Minion) | `CANcoder`, `CANdi`                                                                       |
| `NovaWrapper` (Thrifty Nova)          | `FeedbackSensorType.ABS` (absolute encoder on the Nova's data port), Thrifty `CanEncoder` |
| `A301Wrapper` (FIRST A301)            | The `A301` itself: its own absolute encoder, on its output shaft                          |

Set the encoder up in this order, in your `SmartMotorControllerConfig`. The [complete examples](#complete-examples) below put every step together for each motor controller.

{% stepper %}
{% step %}

### Check your inversion

Using the vendor hardware client (REV Hardware Client or Phoenix Tuner X), apply positive power to the motor and graph the absolute encoder position. The position should **increase** as the motor turns in the positive direction.

If it decreases, invert the encoder reading:

```java
.withExternalEncoderInverted(true)
```

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-fc710684b7b879e5f11ade075bdc083c645d7f4e%2Fsmc-encoder-inverted.png?alt=media" alt="Two panels. When the encoder reading goes up as the motor output is positive, the PID pushes toward the setpoint. When the encoder reading goes down instead, the PID pushes away from the setpoint and the mechanism runs off."><figcaption><p>What a backwards encoder does to closed loop control.</p></figcaption></figure>

**Check it:** with positive power, the encoder position goes up.
{% endstep %}

{% step %}

### Check your gear ratio and mount

The absolute encoder must complete **at most one full rotation** across the entire range of motion of the arm. Confirm this in the hardware client by moving the arm through its full travel and watching the encoder position, it must never wrap from 1 rotation back to 0 more than once.

If the encoder is mounted directly on the arm's shaft (1:1), leave `withExternalEncoderGearing` unset. Only if the encoder is driven through a reduction, pass the encoder-to-mechanism ratio with `.withExternalEncoderGearing(...)`, and read the note on gearing in [Choose the wrapping range](#choose-the-wrapping-range).

{% hint style="warning" %}
If the gear ratio causes the encoder to exceed 1 rotation during the arm's range of motion, the encoder position will wrap unpredictably and **cannot** be used as the primary PID feedback device. Either remount the encoder closer to the mechanism output shaft or change the reduction so the encoder never exceeds 1 rotation.
{% endhint %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-2777bfd697577ff93b59d91b18decd29ed7e64a6%2Fsmc-encoder-gearing-wrap.gif?alt=media" alt="Animation of the same arm moving between hard stops 120 degrees apart, read through two encoder gearings. Each absolute encoder is drawn with a white line on its casing and a white line on its bearing, which line up at the wrap point. With a gearing of 2 the encoder turns 240 degrees, the lines never meet, and YAMS always reports the right angle. With a gearing of 4 the encoder needs 480 degrees, the lines meet partway through the travel, and YAMS then reports an angle 90 degrees too low."><figcaption><p>The same arm and hard stops. Both read [0, 1), so they wrap at the line on the casing. With a gearing of 2 the white lines never meet. With a gearing of 4 they do, and the reported angle is wrong.</p></figcaption></figure>

**Check it:** across the arm's whole travel, the encoder turns less than one rotation.
{% endstep %}

{% step %}

### Choose the wrapping range

An absolute encoder reads one rotation, and wraps at the ends of its range: its **wrap point**, where the reading jumps from its maximum back to its minimum. [`withWrapping`](/documentation/reference/editor/config/encoders#withwrapping) chooses the range. The two usual ones:

* `withWrapping(Rotations.of(0), Rotations.of(1))`: the encoder reads **\[0, 1)** rotations, and wraps from 1 rotation back to 0
* `withWrapping(Rotations.of(-0.5), Rotations.of(0.5))`: the encoder reads **\[-0.5, 0.5)** rotations, and wraps at ±0.5 rotations

```java
.withWrapping(Rotations.of(-0.5), Rotations.of(0.5))  // [-0.5, 0.5) range, for an arm either side of zero
// or
.withWrapping(Rotations.of(0), Rotations.of(1))       // [0, 1) range
```

`withWrapping` only sets what the encoder reads: the arm's closed loop never goes the other way round to a setpoint, so it works with soft limits. Do not use [`withContinuousWrapping`](/documentation/reference/editor/config/closed-loop-control#withcontinuouswrapping) on an arm: it makes the closed loop take the shortest path, which could be through the arm's hard stops.

{% hint style="info" %}
Without `withWrapping`, a SPARK, Thrifty Nova or A301 absolute encoder reads **\[0, 1)**, and a `CANcoder` or `CANdi` keeps the range it has. Each motor controller accepts only the ranges its encoder can read: see [`withWrapping`](/documentation/reference/editor/config/encoders#withwrapping). A Thrifty Nova closing its loop on the encoder runs the loop itself only over **\[0, 1)**; with any other range the loop runs on the SystemCore. The range is one rotation of the **encoder**, so with `.withExternalEncoderGearing(...)` it is not one rotation of the arm.
{% endhint %}

{% hint style="warning" %}
If the arm's physical range of motion crosses the wrap point, the position will jump mid-travel and break closed-loop control. If this happens, remove the encoder, rotate the bearing so the wrap point falls outside the arm's travel range, and remount.
{% endhint %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-651887f365200ae9f7672c0b1be4950fb881d1cb%2Fsmc-encoder-wrapping-range.gif?alt=media" alt="Animation of a 1:1 arm moving between hard stops at minus 40 and 110 degrees, with the two wrapping ranges. The absolute encoder is drawn with a white line on its casing and one on its bearing, which line up at the arm&#x27;s zero in both panels. Wrapping over 0 to 1 rotation, the wrap point is at the line on the casing, inside the travel, so the reading jumps by 360 degrees when the arm goes below zero. Wrapping over minus 0.5 to 0.5 rotations, the wrap point is 180 degrees from the line, where the arm never goes, and the reading follows the arm the whole way."><figcaption><p>Wrapping over [0, 1), the wrap point is at the line on the casing. Over [-0.5, 0.5) it is 180° from it, and the line has not moved.</p></figcaption></figure>

**Check it:** move the arm through its whole travel in the hardware client. The reading never jumps.
{% endstep %}

{% step %}

### Find your zero offset

Move the arm to exactly horizontal (0° from horizontal, parallel to the ground). Read the raw encoder position in the hardware client, with no offset set in the client: that value is your zero offset.

**Units.** The hardware clients show the position in **rotations**, from 0 to 1. `withExternalEncoderZeroOffset` takes an `Angle`, so pass the reading as rotations, or multiply it by 360 for degrees. A reading of 0.0924 is either of these:

```java
.withExternalEncoderZeroOffset(Rotations.of(0.0924))  // the reading, as shown in the client
.withExternalEncoderZeroOffset(Degrees.of(33.25))     // the same, 0.0924 × 360
```

Use one of the two, with your own reading. The offset is in **arm (mechanism) rotations**. With the encoder on the arm's shaft (1:1) and no `withExternalEncoderGearing`, an encoder rotation and an arm rotation are the same, so the client's reading goes in as it is. If you set `withExternalEncoderGearing`, measure the offset as an arm angle instead.

Negative offsets are automatically converted to their positive equivalent (1 rotation is added internally). The offset is applied to the absolute encoder itself, such as the CANcoder's magnet offset or the SPARK's absolute encoder zero offset. On an A301, YAMS applies it to the reading itself.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-bb493ac7388ec2592bf3492c69936460052e265f%2Fsmc-encoder-zero-offset-wrapping.gif?alt=media" alt="Animation of the same arm and 1:1 absolute encoder, reading minus 180 to 180 degrees, with the encoder installed a quarter turn round. With no zero offset the encoder reads zero where the white lines line up and its wrap point is opposite that, inside the arm&#x27;s travel, so YAMS reports an angle 90 degrees off and then jumps by 360 degrees. With a zero offset of 90 degrees, the place where the encoder reads zero and the wrap point have both moved a quarter turn, the wrap point is outside the travel, and YAMS reports the right angle. The white line on the casing has not moved."><figcaption><p>The zero offset moves the zero, and the wrap point moves with it. The line on the casing stays where it is.</p></figcaption></figure>

**Check it:** deploy and hold the arm horizontal. `getExternalEncoderMechanismPosition()` on the `SmartMotorController`, the absolute encoder's angle, reads about 0°, as does the arm's angle under **NetworkTables > Mechanisms**.
{% endstep %}

{% step %}

### Configure the simulation starting position

Simulation has no physical encoder, so the absolute encoder reading is unavailable in sim. Use `.withSimStartingPosition()` to tell the simulator where the arm starts. On a real robot this value is ignored, the true encoder reading is always used.

```java
.withSimStartingPosition(Degrees.of(0))  // arm starts horizontal in sim
```

**Check it:** start the simulation. The arm starts at the angle you gave.
{% endstep %}
{% endstepper %}

***

## Complete examples

The gains in these examples (`kP` of 4, and an `ArmFeedforward` of all zeros) are **placeholders**: with them the arm moves but sags below its setpoints. Find `kG` and then `kP` with the [Arm tutorial's Tune it step](/documentation/tutorials/arm/tune).

### SparkMax + SparkAbsoluteEncoder

```java
private final SparkMax armMotor = new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless);

private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0)
    .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
    .withFeedforward(new ArmFeedforward(0, 0, 0, 0))
    .withSoftLimits(Degrees.of(-30), Degrees.of(100))
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withZeroPower(MotorMode.BRAKE)
    .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH)
    .withStatorCurrentLimit(Amps.of(40))
    .withExternalEncoder(armMotor.getAbsoluteEncoder())
    .withExternalEncoderInverted(false)
    .withExternalEncoderZeroOffset(Degrees.of(33.25))
    .withWrapping(Rotations.of(-0.5), Rotations.of(0.5))  // [-0.5, 0.5) range
    .withUseExternalFeedbackEncoder(true)
    .withSimStartingPosition(Degrees.of(0));

private final SmartMotorController smc = new SparkWrapper(armMotor, DCMotor.getNEO(1), motorConfig);
```

### TalonFX + CANcoder

```java
private final TalonFX armMotor = new TalonFX(1, new CANBus(CANPort.CAN_S0));
private final CANcoder cancoder = new CANcoder(2, new CANBus(CANPort.CAN_S0));

private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0)
    .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
    .withFeedforward(new ArmFeedforward(0, 0, 0, 0))
    .withSoftLimits(Degrees.of(-30), Degrees.of(100))
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withZeroPower(MotorMode.BRAKE)
    .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH)
    .withStatorCurrentLimit(Amps.of(40))
    .withExternalEncoder(cancoder)
    .withExternalEncoderInverted(false)
    .withExternalEncoderZeroOffset(Degrees.of(33.25))
    .withWrapping(Rotations.of(-0.5), Rotations.of(0.5))  // [-0.5, 0.5) range
    .withUseExternalFeedbackEncoder(true)
    .withSimStartingPosition(Degrees.of(0));

private final SmartMotorController smc = new TalonFXWrapper(armMotor, DCMotor.getKrakenX60(1), motorConfig);
```

### TalonFXS + CANdi

The absolute encoder plugs into one of the `CANdi`'s PWM inputs, and the TalonFXS reads the `CANdi` over CAN, so the encoder is not wired to the Talon at all. YAMS configures the `CANdi` the same way as a CANcoder.

A `CANdi` has two PWM inputs, so tell the Talon which one the encoder is on with a vendor config. Without it, YAMS throws a `SmartMotorControllerConfigurationException` because no PWM input is selected. Use `SyncCANdiPWM1` for the PWM1 input or `SyncCANdiPWM2` for PWM2. YAMS sets the matching input on the `CANdi` from the other options here.

```java
private final TalonFXS armMotor = new TalonFXS(1, new CANBus(CANPort.CAN_S0));
private final CANdi candi = new CANdi(2, new CANBus(CANPort.CAN_S0));

private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0)
    .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
    .withFeedforward(new ArmFeedforward(0, 0, 0, 0))
    .withSoftLimits(Degrees.of(-30), Degrees.of(100))
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withZeroPower(MotorMode.BRAKE)
    .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH)
    .withStatorCurrentLimit(Amps.of(40))
    // The encoder is on the CANdi's PWM1 input.
    .withVendorConfig(new TalonFXSConfiguration()
        .withExternalFeedback(new ExternalFeedbackConfigs()
            .withExternalFeedbackSensorSource(ExternalFeedbackSensorSourceValue.SyncCANdiPWM1)))
    .withExternalEncoder(candi)
    .withExternalEncoderInverted(false)
    .withExternalEncoderZeroOffset(Degrees.of(33.25))
    .withWrapping(Rotations.of(-0.5), Rotations.of(0.5))  // [-0.5, 0.5) range
    .withUseExternalFeedbackEncoder(true)
    .withSimStartingPosition(Degrees.of(0));

private final SmartMotorController smc = new TalonFXSWrapper(armMotor, DCMotor.getMinion(1), motorConfig);
```

On a TalonFX the feedback source is in `Feedback` instead:

```java
.withVendorConfig(new TalonFXConfiguration()
    .withFeedback(new FeedbackConfigs()
        .withFeedbackSensorSource(FeedbackSensorSourceValue.SyncCANdiPWM1)))
```

The CTRE types come from Phoenix 6: `com.ctre.phoenix6.configs.TalonFXSConfiguration`, `ExternalFeedbackConfigs`, `TalonFXConfiguration` and `FeedbackConfigs`, and `com.ctre.phoenix6.signals.ExternalFeedbackSensorSourceValue` and `FeedbackSensorSourceValue`.

### Thrifty Nova + absolute encoder on the data port

Pass `FeedbackSensorType.ABS` as the external encoder and tell the Nova which encoder is wired to its data port through the vendor config. The Nova runs this arm's PID, profile and feedforward itself, closing its loop on the encoder, which it reads over \[0, 1): set the zero offset so the wrap point, at the arm's zero, is outside the travel. For an arm that crosses it, set another range with `withWrapping`, and the loop runs on the SystemCore instead. A Thrifty `CanEncoder` on the same CAN bus works too: pass the `CanEncoder` object to `.withExternalEncoder(...)` instead.

```java
private final Nova armMotor = new Nova(0, 1, MotorType.NEO);

private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0)
    .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
    .withFeedforward(new ArmFeedforward(0, 0, 0, 0))
    .withSoftLimits(Degrees.of(-30), Degrees.of(100))
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withZeroPower(MotorMode.BRAKE)
    .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH)
    .withStatorCurrentLimit(Amps.of(40))
    .withVendorConfig(NovaConfig.absoluteEncoderType(AbsoluteEncoderType.REV_ENCODER))
    .withExternalEncoder(FeedbackSensorType.ABS)
    .withExternalEncoderInverted(false)
    .withExternalEncoderZeroOffset(Degrees.of(33.25))
    // The Nova closes its loop on the encoder, which it reads over [0, 1): the default.
    .withUseExternalFeedbackEncoder(true)
    .withSimStartingPosition(Degrees.of(0));

private final SmartMotorController smc = new NovaWrapper(armMotor, DCMotor.getNEO(1), motorConfig);
```

The Nova types come from ThriftyLib: `com.thrifty.nova.Nova`, `com.thrifty.nova.NovaConfig`, `com.thrifty.core.Motor.MotorType`, `com.thrifty.core.Motor.FeedbackSensorType` and `com.thrifty.core.Motor.AbsoluteEncoderType`. The [motor controller feature matrix](/documentation/reference/editor/feature-matrix) lists what the Nova supports.

### FIRST A301 + its own absolute encoder

The A301 has an absolute encoder on its output shaft, after its gearbox. Pass the `A301` itself as the external encoder. YAMS applies the zero offset, inversion and wrapping range to its reading, and runs the arm's PID, profile and feedforward on the SystemCore. The A301 has no current limits, so leave out `withStatorCurrentLimit`.

Here the A301's 135:1 gearbox drives the arm's shaft directly, so the encoder turns once per arm turn and needs no `withExternalEncoderGearing`. With a chain or gears after the A301, the encoder gearing is that ratio, such as `.withExternalEncoderGearing(3)` for a 3:1 chain, and the arm's travel times that ratio must stay under one rotation: see [Check your gear ratio and mount](#check-your-gear-ratio-and-mount).

```java
private final A301 armMotor = new A301(CANPorts.fromBusId(1), 1);

private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0)
    .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
    .withFeedforward(new ArmFeedforward(0, 0, 0, 0))
    .withSoftLimits(Degrees.of(-30), Degrees.of(100))
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(135)))  // the A301's gearbox, rotor to arm
    .withZeroPower(MotorMode.BRAKE)
    .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH)
    .withExternalEncoder(armMotor)
    .withExternalEncoderInverted(false)
    .withExternalEncoderZeroOffset(Degrees.of(33.25))
    .withWrapping(Rotations.of(-0.5), Rotations.of(0.5))  // [-0.5, 0.5) range
    .withUseExternalFeedbackEncoder(true)
    .withSimStartingPosition(Degrees.of(0));

private final SmartMotorController smc = new A301Wrapper(armMotor, motorConfig);
```

The A301 comes from REVLib: `com.revrobotics.spark.A301`, with `com.revrobotics.util.CANPorts`. `A301Wrapper` takes no `DCMotor`.

{% hint style="info" %}
Imports for these examples: `SmartMotorControllerConfig` comes from `yams.commands2.config` (or `yams.commands3.config` for Commands v3). `SmartMotorController`, the wrappers (`yams.core.motorcontrollers.local.SparkWrapper`, `yams.core.motorcontrollers.local.NovaWrapper`, `yams.core.motorcontrollers.local.A301Wrapper`, `yams.core.motorcontrollers.remote.TalonFXWrapper`, `yams.core.motorcontrollers.remote.TalonFXSWrapper`), `yams.core.motorcontrollers.enums.ControlMode`/`MotorMode`, `yams.core.gearing.*` and `yams.core.telemetry.enums.TelemetryVerbosity` all come from `yams.core`. CTRE devices take a `com.ctre.phoenix6.CANBus`, built here from WPILib's `org.wpilib.hardware.bus.CANPort`.
{% endhint %}

***

## Using absolute encoders on a Pivot

The exact same external encoder setup described above works identically for `Pivot` mechanisms (turrets, wrists, and any other single-axis rotational mechanism). The configuration API and all five setup steps are unchanged, just substitute your `PivotConfig` and the appropriate wrapper.

## Code reference

The arm example demonstrates configuring an arm with a CANcoder as its external feedback encoder:

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/ArmSubsystem.java>" %}

## Check it

1. Deploy, and hold the arm horizontal. The arm's angle under **NetworkTables > Mechanisms** should read about 0°.
2. Move the arm by hand through its whole travel. The angle should follow it smoothly, with no jump of 360° anywhere.
3. Power cycle the robot with the arm somewhere else. After boot it should read the right angle straight away, with no homing.

## If it did not work

* **The angle reads about twice your offset, or the offset is the wrong way.** Check the units above, and that the client had no offset of its own set when you read the value.
* **The angle jumps by 360° partway through the travel.** The wrap point is inside the travel; see [Choose the wrapping range](#choose-the-wrapping-range).
* **The angle goes the wrong way.** See [Check your inversion](#check-your-inversion), or [Troubleshooting](/documentation/tutorials/troubleshooting).

## Read more

Send the arm to an angle: [How do I set an arm's target angle?](/documentation/how-to-mechanisms/how-to-set-an-arms-target-angle)


# How do I home a mechanism with limit switches?

**Goal:** reset your mechanism's encoder to a known position whenever it presses a limit switch at a hard stop.

A relative encoder only knows how far the mechanism has moved since the robot turned on, and a slipped belt or a skipped gear throws it off. A limit switch at a hard stop tells the mechanism where it is: when the mechanism presses it, the motor's encoder is set to that hard stop. This is homing. It works for arms, elevators, pivots and turrets.

[YAMG](https://yamg.yassrobotics.com) generates this code for you: turn on **Homing** in its form.

## Wrap the switch in a `Sensor`

Plug the switch into a SystemCore Smart IO port and read it with a `DigitalInput`. Wrap it in a [`Sensor`](/documentation/understanding/sensors), so that the simulation can press it at the hard stop, as the mechanism presses the real one.

{% tabs %}
{% tab title="Commands v2" %}
{% code title="ArmSubsystem.java (fragment)" %}

```java
import static org.wpilib.units.Units.Degrees;

import org.wpilib.command2.Commands;
import org.wpilib.command2.button.Trigger;
import org.wpilib.hardware.discrete.DigitalInput;
import yams.core.mechanisms.config.SensorConfig;
import yams.core.motorcontrollers.simulation.Sensor;

// The arm's hard stops: -10 degrees and 100 degrees.
private final Arm arm = new Arm(armConfig, motor);

// A normally open switch between the signal and power pins of Smart IO port 4.
private final DigitalInput lowerSwitchInput = new DigitalInput(4);
private final Sensor lowerSwitch = new SensorConfig("ArmLowerSwitch")
    // The input reads high (true) while the switch is pressed.
    .withField("Pressed", lowerSwitchInput::get, false)
    // In simulation, the switch is pressed while the simulated arm is at its lower hard stop.
    .withSimulatedValue("Pressed", () -> motor.getSimSupplier()
        .map(sim -> sim.getMechanismPosition().lte(Degrees.of(-9.95)))
        .orElse(false), true)
    .getSensor();

public ArmSubsystem() {
  // Set the encoder to the hard stop once each time the switch is pressed.
  new Trigger(this::isLowerSwitchPressed)
      .onTrue(Commands.runOnce(() -> motor.setEncoderPosition(Degrees.of(-10))).withName("Arm Home LowerSwitch"));
}

public boolean isLowerSwitchPressed() {
  return lowerSwitch.getAsBoolean("Pressed");
}
```

{% endcode %}
{% endtab %}

{% tab title="Commands v3" %}
{% code title="ArmMechanism.java (fragment)" %}

```java
import static org.wpilib.units.Units.Degrees;

import org.wpilib.command3.Command;
import org.wpilib.command3.Trigger;
import org.wpilib.hardware.discrete.DigitalInput;
import yams.core.mechanisms.config.SensorConfig;
import yams.core.motorcontrollers.simulation.Sensor;

// The arm's hard stops: -10 degrees and 100 degrees.
private final Arm arm = new Arm(armConfig, motor);

// A normally open switch between the signal and power pins of Smart IO port 4.
private final DigitalInput lowerSwitchInput = new DigitalInput(4);
private final Sensor lowerSwitch = new SensorConfig("ArmLowerSwitch")
    // The input reads high (true) while the switch is pressed.
    .withField("Pressed", lowerSwitchInput::get, false)
    // In simulation, the switch is pressed while the simulated arm is at its lower hard stop.
    .withSimulatedValue("Pressed", () -> motor.getSimSupplier()
        .map(sim -> sim.getMechanismPosition().lte(Degrees.of(-9.95)))
        .orElse(false), true)
    .getSensor();

public ArmMechanism() {
  // Set the encoder to the hard stop once each time the switch is pressed.
  new Trigger(this::isLowerSwitchPressed)
      .onTrue(Command.noRequirements(coroutine -> motor.setEncoderPosition(Degrees.of(-10))).named("Arm Home LowerSwitch"));
}

public boolean isLowerSwitchPressed() {
  return lowerSwitch.getAsBoolean("Pressed");
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

These are fragments of the class that owns the arm: `motor` is its `SmartMotorController`, and the fields go after `motor` and `arm` (see the pitfall below).

For an elevator, compare the height and set it in meters: `smcConfig.convertFromMechanism(sim.getMechanismPosition()).lte(Meters.of(0.0005))` and `motor.setEncoderPosition(Meters.of(0))`.

The trigger runs its command once each time the switch goes from released to pressed, so the encoder is set once per press. The scheduler checks triggers every loop, which also reads the `Sensor` every loop, as its simulated values need.

## Home on demand: drive onto the switch

The trigger above homes the arm whenever it happens to press the switch. To home it on purpose (at the start of autonomous, or from a button in the pits), drive it slowly toward the switch until it is pressed, then set the encoder. A low voltage is enough to move it without slamming the hard stop; start around 1 to 2 volts and raise it only if the arm does not move. Negative voltage here moves the arm down toward the lower switch; flip the sign if yours is the other way.

{% tabs %}
{% tab title="Commands v2" %}
{% code title="ArmSubsystem.java (fragment)" %}

```java
/** Drive down slowly until the lower switch is pressed, then set the encoder to the hard stop. */
public Command home() {
  return arm.setVoltage(Volts.of(-1.5))
      .until(this::isLowerSwitchPressed)
      .andThen(Commands.runOnce(() -> {
        motor.setEncoderPosition(Degrees.of(-10));
        // Hold where it stopped, rather than going back to the old setpoint.
        arm.setMechanismPositionSetpoint(Degrees.of(-10));
      }))
      .withName("Arm Home");
}
```

{% endcode %}
{% endtab %}

{% tab title="Commands v3" %}
{% code title="ArmMechanism.java (fragment)" %}

```java
/** Drive down slowly until the lower switch is pressed, then set the encoder to the hard stop. */
public Command home() {
  return run(coroutine -> {
    while (true) {
      if (isLowerSwitchPressed()) {
        break;
      }
      arm.setVoltageSetpoint(Volts.of(-1.5));
      coroutine.yield();
    }
    motor.setEncoderPosition(Degrees.of(-10));
    // Hold where it stopped. This also starts the closed loop again.
    arm.setMechanismPositionSetpoint(Degrees.of(-10));
  }).named("Arm Home");
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Check it

1. Deploy, open the `ArmLowerSwitch` sensor under NetworkTables, and press the switch by hand. `Pressed` should be `true` only while you press it.
2. Run `home()` (or move the arm onto the switch). The arm should stop at the switch and its angle should read -10 degrees.
3. In simulation, the arm should read -10 degrees each time it reaches the lower hard stop (except with a SPARK; see the last pitfall).

## Common pitfalls

### The switch is wired or read like an older controller's

A SystemCore Smart IO port is the opposite of the DIO ports on older FRC controllers. It has a pull-down resistor, not a pull-up, and runs at 3.3 V. Wire a switch between the port's **signal** and **power** pins: the input reads low (`false`) while the switch is open, and high (`true`) while it is closed. A normally open switch therefore reads `true` while it is pressed, so its field is `input.get()`. A normally closed switch reads `false` while it is pressed, so its field is `!input.get()`. See [Digital Inputs - Hardware](https://docs.wpilib.org/en/latest/docs/hardware/sensors/digital-inputs-hardware.html).

Code ported from an older robot often reads `!input.get()`, because the older controllers' pull-up made a pressed switch read `false`. On a SystemCore that reads backwards, and the mechanism homes whenever the switch is *not* pressed.

{% hint style="danger" %}
Never wire a switch between the power and ground pins, as switches on older controllers were wired between signal and ground: closing it connects power directly to ground, which trips the SystemCore's protection.
{% endhint %}

Check the switch before trusting it: press it by hand and watch the field on your dashboard.

### Soft limits keep the mechanism off the switch

Put the soft limit at the hard stop, where the switch is pressed. A soft limit inside the hard stop stops the mechanism before it reaches the switch, so the switch only homes it when it is already resting there, such as when the robot turns on. A homing command does not get around this: on a TalonFX or TalonFXS in `CLOSED_LOOP` mode, YAMS sets the soft limits on the Talon itself, and the Talon stops every request at them, including the voltage of `home()`.

### The encoder is set every loop

Home with `onTrue`, which sets the encoder once, as the switch is pressed. `whileTrue`, or an `if` in `periodic()`, sets it every loop while the switch is held. A mechanism often rests on its lower switch for most of a match, so that's a write to the motor controller every 20 ms, and a Talon waits for each one to be acknowledged. It also holds the encoder at the hard stop while the switch is pressed, so the encoder doesn't follow the mechanism through the last bit of the switch's travel. Home on the rising edge (`onTrue`, the moment the switch is pressed). `onFalse` is the falling edge: it homes as the mechanism leaves the switch, and where that happens depends on which way the mechanism moves and on the switch's hysteresis.

### The switch is not where the hard stop is

Homing sets the encoder to where the mechanism is when the switch is pressed. A switch that presses a little before the hard stop homes the mechanism to the wrong position by that much. Set the encoder to the position the switch presses at: move the mechanism onto the switch by hand and read where it is.

### The switch bends or moves

The mechanism hits its switches at the hard stops, which can bend them, shift their mounts or wear their levers. A switch that moves presses at a different position, so homing sets the wrong position, and the mechanism is off by that much until it homes again. Check the switches regularly, such as in pit checks: that they are tight and straight, and that the mechanism reads the hard stop when it presses each one.

### The `Sensor` is declared before the mechanism

The simulated value's lambda uses `motor` (or the mechanism). Java does not let a field's initializer use a field declared after it, even in a lambda, so declare the `Sensor` after them.

### The simulation presses the switch from the encoder

Press the simulated switch from where the simulated mechanism really is, `motor.getSimSupplier()`, rather than from the encoder, `arm.getAngle()`. A real switch is pressed by the mechanism, not by what the encoder says. If the encoder is off, a switch pressed from the encoder is pressed in the wrong place, and homing never corrects it.

### The sensor is not read every loop

A `Sensor`'s simulated values only apply when its field is read. A trigger reads it every loop. If you read it yourself, read it every loop, rather than only inside a command that may not be running.

### Two devices share a Smart IO port

A duty cycle absolute encoder, such as a Through Bore Encoder on the SystemCore, also uses a Smart IO port. Give each switch and each encoder its own port.

### A SPARK does not home in simulation

In REVLib 2027.0.0-alpha-7, the simulated SPARK sets its encoder back to its own position on the next loop, whatever sets it. The switches are still pressed at the hard stops in simulation, but `setEncoderPosition` does not change the simulated SPARK's encoder. Homing a real SPARK is not affected.

## If it did not work

See the pitfalls above, or [Troubleshooting](/documentation/tutorials/troubleshooting).


# How do I zero a mechanism without limit switches?

**Goal:** make your arm or elevator's encoder read the right position, when there is no limit switch and no absolute encoder.

A motor's built-in encoder is **relative**: it only knows how far the mechanism has moved since it was last set. YAMS sets it once, when the robot code starts, to the starting position in your config. Everything after that is counted from there. If the mechanism was somewhere else at power on, or a belt skipped, every position is off by the same amount.

There are three ways to set it without a switch, from simplest to most automatic. They are alternatives: pick one. If you can add a sensor, an [absolute encoder](/documentation/how-to-mechanisms/how-do-i-use-absolute-encoders-on-my-arm) or a [limit switch](/documentation/how-to-mechanisms/how-do-i-home-a-mechanism-with-limit-switches) is more reliable than any of them.

## Always start in the same place

Pick a position the mechanism can always rest in when the robot is turned on, usually against its lower hard stop, and tell YAMS that position with `withStartingPosition` on the `SmartMotorControllerConfig`. A `Distance` starting position needs the drum size first, so it goes after `withMechanismCircumference` (or `withDrumRadius`): without it, YAMS cannot turn meters into rotations and throws.

{% code title="ElevatorSubsystem.java (fragment)" %}

```java
SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    // ...
    .withMechanismCircumference(Inches.of(5.5))
    // The carriage rests on its lower hard stop when the robot turns on.
    .withStartingPosition(Meters.of(0));
```

{% endcode %}

For an arm, use an `Angle`, such as `.withStartingPosition(Degrees.of(-10))` for an arm resting on a stop 10 degrees below horizontal.

This only works if the whole team follows the rule: **the mechanism must be at that position whenever the robot code starts**, including after a code deploy or a brownout. Put it on the pre-match checklist.

## A "zero here" button

When the encoder is wrong, a human can push the mechanism to its hard stop and press a button that says "you are here". `SmartMotorController.setEncoderPosition` sets the encoder to the position you give it. `motor` is the `SmartMotorController` your mechanism was built with; these methods go in the same class.

{% tabs %}
{% tab title="Commands v2" %}
{% code title="ElevatorSubsystem.java (fragment)" %}

```java
/** Tell the encoder the carriage is on its lower hard stop. Works while disabled. */
public Command zeroHere() {
  return Commands.runOnce(() -> motor.setEncoderPosition(Meters.of(0)))
      .ignoringDisable(true)
      .withName("Elevator Zero Here");
}
```

{% endcode %}

Bind it to a button the drive team will not press by accident, for example `m_operatorController.back().onTrue(elevator.zeroHere());`.
{% endtab %}

{% tab title="Commands v3" %}
{% code title="ElevatorMechanism.java (fragment)" %}

```java
/** Tell the encoder the carriage is on its lower hard stop. */
public Command zeroHere() {
  return Command.noRequirements(coroutine -> motor.setEncoderPosition(Meters.of(0)))
      .named("Elevator Zero Here");
}
```

{% endcode %}

Bind it in your opmode to a button the drive team will not press by accident, for example `controller.back().onTrue(robot.elevator.zeroHere());`.
{% endtab %}
{% endtabs %}

Disable the robot, push the carriage down onto the stop by hand, and press the button.

## Drive into the hard stop and watch the current

The robot can find the hard stop itself: drive the mechanism slowly toward it, and when it stops moving and the current rises, it has arrived. This is current, or stall, homing.

Use the `home()` command from [Home on demand: drive onto the switch](/documentation/how-to-mechanisms/how-do-i-home-a-mechanism-with-limit-switches#home-on-demand-drive-onto-the-switch), with two changes: it stops on `isStalled()` below instead of `isLowerSwitchPressed()`, and it sets the encoder to your hard stop, `Meters.of(0)` here, with `elevator.setMeasurementPositionSetpoint(Meters.of(0))` to hold it. The stall check is the only new part, and is the same for Commands v2 and v3:

{% code title="ElevatorSubsystem.java (fragment)" %}

```java
import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.MetersPerSecond;

import org.wpilib.math.filter.Debouncer;
import org.wpilib.units.measure.Current;

// Measure this on your robot: graph current/stator while the carriage pushes on the stop.
// Keep it well below the stator current limit.
private static final Current STALL_CURRENT = Amps.of(20);
// True only once the stall has lasted 0.25 seconds.
private final Debouncer stallDebouncer = new Debouncer(0.25);

/** True once the carriage has pushed on its hard stop, not moving, for 0.25 seconds. */
private boolean isStalled() {
  return stallDebouncer.calculate(
      motor.getStatorCurrent().gte(STALL_CURRENT)
          && motor.getMeasurementVelocity().isNear(MetersPerSecond.of(0), MetersPerSecond.of(0.02)));
}
```

{% endcode %}

The speed check matters: the current also rises for a moment when the motor starts, but the mechanism is moving then. It is the same idea as [detecting a game piece from motor current](/documentation/how-to-motor-controllers-and-sensors/how-do-i-sense-activity-based-off-of-the-current).

Put the soft limit at the hard stop. A soft limit inside it stops the mechanism short, so homing never finishes: on a TalonFX or TalonFXS, the Talon enforces the soft limits itself and stops the homing voltage too. See [Soft limits keep the mechanism off the switch](/documentation/how-to-mechanisms/how-do-i-home-a-mechanism-with-limit-switches#soft-limits-keep-the-mechanism-off-the-switch).

## Check it

1. Move the mechanism away from the hard stop, then zero it with the method you chose.
2. Under **NetworkTables > Mechanisms**, the motor's `measurement/position` (or the arm's angle) should read the hard stop position, 0 m here.
3. Send it to a known height and measure with a tape measure: it should match.

## If it did not work

* **The position is off by the same amount every time.** The mechanism was not at the starting position when the code started, or the zero position in your code is not where the hard stop really is.
* **Stall homing ends too early.** The threshold is too low, or the start up spike is longer than the debounce. Raise the threshold or the debounce time.
* **Stall homing never ends.** The threshold is at or above the current limit, or the soft limit is inside the hard stop. Move the soft limit to the hard stop.
* **Something else.** See [Troubleshooting](/documentation/tutorials/troubleshooting).

## Read more

Before the first enable on the robot, work through the first-enable checks in the [Arm tutorial's Run it on the robot step](/documentation/tutorials/arm/robot). The elevator tutorial has no robot step, and the same checks apply to an elevator.


# How do I control a mechanism that carries a game piece?

A game piece makes a mechanism heavier, and can move its center of mass, which changes the feedforward and feedback gains it needs.

Gains tuned on an empty mechanism are tuned for that mechanism. Pick up a game piece and the elevator is heavier, and the arm is heavier and has its center of mass further out. An empty arm that holds its angle perfectly can sag below it with a game piece, or overshoot and oscillate when it moves.

How much changes depends on the mechanism: how heavy the game piece is next to the mechanism, and where it is held.

**Before you start:** tune the empty mechanism first, as in its tutorial's Tune it step ([Arm](/documentation/tutorials/arm/tune), [Elevator](/documentation/tutorials/elevator/tune)). This page starts from those gains.

## What changes, and what doesn't

| Gain           | Depends on                                                   | With a game piece                                                         |
| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------- |
| `kS`           | Friction in the gearbox and bearings                         | Barely changes                                                            |
| `kV`           | The motor and the gearing                                    | **Does not change.** It is the voltage the motor needs to spin at a speed |
| `kG`           | The weight, and for an arm how far out the center of mass is | **Goes up**, often a lot                                                  |
| `kA`           | The mass, or for an arm the moment of inertia                | Goes up                                                                   |
| `kP`, `kD`     | The mass or inertia they have to move                        | The same gains move a heavier mechanism more slowly, with more overshoot  |
| Profile limits | How fast the motors can accelerate the mechanism             | A heavier mechanism may not keep up with the profile                      |

`kG` is usually the one that matters. It holds the mechanism up, so a `kG` that is too small makes the mechanism sit below its setpoint, with `kP` pushing against the difference.

## How much it changes, by mechanism

| Mechanism          | `kG` with the game piece                                                                                                                                             | Example                                                                                |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Elevator           | `kG` empty × (carriage weight + game piece weight) / carriage weight                                                                                                 | A 1 kg game piece on a 4 kg carriage: 25% more                                         |
| Arm                | `kG` empty × (arm weight × arm's center of mass distance + game piece weight × its distance) / (arm weight × arm's center of mass distance)                          | A 1 kg game piece 0.6 m out, on a 3 kg arm with its center of mass 0.3 m out: 67% more |
| Arm on an elevator | The elevator's `kG` goes up with the arm and game piece, whatever the arm's angle                                                                                    |                                                                                        |
| Shooter flywheel   | No `kG`, and `kV` does not change: the game piece passes through. See [How do I shoot with a shooter?](/documentation/how-to-mechanisms/how-to-shoot-with-a-shooter) |                                                                                        |

These give a starting point, and tell you whether a game piece changes the gains enough to matter: a change of a few percent may not be worth a second set of gains. A spring or counterweight takes a fixed amount off an elevator's `kG`. A cascading or continuous elevator's `kG` steps up as each stage is picked up, and a telescoping arm's or an arm with a wrist changes as it moves: see [A mechanism whose gains change as it moves](#a-mechanism-whose-gains-change-as-it-moves). A game piece held off to one side of an arm moves the angle where gravity pulls hardest, which `ArmFeedforward` does not model, so the arm holds well at some angles and sags at others.

## Measure the gains with the game piece

Measure the loaded gains on the robot, by driving the motor at a voltage with live tuning: on the [YAMS Live Tuner](/documentation/how-to-tuning/live-tuning/live-tuner)'s **Voltage** tab, or by setting the motor's `voltage/enabled` to `true` and typing into `voltage/setpoint` under `NT:/Tuning/<Mechanism>/<Motor>/`. [Drive a motor at a voltage](/documentation/how-to-tuning/live-tuning#drive-a-motor-at-a-voltage) shows how.

{% stepper %}
{% step %}

### Load it and let go

Load a game piece, and move the mechanism to where gravity pulls hardest: an arm level, or an elevator at any height. Start the `Live Tuning` command and turn `voltage/enabled` on, so that only the voltage you type holds it from here on.

**Check it:** the mechanism drifts down slowly at 0 V, and moves when you type a voltage.
{% endstep %}

{% step %}

### Find the up and down voltages

Raise `voltage/setpoint` until the mechanism just starts to move up, and note it. Lower it until the mechanism just starts to move down, and note that.

**Check it:** the up voltage is larger than the down voltage.
{% endstep %}

{% step %}

### Work out kG and kS

`kG` is halfway between the two voltages. `kS` is half the difference between them. Turn `voltage/enabled` off and type the new `kG` into the loaded slot's feedforward.

**Check it:** the loaded `kG` is larger than the empty one, by about what [the table above](#how-much-it-changes-by-mechanism) predicts.
{% endstep %}

{% step %}

### Check the setpoints

With that `kG`, send the mechanism to its setpoints with the game piece, and raise `kP` (and `kD`) if it is slow.

**Check it:** the loaded mechanism settles on each setpoint, rather than sagging below it.
{% endstep %}
{% endstepper %}

## Switch gains when the mechanism picks up a game piece

A motor controller holds up to four [slots](/documentation/reference/editor/config/closed-loop-control#slots) of gains, each with its own [feedforward](/documentation/reference/editor/config/feedforward#slots). Put the empty gains in one slot and the loaded gains in another, and switch slots when the mechanism picks up or lets go of a game piece. Switching is quick: it only changes which slot the motor controller uses.

{% tabs %}
{% tab title="Commands v2" %}
{% code title="ArmSubsystem.java (fragment)" %}

```java
import org.wpilib.command2.Commands;
import org.wpilib.command2.button.Trigger;
import org.wpilib.math.controller.ArmFeedforward;
import yams.core.motorcontrollers.SmartMotorController.ClosedLoopControllerSlot;

private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    // Empty.
    .withClosedLoopController(40, 0, 0, ClosedLoopControllerSlot.SLOT_0)
    .withFeedforward(new ArmFeedforward(0.1, 0.35, 1.2), ClosedLoopControllerSlot.SLOT_0)
    // Holding a game piece: more kG to hold it up, and more kP to move the extra weight.
    .withClosedLoopController(55, 0, 0, ClosedLoopControllerSlot.SLOT_1)
    .withFeedforward(new ArmFeedforward(0.1, 0.60, 1.2), ClosedLoopControllerSlot.SLOT_1)
    // ... the rest of the config
    ;

public ArmSubsystem() {
  // Switch gains as the intake picks up and lets go of a game piece. The commands require
  // nothing, so they do not interrupt the command moving the arm.
  new Trigger(this::hasGamePiece)
      .onTrue(Commands.runOnce(() -> motor.setClosedLoopSlot(ClosedLoopControllerSlot.SLOT_1)))
      .onFalse(Commands.runOnce(() -> motor.setClosedLoopSlot(ClosedLoopControllerSlot.SLOT_0)));
}
```

{% endcode %}
{% endtab %}

{% tab title="Commands v3" %}
{% code title="ArmMechanism.java (fragment)" %}

```java
import org.wpilib.command3.Command;
import org.wpilib.command3.Trigger;
import org.wpilib.math.controller.ArmFeedforward;
import yams.core.motorcontrollers.SmartMotorController.ClosedLoopControllerSlot;

private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    // Empty.
    .withClosedLoopController(40, 0, 0, ClosedLoopControllerSlot.SLOT_0)
    .withFeedforward(new ArmFeedforward(0.1, 0.35, 1.2), ClosedLoopControllerSlot.SLOT_0)
    // Holding a game piece: more kG to hold it up, and more kP to move the extra weight.
    .withClosedLoopController(55, 0, 0, ClosedLoopControllerSlot.SLOT_1)
    .withFeedforward(new ArmFeedforward(0.1, 0.60, 1.2), ClosedLoopControllerSlot.SLOT_1)
    // ... the rest of the config
    ;

public ArmMechanism() {
  // Switch gains as the intake picks up and lets go of a game piece. The commands require
  // nothing, so they do not interrupt the command moving the arm.
  new Trigger(this::hasGamePiece)
      .onTrue(Command.noRequirements(coroutine -> motor.setClosedLoopSlot(ClosedLoopControllerSlot.SLOT_1))
          .named("Arm Loaded Gains"))
      .onFalse(Command.noRequirements(coroutine -> motor.setClosedLoopSlot(ClosedLoopControllerSlot.SLOT_0))
          .named("Arm Empty Gains"));
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

The gains in this code are **placeholders** to show the shape of the change; use the ones you measured above.

`hasGamePiece()` is whatever tells you the mechanism has a game piece: a beam break, a distance sensor, or the intake's current, as in [How do I detect a game piece from motor current?](/documentation/how-to-motor-controllers-and-sensors/how-do-i-sense-activity-based-off-of-the-current). The slot takes effect with the next setpoint, and a mechanism's commands send a setpoint every loop.

[Loosely coupled followers](/documentation/reference/editor/config/followers#withlooselycoupledfollowers) are switched to the same slot, on every motor controller (SPARK MAX, SPARK Flex, TalonFX, TalonFXS, Thrifty Nova and A301). Give each follower the same slots in its own config.

## A mechanism whose gains change as it moves

A telescoping arm, an arm with a wrist, or an elevator picking up its stages needs a different `kG` as it moves, not only with a game piece. Two ways to handle it:

* **Slots for ranges.** Up to four sets of gains, such as retracted, extended, and each with a game piece. Switch with triggers on the position, as above. This is the simplest, and the gains in each slot can be tuned on their own.
* **Change `kG` as it moves**, with `motor.setKg(kG)`, worked out from the extension or angle. Only do this when `kG` has changed enough to matter, not every loop: on a Talon, SPARK or Thrifty Nova, `setKg` writes the motor controller's configuration, which takes time. On a mechanism whose [closed loop runs on the SystemCore](/documentation/reference/editor/config/closed-loop-control#where-the-loop-runs), it only changes a number.

## Common pitfalls

### Only `kP` was raised

A heavier mechanism that sags looks like it needs more `kP`. Raising `kP` pushes it closer to the setpoint, but it still sits below it, and a `kP` large enough to hide the sag makes the empty mechanism oscillate. Raise `kG` first, and `kP` only if the mechanism is still slow.

### The slot switches on a flickering sensor

A sensor that flickers as a game piece passes switches the gains back and forth. Debounce the trigger so it only switches once the sensor has settled: in Commands v2, `new Trigger(this::hasGamePiece).debounce(0.1)` (seconds); in Commands v3, `new Trigger(this::hasGamePiece).debounce(Seconds.of(0.1))`, with `import static org.wpilib.units.Units.Seconds;`.

### Slot 3 on a Talon

A TalonFX and a TalonFXS have three slots, `SLOT_0` to `SLOT_2`. Selecting `SLOT_3` throws an exception.

### The profile is too fast for the loaded mechanism

The motion profile's limits are the same in every slot. A profile that the empty mechanism keeps up with can be too fast with a game piece, so the mechanism lags behind it and overshoots at the end. Set the profile's limits for the loaded mechanism.

### The simulation is always empty

The simulation uses the mass and moment of inertia in the config, so it never carries the game piece. Gains for the loaded mechanism can be checked in simulation by setting the config's mass to the loaded mass, but tune them on the robot.

## Check it

Graph the arm's angle and setpoint, pick up a game piece, and send the arm to the same setpoint with and without it. With the right slot selected, the arm should settle on the setpoint both times, rather than sagging below it when loaded. Watch the motor's `closedloop/slot` value on the dashboard change from 0 to 1 as it picks the game piece up.


# How do I set up an intake roller?

**Goal:** spin an intake, roller, feeder or indexer in and out from buttons, with YAMS telemetry and simulation.

In YAMS a roller is a `FlyWheel`, even when it only ever needs a fixed voltage. Using `FlyWheel` gets you telemetry, simulation and live tuning for free, and lets you switch to speed control later without rewriting the subsystem. Put the motor in `ControlMode.OPEN_LOOP` and drive it with `set` (duty cycle, -1 to 1) or `setVoltage`.

Give each roller its own subsystem (Commands v2) or `Mechanism` (Commands v3): **one YAMS mechanism per subsystem**, so live tuning works and commands for the intake never block the shooter. If you are new to the parts used here, the [Shooter/FlyWheels tutorial](/documentation/tutorials/shooter-flywheels) builds the same kind of class step by step.

## The intake class

This example uses a SPARK MAX with CAN ID 9 driving a NEO through a 3:1 reduction to a 2 inch roller. Change the CAN ID, gearing and diameter to match your robot.

{% tabs %}
{% tab title="Commands v2" %}
{% code title="subsystems/IntakeSubsystem.java" lineNumbers="true" %}

```java
package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Pounds;
import static org.wpilib.units.Units.Volts;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command2.Command;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.system.DCMotor;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.mechanisms.FlyWheel;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.FlyWheelConfig;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class IntakeSubsystem extends SubsystemBase {

  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      // Open loop: no PID or feedforward, the motor just gets a duty cycle or voltage.
      .withControlMode(ControlMode.OPEN_LOOP)
      // 3:1 from the motor to the roller.
      .withGearing(new MechanismGearing(3))
      // Roller size and mass, used by the simulation.
      .withMomentOfInertia(Inches.of(1), Pounds.of(0.5))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("IntakeMotor", TelemetryVerbosity.HIGH);

  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 9, MotorType.kBrushless);

  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

  private final FlyWheelConfig intakeConfig = new FlyWheelConfig()
      .withDiameter(Inches.of(2))
      .withTelemetry("Intake", TelemetryVerbosity.HIGH);

  private final FlyWheel intake = new FlyWheel(intakeConfig, motor);

  /** Pull a game piece in. Runs until interrupted. */
  public Command intake() {
    return intake.setVoltage(Volts.of(8));
  }

  /** Push a game piece out. Runs until interrupted. */
  public Command eject() {
    return intake.setVoltage(Volts.of(-6));
  }

  /** Stop the roller. For the default command. */
  public Command stop() {
    return intake.set(0);
  }

  @Override
  public void periodic() {
    intake.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    intake.simIterate();
  }
}
```

{% endcode %}

Bind it in `RobotContainer`:

{% code title="RobotContainer.java (fragment)" %}

```java
private final IntakeSubsystem intake = new IntakeSubsystem();

// In the constructor or configureBindings():
intake.setDefaultCommand(intake.stop());
m_driverController.leftBumper().whileTrue(intake.intake());
m_driverController.rightBumper().whileTrue(intake.eject());
```

{% endcode %}
{% endtab %}

{% tab title="Commands v3" %}
{% code title="mechanisms/IntakeMechanism.java" lineNumbers="true" %}

```java
package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Pounds;
import static org.wpilib.units.Units.Volts;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command3.Command;
import org.wpilib.command3.Mechanism;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.system.DCMotor;
import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.mechanisms.FlyWheel;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.FlyWheelConfig;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class IntakeMechanism implements Mechanism {

  private final SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
      // Open loop: no PID or feedforward, the motor just gets a duty cycle or voltage.
      .withControlMode(ControlMode.OPEN_LOOP)
      // 3:1 from the motor to the roller.
      .withGearing(new MechanismGearing(3))
      // Roller size and mass, used by the simulation.
      .withMomentOfInertia(Inches.of(1), Pounds.of(0.5))
      .withMotorInverted(false)
      .withZeroPower(MotorMode.COAST)
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("IntakeMotor", TelemetryVerbosity.HIGH);

  private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 9, MotorType.kBrushless);

  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), smcConfig);

  private final FlyWheelConfig intakeConfig = new FlyWheelConfig()
      .withDiameter(Inches.of(2))
      .withTelemetry("Intake", TelemetryVerbosity.HIGH);

  private final FlyWheel intake = new FlyWheel(intakeConfig, motor);

  /** Pull a game piece in. Runs until interrupted. */
  public Command intake() {
    return intake.setVoltage(Volts.of(8));
  }

  /** Push a game piece out. Runs until interrupted. */
  public Command eject() {
    return intake.setVoltage(Volts.of(-6));
  }

  /** Stop the roller at the lowest priority, so any other intake command can take over. */
  public Command idle() {
    return run(coroutine -> coroutine.await(intake.set(0)))
        .withPriority(Command.LOWEST_PRIORITY)
        .named("Intake Idle");
  }

  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
  public void periodic() {
    intake.updateTelemetry();
  }

  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
  public void simulationPeriodic() {
    intake.simIterate();
  }
}
```

{% endcode %}

In `Robot`, create it, set the default command, call `periodic()` from `robotPeriodic()` and start its simulation `Notifier` in `simulationInit()`, as in the [Shooter/FlyWheels tutorial](/documentation/tutorials/shooter-flywheels/commands). Then bind it in your opmode:

{% code title="ExampleTeleop.java (fragment)" %}

```java
// In Robot(): intake.setDefaultCommand(intake.idle());
controller.leftBumper().whileTrue(robot.intake.intake());
controller.rightBumper().whileTrue(robot.intake.eject());
```

{% endcode %}
{% endtab %}
{% endtabs %}

`setVoltage` is usually better than `set` for a roller: 8 volts is 8 volts whether the battery is at 12.5 or 11.5 volts, so the intake behaves the same all match.

## Check it

1. Start the simulation (or enable the robot) and open **NetworkTables > Mechanisms > Intake** in your dashboard.
2. Hold the left bumper. The roller's speed should rise and settle, and the motor's output voltage should read about 8 volts.
3. Release it. The default command takes over and the roller coasts to a stop.

## If it did not work

* **The roller spins the wrong way.** Flip `withMotorInverted`, so that `intake()` pulls the game piece in.
* **The roller does nothing in teleop.** Another command is using the intake, or the default command was never set. In Commands v3, check that the bindings are in the opmode you selected.
* **Something else.** See [Troubleshooting](/documentation/tutorials/troubleshooting).

## Next

Stop the intake by itself when a game piece is in: [How do I detect a game piece from motor current?](/documentation/how-to-motor-controllers-and-sensors/how-do-i-sense-activity-based-off-of-the-current)


# How do I write my own mechanism command?

Write a command, an AdvantageKit IO class or a state machine that sets a mechanism's target with the setpoint functions.

The built-in commands, `run`, `runTo`, `set` and `setVoltage`, cover most needs. When they do not, for example when the target needs extra logic every loop, when an AdvantageKit IO class sets it, or when a state machine decides it, set the target yourself with the mechanism's **setpoint functions**. This page shows each case.

[Controlling a mechanism](/documentation/reference/controlling-a-mechanism#setpoint-functions) lists every setpoint function for each mechanism.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-27b85cd35baeaa4ffcfaab7c9665fb4120340950%2Fsetpoint-two-ways.png?alt=media" alt="Two paths to the same SmartMotorController. A command helper such as arm.run returns a Command that requires the subsystem; a button binding or auto sequence schedules it, and the scheduler stops it when another command needs the mechanism. A direct setpoint method such as arm.setMechanismPositionSetpoint returns nothing and sets the target at once; it is called from your own code, such as a custom command, an IO class or a state machine, and nothing is scheduled."><figcaption><p>A built-in command and a setpoint function end at the same motor controller.</p></figcaption></figure>

## The rules

* **A setpoint function sets the target and returns at once.** It is not a command, and it does not require the subsystem. Call it from inside a command that does, so two pieces of code never fight over the motor.
* **Position and velocity setpoint functions start the closed loop if it was stopped.** Voltage and duty cycle ones stop it. You do not need to manage the loop when you use them.
* **Starting a stopped loop resets it** to where the mechanism is now: the PID controller, the motion profile and the LQR's estimate start fresh. On a loop that is already running, starting it does nothing, so calling `setMechanismPositionSetpoint(...)` every loop is fine.
* **The motor keeps its last request when your command ends,** as with the built-in commands. See [When mechanism commands end](/documentation/understanding/run-vs-runto).

## A command with extra logic

This command follows a target from a supplier, and adds 5 degrees while the arm is below level.

{% tabs %}
{% tab title="Commands v2" %}

```java
package first.robot.commands;

import static org.wpilib.units.Units.Degrees;

import java.util.function.Supplier;
import org.wpilib.command2.Command;
import org.wpilib.units.measure.Angle;
import first.robot.subsystems.ArmSubsystem;

public class OffsetArmCommand extends Command
{
  private final ArmSubsystem    armSubsystem;
  private final Supplier<Angle> target;

  public OffsetArmCommand(ArmSubsystem armSubsystem, Supplier<Angle> target)
  {
    this.armSubsystem = armSubsystem;
    this.target = target;
    addRequirements(armSubsystem); // so no other command drives the arm at the same time
  }

  @Override
  public void execute()
  {
    Angle goal = target.get();
    if (armSubsystem.getArm().getAngle().lt(Degrees.of(0)))
    {
      goal = goal.plus(Degrees.of(5)); // below level, aim a little higher
    }
    armSubsystem.getArm().setMechanismPositionSetpoint(goal); // safe every loop
  }
}
```

`getArm()` is a getter you add to `ArmSubsystem` that returns its YAMS `Arm` field. The command never finishes, so bind it with `whileTrue`, or use it as a default command.
{% endtab %}

{% tab title="Commands v3" %}
Commands v3 has no command classes with `execute()`. Write the same logic as a `while (true)` coroutine in your `ArmMechanism`, where `arm` is its YAMS `Arm` field:

```java
// In ArmMechanism
public Command offsetTo(Supplier<Angle> target)
{
  return run(coroutine -> {
    while (true)
    {
      Angle goal = target.get();
      if (arm.getAngle().lt(Degrees.of(0)))
      {
        goal = goal.plus(Degrees.of(5)); // below level, aim a little higher
      }
      arm.setMechanismPositionSetpoint(goal); // safe every loop
      coroutine.yield();
    }
  }).named("Arm Offset To");
}
```

`run(...)` on a `Mechanism` requires that mechanism, so no other command drives the arm at the same time.
{% endtab %}
{% endtabs %}

To end a command like this when the arm arrives, check `arm.isNear(goal, tolerance)`: in Commands v2 return it from `isFinished()`, and in Commands v3 make it the `while` condition.

## An AdvantageKit IO class

An IO class is called by the subsystem, which owns the requirement, so it uses the setpoint functions directly. Take `Measure` types, not `double`:

```java
// Fragment: ArmIO is your IO interface, with setTargetAngle(Angle) and setVoltage(Voltage).
public class ArmIOYAMS implements ArmIO
{
  private final Arm arm; // built as in the Arm tutorial

  public ArmIOYAMS(Arm arm)
  {
    this.arm = arm;
  }

  @Override
  public void setTargetAngle(Angle angle)
  {
    arm.setMechanismPositionSetpoint(angle); // starts the closed loop if it was stopped
  }

  @Override
  public void setVoltage(Voltage volts)
  {
    arm.setVoltageSetpoint(volts); // stops the closed loop
  }
}
```

[AdvantageKit Integration](/documentation/tutorials/advantagekit-integration) builds the whole IO layer.

## A state machine (Commands v3)

WPILib's Commands v3 has a state machine built in, `org.wpilib.command3.StateMachine`. Each state runs one command, and transitions say when to move to another state. The state machine cancels the current state's command and starts the next one for you.

```java
// Fragment of ArmMechanism. motorConfig, motor and armConfig are built as in the Arm tutorial.
private static final Angle STOW_ANGLE   = Degrees.of(0);
private static final Angle INTAKE_ANGLE = Degrees.of(-20);
private static final Angle SCORE_ANGLE  = Degrees.of(80);
private static final Angle TOLERANCE    = Degrees.of(2);

private final Arm arm = new Arm(armConfig, motor);

/** The command for one state: hold an angle until the state machine moves on. */
private Command holdAt(String name, Angle angle)
{
  return run(coroutine -> {
    while (true)
    {
      arm.setMechanismPositionSetpoint(angle); // safe every loop
      coroutine.yield();
    }
  }).named(name);
}

/** Build the arm's state machine. It is itself a Command. */
public Command stateMachine(BooleanSupplier intakeRequested, BooleanSupplier scoreRequested,
                            BooleanSupplier hasGamePiece)
{
  StateMachine machine = new StateMachine("Arm State Machine");

  State stowed   = machine.addState(holdAt("Arm Stowed", STOW_ANGLE));
  State intaking = machine.addState(holdAt("Arm Intaking", INTAKE_ANGLE));
  State scoring  = machine.addState(holdAt("Arm Scoring", SCORE_ANGLE));

  machine.setInitialState(stowed);

  stowed.switchTo(intaking).when(intakeRequested);
  stowed.switchTo(scoring).when(() -> scoreRequested.getAsBoolean() && hasGamePiece.getAsBoolean());
  intaking.switchTo(stowed).when(hasGamePiece);  // stow once a game piece is in
  scoring.switchTo(stowed).when(() -> arm.isNear(SCORE_ANGLE, TOLERANCE) && !hasGamePiece.getAsBoolean());

  return machine;
}
```

The imports are `org.wpilib.command3.StateMachine`, `org.wpilib.command3.StateMachine.State` and `java.util.function.BooleanSupplier`. Schedule it like any other command. A `Trigger` is a `BooleanSupplier`, so buttons can be the conditions:

```java
// In Robot. arm is your ArmMechanism; intake.hasGamePiece() is your own sensor check.
Scheduler.getDefault().schedule(arm.stateMachine(controller.a(), controller.b(), intake::hasGamePiece));
```

How it behaves:

* **`setInitialState(state)` is required.** Without it the state machine throws when it starts.
* **`when(condition)` fires when the condition turns from false to true while that state is active.** A button already held when the state starts does not count until it is released and pressed again.
* **If two transitions fire in the same loop, the first one declared wins.**
* **The state machine itself requires nothing; each state's command requires the arm.** Another command that takes the arm cancels the running state, and with no `whenComplete()` transition from that state, the state machine exits.
* **A state whose command ends by itself, with no `whenComplete()` transition, also ends the state machine.** These `holdAt` commands never end, so this one runs until it is canceled.

## Driving the motor controller yourself

You can skip the mechanism and call the `SmartMotorController` from `arm.getMotorController()`, with `setPosition(...)`, `setVelocity(...)`, `setVoltage(...)` or `setDutyCycle(...)`. Unlike the setpoint functions, these calls do not start or stop the closed loop, so your command calls `startClosedLoopController()` or `stopClosedLoopController()` once when it starts. [How do I control a mechanism without a mechanism class?](/documentation/how-to-mechanisms/how-do-i-control-a-mechanism-without-a-mechanism-class) shows this in full.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-62ceef77e8ecca60ed63964c9901cd911abf90af%2Fsetpoint-closed-loop-state.png?alt=media" alt="Two panels for calls made straight to the SmartMotorController. Position or velocity requests, motor.setPosition and motor.setVelocity, need the closed loop running: call startClosedLoopController once when your command starts, or the request is ignored and the mechanism does not move. Voltage or duty cycle requests, motor.setVoltage and motor.setDutyCycle, need the closed loop stopped: call stopClosedLoopController once when your command starts, or the loop overwrites your output on its next run. This only matters when the closed loop runs on the SystemCore. The mechanism setpoint functions and command helpers do it for you."><figcaption><p>Calling the motor controller directly: start the closed loop for position and velocity, stop it for voltage and duty cycle. The setpoint functions do this for you.</p></figcaption></figure>

## Read more

[When mechanism commands end](/documentation/understanding/run-vs-runto) explains how your command fits with `runTo` and the default command.


# How do I control a mechanism without a mechanism class?

Control each SmartMotorController yourself, such as when the motors of one mechanism need different setpoints.

**Goal:** drive two motors that belong to one mechanism, but need **different** setpoints, from one subsystem with your own commands.

The example is a shooter with a top wheel and a bottom wheel. Spinning the bottom wheel faster than the top one puts backspin on the game piece, so the two wheels need different speeds at the same time.

## Do you need this page?

YAMS mechanism classes (`Arm`, `Elevator`, `FlyWheel` and so on) drive one motor and its followers with one setpoint. Use them when you can:

* **Motors on one shaft or gearbox** that always do the same thing: make the others [followers](/documentation/reference/editor/config/followers#withfollowers).
* **Separate motors that must move together**, such as one on each side of an intake arm: make the others [loosely coupled followers](/documentation/reference/editor/config/followers#withlooselycoupledfollowers).
* **Two different mechanisms**, such as a shooter and a feeder: give each its own subsystem and mechanism class. One YAMS mechanism per subsystem.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-8fdf189e915651eb7bf985c14d6f3e6c63613df0%2Fsmc-followers.png?alt=media" alt="Two panels. Tightly coupled, withFollowers: a leader and a follower are on one shaft or gearbox and the follower copies the leader&#x27;s output. The motors are mechanically locked, there is one closed loop and one config, the followers are the same vendor as the leader, and voltage and duty cycle reach every motor. Loosely coupled, withLooselyCoupledFollowers: two separate motors joined only by the mechanism get the same setpoint and each runs its own PID. They are not mechanically locked, each has its own closed loop and config, vendors can be mixed, and voltage and duty cycle are not forwarded, so the leader moves alone."><figcaption><p>Tightly coupled followers share a shaft. Loosely coupled followers are separate motors.</p></figcaption></figure>

If none of those fit, control each `SmartMotorController` yourself, as below. The [Double FlyWheel tutorial](/documentation/tutorials/double-flywheel) builds this same shooter step by step, with C++ as well; this page is the short version. You still get YAMS's telemetry, live tuning, current limiting, closed loop control and simulation for each motor. Without a mechanism class, your subsystem does three of its jobs: call `setupTelemetry()` on each motor once, `updateTelemetry()` every loop, and `simIterate()` every loop in simulation. You do not get the mechanism's drawing in the dashboard, or its ready-made commands and triggers.

## Why not two `FlyWheel`s in one subsystem?

Every YAMS-generated command (such as `FlyWheel.run` or `Arm.setVoltage`) requires the subsystem you passed to `new SmartMotorControllerConfig(this)`. A subsystem runs one command at a time. So if `topWheel.run(...)` and `bottomWheel.run(...)` both require the same subsystem, scheduling the second **cancels the first**, and only one wheel spins.

The fix is one command that sets both motors, which is what this page writes.

## The subsystem

The code uses two SPARK MAXes (CAN IDs 4 and 5), each driving a NEO 1:1 to a 4 inch wheel. The gains are **placeholders**: with them the wheels reach roughly the right speed in simulation, but tune them for your robot with [Step 5: Tune it](/documentation/tutorials/arm/tune) (for a flywheel, find `kV` first, then `kP`).

{% tabs %}
{% tab title="Commands v2" %}
{% code title="subsystems/ShooterSubsystem.java" lineNumbers="true" %}

```java
package first.robot.subsystems;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Pounds;
import static org.wpilib.units.Units.RPM;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command2.Command;
import org.wpilib.command2.SubsystemBase;
import org.wpilib.command2.button.Trigger;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import org.wpilib.units.measure.AngularVelocity;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ShooterSubsystem extends SubsystemBase {

  private final SmartMotorController top = new SparkWrapper(
      new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless), DCMotor.getNEO(1), wheelConfig("TopWheel"));

  private final SmartMotorController bottom = new SparkWrapper(
      new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless), DCMotor.getNEO(1), wheelConfig("BottomWheel"));

  /** Both wheels are built the same way, so one method makes both configs. */
  private SmartMotorControllerConfig wheelConfig(String name) {
    return new SmartMotorControllerConfig(this)
        .withControlMode(ControlMode.CLOSED_LOOP)
        .withGearing(new MechanismGearing(1))
        // PLACEHOLDER gains. kV is volts per rotation per second.
        .withClosedLoopController(0.1, 0, 0)
        .withFeedforward(new SimpleMotorFeedforward(0, 0.12, 0))
        // Wheel radius and mass, used by the standalone simulation.
        .withMomentOfInertia(Inches.of(2), Pounds.of(1))
        .withZeroPower(MotorMode.COAST)
        .withStatorCurrentLimit(Amps.of(40))
        .withTelemetry(name, TelemetryVerbosity.HIGH);
  }

  public ShooterSubsystem() {
    // A mechanism class would do this for you. Without one, set up the telemetry
    // (and live tuning) of each motor controller once.
    top.setupTelemetry();
    bottom.setupTelemetry();
  }

  /** Spin each wheel at its own speed. Runs until interrupted. */
  public Command spin(AngularVelocity topSpeed, AngularVelocity bottomSpeed) {
    return startRun(
        () -> {
          // A stop() command may have turned the closed loop off.
          top.startClosedLoopController();
          bottom.startClosedLoopController();
        },
        () -> {
          top.setVelocity(topSpeed);
          bottom.setVelocity(bottomSpeed);
        })
        .withName("Shooter Spin");
  }

  /** Let both wheels coast. For the default command. */
  public Command stop() {
    return startRun(
        () -> {
          top.stopClosedLoopController();
          bottom.stopClosedLoopController();
        },
        () -> {
          top.setDutyCycle(0);
          bottom.setDutyCycle(0);
        })
        .withName("Shooter Stop");
  }

  /** True while both wheels are within 100 RPM of their speeds. */
  public Trigger atSpeed(AngularVelocity topSpeed, AngularVelocity bottomSpeed) {
    return new Trigger(() ->
        top.getMechanismVelocity().isNear(topSpeed, RPM.of(100))
            && bottom.getMechanismVelocity().isNear(bottomSpeed, RPM.of(100)));
  }

  @Override
  public void periodic() {
    top.updateTelemetry();
    bottom.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    top.simIterate();
    bottom.simIterate();
  }
}
```

{% endcode %}

Bind it in `RobotContainer`:

{% code title="RobotContainer.java (fragment)" %}

```java
shooter.setDefaultCommand(shooter.stop());
// Backspin: bottom wheel faster than the top.
m_driverController.rightTrigger().whileTrue(shooter.spin(RPM.of(2500), RPM.of(3500)));
```

{% endcode %}
{% endtab %}

{% tab title="Commands v3" %}
{% code title="mechanisms/ShooterMechanism.java" lineNumbers="true" %}

```java
package first.robot.mechanisms;

import static org.wpilib.units.Units.Amps;
import static org.wpilib.units.Units.Inches;
import static org.wpilib.units.Units.Pounds;
import static org.wpilib.units.Units.RPM;

import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.SparkMax;
import org.wpilib.command3.Command;
import org.wpilib.command3.Mechanism;
import org.wpilib.command3.Trigger;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import org.wpilib.units.measure.AngularVelocity;
import yams.commands3.config.SmartMotorControllerConfig;
import yams.core.gearing.MechanismGearing;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.enums.ControlMode;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;

public class ShooterMechanism implements Mechanism {

  private final SmartMotorController top = new SparkWrapper(
      new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless), DCMotor.getNEO(1), wheelConfig("TopWheel"));

  private final SmartMotorController bottom = new SparkWrapper(
      new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless), DCMotor.getNEO(1), wheelConfig("BottomWheel"));

  /** Both wheels are built the same way, so one method makes both configs. */
  private SmartMotorControllerConfig wheelConfig(String name) {
    return new SmartMotorControllerConfig(this)
        .withControlMode(ControlMode.CLOSED_LOOP)
        .withGearing(new MechanismGearing(1))
        // PLACEHOLDER gains. kV is volts per rotation per second.
        .withClosedLoopController(0.1, 0, 0)
        .withFeedforward(new SimpleMotorFeedforward(0, 0.12, 0))
        // Wheel radius and mass, used by the standalone simulation.
        .withMomentOfInertia(Inches.of(2), Pounds.of(1))
        .withZeroPower(MotorMode.COAST)
        .withStatorCurrentLimit(Amps.of(40))
        .withTelemetry(name, TelemetryVerbosity.HIGH);
  }

  public ShooterMechanism() {
    // A mechanism class would do this for you. Without one, set up the telemetry
    // (and live tuning) of each motor controller once.
    top.setupTelemetry();
    bottom.setupTelemetry();
  }

  /** Spin each wheel at its own speed. Runs until interrupted. */
  public Command spin(AngularVelocity topSpeed, AngularVelocity bottomSpeed) {
    return run(coroutine -> {
      // An idle() command may have turned the closed loop off.
      top.startClosedLoopController();
      bottom.startClosedLoopController();
      while (true) {
        top.setVelocity(topSpeed);
        bottom.setVelocity(bottomSpeed);
        coroutine.yield();
      }
    }).named("Shooter Spin");
  }

  /** Let both wheels coast at the lowest priority, so any other shooter command can take over. */
  public Command idle() {
    return run(coroutine -> {
      top.stopClosedLoopController();
      bottom.stopClosedLoopController();
      while (true) {
        top.setDutyCycle(0);
        bottom.setDutyCycle(0);
        coroutine.yield();
      }
    }).withPriority(Command.LOWEST_PRIORITY).named("Shooter Idle");
  }

  /** True while both wheels are within 100 RPM of their speeds. */
  public Trigger atSpeed(AngularVelocity topSpeed, AngularVelocity bottomSpeed) {
    return new Trigger(() ->
        top.getMechanismVelocity().isNear(topSpeed, RPM.of(100))
            && bottom.getMechanismVelocity().isNear(bottomSpeed, RPM.of(100)));
  }

  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
  public void periodic() {
    top.updateTelemetry();
    bottom.updateTelemetry();
  }

  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
  public void simulationPeriodic() {
    top.simIterate();
    bottom.simIterate();
  }
}
```

{% endcode %}

In `Robot`, set `shooter.setDefaultCommand(shooter.idle())`, call `periodic()` from `robotPeriodic()` and start the simulation `Notifier` in `simulationInit()`, as in the [Shooter/FlyWheels tutorial](/documentation/tutorials/shooter-flywheels/commands). Then in your opmode:

{% code title="ExampleTeleop.java (fragment)" %}

```java
// Backspin: bottom wheel faster than the top.
controller.rightTrigger().whileTrue(robot.shooter.spin(RPM.of(2500), RPM.of(3500)));
```

{% endcode %}
{% endtab %}
{% endtabs %}

Each motor's simulation runs on its own, from the moment of inertia in its config, so `simIterate()` works without a mechanism class.

## Check it

1. Start the simulation and open **NetworkTables > Mechanisms** in your dashboard. There is one entry per motor: `TopWheel` and `BottomWheel`.
2. Hold the right trigger. `TopWheel`'s `mechanism/velocity` should rise to about 41.7 rotations per second (2500 RPM), and `BottomWheel`'s to about 58.3 (3500 RPM), **at the same time**.
3. Release it. Both coast down.

## If it did not work

* **Only one wheel spins.** Two commands that require this subsystem are fighting, so the second cancels the first. Set both motors from one command, as `spin` does.
* **The wheels do not start again after `stop`.** `stop` turned the closed loop off. Call `startClosedLoopController()` when a velocity command starts, as `spin` does.
* **The wheels settle well below their speeds.** `kV` is too low; see [How do I shoot with a shooter?](/documentation/how-to-mechanisms/how-to-shoot-with-a-shooter)

## Next

Feed the game piece only once both wheels are at speed, with `atSpeed(...)` and a feeder: [How do I shoot with a shooter?](/documentation/how-to-mechanisms/how-to-shoot-with-a-shooter)


# How do I use a vendor hardware config?

**Goal:** use a motor controller option that YAMS does not have a method for, such as beep settings, peak voltages or status frame rates.

YAMS configures your motor controller from your `SmartMotorControllerConfig`. For anything else, build the vendor's own config object and pass it to `SmartMotorControllerConfig.withVendorConfig(...)`. YAMS starts from it and applies its own settings on top, so anything you set in `SmartMotorControllerConfig` wins, and everything else in the vendor object is kept.

Each example below is a fragment for your subsystem's fields or constructor.

## CTRE TalonFX

Pass a `TalonFXConfiguration` object:

```java
TalonFXConfiguration talonConfig = new TalonFXConfiguration()
    .withAudio(new AudioConfigs().withBeepOnBoot(false).withBeepOnConfig(false))
    .withVoltage(new VoltageConfigs().withPeakReverseVoltage(-10).withPeakForwardVoltage(10));

SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withVendorConfig(talonConfig)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withZeroPower(MotorMode.BRAKE);

TalonFX talonFX = new TalonFX(1, new CANBus(CANPort.CAN_S0));
SmartMotorController smc = new TalonFXWrapper(talonFX, DCMotor.getKrakenX60(1), motorConfig);
```

## CTRE TalonFXS

Pass a `TalonFXSConfiguration` object:

```java
TalonFXSConfiguration talonConfig = new TalonFXSConfiguration()
    .withMotorOutput(new MotorOutputConfigs().withNeutralMode(NeutralModeValue.Brake))
    .withAudio(new AudioConfigs().withBeepOnBoot(false));

SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withVendorConfig(talonConfig)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)));

TalonFXS talonFXS = new TalonFXS(1, new CANBus(CANPort.CAN_S0));
SmartMotorController smc = new TalonFXSWrapper(talonFXS, DCMotor.getMinion(1), motorConfig);
```

`TalonFXSWrapper` sets the motor arrangement (Minion, NEO, NEO 550, NEO Vortex, Thrifty Pulsar from `YMotors.getThriftyPulsar(1)`) from the `DCMotor` you pass, so you do not set it in the vendor config. A `DCMotor` it does not recognize, such as `DCMotor.getKrakenX60(1)`, throws an `IllegalArgumentException` ("Unknown motor for TalonFXS"), because a Kraken X60 cannot run on a TalonFXS.

## REV SparkMax

Pass a `SparkMaxConfig` object:

```java
SparkMaxConfig sparkConfig = new SparkMaxConfig();
sparkConfig.signals
    .primaryEncoderPositionPeriodMs(10)
    .primaryEncoderVelocityPeriodMs(20);

SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withVendorConfig(sparkConfig)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withZeroPower(MotorMode.BRAKE);

SparkMax spark = new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless);
SmartMotorController smc = new SparkWrapper(spark, DCMotor.getNEO(1), motorConfig);
```

## REV SparkFlex

Pass a `SparkFlexConfig` object:

```java
SparkFlexConfig sparkConfig = new SparkFlexConfig();
sparkConfig.signals
    .primaryEncoderPositionPeriodMs(10)
    .primaryEncoderVelocityPeriodMs(20);

SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withVendorConfig(sparkConfig)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withZeroPower(MotorMode.BRAKE);

SparkFlex spark = new SparkFlex(CANPort.CAN_S0, 1, MotorType.kBrushless);
SmartMotorController smc = new SparkWrapper(spark, DCMotor.getNeoVortex(1), motorConfig);
```

## Thrifty Nova

Pass a ThriftyLib `NovaConfig.Config`, usually a `NovaConfigBatch` holding one or more `NovaConfig` options. The vendor config is applied to the Nova before the YAMS config:

```java
SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withVendorConfig(new NovaConfigBatch(NovaConfig.tempThrottleEnable(true)))
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(4, 0, 0)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withZeroPower(MotorMode.BRAKE);

Nova nova = new Nova(0, 1, MotorType.NEO); // CAN bus 0, CAN ID 1
SmartMotorController smc = new NovaWrapper(nova, DCMotor.getNEO(1), motorConfig);
```

Any other vendor config type throws a `SmartMotorControllerConfigurationException`.

## FIRST A301

The A301 has no vendor config. `A301Wrapper` throws a `SmartMotorControllerConfigurationException` for any `withVendorConfig`, so everything it supports is set through `SmartMotorControllerConfig`.

## Factory reset: `withResetPreviousConfig`

Motor controllers keep their settings in flash, across power cycles and code deploys. With `withResetPreviousConfig(true)`, the default, YAMS clears them before applying your config, so settings left over from last season, or from someone clicking around in the vendor's tool, cannot sneak in: a TalonFX or TalonFXS gets a complete config (your vendor config, or the defaults) with the YAMS options on top, a SPARK resets its parameters first (`ResetMode.kResetSafeParameters`), and a Nova is sent a factory reset first. `A301Wrapper` ignores the option.

```java
// Keep what is already saved on the controller, and only change what this config sets.
.withResetPreviousConfig(false)
```

Turn the reset off only when you configured something on purpose in the vendor's tool (Phoenix Tuner X or REV Hardware Client) and want to keep it. With the reset off, any old setting you did not set yourself stays, which is a common cause of a motor that behaves differently from its twin.

A vendor config passed to `withVendorConfig` is applied either way, and its settings win over the ones saved on the controller. On a SPARK or a Nova, only the settings the vendor config sets change. A `TalonFXConfiguration` or `TalonFXSConfiguration` holds every setting, so on a TalonFX or TalonFXS a vendor config replaces all the saved settings, even with the reset off: to keep a setting saved on a Talon, leave out the vendor config, or set that setting in it too.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-ba628d06d4973f9e80b4c79f0922d331d721e1e1%2Fsmc-config-layers.png?alt=media" alt="Two stacks of layers applied top to bottom. With the reset on, the default, the controller starts from factory defaults, then your vendor config if you gave one, then your SmartMotorControllerConfig options. With the reset off it starts from whatever is already saved on the controller, so old settings you did not set stay."><figcaption><p>What the controller ends up with, with and without the reset.</p></figcaption></figure>

{% hint style="warning" %}
Always verify the final applied configuration on your hardware. Use your vendor's tuning tool (such as Phoenix Tuner X or REV Hardware Client) to confirm that YAMS didn't silently overwrite a setting you intended to keep from your vendor config.
{% endhint %}

## Check it

Open the controller in Phoenix Tuner X or REV Hardware Client after the robot code has started, and check that the vendor setting you added is there (for example, the TalonFX no longer beeps on boot), and that the settings from your `SmartMotorControllerConfig` (gear ratio, current limit, brake mode) are there too.

## If it did not work

* **`SmartMotorControllerConfigurationException` about the vendor config.** The object is the wrong type for the wrapper: a TalonFX needs a `TalonFXConfiguration`, a TalonFXS a `TalonFXSConfiguration`, a SPARK MAX a `SparkMaxConfig`, a SPARK Flex a `SparkFlexConfig`, and a Nova a `NovaConfig.Config` such as a `NovaConfigBatch`. An A301 takes none: remove the vendor config.
* **Your vendor setting is gone.** `SmartMotorControllerConfig` sets the same option, and it wins. Set it there instead.
* **Something else.** See [Troubleshooting](/documentation/tutorials/troubleshooting).

## Read more

To see every option `SmartMotorControllerConfig` does have, see [SmartMotorControllerConfig](/documentation/reference/editor/config).


# How do I use a DCMotor that isn't in WPILib?

**Goal:** simulate a motor that WPILib has no `DCMotor` for, by building one from its datasheet and giving it to your `SmartMotorController`.

Every YAMS wrapper but one (`SparkWrapper`, `TalonFXWrapper`, `TalonFXSWrapper`, `NovaWrapper`) takes a `DCMotor` (`org.wpilib.math.system.DCMotor`). YAMS uses it to simulate the motor, so a wrong `DCMotor` makes the simulation faster or slower and stronger or weaker than the real robot.

First look for a ready-made one:

* **WPILib's factories** cover the motors it knows: `getNEO`, `getNeo550`, `getNeoVortex`, `getFalcon500`, `getKrakenX60`, `getKrakenX44`, `getMinion` and more.
* **`YMotors`** (`yams.core.motorcontrollers.YMotors`, Java) adds the motors WPILib does not have yet: `YMotors.getThriftyPulsar(1)` for a Thrifty Pulsar 775, and `YMotors.getA301(1)` for the motor inside a FIRST A301 (in C++, `YMotors::A301()` from `yams/motorcontrollers/YMotors.hpp`).

{% hint style="info" %}
`A301Wrapper` takes no `DCMotor`. Every A301 has the same motor, so the wrapper always uses `YMotors.getA301(1)`: 13,500 RPM free and 0.078 N·m stalled at 12 V, before the A301's gearbox. FIRST does not publish its currents, so it uses the NEO 550's for now (100 A stalled, 1.4 A free).
{% endhint %}

Use one of those if your motor is listed, and skip the rest of this page. Each is just a call to the `DCMotor` constructor, which you can make yourself for any other motor.

{% stepper %}
{% step %}

### Find the datasheet values

You need four numbers, measured at a nominal voltage (usually 12 V): stall torque, stall current, free current and free speed. Get them from the manufacturer's datasheet, or look the motor up on ReCalc:

{% embed url="<https://www.reca.lc/motors>" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-61664746c59e9e832bb135864f3781085405ac18%2Fhowto-dcmotor-curve.png?alt=media" alt="A graph of torque and current against motor speed for a Minion at 12 volts. Torque falls in a straight line from the stall torque of 3.1 newton meters at zero speed to zero at the free speed of 7200 RPM. Current falls from the stall current of 200.46 amps to the free current of 1.43 amps. Beside it, the DCMotor constructor takes the nominal voltage, stall torque, stall current, free current, free speed and number of motors, in that order."><figcaption><p>The four datasheet values and where each goes in the constructor.</p></figcaption></figure>

**Check it:** you have all four numbers, and know the voltage they were measured at.
{% endstep %}

{% step %}

### Build the DCMotor

The constructor takes the values in this order. Torque is in newton meters, current in amps and free speed in radians per second.

```java
public DCMotor(
    double nominalVoltage,  // volts the values were measured at
    double stallTorque,     // newton meters
    double stallCurrent,    // amps
    double freeCurrent,     // amps
    double freeSpeed,       // radians per second
    int numMotors)          // motors in the gearbox
```

For example, before WPILib added `DCMotor.getMinion()`, a [Minion motor](https://store.ctr-electronics.com/products/minion-brushless-motor) could be created with:

{% code title="ExampleSubsystem.java (fragment)" %}

```java
import static org.wpilib.units.Units.RPM;
import static org.wpilib.units.Units.RadiansPerSecond;
import org.wpilib.math.system.DCMotor;

// One Minion: 12 V, 3.1 N·m stall torque, 200.46 A stall current,
// 1.43 A free current, 7200 RPM free speed.
private final DCMotor minion =
    new DCMotor(12, 3.1, 200.46, 1.43, RPM.of(7200).in(RadiansPerSecond), 1);
```

{% endcode %}

**Check it:** the code builds.
{% endstep %}

{% step %}

### Give it to the wrapper

Pass your `DCMotor` where the examples pass `DCMotor.getNEO(1)`. This fragment goes in the same class, after the `smcConfig` field:

{% code title="ExampleSubsystem.java (fragment)" %}

```java
private final SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);

// The custom DCMotor replaces DCMotor.getNEO(1).
private final SmartMotorController motor = new SparkWrapper(spark, minion, smcConfig);
```

{% endcode %}

{% hint style="warning" %}
`TalonFXSWrapper` uses the `DCMotor` to choose the TalonFXS motor arrangement, so it only accepts the motors it knows (Minion, NEO, NEO 550, NEO Vortex and Thrifty Pulsar), compared value for value. Any other `DCMotor` throws an `IllegalArgumentException` ("Unknown motor for TalonFXS"). That includes a Pulsar you build yourself: the comparison is exact, so different datasheet numbers or a different unit conversion fail it. With a TalonFXS, use the factory, such as `DCMotor.getMinion(1)` or `YMotors.getThriftyPulsar(1)`.
{% endhint %}

**Check it:** the robot code starts in simulation without an exception.
{% endstep %}
{% endstepper %}

## Check it

1. Start the simulation and run the mechanism at full output (for example a `set(1)` command).
2. Watch the motor's `rotor/velocity` under **NetworkTables > Mechanisms**. With little load it should level off near the motor's free speed: 7200 RPM is 120 rotations per second.

## If it did not work

* **The simulated motor is far too fast or too slow.** A value is in the wrong unit: free speed must be in radians per second (convert RPM with `RPM.of(x).in(RadiansPerSecond)`), and torque in newton meters, not inch pounds.
* **`IllegalArgumentException: Unknown motor for TalonFXS`.** Use a factory: see the warning in [Give it to the wrapper](#give-it-to-the-wrapper).

## Read more

Now that the simulation matches the motor, tune your mechanism as its tutorial does: [Arm](/documentation/tutorials/arm/tune), [Elevator](/documentation/tutorials/elevator/tune) or [Shooter](/documentation/tutorials/shooter-flywheels/tune).


# How do I tell YAMS my drum or sprocket size?

**Goal:** tell YAMS how far your elevator (or wheel, or linear slide) moves for each rotation, so you can give it targets in meters or inches instead of rotations.

YAMS turns rotations into distance with the **mechanism circumference**: the distance the mechanism moves for one rotation of its final shaft (after the gearbox). If the circumference is wrong, every height is off by the same factor, and the gains you tune will not make sense.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FAMxbim1J0b5WuJ94m9ja%2Fimage.png?alt=media&amp;token=43ab64dc-75d5-4537-a62b-9fb48fed9a57" alt="A swerve style wheel, its shaft, a gearbox and a NEO motor laid out in a row. The motor shaft is labelled Rotor, the shaft after the gearbox is labelled Mechanism, and the wheel&#x27;s outer edge is labelled Measurement. Rotor and Mechanism are an angle and angular velocity; Measurement is a distance and linear velocity."><figcaption><p>The circumference turns Mechanism rotations into a Measurement distance.</p></figcaption></figure>

## Find the circumference

The circumference belongs to the last part that turns: the drum, sprocket, pulley or wheel that moves the load.

* **Drum or wheel:** circumference = 2 × π × radius = π × diameter.
* **Sprocket on chain:** circumference = chain pitch × number of teeth. For example #25 chain (0.25 inch pitch) on a 22 tooth sprocket moves 5.5 inches per rotation.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-898d5376582d6de685136b38acf1881c8c42e59b%2Fhowto-mechanism-circumference.gif?alt=media" alt="Animation of a 4 inch drum and a 22 tooth sprocket on 0.25 inch pitch chain, each turning two rotations. The drum moves its cable 12.57 inches per rotation, 25.13 inches in total. The sprocket moves its chain 5.50 inches per rotation, 11 inches in total."><figcaption><p>Each rotation of the mechanism moves it by one circumference.</p></figcaption></figure>

## Set it in YAMS

Use **exactly one** of these methods in your `SmartMotorControllerConfig`. They all set the same value, so if you call more than one, the last call wins. Pick the one that matches what you can measure. Each line below is a fragment that goes in the config chain.

```java
// A sprocket on chain: pass the chain pitch and the tooth count.
.withDrumRadius(Inches.of(0.25), 22)        // 0.25 in × 22 = 5.5 in per rotation
```

```java
// A drum or spool, measured across the middle.
.withWheelDiameter(Inches.of(2))            // π × 2 in = 6.28 in per rotation
```

```java
// A drum or spool, measured from the center to the edge.
.withDrumRadius(Inches.of(1))               // same as withWheelRadius(Inches.of(1))
```

```java
// You already know the distance per rotation.
.withMechanismCircumference(Inches.of(5.5))
```

A complete elevator config, using the sprocket:

{% code title="ExampleSubsystem.java (fragment)" %}

```java
SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    // The one circumference call: 0.25 inch pitch chain on a 22 tooth sprocket.
    .withDrumRadius(Inches.of(0.25), 22)
    // Where the carriage is when the robot turns on.
    .withStartingPosition(Meters.of(0))
    .withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);
```

{% endcode %}

### A cascading elevator

In a cascading elevator each stage pulls the next, so the carriage moves faster than the chain or cable: with two moving stages, twice as fast. Tell the motor config with `withCascadingElevatorStages(2)`, called **after** `withGearing(...)`: it divides the gearing already set by the number of stages, so a `withGearing` call after it replaces the result. See [`withCascadingElevatorStages`](/documentation/reference/editor/config/gearing-and-units#withcascadingelevatorstages).

{% code title="ExampleSubsystem.java (fragment)" %}

```java
.withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
.withCascadingElevatorStages(2) // after withGearing: the carriage moves 2 × the chain
.withDrumRadius(Inches.of(0.25), 22)
```

{% endcode %}

`ElevatorConfig.withStages(...)` is a different thing: it gives the height each stage travels, so YAMS can draw every stage on a 3D model. It does not change the gearing, so a cascading elevator needs both. See [How do I show an elevator's stages on a 3D robot model?](/documentation/how-to-simulation-and-logging/how-do-i-show-my-mechanisms-on-a-3d-robot-model/how-do-i-show-an-elevators-stages-on-a-3d-robot-model)

{% hint style="warning" %}
The height YAMS reports is measured from where the carriage was when the robot turned on, not from the floor. If you want heights from the floor, set `withStartingPosition` to the carriage's real starting height and set your limits to match.
{% endhint %}

## Check it

1. Deploy (or start the simulation) and open the motor's `measurement/position` value under **NetworkTables > Mechanisms**. It is in meters.
2. On the robot, disable it and move the carriage by hand a known distance, for example 0.5 m with a tape measure.
3. `measurement/position` should change by the same amount. If it changes by twice as much, or half, the circumference or the gearing is wrong.

## If it did not work

* **The reading is off by a constant factor.** Check the gearing first (`withGearing`), then the circumference. A cascading elevator also needs `withCascadingElevatorStages`, after `withGearing`: see [A cascading elevator](#a-cascading-elevator).
* **The reading goes the wrong way.** The motor is inverted; see [Troubleshooting](/documentation/tutorials/troubleshooting).

## Read more

Send the elevator to a height in meters: [How do I set an elevator's target height?](/documentation/how-to-mechanisms/how-to-set-an-elevators-target-height)


# How do I use exponential profiles?

An exponential profile plans a move the way a DC motor actually moves: hard acceleration at first, then less as it nears top speed. Every `SmartMotorController` in YAMS supports them. This is the short version: [Exponential profiles](/documentation/understanding/exponential-profiles) has the full explanation and the tuning steps.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-cd805259e0788a8a85c06cc806a53802c26af5ab%2Fexponential-profile-compare.png?alt=media" alt="Two graphs. Setpoint velocity over time: a trapezoidal profile ramps in a straight line to a flat top, an exponential profile rises quickly and curves over near top speed. Acceleration against speed: the motor&#x27;s available acceleration falls to zero at top speed, the exponential profile follows it, and the trapezoidal profile asks for a constant acceleration the motor cannot give at high speed"><figcaption><p>The two profiles, and why the motor can follow one more easily than the other.</p></figcaption></figure>

## Use one

Add `withExponentialProfile(...)` instead of `withTrapezoidalProfile(...)`. For an elevator, YAMS works out starting values from the motor, the carriage and the drum. This is a fragment of an elevator subsystem's fields; the rest of the config (feedforward, limits, telemetry) is as in the [Elevator tutorial](/documentation/tutorials/elevator).

{% code title="ElevatorSubsystem.java (fragment)" %}

```java
private final Distance drumRadius = Inches.of(0.25).times(22).div(2 * Math.PI); // 22 tooth sprocket, #25 chain
private final Mass     weight = Pounds.of(16);
private final DCMotor  motors = DCMotor.getNEO(1);
private final MechanismGearing gearing = new MechanismGearing(GearBox.fromReductionStages(3, 4));

private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    // Gearing first: withExponentialProfile reads it to build the profile.
    .withGearing(gearing)
    .withDrumRadius(drumRadius)
    // PLACEHOLDER kP, in volts per meter. Tune it after the profile.
    .withClosedLoopController(10, 0, 0)
    // Maximum voltage during the profile, the motor, the carriage weight and the drum radius.
    .withExponentialProfile(Volts.of(12), motors, weight, drumRadius);
```

{% endcode %}

`withGearing` must come **before** `withExponentialProfile`, because the profile is calculated from the gearing at that moment. This form also makes the closed loop work in meters (see [How do I tune my elevator in rotations instead of meters?](/documentation/how-to-motor-controllers-and-sensors/how-to-disable-linear-closed-loop-control)).

There are helpers for arms, flywheels and custom limits too: see [creating constraints](/documentation/understanding/exponential-profiles#creating-constraints).

## When should I use one?

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-7d94af6bc3483cc22c0e4118b164f3b956505187%2Fexponential-profile-tracking.gif?alt=media" alt="Animation of a 12 volt motor following each profile. With the trapezoidal profile the measured velocity falls behind the setpoint as the speed rises and the motor saturates at 12 volts. With the exponential profile the measured velocity stays on the setpoint"><figcaption><p>A simulated 12 V motor following each profile. The trapezoidal profile asks for more than the motor has left at speed.</p></figcaption></figure>

* **Use one** when a trapezoidal profile is hard to tune, or the mechanism falls behind it and then overshoots.
* **Keep the trapezoidal profile** if it already works well, or the motor is always current limited.
* **It cannot fix an underpowered mechanism.**

See [when to use each profile type](/documentation/understanding/exponential-profiles#when-to-use-each-profile-type).

## Tune it

Start from the helper's values and [refine the profile live](/documentation/understanding/exponential-profiles#refining-the-profile-live). The profile only plans the move, so it still needs a feedforward, and the profile's `kV` and `kA` are [not the feedforward's](/documentation/reference/editor/config/feedforward#these-are-not-an-exponential-profiles-kv-and-ka).

## Check it

Start the simulation, command a new height, and graph the motor's `closedloop/setpoint/position` against `measurement/position` under **NetworkTables > Mechanisms**. The setpoint should curve smoothly to the target, and the measurement should stay close behind it the whole way.

## If it did not work

* **The setpoint jumps straight to the target, or the elevator does not move.** The profile is missing or empty: check that `withGearing` comes before `withExponentialProfile`, and that the drum radius and carriage weight are right.
* **The elevator falls behind the setpoint and then overshoots.** The feedforward is missing or `kG` is 0. See [Feedforward](/documentation/reference/editor/config/feedforward).

## Code reference

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/ExponentiallyProfiledElevatorSubsystem.java>" %}


# How do I tune my elevator in rotations instead of meters?

**Goal:** keep the closed loop controller (its error, `kP` and profile limits) in rotations, while still reading positions and speeds in meters.

## What is linear closed loop control?

YAMS's closed loop controller can work in one of two units:

* **Angle based** (rotations). The error is in rotations, `kP` is in volts per rotation, and profile limits are in rotations per second.
* **Distance based**, or **linear** (meters). The error is in meters, `kP` is in volts per meter, and profile limits are in meters per second.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d8e5a04c33cb35b8f4335c31a13830d94901974d%2Fsmc-linear-units.png?alt=media" alt="Two panels. Angle based, the default: error is measured in rotations, kP is in volts per rotation and profile limits are in rotations per second, for arms, pivots, turrets and flywheels. Distance based: error in meters, kP in volts per meter and profile limits in meters per second, for elevators and other linear mechanisms."><figcaption><p>The units the gains and limits are in.</p></figcaption></figure>

The units change what your gains mean: a `kP` of 4 volts per meter is a very different controller from 4 volts per rotation.

## When is it on?

It is **off by default**. Setting a circumference (`withWheelDiameter`, `withDrumRadius` and so on) does not turn it on; that only lets YAMS report distances. These `SmartMotorControllerConfig` calls turn it on:

* `withFeedforward(ElevatorFeedforward)` or `withSimFeedforward(ElevatorFeedforward)`
* `withTrapezoidalProfile(LinearVelocity, LinearAcceleration)` (a profile in meters per second)
* `withTrapezoidalProfile(LinearAcceleration, Velocity<LinearAccelerationUnit>)`
* `withExponentialProfile(Voltage, DCMotor, Mass, Distance)` (the elevator form)

So a typical elevator config uses linear closed loop control without you asking for it.

## When would I turn it off?

* You tuned an elevator in rotations and want to keep those gains.
* You are copying gains from a tool or another robot that works in rotations.
* You use an `ElevatorFeedforward` for a mechanism that you want to control in rotations.

Turning it off does not stop YAMS reporting distances. `getMeasurementPosition()` and `getMeasurementVelocity()` still return meters, as long as the circumference is set.

{% stepper %}
{% step %}

### Turn it off

Add `withLinearClosedLoopController(false)` **after** every call in the list above. Those calls switch it back on, so if one comes later in the chain, your `false` is lost.

{% code title="ExampleSubsystem.java (fragment)" %}

```java
SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withDrumRadius(Inches.of(0.25), 22)
    // Placeholder gains, now in volts per rotation. Tune them for your elevator.
    .withClosedLoopController(4, 0, 0)
    .withFeedforward(new ElevatorFeedforward(0, 0, 0))   // turns linear on...
    // ...so this comes last, to turn it off again.
    .withLinearClosedLoopController(false);
```

{% endcode %}

**Check it:** the code builds, and `withLinearClosedLoopController(false)` is the last call in the chain.
{% endstep %}

{% step %}

### Make the profile limits angular

If the config has a motion profile, its limits must now be angular too, for example `withTrapezoidalProfile(RotationsPerSecond.of(2), RotationsPerSecondPerSecond.of(4))`, placed before the `false`. Your gains are now in volts per rotation, so tune `kP` again.

**Check it:** the code builds, and a commanded move is neither much softer nor much harsher than you expect.
{% endstep %}
{% endstepper %}

## Check it

1. Deploy (or start the simulation) and command a height.
2. Under **NetworkTables > Mechanisms**, the motor's `closedloop/setpoint/position` is now in rotations, while `measurement/position` is still in meters.

## If it did not work

* **The setpoint is still in meters.** A call from the list above comes after `withLinearClosedLoopController(false)`. Move the `false` to the end of the chain.
* **The elevator is much too soft or too aggressive.** Your gains were tuned in the other unit. Tune `kP` again; see [Troubleshooting](/documentation/tutorials/troubleshooting).

## Read more

Command the elevator in meters: [How do I set an elevator's target height?](/documentation/how-to-mechanisms/how-to-set-an-elevators-target-height)


# How do I detect a game piece from motor current?

**Goal:** know when your intake has a game piece, without a beam break or limit switch, by watching the roller motor's current.

When a game piece jams against a spinning roller, the roller slows and the motor draws more current. **Stator current** is the current through the motor's windings, and it rises with the load. YAMS reads it with `SmartMotorController.getStatorCurrent()`, so you can turn "current has been high for a moment" into a `Trigger`.

This is a fallback for when there is no room or time for a real sensor. A beam break is more reliable, so ask for one if you can.

This page builds on the `IntakeSubsystem` from [How do I set up an intake roller?](/documentation/how-to-mechanisms/how-do-i-set-up-an-intake-roller)

{% stepper %}
{% step %}

### Measure your current

Simulation does not model a game piece, so this step has to be done on the real robot. Pick the threshold from your robot, not from this page.

1. Deploy the intake from [How do I set up an intake roller?](/documentation/how-to-mechanisms/how-do-i-set-up-an-intake-roller) to the robot and open the motor's `current/stator` value under **NetworkTables > Mechanisms** as a graph (Elastic, AdvantageScope or the Glass graph widget).
2. Run the intake with nothing in it. Note the current once it is up to speed; a roller like this one often sits around 5 to 15 amps.
3. Feed it a game piece and let it jam. Note how high the current goes and how long it stays there.

Choose a threshold between the two, well clear of both: if it runs at 10 A empty and climbs to the 40 A limit with a game piece, try 25 A.

{% hint style="warning" %}
**Keep the threshold below the stator current limit.** The limit (`withStatorCurrentLimit(Amps.of(40))`) stops the current from going over 40 A, so a stalled roller reads at or just under 40 A. A threshold equal to the limit may never be reached, or flicker on and off.
{% endhint %}

**Check it:** you have two readings, empty and jammed, at least 10 A apart, and a threshold between them.
{% endstep %}

{% step %}

### Add the detection

Add a `Debouncer` and a method to the intake class. The `Debouncer` only reports `true` once the current has stayed over the threshold for 0.1 seconds, so the short spike when the motor starts does not count as a game piece. These lines are a fragment: they go in the `IntakeSubsystem` (or `IntakeMechanism`) class, next to the `motor` field.

{% code title="IntakeSubsystem.java (fragment)" %}

```java
import static org.wpilib.units.Units.Amps;
import org.wpilib.math.filter.Debouncer;
import org.wpilib.units.measure.Current;

// Over this, the roller is pushing against a game piece. Measured on our robot:
// about 10 A empty, 40 A (the current limit) with a game piece jammed.
private static final Current GAME_PIECE_CURRENT = Amps.of(25);

// True only after the current has stayed high for 0.1 seconds.
private final Debouncer gamePieceDebouncer = new Debouncer(0.1);

/** True once the roller has been pushing against a game piece for 0.1 seconds. */
public boolean hasGamePiece() {
  return gamePieceDebouncer.calculate(motor.getStatorCurrent().gte(GAME_PIECE_CURRENT));
}
```

{% endcode %}

**Check it:** the code builds.
{% endstep %}

{% step %}

### Use it

Run the intake until it has a game piece, then stop.

{% tabs %}
{% tab title="Commands v2" %}
{% code title="IntakeSubsystem.java (fragment)" %}

```java
/** Run the intake until a game piece is detected. */
public Command intakeUntilGamePiece() {
  return intake().until(this::hasGamePiece);
}
```

{% endcode %}

To use it as a `Trigger` elsewhere (for example to rumble the controller), wrap it: `new Trigger(intake::hasGamePiece)`.
{% endtab %}

{% tab title="Commands v3" %}
{% code title="IntakeMechanism.java (fragment)" %}

```java
/** Run the intake until a game piece is detected. */
public Command intakeUntilGamePiece() {
  return run(coroutine -> {
    while (true) {
      if (hasGamePiece()) {
        intake.setVoltageSetpoint(Volts.of(0));
        return;
      }
      intake.setVoltageSetpoint(Volts.of(8));
      coroutine.yield();
    }
  }).named("Intake Until Game Piece");
}
```

{% endcode %}

To use it as a `Trigger` elsewhere, wrap it: `new Trigger(intake::hasGamePiece)` with `org.wpilib.command3.Trigger`.
{% endtab %}
{% endtabs %}

**Check it:** the code builds, and the intake runs when you press its button.
{% endstep %}
{% endstepper %}

## Check it

1. On the robot, graph `current/stator` and `hasGamePiece()` together (publish `hasGamePiece()` with `Telemetry.log`, or watch the command end).
2. Start the intake with nothing in it. `hasGamePiece()` should stay `false`, even during the spike when the motor starts.
3. Feed it a game piece. `hasGamePiece()` should turn `true` about 0.1 seconds after the current climbs over the threshold, and the intake should stop.

## If it did not work

* **It never detects the game piece.** The threshold is too high, or the same as the current limit. Lower it toward the middle of your empty and jammed readings.
* **It detects a game piece when the intake starts.** The start up spike lasts longer than 0.1 seconds. Raise the `Debouncer` time to 0.2 or 0.25 seconds, or the threshold.
* **It works with a full battery but not a low one.** A tired battery slows the roller and changes the current. Use `setVoltage` rather than `set` for the intake, and measure again with a used battery.

## Read more

To feed that game piece into a shooter, see [How do I shoot with a shooter?](/documentation/how-to-mechanisms/how-to-shoot-with-a-shooter)

For more on `Debouncer`, see the WPILib docs:

{% embed url="<https://docs.wpilib.org/en/stable/docs/software/advanced-controls/filters/debouncer.html#debouncer>" %}


# How do I use a gyro mounted on its side?

A swerve drive needs the robot's heading, which is rotation about the axis pointing up through the robot. A gyro mounted flat reports that as its yaw. If packaging forces you to mount the gyro on its side (for example vertically on a superstructure plate), the robot turning shows up as the gyro's roll or pitch instead, and a `SwerveDrive` reading yaw will see almost no heading change. `SwerveDriveConfig.withGyroHeadingAxis(GyroAxis)` tells YAMS which gyro axis points up, so the heading and tilt are read correctly without any math in your robot code.

## Give the drive the gyro's full attitude

`withGyro(...)` takes a `Supplier<Rotation3d>` (`WithGyro(std::function<Rotation3d()>)` in C++): the gyro's full 3D attitude, not just a yaw angle. Most gyros expose this directly, such as `pigeon::getRotation3d`.

## Pick the heading axis

`GyroAxis` lives in `yams.core.mechanisms.config.enums` (`yams::mechanisms::config::GyroAxis` in C++) and names the gyro axis that points up through the robot:

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-c4cb94eececc5e0d196a99a6f23101e015b34e01%2Fgyro-axes.png?alt=media" alt="Three drawings of a gyro on a robot chassis with its X, Y and Z axes. Mounted flat, Z points up, X to the front and Y to the left: GyroAxis.YAW. Standing on its side with X pointing up, Y to the robot&#x27;s left and Z to the back: GyroAxis.ROLL. Standing on its side with Y pointing up, X to the robot&#x27;s front and Z to the right: GyroAxis.PITCH"><figcaption><p>Find the gyro axis that points up, and pick the matching <code>GyroAxis</code>.</p></figcaption></figure>

| `GyroAxis`      | Gyro mounting                                                                                      | Robot turning shows up as |
| --------------- | -------------------------------------------------------------------------------------------------- | ------------------------- |
| `YAW` (default) | Flat, the gyro's Z axis points up                                                                  | The gyro's yaw            |
| `ROLL`          | On its side, the gyro's X axis points up. The gyro's Y axis is taken to point to the robot's left  | The gyro's roll           |
| `PITCH`         | On its side, the gyro's Y axis points up. The gyro's X axis is taken to point to the robot's front | The gyro's pitch          |

{% tabs %}
{% tab title="Java" %}
{% code title="SwerveSubsystem.java (fragment)" %}

```java
import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.Pigeon2;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.math.controller.PIDController;
import org.wpilib.math.geometry.Pose2d;
import org.wpilib.math.geometry.Rotation2d;
import yams.commands2.config.SwerveDriveConfig;
import yams.commands2.swerve.SwerveDrive;
import yams.core.mechanisms.config.enums.GyroAxis;

private final Pigeon2 gyro = new Pigeon2(14, new CANBus(CANPort.CAN_S0));

// In the constructor, after the four modules are created:
SwerveDriveConfig config = new SwerveDriveConfig(this, fl, fr, bl, br)
    .withGyro(gyro::getRotation3d)
    // The gyro is mounted with its X axis pointing up, so the robot's heading is the gyro's roll.
    .withGyroHeadingAxis(GyroAxis.ROLL)
    .withStartingPose(new Pose2d(0, 0, Rotation2d.fromDegrees(0)))
    .withTranslationController(new PIDController(1, 0, 0))
    .withRotationController(new PIDController(1, 0, 0));
drive = new SwerveDrive(config);
```

{% endcode %}

For Commands v3, import `SwerveDriveConfig` and `SwerveDrive` from `yams.commands3` instead. `GyroAxis` is the same class for both.
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/SwerveSubsystem.cpp (fragment)" %}

```cpp
#include <ctre/phoenix6/Pigeon2.hpp>
#include <wpi/math/geometry/Rotation3d.hpp>

#include "yams/mechanisms/config/GyroAxis.hpp"
#include "yams/mechanisms/swerve/SwerveDrive.hpp"

// The header declares: ctre::phoenix6::hardware::Pigeon2 m_gyro{14, ctre::phoenix6::CANBus{}};
m_driveConfig
    .WithSubsystem(this)
    .WithModules({&m_frontLeft.module.value(), &m_frontRight.module.value(),
                  &m_backLeft.module.value(), &m_backRight.module.value()})
    .WithGyro([this]() -> wpi::math::Rotation3d { return m_gyro.GetRotation3d(); })
    // The gyro is mounted with its X axis pointing up, so the robot's heading is the gyro's roll.
    .WithGyroHeadingAxis(yams::mechanisms::config::GyroAxis::ROLL)
    .WithStartingPose(wpi::math::Pose2d{})
    .WithTranslationController(wpi::math::PIDController{1, 0, 0})
    .WithRotationController(wpi::math::PIDController{1, 0, 0})
    .WithTelemetry("swerve", Cfg::TelemetryVerbosity::HIGH);

m_drive.emplace(&m_driveConfig);
```

{% endcode %}

This is the drive config from the [Swerve Drive tutorial](/documentation/tutorials/swerve-drive/modules-and-drive) with one line added. `WithGyroHeadingAxis` needs the `Rotation3d` overload of `WithGyro`: the `degree_t` overload gives only a heading, with nothing to rotate.
{% endtab %}
{% endtabs %}

YAMS rotates the gyro's attitude into the robot's frame before anything reads it. After that, the yaw of the result is the robot's heading, and its roll and pitch are the robot's tilt (which anti-tipping uses), whichever way the gyro is mounted. `withGyroInverted(...)` and `withGyroOffset(...)` apply to the resulting heading.

## Read the heading

Use `getGyroRotation3d()` (`GetGyroRotation3d()` in C++), which returns the robot's attitude with the heading axis already applied:

```java
Rotation2d heading = drive.getGyroRotation3d().toRotation2d();
```

The heading wraps at ±180 degrees. Use `drive.getPose().getRotation()` if you want the odometry heading instead of the raw gyro heading.

## Check it

Put the robot on blocks or a cart, and graph `NT:/Mechanisms/<drive name>/gyro` (such as `NT:/Mechanisms/swerve/gyro`), the heading in degrees, in AdvantageScope. It is published at every telemetry verbosity. Rotate the robot counterclockwise, viewed from above: the heading should increase by about as much as the robot turned.

## If it did not work

* **The heading barely changes:** the wrong axis is selected. Try the other of `ROLL` and `PITCH`.
* **It changes in the wrong direction:** add `.withGyroInverted(true)`.

## Related pages

* [Swerve Drive](/documentation/tutorials/swerve-drive)


# How do I limit power consumption?

**Goal:** set current limits so that the robot's mechanisms, all running at once, do not pull the battery low enough to brown out.

A motor controller has two currents. The **supply** current flows from the battery into the controller, and its limit protects the battery, the breakers and the voltage everything else runs on. The **stator** current flows from the controller through the motor, and its limit protects the motor and caps its torque. CTRE's [Improving performance with current limits](https://v6.docs.ctr-electronics.com/en/stable/docs/hardware-reference/talonfx/improving-performance-with-current-limits.html) explains how they relate.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-75f89f9c2884411442900d9c21b991c13d9e279d%2Fpower-supply-stator.png?alt=media" alt="A battery at 12 volts feeds a motor controller running at 25 percent output, which feeds a motor with 3 volts across it. The supply current is 20 amps at 12 volts and the stator current is 80 amps at 3 volts, the same 240 watts. The supply current limit protects the battery, breaker and bus voltage. The stator current limit protects the motor and limits torque"><figcaption><p>The two currents, and what each limit protects.</p></figcaption></figure>

{% hint style="danger" %}
A SPARK MAX or SPARK Flex only has a stator current limit. `SparkWrapper` throws a `SmartMotorControllerConfigurationException` if you set a supply current limit, and it does not publish the supply current.
{% endhint %}

## Before you start

* Your mechanisms run in simulation, each with `simIterate()` called every loop. YAMS adds their current draw into one simulated battery: see [Battery simulation](/documentation/understanding/battery-simulation).
* Each motor's telemetry is at `TelemetryVerbosity.HIGH`, so the current limits are published and tunable. The keys below are under `NT:/Mechanisms/<Mechanism>/<Motor>/`, as in [Live tuning keys and units](/documentation/reference/keys-and-units).

{% stepper %}
{% step %}

### Publish the battery voltage

YAMS sets the simulated battery voltage, but does not publish it. Log it every loop:

{% tabs %}
{% tab title="Java" %}
{% code title="Robot.java (fragment)" %}

```java
import static org.wpilib.units.Units.Volts;

import org.wpilib.system.RobotController;
import org.wpilib.telemetry.Telemetry;

@Override
public void robotPeriodic() {
  // ...
  Telemetry.log("Battery/Voltage", RobotController.getMeasureBatteryVoltage().in(Volts));
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/Robot.cpp (fragment)" %}

```cpp
#include <wpi/system/RobotController.hpp>
#include <wpi/telemetry/Telemetry.hpp>

void Robot::RobotPeriodic() {
  // ...
  wpi::telemetry::Log("Battery/Voltage", wpi::RobotController::GetBatteryVoltage().value());
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**Check it:** start the simulation and open AdvantageScope. `Battery/Voltage` reads 12 volts with the robot still, and dips when a mechanism moves.
{% endstep %}

{% step %}

### Find the worst moment

In simulation, do the things that happen together in a match: accelerate the drive, spin up the shooter, raise the elevator. Graph `Battery/Voltage` and each motor's current:

* TalonFX, TalonFXS and Thrifty Nova: `current/supply`, the current drawn from the battery, and `current/limit/supply`.
* SPARK MAX and SPARK Flex: `current/stator` and `current/limit/stator`, since their supply current is not published.
* FIRST A301: `current/stator`. It publishes no supply current and has no limits.

**Check it:** you can see the moment the voltage is lowest, and which motors draw the most current then.
{% endstep %}

{% step %}

### Set a starting limit on each motor

Add the limits to each `SmartMotorControllerConfig`:

{% code title="SmartMotorControllerConfig (fragment)" %}

```java
import static org.wpilib.units.Units.Amps;

.withStatorCurrentLimit(Amps.of(40)) // stator: current through the motor, limits torque and heat
.withSupplyCurrentLimit(Amps.of(30)) // supply: current from the battery; leave out on a SPARK
```

{% endcode %}

In C++, `WithStatorCurrentLimit(40_A)` and `WithSupplyCurrentLimit(30_A)`. These are places to start, not rules. Drive motors usually run higher stator limits than mechanisms, and a NEO 550 overheats quickly when stalled, so keep its stator limit low on intakes and rollers that can jam.

| Motor      | Usually on                | Stator limit to start | Supply limit to start              |
| ---------- | ------------------------- | --------------------- | ---------------------------------- |
| Kraken X60 | TalonFX                   | 60 A                  | 40 A                               |
| NEO        | SPARK MAX, TalonFXS, Nova | 40 A                  | 30 A, where the controller has one |
| NEO 550    | SPARK MAX, TalonFXS       | 20 A                  | 20 A, where the controller has one |
| NEO Vortex | SPARK Flex, TalonFXS      | 60 A                  | 40 A, where the controller has one |

{% hint style="warning" %}
The FIRST A301 has no current limits: `A301Wrapper` throws a `SmartMotorControllerConfigurationException` if either one is set, so leave them out on an A301. Its motor peaks at about 28 W, so it draws little from the battery; lower its load with gearing or a [maximum closed loop voltage](/documentation/reference/editor/config/closed-loop-control#withclosedloopcontrollermaximumvoltage) instead.
{% endhint %}

**Check it:** `current/limit/stator` (and `current/limit/supply`, where published) shows the value you set.
{% endstep %}

{% step %}

### Lower the biggest load first

The drive is usually the largest draw, so limiting it does the most. Then the next largest. For each load, stop at the first thing that brings the dip under control:

1. A [motion profile](/documentation/reference/editor/config/motion-profiles), if one suits the mechanism, so it asks for less current in the first place.
2. A lower supply current limit, where the motor controller has one.
3. A lower stator current limit, where it does not.
4. A ramp rate, only if nothing else works: see [Ramp rates](#ramp-rates).

The limits are tunable while the simulation runs: type a new value into `current/limit/supply` or `current/limit/stator` under `NT:/Tuning/<Mechanism>/<Motor>/`, as in [Live tuning](/documentation/how-to-tuning/live-tuning).

**Check it:** repeat the worst moment. The lowest `Battery/Voltage` is higher than before.
{% endstep %}

{% step %}

### Check the mechanism still does its job

A limit that is too low makes the mechanism slow or stalls it. Lower each limit until the voltage is acceptable, not further, then copy the values you settled on into your configs.

**Check it:** each mechanism still reaches its target in about the time it did, and `current/stator` sits at the limit for only a short time.
{% endstep %}
{% endstepper %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-5876fc27fea333a9e0efbb376f6fa68ba1143dca%2Fpower-limits-battery.gif?alt=media" alt="Animation of the current drawn by a swerve drive, shooter, elevator and arm, with each mechanism&#x27;s supply current limit marked. Two battery voltage traces are drawn: without limits the voltage dips to about 8.8 volts when the peaks stack, and with limits it stays near 9.7 volts"><figcaption><p>The same few seconds with and without supply current limits. Example currents and limits.</p></figcaption></figure>

## Check it

Run the worst moment once more with the limits in your code: the lowest battery voltage is higher than it was without limits, and every mechanism still does its job.

## If it did not work

* **`SmartMotorControllerConfigurationException` about a supply current limit:** the motor controller is a SPARK MAX or SPARK Flex. Remove `withSupplyCurrentLimit(...)` and use the stator limit.
* **`current/limit/...` is missing:** the motor's telemetry verbosity is below `HIGH`. On a SPARK, `current/supply` and `current/limit/supply` never appear.
* **The voltage barely dips:** the simulated currents depend on each mechanism's moment of inertia or mass. A guessed value that is too light understates them: see [Battery simulation](/documentation/understanding/battery-simulation).
* **A mechanism stutters while pushing on a game piece or stuck:** the current is being held at the limit, which is what the limit is for. Raise it a little if the mechanism is too weak.

## Ramp rates

A ramp rate is the shortest time the motor's output may take to go from 0% to 100%. It delays everything the motor does, which makes the robot seem slow, so it is the last thing to reach for.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-bc32dd1cff426cef59e9f2d76b723ed744645101%2Fpower-ramp-rate.png?alt=media" alt="Without a ramp rate the motor output jumps to full at once and the current spikes. With a 0.25 second ramp rate the output climbs over 0.25 seconds and the current is a lower, wider bump, with a slower start"><figcaption><p>A ramp rate trades the current spike for a slower start.</p></figcaption></figure>

The closed loop ramp rate applies when the motor controller's closed loop drives the motor, and the open loop ramp rate when a voltage or duty cycle does:

{% code title="SmartMotorControllerConfig (fragment)" %}

```java
import static org.wpilib.units.Units.Seconds;

.withClosedLoopRampRate(Seconds.of(0.25)) // at least 0.25 s from 0 to full output under closed loop
.withOpenLoopRampRate(Seconds.of(0.25))   // the same for voltage and duty cycle commands
```

{% endcode %}

{% hint style="warning" %}
The Thrifty Nova has a single ramp rate for open and closed loop control. `NovaWrapper` throws a `SmartMotorControllerConfigurationException` if the two ramp rates differ, so set only one of them, or both to the same value.
{% endhint %}

{% hint style="warning" %}
The FIRST A301 has no ramp rates. `A301Wrapper` throws a `SmartMotorControllerConfigurationException` if either one is set.
{% endhint %}


# How do I enable battery discharge simulation?

**Goal:** make the simulated battery run down over a match, so the voltage sags harder near the end than at the start, as a real battery does.

By default the simulated battery sags while your mechanisms draw current, but it never runs down: every moment of the run starts from a full 12 V battery. Discharge simulation adds the battery's **state of charge**, how full it is from 1 (full) to 0 (empty). As your mechanisms draw current, the charge goes down. A battery that is less full rests at a lower voltage, and its **internal resistance**, which makes the voltage sag under load, goes up. So late in a long simulated run, the same load sags the voltage further.

For why YAMS models one shared battery at all, see [Battery Simulation](/documentation/understanding/battery-simulation).

## Turn on discharge modeling

Call `enableDischarge(...)` once, early on, with the battery's capacity in amp-hours (how much charge it holds), its voltage when full, and its internal resistance when full. The `Robot` constructor is a good place for it. A fresh 18 Ah competition battery is a reasonable default if you have no measured numbers for your own.

{% tabs %}
{% tab title="Java" %}
{% code title="Robot.java (fragment)" %}

```java
import static org.wpilib.units.Units.MilliOhms;
import static org.wpilib.units.Units.Volts;

import yams.core.motorcontrollers.simulation.BatterySim;

public Robot() {
  // 18 Ah, 12.9 V and 20 milliohms when full.
  BatterySim.enableDischarge(18.0, Volts.of(12.9), MilliOhms.of(20));
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/Robot.cpp (fragment)" %}

```cpp
#include <yams/motorcontrollers/simulation/BatterySim.hpp>

Robot::Robot() {
  // 18 Ah, 12.9 V and 20 milliohms when full.
  yams::motorcontrollers::simulation::BatterySim::EnableDischarge(
      18.0, wpi::units::volt_t{12.9}, wpi::units::ohm_t{0.020});
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Discharge modeling only affects simulation. On a real robot `BatterySim` is never used: the SystemCore reports the real battery voltage, so this call does nothing there.
{% endhint %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-2f3c0455fba73fccc85b012549c367bc6a649c39%2Fbattery-sim-discharge.png?alt=media" alt="Two graphs of the default discharge model. Resting voltage against state of charge falls slowly from 12.9 volts at full to 12.0 volts at 20 percent, then steeply to 9 volts when empty. Usable capacity against sustained current falls from 100 percent at 0.9 amps to 60 percent at 54 amps. Internal resistance rises from 20 milliohms when full to 60 milliohms when empty"><figcaption><p>The default discharge curves.</p></figcaption></figure>

## Make sure your mechanisms report accurate current draw

The simulated battery only runs down as fast as the current your mechanisms draw, and that comes from each mechanism's physics simulation. If a mechanism's moment of inertia is guessed rather than measured, its simulated current draw, and so how fast it drains the battery, will be off. Set a real one on each `SmartMotorControllerConfig` with `withMomentOfInertia(...)` before relying on discharge numbers: see [MOI](/documentation/understanding/turrets-wrists#moment-of-inertia) for how.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-5676fc440147bf970eeca17663417c43d4f9a903%2Fbattery-sim-mechanisms.png?alt=media" alt="Six sketches of current over time. Arm: spikes when it starts and stops, then a steady draw to hold against gravity. Elevator: largest going up, steady to hold a height. Flywheel, shooter, rollers: very large while spinning up, small at speed, a bump on every shot. Pivot, turret, wrist: short bursts when starting and stopping. Swerve drive: eight motors, usually the largest draw. All together: the draws add up and overlapping peaks cause the deepest sag"><figcaption><p>When each kind of mechanism draws current.</p></figcaption></figure>

## Reset between runs (optional)

The simulated battery keeps its charge from one simulated match to the next, as a real battery does. To start every simulated match or unit test from a full battery, call `resetDischarge()` at the start of it: in the setup of your unit tests, or wherever you reset robot state between simulated matches. `disableDischarge()` turns discharge modeling back off.

{% tabs %}
{% tab title="Java" %}
{% code title="A unit test (fragment)" %}

```java
import org.junit.jupiter.api.BeforeEach;
import yams.core.motorcontrollers.simulation.BatterySim;

@BeforeEach
void setup() {
  BatterySim.resetDischarge();
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="A unit test (fragment)" %}

```cpp
#include <yams/motorcontrollers/simulation/BatterySim.hpp>

// At the start of each test.
yams::motorcontrollers::simulation::BatterySim::ResetDischarge();
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Read the state of charge for telemetry (optional)

`getStateOfCharge()` returns the charge from `0` (empty) to `1` (full). Publish it every loop to watch the battery run down over a simulated match. YAMS sets the simulated battery voltage but does not publish it, so publish that too: it is what `RobotController` reports, in simulation as on the robot.

{% tabs %}
{% tab title="Java" %}
{% code title="Robot.java (fragment)" %}

```java
import static org.wpilib.units.Units.Volts;

import org.wpilib.system.RobotController;
import org.wpilib.telemetry.Telemetry;
import yams.core.motorcontrollers.simulation.BatterySim;

@Override
public void robotPeriodic() {
  // ...
  Telemetry.log("Battery/StateOfCharge", BatterySim.getStateOfCharge());
  Telemetry.log("Battery/Voltage", RobotController.getMeasureBatteryVoltage().in(Volts));
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/Robot.cpp (fragment)" %}

```cpp
#include <wpi/system/RobotController.hpp>
#include <wpi/telemetry/Telemetry.hpp>
#include <yams/motorcontrollers/simulation/BatterySim.hpp>

void Robot::RobotPeriodic() {
  // ...
  wpi::telemetry::Log("Battery/StateOfCharge",
                      yams::motorcontrollers::simulation::BatterySim::GetStateOfCharge());
  wpi::telemetry::Log("Battery/Voltage", wpi::RobotController::GetBatteryVoltage().value());
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Replace the state-of-charge curve (optional)

`enableDischarge(...)` lowers the resting voltage along a curve for a typical FRC sealed lead-acid battery: flat through most of the charge, then dropping quickly near empty. To model a different battery, such as a well-used one that sags earlier, or one you measured with a load tester, call `replaceSOCInterpolation(...)` with your own curve of state of charge to voltage, **before** `enableDischarge(...)`.

{% tabs %}
{% tab title="Java" %}
{% code title="Robot.java (fragment)" %}

```java
import static org.wpilib.units.Units.MilliOhms;
import static org.wpilib.units.Units.Volts;

import org.wpilib.math.interpolation.InterpolatingDoubleTreeMap;
import yams.core.motorcontrollers.simulation.BatterySim;

// State of charge, then the resting voltage at that charge.
InterpolatingDoubleTreeMap wornBatteryCurve = new InterpolatingDoubleTreeMap();
wornBatteryCurve.put(0.00, 8.0);
wornBatteryCurve.put(0.05, 9.5);
wornBatteryCurve.put(0.10, 10.5);
wornBatteryCurve.put(0.20, 11.2);
wornBatteryCurve.put(0.40, 11.6);
wornBatteryCurve.put(0.60, 11.9);
wornBatteryCurve.put(0.80, 12.2);
wornBatteryCurve.put(0.90, 12.4);
wornBatteryCurve.put(1.00, 12.6);

BatterySim.replaceSOCInterpolation(wornBatteryCurve);
// replaceSOCInterpolation swaps the curve as soon as it is called. Calling it first means discharge uses your curve from the start.
BatterySim.enableDischarge(15.0, Volts.of(12.6), MilliOhms.of(28));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/Robot.cpp (fragment)" %}

```cpp
#include <map>

#include <yams/motorcontrollers/simulation/BatterySim.hpp>

using yams::motorcontrollers::simulation::BatterySim;

// State of charge, then the resting voltage at that charge.
std::map<double, double> wornBatteryCurve{
    {0.00, 8.0},  {0.05, 9.5},  {0.10, 10.5}, {0.20, 11.2}, {0.40, 11.6},
    {0.60, 11.9}, {0.80, 12.2}, {0.90, 12.4}, {1.00, 12.6},
};

BatterySim::ReplaceSOCInterpolation(wornBatteryCurve);
// ReplaceSOCInterpolation swaps the curve as soon as it is called. Calling it first means discharge uses your curve from the start.
BatterySim::EnableDischarge(15.0, wpi::units::volt_t{12.6}, wpi::units::ohm_t{0.028});
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
Cover the whole range of charge, from `0` to `1`. Outside the points you give, the voltage stays at the nearest point's, so a curve missing the low or high end will not sag realistically there. See [Custom discharge curves](/documentation/understanding/battery-simulation#custom-discharge-curves) for choosing the points.
{% endhint %}

## Replace the capacity derating curve (optional)

A lead-acid battery gives fewer amp-hours the faster it is drained (the Peukert effect). `enableDischarge(...)` accounts for this with a curve of sustained current to the fraction of the capacity you get, averaged from real FRC battery testing. If you measured your own battery, call `replaceCapacityDerating(...)` with your curve, **before** `enableDischarge(...)`.

{% tabs %}
{% tab title="Java" %}
{% code title="Robot.java (fragment)" %}

```java
import static org.wpilib.units.Units.MilliOhms;
import static org.wpilib.units.Units.Volts;

import org.wpilib.math.interpolation.InterpolatingDoubleTreeMap;
import yams.core.motorcontrollers.simulation.BatterySim;

// Sustained current in amps, then the fraction of the capacity you get at that current.
InterpolatingDoubleTreeMap measuredDerating = new InterpolatingDoubleTreeMap();
measuredDerating.put(0.9, 1.000);
measuredDerating.put(20.0, 0.80);
measuredDerating.put(40.0, 0.65);
measuredDerating.put(60.0, 0.55);

BatterySim.replaceCapacityDerating(measuredDerating);
// replaceCapacityDerating swaps the curve as soon as it is called. Calling it first means discharge uses your curve from the start.
BatterySim.enableDischarge(18.0, Volts.of(12.9), MilliOhms.of(20));
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/Robot.cpp (fragment)" %}

```cpp
#include <map>

#include <yams/motorcontrollers/simulation/BatterySim.hpp>

using yams::motorcontrollers::simulation::BatterySim;

// Sustained current in amps, then the fraction of the capacity you get at that current.
std::map<double, double> measuredDerating{{0.9, 1.000}, {20.0, 0.80}, {40.0, 0.65}, {60.0, 0.55}};

BatterySim::ReplaceCapacityDerating(measuredDerating);
// ReplaceCapacityDerating swaps the curve as soon as it is called. Calling it first means discharge uses your curve from the start.
BatterySim::EnableDischarge(18.0, wpi::units::volt_t{12.9}, wpi::units::ohm_t{0.020});
```

{% endcode %}
{% endtab %}
{% endtabs %}

See [Capacity derating](/documentation/understanding/battery-simulation#capacity-derating) for where the default curve comes from.

## Check it

1. Publish the state of charge and the battery voltage as in [Read the state of charge for telemetry](#read-the-state-of-charge-for-telemetry-optional), start the simulation, and graph `Battery/StateOfCharge` and `Battery/Voltage` in AdvantageScope.
2. Run your mechanisms hard for a minute or two: spin up a shooter, drive the swerve back and forth.
3. `Battery/StateOfCharge` should start at 1 and fall steadily while mechanisms run, and stay put while they are idle. `Battery/Voltage` should sag more under the same load late in the run than at the start, and its resting value should creep down.

If the state of charge never moves, `enableDischarge(...)` was not called. If it barely moves, check the moments of inertia: see [Make sure your mechanisms report accurate current draw](#make-sure-your-mechanisms-report-accurate-current-draw).

## Related pages

* [Battery Simulation](/documentation/understanding/battery-simulation), the full explanation of the shared battery model and why it matters
* [MOI](/documentation/understanding/turrets-wrists#moment-of-inertia), accurate current draw starts with an accurate moment of inertia
* [Limiting Power Consumption](/documentation/how-to-motor-controllers-and-sensors/limiting-power-consumption)


# How do I run a high fidelity simulation?

Step the simulated physics every millisecond from a Notifier, so a closed loop running on the motor controller sees a fresh measurement on every run.

A TalonFX, TalonFXS or SPARK can run its closed loop on the motor controller, once every millisecond (1 kHz). By default YAMS steps the simulated physics once every 20 ms. Between two steps the simulated motor controller runs its loop 20 times against a measurement that has not changed, the way a real controller would if its encoder only updated every 20 ms.

For most robots that is close enough. It stops being close enough with stiff gains: a loop that holds steady on the robot can oscillate in simulation, and gains tuned in simulation come out softer than the robot can take.

A high fidelity simulation steps the physics every 1 ms instead, from a `Notifier`, so every run of the motor controller's loop sees where the mechanism actually is.

{% hint style="info" %}
This only changes simulation. Nothing on this page has any effect on the real robot.
{% endhint %}

## What changes

|                                                                                                                                                  | Default                                             | High fidelity                                      |
| ------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | -------------------------------------------------- |
| Physics step ([`withSimulationPeriod`](/documentation/reference/editor/config/simulation#withsimulationperiod))                                  | 20 ms                                               | 1 ms                                               |
| What calls `simIterate()`                                                                                                                        | `simulationPeriodic()`, every 20 ms                 | A `Notifier`, every 1 ms                           |
| Loop on the motor controller                                                                                                                     | Runs every 1 ms, gets a new measurement every 20 ms | Runs every 1 ms, gets a new measurement every 1 ms |
| Loop on the SystemCore ([`withClosedLoopControlPeriod`](/documentation/reference/editor/config/closed-loop-control#withclosedloopcontrolperiod)) | 20 ms                                               | Unchanged                                          |
| `updateTelemetry()`                                                                                                                              | `periodic()`                                        | Unchanged                                          |

## Which motor controllers it helps

[Where the loop runs](/documentation/reference/editor/config/closed-loop-control#where-the-loop-runs) decides how much you gain.

* **TalonFX and TalonFXS.** PID and motion profiles run on the motor controller. Phoenix simulates the motor controller's own loop, and YAMS gives it the rotor position and velocity on every `simIterate()`. YAMS also raises the update rate of the motor's status signals to match the simulation period, in simulation only, so the values you read keep up with the physics.
* **SPARK MAX and SPARK Flex.** PID and trapezoidal profiles run on the motor controller. YAMS already runs the SPARK's simulated loop once per millisecond inside every step, but the mechanism's velocity is frozen for the whole step. At 1 ms every run of the loop gets a fresh one.
* **Exponential profiles or** [**LQR**](/documentation/understanding/lqr-controllers) **on any motor controller, velocity trapezoidal profiles and other loops a Thrifty Nova can't run, and every loop on an A301.** The loop runs on the SystemCore, every closed loop control period. Those loops gain nothing from a faster simulation period apart from smoother physics.

## Set it up

{% stepper %}
{% step %}

#### Set the simulation period to 1 ms

Add `withSimulationPeriod` to the `SmartMotorControllerConfig` of every motor the `Notifier` will step. For a swerve drive that is the drive motor and the azimuth motor of every module.

{% tabs %}
{% tab title="Java" %}

```java
import static org.wpilib.units.Units.Milliseconds;

.withSimulationPeriod(Milliseconds.of(1))
```

{% endtab %}

{% tab title="C++" %}

```cpp
.WithSimulationPeriod(1_ms)
```

{% endtab %}
{% endtabs %}

The simulated supply current filter and the shared [battery simulation](/documentation/understanding/battery-simulation) follow the simulation period on their own, so there is nothing else to set for them.

{% hint style="warning" %}
**The simulation period must match how often `simIterate()` is called.** Each call moves the simulated mechanism forward by exactly one simulation period, however much time has really passed. With a 20 ms period called every 1 ms, the mechanism moves 20 times faster than real time. With a 1 ms period called every 20 ms, it moves 20 times slower.
{% endhint %}
{% endstep %}

{% step %}

#### Step the simulation from a `Notifier`

Create a `Notifier` that calls `simIterate()` every millisecond, and only start it in simulation. Then take `simIterate()` out of `simulationPeriodic()`. If both call it, the mechanism is stepped twice and moves faster than real time.

Keep `updateTelemetry()` where it is. Publishing telemetry every millisecond only costs time.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/ArmSubsystem.java" %}

```java
import static org.wpilib.units.Units.Milliseconds;

import org.wpilib.framework.RobotBase;
import org.wpilib.system.Notifier;

public class ArmSubsystem extends SubsystemBase {
  // ...

  // Steps the arm's physics simulation every millisecond, in simulation only.
  private final Notifier simNotifier = new Notifier(() -> arm.simIterate());

  public ArmSubsystem() {
    if (RobotBase.isSimulation()) {
      simNotifier.setName("Arm simulation");
      // Must match withSimulationPeriod on the arm's motor.
      simNotifier.startPeriodic(Milliseconds.of(1));
    }
  }

  @Override
  public void periodic() {
    // Publishes the arm's telemetry, and applies anything changed through live tuning.
    arm.updateTelemetry();
  }

  // No simulationPeriodic(): the Notifier calls arm.simIterate() instead.
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
In Commands v3 the simulation already runs in a `Notifier` that `Robot.simulationInit()` starts for each mechanism (see [Step 4: Simulate it](/documentation/tutorials/arm/simulate)). Keep that pattern and only change the period: start the arm's `Notifier` every 1 ms instead of every robot loop.

{% code title="Robot.java (fragment)" %}

```java
import static org.wpilib.units.Units.Milliseconds;

import org.wpilib.units.measure.Time;

@Override
public void simulationInit() {
  // Must match withSimulationPeriod on the arm's motor.
  startSimulation("Arm", arm::simulationPeriodic, Milliseconds.of(1));
}

// Keep the tutorial's startSimulation(name, simulationPeriodic), which runs every robot loop,
// for mechanisms left on the default 20 ms period, and add this overload beside it.

/** Runs a mechanism's simulation in its own Notifier, every period. */
private void startSimulation(String name, Runnable simulationPeriodic, Time period) {
  Notifier notifier = new Notifier(simulationPeriodic);
  notifier.setName(name + " Simulation");
  notifier.startPeriodic(period);
  simulationNotifiers.add(notifier);
}
```

{% endcode %}

`arm` is the `ArmMechanism` field in the tutorial's `Robot`, and `ArmMechanism.simulationPeriodic()` stays as it is, calling `arm.simIterate()`. Mechanisms left on the default 20 ms period keep calling the two-argument `startSimulation(...)`.
{% endtab %}

{% tab title="C++" %}
{% code title="include/subsystems/ArmSubsystem.hpp" %}

```cpp
#include <wpi/system/Notifier.hpp>

class ArmSubsystem : public wpi::cmd::SubsystemBase {
  // ...
 private:
  // Steps the arm's physics simulation every millisecond, in simulation only.
  // Declare it after m_arm, so it is stopped and destroyed before the arm is.
  wpi::Notifier m_simNotifier{[this] { m_arm->SimIterate(); }};
};
```

{% endcode %}

{% code title="cpp/subsystems/ArmSubsystem.cpp" %}

```cpp
#include <wpi/framework/RobotBase.hpp>

ArmSubsystem::ArmSubsystem() {
  // ...
  if (wpi::RobotBase::IsSimulation()) {
    m_simNotifier.SetName("Arm simulation");
    // Must match WithSimulationPeriod on the arm's motor.
    m_simNotifier.StartPeriodic(1_ms);
  }
}

void ArmSubsystem::Periodic() {
  // Publishes the arm's telemetry, and applies anything changed through live tuning.
  m_arm->UpdateTelemetry();
}

// No SimulationPeriodic(): the Notifier calls m_arm->SimIterate() instead.
```

{% endcode %}
{% endtab %}
{% endtabs %}

The same pattern works for every mechanism class, and for a `SmartMotorController` used without one: call its `simIterate()` from the `Notifier`. A mechanism class also updates its Mechanism2d drawing on every step, and an `Arm` or `Pivot` enforces its simulated hard limits there too, so those keep up with the physics. For a swerve drive, call the drive's `simIterate()` from the `Notifier`.
{% endstep %}

{% step %}

#### Check your simulation gains

Gains that were tuned against 20 ms physics may now behave differently, usually better. If you set [`withSimClosedLoopController`](/documentation/reference/editor/config/simulation#withsimclosedloopcontroller-and-withsimfeedforward) softer than the real gains to stop oscillation in simulation, try the real gains again first.

Nothing else needs to change:

* **Leave `withClosedLoopControlPeriod` alone.** It sets how often a loop on the SystemCore runs, not the physics. An LQR controller must keep the default 20 ms.
* **Leave the real-robot config alone.** `withSimulationPeriod` is ignored on the robot.
  {% endstep %}
  {% endstepper %}

## Things to know

* **The `Notifier` runs on its own thread**, at the same time as your periodic methods and commands. YAMS runs its own SystemCore closed loops the same way. Call `simIterate()` for a mechanism from one place only.
* **It costs CPU.** Every mechanism now runs its physics 1000 times a second. If your computer cannot keep up, the `Notifier` runs late, and since each call still adds exactly 1 ms, the simulation runs slower than real time. With many mechanisms, one `Notifier` that calls every `simIterate()` is lighter than one per mechanism. A period of 2 ms or 5 ms is a good compromise: it is still 10 or 4 times finer than the default.
* **Keep unit tests on the default period.** Stepping every millisecond makes tests much slower, especially on CI.

## Check it

Start the simulation and hold the arm at a setpoint. With stiff gains that oscillated before, the arm should now settle. The mechanism should also move at real speed: a move that takes 1 second on the robot should take about 1 second in simulation. If it is 20 times too fast or too slow, the simulation period and the `Notifier` period do not match.

## Read more

* Make the battery run down in simulation too: [How do I enable battery discharge simulation?](/documentation/how-to-simulation-and-logging/how-do-i-enable-battery-discharge-simulation)

## Code Reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)


# How do I view my DataLog in AdvantageScope?

Record what your robot did to a DataLog file, then open that file in AdvantageScope to replay the run on a graph, a field and a swerve view. This page does it for the swerve drive from the [Swerve Drive tutorial](/documentation/tutorials/swerve-drive). Any YAMS mechanism works the same way.

You need:

* [AdvantageScope](https://docs.advantagescope.org/) installed on your computer.
* A robot project with YAMS telemetry, on the robot or in simulation.

{% hint style="info" %}
This is not AdvantageKit's [Log Replay](https://docs.advantagekit.org/getting-started/what-is-advantagekit), which runs your code again against a recorded log. Here you only open the file and look at the values. It works with every YAMS project, with or without AdvantageKit.
{% endhint %}

{% stepper %}
{% step %}

### Start the DataLog

WPILib's `DataLogManager` owns the file; YAMS writes into it. Start it once, at the top of the `Robot` constructor:

{% code title="Robot.java (fragment)" %}

```java
import org.wpilib.driverstation.DriverStation;
import org.wpilib.system.DataLogManager;

public Robot() {
  DataLogManager.start();
  // Optional: also log the Driver Station and joysticks.
  DriverStation.startDataLog(DataLogManager.getLog());
}
```

{% endcode %}

Without this call, the log starts the first time YAMS writes to it. Calling it yourself starts the log at power on, and lets you add the Driver Station data.

Where the file goes:

* **On the robot:** a USB drive, if one is plugged in. Otherwise `/home/systemcore/logs` on the SystemCore.
* **In simulation:** the `logs/` folder next to `build.gradle`.

The file starts as `WPILIB_TBD_<random>.wpilog`. Once the Driver Station connects and the time is known, it is renamed to a timestamp, such as `WPILIB_20260817_010558.wpilog`, and the console prints `DataLog: Renamed log file from '...' to '...'`.

**Check it:** run the code in simulation. A `.wpilog` file appears in the `logs/` folder.
{% endstep %}

{% step %}

### Turn on the DataLog for the swerve drive

A DataLog name turns logging on, and it is set on each telemetry config. The drive, each module and each motor have their own config, and setting one does not set the others. In the swerve tutorial, change three `withTelemetry(...)` calls:

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-6a0705bf23cb0c0b1c60a520a2a8bc8bbe8a32ae%2Fdatalog-walkthrough-1-configure.gif?alt=media" alt="Scrolling through SwerveSubsystem in the editor, stopping on each withDataLogName call: on the azimuth motor&#x27;s telemetry config in createModule, on each module&#x27;s telemetry config, and on the drive&#x27;s telemetry config in the constructor."><figcaption><p>The three places a DataLog name goes.</p></figcaption></figure>

{% tabs %}
{% tab title="Java" %}
In `createModule()`, the azimuth motor's config (from [The module motors](/documentation/tutorials/swerve-drive/module-motors)), in place of `.withTelemetry("angleMotor", TelemetryVerbosity.HIGH)`:

```java
.withTelemetry("angleMotor", new SmartMotorControllerTelemetryConfig()
    .withTelemetryVerbosity(TelemetryVerbosity.HIGH)
    .withDataLogName("Swerve/" + moduleName + "/angleMotor"));
```

In `createModule()`, the module's config (from [The modules and the drive](/documentation/tutorials/swerve-drive/modules-and-drive)), in place of `.withTelemetry(moduleName, TelemetryVerbosity.HIGH)`:

```java
.withTelemetry(moduleName, new SwerveModuleTelemetryConfig(TelemetryVerbosity.HIGH)
    .withDataLogName("Swerve/" + moduleName))
```

In the constructor, the drive's config:

```java
.withTelemetry("swerve", new SwerveDriveTelemetryConfig(TelemetryVerbosity.HIGH)
    .withDataLogName("Swerve"))
```

The `*TelemetryConfig` classes are in `yams.core.telemetry`, and `TelemetryVerbosity` is in `yams.core.telemetry.enums`.
{% endtab %}

{% tab title="C++" %}
The same three changes, with `WithDataLogName`. From the [C++ swerve example](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/cpptest/src/main/cpp/subsystems/SwerveSubsystem.cpp):

```cpp
// The drive.
.WithTelemetry("swerve", yams::telemetry::SwerveDriveTelemetryConfig(SwerveDriveConfig::TelemetryVerbosity::HIGH)
    .WithDataLogName("Swerve"))

// Each module.
.WithTelemetry(moduleName, yams::telemetry::SwerveModuleTelemetryConfig(Cfg::TelemetryVerbosity::HIGH)
    .WithDataLogName("Swerve/" + moduleName))
```

The azimuth motor takes a `yams::telemetry::SmartMotorControllerTelemetryConfig` with `.WithDataLogName(...)`, as on the [Telemetry](/documentation/understanding/telemetry#recording-a-match-to-a-datalog) page.
{% endtab %}
{% endtabs %}

Starting each name with `Swerve/` puts everything in one `Swerve` group in AdvantageScope. The drive motors are left out here; give them a DataLog name the same way if you want them.

{% hint style="info" %}
**At competition**, keep the DataLog but stop sending to NetworkTables, so the dashboard link stays light. `withNetworkTables(...)` is read once, when the code starts, so drive it from a constant you set to `true` before you deploy for matches:

```java
// Constants.COMPETITION is a boolean you add to Constants.java.
.withTelemetry("angleMotor", new SmartMotorControllerTelemetryConfig()
    .withTelemetryVerbosity(TelemetryVerbosity.HIGH)
    .withDataLogName("Swerve/" + moduleName + "/angleMotor")
    .withNetworkTables(!Constants.COMPETITION));
```

`RobotState.isFMSAttached()` does not work here: the code starts before the field connects, so it reads `false` and NetworkTables stays on.

[DataLog best practices](/documentation/understanding/datalog-best-practices) covers choosing what to log.
{% endhint %}

**Check it:** the code builds.
{% endstep %}

{% step %}

### Record a run

Deploy or simulate the robot, enable it, and drive around for a bit. Every loop writes to NetworkTables and to the DataLog.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-2dd328831c495daefdb8210c1a0e0a228c690ad2%2Fdatalog-walkthrough-2-run-in-sim.gif?alt=media" alt="The swerve example running in WPILib simulation in Teleoperated, with the robot driven around the field so that telemetry is being recorded."><figcaption><p>Driving the swerve example in simulation to record a run.</p></figcaption></figure>

**Check it:** stop the run. The newest `.wpilog` file has grown while you drove.
{% endstep %}

{% step %}

### Open the file in AdvantageScope

1. Copy the `.wpilog` from the USB drive or `/home/systemcore/logs`, or find it in your project's `logs/` folder after a simulation.
2. In AdvantageScope, choose **File > Open File...**, or drag the file onto the window. Don't use **Connect to Robot** or **Connect to Simulator**: those show live values, not the recording.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-75bb9a694ee85379c1900bfeefcd0a58112395de%2Fdatalog-walkthrough-3-open-in-advantagescope.gif?alt=media" alt="AdvantageScope&#x27;s File, Open File dialog showing the logs folder, with the newest .wpilog selected among the logs from earlier runs."><figcaption><p>Opening the newest <code>.wpilog</code> in the <code>logs/</code> folder.</p></figcaption></figure>

The sidebar shows everything in the file, grouped by the DataLog names. Under `Swerve`:

| Entry                                                      | What it is                                               |
| ---------------------------------------------------------- | -------------------------------------------------------- |
| `Swerve/pose`                                              | The robot's pose                                         |
| `Swerve/chassis/current`, `Swerve/chassis/desired`         | The robot's measured and requested velocity              |
| `Swerve/states/current`, `Swerve/states/desired`           | The four module states                                   |
| `Swerve/degrees/gyro`                                      | The gyro angle                                           |
| `Swerve/frontleft/degrees/encoder`                         | A module's absolute encoder angle (one per module)       |
| `Swerve/frontleft/state`                                   | A module's own state                                     |
| `Swerve/frontleft/angleMotor/rotations/mechanism/position` | One of the azimuth motor's values (one group per module) |

Numbers are filed under a folder named after their unit, such as `degrees` or `rotations`, so you always know what you are looking at. Poses and states have no unit folder.

**Check it:** the sidebar has a `Swerve` group.
{% endstep %}

{% step %}

### Explore the run

* **Swerve tab:** drag `Swerve/states/current` into **Sources** to watch the wheels turn and spin as they did.
* **2D Field tab:** drag `Swerve/pose` in to see the path the robot drove.
* **Line Graph tab:** drag in any number, such as `Swerve/degrees/gyro` or a motor's current. To show it in other units, right-click it in the legend and choose **Convert Units...** ([more on units](/documentation/reference/keys-and-units#see-both-in-the-same-units-with-advantagescope)).

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-90666d18be34efc6d8f589910cc81dd25153ab98%2Fdatalog-walkthrough-4-explore-swerve-tab.gif?alt=media" alt="The AdvantageScope field tree expanded to Swerve, states, current, which is dragged into the Swerve tab&#x27;s Sources list; the four module vectors then animate as the timeline plays."><figcaption><p>Replaying the recorded module states in the Swerve tab.</p></figcaption></figure>

Drag the timeline at the top to move through the run, or press play to watch it at normal speed. The file needs nothing else running, so you can open two matches side by side, or send the file to a teammate.

**Check it:** dragging the timeline moves the wheels in the Swerve tab.
{% endstep %}
{% endstepper %}

## Check it

The sidebar has a `Swerve` group with the entries in the table above, and dragging `Swerve/pose` into a 2D Field tab draws the path you drove.

## If it did not work

* **There is no `.wpilog` file.** The DataLog never started. Call `DataLogManager.start()` in the `Robot` constructor, as in [Start the DataLog](#start-the-datalog).
* **The `Swerve` group is missing, but NetworkTables shows the values.** That telemetry config has no `withDataLogName(...)`. The drive, each module and each motor need their own.
* **A number you can see live isn't in the file.** Values you can edit under `NT:/Tuning`, such as gains, are not written to the DataLog.
* **Something else.** See [Troubleshooting](/documentation/tutorials/troubleshooting).


# How do I show my mechanisms on a 3D robot model?

Publish each mechanism's Pose3d, so AdvantageScope moves the matching part of your robot's CAD model as the real mechanism moves.

AdvantageScope can show your robot's CAD model on the 3D field, with each mechanism moving as the real one does: the arm swinging, the elevator rising and the turret turning. Each moving part is a separate model, called a component, and your robot code publishes a `Pose3d` for each one. Every YAMS mechanism gives you that pose with `getPose3d()`.

{% hint style="info" %}
`getPose3d()` is in YAMS releases after v2026.10.15. It replaces `getRelativeMechanismPosition()`.
{% endhint %}

{% hint style="success" %}
Only want to see your mechanisms in 3D in simulation, without a CAD model? In simulation, every YAMS mechanism publishes a `Mechanism2d` under `Mechanisms/<name>/mechanism`, and AdvantageScope can [show a `Mechanism2d` on the 3D field](https://docs.advantagescope.org/tab-reference/3d-field#2d-mechanisms) with no setup. `getPose3d()` also works on the real robot.
{% endhint %}

AdvantageScope's video walks through setting up a custom robot model and its components:

{% embed url="<https://www.youtube.com/watch?v=unX1PsPi0VA>" %}
Configuring Custom Robot Models for AdvantageScope
{% endembed %}

[AdvantageScope's custom assets page](https://docs.advantagescope.org/more-features/custom-assets) has the full reference.

{% stepper %}
{% step %}

### Tell YAMS where each mechanism is

Give each mechanism a `MechanismPositionConfig`: where it is mounted on the robot, and the plane it moves in. Positions are in meters from the robot's origin, which AdvantageScope puts at the center of the robot, **on the floor**: +X forward, +Y left and +Z up.

| Mechanism          | Where it is mounted         | Its pose                                                                                                                                                                                                                                                                                                                  |
| ------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Arm`, `Pivot`     | The axis it turns about     | The axis, turned to its angle                                                                                                                                                                                                                                                                                             |
| `Elevator`         | The carriage at zero height | The carriage, moved by its height along the elevator's angle. For each stage of a multi-stage elevator, see [How do I show an elevator's stages on a 3D robot model?](/documentation/how-to-simulation-and-logging/how-do-i-show-my-mechanisms-on-a-3d-robot-model/how-do-i-show-an-elevators-stages-on-a-3d-robot-model) |
| `FlyWheel`         | Its axle                    | The axle, turned by the wheel's position                                                                                                                                                                                                                                                                                  |
| `DoubleJointedArm` | The lower arm's axis        | `getPose3d()` for the lower arm, `getUpperPose3d()` for the upper arm at the elbow                                                                                                                                                                                                                                        |

A part turns in its movement plane: **XZ** by default (it points forward at 0° and a positive angle turns it up, like an arm over the front), **YZ** for an arm over the side (it points left at 0°), or **XY** for a turret (it points forward at 0° and a positive angle turns it left). A `Pivot` is in the XY plane unless you give it a `MechanismPositionConfig`.

{% tabs %}
{% tab title="Java" %}
One YAMS mechanism per subsystem, so these are fragments of three subsystems. Each one exposes its mechanism's pose with a `getPose3d()` method.

{% code title="ElevatorSubsystem.java (fragment)" %}

```java
import org.wpilib.math.geometry.Pose3d;
import org.wpilib.math.geometry.Translation3d;
import yams.core.mechanisms.config.MechanismPositionConfig;

// An elevator 0.1 m behind the robot's center, its carriage 0.15 m off the floor at zero height.
private final Elevator elevator = new Elevator(new ElevatorConfig()
    // ... the rest of the config
    .withMechanismPositionConfig(new MechanismPositionConfig()
        .withRelativePosition(new Translation3d(-0.1, 0, 0.15))), elevatorMotor);

public Pose3d getPose3d() {
  return elevator.getPose3d();
}
```

{% endcode %}

{% code title="ArmSubsystem.java (fragment)" %}

```java
import org.wpilib.math.geometry.Pose3d;
import org.wpilib.math.geometry.Translation3d;
import yams.core.mechanisms.config.MechanismPositionConfig;

private final Arm arm;

// The arm rides on the elevator's carriage, so it is given the elevator subsystem.
public ArmSubsystem(ElevatorSubsystem elevator) {
  // Its axis is 0.2 m above the carriage's reference point, and it moves with the carriage.
  arm = new Arm(new ArmConfig()
      // ... the rest of the config
      .withMechanismPositionConfig(new MechanismPositionConfig()
          .withParent(elevator::getPose3d)
          .withRelativePosition(new Translation3d(0, 0, 0.2))), armMotor);
}

public Pose3d getPose3d() {
  return arm.getPose3d();
}
```

{% endcode %}

{% code title="TurretSubsystem.java (fragment)" %}

```java
import org.wpilib.math.geometry.Pose3d;
import org.wpilib.math.geometry.Rotation3d;
import org.wpilib.math.geometry.Transform3d;
import org.wpilib.math.geometry.Translation3d;
import yams.core.mechanisms.config.MechanismPositionConfig;
import yams.core.mechanisms.config.MechanismPositionConfig.Plane;

// A turret 0.3 m off the floor, turned 180° so that its 0° faces the back of the robot.
private final Pivot turret = new Pivot(new PivotConfig()
    // ... the rest of the config
    .withMechanismPositionConfig(new MechanismPositionConfig()
        .withMovementPlane(Plane.XY)
        .withRelativePosition(new Transform3d(new Translation3d(0, 0, 0.3), new Rotation3d(0, 0, Math.PI)))), turretMotor);

public Pose3d getPose3d() {
  return turret.getPose3d();
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}

```cpp
using yams::mechanisms::config::MechanismPositionConfig;

// An elevator 0.1 m behind the robot's center, its carriage 0.15 m off the floor at zero height.
m_elevatorConfig.WithMechanismPositionConfig(
    MechanismPositionConfig{}.WithRelativePosition(wpi::math::Translation3d{-0.1_m, 0_m, 0.15_m}));

// An arm on the elevator's carriage, its axis 0.2 m above the carriage's reference point.
m_armConfig.WithMechanismPositionConfig(
    MechanismPositionConfig{}
        .WithParent([this] { return m_elevator->GetPose3d(); })
        .WithRelativePosition(wpi::math::Translation3d{0_m, 0_m, 0.2_m}));

// A turret 0.3 m off the floor, turned 180 degrees so that its 0 degrees faces the back of the robot.
m_turretConfig.WithMechanismPositionConfig(
    MechanismPositionConfig{}
        .WithMovementPlane(MechanismPositionConfig::Plane::XY)
        .WithRelativePosition(wpi::math::Transform3d{wpi::math::Translation3d{0_m, 0_m, 0.3_m},
                                                     wpi::math::Rotation3d{0_rad, 0_rad, 180_deg}}));
```

{% endtab %}
{% endtabs %}

`withRelativePosition(Transform3d)` turns the mechanism where it is mounted, such as an arm on the side of the robot facing left. With `withParent(...)`, the relative position is from the parent's pose, such as the elevator's carriage, rather than from the robot.

**Check it:** the code builds.
{% endstep %}

{% step %}

### Publish the poses

Publish every component's pose in one array, in the same order as the components in the model (`model_0.glb`, `model_1.glb`, ...). Publish it every loop.

{% tabs %}
{% tab title="Java" %}
Commands v2: add a method to `RobotContainer`, where all three subsystems are, and call it from `Robot.robotPeriodic()`. Commands v3: put the call in `Robot.robotPeriodic()`.

{% code title="RobotContainer.java (fragment)" %}

```java
import org.wpilib.math.geometry.Pose3d;
import org.wpilib.telemetry.Telemetry;

/** Publishes every component's pose. Call it every loop from Robot.robotPeriodic(). */
public void publishComponents() {
  Telemetry.log("Robot/Components",
                new Pose3d[] {elevator.getPose3d(), arm.getPose3d(), turret.getPose3d()},
                Pose3d.struct);
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/RobotContainer.cpp (fragment)" %}

```cpp
#include <array>
#include <span>
#include <wpi/telemetry/Telemetry.hpp>

// In a method you call every loop from Robot::RobotPeriodic().
std::array<wpi::math::Pose3d, 3> components{m_elevator->GetPose3d(), m_arm->GetPose3d(),
                                            m_turret->GetPose3d()};
wpi::telemetry::Log("Robot/Components", std::span<const wpi::math::Pose3d>{components});
```

{% endcode %}
{% endtab %}
{% endtabs %}

With AdvantageKit, record the same array with `Logger.recordOutput("Robot/Components", poses)`.

**Check it:** start the simulation. `Robot/Components` shows in AdvantageScope's sidebar as an array of `Pose3d`, one for each component.
{% endstep %}

{% step %}

### Export the model

Export the robot from CAD without the moving parts as `model.glb`, and each moving part as its own file: `model_0.glb`, `model_1.glb`, and so on, in the order you publish their poses. Export every part where it is when the robot is at its starting position. [Converting Onshape & STEP Files to glTF](https://docs.advantagescope.org/more-features/custom-assets/gltf-convert) explains how.

Put them in a folder named `Robot_<name>`, such as `Robot_Dozer`, with a `config.json`, in AdvantageScope's assets folder (`App`/`AdvantageScope` > `Show Assets Folder`). `App`/`AdvantageScope` > `Use Custom Assets Folder` can load them from your robot project instead, so they are kept with your code.

```json
{
  "name": "Dozer",
  "rotations": [],
  "position": [0, 0, 0],
  "cameras": [],
  "components": [
    { "zeroedRotations": [], "zeroedPosition": [0, 0, 0] },
    { "zeroedRotations": [], "zeroedPosition": [0, 0, 0] },
    { "zeroedRotations": [], "zeroedPosition": [0, 0, 0] }
  ]
}
```

**Check it:** restart AdvantageScope. Your robot's name is in the 3D Field tab's robot list, and the robot model is drawn.
{% endstep %}

{% step %}

### Line each part up with its pose

AdvantageScope moves each component from where its `zeroedRotations` and `zeroedPosition` put it, by the pose you publish. Set them so that each part sits at the origin as YAMS's pose for it at zero expects:

| Component            | Zeroed at the origin                                                                       |
| -------------------- | ------------------------------------------------------------------------------------------ |
| An arm or pivot      | Its axis at the origin, pointing along +X at 0° (+Y in the YZ plane)                       |
| An elevator carriage | The carriage's reference point, the point you gave as its relative position, at the origin |
| A flywheel           | Its axle at the origin                                                                     |
| A part on another    | As for its own kind: its relative position is from its parent, not the robot               |

To set them:

1. Publish a zeroed robot pose every loop, such as `Telemetry.log("Robot/ZeroPose", Pose2d.ZERO, Pose2d.struct);`, select it as the robot's pose in AdvantageScope, and pick the "Axes" field, which shows the origin.
2. Adjust the model's `rotations`, then its `position`, until the robot is upright, facing +X, with its center on the origin and its wheels on the floor.
3. Publish an array of zeroed poses, one for each component, such as `Telemetry.log("Robot/ZeroComponents", new Pose3d[] {Pose3d.ZERO, Pose3d.ZERO, Pose3d.ZERO}, Pose3d.struct);`, and select it as the component poses.
4. For each component, adjust its `zeroedRotations`, then its `zeroedPosition`, until it sits at the origin as the table above says.
5. Publish the real poses, as in [Publish the poses](#publish-the-poses). Each part now moves with its mechanism.

**Check it:** with the zeroed poses, every part sits where the table above says.
{% endstep %}
{% endstepper %}

## Check it

Start the simulation, open AdvantageScope's 3D Field tab with your robot model, and move each mechanism. Each part should move with its mechanism and stay attached to the robot, and the arm should rise with the elevator's carriage.

## If it did not work

* **A part is drawn 90° off.** An arm's pose is turned by its angle from 0° pointing forward, so an arm that reads 0° straight down is drawn 90° off. Set the arm's angle so 0° is level, as YAMS's [arm feedforward expects](/documentation/understanding/arms), rather than turning the model to make up for it.
* **The robot or the parts float or sink.** AdvantageScope's robot origin is on the floor. Measure each mechanism's relative position from the floor, not the bellypan, and line the robot model up with the floor as in [Line each part up with its pose](#line-each-part-up-with-its-pose).
* **A part moves with another mechanism's pose.** The poses are in a different order from the components: AdvantageScope gives the first pose to `model_0.glb`, the second to `model_1.glb`, and so on.
* **A turret swings up instead of turning.** A new `MechanismPositionConfig` is in the XZ plane, so set `withMovementPlane(Plane.XY)` on the one you give a turret.
* **A part on another mechanism does not move with it.** It needs `withParent(...)`, such as an arm on an elevator's carriage. Without it, its relative position is from the robot, and it stays put as the carriage rises.
* **Every part is off by the same amount all the time.** It was exported away from its starting position. Export every part where it is at the robot's starting position.

## Read more

* Elevator stages: [How do I show an elevator's stages on a 3D robot model?](/documentation/how-to-simulation-and-logging/how-do-i-show-my-mechanisms-on-a-3d-robot-model/how-do-i-show-an-elevators-stages-on-a-3d-robot-model)
* Record a match and replay it: [How do I view my DataLog in AdvantageScope?](/documentation/how-to-simulation-and-logging/how-do-i-view-my-datalog-in-advantagescope)


# How do I show an elevator's stages on a 3D robot model?

Give an elevator's stages to YAMS, and publish a pose for every stage so each one moves on your robot model in AdvantageScope.

**Goal:** every stage of your elevator moves on the 3D robot model in AdvantageScope, not just the carriage.

This builds on [How do I show my mechanisms on a 3D robot model?](/documentation/how-to-simulation-and-logging/how-do-i-show-my-mechanisms-on-a-3d-robot-model): set that up first, with the elevator's `MechanismPositionConfig`, the model files and the component poses. An elevator with only a carriage needs nothing more than `getPose3d()`.

## Give YAMS the stages

An elevator with moving stages has a component for each stage. Give its `ElevatorConfig` the stages with [`withStages`](/documentation/reference/mechanism-configs/elevator-config#withstages): how far each moving stage travels relative to the stage below it, one height for each stage, the carriage last. The heights must add up to the elevator's maximum height, and without hard limits they set it.

YAMS only knows the carriage's height, `getHeight()`. Where each stage below it sits depends on how the elevator is rigged, so there are two methods. Both return a pose for each moving stage, in order from the stage nearest the fixed stage to the carriage, and the last pose is always the carriage, the same as `getPose3d()`. Each pose is the stage's bottom, moved straight along the elevator's angle from where the elevator is mounted.

## Cascading elevators

In a cascading elevator every stage is rigged to the one below it, so every stage moves at once. Use `getCascadePose3d()`: each stage moves its share of the carriage's height, its travel divided by the total travel, on top of the stage below it. With stages of 0.6 m, 0.6 m and 0.5 m, a carriage at 0.85 m, halfway, puts stage 1 at 0.3 m, stage 2 at 0.6 m and the carriage at 0.85 m.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-1fa51d934576b65aff277a50bda74bb81b85c89a%2Fhowto-elevator-cascade-stages.gif?alt=media" alt="Animation of a cascading elevator with a fixed stage, stage 1, stage 2 and a carriage, rising from 0 to 1.7 meters and back down. Every stage moves at the same time. A bar for each stage shows how far it has moved along the stage below it, and all three bars fill and empty together. At 0.9 meters stage 1 is at 0.32 meters, stage 2 at 0.64 meters and the carriage at 0.9 meters."><figcaption><p>A cascading elevator: every stage is always the same fraction of the way up the stage below it.</p></figcaption></figure>

## Continuous elevators

In a continuous elevator one rope runs through every stage, so the stages move one at a time. Which moves first depends on how it is rigged, and on friction and the weight it carries, so watch your elevator move and tell `getContinuousPose3d(carriageFirst)` which it is. Either way, the carriage is always at the elevator's height.

**Carriage first: `getContinuousPose3d(true)`.** The carriage rises the whole of its travel first, then the stage below it, and so on out to the stage nearest the fixed stage. Going down, the stage nearest the fixed stage lowers first, and the carriage last. With the same stages, a carriage at 0.85 m has risen its whole 0.5 m and stage 2 the other 0.35 m, so stage 1 is at 0 m, stage 2 at 0.35 m and the carriage at 0.85 m.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-4db28d408b10e94c1f929b8486c6f9ac2483afc9%2Fhowto-elevator-continuous-stages.gif?alt=media" alt="Animation of a continuous elevator with a fixed stage, stage 1, stage 2 and a carriage, rising from 0 to 1.7 meters and back down. The carriage rises its whole 0.5 meters first while the stages stay down, then stage 2 rises its 0.6 meters, then stage 1. Coming down, stage 1 lowers first, then stage 2, then the carriage."><figcaption><p>A continuous elevator that moves the carriage first: <code>getContinuousPose3d(true)</code>.</p></figcaption></figure>

**Carriage last: `getContinuousPose3d(false)`.** The stage nearest the fixed stage rises the whole of its travel first, then the next, and the carriage last. Going down, the carriage lowers first, and the stage nearest the fixed stage last. With the same stages, a carriage at 0.85 m has stage 1 at the top of its 0.6 m, and stage 2 has risen the other 0.25 m, so stage 1 is at 0.6 m, and stage 2 and the carriage are both at 0.85 m.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-6c7faf8282db4cf44f18bef5f296b706a7e2b1cc%2Fhowto-elevator-continuous-carriage-last-stages.gif?alt=media" alt="Animation of a continuous elevator with a fixed stage, stage 1, stage 2 and a carriage, rising from 0 to 1.7 meters and back down. Stage 1 rises its whole 0.6 meters first, carrying stage 2 and the carriage with it, then stage 2 rises its 0.6 meters, then the carriage its 0.5 meters. Coming down, the carriage lowers first, then stage 2, then stage 1."><figcaption><p>A continuous elevator that moves the carriage last: <code>getContinuousPose3d(false)</code>.</p></figcaption></figure>

## Publish the stages

Publish the stage poses in place of the carriage's `getPose3d()`, and put any mechanism mounted on the carriage after them:

{% tabs %}
{% tab title="Java" %}
{% code title="ElevatorSubsystem.java (fragment)" %}

```java
import static org.wpilib.units.Units.Meters;

import java.util.List;
import org.wpilib.math.geometry.Pose3d;

// Two stages that each travel 0.6 m, then a carriage that travels 0.5 m.
new ElevatorConfig()
    // ... the rest of the config
    .withStages(Meters.of(0.6), Meters.of(0.6), Meters.of(0.5));

/** Every stage's pose, for a cascading elevator: the first stage, the second, then the carriage. */
public List<Pose3d> getCascadePose3d() {
  return elevator.getCascadePose3d();
}

/** Every stage's pose, for a continuous elevator: true if the carriage moves first. */
public List<Pose3d> getContinuousPose3d(boolean carriageFirst) {
  return elevator.getContinuousPose3d(carriageFirst);
}
```

{% endcode %}

`elevator` inside `ElevatorSubsystem` is the YAMS `Elevator`. In Commands v3, put the two methods in your `ElevatorMechanism` instead.

{% code title="RobotContainer.java (fragment)" %}

```java
import java.util.ArrayList;
import java.util.List;
import org.wpilib.math.geometry.Pose3d;
import org.wpilib.telemetry.Telemetry;

// Every loop, where the elevator and the arm are both visible (see the 3D robot model page).
// The first stage, the second stage, then the carriage, which is elevator.getPose3d().
// A continuous elevator uses elevator.getContinuousPose3d(true), or (false) if its carriage moves last.
List<Pose3d> components = new ArrayList<>(elevator.getCascadePose3d());
components.add(arm.getPose3d());
Telemetry.log("Robot/Components", components.toArray(Pose3d[]::new), Pose3d.struct);
```

{% endcode %}

`elevator` and `arm` here are the subsystems, each with methods that return its mechanism's poses, as on the 3D robot model page.
{% endtab %}

{% tab title="C++" %}
{% code title="cpp/subsystems/ElevatorSubsystem.cpp (fragment)" %}

```cpp
#include <span>
#include <vector>

#include <wpi/telemetry/Telemetry.hpp>

// Two stages that each travel 0.6 m, then a carriage that travels 0.5 m.
m_elevatorConfig.WithStages(0.6_m, 0.6_m, 0.5_m);

// The first stage, the second stage, then the carriage, which is m_elevator->GetPose3d().
// A continuous elevator uses m_elevator->GetContinuousPose3d(true), or (false) if its carriage moves last.
std::vector<wpi::math::Pose3d> components = m_elevator->GetCascadePose3d();
components.push_back(m_arm->GetPose3d());
wpi::telemetry::Log("Robot/Components", std::span<const wpi::math::Pose3d>{components});
```

{% endcode %}
{% endtab %}
{% endtabs %}

Both need 2 or more stages, and throw an `ElevatorConfigurationException` without them: an elevator with only a carriage uses `getPose3d()`. In AdvantageScope each stage is a component, zeroed like the carriage: as it sits with the elevator all the way down.

## Line up the stages

Export each stage as its own component, as the robot model page's [Export the model](/documentation/how-to-simulation-and-logging/how-do-i-show-my-mechanisms-on-a-3d-robot-model#export-the-model) does for any part, in the order you publish the poses. Then zero each one as in [Line each part up with its pose](/documentation/how-to-simulation-and-logging/how-do-i-show-my-mechanisms-on-a-3d-robot-model#line-each-part-up-with-its-pose): a stage sits as it does with the elevator all the way down, moved by the same offset as the carriage.

## Check it

Start the simulation, open AdvantageScope's 3D Field tab with your robot model, and move the elevator from the bottom to the top. Every stage should move with the carriage the way your real elevator does: all together for a cascading elevator, one at a time for a continuous one. If the stages move in the wrong order, switch between `getCascadePose3d()` and `getContinuousPose3d(...)`, or flip `carriageFirst`.


# Live tuning

Live tuning lets you change gains, motion profiles and limits from a dashboard while the robot is enabled, and see the result straight away. It works over NetworkTables with AdvantageScope or Elastic.

This page shows how to turn it on, start it, change values and drive a motor at a voltage. [Tune a swerve drive](/documentation/how-to-tuning/live-tuning/swerve-drive) covers the `SwerveDrive` tuning command. For every key, its units and what to watch, see [Live tuning keys and units](/documentation/reference/keys-and-units).

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-afd9f41093fce666c67118c8c456f0c6125b0fb5%2Flive-tuning-loop.png?alt=media" alt="A loop: the dashboard sends tunable values under NT:/Tuning to the Live Tuning command, which applies them to the SmartMotorController every loop, and telemetry under NT:/Mechanisms flows back to the dashboard"><figcaption><p>Change a number, watch the graph, change it again.</p></figcaption></figure>

## Turn it on

**If you followed a tutorial, live tuning is already on.** It comes from this one line on the motor's `SmartMotorControllerConfig`:

```java
.withTelemetry("ArmMotor", TelemetryVerbosity.HIGH) // yams.core.telemetry.enums.TelemetryVerbosity
```

`TelemetryVerbosity.HIGH` publishes the tunable values and registers the `Live Tuning` command. That is all most robots need. Live tuning also needs `.withControlMode(ControlMode.CLOSED_LOOP)` on the same config, and a subsystem (Commands v2) or mechanism (Commands v3) on it, from `new SmartMotorControllerConfig(this)`, `withSubsystem(...)` or `withMechanism(...)`: the command is registered with it.

Only what the config has is published. The motion profile keys, `closedloop/motionprofile/...`, only exist when the config has a profile, such as `withTrapezoidalProfile(...)` or `withExponentialProfile(...)`, and `closedloop/feedforward/kG` only with a feedforward.

A fragment of a flywheel motor config, with the line in place:

<pre class="language-java" data-title="Fragment: a flywheel&#x27;s SmartMotorControllerConfig"><code class="lang-java">SmartMotorControllerConfig lowerFlyWheelConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withZeroPower(MotorMode.COAST)
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withMomentOfInertia(Inches.of(4), Pounds.of(2))
      .withClosedLoopController(1,
                                0,
                                0) // You generally do not want a profile because its not a position controlled loop.
      .withFeedforward(new SimpleMotorFeedforward(0, 0, 0)) // Helps track changing RPM goals
      .withMotorInverted(false)
<strong>      .withTelemetry("LowerFlyWheel", TelemetryVerbosity.HIGH);
</strong></code></pre>

| How the motor's telemetry is set up                                                                               | Live Tuning command                                       |
| ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
| `withTelemetry(name, TelemetryVerbosity.HIGH)`                                                                    | Registered for you                                        |
| `withTelemetry(name, telemetryConfig)` with a `SmartMotorControllerTelemetryConfig`                               | Registered for you                                        |
| A mechanism, such as an `Arm`, `Elevator`, `Pivot` or `FlyWheel`, with `withTelemetry(...)` on its own config too | Registered for you, for the mechanism's motor controllers |
| You call `setupTelemetry(NetworkTable, NetworkTable)` yourself (Java)                                             | Call `setupLiveTuning()` afterwards, see below            |
| C++ with `TelemetryVerbosity::HIGH` and a subsystem on the config                                                 | Registered for you when `SetupTelemetry()` runs           |

YAMS registers **one** `Live Tuning` command per subsystem (Commands v2) or mechanism (Commands v3). Every motor controller in that subsystem or mechanism joins the same command.

<details>

<summary>Setting up live tuning explicitly</summary>

If you set up telemetry yourself, the `Live Tuning` command is not registered for you. Call `setupLiveTuning()` on the config after the telemetry is set up:

```java
SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);
SmartMotorController motor = new TalonFXWrapper(armMotor, DCMotor.getKrakenX60(1), motorConfig);

motor.setupTelemetry(telemetryTable, tuningTable);
motorConfig.setupLiveTuning();
```

`setupLiveTuning()` does nothing when:

* the `SmartMotorController` has not set up its telemetry yet (that is what attaches the controller to the config), or
* the config has no subsystem (Commands v2) or mechanism (Commands v3).

Registering two different subsystem or mechanism instances with the same name throws an `IllegalStateException`. Give each one a unique name, for example `LeftTurret` and `RightTurret`.

In C++ there is no explicit call.

</details>

{% hint style="info" %}
Tuning an elevator, arm, pivot or flywheel? The [YAMS Live Tuner](/documentation/how-to-tuning/live-tuning/live-tuner) walks you through checking the mechanism, then sends setpoints and gains while you watch a graph.
{% endhint %}

{% hint style="info" %}
Using CTRE TalonFX or TalonFXS motors? Phoenix Tuner X can connect to your simulation too. See [TunerX in simulation](/documentation/how-to-tuning/live-tuning/tunerx-in-simulation).
{% endhint %}

## Use it

{% hint style="danger" %}
Like all tuning, live tuning can be **dangerous**. It's best to practice in simulation before the real robot.
{% endhint %}

The steps below are a first run with the arm from the [Arm tutorial](/documentation/tutorials/arm): `ArmSubsystem` in Commands v2 and C++, `ArmMechanism` in Commands v3. Its mechanism is named `Arm` and its motor `ArmMotor`, so:

* The `Live Tuning` command is at `NT:/Tuning/ArmSubsystem/Live Tuning` (Commands v2 and C++, the subsystem's name) or `NT:/Tuning/ArmMechanism/Live Tuning` (Commands v3, the `Mechanism`'s `getName()`).
* The values you type are under `NT:/Tuning/Arm/ArmMotor/`.
* The values you watch are under `NT:/Mechanisms/Arm/ArmMotor/`.

For your own robot, swap in your subsystem's class name and the names you gave `withTelemetry(...)`. [NetworkTables keys](/documentation/reference/keys-and-units#networktables-keys) explains each part.

{% stepper %}
{% step %}

### Run the code in simulation

Run the robot code in simulation and go through these steps there first. In simulation you are tuning the `withSimClosedLoopController(...)` and `withSimFeedforward(...)` gains: the simulation uses those when they are set, so the values the dashboard starts at, and the ones you find, belong in the `withSim...` lines.

**Check it:** the arm shows on the simulation's `Mechanism2d` and `NT:/Mechanisms/Arm/ArmMotor/mechanism/position` updates.
{% endstep %}

{% step %}

### Enable the robot

Set the robot to Teleoperated and enable it. Dashboard edits are only applied while the robot is enabled and the `Live Tuning` command is running.

**Check it:** the Driver Station (or the simulation GUI) shows the robot enabled in Teleoperated.
{% endstep %}

{% step %}

### Start the `Live Tuning` command

{% tabs %}
{% tab title="Commands v2" %}
It is a regular WPILib Commands v2 `Command` that requires the subsystem, published at `NT:/Tuning/ArmSubsystem/Live Tuning` with a `running` boolean:

* **Elastic:** drag `NT:/Tuning/ArmSubsystem/Live Tuning` onto your dashboard and press its button.
* **AdvantageScope:** turn on tuning mode (see [Change a value](#change-a-value)), then set `running` under `NT:/Tuning/ArmSubsystem/Live Tuning` to `true`. Set it to `false` to stop the command.

Or bind it to a controller button in `RobotContainer`:

```java
import yams.commands2.telemetry.SmartMotorControllerCommandRegistry;

// In configureBindings(), after the subsystem is created.
// getCommand returns an Optional<Command>: it is empty if no Live Tuning command was registered.
SmartMotorControllerCommandRegistry.getCommand("Live Tuning", arm)
    .ifPresent(liveTuning -> driverController.rightStick().toggleOnTrue(liveTuning));
```

Pressing the right stick starts it, and pressing it again stops it.
{% endtab %}

{% tab title="Commands v3" %}
Commands v3 commands are not dashboard widgets themselves, so YAMS publishes the command through `yams.commands3.telemetry.CommandTunable`. It shows up with a single `running` boolean at `NT:/Tuning/ArmMechanism/Live Tuning/running`, named after the Commands v3 `Mechanism`'s `getName()`, which is its class name unless you change it. In AdvantageScope, turn on tuning mode first.

* Set `running` to `true` to schedule the command on the default `Scheduler`.
* Set `running` to `false` to cancel it.
* `running` reads back whether the command is currently running.

The command requires the mechanism and runs a `while (true)` loop that applies the dashboard values and calls `coroutine.yield()` each loop.
{% endtab %}
{% endtabs %}

The command takes over from the default command and holds the setpoint the motor controller had. In the Arm tutorial that is the default command's 0 degrees, so the arm holds level.

{% hint style="info" %}
If the default command coasted the motor with a duty cycle or voltage, it stopped any closed loop that runs on the SystemCore, such as an [LQR](/documentation/understanding/lqr-controllers) or an [exponential profile](/documentation/understanding/exponential-profiles). The `Live Tuning` command starts it again.
{% endhint %}

**Check it:** in Elastic the button shows the command running, or `running` reads `true`.
{% endstep %}

{% step %}

### Graph what to watch

Graph these two together. They are what you compare after every change:

* `NT:/Mechanisms/Arm/ArmMotor/closedloop/setpoint/position`: where the arm is told to be.
* `NT:/Mechanisms/Arm/ArmMotor/mechanism/position`: where it is.

Add `NT:/Mechanisms/Arm/ArmMotor/motor/outputVoltage` too: it is how you find kG below.

{% hint style="warning" %}
**You type degrees, you read rotations.** A setpoint typed as `15` (degrees) is graphed as `0.0417` (rotations). To graph in degrees, see [See both in the same units with AdvantageScope](/documentation/reference/keys-and-units#see-both-in-the-same-units-with-advantagescope). All the units are in [Units: what you type and what you read](/documentation/reference/keys-and-units#units-what-you-type-and-what-you-read).
{% endhint %}

**Check it:** both lines are on the graph, on top of each other while the arm holds still.
{% endstep %}

{% step %}

### Change a value

The tunable values are under `NT:/Tuning/Arm/ArmMotor/`. Edit one, and it is applied on the next loop. A value is only applied when it changes, so typing the number that is already there does nothing.

{% tabs %}
{% tab title="AdvantageScope" %}
AdvantageScope only reads NetworkTables until you turn on **tuning mode**. Click the tuning mode button, the sliders icon beside the search box at the top of the sidebar. It is only shown while AdvantageScope is connected to a live robot or simulation.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-5d2d7d4cf4545361343b060411d31ceaa5402dcb%2Flive-tuning-ascope.png?alt=media" alt="Schematic of the AdvantageScope sidebar: step 1, click the tuning mode button, a sliders icon beside the search box; step 2, type a new value into a field under NT Tuning"><figcaption><p>Turn tuning mode on, then edit the fields under <code>NT:/Tuning</code>.</p></figcaption></figure>

With tuning mode on, the fields under `NT:/Tuning` can be edited in the sidebar. If typing a value does nothing, check this button first.
{% endtab %}

{% tab title="Elastic" %}
Drag a field from `NT:/Tuning/` onto the dashboard as a text or number widget and type the new value. Elastic can always write to NetworkTables, so there is nothing to turn on.
{% endtab %}
{% endtabs %}

Try it: type `10` into `NT:/Tuning/Arm/ArmMotor/closedloop/setpoint/position`.

**Check it:** `closedloop/setpoint/position` under `NT:/Mechanisms` jumps to about `0.028` (10 degrees in rotations), and `mechanism/position` follows it up. Type `0` to bring the arm back to level.
{% endstep %}

{% step %}

### Tune, then copy the values into your code

Follow the [Tuning order](#tuning-order) for your mechanism. Values typed on the dashboard are lost when the robot code restarts, so the last step is always to copy them into your config: in simulation into the `withSim...` lines, on the robot into `withClosedLoopController(...)` and `withFeedforward(...)`.

**Check it:** after restarting the robot code, the values under `NT:/Tuning` start at the ones you found.
{% endstep %}
{% endstepper %}

{% hint style="warning" %}
The `Live Tuning` command requires the subsystem or mechanism, so the controller, a default command, or any other trigger for that subsystem or mechanism can interrupt it. Dashboard edits stop being applied when it is interrupted. If your edits suddenly do nothing, check the command is still running.
{% endhint %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FqroomAx6l1Uwtolu2AxF%2Fnew_liveutinging.gif?alt=media&amp;token=58d9212c-3d43-4c5c-918c-e061f4b68a99" alt="Starting the Live Tuning command from the dashboard, then typing a new value into a tunable field and the mechanism responding"><figcaption><p>Starting the command and changing a value.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FQO5BiQ38yeh3YQOoRZxY%2FAScopeLiveTuningExample.gif?alt=media&amp;token=13d7b793-7c24-41ff-ba92-ecb691c10247" alt="AdvantageScope with tuning mode on: a gain is edited in the sidebar and the position graph changes while the robot is enabled"><figcaption><p>Tuning while the robot is enabled.</p></figcaption></figure>

## Tuning order

Tune the feedforward first, then the feedback, then the motion profile last, one value at a time. Each tutorial's Tune it step goes through it for its mechanism, with the keys to type and the graph to expect, in simulation:

* [Arm: Tune it](/documentation/tutorials/arm/tune)
* [Elevator: Tune it](/documentation/tutorials/elevator/tune)
* [Shooter/FlyWheels: Tune it](/documentation/tutorials/shooter-flywheels/tune)
* [Double FlyWheel: Tune it](/documentation/tutorials/double-flywheel/tune)
* [Swerve Drive: Tune it](/documentation/tutorials/swerve-drive/tune), then [Tune a swerve drive](/documentation/how-to-tuning/live-tuning/swerve-drive) on the real robot

[What to tune and what to watch](/documentation/reference/keys-and-units#what-to-tune-and-what-to-watch) lists the key to watch for each value. The WPILib docs explain what each gain does, with interactive simulations to practice on: [Introduction to PID](https://docs.wpilib.org/en/stable/docs/software/advanced-controls/introduction/introduction-to-pid.html) and [introduction to feedforward](https://docs.wpilib.org/en/stable/docs/software/advanced-controls/introduction/introduction-to-feedforward.html).

### What is different on a real robot

Use the same order on the robot, and start again from the tutorial's placeholder gains rather than trusting the simulation's: the simulation does not know about friction, cables, springs or a slightly wrong mass.

* **kS is real.** The simulation has almost no friction, so kS there is near 0. On the robot, find the voltage that just starts the mechanism moving with [Drive a motor at a voltage](#drive-a-motor-at-a-voltage).
* **Friction and binding make kG and kS harder to read.** Holding an arm or elevator with kP and reading the voltage lands anywhere between the voltage that moves it up and the one that lets it move down. Find both with a voltage: `kG = (up + down) / 2` and `kS = (up - down) / 2`.
* **Springs change kG.** A constant force spring on an elevator does part of the motor's job: see [Elevators with a constant force spring](#elevators-with-a-constant-force-spring).
* **The robot gains go in different lines.** Copy what you find on the robot into `withClosedLoopController(...)` and `withFeedforward(...)`, not the `withSim...` lines.

{% hint style="info" %}
**With an LQR**, tune the feedforward the same way, then the `closedloop/lqr/` fields where the steps say kP and kD. See [Tune it live](/documentation/understanding/lqr-controllers#tune-it-live).
{% endhint %}

## Drive a motor at a voltage

Sometimes you want no closed loop at all, just a voltage: to find the voltage that just starts a mechanism moving, to check that a positive voltage moves it the way you expect, or to see how fast it goes at 3 V. Every motor controller with `TelemetryVerbosity.HIGH` has two keys for this under `NT:/Tuning/<Mechanism>/<Motor>/`:

| You type           | Units   | What it is                                                                                                                                                                                                                                                                                                                              |
| ------------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `voltage/enabled`  | Boolean | Drive the motor at `voltage/setpoint` while `true`.                                                                                                                                                                                                                                                                                     |
| `voltage/setpoint` | Volts   | The voltage. Set back to `0` when `voltage/enabled` turns on, and sent to the motor and its [loosely coupled followers](/documentation/reference/editor/config/followers#withlooselycoupledfollowers) every loop while `voltage/enabled` is `true`, even when it has not changed. It is not applied while `voltage/enabled` is `false`. |

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-14e7e7e04ba0349f19b2cf0de53b6ee2b290b2c6%2Flive-tuning-voltage.png?alt=media" alt="Three steps. Closed loop: the leader and its loosely coupled follower hold the setpoint. Voltage on: both closed loops stop and the leader and the follower are driven at voltage/setpoint. Voltage off, or the Live Tuning command ends: the voltage goes to 0, both closed loops start again and the setpoint is sent again"><figcaption><p>The closed loop hands over to the voltage, and back again.</p></figcaption></figure>

{% stepper %}
{% step %}

### Start the `Live Tuning` command

As in [Use it](#use-it), for example from `NT:/Tuning/ArmSubsystem/Live Tuning`. The voltage is only applied while the command runs.

**Check it:** the command shows as running.
{% endstep %}

{% step %}

### Turn it on, then type a voltage

Set `voltage/enabled` to `true`. YAMS stops the closed loop and starts the motor at 0 V, with `voltage/setpoint` set back to `0`, so nothing moves until you type a voltage. A closed loop that runs on the SystemCore (with an [LQR](/documentation/understanding/lqr-controllers) or an [exponential profile](/documentation/understanding/exponential-profiles), or a velocity trapezoidal profile or another loop a Thrifty Nova can't run, and every closed loop on an A301), would replace the voltage on its next loop, which is why it is stopped.

Now type a small voltage, such as `1`, into `voltage/setpoint`, for example `NT:/Tuning/Arm/ArmMotor/voltage/setpoint`. It is sent every loop, so the motor keeps outputting it until you change it.

**Check it:** `motor/outputVoltage` under `NT:/Mechanisms` reads the voltage you typed.
{% endstep %}

{% step %}

### Watch it move

Graph `mechanism/velocity` (or `measurement/velocity`), `motor/outputVoltage` and `current/stator`. Raise or lower `voltage/setpoint` a little at a time.

**Check it:** a positive voltage moves the mechanism the way you expect, faster as you raise it.
{% endstep %}

{% step %}

### Turn it off

Set `voltage/enabled` to `false`. The voltage goes to 0, the closed loop starts again, and the setpoint it held before is sent again, so the mechanism goes back to it.

**Check it:** the mechanism returns to its setpoint and holds it.
{% endstep %}
{% endstepper %}

**Setpoints typed while the voltage is on are skipped.** A value typed into `closedloop/setpoint/position` or `closedloop/setpoint/velocity` then is not saved for later. Type it again once the voltage is off. Gains, limits and the other tunable values are applied as soon as you type them, even while the voltage is on.

**Loosely coupled followers** are driven at the same voltage, each with its own inversion, and their closed loops stop and start again with the leader's.

**When the `Live Tuning` command ends**, because you stopped it or another command for the subsystem or mechanism interrupted it, the voltage stops too. YAMS turns the voltage off, sets `voltage/enabled` back to `false` so the voltage is not applied again as soon as the command starts again, and the closed loop holds the setpoint.

{% hint style="warning" %}
A voltage has no speed limit and no motion profile. Start low, keep the mechanism away from its hard stops, and keep a hand on disable. On an arm or elevator, a voltage too small to hold it up lets it fall.
{% endhint %}

{% hint style="info" %}
Live tuning needs `ControlMode.CLOSED_LOOP`. The voltage keys are published at `TelemetryVerbosity.HIGH`, or with `withCustom(DoubleTelemetryField.TunableVoltage, true)` and `withCustom(BooleanTelemetryField.TunableVoltageEnabled, true)` on a `SmartMotorControllerTelemetryConfig`.
{% endhint %}

## Elevators with a constant force spring

A constant force spring pulls the carriage up with about the same force at every height. It does part of the motor's job, which changes what kG should be.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-a48aa36c10051855d3416f571dad7bf950e1a76a%2Flive-tuning-spring.png?alt=media" alt="Three elevators. With no spring the motor holds all of the weight and kG is large and positive. With a spring that matches the carriage weight, kG is close to zero. With a stronger spring the motor has to hold the carriage down and kG is negative"><figcaption><p>kG is what is left for the motor to do after the spring.</p></figcaption></figure>

Do not copy kG from a calculation or from the robot before the springs went on. Measure it. With a spring, holding the carriage with kP and reading the voltage (as the [Elevator tutorial's Tune it step](/documentation/tutorials/elevator/tune) does) can land anywhere between the up and down voltages, so use the two voltages below instead. The steps below type the voltages into `closedloop/feedforward/kG`; you can type them into [`voltage/setpoint`](#drive-a-motor-at-a-voltage) with `voltage/enabled` on instead, which takes the closed loop out of the way without zeroing any gains:

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-9e96c69c69e7f96bb1fc63ea7708d07d48621e13%2Flive-tuning-spring-test.png?alt=media" alt="A bar chart of two voltages: plus 1.1 volts just makes the carriage creep up and minus 0.5 volts just makes it creep down. kG is halfway between them, 0.3 volts. kS is half the gap between them, 0.8 volts"><figcaption><p>Two voltages give kG and kS. Example values.</p></figcaption></figure>

{% stepper %}
{% step %}

### Find the voltage that just moves it up

Put the carriage in the middle of the travel and start the `Live Tuning` command. Set kP, kI, kD and `closedloop/feedforward/kS` to 0. Now `closedloop/feedforward/kG` is the only voltage reaching the motor. Raise it slowly until the carriage just creeps upward, and write the value down.

**Check it:** at that voltage the carriage creeps up, and a little below it, it stays put.
{% endstep %}

{% step %}

### Find the voltage that just moves it down

Lower `closedloop/feedforward/kG` slowly until the carriage just creeps downward. This number is often negative on a sprung elevator. Write it down.

**Check it:** the down voltage is smaller than the up voltage.
{% endstep %}

{% step %}

### Work out kG and kS

`kG = (up + down) / 2` and `kS = (up - down) / 2`. Type them into `closedloop/feedforward/kG` and `closedloop/feedforward/kS`.

**Check it:** the carriage stays where you leave it in the middle of the travel.
{% endstep %}

{% step %}

### Check it at the bottom, middle and top

With only the feedforward, the carriage should stay where you leave it at every height. "Constant force" springs are not perfectly constant, and each stage of a multi stage elevator can have its own springs. If the carriage drifts at one end, use the kG that holds best in the range you care about most and let kP hold the rest.

**Check it:** the carriage holds at the heights you use most.
{% endstep %}

{% step %}

### Tune kV, kP and kD as usual

Follow the [Elevator tutorial's Tune it step](/documentation/tutorials/elevator/tune), including copying the values into your code at the end. The spring does not change them.

**Check it:** the carriage reaches its setpoints up and down, and the values are in your code.
{% endstep %}
{% endstepper %}

| With a spring, expect         | Why                                                                                                                               |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| kG near zero, or negative     | The spring carries the weight. If it is stronger than the carriage, the motor has to pull down.                                   |
| A larger kS                   | The spring and its spool add friction.                                                                                            |
| Different effort up and down  | Check `motor/outputVoltage` in both directions. Size the motion profile's `maxAcceleration` for the direction that needs more.    |
| A drift when the load changes | A spring sized for the empty carriage is too weak with a game piece, and the other way round. Tune for the load you hold longest. |

{% hint style="warning" %}
The simulation does not know about the spring: it models the full carriage weight from `ElevatorConfig.withCarriageWeight(...)`. Keep a separate kG for simulation with `withSimFeedforward(...)`, so a sprung robot's small kG does not make the simulated elevator sag.
{% endhint %}

## Troubleshooting

For problems outside live tuning, such as a mechanism that does not move at all or moves the wrong way, see [Troubleshooting](/documentation/tutorials/troubleshooting).

### Live tuning does nothing

| What you see                                                 | Likely cause                                                                                                                                          | Fix                                                                                                           |
| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| Typing a value changes nothing                               | The `Live Tuning` command is not running, or something interrupted it                                                                                 | Start it again. A button binding or default command for the same subsystem interrupts it.                     |
| Typing a value in AdvantageScope changes nothing             | Tuning mode is off                                                                                                                                    | Click the sliders icon at the top of the sidebar.                                                             |
| Typing the same setpoint again does nothing                  | Values are applied only when they change                                                                                                              | Type a different value, then the one you want.                                                                |
| There is no `NT:/Tuning/.../Live Tuning`                     | The motor is not at `TelemetryVerbosity.HIGH`, you set up telemetry yourself, or the config has no subsystem (Commands v2) or mechanism (Commands v3) | See [Turn it on](#turn-it-on).                                                                                |
| Live tuning throws "Live tuning does not work in OPEN\_LOOP" | The config is open loop                                                                                                                               | Add `.withControlMode(ControlMode.CLOSED_LOOP)`.                                                              |
| The gains reset when the code restarts                       | Dashboard values are not saved                                                                                                                        | Copy them into your config, the last step of each tutorial's Tune it step: see [Tuning order](#tuning-order). |
| The gains you found in simulation do nothing on the robot    | Simulation uses the `withSim...` gains                                                                                                                | Copy them into `withClosedLoopController(...)` and `withFeedforward(...)` too, then tune again on the robot.  |

When the gains are right but the mechanism still cannot reach its setpoint, see [When tuning does not help](/documentation/tutorials/troubleshooting#when-tuning-does-not-help).


# Tune a swerve drive

**Goal:** tune the swerve modules on the real robot, lifted on blocks, and then its auto-align, with the `SwerveDrive` tuning command.

To learn these steps first, go through the [Swerve Drive tutorial's Tune it step](/documentation/tutorials/swerve-drive/tune) in simulation. [Live tuning](/documentation/how-to-tuning/live-tuning) explains how live tuning works for any mechanism.

`SwerveDrive` has its own tuning command and its own keys. It can tune three things, one at a time:

| Mode                  | Turn it on with           | What it does                                                                       |
| --------------------- | ------------------------- | ---------------------------------------------------------------------------------- |
| Module azimuth motors | `modules/azimuth/enabled` | Turns every module to an angle you type.                                           |
| Module drive motors   | `modules/drive/enabled`   | Runs every module's drive motor at a velocity you type.                            |
| Auto-align            | `autoalign/enabled`       | Drives the robot to a pose you type, using the translation and rotation PID gains. |

| What                    | Where it is published           |
| ----------------------- | ------------------------------- |
| Values you type         | `NT:/Tuning/<name>/<key>`       |
| The tuning command      | `NT:/Tuning/<name>/Live Tuning` |
| The robot pose to watch | `NT:/Mechanisms/<name>/pose`    |

`<name>` is the name given to `SwerveDriveConfig.withTelemetry(name, ...)`. The keys are published at `TelemetryVerbosity.HIGH`.

Only one mode drives the robot at a time. Auto-align outranks drive tuning, and drive tuning outranks azimuth tuning: turning on a mode turns the ones below it back off, in NetworkTables too, so the dashboard shows what is actually running.

{% hint style="warning" %}
The tuning command is only published when both a translation and a rotation controller are set with `withTranslationController(...)` and `withRotationController(...)`. Nothing you type is applied unless the command is running.
{% endhint %}

## Start the tuning command

{% tabs %}
{% tab title="Commands v2" %}
In Elastic, drag `NT:/Tuning/<name>/Live Tuning` onto your dashboard and press its button. In AdvantageScope, turn on tuning mode and set `running` under `NT:/Tuning/<name>/Live Tuning` to `true`. You can also bind it to a controller button.
{% endtab %}

{% tab title="Commands v3" %}
The command is published through `CommandTunable`. Set `NT:/Tuning/<name>/Live Tuning/running` to `true` to start it and `false` to stop it.
{% endtab %}
{% endtabs %}

Starting the command resets the translation and rotation PID controllers. It requires the drive, so it pauses the default drive command while it runs. Stopping it turns every mode off, holds the wheels where they are, and brings the default drive command back.

## Tune the swerve modules

Tune the modules before auto-align: auto-align can only be as good as the modules under it. Do the azimuth motors first, so the wheels point where they are told while you tune the drive motors.

The module keys are shared. One value is applied to all four modules, which is what you want when the modules are built the same.

| What                     | Where it is published                                                             |
| ------------------------ | --------------------------------------------------------------------------------- |
| Values you type          | `NT:/Tuning/<name>/modules/azimuth/...` and `NT:/Tuning/<name>/modules/drive/...` |
| One motor's telemetry    | `NT:/Mechanisms/<name>/modules/<module>/<motor>/...`                              |
| All four modules at once | `NT:/Mechanisms/<name>/states/desired` and `states/current`                       |

`<module>` and `<motor>` are the names given to the module's and the motor's `withTelemetry(...)`. In AdvantageScope, drag `states/desired` and `states/current` onto a **Swerve** tab to see every module's target and actual state together.

{% hint style="warning" %}
Always start on the real robot with it lifted on blocks, and every wheel clear of the blocks and of the ground, for the azimuth and drive steps.
{% endhint %}

{% hint style="info" %}
**Practice in simulation first.** The [Swerve Drive tutorial's Tune it step](/documentation/tutorials/swerve-drive/tune) goes through these steps in simulation. Gains found there cannot be relied on for the real modules: tune again on the lifted robot, as on this page, before the wheels touch the ground.
{% endhint %}

### Azimuth motors

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-dca0a83473554d506a4b0357150ac90d3e78d92a%2Flive-tuning-swerve-azimuth.gif?alt=media" alt="Animation: with feedback/p too low the modules turn slowly and stop short of 90 degrees, with it too high they overshoot and shake, and with a little less p plus some d they turn quickly and settle"><figcaption><p>What each azimuth gain change looks like.</p></figcaption></figure>

| You type (`NT:/Tuning/<name>/`)           | Units             | What it is                                                                                                                             |
| ----------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `modules/azimuth/enabled`                 | Boolean           | Hold the angle while `true`.                                                                                                           |
| `modules/azimuth/angle`                   | Degrees           | Target angle for every module.                                                                                                         |
| `modules/azimuth/feedback/p`, `i`, `d`    | PID gains         | Azimuth motor feedback gains.                                                                                                          |
| `modules/azimuth/feedforward/s`, `v`, `a` | Feedforward gains | Azimuth motor kS, kV, kA.                                                                                                              |
| `modules/azimuth/voltage/enabled`         | Boolean           | Turn the azimuth motors at `voltage/setpoint` instead of holding the angle. See [Characterize the modules](#characterize-the-modules). |
| `modules/azimuth/voltage/setpoint`        | Volts             | Voltage for every azimuth motor.                                                                                                       |

Watch one azimuth motor's `mechanism/position` against its `closedloop/setpoint/position`, or the module arrows on the Swerve tab.

{% stepper %}
{% step %}

### Start the tuning command and turn the mode on

Start `NT:/Tuning/<name>/Live Tuning`, type `0` into `modules/azimuth/angle`, then set `modules/azimuth/enabled` to `true`. The drive motors are held at 0, so the wheels only turn in place.

**Check it:** every wheel points straight ahead and does not spin.
{% endstep %}

{% step %}

### Step the angle

Type `90` into `NT:/Tuning/<name>/modules/azimuth/angle`, then `0`, and keep switching. That key is the setpoint angle for every azimuth motor, in degrees. Each change is a step you can judge the gains by.

**Check it:** every module turns when you change the angle.
{% endstep %}

{% step %}

### Raise `feedback/p`

Raise it until the modules snap to the angle quickly. If they stop short or turn lazily, it is too low. If they overshoot and shake, it is too high: back it off.

**Check it:** the modules reach 90° quickly and stop without shaking.
{% endstep %}

{% step %}

### Add `feedback/d` if it still overshoots

A small amount takes out the last of the overshoot. Leave `feedback/i` at 0.

**Check it:** the modules settle on the angle without swinging past it.
{% endstep %}

{% step %}

### Add `feedforward/s` if the modules stop just short

If they settle a degree or two away from the angle, a little kS overcomes the friction.

**Check it:** `mechanism/position` settles on `closedloop/setpoint/position`.
{% endstep %}

{% step %}

### Save the gains and turn the mode off

Copy the gains into the azimuth motor's `withClosedLoopController(...)` and `withFeedforward(...)`. Values typed on the dashboard are lost when the robot code restarts. Set `modules/azimuth/enabled` to `false`. The modules stay at the last angle; they do not return to 0°.

**Check it:** after restarting the code, the azimuth gains under `NT:/Tuning/<name>/modules/azimuth/` show your values.
{% endstep %}
{% endstepper %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-c45593c1b3c3187b230346a730fede4eb1a82330%2Fmodule-azimuth-tuning.gif?alt=media" alt="Editing modules/azimuth/angle in AdvantageScope and every module turning to the new heading"><figcaption><p>In AdvantageScope: every module following <code>modules/azimuth/angle</code>.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-20ff062f8a719dfc3cca73b58fc5ebe1090a2505%2Fmodule-azimuth-tuning.png?alt=media" alt="The Tuning/swerve/modules tree in AdvantageScope with the azimuth and drive entries"><figcaption><p>The <code>Tuning/swerve/modules</code> tree.</p></figcaption></figure>

### Drive motors

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-2d9457f8a6326813f48d6aa7eecfa1aee742c1df%2Flive-tuning-swerve-drive.gif?alt=media" alt="Animation: with feedforward/v too low the wheel speed settles well below the 2 meters per second setpoint, raising it brings the speed up to the setpoint, and adding feedback/p makes it arrive sooner and hold"><figcaption><p>What each drive gain change looks like.</p></figcaption></figure>

| You type (`NT:/Tuning/<name>/`)         | Units             | What it is                                                                                                                                            |
| --------------------------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `modules/drive/enabled`                 | Boolean           | Run the drive motors while `true`.                                                                                                                    |
| `modules/drive/velocity`                | Meters per second | Wheel speed for every module.                                                                                                                         |
| `modules/drive/inplace`                 | Boolean           | `false`: every module points at 0° and the robot drives straight. `true`: the modules point tangent to the robot center and the robot spins in place. |
| `modules/drive/feedback/p`, `i`, `d`    | PID gains         | Drive motor feedback gains.                                                                                                                           |
| `modules/drive/feedforward/s`, `v`, `a` | Feedforward gains | Drive motor kS, kV, kA.                                                                                                                               |
| `modules/drive/voltage/enabled`         | Boolean           | Drive the drive motors at `voltage/setpoint` instead of the velocity. See [Characterize the modules](#characterize-the-modules).                      |
| `modules/drive/voltage/setpoint`        | Volts             | Voltage for every drive motor.                                                                                                                        |

Watch one drive motor's `measurement/velocity` against its `closedloop/setpoint/velocity`. The gains start at the first module's configured values.

{% stepper %}
{% step %}

### Start the tuning command and turn the mode on

Start `NT:/Tuning/<name>/Live Tuning`, type `0` into `modules/drive/velocity`, then set `modules/drive/enabled` to `true`.

**Check it:** the wheels point forward and do not spin.
{% endstep %}

{% step %}

### Zero the feedback

Set `modules/drive/feedback/p`, `i` and `d` to 0 so you can see what the feedforward does on its own.

**Check it:** the three feedback keys read 0.
{% endstep %}

{% step %}

### Find `feedforward/s`

Type a very small velocity, such as `0.1`, into `NT:/Tuning/<name>/modules/drive/velocity`. That key is the setpoint velocity for every drive motor, in meters per second. Raise `modules/drive/feedforward/s` until the wheels just start to turn, then back it off slightly.

**Check it:** at 0.1 m/s the wheels barely turn, or just stop.
{% endstep %}

{% step %}

### Find `feedforward/v`

Type a normal driving speed, such as `2`, into `NT:/Tuning/<name>/modules/drive/velocity`. Raise `modules/drive/feedforward/v` until the motor's `measurement/velocity` settles on its `closedloop/setpoint/velocity`. Check a second speed, such as `1` or `3`, in the same key: it should match there too.

**Check it:** at two speeds, `measurement/velocity` settles within a few percent of the setpoint.
{% endstep %}

{% step %}

### Add `feedback/p`

Raise `modules/drive/feedback/p` until the speed reaches the setpoint quickly and holds when the wheels are loaded. If the speed starts to buzz or oscillate, it is too high. `feedback/d` is rarely needed on a drive motor.

**Check it:** the speed reaches the setpoint quickly and does not buzz.
{% endstep %}

{% step %}

### Check it on the ground with `inplace`

Take the robot off the blocks and set `modules/drive/inplace` to `true`. The modules point tangent to the robot center, so the robot spins in place instead of crossing the field. A positive `modules/drive/velocity` spins it counter-clockwise.

**Check it:** the robot spins in place without wandering.
{% endstep %}

{% step %}

### Save the gains and turn the mode off

Copy the gains into the drive motor's `withClosedLoopController(...)` and `withFeedforward(...)`, then set `modules/drive/enabled` to `false`. The drive motors are commanded to 0 m/s once it is off.

**Check it:** after restarting the code, the drive gains under `NT:/Tuning/<name>/modules/drive/` show your values.
{% endstep %}
{% endstepper %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-84f88c473b8f34fbe4c7445b4c0bc87ae5061189%2Fmodule-drive-tuning.png?alt=media" alt="AdvantageScope with modules/drive/enabled on and every module driving at minus 3 meters per second"><figcaption><p>In AdvantageScope: every module driving at the typed velocity.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-a7184d0628b720694130955ea0b47f367d6c2da7%2Fmodule-drive-inplace.gif?alt=media" alt="With modules/drive/inplace true, raising the velocity spins the chassis faster in place"><figcaption><p>In AdvantageScope: spinning in place with <code>modules/drive/inplace</code>.</p></figcaption></figure>

## Characterize the modules

Instead of tuning by hand, the modules can be driven at a voltage and the gains worked out from how they move, the way WPILib's SysId does. While drive or azimuth tuning is on, set its `voltage/enabled` to `true` and type a voltage into `voltage/setpoint`:

* **Drive:** every drive motor runs at the voltage, without its closed loop. The wheels point forward, or around the robot with `modules/drive/inplace`, and are not optimized, so they always drive the same way.
* **Azimuth:** every azimuth motor turns at the voltage, without its closed loop, and the drive motors are held still.

A closed loop that runs on the SystemCore (with an [LQR](/documentation/understanding/lqr-controllers) or an [exponential profile](/documentation/understanding/exponential-profiles), or a velocity trapezoidal profile or another loop a Thrifty Nova can't run), would replace the voltage on its next loop, so YAMS stops it while the voltage is on and starts it again when the voltage turns off. The setpoint you typed is sent again then, or the wheels are held where they are if no mode is on.

{% hint style="info" %}
The YAGSL config generator's [Quick Start Guide](https://config.yagsl.com/guide) uses these keys in its Live mode: **Auto**, next to the gain fields, runs a slow ramp and a quick step each way, fits the feedforward, works out the feedback with an LQR, and fills in all six gains. The feedback depends on how often the closed loop runs, which each motor controller publishes as `closedloop/period` at `TelemetryVerbosity.HIGH`.
{% endhint %}

{% hint style="warning" %}
A voltage has no speed limit. On a real robot, do this on blocks with every wheel clear, and keep the voltage low.
{% endhint %}

## Tune auto-align

| You type (`NT:/Tuning/<name>/`)                | Units          | What it is                      |
| ---------------------------------------------- | -------------- | ------------------------------- |
| `autoalign/enabled`                            | Boolean        | Drive to the pose while `true`. |
| `autoalign/setpoint/x`, `autoalign/setpoint/y` | Meters         | Field relative target position. |
| `autoalign/setpoint/rot`                       | Degrees        | Field relative target heading.  |
| `autoalign/translation/p`, `i`, `d`            | PID on meters  | Translation gains.              |
| `autoalign/rotation/p`, `i`, `d`               | PID on radians | Rotation gains.                 |

The gains start at the values given to `withTranslationController(...)` and `withRotationController(...)`, not `0`.

{% stepper %}
{% step %}

### Start the tuning command

Start `NT:/Tuning/<name>/Live Tuning`, as in [Start the tuning command](#start-the-tuning-command), with the robot on the ground and room around it.

**Check it:** the command shows as running.
{% endstep %}

{% step %}

### Type the target pose

Type the target into `autoalign/setpoint/x`, `autoalign/setpoint/y` and `autoalign/setpoint/rot`, a short way from where the robot is.

**Check it:** the three values read back what you typed.
{% endstep %}

{% step %}

### Turn auto-align on

Set `autoalign/enabled` to `true`. The robot drives to the pose with the current gains.

**Check it:** on a 2D field, `NT:/Mechanisms/<name>/pose` moves to the target and stops.
{% endstep %}

{% step %}

### Change the gains

Change a gain and watch `NT:/Mechanisms/<name>/pose` on a 2D field. Changing a gain only resets that controller when the value actually changed. Raise `p` until the robot arrives quickly; if it overshoots or wobbles at the end, lower it or add a little `d`.

**Check it:** the robot settles on the target, as in the pictures below.
{% endstep %}

{% step %}

### Copy the gains and turn it off

Copy the gains you like into `withTranslationController(...)` and `withRotationController(...)`. Values typed on the dashboard are lost when the robot code restarts. Set `autoalign/enabled` back to `false` before handing control back to the driver.

**Check it:** after restarting the code, the `autoalign/translation/` and `autoalign/rotation/` gains show your values.
{% endstep %}
{% endstepper %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d1f3249ee41fe9dadd85cd9dfbd65ed302de2d7c%2Fautoalign-tuning-setup.png?alt=media" alt="AdvantageScope 2D field next to the Tuning/swerve/autoalign tree with the enabled, setpoint and gain entries"><figcaption><p>The <code>Tuning/swerve/autoalign</code> tree next to a 2D field.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-82515aa6e244cf8b462354eb5781e521467598fd%2Fautoalign-tuning.gif?alt=media" alt="The simulated robot drives to a target of x 12, y 4, rotation 90 while autoalign/enabled is true"><figcaption><p>Driving to <code>x=12</code>, <code>y=4</code>, <code>rot=90</code> in simulation.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-68175b678c5603979b97fe06c1a7ff89a1546e42%2Fautoalign-tuning-converged.png?alt=media" alt="The robot settled at X 11.975 m, Y 3.977 m, 90 degrees against a target of 12, 4, 90"><figcaption><p>Settled at the target pose.</p></figcaption></figure>

## Good to know

* **One mode at a time.** If more than one `enabled` key is `true`, YAMS keeps one and sets the others back to `false`. Auto-align wins over drive tuning, and drive tuning wins over azimuth tuning.
* **Every module shares the values.** The `modules/drive/*` and `modules/azimuth/*` keys apply to all modules at once. There are no per-module keys.
* **Module optimization still applies.** Both module modes go through `SwerveDrive.setSwerveModuleStates(...)`, so `withOptimization(true)` behaves the same as it does while driving.
* **No gyro needed in simulation.** The simulated drive tracks its own heading, so you can practice tuning the drive and azimuth motors before writing any gyro code. On a real robot, `SwerveDrive` throws an `IllegalStateException` if `withGyro(...)` was never called.


# YAMS Live Tuner

The [YAMS Live Tuner](https://tuning.yassrobotics.com/) is a web page that tunes an elevator, arm, pivot or flywheel through [live tuning](/documentation/how-to-tuning/live-tuning). It connects to the robot or simulation over NetworkTables, finds every YAMS motor controller with live tuning, and walks you through checking it before anything moves: a safety checklist, the motor inversion, and the range of motion. Then you send setpoints, drive with voltage and change gains while watching a graph.

It writes the same `NT:/Tuning` keys you would edit in AdvantageScope or Elastic, so everything on the [Live tuning](/documentation/how-to-tuning/live-tuning) page still applies.

{% hint style="warning" %}
The Live Tuner drives the motor at a voltage while it checks the inversion and the range of motion. That needs YAMS v2026.10.22 or newer, which adds `voltage/enabled` and `voltage/setpoint` to live tuning, and registers the `Live Tuning` command for mechanisms such as `Elevator` and `Arm`.
{% endhint %}

The screenshots below come from the YAMS Commands v3 examples running in simulation: the BroncBotz 2025 elevator and coral arm, the BroncBotz 2026 turret and kicker, and the `double_flywheel` example. Each motor is set up with `withTelemetry(name, TelemetryVerbosity.HIGH)` and its mechanism with `withTelemetry(...)` too, which is all live tuning needs.

{% hint style="danger" %}
Like all tuning, this can be **dangerous** on a real robot. Practice in simulation first. Press **Space** anywhere on the page, or the red **STOP** button at the top, to stop straight away, and keep a hand on the Driver Station's disable.
{% endhint %}

## Connect

Open [tuning.yassrobotics.com](https://tuning.yassrobotics.com/). Pick where the robot code is running, then press **Connect**:

* **Robot (team)**: the robot, from your team number.
* **Simulation**: robot code running in simulation on this computer.
* **Custom host**: any other address.

Once connected, the badge shows the host and the robot's mode. Enable the robot, in Teleop or Test, from the Driver Station before anything moves.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-a69700cfe54cd00a2f7ec8e514840bf783ce65f6%2Flive-tuner-connect.png?alt=media" alt="The Live Tuner header connected to a simulation on localhost, with the robot in Teleop and enabled"><figcaption><p>Connected to a simulation, with the robot enabled in Teleop.</p></figcaption></figure>

{% hint style="info" %}
No robot code to hand? Pick **Demo (no robot)**, or open [tuning.yassrobotics.com/?demo](https://tuning.yassrobotics.com/?demo), to try the Live Tuner on a robot simulated in the page.
{% endhint %}

{% hint style="info" %}
If your browser asks whether the page may connect to devices on your local network, allow it. The robot and the simulation are on your local network.
{% endhint %}

## Tune a mechanism

The strip at the top of the page shows the five steps: **Mechanism**, **Checklist**, **Inversions**, **Range** and **Live tune**. Only one step is shown at a time, next to the telemetry, and each one has to be finished, or skipped where that is allowed, before the next. While nothing is running, select a finished step in the strip to open it again.

The telemetry card shows the position, velocity, stator current and output voltage, with a graph of the measured value against the setpoint. Select the motor temperature under the graph to switch between °C and °F.

The steps are the same for every mechanism. Where an elevator, an arm or pivot, and a flywheel differ, the step says so, with a picture of each.

{% stepper %}
{% step %}

### Pick the mechanism

Choose the motor controller under **Telemetry name**, and the subsystem (Commands v2) or mechanism (Commands v3) under **Live Tuning command**. The lists are filled in from what the robot publishes under `NT:/Tuning`, so a motor controller only shows up once live tuning is [turned on](/documentation/how-to-tuning/live-tuning#turn-it-on) for it. Then set **Type** and press **Continue**:

* **Elevator:** setpoints are in meters.
* **Arm** for an arm that gravity pulls on, or **Pivot** for anything else that turns, such as a turret: setpoints are in degrees. For a pivot, tick **Continuous (no range of motion)** only if it can spin freely forever without wrapping wires.
* **Flywheel:** setpoints are in RPM. Leave **Second flywheel** at **None**, unless it is a [double flywheel](#double-flywheels).

Changing anything in this step resets every confirmation after it.

{% tabs %}
{% tab title="Elevator" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d6d16b6d2741cd557884a78785b5e96ab53e042a%2Flive-tuner-elevator-mechanism.png?alt=media" alt="The Mechanism step with Elevator/ElevatorMotor as the telemetry name, Elevator as the Live Tuning command and Elevator as the type, so setpoints are in meters, and a Continue button"><figcaption><p>The BroncBotz 2025 elevator: its motor, its mechanism's <code>Live Tuning</code> command, and the Elevator type.</p></figcaption></figure>
{% endtab %}

{% tab title="Arm and pivot" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-874e60856546bf17ebd1763f55d61b627475ff48%2Flive-tuner-arm-mechanism.png?alt=media" alt="The Mechanism step with CoralArm/CoralArmMotor as the telemetry name, CoralArm as the Live Tuning command and Arm as the type"><figcaption><p>The BroncBotz 2025 coral arm, as an Arm.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-e42dfe259e58089a1b371f2cd1c6b246820335ad%2Flive-tuner-pivot-mechanism.png?alt=media" alt="The Mechanism step with Turret/TurretMotor as the telemetry name, Turret as the Live Tuning command, Pivot as the type, and the Continuous (no range of motion) checkbox unticked"><figcaption><p>The BroncBotz 2026 turret, as a Pivot.</p></figcaption></figure>
{% endtab %}

{% tab title="Flywheel" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-f0e3feb014f6468b272766e89f6997d39d5e5b03%2Flive-tuner-flywheel-mechanism.png?alt=media" alt="The Mechanism step with Kicker/KickerMotor as the telemetry name, Kicker as the Live Tuning command, Flywheel as the type and None as the second flywheel"><figcaption><p>The BroncBotz 2026 kicker, as a Flywheel.</p></figcaption></figure>
{% endtab %}
{% endtabs %}

**Check it:** the Checklist step opens.
{% endstep %}

{% step %}

### Go through the pre-motion checklist

Tick every item, then press **Continue**. **Current trip (A)** stops Live Tuning if the stator current stays above it for 250 ms, which catches a stalled or jammed mechanism. You can change it later on the Settings card's **Tuner** tab. A flywheel's checklist has three items, the others four.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-c6d0b30fa66db70725386fb033ef1a51d9d411f3%2Flive-tuner-arm-checklist.png?alt=media" alt="The pre-motion checklist with all four items ticked, the current trip at 40 A, and Continue"><figcaption><p>Every item confirmed, with a 40 A current trip.</p></figcaption></figure>

**Check it:** the Inversions step opens.
{% endstep %}

{% step %}

### Check the inversions

This step drives the motor at a small voltage, with no closed loop, to check that a positive voltage moves the mechanism in its positive direction, or spins a flywheel forward, and that the reading goes the same way.

Read the warning, tick the confirmation, and press **Start voltage control**. If the inversions were already checked on this robot, **Skip (already checked)** goes straight to the next step.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-0e5566af8174df0e25e99c88936017db56274bd9%2Flive-tuner-elevator-inversions-confirm.png?alt=media" alt="The Check inversions step before it starts: a warning about driving open loop and followers fighting each other, the confirmation ticked, and the Start voltage control and Skip (already checked) buttons"><figcaption><p>Voltage control only starts once you confirm you are watching the mechanism.</p></figcaption></figure>

Drag the slider, or type a voltage under **Type a voltage** and press **Enter** or **Apply**. With **Back to 0 V on release** on, the slider goes back to 0 V when you let go; a typed voltage holds until you change it. Type 0, or press Space, to stop. The slider's ends start at −1 V and +1 V; select either end to change it.

Start with a fraction of a volt, at least 0.25 V, and raise it until the mechanism moves:

* **Elevator:** gravity pulls it down, so it can need more voltage to move up than down.
* **Arm:** near horizontal, gravity can be stronger than a small voltage, so try a little more voltage before changing an inversion.
* **Flywheel:** it keeps spinning after you let go, so set 0 V and let it stop before you drive it the other way.

{% tabs %}
{% tab title="Elevator" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-6b666ebdc3f76835b4e6b5f0ab5b62b1681a30a0%2Flive-tuner-elevator-inversions-up.png?alt=media" alt="Holding a typed 1 V: the applied voltage reads 1.00 V, Positive voltage moves up is ticked, and Finish check is enabled"><figcaption><p>At +1 V the position rises, so <strong>Positive voltage moves up</strong> is ticked.</p></figcaption></figure>
{% endtab %}

{% tab title="Arm and pivot" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-75ea7d48a77d973f564a0680727b36cf55dc5572%2Flive-tuner-arm-inversions-up.png?alt=media" alt="Holding a typed 1 V on the coral arm: the applied voltage reads 1.00 V, Positive voltage moves forward is ticked, and Finish check is enabled"><figcaption><p>At +1 V the angle rises, so <strong>Positive voltage moves forward</strong> is ticked.</p></figcaption></figure>
{% endtab %}

{% tab title="Flywheel" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-eceed60c105c09b128adaaf92a895ad1e291b639%2Flive-tuner-flywheel-inversions-up.png?alt=media" alt="Holding a typed 0.5 V on the kicker: the speed reads 80 RPM, Positive voltage moves forward is ticked, and Finish check is enabled"><figcaption><p>At +0.5 V the kicker spins forward.</p></figcaption></figure>
{% endtab %}
{% endtabs %}

One direction is enough. Once it is ticked, set the voltage back to 0 and press **Finish check**. If the reading goes the wrong way, the Live Tuner warns you. Stop and fix `withMotorInverted(...)`, or the encoder inversion, in the robot code before going on.

**Check it:** the direction is ticked, and the Range step opens.
{% endstep %}

{% step %}

### Range of motion

The Live Tuner only sends setpoints inside a range of motion you have set. A flywheel and a continuous pivot spin forever, so they have no range: Live tune opens next, and for a flywheel the speed slider's range caps it instead. For the others, there are two ways to set it:

* **Find ends by driving**: drive to each physical end of travel, and mark each end.
* **Enter range manually**: type each end, or move the mechanism by hand with the robot disabled and press **Use current position** under each end. Then press **Use this range**. Nothing is driven. The ends start at the robot's soft limits, if it publishes any.

To find the ends by driving, choose how to hold the mechanism between drives first. **Voltage, no closed loop** is safe before tuning: press **Use robot kG** so the **Gravity hold voltage** holds it up. On an arm, the gravity hold voltage is scaled by the cosine of the angle, like kG. **Closed loop (tuned gains)** holds it with the gains it has.

Press **Start verification**, then hold **Hold: drive up** or **Hold: drive down**. They drive at the ends of the **Voltage** slider, ±1 V to start with, and the slider drives at any voltage in between. Voltage is only applied while you hold a button or the slider. **When the voltage is let go** sets whether it cuts to 0 V, the default, or ramps down.

Press **Mark upper end here** and **Mark lower end here** at each end. A hard stop, the current trip, or a soft limit on the way marks that end for you. While it drives, the bar at the top of the window reads **VERIFYING RANGE**, and Space stops it. Once both ends are marked, press **Finish verification**. **Skip verification** goes on without a range, so only the robot's soft limits, if it has any, bound the travel.

{% tabs %}
{% tab title="Elevator" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-0cd569a3f78754e2fec54b2ba6f3b2e51994cfd9%2Flive-tuner-elevator-range-verified.png?alt=media" alt="The range step after driving: the upper end marked at 0.165 m, the lower end at 0.000 m marked by a hard stop, the Voltage slider from -1.00 V to 1.00 V, Cut to 0 V, and the gravity hold voltage set to the robot&#x27;s kG of 0.239 V"><figcaption><p>Driven up to 0.165 m and marked, then driven down until the hard stop marked 0 m.</p></figcaption></figure>
{% endtab %}

{% tab title="Arm and pivot" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b8410fd9418d2f895fc9a17cd77e4c142040b450%2Flive-tuner-arm-range-manual.png?alt=media" alt="The range step with Enter range manually chosen: the lower end set to -42.9° with Use current position, the upper end typed as 45, and Use this range enabled"><figcaption><p>The coral arm: the lower end from where it rests, the upper end typed.</p></figcaption></figure>
{% endtab %}
{% endtabs %}

**Check it:** both ends are marked, or the step was skipped, and the Live tune step opens.
{% endstep %}

{% step %}

### Live tune

Press **Start Live Tuning**. This starts the mechanism's `Live Tuning` command, so the setpoints and gains you send are applied every loop.

On the **Setpoints** tab, send a setpoint by typing it and pressing **Send**, or with the slider. With **Follow slider** off, the setpoint is sent when you let go. The graph shows the measured value against the setpoint, with the stator current, the current trip and the range.

* **Elevator, arm and pivot:** the buttons are **Lower**, **25%**, **Mid**, **75%** and **Upper**, and the slider's ends start at the range of motion. On an arm or pivot, the motion profile is typed in degrees per second, with the RPM that YAMS reads shown under each value.
* **Flywheel:** the buttons are **Idle (0)** and a quarter, half, three quarters and all of the slider's range. Speeds are limited to the slider's range, which starts at the ±4000 RPM safety default; select either end to change it.

Change a gain on the **Settings** card, described in [The Settings card](#the-settings-card), and send the setpoints again. Tune in the order of your mechanism's tutorial: the [Arm](/documentation/tutorials/arm/tune), [Elevator](/documentation/tutorials/elevator/tune), [Shooter/FlyWheels](/documentation/tutorials/shooter-flywheels/tune) and [Double FlyWheel](/documentation/tutorials/double-flywheel/tune) Tune it steps use the Live Tuner too. A pivot has no kG.

Turn on **Alternate setpoints** to switch between **Setpoint A** and **Setpoint B** every 5 seconds. Each step is the same, so you can change a gain and compare the next step with the last one.

{% tabs %}
{% tab title="Elevator" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-0fa0aaaa7b51794ed44deb188201e48fea55a764%2Flive-tuner-elevator.gif?alt=media" alt="The elevator stepping between its Mid and 25% setpoints, first with Max velocity cut from 1 m/s to 0.03 m/s, where it ramps slowly to each one, then with Max velocity put back to 1 m/s with its was button, where it gets there quickly"><figcaption><p>Max velocity cut to 0.03 m/s, then put back with <strong>was 1</strong>: the elevator crawls to each setpoint, then gets there quickly again.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-0cf43cbdb73fba2a9101be251776505f512ab01b%2Flive-tuner-elevator-gains.png?alt=media" alt="The Settings card&#x27;s Gains tab for the elevator: kP 33.966, kI 0, kD 0; kS 0.21471 V, kV 10.39, kA 0, kG 0.23861 V with a ± button; max velocity 1 m/s and max acceleration 0.5 m/s²"><figcaption><p>The elevator's gains and motion profile.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-a0dff228d3775cc07c73dd07bca05565295e8137%2Flive-tuner-elevator-alternate.png?alt=media" alt="Alternate setpoints on, switching between 0.045 m and 0.126 m: the graph shows the elevator stepping up and back down"><figcaption><p>Stepping between 0.045 m and 0.126 m.</p></figcaption></figure>
{% endtab %}

{% tab title="Arm and pivot" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-6eddbca2b2c97abcee48656845e74f78aa97bbc0%2Flive-tuner-arm.gif?alt=media" alt="The coral arm stepping between about -21° and 1°, first with Max velocity cut from 600 to 20 deg/s, where it moves slowly, then with Max velocity put back with its was button, where it moves quickly. Both times it settles a few degrees below each setpoint"><figcaption><p>The coral arm with Max velocity cut to 20 deg/s, then put back. Both times it settles a few degrees under each setpoint.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-f6a0a316f6ba1478294a290e769b902f6c88bcce%2Flive-tuner-pivot.gif?alt=media" alt="The turret stepping between -100° and 0°, first with Max velocity cut from 720 to 45 deg/s, where it turns slowly, then with Max velocity put back with its was button, where it turns quickly"><figcaption><p>The turret, a pivot, with Max velocity cut to 45 deg/s, then put back.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-56c5b4384561a24f8e54da9b0532c42d01e1c51c%2Flive-tuner-arm-gains.png?alt=media" alt="The coral arm&#x27;s Gains tab: kP 71.8502, kI 0, kD 0; kS 0.19214 V, kV 2.01765, kA 0, kG 0.023981 V; max velocity 600 deg/s, shown as 100 RPM, and max acceleration 300 deg/s², shown as 50 RPM/s"><figcaption><p>The coral arm's gains, with its motion profile in degrees.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-166363e49390d6f7b6f5806437b000a01b356c35%2Flive-tuner-arm-alternate.png?alt=media" alt="Alternate setpoints on, switching between -20.9° and 23°: the graph shows the coral arm stepping up and back down"><figcaption><p>The coral arm stepping between −20.9° and 23°.</p></figcaption></figure>
{% endtab %}

{% tab title="Flywheel" %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-e3ea90eccced29cbab659ee2da683d400c4434dd%2Flive-tuner-flywheel.gif?alt=media" alt="The kicker stepping between 1000 and 2000 RPM: with kP raised from 0 to 0.5 it runs at about 1150 RPM at the 1000 RPM setpoint, and with kP put back to 0 with its was button it runs at about 1340 RPM. At 2000 RPM it runs at about 1920 RPM both times"><figcaption><p>The kicker with kP raised to 0.5, then put back to 0. With kP, the speed at the 1000 RPM setpoint comes closer to it.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-9ba153b0fd3ef4cd367870721b884e1b3ed1d613%2Flive-tuner-flywheel-gains.png?alt=media" alt="The kicker&#x27;s Gains tab: kP 0, kI 0, kD 0; kS 0, kV 0.5, kA 0"><figcaption><p>The kicker's gains.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-9d6f6b38ffc9dab948bbd3dd95e2a5cd27b44cf0%2Flive-tuner-flywheel-alternate.png?alt=media" alt="Alternate setpoints on, switching between 1000 and 3000 RPM: the kicker runs at about 1340 and 1920 RPM"><figcaption><p>The kicker stepping between 1000 and 3000 RPM, with neither speed on its setpoint yet.</p></figcaption></figure>
{% endtab %}
{% endtabs %}

**Check it:** the measured value settles on each setpoint without overshooting.
{% endstep %}
{% endstepper %}

## Copy the gains into your code

Values sent from the Live Tuner are lost when the robot code restarts, so copy them from the **Gains** tab into the motor's `SmartMotorControllerConfig`:

| On the Gains tab                         | Goes in                                                                                                                                                                                       |
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| kP, kI, kD                               | `withClosedLoopController(kP, kI, kD)`                                                                                                                                                        |
| kS, kV, kA, and kG on an arm or elevator | `withFeedforward(new SimpleMotorFeedforward(kS, kV, kA))` for a flywheel or pivot, `new ArmFeedforward(kS, kG, kV, kA)` for an arm, `new ElevatorFeedforward(kS, kG, kV, kA)` for an elevator |
| Max velocity, max acceleration           | `withTrapezoidalProfile(maxVelocity, maxAcceleration)`                                                                                                                                        |

In simulation you tuned the simulation's gains: when the config has `withSimClosedLoopController(...)` and `withSimFeedforward(...)`, the simulation uses those, so copy the values into those lines instead, and tune again on the real robot for the others. Each tutorial shows the lines before and after: Copy the numbers into your code for the [Arm](/documentation/tutorials/arm/tune#copy-the-numbers-into-your-code), the [Elevator](/documentation/tutorials/elevator/tune#copy-the-numbers-into-your-code), the [Shooter](/documentation/tutorials/shooter-flywheels/tune#copy-the-numbers-into-your-code) and the [Double FlyWheel](/documentation/tutorials/double-flywheel/tune#copy-the-numbers-into-your-code).

## Double flywheels

A double flywheel is two YAMS flywheels in one subsystem, sharing its `Live Tuning` command, such as the [`double_flywheel` example](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands3/double_flywheel). Pick one wheel under **Telemetry name** and the other under **Second flywheel**, and both are tuned together.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-2a872e32132264f6344a68f3465d45bc7f9dcc23%2Flive-tuner-double-flywheel-mechanism.png?alt=media" alt="The Mechanism step with UpperFlyWheel/UpperMotor as the telemetry name, DoubleFlyWheelMechanism as the Live Tuning command, Flywheel as the type, and LowerFlyWheel/LowerMotor as the second flywheel"><figcaption><p>The <code>double_flywheel</code> example's upper and lower wheels.</p></figcaption></figure>

* **Inversions:** check one wheel at a time. The step passes once both wheels have.
* **Setpoints:** each wheel has its own box and slider. **Send both** sends both boxes. Turn on **Same speed for both** to move both sliders together. The buttons, such as **Both 2000 RPM**, and **Alternate setpoints** drive both wheels.
* **Wheel:** the **Wheel** picker on the telemetry card and the Settings card chooses which wheel's readings, gains and voltage drive you see. The graph plots both wheels, the second one dashed.
* **Copy these gains:** on the **Gains** tab, copies one wheel's feedback, feedforward and motion profile to the other, for wheels that are alike.
* **Safety:** the current trip watches each motor, and a stop spins both wheels down.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-979cf7a09497af006e940ce3bdbb9af596fd8e92%2Flive-tuner-double-flywheel.png?alt=media" alt="Live tune for the double flywheel: the upper wheel at 2416 RPM of a 3000 RPM setpoint and the lower wheel at 1611 RPM of 2000 RPM, sent together with Send both; the graph shows the upper wheel solid and the lower wheel dashed"><figcaption><p>3000 and 2000 RPM sent together. With the example's starting gains, both wheels settle short.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-7329811e9d71c30e2dca1d7060c104c279429133%2Flive-tuner-double-flywheel-settings.png?alt=media" alt="The Settings card with the Wheel picker on UpperFlyWheel: kP 0.002, kV 0.1, and a Copy these gains to LowerFlyWheel button"><figcaption><p>The upper wheel's gains, ready to copy to the lower wheel.</p></figcaption></figure>

\## The Settings card

The **Settings** card sits under the Live tune card. A line under its tabs says whether that tab's values live on the robot or only in this tuner.

| Tab         | Where it lives                   | What is on it                                                                                                                            |
| ----------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| **Gains**   | On the robot, under `NT:/Tuning` | Feedback, feedforward and motion profile                                                                                                 |
| **Limits**  | On the robot, under `NT:/Tuning` | Current limits, soft limits and the closed-loop ramp rate                                                                                |
| **Tuner**   | Only in this tuner               | The current trip, and the range of motion                                                                                                |
| **Voltage** | Only in this tuner               | What happens when you let go of the voltage, and the gravity hold voltage. Only shown while the Live tune card is on its **Voltage** tab |

Type a new value: it is applied when you press **Enter** or click away. **Esc** puts the old value back. [What to tune and what to watch](/documentation/reference/keys-and-units#what-to-tune-and-what-to-watch) lists what each gain does.

* **was …:** under a setting you changed, **was** shows its value before the change. Press it to put that value back, and press it again to go one change further back. When more than one value is saved, the count is shown, as in **was 160 (2)**.
* **Number fields:** a field only takes what fits it. Gains take up to 4 significant digits, and only kG can be negative. Current limits and the current trip are whole amps. A comma is read as a decimal point.
* **Values read from the robot** are shown as the robot sends them, so they can have more than 4 significant digits, such as kP 33.966.
* **±:** on a touch screen, a field that takes negative numbers, such as kG or a soft limit, shows a **±** button to its left while the field is focused, since a phone's number keypad has no minus key.
* **LQR mechanisms:** a mechanism with an [LQR](/documentation/understanding/lqr-controllers) shows the LQR's values on the **Gains** tab in place of kP, kI and kD: its tolerances, voltage effort, how far to trust the model and the encoder, and its maximum voltage. Each change rebuilds the LQR on the robot.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-8ebb7905c333c49cf755394b42289421c7a64464%2Flive-tuner-settings-limits.png?alt=media" alt="The Limits tab: On the robot. A stator limit of 40 A, soft limits of 0 m and 0 m, and a closed-loop ramp of 0 s"><figcaption><p>The <strong>Limits</strong> tab, for the elevator.</p></figcaption></figure>

On the **Tuner** tab, **Range of motion** changes the range set in the [Range of motion](#range-of-motion) step. Live Tuning stops if the mechanism leaves it, and setpoints are limited to it. It can go past what you verified, with a warning under the field, but that can drive the mechanism into a hard stop.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-c9a1d0835f171c5b54a51d13fd68c59a7660cf4c%2Flive-tuner-settings-tuner.png?alt=media" alt="The Tuner tab: Only in this tuner. A current trip of 40 A, and a range of motion from 0.004 m to 0.167 m"><figcaption><p>The <strong>Tuner</strong> tab, with the current trip and the range of motion.</p></figcaption></figure>

## Drive with voltage

The Live tune card's **Voltage** tab moves the mechanism with voltage instead of the closed loop, for example to feel how much voltage it takes, or to bring it somewhere by hand.

Hold **Hold: drive up** or **Hold: drive down**, or drag the **Voltage** slider. The buttons drive at the slider's ends, ±2 V to start with; select either end to change it. The drive stops at the ends of the range of motion, or the soft limits if there is none.

* **During Live Tuning:** with **Stay in voltage control** on, letting go keeps voltage control at the gravity hold voltage, or 0 V. Switch back to **Setpoints**, or turn it off, to hand back to the closed loop, which holds where the mechanism is. A flywheel goes back to the speed it had.
* **Without Live Tuning:** **Start voltage control** drives with voltage only, and the motor gets 0 V, or the gravity hold voltage, between presses.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-f8c4788a814a6e2d73840b8def4a96de070f4bee%2Flive-tuner-elevator-voltage.png?alt=media" alt="The Voltage tab during Live Tuning on the elevator: Hold: drive down (−2.00 V) and Hold: drive up (+2.00 V), the voltage slider at 0 V, Stay in voltage control on, In voltage control. The closed loop is off, and Stopped at the upper end of the verified range (0.165 m)"><figcaption><p>Driven up to the end of the range, where the drive stopped. The closed loop is off until you go back to <strong>Setpoints</strong>.</p></figcaption></figure>

The Settings card's **Voltage** tab sets **When the voltage is let go**, **Cut to 0 V** or **Ramp to 0 V**, and the **Gravity hold voltage**. On an elevator or arm, the gravity hold voltage is added to every drive, and an arm's is scaled by the cosine of its angle, like kG. **Use robot kG** copies kG into it, and **Set kG to this** sends it to the robot as kG.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-bbcc22470fe3d400444d33f91b9bc2f5015ad08d%2Flive-tuner-settings-voltage.png?alt=media" alt="The Settings card&#x27;s Voltage tab: When the voltage is let go, Cut to 0 V or Ramp to 0 V; the gravity hold voltage at 0 V with Use robot kG (0.24 V), Set kG to this and Set to 0 V"><figcaption><p>The <strong>Voltage</strong> tab, for the elevator.</p></figcaption></figure>

## If the mechanism is outside the range

If the mechanism is outside its range of motion, for example an arm that sagged below its lower end while disabled, the Live tune card says so before you start. Start Live Tuning anyway, then send a setpoint inside the range, or drive it back on the **Voltage** tab. Until it is back inside, the bar at the top of the window shows an **Out of range** warning, and moving further out stops Live Tuning.

## Stop

While anything runs, the bar at the top of the window says what is running and stays there as you scroll.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-ca001c832524f9d7b1f402230bc9b36d596b170a%2Flive-tuner-stop-bar.png?alt=media" alt="The bar at the top of the window: LIVE TUNING · Elevator/ElevatorMotor · Press Space anywhere to stop, and a red STOP button"><figcaption><p>The bar while Live Tuning runs on the elevator.</p></figcaption></figure>

Press **Space**, or **STOP**, at any time and from anywhere on the page. The Live Tuner sets the setpoint to where the mechanism is, or slows a flywheel down first, and then ends the `Live Tuning` command. The subsystem's default command, if it has one, takes over from there. Closing the page stops Live Tuning too, and so does disabling the robot from the Driver Station.


# TunerX in simulation

Phoenix Tuner X can connect to your simulation and show every simulated TalonFX and TalonFXS signal (position, velocity, closed loop error, applied voltage, current draw) as it would on real hardware. You can check gain behavior, confirm soft and hard limits trigger, and plot signals without a robot.

{% hint style="info" %}
This works because YAMS feeds its physics simulation results back to the simulated Talons through Phoenix's `getSimState()` API. It is specific to **CTRE TalonFX and TalonFXS** motors. REV SPARKs and the Thrifty Nova use WPILib's simulation, and are visible through AdvantageScope or Elastic over NetworkTables instead.
{% endhint %}

{% hint style="warning" %}
Changes you make in Tuner X are not YAMS [live tuning](/documentation/how-to-tuning/live-tuning), and are not saved to your YAMS config. YAMS applies its config to the Talon each time the code starts, which replaces the settings YAMS manages. Use Tuner X to watch the signals, and change gains, profiles and limits with live tuning, then copy them into your code.
{% endhint %}

{% stepper %}
{% step %}

### Run the simulation

Run your robot code in simulation, for example with **WPILib: Simulate Robot Code** in VS Code, or `./gradlew simulateJava` in a terminal.

**Check it:** the simulation GUI opens and the robot code prints no errors.
{% endstep %}

{% step %}

### Connect Tuner X to localhost

Open Phoenix Tuner X, then open the flyout menu in the upper left. Click the arrow next to the connection field and choose the **localhost** preset, which CTRE describes as the setting for simulation. See [Connecting Tuner X](https://v6.docs.ctr-electronics.com/en/stable/docs/tuner/connecting.html) in the Phoenix 6 docs.

**Check it:** the connection field says localhost, and Tuner X shows it is connected.
{% endstep %}

{% step %}

### Find your devices

Open the **Devices** page. Every simulated TalonFX and TalonFXS shows up with the CAN ID from your code, all on one CAN bus.

**Check it:** the list has one entry for each TalonFX or TalonFXS in your code. If it is empty, check the simulation is still running and the connection field says localhost.
{% endstep %}

{% step %}

### Plot the signals

Select a motor and plot its signals. Enable the robot and move the mechanism.

**Check it:** the position, velocity, applied voltage and current change as the simulated mechanism moves.
{% endstep %}
{% endstepper %}

{% hint style="warning" %}
In simulation every CAN device appears on the same CAN bus, so two simulated devices with the same CAN ID on different buses clash. Give them unique IDs.
{% endhint %}


# Organizing configs in constants

As your robot grows, managing configuration across multiple subsystems can become unwieldy. YAMS supports a clean pattern where you define all your configs in a centralized Constants file, then bind them to subsystems at construction time using `.withSubsystem()`.

## The problem

Without organization, each subsystem file contains its own configuration inline:

```java
// ArmSubsystem.java - config mixed with subsystem logic
public class ArmSubsystem extends SubsystemBase {
  private final Arm arm;
  
  public ArmSubsystem() {
    SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
        .withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4, 3)))
        .withClosedLoopController(5, 0, 0.1)
        .withFeedforward(new ArmFeedforward(0.1, 0.3, 0.5, 0.01))
        .withTrapezoidalProfile(RotationsPerSecond.of(1.0), RotationsPerSecondPerSecond.of(2.0));
    
    SmartMotorController smc = new TalonFXWrapper(new TalonFX(1, new CANBus(CANPort.CAN_S0)), DCMotor.getKrakenX60(1), smcConfig);
    
    ArmConfig armConfig = new ArmConfig()
        .withLength(Inches.of(18))
        // ... more config
    
    this.arm = new Arm(armConfig, smc);
  }
}
```

This approach has drawbacks:

* Configs are scattered across many files
* Hard to compare settings between mechanisms
* Tuning requires opening multiple files
* CAN IDs, motor types, and gear ratios are buried in subsystem code

## The solution: Centralized constants with `withSubsystem()`

YAMS configs can be created **without** a subsystem reference, then bound later using `.withSubsystem()`. This enables a clean separation:

{% hint style="info" %}
This page uses Commands v2 (`yams.commands2.config.SmartMotorControllerConfig`). With Commands v3, import `yams.commands3.config.SmartMotorControllerConfig` and bind it with `.withMechanism(this)` from your `Mechanism` class instead of `.withSubsystem(this)`. Everything else is the same.
{% endhint %}

```java
// Constants.java - ALL configs in one place
public final class Constants {
  
  public static final class ArmConstants {
    public static final int CAN_ID = 1;
    
    public static final SmartMotorControllerConfig SMC_CONFIG = 
        new SmartMotorControllerConfig()  // No subsystem yet!
            .withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4, 3)))
            .withClosedLoopController(5, 0, 0.1)
            .withFeedforward(new ArmFeedforward(0.1, 0.3, 0.5, 0.01))
            .withTrapezoidalProfile(RotationsPerSecond.of(1.0), RotationsPerSecondPerSecond.of(2.0))
            .withStartingPosition(Degrees.of(0));  // Where the arm is when the robot turns on
    
    public static final ArmConfig ARM_CONFIG = 
        new ArmConfig()  // No SmartMotorController yet!
            .withLength(Inches.of(18))
            .withHardLimits(Rotations.of(-0.3), Rotations.of(0.3))
            .withTelemetry("Arm", TelemetryVerbosity.HIGH);
  }
  
  public static final class ElevatorConstants {
    public static final int CAN_ID = 2;
    
    public static final SmartMotorControllerConfig SMC_CONFIG = 
        new SmartMotorControllerConfig()
            .withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4)))
            .withDrumRadius(Inches.of(0.75))
            .withClosedLoopController(10, 0, 0.5)
            .withFeedforward(new ElevatorFeedforward(0.1, 0.2, 0.5, 0.01))
            .withTrapezoidalProfile(MetersPerSecond.of(1.0), MetersPerSecondPerSecond.of(2.0))
            .withStartingPosition(Meters.of(0));  // Height when the robot turns on
    
    public static final ElevatorConfig ELEVATOR_CONFIG = 
        new ElevatorConfig()
            .withCarriageWeight(Pounds.of(10))
            .withHardLimits(Meters.of(0), Meters.of(1.5))
            .withTelemetry("Elevator", TelemetryVerbosity.HIGH);
  }
  
  public static final class ShooterConstants {
    public static final int CAN_ID = 3;
    
    public static final SmartMotorControllerConfig SMC_CONFIG = 
        new SmartMotorControllerConfig()
            .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
            .withClosedLoopController(0.5, 0, 0)
            .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0.01));
    
    public static final FlyWheelConfig FLYWHEEL_CONFIG = 
        new FlyWheelConfig()
            .withDiameter(Inches.of(4))
            .withTelemetry("Shooter", TelemetryVerbosity.HIGH);
  }
}
```

{% hint style="warning" %}
**Give arms and elevators a starting position.** The starting position lives on the `SmartMotorControllerConfig`, so it belongs in the constant too. Without `withStartingPosition(...)`, creating an `Arm` in simulation throws `Arm starting angle is empty`, and an `Elevator` throws `Starting height is not configured!`. It must also sit inside the mechanism's hard limits.
{% endhint %}

Then in your subsystems, use `.withSubsystem()` to bind the config:

```java
// ArmSubsystem.java - clean and focused
public class ArmSubsystem extends SubsystemBase {
  private final Arm arm;
  
  public ArmSubsystem() {
    // Copy the shared config, then bind the copy to this subsystem
    SmartMotorControllerConfig smcConfig = ArmConstants.SMC_CONFIG.clone()
        .withSubsystem(this);
    
    // Create SmartMotorController with the bound config
    SmartMotorController smc = new TalonFXWrapper(
        new TalonFX(ArmConstants.CAN_ID, new CANBus(CANPort.CAN_S0)), 
        DCMotor.getKrakenX60(1), 
        smcConfig
    );
    
    // Clone ArmConfig and pass smc to the mechanism constructor
    ArmConfig armConfig = ArmConstants.ARM_CONFIG.clone();
    
    this.arm = new Arm(armConfig, smc);
  }
  
  // Commands and business logic only, no config clutter!
  public Command goToAngle(Angle target) {
    return arm.runTo(target, Degrees.of(1));  // tolerance required
  }
}
```

## Benefits of this pattern

| Benefit                    | Description                                            |
| -------------------------- | ------------------------------------------------------ |
| **Single Source of Truth** | All CAN IDs, gear ratios, PID gains in one file        |
| **Easy Comparison**        | See all mechanism configs side-by-side                 |
| **Faster Tuning**          | Change gains without navigating subsystem files        |
| **Cleaner Subsystems**     | Subsystem classes focus on behavior, not configuration |
| **Reusable Configs**       | Share base configs between similar mechanisms          |

## Complete example: Constants file

```java
package first.robot;

import static org.wpilib.units.Units.*;

import org.wpilib.math.controller.ArmFeedforward;
import org.wpilib.math.controller.ElevatorFeedforward;
import org.wpilib.math.controller.SimpleMotorFeedforward;
import org.wpilib.math.system.DCMotor;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.core.gearing.GearBox;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.ArmConfig;
import yams.core.mechanisms.config.ElevatorConfig;
import yams.core.mechanisms.config.FlyWheelConfig;
import yams.core.motorcontrollers.enums.MotorMode;
import yams.core.telemetry.enums.TelemetryVerbosity;

public final class Constants {

  // ==================== ARM ====================
  public static final class ArmConstants {
    public static final int CAN_ID = 1;
    public static final DCMotor MOTOR = DCMotor.getKrakenX60(1);
    
    public static final SmartMotorControllerConfig SMC_CONFIG = 
        new SmartMotorControllerConfig()
            .withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4, 3)))
            .withClosedLoopController(5, 0, 0.1)
            .withFeedforward(new ArmFeedforward(0.1, 0.3, 0.5, 0.01))
            .withTrapezoidalProfile(RotationsPerSecond.of(1.0), RotationsPerSecondPerSecond.of(2.0))
            .withZeroPower(MotorMode.BRAKE)
            .withStartingPosition(Degrees.of(0)); // Required: Arm throws without it in simulation
    
    public static final ArmConfig ARM_CONFIG = 
        new ArmConfig()
            .withLength(Inches.of(18))
            .withHardLimits(Rotations.of(-0.3), Rotations.of(0.3))
            .withTelemetry("Arm", TelemetryVerbosity.HIGH);
  }

  // ==================== ELEVATOR ====================
  public static final class ElevatorConstants {
    public static final int CAN_ID = 2;
    public static final DCMotor MOTOR = DCMotor.getKrakenX60(1);
    
    public static final SmartMotorControllerConfig SMC_CONFIG = 
        new SmartMotorControllerConfig()
            .withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4)))
            .withDrumRadius(Inches.of(0.75))
            .withClosedLoopController(10, 0, 0.5)
            .withFeedforward(new ElevatorFeedforward(0.1, 0.2, 0.5, 0.01))
            .withTrapezoidalProfile(MetersPerSecond.of(1.0), MetersPerSecondPerSecond.of(2.0))
            .withZeroPower(MotorMode.BRAKE)
            .withStartingPosition(Meters.of(0)); // Required: Elevator throws without it in simulation
    
    public static final ElevatorConfig ELEVATOR_CONFIG = 
        new ElevatorConfig()
            .withCarriageWeight(Pounds.of(10))
            .withHardLimits(Meters.of(0), Meters.of(1.5))
            .withTelemetry("Elevator", TelemetryVerbosity.HIGH);
  }

  // ==================== SHOOTER ====================
  public static final class ShooterConstants {
    public static final int UPPER_CAN_ID = 3;
    public static final int LOWER_CAN_ID = 4;
    public static final DCMotor MOTOR = DCMotor.getKrakenX60(1);
    
    public static final SmartMotorControllerConfig SMC_CONFIG = 
        new SmartMotorControllerConfig()
            .withGearing(new MechanismGearing(GearBox.fromReductionStages(1)))
            .withClosedLoopController(0.5, 0, 0)
            .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0.01))
            .withZeroPower(MotorMode.COAST);
    
    public static final FlyWheelConfig FLYWHEEL_CONFIG = 
        new FlyWheelConfig()
            .withDiameter(Inches.of(4))
            .withTelemetry("Shooter", TelemetryVerbosity.HIGH);
  }
}
```

## Complete example: Subsystem using constants

```java
package first.robot.subsystems;

import static org.wpilib.units.Units.*;

import com.ctre.phoenix6.CANBus;
import com.ctre.phoenix6.hardware.TalonFX;
import org.wpilib.hardware.bus.CANPort;
import org.wpilib.units.measure.Angle;
import org.wpilib.command2.Command;
import org.wpilib.command2.SubsystemBase;
import first.robot.Constants.ArmConstants;
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.mechanisms.Arm;
import yams.core.mechanisms.config.ArmConfig;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.remote.TalonFXWrapper;

public class ArmSubsystem extends SubsystemBase {

  private final Arm arm;

  public ArmSubsystem() {
    // Step 1: Copy the shared SmartMotorControllerConfig and bind the copy to this subsystem
    SmartMotorControllerConfig smcConfig = ArmConstants.SMC_CONFIG.clone()
        .withSubsystem(this);

    // Step 2: Create SmartMotorController
    SmartMotorController smc = new TalonFXWrapper(
        new TalonFX(ArmConstants.CAN_ID, new CANBus(CANPort.CAN_S0)),
        ArmConstants.MOTOR,
        smcConfig
    );

    // Step 3: Clone ArmConfig and pass smc to the mechanism constructor
    ArmConfig armConfig = ArmConstants.ARM_CONFIG.clone();

    // Step 4: Create Arm mechanism
    this.arm = new Arm(armConfig, smc);
  }

  // ==================== COMMANDS ====================
  
  public Command runToAngle(Angle target) {
    return arm.runTo(target, Degrees.of(1));  // tolerance required
  }

  public Command holdAngle(Angle target) {
    return arm.run(target);
  }

  public Command stow() {
    return arm.runTo(Rotations.of(0), Degrees.of(1));  // tolerance required
  }

  // ==================== ACCESSORS ====================
  
  public Arm getArm() {
    return arm;
  }
}
```

## After live tuning: copy the values into Constants

[Live tuning](/documentation/how-to-tuning/live-tuning) changes gains while the robot runs, but the values are lost when the code restarts. With this pattern the gains live in `Constants`, so that is where you copy them:

```java
// Before
.withClosedLoopController(5, 0, 0.1)
.withFeedforward(new ArmFeedforward(0.1, 0.3, 0.5, 0.01))
// After: the kP, kI, kD and kS, kG, kV, kA you found
.withClosedLoopController(8, 0, 0.3)
.withFeedforward(new ArmFeedforward(0.12, 0.45, 0.5, 0.01))
```

If the config also has `withSimClosedLoopController(...)` or `withSimFeedforward(...)`, values found in simulation belong in those lines, because the simulation uses them.

## Organizing multiple config files

For larger robots, you may want to split configs into separate files:

```
first/robot/
├── Constants.java           // General constants (CAN IDs, ports)
├── configs/
│   ├── ArmConfigs.java      // Arm-related configs
│   ├── ElevatorConfigs.java // Elevator-related configs
│   ├── ShooterConfigs.java  // Shooter-related configs
│   └── DriveConfigs.java    // Swerve/drive configs
└── subsystems/
    ├── ArmSubsystem.java
    ├── ElevatorSubsystem.java
    └── ...
```

{% hint style="info" %}
**Important**: When using this pattern, you **must** call `.withSubsystem()` (`.withMechanism()` in Commands v3) before passing the `SmartMotorControllerConfig` to a `SmartMotorController`. It can only be called once per config and throws a `SmartMotorControllerConfigurationException` if a subsystem is already set, so call `.clone()` on the shared constant first and bind the copy. Never pass the same config instance to more than one `SmartMotorController`. `clone()` copies the settings but shares the gain objects (the PID controllers and feedforwards) with the original, so do not clone one constant for two motors that run their own closed loop. Give each mechanism its own constant. Pass the `SmartMotorController` directly as the second argument to the mechanism constructor (e.g., `new Arm(armConfig, smc)`).
{% endhint %}

## When not to use this pattern

This pattern adds a layer of indirection. For simple robots with 1-2 mechanisms, inline configuration may be clearer. Consider using centralized configs when:

* You have 3+ mechanisms
* Multiple team members tune different subsystems
* You want to quickly compare settings across mechanisms
* You're building a constants dashboard or config loader


# Arms

An `Arm` is a mechanism that swings about a pivot and has to hold itself up against gravity: an intake arm, a shooter hood that tilts, a climber hook.

## How an arm works

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-afeaf6518bd6bf813e17b35d6216581bc8c83757%2Fmech-arm.png?alt=media" alt="An arm drawn at 40 degrees above a level dashed line marked 0 degrees, with straight up marked 90 degrees. Its length, set by withLength, runs from the pivot to the end of the arm, and gravity pulls down on the end. Level is zero because gravity pulls hardest on a level arm and ArmFeedforward uses kG times the cosine of the angle."><figcaption><p>An arm is measured from level.</p></figcaption></figure>

Following WPILib, an arm is at 0° when it is parallel to the ground and 90° when it points straight up. Gravity pulls hardest on a level arm and not at all on a vertical one, and [`ArmFeedforward`](/documentation/reference/editor/config/feedforward#withfeedforward) uses that angle to work out how much voltage holds the arm still. So the arm's encoder has to read 0 when the arm is level.

If your mechanism does not need gravity accounted for, because it turns about a vertical axis or is balanced, use a [Pivot](/documentation/understanding/turrets-wrists) instead.

## Creating an arm

This is the shape of an arm class, not a complete file: the imports and the motor controller object (`spark`, a `SparkMax`) are left out. [Step 2 of the Arm tutorial](/documentation/tutorials/arm/mechanism) builds the complete file. The code is the same for Commands v2 and Commands v3 except for the package you import from and the class that owns the mechanism.

{% tabs %}
{% tab title="Commands v2" %}

```java
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.mechanisms.Arm;

public class ArmSubsystem extends SubsystemBase
{
  private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withClosedLoopController(4, 0, 0)
      .withFeedforward(new ArmFeedforward(0, 0.3, 1.2))
      .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
      .withSoftLimits(Degrees.of(-25), Degrees.of(105))
      .withStartingPosition(Degrees.of(0))
      .withMomentOfInertia(Feet.of(3), Pounds.of(4))
      .withStatorCurrentLimit(Amps.of(40))
      .withZeroPower(MotorMode.BRAKE)
      .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), motorConfig);
  private final ArmConfig config = new ArmConfig()
      .withLength(Feet.of(3))
      .withHardLimits(Degrees.of(-30), Degrees.of(110))
      .withTelemetry("Arm", TelemetryVerbosity.HIGH);
  private final Arm arm = new Arm(config, motor);

  @Override
  public void periodic()
  {
    arm.updateTelemetry(); // every loop
  }

  @Override
  public void simulationPeriodic()
  {
    arm.simIterate(); // every loop, in simulation
  }
}
```

`this` is the `Subsystem`. The scheduler calls `periodic()` and `simulationPeriodic()` for you.
{% endtab %}

{% tab title="Commands v3" %}

```java
import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.mechanisms.Arm;

public class ArmMechanism implements Mechanism
{
  private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withClosedLoopController(4, 0, 0)
      .withFeedforward(new ArmFeedforward(0, 0.3, 1.2))
      .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
      .withSoftLimits(Degrees.of(-25), Degrees.of(105))
      .withStartingPosition(Degrees.of(0))
      .withMomentOfInertia(Feet.of(3), Pounds.of(4))
      .withStatorCurrentLimit(Amps.of(40))
      .withZeroPower(MotorMode.BRAKE)
      .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), motorConfig);
  private final ArmConfig config = new ArmConfig()
      .withLength(Feet.of(3))
      .withHardLimits(Degrees.of(-30), Degrees.of(110))
      .withTelemetry("Arm", TelemetryVerbosity.HIGH);
  private final Arm arm = new Arm(config, motor);

  public void periodic()
  {
    arm.updateTelemetry(); // every loop
  }

  public void simulationPeriodic()
  {
    arm.simIterate(); // every loop, in simulation
  }
}
```

`this` is the Commands v3 `Mechanism`. A `Mechanism` has no periodic hook, so call `periodic()` yourself from `Robot.robotPeriodic()`, and run `simulationPeriodic()` in its own `Notifier`, started from `Robot.simulationInit()`. [Where the tutorials put things](/documentation/tutorials/project-setup#where-the-tutorials-put-things) shows both.
{% endtab %}
{% endtabs %}

The options in `motorConfig` are explained in [SmartMotorControllerConfig](/documentation/reference/editor/config), and the options in `config` in [ArmConfig](/documentation/reference/mechanism-configs/arm-config). The hard limits are the arm's physical stops, and the soft limits sit 5° inside them.

{% hint style="info" %}
The gains (`kP` of 4, `kG` of 0.3, `kV` of 1.2) and the profile are placeholders. In simulation the arm should move to its target and hold there, perhaps with some overshoot or sag. On your robot they will be wrong: [Step 5 of the Arm tutorial](/documentation/tutorials/arm/tune) finds the real ones.
{% endhint %}

## Controlling an arm

An arm takes `Angle` targets: `arm.setAngle(Degrees.of(45))` goes to 45° and holds it, `arm.runTo(Degrees.of(45), Degrees.of(2))` ends when it gets there, and `arm.getAngle()` reads where it is. [Controlling a mechanism](/documentation/reference/controlling-a-mechanism) lists every command, setpoint function and check, and [When mechanism commands end](/documentation/understanding/run-vs-runto) explains how they work with a default command.

## Absolute encoders

An arm that does not know where it is when the robot turns on has to be started in the same place every time. An absolute encoder removes that.

{% hint style="warning" %}
YAMS reads an absolute encoder through the motor controller, so it must be one that motor controller supports: see [Encoders](/documentation/reference/editor/config/encoders#withexternalencoder). For any other encoder, read it yourself and call `SmartMotorController.setEncoderPosition` once at startup.
{% endhint %}

[How do I use absolute encoders on my arm?](/documentation/how-to-mechanisms/how-do-i-use-absolute-encoders-on-my-arm) has a complete example for each vendor, including the [zero offset](/documentation/reference/editor/config/encoders#withexternalencoderzerooffset) that makes the encoder read 0 when the arm is level.

## Arms with a brake

Some arms have a brake module that holds the arm so the motor can stop working. That saves battery and keeps the motor cool on an arm that holds a heavy load for a long time.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d7fb19521fc68b4e57cbdde3bc3eb5b395e0410f%2Fmech-arm-brake.png?alt=media" alt="Four stages: when the motor drives, the brake lets go, by itself or on command; the arm moves with runTo; when the motor stops driving, the brake bites and holds the arm; then the motor output is zero, so it draws no current and makes no heat. A graph of motor current shows a spike while moving, a steady holding current until the brake bites, and then almost none, where an arm without a brake would draw holding current forever."><figcaption><p>The brake holds the arm once the motor stops driving it.</p></figcaption></figure>

{% hint style="info" %}
This is not `MotorMode.BRAKE`. [Brake mode](/documentation/reference/editor/config/motor-basics#withzeropower) is electrical: it resists movement but cannot hold an arm up. A brake module is mechanical, and can.
{% endhint %}

Most brake modules are **automatic**: they bite on their own when the motor stops driving and let go when it drives again, with nothing for your code to command. Some are **manual**, released by a solenoid or a servo that your code controls. Check which yours is, because it changes what you can do. YAMS has no brake class of its own for either kind.

### What to aim for

These are suggestions, not rules. With an automatic brake you do not control when it bites, so you cannot always follow them. Get as close as your brake allows.

* **Let the brake do the holding.** Once the arm has arrived, stop driving the motor so the brake takes the load. An arm that keeps holding its setpoint against the brake gains nothing from having one.
* **Avoid driving against the brake.** A motor pushing on an engaged brake heats up and wears the brake. With an automatic brake some of this is unavoidable at the start of each move, while the brake lets go.
* **Avoid a default command that holds an angle.** It keeps the motor driving, which is the opposite of resting. A default command that rests the motor is ideal.
* **Allow for the brake's timing.** A brake takes a moment to bite and to let go. Expect a small lurch or sag at each end of a move, and allow for it where you can.

### Resting the motor

Resting means an output of zero with the closed loop controller stopped. If the closed loop kept running it would go on driving the arm to its setpoint, against the brake.

The `set(0)` helper command does all of it. It stops the closed loop controller, holds the output at zero, and starts the closed loop again when another command takes over. So you can ignore the closed loop entirely: make `set(0)` the arm's default command, and the arm rests whenever nothing else is moving it.

### With an automatic brake

There is nothing to command on the brake. Move with `runTo`, which ends when the arm arrives, and the default command rests the motor so the brake bites:

{% tabs %}
{% tab title="Commands v2" %}

```java
// In the subsystem
public Command rest()
{
  return arm.set(0); // output 0, closed loop stopped; it restarts when another command takes over
}

public Command moveTo(Angle angle)
{
  return arm.runTo(angle, Degrees.of(2)); // driving releases the brake
}

// In RobotContainer
arm.setDefaultCommand(arm.rest());
```

{% endtab %}

{% tab title="Commands v3" %}

```java
// In the mechanism
public Command rest()
{
  return run(coroutine -> coroutine.await(arm.set(0))) // output 0, closed loop stopped
      .withPriority(Command.LOWEST_PRIORITY)           // so any other command can take over
      .named("Arm Rest");
}

public Command moveTo(Angle angle)
{
  return arm.runTo(angle, Degrees.of(2)); // driving releases the brake
}

// In Robot
arm.setDefaultCommand(arm.rest());
```

{% endtab %}
{% endtabs %}

### With a manual brake

If your code controls the brake, release it before the move and engage it after. The default command still rests the motor:

{% tabs %}
{% tab title="Commands v2" %}

```java
// brake is your own actuator: a Solenoid, a Servo, or anything with an on and off
public Command moveTo(Angle angle)
{
  return runOnce(() -> brake.set(false))         // release
      .andThen(arm.runTo(angle, Degrees.of(2)))  // move
      .finallyDo(() -> brake.set(true));         // engage, even if interrupted
}

// In RobotContainer
arm.setDefaultCommand(arm.rest());               // then the motor rests
```

{% endtab %}

{% tab title="Commands v3" %}

```java
// brake is your own actuator: a Solenoid, a Servo, or anything with an on and off
public Command moveTo(Angle angle)
{
  return run(coroutine -> {
    brake.set(false);                                  // release
    coroutine.await(arm.runTo(angle, Degrees.of(2)));  // move
    brake.set(true);                                   // engage
  }).whenCanceled(() -> brake.set(true)).named("Arm Move And Brake");
}

// In Robot
arm.setDefaultCommand(arm.rest());                     // then the motor rests
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Resting the motor with `set(0)` or `arm.setDutyCycleSetpoint(0)` stops a closed loop that runs on the SystemCore. The next move, with a command such as `runTo(...)` or a function such as `arm.setMechanismPositionSetpoint(...)`, starts it again for you. Only when you call `arm.getMotorController()` directly do you start and stop it yourself: see [Driving the motor controller yourself](/documentation/how-to-mechanisms/how-do-i-write-my-own-mechanism-command#driving-the-motor-controller-yourself).
{% endhint %}

Soft limits still apply while the arm moves, with either kind of brake. The brake does not replace them.

## Configuring and tuning an arm, step by step

Do the configuration steps first, in simulation, then tune the real arm with [live tuning](/documentation/how-to-tuning/live-tuning). Tuning something that is configured wrong wastes the time.

{% hint style="danger" %}
Like all tuning, this can be dangerous. Keep clear of the mechanism, start with low current limits and small moves, and practice in simulation first.
{% endhint %}

### Configure it

{% stepper %}
{% step %}

#### Set the gearing

Give the reduction from the motor to the arm's pivot with [`withGearing`](/documentation/reference/editor/config/gearing-and-units#withgearing). Check it by moving the arm a known angle by hand and reading `mechanism/position`.
{% endstep %}

{% step %}

#### Make up positive

Apply a small positive voltage with `setVoltage`. If the arm goes down, flip [`withMotorInverted`](/documentation/reference/editor/config/motor-basics#withmotorinverted). If the angle counts down while it goes up, an [encoder is backwards](/documentation/reference/editor/config/encoders#withencoderinverted).
{% endstep %}

{% step %}

#### Make level read zero

Hold the arm level. With an absolute encoder, set its [zero offset](/documentation/reference/editor/config/encoders#withexternalencoderzerooffset) so it reads 0 there. Without one, set a [starting position](/documentation/reference/editor/config/encoders#withstartingposition) for where the arm rests when the robot turns on.
{% endstep %}

{% step %}

#### Set the limits

Put [`withHardLimits`](/documentation/reference/mechanism-configs/shared-options#withhardlimits) where the stops are and [`withSoftLimits`](/documentation/reference/editor/config/limits-and-protection#withsoftlimits) a few degrees inside them.
{% endstep %}

{% step %}

#### Protect the motor

Set a low [stator current limit](/documentation/reference/editor/config/limits-and-protection#withstatorcurrentlimit-and-withsupplycurrentlimit) to start with, and `MotorMode.BRAKE`.
{% endstep %}

{% step %}

#### Describe it to the simulator

Set [`withLength`](/documentation/reference/mechanism-configs/arm-config#withlength) and [`withMomentOfInertia`](/documentation/reference/editor/config/simulation#withmomentofinertia), run it in simulation, and check the arm moves the way you expect before enabling the real one.
{% endstep %}
{% endstepper %}

### What is different when tuning an arm

[Step 5 of the Arm tutorial](/documentation/tutorials/arm/tune) walks through tuning an arm, and [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order) lists the order with the keys to watch. What sets an arm apart:

* **kG comes first, found with the arm level.** Gravity pulls hardest on a level arm, and `ArmFeedforward` scales kG by the cosine of the angle, so a kG that holds the arm level holds it everywhere.
* **Zero must really be level.** If the encoder is a few degrees off, kG is applied at the wrong strength and the arm sags at some angles and drifts up at others.
* **Straight up needs no kG.** Check the arm near vertical too, where kP alone holds it.
* **A game piece changes the gains.** Test it loaded. If it needs different gains, put them in a second [slot](/documentation/reference/editor/config/closed-loop-control#slots): [How do I control a mechanism that carries a game piece?](/documentation/how-to-mechanisms/how-do-i-control-a-mechanism-that-carries-a-game-piece) shows how.

### Tuning an arm with a brake

Tune the arm itself with the steps above first. If your brake can be held off, hold it off while you do. If it is automatic and cannot be, tune with it in place and expect the gains to carry a little of its drag.

Then look at how the arm and the brake work together. These are things to check and try, not steps that every brake allows:

* **Watch the start of a move.** A lurch or a spike in `current/stator` at the start is the motor pushing on a brake that has not let go yet. A slower start to the [profile](/documentation/reference/editor/config/motion-profiles#withtrapezoidalprofile) gives an automatic brake time to release. With a manual brake, release it a moment earlier.
* **Watch the end of a move.** If `mechanism/position` sags as the brake bites, the motor let go before the brake held. With a manual brake, engage it before resting the motor. With an automatic one, a sag of a known size can be allowed for in the setpoint.
* **Check the rest.** With the arm braked, `current/stator` should be close to zero. If it is not, something is still commanding the motor: look for a default command that holds a setpoint.
* **Widen the tolerance if it hunts.** A brake holds wherever it bites. If `runTo` takes a long time to finish, the last fraction of a degree is not worth the wait.
* **Keep an eye on `motor/temperature`** over a few minutes of use. If the motor still runs hot, it is working against the brake somewhere.

## ArmConfig options

Every `ArmConfig` option is on the [ArmConfig](/documentation/reference/mechanism-configs/arm-config) page under this one, with a graphic and an example for each. Options shared by every mechanism are in [Shared options](/documentation/reference/mechanism-configs/shared-options).

An `Arm` needs its length, hard limits and a starting position before it can be created in simulation: see [what simulation needs](/documentation/reference/mechanism-configs#what-simulation-needs).

## Code reference

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/ArmSubsystem.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/simple_robot-2027/src/main/java/first/robot/mechanisms/ArmMechanism.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/ExponentiallyProfiledArmSubsystem.java>" %}


# Elevators

An `Elevator` moves a carriage along a line: a lift, a telescoping climber, or a linear slide.

## How an elevator works

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-754589ffb47c57a8684ab7cacfb3b4cbfd7a1178%2Fmech-elevator-how.png?alt=media" alt="A motor drives a gearbox, set by withGearing, which turns a drum or sprocket, set by withDrumRadius, which pulls a carriage up a rail. One drum rotation lifts the carriage one circumference, so the height is the drum rotations times the circumference and you work in meters."><figcaption><p>A rotating motor becomes a distance.</p></figcaption></figure>

The motor turns a drum or sprocket through a gearbox, and the drum pulls the carriage. One rotation of the drum moves the carriage one circumference, so once YAMS knows the [drum size](/documentation/reference/editor/config/gearing-and-units#withmechanismcircumference) you can work in meters and never think about rotations. [How do I find my mechanism's circumference?](/documentation/how-to-motor-controllers-and-sensors/how-to-find-your-mechanism-circumference) covers measuring it.

A vertical elevator has to hold its carriage up, which is what the `kG` term of [`ElevatorFeedforward`](/documentation/reference/editor/config/feedforward#withfeedforward) is for.

## Creating an elevator

This is the shape of an elevator class, not a complete file: the imports and the motor controller object (`spark`, a `SparkMax`) are left out. [Step 2 of the Elevator tutorial](/documentation/tutorials/elevator/mechanism) builds the complete file. The code is the same for Commands v2 and Commands v3 except for the package you import from and the class that owns the mechanism.

{% tabs %}
{% tab title="Commands v2" %}

```java
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.mechanisms.Elevator;

public class ElevatorSubsystem extends SubsystemBase
{
  private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withDrumRadius(Inches.of(0.25), 22) // chain pitch and sprocket teeth
      .withClosedLoopController(4, 0, 0)
      .withFeedforward(new ElevatorFeedforward(0, 0.4, 3.5))
      .withTrapezoidalProfile(MetersPerSecond.of(1.5), MetersPerSecondPerSecond.of(3))
      .withSoftLimits(Meters.of(0), Meters.of(1.25))
      .withStartingPosition(Meters.of(0))
      .withStatorCurrentLimit(Amps.of(40))
      .withZeroPower(MotorMode.BRAKE)
      .withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), motorConfig);
  private final ElevatorConfig config = new ElevatorConfig()
      .withCarriageWeight(Pounds.of(16))
      .withHardLimits(Meters.of(0), Meters.of(1.3))
      .withTelemetry("Elevator", TelemetryVerbosity.HIGH);
  private final Elevator elevator = new Elevator(config, motor);

  @Override
  public void periodic()
  {
    elevator.updateTelemetry(); // every loop
  }

  @Override
  public void simulationPeriodic()
  {
    elevator.simIterate(); // every loop, in simulation
  }
}
```

`this` is the `Subsystem`. The scheduler calls `periodic()` and `simulationPeriodic()` for you.
{% endtab %}

{% tab title="Commands v3" %}

```java
import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.mechanisms.Elevator;

public class ElevatorMechanism implements Mechanism
{
  private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withDrumRadius(Inches.of(0.25), 22) // chain pitch and sprocket teeth
      .withClosedLoopController(4, 0, 0)
      .withFeedforward(new ElevatorFeedforward(0, 0.4, 3.5))
      .withTrapezoidalProfile(MetersPerSecond.of(1.5), MetersPerSecondPerSecond.of(3))
      .withSoftLimits(Meters.of(0), Meters.of(1.25))
      .withStartingPosition(Meters.of(0))
      .withStatorCurrentLimit(Amps.of(40))
      .withZeroPower(MotorMode.BRAKE)
      .withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), motorConfig);
  private final ElevatorConfig config = new ElevatorConfig()
      .withCarriageWeight(Pounds.of(16))
      .withHardLimits(Meters.of(0), Meters.of(1.3))
      .withTelemetry("Elevator", TelemetryVerbosity.HIGH);
  private final Elevator elevator = new Elevator(config, motor);

  public void periodic()
  {
    elevator.updateTelemetry(); // every loop
  }

  public void simulationPeriodic()
  {
    elevator.simIterate(); // every loop, in simulation
  }
}
```

`this` is the Commands v3 `Mechanism`. A `Mechanism` has no periodic hook, so call `periodic()` yourself from `Robot.robotPeriodic()`, and run `simulationPeriodic()` in its own `Notifier`, started from `Robot.simulationInit()`. [Where the tutorials put things](/documentation/tutorials/project-setup#where-the-tutorials-put-things) shows both.
{% endtab %}
{% endtabs %}

The options in `motorConfig` are explained in [SmartMotorControllerConfig](/documentation/reference/editor/config), and the options in `config` in [ElevatorConfig](/documentation/reference/mechanism-configs/elevator-config).

{% hint style="info" %}
The gains (`kP` of 4, `kG` of 0.4, `kV` of 3.5) and the profile are placeholders. In simulation the carriage should rise to its target and hold there, perhaps with some overshoot or sag. On your robot they will be wrong: the [Elevator tutorial](/documentation/tutorials/elevator) finds the real ones.
{% endhint %}

## Controlling an elevator

An elevator takes `Distance` targets: `elevator.setHeight(Meters.of(1.2))` goes to 1.2 m and holds it, `elevator.runTo(Meters.of(1.2), Centimeters.of(2))` ends when it gets there, and `elevator.getHeight()` reads where it is. [Controlling a mechanism](/documentation/reference/controlling-a-mechanism) lists every command, setpoint function and check, and [When mechanism commands end](/documentation/understanding/run-vs-runto) explains how they work with a default command.

## Which kind of elevator do you have?

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b5ab1af1111fb8bab3c1b5b6f4c0629130887712%2Fmech-elevator-kinds.png?alt=media" alt="Five kinds of elevator and what each needs. Drum, rope or cable on a spool: withDrumRadius with the radius. Chain or belt, a sprocket or pulley: withDrumRadius with the pitch and teeth. Rack and pinion, a gear on a toothed bar: withMechanismCircumference with the pinion pitch diameter times pi. Cascading, each stage lifts the next: withCascadingElevatorStages. Continuous, one rope through all stages: nothing extra."><figcaption><p>Five kinds of elevator and what each changes in the config.</p></figcaption></figure>

Two questions decide the config: how the motor moves the elevator, and how the stages are rigged. Answer both.

### How the motor moves it

{% tabs %}
{% tab title="Drum" %}
A rope, cable or strap winds onto a drum. Give the drum's radius, measured to the middle of the rope where it sits on the drum.

```java
.withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4)))
.withDrumRadius(Inches.of(0.75))
```

If the rope winds over itself, the radius grows as the elevator rises and the height reads short near the top. Use a drum wide enough for one layer, or measure the travel and work the circumference back from it.
{% endtab %}

{% tab title="Chain driven" %}
A sprocket drives a chain that carries the carriage. The chain moves one pitch for every tooth, so give the chain pitch and the sprocket's tooth count and YAMS works out the rest.

```java
.withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4)))
.withDrumRadius(Inches.of(0.25), 22) // #25 chain is 0.25 in pitch, #35 is 0.375 in; 22 teeth
```

A timing belt on a pulley works the same way: give the belt pitch and the pulley's tooth count.
{% endtab %}

{% tab title="Rack and pinion" %}
A pinion gear on the motor runs along a toothed rack. One turn of the pinion moves the carriage the pinion's pitch circumference.

```java
.withGearing(new MechanismGearing(GearBox.fromReductionStages(5)))
.withMechanismCircumference(Inches.of(1.5).times(Math.PI)) // pitch diameter x pi
```

Use the pitch diameter from the gear's datasheet, not the outside diameter. For a metric gear the pitch diameter is the module times the tooth count.

Most rack and pinion mechanisms are level linear slides. Tell the simulation there is no gravity to hold against, and expect to need [separate simulation gains](/documentation/understanding/simulation-only-pid-+-feedforward):

```java
new ElevatorConfig()
    .withAngle(Degrees.of(0))  // drawn level
    .withHorizontalElevator()  // no gravity in simulation
```

A level slide needs no `kG`, so its `ElevatorFeedforward` has `kG` of 0.
{% endtab %}
{% endtabs %}

### How the stages are rigged

{% tabs %}
{% tab title="One stage" %}
The carriage rides directly on the fixed frame. There is nothing more to set.
{% endtab %}

{% tab title="Cascading" %}
Each stage lifts the next one, so the carriage moves further than the part the motor pulls: twice as far with two moving stages, three times with three. Tell YAMS how many, and it divides the gearing to match.

```java
.withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4)))
.withDrumRadius(Inches.of(0.25), 22)
.withCascadingElevatorStages(2)
```

Call it after `withGearing`. See [`withCascadingElevatorStages`](/documentation/reference/editor/config/gearing-and-units#withcascadingelevatorstages). Every height you give and read is then the carriage's height.

To show each stage on an AdvantageScope robot model, also give the `ElevatorConfig` the stages with [`withStages`](/documentation/reference/mechanism-configs/elevator-config#withstages), and publish `elevator.getCascadePose3d()`: every stage moves at once, each by its share of the carriage's height.
{% endtab %}

{% tab title="Continuous" %}
One rope or belt runs through every stage. The stages may rise in any order, but the carriage always rises by the length of rope pulled, so a continuous elevator is configured like a single stage: nothing extra to set.

```java
.withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4)))
.withDrumRadius(Inches.of(0.75))
```

To show each stage on an AdvantageScope robot model, give the `ElevatorConfig` the stages with [`withStages`](/documentation/reference/mechanism-configs/elevator-config#withstages), and publish `elevator.getContinuousPose3d(carriageFirst)`. Pass `true` if the carriage rises the whole of its travel first, then the stage below it, and so on, or `false` if the stage nearest the fixed stage rises first and the carriage last. Watch your elevator move to see which it is.
{% endtab %}
{% endtabs %}

{% hint style="info" %}
Whatever the kind, check it the same way: command a move of a known distance and measure how far the carriage really went. If it is off by a constant factor, the circumference or the stage count is wrong.
{% endhint %}

### Elevators with a constant force spring

A spring that helps lift the carriage changes what `kG` should be. See [Elevators with a constant force spring](/documentation/how-to-tuning/live-tuning#elevators-with-a-constant-force-spring).

## Hard limits and soft limits

Hard limits are where the physical stops are, and the simulated elevator cannot pass them. Soft limits are where the motor controller keeps the real elevator. Set both, with the soft limits a little inside: see [`withHardLimits`](/documentation/reference/mechanism-configs/shared-options#withhardlimits).

## Configuring and tuning an elevator, step by step

Do the configuration steps first, in simulation, then tune the real elevator with [live tuning](/documentation/how-to-tuning/live-tuning). Tuning something that is configured wrong wastes the time.

{% hint style="danger" %}
Like all tuning, this can be dangerous. Keep clear of the mechanism, start with low current limits and small moves, and practice in simulation first.
{% endhint %}

### Configure it

{% stepper %}
{% step %}

#### Set the gearing

Give the reduction from the motor to the drum, sprocket or pinion with [`withGearing`](/documentation/reference/editor/config/gearing-and-units#withgearing).
{% endstep %}

{% step %}

#### Set how the motor moves it

Give the drum radius, the chain pitch and teeth, or the pinion's pitch circumference: see [how the motor moves it](#how-the-motor-moves-it) below.
{% endstep %}

{% step %}

#### Set how the stages are rigged

Add `withCascadingElevatorStages` for a cascading elevator and nothing for a single stage or continuous one: see [how the stages are rigged](#how-the-stages-are-rigged).
{% endstep %}

{% step %}

#### Make up positive

Apply a small positive voltage. If the carriage goes down, flip [`withMotorInverted`](/documentation/reference/editor/config/motor-basics#withmotorinverted).
{% endstep %}

{% step %}

#### Check the distance

Command a move of a known distance, such as 0.5 m, and measure the carriage with a tape. If it is off by a constant factor, fix the circumference or the stage count before going any further.
{% endstep %}

{% step %}

#### Set where it starts

Decide what height 0 means, usually the carriage fully down, and set [`withStartingPosition`](/documentation/reference/editor/config/encoders#withstartingposition) to where the carriage is when the robot turns on.
{% endstep %}

{% step %}

#### Set the limits

Put [`withHardLimits`](/documentation/reference/mechanism-configs/shared-options#withhardlimits) at the stops and [`withSoftLimits`](/documentation/reference/editor/config/limits-and-protection#withsoftlimits) a centimeter or two inside them.
{% endstep %}

{% step %}

#### Describe it to the simulator

Set [`withCarriageWeight`](/documentation/reference/mechanism-configs/elevator-config#withcarriageweight), and `withHorizontalElevator()` for a level slide.
{% endstep %}
{% endstepper %}

### What is different when tuning an elevator

The [Elevator tutorial](/documentation/tutorials/elevator/tune) walks through tuning an elevator, and [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order) lists the order with the keys to watch. What sets an elevator apart:

* **kG is the same at every height.** Gravity pulls the carriage with the same force wherever it is, unlike an arm.
* **Find kG and kS together from two voltages.** Set kP, kI, kD and kS to 0. Raise kG until the carriage just creeps up, then lower it until it just creeps down. kG is the average of the two, and kS is half the difference.
* **Check the hold at the bottom, the middle and the top,** then again with a game piece on the carriage.
* **Tune with small moves first,** a few centimeters at a time, until the motion profile is in.

### What changes for each kind

{% tabs %}
{% tab title="Rack and pinion" %}
A level rack and pinion slide has no weight to hold, so it tunes differently:

* **kG is 0.** Skip the two voltage test for kG. Find kS on its own: the voltage at which the slide just starts to move, in either direction.
* **kS matters more.** A slide's resistance is nearly all friction, so a good kS does most of the work at low speed.
* **Expect backlash.** The gap between the pinion and the rack means the carriage can move a little with the motor still. Do not raise kP to chase it, or the slide will buzz back and forth across the gap. Use a `runTo` tolerance wider than the backlash.
* **Simulate it level.** Use `withHorizontalElevator()`, and give it [its own simulation gains](/documentation/understanding/simulation-only-pid-+-feedforward), because the simulation has no friction or backlash.

A rack and pinion that lifts vertically is tuned like any other elevator, with kG.
{% endtab %}

{% tab title="Cascading" %}
Everything is measured at the carriage, which moves several times further than the stage the motor pulls:

* **Check the stage count first.** The distance check in the configuration steps is what catches a wrong `withCascadingElevatorStages`.
* **Expect a larger kG.** The motor lifts the carriage through a mechanical disadvantage, and lifts the moving stages as well, so it needs more voltage to hold than a single stage with the same carriage.
* **Profile limits are the carriage's.** A maximum velocity of 1.5 m/s is the carriage moving at 1.5 m/s. The first stage moves at a fraction of that.
* **Watch the current.** Because of the disadvantage, a cascading elevator draws more current for the same load. If it cannot reach the top, see [when tuning does not help](/documentation/tutorials/troubleshooting#when-tuning-does-not-help).
  {% endtab %}

{% tab title="Continuous" %}
A continuous elevator is configured like a single stage, but its stages rise in whatever order friction decides:

* **Check kG at several heights.** The weight being lifted changes as each stage starts to move. If the carriage holds at the bottom but drifts higher up, use the kG that holds best in the range you use most and let kP hold the rest.
* **Expect a bump** as each stage picks up or sets down. A little kD smooths it.
  {% endtab %}

{% tab title="With a constant force spring" %}
A constant force spring does part of the motor's job, so kG is whatever is left over. It can be small, zero, or negative when the spring is stronger than the carriage.

* **Measure kG, do not calculate it.** Use the two voltage test in the tuning steps. With a spring, the voltage that just moves the carriage down is often negative.
* **Check the hold at the bottom, middle and top.** The springs are not perfectly constant.
* **Give it simulation gains.** The simulation knows nothing about the spring, so the real gains will not hold the simulated carriage. Set [simulation only gains](/documentation/understanding/simulation-only-pid-+-feedforward) for it.
* **The spring does not change kV, kP or kD.**

[Elevators with a constant force spring](/documentation/how-to-tuning/live-tuning#elevators-with-a-constant-force-spring) walks through the measurement with graphics.
{% endtab %}
{% endtabs %}

## ElevatorConfig options

Every `ElevatorConfig` option is on the [ElevatorConfig](/documentation/reference/mechanism-configs/elevator-config) page under this one, with a graphic and an example for each. Options shared by every mechanism are in [Shared options](/documentation/reference/mechanism-configs/shared-options).

An `Elevator` needs its carriage weight, hard limits, a drum size and a starting position before it can be created in simulation: see [what simulation needs](/documentation/reference/mechanism-configs#what-simulation-needs).

## Code reference

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/ElevatorSubsystem.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/simple_robot-2027/src/main/java/first/robot/mechanisms/ElevatorMechanism.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/ExponentiallyProfiledElevatorSubsystem.java>" %}


# Turrets/Wrists

Turrets and wrists are both a `Pivot` in YAMS: a mechanism that turns to an angle. A `Pivot` is different from an `Arm` because it does not account for gravity.

## How a pivot works

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-c2b06d3aa0ed4a7f2b0c8e3b7fd5ec15c14acb6e%2Fmech-pivot-vs-arm.png?alt=media" alt="Two panels. An Arm accounts for gravity: it swings up and down, needs kG to hold and uses ArmFeedforward. A Pivot does not account for gravity: it is for a vertical axis or a balanced wrist, has no kG and uses SimpleMotorFeedforward."><figcaption><p>An Arm accounts for gravity. A Pivot does not.</p></figcaption></figure>

A pivot is controlled exactly like an arm, with one difference: a `Pivot` does not account for gravity. It has no `kG`, its simulation applies no gravity, and it uses [`SimpleMotorFeedforward`](/documentation/reference/editor/config/feedforward#withfeedforward) where an arm uses `ArmFeedforward`.

That is the right model for a turret, which turns about a vertical axis, and for a wrist that is balanced about its shaft: neither needs voltage just to stay where it is. It also makes a pivot simpler to tune.

If your mechanism needs voltage to hold itself up, it needs gravity accounted for: use an [Arm](/documentation/understanding/arms).

## Creating a pivot

This is the shape of a turret class, not a complete file: the imports and the motor controller object (`spark`, a `SparkMax`) are left out. The [Arm tutorial](/documentation/tutorials/arm/mechanism) builds a complete mechanism file the same way. The code is the same for Commands v2 and Commands v3 except for the package you import from and the class that owns the mechanism.

{% tabs %}
{% tab title="Commands v2" %}

```java
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.mechanisms.Pivot;

public class TurretSubsystem extends SubsystemBase
{
  private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withClosedLoopController(4, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.5, 0)) // kS, kV, kA: no kG on a pivot
      .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
      .withSoftLimits(Degrees.of(-170), Degrees.of(170))
      .withStartingPosition(Degrees.of(0))
      .withMomentOfInertia(Meters.of(0.25), Pounds.of(4))
      .withStatorCurrentLimit(Amps.of(40))
      .withZeroPower(MotorMode.BRAKE)
      .withTelemetry("TurretMotor", TelemetryVerbosity.HIGH);
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), motorConfig);
  private final PivotConfig config = new PivotConfig()
      .withHardLimits(Degrees.of(-180), Degrees.of(180))
      .withTelemetry("Turret", TelemetryVerbosity.HIGH);
  private final Pivot pivot = new Pivot(config, motor); // the YAMS Pivot inside the turret

  @Override
  public void periodic()
  {
    pivot.updateTelemetry(); // every loop
  }

  @Override
  public void simulationPeriodic()
  {
    pivot.simIterate(); // every loop, in simulation
  }
}
```

`this` is the `Subsystem`. The scheduler calls `periodic()` and `simulationPeriodic()` for you.
{% endtab %}

{% tab title="Commands v3" %}

```java
import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.mechanisms.Pivot;

public class TurretMechanism implements Mechanism
{
  private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withClosedLoopController(4, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.5, 0)) // kS, kV, kA: no kG on a pivot
      .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
      .withSoftLimits(Degrees.of(-170), Degrees.of(170))
      .withStartingPosition(Degrees.of(0))
      .withMomentOfInertia(Meters.of(0.25), Pounds.of(4))
      .withStatorCurrentLimit(Amps.of(40))
      .withZeroPower(MotorMode.BRAKE)
      .withTelemetry("TurretMotor", TelemetryVerbosity.HIGH);
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), motorConfig);
  private final PivotConfig config = new PivotConfig()
      .withHardLimits(Degrees.of(-180), Degrees.of(180))
      .withTelemetry("Turret", TelemetryVerbosity.HIGH);
  private final Pivot pivot = new Pivot(config, motor); // the YAMS Pivot inside the turret

  public void periodic()
  {
    pivot.updateTelemetry(); // every loop
  }

  public void simulationPeriodic()
  {
    pivot.simIterate(); // every loop, in simulation
  }
}
```

`this` is the Commands v3 `Mechanism`. A `Mechanism` has no periodic hook, so call `periodic()` yourself from `Robot.robotPeriodic()`, and run `simulationPeriodic()` in its own `Notifier`, started from `Robot.simulationInit()`. [Where the tutorials put things](/documentation/tutorials/project-setup#where-the-tutorials-put-things) shows both.
{% endtab %}
{% endtabs %}

The options in `motorConfig` are explained in [SmartMotorControllerConfig](/documentation/reference/editor/config), and the options in `config` in [PivotConfig](/documentation/reference/mechanism-configs/pivot-config).

In the rest of your code, `turret` is the `TurretSubsystem` (or `TurretMechanism`), and `pivot` is the YAMS `Pivot` inside it.

{% hint style="info" %}
The gains (`kP` of 4, `kS` of 0.1, `kV` of 0.5) and the profile are placeholders. In simulation the turret should turn to its target and stop there, perhaps with some overshoot. On your robot they will be wrong: tune them as below.
{% endhint %}

## Controlling a pivot

A pivot takes `Angle` targets: `pivot.setAngle(Degrees.of(90))` goes to 90° and holds it, `pivot.runTo(Degrees.of(90), Degrees.of(1))` ends when it gets there, and `pivot.getAngle()` reads where it is. [Controlling a mechanism](/documentation/reference/controlling-a-mechanism) lists every command, setpoint function and check, and [When mechanism commands end](/documentation/understanding/run-vs-runto) explains how they work with a default command.

To track a moving target, give `setAngle` (or `run`) a `Supplier<Angle>`: it follows the supplier every loop and never ends. `runTo` with a supplier also follows it, but ends as soon as the turret catches up, so it is not for tracking.

## Turret or wrist?

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-ca36ee521512121a9e78319a1cf62adb73dcb685%2Fmech-pivot-kinds.png?alt=media" alt="Two panels. A turret, seen from above, turns on top of the robot with its angle measured from the robot&#x27;s front; it either wraps or is limited by its wiring, tracks a target with a Supplier of Angle, and can use EasyCRT for its true angle. A wrist turns on the end of an arm with its angle measured from the arm it is mounted on; it always has soft limits, moves together with the arm in a sequence, and should be kept balanced."><figcaption><p>A turret and a wrist are both a Pivot.</p></figcaption></figure>

{% tabs %}
{% tab title="Turret" %}
A turret turns on top of the robot. Its angle is measured from the robot's front, so 0° usually means pointing forward.

**Configure it** for how far it can turn:

| The turret                                            | What to set                                                                                                                                                           |
| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Can spin forever (a slip ring, or nothing to wind up) | [`withContinuousWrapping`](/documentation/reference/editor/config/closed-loop-control#withcontinuouswrapping) and no soft limits, so it takes the short way round.    |
| Is limited by its wiring                              | [`withSoftLimits`](/documentation/reference/editor/config/limits-and-protection#withsoftlimits), with hard limits a little wider. It may have to unwind the long way. |

```java
// Fragment: a turret limited by its wiring to one and a bit turns. Placeholder gains.
SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(10, 4)))
    .withClosedLoopController(20, 0, 0.5)
    .withFeedforward(new SimpleMotorFeedforward(0.2, 0.5, 0)) // kS, kV, kA
    .withTrapezoidalProfile(DegreesPerSecond.of(360), DegreesPerSecondPerSecond.of(720))
    .withSoftLimits(Degrees.of(-200), Degrees.of(200))
    .withStartingPosition(Degrees.of(0))
    .withMomentOfInertia(Meters.of(0.25), Pounds.of(8))
    .withTelemetry("TurretMotor", TelemetryVerbosity.HIGH);
PivotConfig config = new PivotConfig()
    .withHardLimits(Degrees.of(-220), Degrees.of(220))
    .withTelemetry("Turret", TelemetryVerbosity.HIGH);
```

**Use it** to track something by giving `setAngle` a supplier, which it reads every loop. To aim at a point on the field, the turret's angle is the direction to the target minus the robot's heading:

```java
// In TurretSubsystem. Never ends: bind it with whileTrue, or make it the default command.
public Command aimAt(Supplier<Angle> fieldAngleToTarget, Supplier<Angle> robotHeading)
{
  return pivot.setAngle(() -> fieldAngleToTarget.get().minus(robotHeading.get()));
}
```

A turret geared so its encoders turn more than once over its travel cannot tell where it is from one encoder. [EasyCRT](/documentation/understanding/easycrt) works out its true angle from two.
{% endtab %}

{% tab title="Wrist" %}
A wrist turns on the end of another mechanism, usually an arm. Its angle is measured from the arm it is mounted on, not from the ground.

**Configure it** with soft limits always, because a wrist has parts to hit at both ends of its travel, and a small moment of inertia.

```java
// Fragment: a wrist on the end of an arm. Placeholder gains.
SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 5)))
    .withClosedLoopController(12, 0, 0.2)
    .withFeedforward(new SimpleMotorFeedforward(0.1, 0.3, 0)) // kS, kV, kA
    .withTrapezoidalProfile(DegreesPerSecond.of(360), DegreesPerSecondPerSecond.of(720))
    .withSoftLimits(Degrees.of(-90), Degrees.of(90))
    .withStartingPosition(Degrees.of(0))
    .withMomentOfInertia(Inches.of(6), Pounds.of(2))
    .withTelemetry("WristMotor", TelemetryVerbosity.HIGH);
PivotConfig config = new PivotConfig()
    .withHardLimits(Degrees.of(-100), Degrees.of(100))
    .withTelemetry("Wrist", TelemetryVerbosity.HIGH);
```

**Use it** together with the arm it rides on. Keep the wrist in its own subsystem, and move the two from a command that owns neither, so each keeps its own default command.

A `Pivot` does not account for gravity, so it suits a wrist that is balanced about its shaft. A heavy, unbalanced wrist is pulled on by gravity by an amount that depends on the arm's angle as well as its own, which neither `Pivot` nor `Arm` models. Balance the wrist if you can. If you cannot, expect to need more `kP`, and check it holds at every arm angle.
{% endtab %}
{% endtabs %}

## Moment of inertia

How heavy the pivot is to turn is set on the motor config with [`withMomentOfInertia`](/documentation/reference/editor/config/simulation#withmomentofinertia). It only matters in simulation, where it also decides the current the pivot draws from the [battery simulation](/documentation/understanding/battery-simulation).

## Configuring and tuning a pivot, step by step

Do the configuration steps first, in simulation, then tune the real pivot with [live tuning](/documentation/how-to-tuning/live-tuning). Tuning something that is configured wrong wastes the time.

{% hint style="danger" %}
Like all tuning, this can be dangerous. Keep clear of the mechanism, start with low current limits and small moves, and practice in simulation first.
{% endhint %}

### Configure it

{% stepper %}
{% step %}

#### Set the gearing

Give the reduction from the motor to the pivot with [`withGearing`](/documentation/reference/editor/config/gearing-and-units#withgearing).
{% endstep %}

{% step %}

#### Choose the positive direction

For a turret, counter-clockwise seen from above is positive, to match the robot's heading. Apply a small positive voltage and flip [`withMotorInverted`](/documentation/reference/editor/config/motor-basics#withmotorinverted) if it turns the other way.
{% endstep %}

{% step %}

#### Choose where zero is

A turret's zero is usually pointing at the robot's front. A wrist's zero is usually in line with its arm. Set an absolute encoder's [zero offset](/documentation/reference/editor/config/encoders#withexternalencoderzerooffset), or a [starting position](/documentation/reference/editor/config/encoders#withstartingposition).
{% endstep %}

{% step %}

#### Wrap it or limit it

A turret that can spin forever gets [`withContinuousWrapping`](/documentation/reference/editor/config/closed-loop-control#withcontinuouswrapping) and no soft limits. Everything else gets [`withSoftLimits`](/documentation/reference/editor/config/limits-and-protection#withsoftlimits), inside [`withHardLimits`](/documentation/reference/mechanism-configs/shared-options#withhardlimits). If its absolute encoder must read across zero, add [`withWrapping`](/documentation/reference/editor/config/encoders#withwrapping): it sets the encoder's range without the closed loop wrapping, so it works with soft limits.
{% endstep %}

{% step %}

#### Describe it to the simulator

Set [`withMomentOfInertia`](/documentation/reference/editor/config/simulation#withmomentofinertia) on the motor config.
{% endstep %}
{% endstepper %}

### What is different when tuning a pivot

A pivot is tuned like an arm without the kG step: follow [Step 5 of the Arm tutorial](/documentation/tutorials/arm/tune), and see [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order) for the keys to watch. What sets a pivot apart:

* **There is no kG.** Start with kS: raise it until the pivot is just about to move, in each direction, and use the smaller value.
* **Friction varies with direction and position.** Cables and hoses drag more one way, and more near the ends of the travel. Tune where the drag is worst.
* **kV matters more than on an arm** for a turret that tracks, because its setpoint never stops moving.

### What changes for each kind

{% tabs %}
{% tab title="Turret" %}

* **Check both directions.** Cables and hoses drag more one way than the other, and more near the end of the travel. Tune kS and kP where the drag is worst.
* **Tune it while tracking.** A turret that aims at a target has a setpoint that never stops moving. Drive and spin the robot while it tracks, and raise kV and kP until it stays on target.
* **Check the seam.** With continuous wrapping, command a move across the wrapping point and check it takes the short way.
* **Check the unwind.** With soft limits, command an angle just past a limit and check the turret goes the long way round to reach it, or stops at the limit.
  {% endtab %}

{% tab title="Wrist" %}

* **Tune it at several arm angles.** Because a `Pivot` does not account for gravity, an unbalanced wrist is pushed around by it as the arm moves. Tune with the arm level, where that is worst, then check with the arm up and down.
* **Raise kP to hold against gravity** if you cannot balance the wrist. Expect a small steady error that changes with the arm's angle.
* **Tune it holding a game piece**, which changes both its weight and its balance.
* **Check the limits with the arm in every position.** A wrist that clears the robot with the arm up may hit it with the arm down.
  {% endtab %}
  {% endtabs %}

## PivotConfig options

Every `PivotConfig` option is on the [PivotConfig](/documentation/reference/mechanism-configs/pivot-config) page under this one, with a graphic and an example for each. Options shared by every mechanism are in [Shared options](/documentation/reference/mechanism-configs/shared-options).

A `Pivot` needs its hard limits and a starting position before it can be created in simulation: see [what simulation needs](/documentation/reference/mechanism-configs#what-simulation-needs).

## Code reference

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/TurretSubsystem.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/simple_robot-2027/src/main/java/first/robot/mechanisms/TurretMechanism.java>" %}


# Shooters

A shooter is a `FlyWheel` in YAMS, and so is anything else that spins: rollers, intakes, feeders and indexers.

## How a flywheel works

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-f39e7cabe75cb6ce112124da2bec4ada7b657613%2Fmech-flywheel-how.png?alt=media" alt="A graph of flywheel speed against time. It spins up to the speed you asked for, sits inside a tolerance band where it is ready to shoot, drops when a game piece goes through, and recovers back into the band."><figcaption><p>A flywheel holds a speed.</p></figcaption></figure>

Where an arm or an elevator goes to a position, a flywheel goes to a speed. Most of the voltage comes from the `kV` term of [`SimpleMotorFeedforward`](/documentation/reference/editor/config/feedforward#withfeedforward), which is the voltage that speed needs, and a small `kP` corrects what is left and brings the wheel back after a game piece slows it.

A roller that only ever needs a voltage is still a `FlyWheel`: put its motor in [`ControlMode.OPEN_LOOP`](/documentation/reference/editor/config/motor-basics#withcontrolmode) and drive it with `set` or `setVoltage`, as in [Intakes, rollers and feeders](#intakes-rollers-and-feeders) below.

## Creating a flywheel

This is the shape of a shooter class, not a complete file: the imports and the motor controller object (`spark`, a `SparkMax`) are left out. [Step 2 of the Shooter/FlyWheels tutorial](/documentation/tutorials/shooter-flywheels/mechanism) builds the complete file. The code is the same for Commands v2 and Commands v3 except for the package you import from and the class that owns the mechanism.

{% tabs %}
{% tab title="Commands v2" %}

```java
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.mechanisms.FlyWheel;

public class ShooterSubsystem extends SubsystemBase
{
  private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withGearing(new MechanismGearing(1))
      .withClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0.01))
      .withMomentOfInertia(Inches.of(4), Pounds.of(1))
      .withStatorCurrentLimit(Amps.of(40))
      .withZeroPower(MotorMode.COAST)
      .withTelemetry("ShooterMotor", TelemetryVerbosity.HIGH);
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), motorConfig);
  private final FlyWheelConfig config = new FlyWheelConfig()
      .withDiameter(Inches.of(4))
      .withTelemetry("Shooter", TelemetryVerbosity.HIGH);
  private final FlyWheel flywheel = new FlyWheel(config, motor); // the YAMS FlyWheel inside the shooter

  @Override
  public void periodic()
  {
    flywheel.updateTelemetry(); // every loop
  }

  @Override
  public void simulationPeriodic()
  {
    flywheel.simIterate(); // every loop, in simulation
  }
}
```

`this` is the `Subsystem`. The scheduler calls `periodic()` and `simulationPeriodic()` for you.
{% endtab %}

{% tab title="Commands v3" %}

```java
import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.mechanisms.FlyWheel;

public class ShooterMechanism implements Mechanism
{
  private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
      .withControlMode(ControlMode.CLOSED_LOOP)
      .withGearing(new MechanismGearing(1))
      .withClosedLoopController(0.1, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0.01))
      .withMomentOfInertia(Inches.of(4), Pounds.of(1))
      .withStatorCurrentLimit(Amps.of(40))
      .withZeroPower(MotorMode.COAST)
      .withTelemetry("ShooterMotor", TelemetryVerbosity.HIGH);
  private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), motorConfig);
  private final FlyWheelConfig config = new FlyWheelConfig()
      .withDiameter(Inches.of(4))
      .withTelemetry("Shooter", TelemetryVerbosity.HIGH);
  private final FlyWheel flywheel = new FlyWheel(config, motor); // the YAMS FlyWheel inside the shooter

  public void periodic()
  {
    flywheel.updateTelemetry(); // every loop
  }

  public void simulationPeriodic()
  {
    flywheel.simIterate(); // every loop, in simulation
  }
}
```

`this` is the Commands v3 `Mechanism`. A `Mechanism` has no periodic hook, so call `periodic()` yourself from `Robot.robotPeriodic()`, and run `simulationPeriodic()` in its own `Notifier`, started from `Robot.simulationInit()`. [Where the tutorials put things](/documentation/tutorials/project-setup#where-the-tutorials-put-things) shows both.
{% endtab %}
{% endtabs %}

The options in `motorConfig` are explained in [SmartMotorControllerConfig](/documentation/reference/editor/config), and the options in `config` in [FlyWheelConfig](/documentation/reference/mechanism-configs/flywheel-config).

In the rest of your code, `shooter` is the `ShooterSubsystem` (or `ShooterMechanism`), and `flywheel` is the YAMS `FlyWheel` inside it.

{% hint style="info" %}
The gains (`kP` of 0.1, `kS` of 0.1, `kV` of 0.12) are placeholders. In simulation the wheel should spin up close to the speed you ask for, perhaps settling a little under or over it. On your robot they will be wrong: the [Shooter/FlyWheels tutorial](/documentation/tutorials/shooter-flywheels/tune) finds the real ones.
{% endhint %}

## Controlling a flywheel

A flywheel takes speed targets: `flywheel.run(RPM.of(3000))` spins at 3000 RPM until interrupted, `flywheel.runTo(RPM.of(3000), RPM.of(100))` ends once it is at speed, and `flywheel.getSpeed()` reads how fast it is going. [Controlling a mechanism](/documentation/reference/controlling-a-mechanism) lists every command, setpoint function and check, and [When mechanism commands end](/documentation/understanding/run-vs-runto) explains how they work with a default command.

A shooter subsystem usually wraps them in a few command factories:

{% tabs %}
{% tab title="Commands v2" %}

```java
// In ShooterSubsystem
public Command spin(AngularVelocity speed)
{
  return flywheel.run(speed); // holds the speed, never ends
}

public Command spinUp(AngularVelocity speed)
{
  return flywheel.runTo(speed, RPM.of(100)); // ends once it is at speed
}

public Command stop()
{
  return flywheel.set(0); // closed loop off, output 0: the wheel coasts down
}

public Trigger atSpeed(AngularVelocity speed)
{
  return flywheel.near(speed, RPM.of(100));
}

// In RobotContainer
shooter.setDefaultCommand(shooter.stop());
```

{% endtab %}

{% tab title="Commands v3" %}

```java
// In ShooterMechanism
public Command spin(AngularVelocity speed)
{
  return flywheel.run(speed); // holds the speed, never ends
}

public Command spinUp(AngularVelocity speed)
{
  return flywheel.runTo(speed, RPM.of(100)); // ends once it is at speed
}

public Command stop()
{
  return run(coroutine -> coroutine.await(flywheel.set(0))) // closed loop off, output 0
      .withPriority(Command.LOWEST_PRIORITY)                // so any other command can take over
      .named("Shooter Stop");
}

public Trigger atSpeed(AngularVelocity speed)
{
  return flywheel.near(speed, RPM.of(100));
}

// In Robot
shooter.setDefaultCommand(shooter.stop());
```

{% endtab %}
{% endtabs %}

Make `set(0)` the default command, not `run(RPM.of(0))`. A speed of zero is a closed loop target, so the motor would brake the wheel to a stop against its momentum, drawing current to do it. `set(0)` turns the closed loop off and lets the wheel coast down, with `MotorMode.COAST`.

## Shooting

A shot is two flywheels working together: the shooter spins up, and a feeder pushes the game piece in once the shooter is at speed. Gate the feeder on the shooter's `atSpeed` trigger:

```java
// In RobotContainer (Commands v2) or Robot (Commands v3).
// feeder is a roller subsystem with a feed() command, as in the next section.
controller.rightTrigger().whileTrue(shooter.spin(RPM.of(3000)));
controller.rightTrigger().and(shooter.atSpeed(RPM.of(3000))).whileTrue(feeder.feed());
```

While the trigger is held the shooter holds 3000 RPM, and the feeder only runs while the shooter is within 100 RPM of it. On release, both default commands take over. [How do I shoot with a shooter?](/documentation/how-to-mechanisms/how-to-shoot-with-a-shooter) walks through it, and [Double FlyWheel](/documentation/tutorials/double-flywheel) covers two wheels spinning at different speeds.

## Shooting on the move

A shooter on a moving robot needs a lead: [How do I shoot on the move?](/documentation/how-to-mechanisms/how-do-i-shoot-on-the-move) lists where to learn the math and which YAMS call does each part, and [Shoot on the move: worked example](/documentation/how-to-mechanisms/how-do-i-shoot-on-the-move/shoot-on-the-move-example) builds a complete robot. This section explains the idea, and what the Swerve Input Stream does for you.

### The idea in one picture

A game piece keeps the robot's velocity when it leaves the shooter, so a robot that aims straight at the target while driving sideways misses. The sources listed in [How do I shoot on the move?](/documentation/how-to-mechanisms/how-do-i-shoot-on-the-move) all solve the same problem: work out a **lead** that cancels the robot's motion.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-de2d204b5e42da8a5d96b1e367da6a5f3b1f4def%2Fhowto-sotm-virtual-target.gif?alt=media" alt="Animation of two robots seen from above, both driving to the right at the same speed and shooting at a target. The first aims straight at the target, and every shot drifts to the right of it and misses. The second aims at a virtual target to the left of the real one, and every shot drifts into the real target."><figcaption><p>The shot keeps the robot's velocity, so the aim has to lead it.</p></figcaption></figure>

### A primer: vector subtraction

**Read:** Eeshwar's [Shooting on the Fly](https://blog.eeshwark.com/robotblog/shooting-on-the-fly) and [Shooting on the Fly, Part 2: The LUT Approach](https://blog.eeshwark.com/robotblog/shooting-on-the-fly-pt2).

Before you pick a firing strategy, it helps to see the lead as one subtraction, which is how Eeshwar's posts explain it:

1. The time of flight in your lookup table gives the horizontal speed of the standing shot: the distance divided by the time.
2. Point a velocity of that speed at the target. This is the velocity the game piece needs over the ground.
3. Subtract the robot's velocity. What is left is the velocity the shooter has to give the game piece.
4. The direction of that vector is where to aim, and its length is the speed the shot needs.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b6e1071fbc7569172b3ec41aaadd6513e2037308%2Fhowto-sotm-vector-subtraction.gif?alt=media" alt="Animation of a robot driving to the right with a target ahead and to its right, built up in four steps. A purple arrow from the robot points at the target: the velocity the game piece needs over the ground. A green arrow points right: the robot&#x27;s velocity. A dashed green arrow of the same length runs backwards from the tip of the purple arrow: the subtraction. An orange arrow from the robot to the end of the dashed arrow is the velocity the shooter has to give, and the robot turns to face along it."><figcaption><p>The orange arrow is what the shooter has to give: the purple arrow minus the green one.</p></figcaption></figure>

Two things follow from this, and every firing strategy has to deal with both. The **aim** changes when the robot moves, and so does the **speed** of the shot: drive toward the target and the shooter needs less, drive away and it needs more. The firing strategies in the [worked example](/documentation/how-to-mechanisms/how-do-i-shoot-on-the-move/shoot-on-the-move-example) are different ways of working out that same lead from the time of flight in your table.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-4b7149eafa7517d5391f2d1e96fea4e16b3f3270%2Fhowto-sotm-vector-sweep.gif?alt=media" alt="Animation of a robot with a target straight ahead, driving at 2 meters per second in every direction in turn. The velocity needed over the ground stays at 4.3 meters per second toward the target. Driving toward the target, the velocity the shooter gives shrinks to 2.3 meters per second. Driving away, it grows to 6.3 meters per second. Driving across, it stays near 4.7 meters per second and swings about 25 degrees back against the motion."><figcaption><p>Toward the target the shot needs less speed, away it needs more, and across it the aim swings back.</p></figcaption></figure>

### What `SwerveInputStream` does, and what it leaves to you

The stream's aim mode uses the simplest method there is, **point at the pose**. [`withAim`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-at-a-target) takes a target pose, works out the direction from the robot to it, and lets the drive's rotation PID controller turn the front of the robot that way while the left stick keeps translating.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-994c292da5fb3b9009ea24281febe15d3f254779%2Fsis-aim.gif?alt=media" alt="Animation of a robot driven left and right by the left stick while it stays facing a target on the field"><figcaption><p><code>withAim</code>: the left stick drives, and the robot keeps facing the target it is given.</p></figcaption></figure>

Four options refine it: [`withAimLookahead`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-lookahead), [`withAimFeedforward`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-feedforward), [`withAimHeadingOffset`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-heading-offset) and [`aimLock`](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-lock). The [Swerve Input Stream](/documentation/reference/swerve-input-stream/swerve-input-stream-aim#aim-at-a-target) page explains each one.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-1f4290106eee9438b58b9d3aebb229ffabc80c78%2Fsis-aim-lookahead.gif?alt=media" alt="Animation of a robot driving to the right with a faded copy of itself a short way ahead along its velocity. A grey dashed line runs from the robot to the target, and an orange dashed line runs from the faded copy to the target. The robot turns to the direction of the orange line."><figcaption><p><code>withAimLookahead</code>: the robot turns to the direction it will need a moment from now.</p></figcaption></figure>

Even with all four, the stream on its own does **not** shoot on the move the way you might expect:

* **The lookahead is one fixed time.** Aiming from where the robot will be in 0.3 seconds is the same as leading the target by 0.3 seconds of travel. That is only the right lead when the time of flight is 0.3 seconds, which is true at one distance. Use the lookahead for what the sources call latency: the short, constant delay before the game piece leaves the robot.
* **It only turns the robot.** A lead changes the distance of the shot as well as its direction. The stream knows nothing about your flywheel, your hood or your tables, so it cannot change the shot to match.
* **It assumes a straight line.** The lookahead takes the robot's velocity right now and assumes it stays the same.
* **Without a feedforward, the rotation lags.** The PID controller only reacts to error, so while the robot drives past the target it trails a little behind.

So let the stream do the turning, and give it the right thing to turn to. The lead itself comes from one of the methods in the sources, which is the part you write.

## Intakes, rollers and feeders

A roller that only needs to push a game piece in or out does not need a speed. Make it a `FlyWheel` in its own subsystem, with its motor in open loop, and give it a voltage:

```java
// Fragment of FeederSubsystem (Commands v2). spark is the SparkMax for the roller.
private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.OPEN_LOOP)            // no PID or feedforward
    .withGearing(new MechanismGearing(3))
    .withMomentOfInertia(Inches.of(1), Pounds.of(0.5)) // for the simulation
    .withStatorCurrentLimit(Amps.of(40))
    .withZeroPower(MotorMode.COAST)
    .withTelemetry("FeederMotor", TelemetryVerbosity.HIGH);
private final SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), motorConfig);
private final FlyWheel roller = new FlyWheel(
    new FlyWheelConfig().withTelemetry("Feeder", TelemetryVerbosity.HIGH), motor);

public Command feed()
{
  return roller.setVoltage(Volts.of(8));  // push the game piece toward the shooter, until interrupted
}

public Command eject()
{
  return roller.set(-0.8);                // 80% backwards, until interrupted
}

public Command stop()
{
  return roller.set(0);                   // the default command
}
```

`set` takes a duty cycle from -1 to 1, and `setVoltage` a voltage. A voltage gives the same push as the battery drains, so prefer it. An intake is the same class with an `intake()` command. In Commands v3, write `stop()` as a lowest priority default command, as for the shooter above. [How do I set up an intake roller?](/documentation/how-to-mechanisms/how-do-i-set-up-an-intake-roller) has complete files for both.

## When a flywheel will not reach its speed

A flywheel that reaches low speeds but not high ones, or that slows down more with every shot, is usually short of power and not badly tuned: see [when tuning does not help](/documentation/tutorials/troubleshooting#when-tuning-does-not-help).

## Configuring and tuning a flywheel, step by step

Do the configuration steps first, in simulation, then tune the real flywheel with [live tuning](/documentation/how-to-tuning/live-tuning). Tuning something that is configured wrong wastes the time.

{% hint style="danger" %}
Like all tuning, this can be dangerous. Keep clear of the mechanism, start with low current limits and small moves, and practice in simulation first.
{% endhint %}

### Configure it

{% stepper %}
{% step %}

#### Set the gearing

Give the reduction from the motor to the wheel with [`withGearing`](/documentation/reference/editor/config/gearing-and-units#withgearing). An overdrive, where the wheel spins faster than the motor, is a number below 1.
{% endstep %}

{% step %}

#### Choose the positive direction

Positive should be the direction that shoots or intakes. Flip [`withMotorInverted`](/documentation/reference/editor/config/motor-basics#withmotorinverted) if it is not.
{% endstep %}

{% step %}

#### Let it coast

Use `MotorMode.COAST` so the wheel is not braked to a stop every time the command ends, and set a [stator current limit](/documentation/reference/editor/config/limits-and-protection#withstatorcurrentlimit-and-withsupplycurrentlimit).
{% endstep %}

{% step %}

#### Set the diameter

Set [`withDiameter`](/documentation/reference/mechanism-configs/flywheel-config#withdiameter) if you want to ask for surface speeds.
{% endstep %}

{% step %}

#### Describe it to the simulator

Set [`withMomentOfInertia`](/documentation/reference/editor/config/simulation#withmomentofinertia) on the motor config.
{% endstep %}
{% endstepper %}

### What is different when tuning a flywheel

The [Shooter/FlyWheels tutorial](/documentation/tutorials/shooter-flywheels/tune) walks through tuning a flywheel, and [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order) lists the order with the keys to watch. What sets a flywheel apart:

* **kV does most of the work.** It is the voltage the speed needs. Find kS, then raise kV until `mechanism/velocity` settles on the setpoint with no help from kP, and check it at a low and a high speed.
* **kP only needs to be small.** Its job is to bring the wheel back after a game piece slows it. Too much makes the speed ripple.
* **There is no kG and no position.** Nothing to hold up, and no soft limits.
* **Choose the tolerance by shooting.** Shoot at the edges of your `atSpeed` tolerance, and use the widest one where the shots still land, so the shooter is ready sooner.
* **A brownout is not a tuning problem.** If spinning up browns out the robot, add a [velocity profile](/documentation/reference/editor/config/motion-profiles#velocity-profiles-for-flywheels) or a [current limit](/documentation/reference/editor/config/limits-and-protection#withstatorcurrentlimit-and-withsupplycurrentlimit), and test it against the [battery simulation](/documentation/understanding/battery-simulation).

## FlyWheelConfig options

Every `FlyWheelConfig` option is on the [FlyWheelConfig](/documentation/reference/mechanism-configs/flywheel-config) page under this one, with a graphic and an example for each. Options shared by every mechanism are in [Shared options](/documentation/reference/mechanism-configs/shared-options).

A `FlyWheel` needs nothing on its config to be simulated. Its [moment of inertia](/documentation/reference/editor/config/simulation#withmomentofinertia) is on the motor config.

## Code reference

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/ShooterSubsystem.java>" %}

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/simple_robot-2027/src/main/java/first/robot/mechanisms/ShooterMechanism.java>" %}


# Swerve Drive

This page explains how `SwerveDrive` works and what it can do. Every `SwerveDriveConfig` option, with a graphic and an example, is on the [SwerveDriveConfig](/documentation/reference/mechanism-configs/swerve-drive-config) page under this one. To build one from scratch, follow the [Swerve Drive tutorial](/documentation/tutorials/swerve-drive).

## How a swerve drive works

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-1173a038385c1e461d064705d38501d5f65df7ae%2Fmech-swerve-how.png?alt=media" alt="A flow diagram. You ask for a ChassisVelocities with vx, vy and omega. The kinematics, built from the module locations, turn it into four module states, a speed and an angle each. Odometry combines wheel travel and the gyro into the robot&#x27;s pose, which feeds field relative driving, auto-align and paths."><figcaption><p>From one chassis velocity to four wheels, and back to a pose.</p></figcaption></figure>

You tell the drive how the whole robot should move, as a `ChassisVelocities`: forward speed, sideways speed and turn rate. The drive's kinematics, built from where each module is, turn that into a speed and an angle for every wheel. Each [swerve module](/documentation/understanding/swerve-drive/swerve-module) then steers and drives its own wheel.

Going the other way, the drive adds up how far each wheel has rolled and combines it with the gyro to estimate where the robot is on the field. That pose is what makes field relative driving, auto-align and path following possible.

## Why `SwerveDrive` is different from other mechanisms

Every other mechanism in YAMS (`Arm`, `Elevator`, `Pivot`, `FlyWheel`) wraps a single `SmartMotorController`. `SwerveDrive` is a mechanism made of mechanisms: it owns an array of `SwerveModule`s, and each `SwerveModule` owns two `SmartMotorController`s of its own (drive and azimuth). `SwerveDriveConfig` is where the two levels meet: you build each `SwerveModule` (and its own `SwerveModuleConfig`) first, then hand the finished modules to `SwerveDriveConfig`, which derives the robot's kinematics automatically from where you told each module it physically sits.

## Basic swerve config

Here is the shape of a four-module config, condensed from the [tutorial](/documentation/tutorials/swerve-drive). The modules are passed front left, front right, back left, back right. The kinematics come from each module's location, so that order is not what makes the robot drive, but arrays such as `getModuleStates()` and the feedforward `Force[]` use the same order.

Robot code imports `SmartMotorControllerConfig`, `SwerveDriveConfig`, `SwerveDrive` and `SwerveInputStream` from the command framework package that matches your vendordep, and everything else from `yams.core`:

{% tabs %}
{% tab title="Commands v2" %}

```java
import yams.commands2.config.SmartMotorControllerConfig;
import yams.commands2.config.SwerveDriveConfig;
import yams.commands2.swerve.SwerveDrive;
import yams.commands2.swerve.SwerveInputStream;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.SwerveModuleConfig;
import yams.core.mechanisms.swerve.SwerveModule;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;
```

{% endtab %}

{% tab title="Commands v3" %}

```java
import yams.commands3.config.SmartMotorControllerConfig;
import yams.commands3.config.SwerveDriveConfig;
import yams.commands3.swerve.SwerveDrive;
import yams.commands3.swerve.SwerveInputStream;
import yams.core.gearing.MechanismGearing;
import yams.core.mechanisms.config.SwerveModuleConfig;
import yams.core.mechanisms.swerve.SwerveModule;
import yams.core.motorcontrollers.SmartMotorController;
import yams.core.motorcontrollers.local.SparkWrapper;
import yams.core.telemetry.enums.TelemetryVerbosity;
```

In Commands v3, `this` is your `Mechanism` instead of a `Subsystem`.
{% endtab %}
{% endtabs %}

A fragment for your subsystem's or mechanism's constructor. `driveMotor`, `azimuthMotor`, `encoder` and `gyro` are your hardware objects, and the gains are placeholders:

```java
SmartMotorControllerConfig driveCfg = new SmartMotorControllerConfig(this)
      .withWheelDiameter(Inches.of(4))
      .withGearing(new MechanismGearing(6.75))
      .withClosedLoopController(0.3, 0, 0)
      .withFeedforward(new SimpleMotorFeedforward(0, 0.85))
      .withStatorCurrentLimit(Amps.of(40))
      .withTelemetry("driveMotor", TelemetryVerbosity.HIGH);

SmartMotorControllerConfig azimuthCfg = new SmartMotorControllerConfig(this)
      .withClosedLoopController(4, 0, 0)
      .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
      .withGearing(new MechanismGearing(12.8))
      .withStatorCurrentLimit(Amps.of(20))
      .withTelemetry("angleMotor", TelemetryVerbosity.HIGH);

SmartMotorController driveSMC   = new SparkWrapper(driveMotor,   DCMotor.getNEO(1), driveCfg);
SmartMotorController azimuthSMC = new SparkWrapper(azimuthMotor, DCMotor.getNEO(1), azimuthCfg);

SwerveModuleConfig moduleConfig = new SwerveModuleConfig(driveSMC, azimuthSMC)
      .withAbsoluteEncoder(encoder.getAbsolutePosition().asSupplier())
      .withAbsoluteEncoderOffset(Degrees.of(64.2)) // this module's own reading, wheel forward
      .withLocation(Meters.of(0.3), Meters.of(0.3)) // front, left, from robot center
      .withOptimization(true)
      .withTelemetry("frontleft", TelemetryVerbosity.HIGH);

SwerveModule fl = new SwerveModule(moduleConfig);
// ...repeat for fr, bl, br with their own locations...

SwerveDriveConfig config = new SwerveDriveConfig(this, fl, fr, bl, br)
      .withGyro(gyro::getRotation3d) // e.g. a Pigeon2 or the SystemCore's OnboardIMU
      .withMaximumChassisSpeed(MetersPerSecond.of(4.5), DegreesPerSecond.of(360))
      .withTranslationController(new PIDController(1.0, 0, 0))
      .withRotationController(new PIDController(1.0, 0, 0))
      .withStartingPose(new Pose2d());

SwerveDrive drive = new SwerveDrive(config);
```

## Commands

`SwerveDrive` has the same commands and functions in Commands v2 and Commands v3.

| Command or function                    | Commands v2 | Commands v3 | What it does                                                                                                                                                                       |
| -------------------------------------- | ----------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `drive(Supplier<ChassisVelocities>)`   | ✅           | ✅           | Drives with **robot relative** speeds until interrupted.                                                                                                                           |
| `driveToPose(Pose2d)`                  | ✅           | ✅           | Drives to a pose with the [auto-align controllers](/documentation/reference/mechanism-configs/swerve-drive-config#auto-align-controllers) until interrupted, then stops the drive. |
| `driveToPose(Pose2d, Distance, Angle)` | ✅           | ✅           | The same, ending once the robot is within the tolerances.                                                                                                                          |
| `isNear(Pose2d, Distance, Angle)`      | ✅           | ✅           | Whether the robot is within the tolerances of a pose.                                                                                                                              |
| `stop()`                               | ✅           | ✅           | Commands zero speed.                                                                                                                                                               |

Field relative driving from a controller is a command you write around a [`SwerveInputStream`](/documentation/reference/swerve-input-stream). These are outlines of the class: `config` is the `SwerveDriveConfig` from above.

{% tabs %}
{% tab title="Commands v2" %}

```java
public class SwerveSubsystem extends SubsystemBase
{
  private final SwerveDrive drive = new SwerveDrive(config);

  public Command driveFieldRelative(SwerveInputStream input)
  {
    return run(() -> drive.setFieldRelativeChassisSpeeds(input.get()));
  }

  @Override
  public void periodic()
  {
    drive.updateTelemetry(); // also updates the pose estimate
  }

  @Override
  public void simulationPeriodic()
  {
    drive.simIterate();
  }
}
```

{% endtab %}

{% tab title="Commands v3" %}

```java
public class SwerveMechanism implements Mechanism
{
  private final SwerveDrive drive = new SwerveDrive(config);

  public Command driveFieldRelative(SwerveInputStream input)
  {
    return run(coroutine -> {
      while (true)
      {
        drive.setFieldRelativeChassisSpeeds(input.get());
        coroutine.yield();
      }
    }).named("Drive");
  }

  public void periodic() // call from Robot.robotPeriodic()
  {
    drive.updateTelemetry(); // also updates the pose estimate
  }

  public void simulationPeriodic() // Robot.simulationInit() runs this in its own Notifier
  {
    drive.simIterate();
  }
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
`updateTelemetry()` is what updates the pose estimate, so it must be called every loop even if you do not look at the telemetry.
{% endhint %}

## Driving functions

These set what the drive does and return at once. They are what the commands above are built on.

| Function                                           | What it does                                                                                                       |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `setFieldRelativeChassisSpeeds(ChassisVelocities)` | Drive with speeds measured against the field. This is what a `SwerveInputStream` gives you.                        |
| `setRobotRelativeChassisSpeeds(ChassisVelocities)` | Drive with speeds measured against the robot. An overload adds a feedforward force per module, for path followers. |
| `setSwerveModuleStates(SwerveModuleVelocity[])`    | Set every module directly, skipping the kinematics.                                                                |
| `lockPose()`                                       | Turn the wheels into an X so the robot is hard to push.                                                            |
| `resetOdometry(Pose2d)`                            | Tell the drive where it is, and set the gyro to that heading.                                                      |
| `zeroGyro()`                                       | Make the direction the robot faces now the new zero heading.                                                       |
| `addVisionMeasurement(Pose2d, double)`             | Correct the pose estimate with a vision measurement.                                                               |

## Asking where it is

| Function                                                            | Returns                                                                                 |
| ------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `getPose()`                                                         | The estimated position and heading on the field.                                        |
| `getRobotRelativeSpeed()`, `getFieldRelativeSpeed()`                | How the robot is moving now.                                                            |
| `getModuleStates()`, `getModulePositions()`                         | Each wheel's speed and angle, and how far it has rolled.                                |
| `getGyroRotation3d()`                                               | The robot's attitude from the gyro.                                                     |
| `getDistanceFromPose(Pose2d)`, `getAngleDifferenceFromPose(Pose2d)` | How far the robot is from a pose.                                                       |
| `getField2d()`                                                      | The `Field2d` the drive publishes its pose to. Use this one instead of making your own. |

## Setting up a swerve drive on a real robot

Setting the encoder offsets, checking every direction, tuning the modules and the first drive on the ground are steps in a tutorial now: see [Step 5: On the real robot](/documentation/tutorials/swerve-drive/real-robot). It ends with the speed limits, the drift corrections and auto-align, in the order to do them.

## Module location drives the kinematics

[`SwerveModuleConfig.withLocation(front, left)`](/documentation/reference/mechanism-configs/swerve-module-config#withlocation) is not just bookkeeping. `SwerveDrive` builds its `SwerveDriveKinematics` directly from the locations of every module you pass it, so the drive and rotate math is always right for your chassis without you ever constructing a `SwerveDriveKinematics` yourself.

{% hint style="warning" %}
Every module needs its location set before it's handed to `SwerveDriveConfig`. A missing or wrong location silently produces incorrect kinematics rather than a compile error, so double check trackwidth/wheelbase math when a robot doesn't drive straight.
{% endhint %}

The `withOptimization(true)` seen in the config above is a per-module flag, not a drive-level one. See [Optimization and Cosine Compensation](/documentation/understanding/swerve-drive/swerve-module#optimization-and-cosine-compensation) on the Swerve Module page for what it (and its counterpart `withCosineCompensation`) actually does.

## Gyro integration and field vs. robot relative speeds

`SwerveDriveConfig.withGyro(Supplier<Rotation3d>)` is what lets `SwerveDrive` convert between field-relative and robot-relative `ChassisVelocities` (WPILib 2027's name for `ChassisSpeeds`). The supplier returns the gyro's full attitude, such as `pigeon::getRotation3d` or `imu::getRotation3d`: its yaw is the robot's heading, and its roll and pitch are the robot's tilt. Internally, `SwerveDrive` always drives the modules with robot-relative speeds; `setFieldRelativeChassisSpeeds` just rotates the requested speeds into the robot frame using the current heading before handing them to the same code path robot-relative callers use.

```java
drive.setFieldRelativeChassisSpeeds(new ChassisVelocities(1.0, 0, 0));
```

[`withGyroOffset` and `withGyroInverted`](/documentation/reference/mechanism-configs/swerve-drive-config#the-gyro) correct the gyro's zero and sign without touching your drive code. Both apply to the heading (the yaw).

### Gyros mounted on their side

If the gyro is not mounted flat, the robot turning shows up as the gyro's roll or pitch instead of its yaw. `withGyroHeadingAxis(GyroAxis)` tells `SwerveDriveConfig` which gyro axis points up through the robot. `GyroAxis` lives in `yams.core.mechanisms.config.enums` and has three values:

| `GyroAxis` | Gyro axis pointing up | Use when                                                 |
| ---------- | --------------------- | -------------------------------------------------------- |
| `YAW`      | Z                     | The gyro is mounted flat. This is the default.           |
| `ROLL`     | X                     | The gyro is on its side, with its Y axis to robot left.  |
| `PITCH`    | Y                     | The gyro is on its side, with its X axis to robot front. |

```java
import yams.core.mechanisms.config.enums.GyroAxis;

config.withGyro(pigeon::getRotation3d)
      .withGyroHeadingAxis(GyroAxis.ROLL);
```

The gyro's attitude is rotated into the robot's frame first, then `withGyroInverted` and `withGyroOffset` are applied to the resulting heading.

### Reading the heading

`SwerveDrive.getGyroRotation3d()` (and `SwerveDriveConfig.getGyroRotation3d()`) returns the robot's attitude after the heading axis, inversion and offset are applied. Its yaw (`getZ()`, or `toRotation2d()`) is the heading, wrapped to +/-180 degrees, and its roll and pitch are the robot's tilt. In simulation, `SwerveDrive.getGyroRotation3d()` returns the simulated heading with no tilt.

```java
Rotation2d heading = drive.getGyroRotation3d().toRotation2d();
```

{% hint style="info" %}
`GyroAxis`, `withGyroHeadingAxis` and `getGyroRotation3d` are Java only. C++ takes a heading with `WithGyro(std::function<wpi::units::degree_t()>)` and reads it back with `GetGyroAngle()`.
{% endhint %}

`withGyroVelocity` and `withGyroAngularVelocityScaleFactor` correct the path of a robot that drives and turns at the same time, using how fast the gyro says the robot is turning. [`withGyroAngularVelocityScaleFactor`](/documentation/reference/mechanism-configs/swerve-drive-config#withgyroangularvelocityscalefactor) explains how to find the value.

{% hint style="info" %}
`SwerveInputStream` is the recommended way to turn raw joystick axes into a field-relative `ChassisVelocities` supplier; it handles deadbanding, axis cubing, and alliance-relative flipping so you don't have to write that math by hand. See [Swerve Input Stream](/documentation/reference/swerve-input-stream) for the full picture, or the [tutorial](/documentation/tutorials/swerve-drive) for a worked example.
{% endhint %}

A Commands v2 fragment, in the subsystem's constructor. `controller` is a `CommandGamepad`:

```java
SwerveInputStream input =
    SwerveInputStream.of(drive, () -> -controller.getLeftY(), () -> -controller.getLeftX())
        .withControllerRotationAxis(() -> -controller.getRightX());
// SwerveInputStream output is field relative.
setDefaultCommand(run(() -> drive.setFieldRelativeChassisSpeeds(input.get())));
```

## Locking the wheels (X pattern)

`SwerveDrive.lockPose()` turns every wheel to point at the robot center (each module's angle from its `withLocation(...)`) without driving it. On a rectangular chassis the four wheels form an X, so the robot resists being pushed. Call it every loop for as long as the lock should hold:

{% tabs %}
{% tab title="Commands v2" %}

```java
public Command lockPose() {
  return run(drive::lockPose).withName("Lock Pose");
}
```

{% endtab %}

{% tab title="Commands v3" %}

```java
public Command lock() {
  return run(coroutine -> {
    while (true) {
      drive.lockPose();
      coroutine.yield();
    }
  }).named("Swerve Lock");
}
```

{% endtab %}
{% endtabs %}

In Java each module is locked through `SwerveModule.setAzimuthAngle(Rotation2d)`, which uses `SwerveModuleConfig.getLockedState(...)`. Unlike a normal zero-speed module state, the lock skips the module's [velocity deadband](/documentation/understanding/swerve-drive/swerve-module#velocity-deadband), which would otherwise hold the wheels where they are, so the wheels actually turn into the X. With optimization enabled each wheel turns to whichever of the lock angle and its opposite is nearer, since both hold the robot the same way. C++ `LockPose()` does the same through `SwerveModule::SetAzimuthAngle(...)`. To turn every module to one angle without driving, as the azimuth live tuning does, use `setAzimuthAngles(Rotation2d)` (C++ `SetAzimuthAngles(...)`).

{% hint style="info" %}
`lockPose()` is not compatible with AdvantageKit, like the other `SwerveDrive` methods that command the modules directly.
{% endhint %}

## How to: follow PathPlanner paths with feedforward forces

`setRobotRelativeChassisSpeeds` has an overload that accepts a per-module drive-wheel feedforward `Force[]` (FL, FR, BL, BR order, matching module order) alongside the `ChassisVelocities`:

```java
drive.setRobotRelativeChassisSpeeds(speeds, feedforwardForces);
```

This exists specifically to plug into PathPlanner's `AutoBuilder.configure(...)`, whose `driveRobotRelative` consumer hands back a `DriveFeedforwards` alongside the requested `ChassisVelocities`. Its `linearForces()` is exactly the `Force[]` this overload expects:

```java
AutoBuilder.configure(
    drive::getPose,
    drive::resetOdometry,
    drive::getRobotRelativeSpeed,
    (speeds, feedforwards) -> drive.setRobotRelativeChassisSpeeds(speeds, feedforwards.linearForces()),
    new PPHolonomicDriveController(new PIDConstants(5.0, 0.0, 0.0), new PIDConstants(5.0, 0.0, 0.0)),
    RobotConfig.fromGUISettings(),
    () -> MatchState.getAlliance().map(alliance -> alliance == Alliance.RED).orElse(false),
    this);
```

Each module's drive `SmartMotorController` converts its share of the `Force[]` into the correct feedforward for whatever control mode it's using (voltage or torque-current) via `SmartMotorControllerConfig.convertToVoltage(...)`/`convertToCurrent(...)`, which need `withGearing(...)` and `withMechanismCircumference(...)`/`withWheelRadius(...)` configured on that motor to do the conversion. Passing an empty `Force[]` (or just calling the original single-argument overload) skips the feedforward entirely, so existing code that only calls `setRobotRelativeChassisSpeeds(speeds)` keeps working unchanged.

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/BroncBotz_2026/java/first/robot/subsystems/Swerve.java#L185-L200>" %}

{% hint style="info" %}
`SmartMotorController.setVelocity(velocity, force)` is the underlying per-motor API this builds on, and it isn't specific to swerve: any velocity-controlled `SmartMotorController` with gearing and a mechanism circumference configured can take a feedforward `Force` the same way. A `null`/unset force falls back to plain velocity control, which is what `getSetpointFeedforwardForce()` and the `SetpointForce` telemetry field then read back as empty/`0`.
{% endhint %}

## Auto-Align

`SwerveDrive` has a built-in field relative auto-align.

| Method                                 | What it does                                                                                                                             |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `driveToPose(Pose2d)`                  | Returns a `Command` that drives to the pose until it is interrupted, then stops the drive.                                               |
| `driveToPose(Pose2d, Distance, Angle)` | Returns a `Command` that drives to the pose and ends once the robot is within the distance and heading tolerances, then stops the drive. |
| `isNear(Pose2d, Distance, Angle)`      | Whether the robot is within the distance and heading tolerances of the pose.                                                             |
| `driveToPoseSetpoint(Pose2d)`          | Computes the `ChassisVelocities` that drive toward the pose, for use in your own command.                                                |

The commands and `driveToPoseSetpoint` use the translation and rotation `PIDController`s from `SwerveDriveConfig.withTranslationController(...)` and `withRotationController(...)`. Each command is a Commands v2 or Commands v3 `Command`, depending on which `SwerveDrive` you use, and all of them exist in both.

A fragment for your bindings. `driver` is a `CommandGamepad`:

```java
// Hold to align: drives to the pose for as long as the button is held.
driver.faceDown().whileTrue(drive.driveToPose(new Pose2d(2, 4, Rotation2d.ZERO)));

// Press to align: ends by itself within 5 cm and 3 degrees, so it can be used in a sequence or an auto.
driver.faceRight().onTrue(drive.driveToPose(new Pose2d(2, 4, Rotation2d.ZERO), Centimeters.of(5), Degrees.of(3)));
```

Use the version with tolerances whenever something has to happen after the robot arrives. The version without them never ends on its own.

{% hint style="success" %}
The auto-align gains, and the drive and azimuth motor gains, can be tuned from a dashboard without redeploying. See [Tune a swerve drive](/documentation/how-to-tuning/live-tuning/swerve-drive).
{% endhint %}

## Telemetry verbosity

Like every other mechanism, `SwerveDriveConfig.withTelemetry(name, TelemetryVerbosity)` picks a preset bundle of fields to publish, from pose and gyro angle at `LOW` up to full desired/measured chassis speeds and module states at `HIGH`. Each level includes everything the level below it publishes.

```java
config.withTelemetry("swerve", TelemetryVerbosity.HIGH);
```

| Field                                      | NetworkTables key                   | `LOW` | `MID` | `HIGH` |
| ------------------------------------------ | ----------------------------------- | :---: | :---: | :----: |
| Pose                                       | `pose`                              |   ✓   |   ✓   |    ✓   |
| Gyro angle                                 | `gyro`                              |   ✓   |   ✓   |    ✓   |
| Current robot-relative ChassisVelocities   | `chassis/current`                   |       |   ✓   |    ✓   |
| Field-relative ChassisVelocities           | `chassis/field`                     |       |   ✓   |    ✓   |
| Current module states                      | `states/current`                    |       |   ✓   |    ✓   |
| Desired robot-relative ChassisVelocities   | `chassis/desired`                   |       |       |    ✓   |
| Desired module states                      | `states/desired`                    |       |       |    ✓   |
| Translation P/I/D (tunable)                | `autoalign/translation/p,i,d`       |       |       |    ✓   |
| Rotation P/I/D (tunable)                   | `autoalign/rotation/p,i,d`          |       |       |    ✓   |
| Auto-align target X (tunable)              | `autoalign/setpoint/x`              |       |       |    ✓   |
| Auto-align target Y (tunable)              | `autoalign/setpoint/y`              |       |       |    ✓   |
| Auto-align target rotation (tunable)       | `autoalign/setpoint/rot`            |       |       |    ✓   |
| Auto-align enabled (tunable)               | `autoalign/enabled`                 |       |       |    ✓   |
| Modules drive P/I/D (tunable, shared)      | `modules/drive/feedback/p,i,d`      |       |       |    ✓   |
| Modules drive kS/kV/kA (tunable, shared)   | `modules/drive/feedforward/s,v,a`   |       |       |    ✓   |
| Modules drive velocity (tunable, shared)   | `modules/drive/velocity`            |       |       |    ✓   |
| Modules drive tuning enabled (tunable)     | `modules/drive/enabled`             |       |       |    ✓   |
| Modules drive in place (tunable)           | `modules/drive/inplace`             |       |       |    ✓   |
| Modules drive voltage (tunable, shared)    | `modules/drive/voltage/setpoint`    |       |       |    ✓   |
| Modules drive voltage enabled (tunable)    | `modules/drive/voltage/enabled`     |       |       |    ✓   |
| Modules azimuth P/I/D (tunable, shared)    | `modules/azimuth/feedback/p,i,d`    |       |       |    ✓   |
| Modules azimuth kS/kV/kA (tunable, shared) | `modules/azimuth/feedforward/s,v,a` |       |       |    ✓   |
| Modules azimuth angle (tunable, shared)    | `modules/azimuth/angle`             |       |       |    ✓   |
| Modules azimuth tuning enabled (tunable)   | `modules/azimuth/enabled`           |       |       |    ✓   |
| Modules azimuth voltage (tunable, shared)  | `modules/azimuth/voltage/setpoint`  |       |       |    ✓   |
| Modules azimuth voltage enabled (tunable)  | `modules/azimuth/voltage/enabled`   |       |       |    ✓   |

{% hint style="info" %}
`autoalign/setpoint/x`/`autoalign/setpoint/y`/`autoalign/setpoint/rot` and `autoalign/enabled`, and the `modules/drive/*`/`modules/azimuth/*` tuning fields, only take effect while the `Tuning/<name>/Live Tuning` command is scheduled, since that's the loop that actually reads them. Publishing values to them with the tuning command idle has no effect on the robot.
{% endhint %}

{% hint style="warning" %}
The `modules/drive/*` and `modules/azimuth/*` fields are **shared across every module**, not per-module. There is no way to tune a single module's PID or setpoint independently through this mechanism; it applies the same gains and setpoint to all modules on the drive at once.
{% endhint %}

### Using `SwerveDriveTelemetryConfig` directly

Pass a `SwerveDriveTelemetryConfig` instead of a verbosity level when you need finer control than a preset gives you, such as disabling the auto-align tuning fields, or routing telemetry to a DataLog instead of NetworkTables during competition:

```java
SwerveDriveTelemetryConfig telemetryCfg =
    new SwerveDriveTelemetryConfig(TelemetryVerbosity.HIGH)
        // HIGH enables this by default; opt back out if you don't want live driveToPose tuning exposed.
        .withCustom(SwerveDriveTelemetry.BooleanTelemetryField.AutoAlignEnabled, false)
        .withoutNetworkTables()
        .withDataLogName("swerve");

SwerveDriveConfig config = new SwerveDriveConfig(this, fl, fr, bl, br)
      .withGyro(gyro::getRotation3d)
      .withTranslationController(new PIDController(1.0, 0, 0))
      .withRotationController(new PIDController(1.0, 0, 0))
      .withTelemetry("swerve", telemetryCfg);
```

`SwerveDriveTelemetryConfig(TelemetryVerbosity)` is a shorthand constructor equivalent to `new SwerveDriveTelemetryConfig().withTelemetryVerbosity(verbosity)`, useful when you're about to layer more `with*()` calls on top anyway. See [Telemetry](/documentation/understanding/telemetry) for the shared telemetry architecture these configs build on.

## Code reference

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/SwerveSubsystem.java>" %}


# Swerve Module

Every `SwerveModuleConfig` option, with a graphic and an example, is on the [SwerveModuleConfig](/documentation/reference/mechanism-configs/swerve-module-config) page under this one.

## How a swerve module works

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-334ca718dfc3af013b0986833ea5b5326ba2a2dc%2Fmech-module-how.png?alt=media" alt="A swerve module seen from above, with its speed along the wheel and its angle. The drive motor uses velocity control to set how fast the wheel rolls. The azimuth motor uses position control with wrapping to set which way the wheel points. An absolute encoder tells the azimuth where the wheel is at startup. The module&#x27;s state is a SwerveModuleVelocity, a speed and an angle."><figcaption><p>One module is a drive motor, an azimuth motor and an absolute encoder.</p></figcaption></figure>

A module has one job: make its wheel roll at a speed, pointing at an angle. The drive motor runs velocity control for the speed, and the azimuth motor runs position control for the angle. An absolute encoder tells the azimuth which way the wheel points when the robot turns on, because the azimuth motor's own encoder starts at zero wherever the wheel happens to be.

Both motors are ordinary [`SmartMotorController`s](/documentation/reference/editor), each with its own [`SmartMotorControllerConfig`](/documentation/reference/editor/config), so everything about gearing, gains and current limits applies to them unchanged.

## Commands v2, Commands v3 and functions

A `SwerveModule` has no commands of its own, and is the same class in Commands v2 and Commands v3: `yams.core.mechanisms.swerve.SwerveModule`. The only difference is the package its two motor configs come from, `yams.commands2.config` or `yams.commands3.config`. The [`SwerveDrive`](/documentation/understanding/swerve-drive#commands) is what you command, and it sets each module for you.

You rarely call a module directly, but these are the functions it has:

| Function                                                   | What it does                                                                                                                                                                                                                   |
| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `setSwerveModuleState(SwerveModuleVelocity)`               | Set the wheel's speed and angle. The [optimization, cosine compensation and velocity deadband](/documentation/reference/mechanism-configs/swerve-module-config) are applied first. An overload adds a drive feedforward force. |
| `setAzimuthAngle(Rotation2d)`                              | Turn the wheel to an angle without driving it.                                                                                                                                                                                 |
| `getState()`                                               | The wheel's current speed and angle, and how fast the azimuth is turning.                                                                                                                                                      |
| `getPosition()`                                            | How far the wheel has rolled, and its angle. Used for odometry.                                                                                                                                                                |
| `seedAzimuthEncoder()`                                     | Set the azimuth motor's encoder from the absolute encoder.                                                                                                                                                                     |
| `getRawAbsoluteEncoderAngle()`                             | The absolute encoder's reading with no offset, for [finding the offset](/documentation/reference/mechanism-configs/swerve-module-config#withabsoluteencoderoffset).                                                            |
| `getDriveMotorController()`, `getAzimuthMotorController()` | The two motors, for anything YAMS does not wrap.                                                                                                                                                                               |

`SwerveDrive.updateTelemetry()` and `SwerveDrive.simIterate()` update every module, so you do not call those on a module yourself.

See [Swerve Drive](/documentation/understanding/swerve-drive) first for how modules fit into the drive as a whole. This page goes deeper on `SwerveModule` and `SwerveModuleConfig` themselves.

Both are in `yams.core` and are shared by Commands v2 and Commands v3, so the imports are the same whichever vendordep you use:

```java
import yams.core.mechanisms.config.SwerveModuleConfig;
import yams.core.mechanisms.swerve.SwerveModule;
```

Module states are WPILib 2027 `SwerveModuleVelocity`s (the 2027 name for `SwerveModuleState`).

## Setting up a module on a real robot

Finding each module's absolute encoder offset, checking which way the motors turn and tuning the azimuth and drive motors are steps in a tutorial now: see [Step 5: On the real robot](/documentation/tutorials/swerve-drive/real-robot).

## A fully configured module

Here's every `SwerveModuleConfig` option from this page in one place. The sections below explain each call, and [SwerveModuleConfig](/documentation/reference/mechanism-configs/swerve-module-config) has one section per option:

```java
SwerveModuleConfig moduleConfig = new SwerveModuleConfig(driveSMC, azimuthSMC)
      .withAbsoluteEncoder(encoder.getAbsolutePosition().asSupplier())
      .withAbsoluteEncoderOffset(Rotations.of(0.25))
      .withAbsoluteEncoderGearing(new GearBox(new double[]{1.5}))
      .withLocation(Meters.of(0.3), Meters.of(0.3))
      .withOptimization(true)
      .withCosineCompensation(true)
      .withVelocityDeadband(MetersPerSecond.of(0.05))
      .withTelemetry("frontleft", TelemetryVerbosity.HIGH);

SwerveModule fl = new SwerveModule(moduleConfig);
```

{% hint style="info" %}
`withWheelRadius(Distance)`/`withWheelDiameter(Distance)` also exist on `SwerveModuleConfig`, but the source recommends setting wheel size on the drive motor's `SmartMotorControllerConfig` instead (see [Swerve Drive's Basic Swerve Config](/documentation/understanding/swerve-drive#basic-swerve-config)), so they're left out above.
{% endhint %}

## Two motors, one module

A `SwerveModule` pairs exactly two `SmartMotorController`s: a drive motor (velocity control, drives the wheel) and an azimuth motor (position control, steers the wheel). `SwerveModuleConfig`'s constructor takes both directly:

```java
SwerveModuleConfig moduleConfig = new SwerveModuleConfig(driveSMC, azimuthSMC);
SwerveModule fl = new SwerveModule(moduleConfig);
```

See [Swerve Drive's Basic Swerve Config](/documentation/understanding/swerve-drive#basic-swerve-config) for a full worked example with the rest of the chain filled in.

{% hint style="info" %}
There's also a no-arg `SwerveModuleConfig()` constructor paired with `withSmartMotorController(drive, azimuth)`, for cases where the config needs to exist before both motor controllers are ready. Calling `withSmartMotorController` twice on the same config throws an `IllegalStateException`, it's meant to be set exactly once.
{% endhint %}

```java
SwerveModuleConfig moduleConfig = new SwerveModuleConfig();
moduleConfig.withSmartMotorController(driveSMC, azimuthSMC);
```

## Absolute encoder wiring

Unlike an `Arm` or `Elevator`, a swerve azimuth motor has no safe "starting position" to assume, the wheel could be facing any direction when the robot powers on. That's why `SwerveModule` reads the absolute encoder and seeds the azimuth motor's relative encoder from it at construction time (`seedAzimuthEncoder()`), rather than requiring a homing routine.

`SwerveModuleConfig.withAbsoluteEncoder(...)` has two forms:

* Pass a same-vendor absolute encoder object directly, and YAMS wires it into the azimuth `SmartMotorControllerConfig` as an external feedback encoder. The azimuth config must also have `withUseExternalFeedbackEncoder(true)`.
* Pass a `Supplier<Angle>` (or `DoubleSupplier`) for any other absolute encoder, such as a CANcoder read through its own API on a non-CTRE azimuth motor.

A CANcoder feeding a `TalonFXWrapper` azimuth motor is same-vendor, so it can be passed directly. The azimuth motor's closed loop then runs on the CANcoder, so its config needs `withUseExternalFeedbackEncoder(true)`. Without it, `new SwerveModule(...)` throws a `SmartMotorControllerConfigurationException` (`External encoder cannot be used without external feedback`).

```java
CANBus canBus = new CANBus(CANPort.CAN_S0);
CANcoder canCoder = new CANcoder(3, canBus);

SmartMotorControllerConfig azimuthCfg = new SmartMotorControllerConfig(this)
      .withClosedLoopController(4, 0, 0)
      .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
      .withGearing(new MechanismGearing(12.8))
      // Required with a same-vendor absolute encoder: SwerveModule throws without it.
      .withUseExternalFeedbackEncoder(true);
SmartMotorController azimuthSMC = new TalonFXWrapper(new TalonFX(2, canBus), DCMotor.getKrakenX60(1), azimuthCfg);

SwerveModuleConfig moduleConfig = new SwerveModuleConfig(driveSMC, azimuthSMC)
      .withAbsoluteEncoder(canCoder)
      .withAbsoluteEncoderOffset(Rotations.of(0.25)); // the encoder's reading with the wheel forward, bevel left

// withAbsoluteEncoder and withAbsoluteEncoderOffset change azimuthCfg, so apply it again.
azimuthSMC.applyConfig(azimuthCfg);
```

You can also set the external encoder inside the azimuth config yourself, which also lets you set its other options. `withExternalEncoderZeroOffset(...)` is read back with `getExternalEncoderZeroOffset()` (formerly `getZeroOffset()`).

```java
SmartMotorControllerConfig azimuthCfg = new SmartMotorControllerConfig(this)
      .withExternalEncoder(canCoder)
      .withExternalEncoderZeroOffset(Rotations.of(0.25))
      .withExternalEncoderInverted(true)
      .withClosedLoopController(50, 0, 0.5)
      .withContinuousWrapping(Rotations.of(-0.5), Rotations.of(0.5))
      .withUseExternalFeedbackEncoder(true);

SmartMotorController azimuthSMC = new TalonFXWrapper(new TalonFX(2, canBus), DCMotor.getKrakenX60(1), azimuthCfg);

SwerveModuleConfig moduleConfig = new SwerveModuleConfig(driveSMC, azimuthSMC);
```

`withContinuousWrapping` makes the CANcoder read -180° to 180° and lets the azimuth take the shortest way round. `withUseExternalFeedbackEncoder(true)` makes the azimuth's closed-loop controller run on the absolute encoder all the time. Whenever the azimuth config has an external encoder, `SwerveModule` requires it, and throws if it is missing. To read an absolute encoder only once at startup and run the closed loop on the motor's own encoder, use the `Supplier<Angle>` form below instead: the module seeds the motor's encoder from it with `seedAzimuthEncoder()`.

A CANcoder feeding a REV azimuth motor is a different vendor, so it goes through the `Supplier<Angle>` form instead:

```java
.withAbsoluteEncoder(canCoder.getAbsolutePosition().asSupplier())
.withAbsoluteEncoderOffset(Rotations.of(0.25)) // bevel-left zero offset
```

`getAbsoluteEncoderAngle()` returns the angle with gearing and offset applied, the value actually used for seeding and optimization. `getRawAbsoluteEncoderAngle()` returns the same reading with no offset or gearing conversion applied, and the module publishes it as `encoder`: that raw reading, taken with the wheel forward and the bevel gear left, is the offset. [Step 5: On the real robot](/documentation/tutorials/swerve-drive/real-robot#set-the-absolute-encoder-offsets) walks through it.

```java
Angle angle = moduleConfig.getAbsoluteEncoderAngle();
Angle raw = moduleConfig.getRawAbsoluteEncoderAngle().get();
```

## Optimization and cosine compensation

Two `SwerveModuleConfig` flags exist purely to make a module track its setpoint more efficiently:

* `withOptimization(true)` optimizes each state like WPILib's `SwerveModuleVelocity.optimize(...)`, so a module never rotates more than 90 degrees to reach a target heading (it reverses the drive direction instead of steering the long way around). `SwerveDriveConfig.withModuleStateOptimization(boolean)` overrides this flag on every module of a drive at once, even while it is running.
* `withCosineCompensation(true)` scales the commanded drive velocity by the cosine of the angle error between the module's current heading and its desired heading, so a module that hasn't finished rotating yet doesn't also try to drive at full speed in the wrong direction.

```java
moduleConfig.withOptimization(true)
            .withCosineCompensation(true);
```

Both are safe to leave enabled for essentially every swerve module; they exist as flags mainly so you can disable them while debugging module behavior in isolation. `SwerveModuleConfig.getOptimizedState(...)` is what `SwerveModule.setSwerveModuleState(...)` calls every loop to apply both before commanding the motors.

### The flip-decision feedback loop

When optimization is enabled, the module decides every loop whether to flip 180 degrees (and reverse the drive) or steer straight to the target.

Kinematics recomputes the raw desired angle from scratch every loop with no memory of a prior flip, and a wheel that is still turning can sit near 90 degrees from both orientations of a target that keeps moving, such as a path starting off in a new direction. Choosing by the measured angle alone would reverse the wheel back and forth. `SwerveModuleConfig` therefore remembers `lastCommandedAngle`, the orientation it last actually sent, and keeps that orientation unless the other one is better by more than 30 degrees of hysteresis (see `SwerveModuleVelocityWithAzimuth.optimize(...)`). That avoids the module chattering between two headings.

## Velocity deadband

`SwerveModuleConfig.withVelocityDeadband(LinearVelocity)` sets a wheel speed at or below which the module stops and holds its current angle, instead of steering to the angle the kinematics ask for. The default is 0.1 m/s.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-6bc6f47053991731658bd435d087157f1ad8b773%2Fswerve-velocity-deadband.gif?alt=media" alt="Animation of a wheel whose requested speed sweeps from 0 to 0.3 meters per second and back. While the request is inside the 0.1 meters per second deadband the commanded speed is zero and the wheel is stopped. Above it the commanded speed equals the request"><figcaption><p>Requested and commanded wheel speed with the default 0.1 m/s deadband.</p></figcaption></figure>

**Why it exists.** When the driver lets go of the stick the requested speed is nearly zero, and the direction of a nearly zero velocity is mostly noise. Without the deadband every module would keep steering to chase that noise, which looks like constant, pointless wheel chatter.

**What it costs.** The robot cannot move slower than the deadband:

| Requested wheel speed    | What the module does                       |
| ------------------------ | ------------------------------------------ |
| Above the deadband       | Drives at that speed and steers normally.  |
| At or below the deadband | Stops, and holds the angle it already has. |

That matters whenever the robot is meant to creep:

* **Lining up slowly by hand.** Gentle stick pushes do nothing until the request passes the deadband, then the robot starts with a small jump.
* **The end of auto-align or a path.** As a PID closes in on its target it asks for smaller and smaller speeds. Once they drop inside the deadband the wheels stop, and the robot can settle a little short of the target.
* **Slow turns.** Wheels closer to the center of rotation move slower, so they can fall inside the deadband while the others keep driving.

If the robot stops short or will not creep, lower the deadband. If the wheels twitch at rest, raise it. Pass `null` to turn it off and always steer.

```java
moduleConfig.withVelocityDeadband(MetersPerSecond.of(0.05));
```

The deadband does not apply when the drive locks its wheels with [`lockPose()`](/documentation/understanding/swerve-drive#locking-the-wheels-x-pattern): `SwerveModule.setAzimuthAngle(Rotation2d)` uses `SwerveModuleConfig.getLockedState(...)`, which turns the wheel to the lock angle at zero speed instead of holding it where it is. Azimuth [live tuning](/documentation/how-to-tuning/live-tuning/swerve-drive) turns the wheels the same way, through `SwerveDrive.setAzimuthAngles(Rotation2d)`.

## Steer to drive coupling

On most modules the drive gearing turns the wheel when the azimuth rotates, even with the drive motor still, so steering alone would drive the wheel and skew its speed and odometry. `withCouplingRatio(...)` compensates for this the same way the CTRE swerve API does: the drive setpoint includes the motion steering causes, and that motion is removed from the measured wheel speed and distance.

```java
moduleConfig.withCouplingRatio(3.5); // drive motor rotations per azimuth rotation, e.g. kCoupleRatio from CTRE Tuner X
```

`withCouplingRatio(GearBox)` takes the same ratio as a `GearBox` from the drive motor (input) to the azimuth (output). A ratio of `0` disables compensation.

## Module telemetry

`SwerveModuleConfig.withTelemetry(name, TelemetryVerbosity)` (or the `SwerveModuleTelemetryConfig` overload for finer control) is separate from the parent drive's telemetry, but `SwerveDrive` wires it up for you: `SwerveDriveTelemetry.setupTelemetry(...)` calls `SwerveModule.setupTelemetry(driveName)` for every module, which nests each module's NetworkTables entries under `Mechanisms/<driveName>/modules/<moduleName>`.

`SwerveModuleTelemetryConfig` publishes two fields:

| Field                                               | NetworkTables key | `LOW` | `MID` | `HIGH` |
| --------------------------------------------------- | ----------------- | :---: | :---: | :----: |
| Absolute encoder angle, raw (no offset), in degrees | `encoder`         |   ✓   |   ✓   |    ✓   |
| SwerveModuleVelocity                                | `state`           |       |       |    ✓   |

See [Telemetry](/documentation/understanding/telemetry) for how struct-encoded fields and verbosity presets work across YAMS generally.

### Using `SwerveModuleTelemetryConfig` directly

Pass a `SwerveModuleTelemetryConfig` instead of a verbosity level when you need to route a single module's telemetry somewhere specific, such as nesting its DataLog entries under the same prefix as the parent drive:

```java
SwerveModuleTelemetryConfig telemetryCfg =
    new SwerveModuleTelemetryConfig(TelemetryVerbosity.HIGH)
        .withDataLogName("swerve/modules/frontleft");

SwerveModuleConfig moduleConfig = new SwerveModuleConfig(driveSMC, azimuthSMC)
      .withAbsoluteEncoder(encoder.getAbsolutePosition().asSupplier())
      .withLocation(Meters.of(0.3), Meters.of(0.3))
      .withOptimization(true)
      .withTelemetry("frontleft", telemetryCfg);
```

`SwerveModuleTelemetryConfig(TelemetryVerbosity)` is a shorthand constructor equivalent to `new SwerveModuleTelemetryConfig().withTelemetryVerbosity(verbosity)`.

## How SwerveDrive uses each module

`SwerveDrive` computes one `SwerveModuleVelocity[]` per loop from the requested `ChassisVelocities` via kinematics, then calls `setSwerveModuleState(...)` on each module. That call is also where [optimization and cosine compensation](#optimization-and-cosine-compensation) are actually applied, so the state `SwerveDrive` asked for and the state a module actually drives to can differ slightly by design.

## Code reference

{% @github-files/github-code-block url="<https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/simple_robot-2027/src/main/java/first/robot/subsystems/SwerveSubsystem.java>" %}


# When mechanism commands end

Why run() never ends, why runTo() does, and how both work with a default command.

Every YAMS mechanism gives you three kinds of command: `run` (also called `setAngle` or `setHeight`), `runTo`, and `set` with `setVoltage`. They differ in one way that matters a lot: when they end. This page explains that, and what happens to the motor and to your default command afterwards. The full list of commands for each mechanism is in [Controlling a mechanism](/documentation/reference/controlling-a-mechanism).

You need to know what a command and a default command are. [WPILib's command-based docs](https://docs.wpilib.org/en/stable/docs/software/commandbased/index.html) cover both.

## Three kinds of command

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-3fadf4560c9eaad8dd912329ba84d272841fdef5%2Fmech-commands.png?alt=media" alt="Three timelines starting when the command is scheduled. run(setpoint), also called setAngle or setHeight, runs until something else takes the mechanism and holds the setpoint the whole time. runTo(setpoint, tolerance) ends when the mechanism is within the tolerance, and then the default command takes over. set(dutycycle) and setVoltage(volts) are open loop with no PID, run until interrupted, and the closed loop controller comes back when they end."><figcaption><p>When each kind of command ends.</p></figcaption></figure>

| Command                        | Control                    | Ends                                                        | Good for                                         |
| ------------------------------ | -------------------------- | ----------------------------------------------------------- | ------------------------------------------------ |
| `run(target)`                  | Closed loop                | Never. Something else has to interrupt it.                  | Default commands, `whileTrue` buttons, tracking  |
| `runTo(target, tolerance)`     | Closed loop                | When the mechanism has been within the tolerance for 0.1 s. | Steps in a sequence, one press to go to a preset |
| `set(dutyCycle)`, `setVoltage` | Open loop, closed loop off | Never. Something else has to interrupt it.                  | Rollers, resting a mechanism, manual control     |

All three require the mechanism's subsystem, so starting one interrupts whichever was running. Every closed loop command starts the closed loop when it begins. `set` and `setVoltage` stop it when they begin and start it again when they end.

With a supplier, `run(Supplier)` follows the target forever, and `runTo(Supplier, tolerance)` follows it until the mechanism has caught up with the supplier's latest value.

## The motor keeps its last request

Ending a command does not stop the motor. The `SmartMotorController` keeps doing the last thing it was asked: after `runTo(Meters.of(1.0), ...)` ends, the elevator keeps holding 1 meter. That is on purpose, so a mechanism does not go limp between one step of a sequence and the next.

So when a command ends, the question is never "does the motor stop?" but "what runs next?". If nothing does, the mechanism holds. If the subsystem has a default command, that runs next.

## runTo and the default command

The examples below use two command factories on the subsystem:

{% tabs %}
{% tab title="Commands v2" %}

```java
// In ElevatorSubsystem. elevator here is the YAMS Elevator field.
public Command hold(Distance height)
{
  return elevator.setHeight(height); // never ends
}

public Command moveTo(Distance height)
{
  return elevator.runTo(height, Centimeters.of(2)); // ends when it gets there
}
```

{% endtab %}

{% tab title="Commands v3" %}

```java
// In ElevatorMechanism. elevator here is the YAMS Elevator field.
public Command hold(Distance height)
{
  return run(coroutine -> coroutine.await(elevator.setHeight(height)))
      .withPriority(Command.LOWEST_PRIORITY) // so any other command can take over
      .named("Elevator Hold");
}

public Command moveTo(Distance height)
{
  return elevator.runTo(height, Centimeters.of(2)); // ends when it gets there
}
```

{% endtab %}
{% endtabs %}

This is the most common surprise. A default command that holds the bottom, and a button that moves to the top:

```java
// In RobotContainer (Commands v2) or Robot (Commands v3). elevator is the subsystem.
elevator.setDefaultCommand(elevator.hold(Meters.of(0)));
controller.a().onTrue(elevator.moveTo(Meters.of(1.0)));
```

You press A. The elevator rises to 1 meter, `runTo` ends, the default command starts, and the elevator goes straight back down. Nothing is broken: `runTo` did its job and ended, and then the default command did its job. Pick the fix that matches what you want the robot to do.

### Solution 1: stay there, with run

If the elevator should stay at the target until another button moves it, use the command that never ends. The default command only comes back once nothing else is running.

```java
controller.a().onTrue(elevator.hold(Meters.of(1.0)));
```

### Solution 2: no default command

If the elevator should hold wherever it was last sent, do not give it a default command. When `runTo` ends nothing else runs, and the motor keeps holding the last target.

```java
// No setDefaultCommand for the elevator
controller.a().onTrue(elevator.moveTo(Meters.of(0.5)));
controller.b().onTrue(elevator.moveTo(Meters.of(1.0)));
```

### Solution 3: only while the button is held

If the elevator should go home whenever the driver lets go, hold the target while the button is held. The default command takes over on release.

```java
elevator.setDefaultCommand(elevator.hold(Meters.of(0)));
controller.a().whileTrue(elevator.hold(Meters.of(1.0)));
```

## runTo in a sequence

`runTo` is the command to use when the next step must wait for the mechanism.

{% tabs %}
{% tab title="Commands v2" %}

```java
// In RobotContainer. elevator, arm and intake are subsystems with the command factories
// elevator.moveTo(Distance), arm.moveTo(Angle) and intake.eject(), as on their pages.
public Command scoreHigh()
{
  return Commands.sequence(
      elevator.moveTo(Meters.of(1.2)),   // ends at 1.2 m, and keeps holding it
      arm.moveTo(Degrees.of(45)),        // ends at 45 degrees
      intake.eject().withTimeout(0.5),   // eject() never ends, so give it a time
      arm.moveTo(Degrees.of(0)),
      elevator.moveTo(Meters.of(0)));
}
```

A sequence requires every subsystem in it until the whole sequence ends, so no default command runs between the steps.
{% endtab %}

{% tab title="Commands v3" %}

```java
// In Robot. elevator, arm and intake are mechanisms with the command factories
// elevator.moveTo(Distance), arm.moveTo(Angle) and intake.eject(), as on their pages.
public Command scoreHigh()
{
  return Command.requiring(elevator, arm).executing(coroutine -> {
    coroutine.await(elevator.moveTo(Meters.of(1.2)));  // ends at 1.2 m, and keeps holding it
    coroutine.await(arm.moveTo(Degrees.of(45)));       // ends at 45 degrees
    coroutine.awaitAny(intake.eject(), Command.waitFor(Seconds.of(0.5)).named("Eject Time"));
    coroutine.await(arm.moveTo(Degrees.of(0)));
    coroutine.await(elevator.moveTo(Meters.of(0)));
  }).named("Score High");
}
```

`Command.requiring(elevator, arm)` keeps both mechanisms for the whole sequence, so their default commands do not run between the steps. With `Command.noRequirements(...)` instead, each mechanism is only owned while its own step runs, and its default command takes over as soon as its `moveTo` ends.
{% endtab %}
{% endtabs %}

## Stopping the motor

To let the motor go, run `set(0)`. It stops the closed loop and outputs zero, and it never ends by itself, so it makes a good default command for a mechanism that should rest, such as a flywheel that should coast or [an arm with a brake](/documentation/understanding/arms#arms-with-a-brake). When another command takes over, `set(0)` ends and starts the closed loop again, and the new command sets its own target.

You can also call `setDutyCycleSetpoint(0)` at the end of your own command. The motor rests until the next closed loop command, which starts the closed loop when it begins.

{% hint style="warning" %}
When `set` or `setVoltage` ends, the closed loop starts again and drives toward the last closed loop target, if there was one. So `set(0).withTimeout(1)` on a flywheel that was at 4000 RPM spins it back up after a second, unless another command takes over. Use `set(0)` as a default command, or follow it with the command you want next.
{% endhint %}

## Which one do I use?

```
Should the motor be off, or only get a voltage?
└── Yes → set() or setVoltage()
Should the command end by itself?
├── No → run()  (default commands, whileTrue buttons, tracking a target)
└── Yes → runTo()
    └── Does the subsystem have a default command?
        ├── No → fine: the mechanism holds where it stopped
        └── Yes → Is it fine for the default command to take over when runTo() ends?
            ├── Yes → fine (inside a sequence, it does not take over until the end)
            └── No → Solution 1, 2 or 3 above
```

## Common pitfalls

| Pitfall                                          | What you see                                        | Fix                                                                 |
| ------------------------------------------------ | --------------------------------------------------- | ------------------------------------------------------------------- |
| `runTo` with a default command                   | The mechanism reaches the goal, then goes back      | Solution 1, 2 or 3                                                  |
| `run` as a step in a sequence                    | The sequence never gets past that step              | Use `runTo` for steps that must end                                 |
| Expecting the motor to stop when a command ends  | The mechanism keeps holding, or keeps spinning      | Run `set(0)` when you want it off                                   |
| Tolerance smaller than the error that remains    | `runTo` never ends                                  | Widen the tolerance, or tune the mechanism so it settles closer     |
| Tolerance too tight for a mechanism that wobbles | `runTo` never ends, or takes a long time            | Widen it: the 0.1 s only counts while the mechanism stays inside it |
| `Command.noRequirements` sequence in Commands v3 | Each mechanism's default command runs between steps | Use `Command.requiring(...)` for the mechanisms the sequence moves  |

## Best practices

1. Make default commands never end: `run`, or `set(0)` for a mechanism that should rest. In Commands v3, also give them `Command.LOWEST_PRIORITY`.
2. Pair `whileTrue` with `run`.
3. Use `runTo` for each step of a sequence that must finish before the next.
4. For each `runTo`, decide what should run after it, and check the default command does that.
5. Test what happens when a command ends, not only while it runs.

## Next

To write a command that the built-in ones do not cover, see [How do I write my own mechanism command?](/documentation/how-to-mechanisms/how-do-i-write-my-own-mechanism-command)


# Sensors

Wrap a beam break, limit switch or other sensor so your code can read it in simulation as well as on the robot.

YAMS simulates your mechanisms well, but most sensors have no simulation of their own: in simulation a beam break never breaks and a limit switch is never pressed. A YAMS `Sensor` fixes that.

## What is a `Sensor`?

A `Sensor` wraps a real sensor on your robot, such as a beam break, a limit switch, a `CANrange`, a `LaserCAN` or a `CanandColor`. It has one or more named **fields**, and each field reads a value from the real sensor. In simulation you can also say what each field should read, and when: while the match time (the time left in the period, counting down) is in a window, or while a condition is true, such as the arm being at the angle where it breaks the beam.

Fields hold `boolean`, `int`, `long` or `double` values.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-f1d9f87dc66eb6f8bc4725bcc486c062f97b655d%2Fsensor-value-source.png?alt=media" alt="Two panels. On the real robot, getAsBoolean returns the real sensor reading from the supplier you gave, and simulated values are ignored. In simulation, the first simulated value whose condition is true is returned. Otherwise the value shown in the Sim GUI is returned, which starts as the default and can be changed by hand or with getField and set."><figcaption><p>Your code makes the same call on the real robot and in simulation.</p></figcaption></figure>

## How do I create a `Sensor`?

Build it with a `SensorConfig`, which takes the sensor's name, then a field for each value it reports.

{% hint style="warning" %}
Declare the `Sensor` field after every field its lambdas use, such as the `DigitalInput`, the motor and the mechanism. Java does not let a field's initializer use a field declared after it, even inside a lambda.
{% endhint %}

```java
import static org.wpilib.units.Units.Degrees;
import static org.wpilib.units.Units.Seconds;

import org.wpilib.hardware.discrete.DigitalInput;
import yams.core.mechanisms.config.SensorConfig;
import yams.core.motorcontrollers.simulation.Sensor;

// Fields of your subsystem, after the arm field
private final DigitalInput dio = new DigitalInput(0);
private final Sensor coralSensor = new SensorConfig("CoralDetectorBeamBreak") // the sensor's name
    .withField("Beam", dio::get, false)                              // field "Beam" reads dio.get(), default false
    .withSimulatedValue("Beam", Seconds.of(3), Seconds.of(4), true)  // in simulation, true from 4 s left until 3 s left in the period
    .withSimulatedValue("Beam", () -> arm.isNear(Degrees.of(40), Degrees.of(2)), true) // and while the arm is near 40 degrees
    .getSensor();
```

Reading through a `Sensor` is a little slower than reading the input directly. For a beam break or a limit switch that does not matter.

## How do I add simulated values to a sensor?

You can add a simulated value to a `Sensor` you already have with `addSimTrigger(field, value, condition)`. The value is a `HALValue` (`org.wpilib.hardware.hal.HALValue`), for example `HALValue.makeBoolean(true)`.

```java
// Fragment: coralSensor is the Sensor above, without its second withSimulatedValue
coralSensor.addSimTrigger("Beam", HALValue.makeBoolean(true),
                          () -> arm.isNear(Degrees.of(40), Degrees.of(2))); // true while the arm is near 40 degrees
```

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-4d892425b01ade12b02db8c6a0c4ab6d64fda9ab%2Fsensor-sim-values.gif?alt=media" alt="Animation of the Beam field of a beam break sensor in simulation, false by default. It turns true while the arm is within 2 degrees of 40 degrees, turns false when the arm moves on, turns true again while the match time is between 3 and 4 seconds, and then goes back to false."><figcaption><p>The field reads true while either simulated value is true, and goes back to what it was when neither is.</p></figcaption></figure>

## What does this look like?

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2FxZnE2jTxxjCEg91Q7rhP%2Fimage.png?alt=media&amp;token=bc957101-6b79-4283-a53b-a4e1069017aa" alt="The simulation GUI with the Other Devices panel open. Below the SPARK MAX entries is a Sensor[CoralDetectorBeamBreak] entry, circled in red, with its Beam field reading false in a drop-down that can be changed by hand."><figcaption><p>The sensor's fields appear under Other Devices in the simulation GUI.</p></figcaption></figure>

The circled value turns true while the arm is within 2° of 40°. You can also change it by hand in the simulation GUI.

## How do I use the value from a `Sensor`?

{% hint style="warning" %}
A simulated value only updates when your code reads the sensor. Read it every loop, for example from a `Trigger` or `periodic()`, or its simulated values never take effect.
{% endhint %}

Read the field from the `Sensor`, not from the input it wraps:

```java
public boolean getBeamBreak()
{
  // return dio.get(); // does not see the simulated values
  return coralSensor.getAsBoolean("Beam");
}
```

`getAsInt`, `getAsLong` and `getAsDouble` read the other kinds of field.

## How do I simulate the sensor value?

You can set a field by hand: get it with `getField` and call `set`. The new value stays until it is changed again, from the simulation GUI or with `set`.

{% hint style="info" %}
This only changes the value in simulation. It does not affect the real sensor on the robot.
{% endhint %}

{% tabs %}
{% tab title="Commands v2" %}

```java
public void setBeamBreakWhenArmIsLow()
{
  arm.lte(Degrees.of(10)).onTrue(Commands.runOnce(() -> coralSensor.getField("Beam").set(true)));
}
```

{% endtab %}

{% tab title="Commands v3" %}

```java
public void setBeamBreakWhenArmIsLow()
{
  arm.lte(Degrees.of(10)).onTrue(Command.noRequirements(coroutine -> coralSensor.getField("Beam").set(true))
                                        .named("Set Beam Break"));
}
```

{% endtab %}
{% endtabs %}

## How do I simulate a sensor the mechanism triggers?

Some sensors are triggered by the mechanism itself, like a limit switch at a hard stop, or a beam break the arm passes through. Simulate those from where the simulated mechanism really is, rather than from what its encoder says. The motor's sim supplier (`SmartMotorController.getSimSupplier()`) has the simulated mechanism's position. It is empty on a real robot, so the condition is `false` there.

```java
// Fields of ArmSubsystem, after motor
private final DigitalInput lowerSwitchInput = new DigitalInput(4);
private final Sensor lowerSwitch = new SensorConfig("ArmLowerSwitch")
    .withField("Pressed", lowerSwitchInput::get, false)
    // Pressed while the simulated arm is within 0.05° of its lower hard stop at -30°.
    .withSimulatedValue("Pressed", () -> motor.getSimSupplier()
        .map(sim -> sim.getMechanismPosition().lte(Degrees.of(-29.95)))
        .orElse(false), true)
    .getSensor();
```

For an elevator, convert the simulated position to a height with the motor controller's config: `smcConfig.convertFromMechanism(sim.getMechanismPosition())`.

A real limit switch is pressed by the mechanism, not by its encoder. If the encoder is off, say after a belt skips, a switch simulated from the encoder (`arm.isNear(...)`) is pressed in the wrong place. One simulated from the sim supplier is pressed at the hard stop, as the real one is.

A SystemCore Smart IO port reads `true` while a normally open switch, wired between the signal and power pins, is pressed. So the field is `input::get`, not `!input.get()`.

## Next

To reset the encoder each time a limit switch is pressed, see [How do I home a mechanism with limit switches?](/documentation/how-to-mechanisms/how-do-i-home-a-mechanism-with-limit-switches) [YAMG](https://yamg.yassrobotics.com) generates the sensor and the homing code when you turn on **Homing**.


# Simulation-only PID + feedforward

A simulated mechanism is an ideal motor and load: no friction, no backlash, no cable drag, and exactly the mass you told YAMS. A real mechanism has all of those. So the gains that hold a real arm usually do something different in simulation, and the other way round. `withSimClosedLoopController` and `withSimFeedforward` let you keep one set of gains for each, so tuning one never breaks the other.

## An example

An arm tuned on the real robot needed `kS = 0.15 V` to get past friction and `kG = 0.35 V` to hold it level. In simulation there is no friction, and the simulated arm is a little lighter than the real one with its wiring and bolts:

```java
.withClosedLoopController(4, 0, 0.2)                 // real robot
.withFeedforward(new ArmFeedforward(0.15, 0.35, 1.2)) // real robot: kS, kG, kV
.withSimClosedLoopController(4, 0, 0.2)              // simulation: the same PID
.withSimFeedforward(new ArmFeedforward(0, 0.30, 1.2)) // simulation: no friction, a lighter arm
```

With the real `kS` in simulation, the arm would push 0.15 V harder than it needs to and overshoot every small move. With the real `kG`, it would creep upward when it should hold still. Each set is right for its own mechanism.

## When you need it

* **Leave them out at first.** Without them, simulation uses your real gains. That is fine while you are getting a mechanism moving.
* **Add them once the real robot is tuned**, if simulation then behaves worse than it did. Tune the simulation gains in simulation with [live tuning](/documentation/how-to-tuning/live-tuning), the same way as the real ones.
* **Do not tune the real robot in simulation.** Gains found in simulation are a starting point at best: [Step 5 of the Arm tutorial](/documentation/tutorials/arm/tune) tunes them on the robot.

[`withSimClosedLoopController` and `withSimFeedforward`](/documentation/reference/editor/config/simulation#withsimclosedloopcontroller-and-withsimfeedforward) list the options, including slots.


# Exponential profiles

For the short version, with one example, see [How do I use exponential profiles?](/documentation/how-to-motor-controllers-and-sensors/how-do-i-use-exponential-profiles) This page explains them fully and how to tune one.

## What is a motion profile?

A motion profile is a trajectory that defines how a mechanism should move from one position to another over time. Instead of commanding a mechanism to instantly jump to a target position (which would require infinite acceleration), motion profiles generate a smooth path that respects the physical limitations of your system.

Motion profiles output a series of intermediate setpoints (position and velocity) that your closed-loop controller tracks. This results in:

* **Predictable motion** - You know exactly how long a movement will take
* **Smooth transitions** - No jerky movements that stress mechanical components
* **Controlled acceleration** - Prevents excessive current draw and brownouts

## Trapezoidal vs exponential profiles

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-cd805259e0788a8a85c06cc806a53802c26af5ab%2Fexponential-profile-compare.png?alt=media" alt="Two graphs. Setpoint velocity over time: a trapezoidal profile ramps in a straight line to a flat top, an exponential profile rises quickly and curves over near top speed. Acceleration against speed: the motor&#x27;s available acceleration falls to zero at top speed, the exponential profile follows it, and the trapezoidal profile asks for a constant acceleration the motor cannot give at high speed"><figcaption><p>The two profiles, and why the motor can follow one more easily than the other.</p></figcaption></figure>

### Trapezoidal profiles

Trapezoidal profiles are the most common type. The name comes from the trapezoidal shape of the velocity-time graph.

**Key characteristics:**

* Constant acceleration until max velocity is reached
* Cruise at max velocity (if distance is long enough)
* Constant deceleration to stop at target
* Assumes unlimited torque during acceleration phases

**When trapezoidal profiles struggle:**

* When a disturbance knocks the mechanism off the profile
* When the motor cannot actually provide the commanded acceleration
* When current limiting reduces available torque

### Exponential profiles

Exponential profiles model how DC motors actually behave. Instead of assuming constant acceleration, they account for the motor's torque-speed curve and the system's physical dynamics.

**Key characteristics:**

* Acceleration naturally decreases as velocity increases (following motor physics)
* Models the mechanism with a kV (velocity constant) and a kA (acceleration constant)
* More accurately represents what the motor can actually achieve
* Better disturbance rejection

{% hint style="info" %}
Exponential profiles are named for the exponential approach to maximum velocity, which mirrors the natural response of a first-order system like a DC motor.
{% endhint %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-7d94af6bc3483cc22c0e4118b164f3b956505187%2Fexponential-profile-tracking.gif?alt=media" alt="Animation of a 12 volt motor following each profile. With the trapezoidal profile the measured velocity falls behind the setpoint as the speed rises and the motor saturates at 12 volts. With the exponential profile the measured velocity stays on the setpoint"><figcaption><p>A simulated 12 V motor following each profile. The trapezoidal profile asks for more than the motor has left at speed.</p></figcaption></figure>

## The physics behind exponential profiles

DC motors produce torque proportional to current. However, as the motor spins faster, back-EMF reduces the effective voltage across the windings, which reduces current and therefore torque.

The relationship is:

$$V = kS + kV \cdot \omega + kA \cdot \alpha$$

Where:

* **V** = Applied voltage
* **kS** = Static friction voltage (voltage to overcome stiction)
* **kV** = Velocity constant (volts per unit velocity)
* **kA** = Acceleration constant (volts per unit acceleration)
* **ω** = Angular velocity
* **α** = Angular acceleration

Rearranging for acceleration:

$$\alpha = \frac{V - kS - kV \cdot \omega}{kA}$$

This shows that as velocity (ω) increases, the available acceleration (α) decreases. This is the fundamental insight that exponential profiles capture.

## When to use each profile type

| Situation                               | Recommended Profile      | Why                                                                                                                                                           |
| --------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Motor is always current-limited         | Trapezoidal              | Current limiting makes torque roughly constant regardless of speed                                                                                            |
| Motor is never current-limited          | Exponential              | Motor follows natural torque-speed curve                                                                                                                      |
| Sometimes current-limited               | Hybrid (not yet in YAMS) | See the [trapezoidal/exponential profiling whitepaper](https://www.chiefdelphi.com/t/whitepaper-trapezoidal-exponential-motion-profiling/443468/12?u=nstrike) |
| Heavy mechanism with adequate motor     | Exponential              | Gravity/friction dominate, exponential handles disturbances better                                                                                            |
| Lightweight mechanism                   | Either                   | Both work well when inertia is low                                                                                                                            |
| Mechanism with significant disturbances | Exponential              | Better recovery when knocked off profile                                                                                                                      |
| Precise timing required                 | Trapezoidal              | Deterministic duration calculation                                                                                                                            |

{% hint style="success" %}
**Rule of thumb:** start with a trapezoidal profile. If it works, keep it. Switch to an exponential profile when the mechanism falls behind a trapezoidal profile as it speeds up, or gets knocked off it. If the motor sits at its current limit for most of the move, stay with the trapezoidal profile.
{% endhint %}

## Exponential profiles in YAMS

YAMS provides `ExponentialProfilePIDController` (`yams.core.math.ExponentialProfilePIDController`), which combines an exponential motion profile with a PID controller and has factory methods for the profile's constraints. In a `SmartMotorControllerConfig` you set the PID gains with `withClosedLoopController(kP, kI, kD)` and the profile with `withExponentialProfile(constraints)`, instead of a trapezoidal profile (`withTrapezoidalProfile`) or no profile at all.

Exponential profiles in YAMS follow the same idea as CTRE's Motion Magic Expo, on every supported motor controller. CTRE's documentation is a good companion to this page:

{% embed url="<https://v6.docs.ctr-electronics.com/en/latest/docs/api-reference/device-specific/talonfx/motion-magic.html#motion-magic-expo>" %}

### What you set

An exponential profile is defined by a kV and a kA, and those are what you tune, exactly as CTRE's documentation describes. What YAMS adds is a way to get **starting values** for them without measuring anything: you give the **maximum voltage** and one of two descriptions of the mechanism, and YAMS works out a kV and a kA to start from:

| You give                                                                                        | YAMS works out the starting kV and kA from                                                  |
| ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| Maximum voltage, the motor, and the mechanism's moment of inertia (or its mass and drum radius) | The motor and the load it has to move                                                       |
| Maximum voltage, a maximum velocity and a maximum acceleration                                  | `kV = maximum voltage / maximum velocity` and `kA = maximum voltage / maximum acceleration` |

The second row is the same relationship [CTRE's Motion Magic Expo documentation](https://v6.docs.ctr-electronics.com/en/latest/docs/api-reference/device-specific/talonfx/motion-magic.html#motion-magic-expo) gives: dividing the voltage by kV gives the maximum velocity of the profile, and dividing it by kA gives its maximum acceleration from a standstill. CTRE's page is the best description of exponential profiles there is, and this page is meant to agree with it. If the two ever differ, CTRE's is right.

From there you adjust kV and kA directly, either [live](#refining-the-profile-live) or by passing your own with `ExponentialProfile.Constraints.fromCharacteristics(maxVoltage, kV, kA)`.

`SmartMotorControllerConfig` takes all of these directly:

```java
.withExponentialProfile(Volts.of(10), DCMotor.getKrakenX60(1), KilogramSquareMeters.of(0.5))  // arm or flywheel
.withExponentialProfile(Volts.of(10), DCMotor.getKrakenX60(2), Kilograms.of(8), Inches.of(1)) // elevator
.withExponentialProfile(Volts.of(10), RotationsPerSecond.of(2), RotationsPerSecondPerSecond.of(8))
```

### Creating constraints

YAMS provides factory methods to create exponential profile constraints for common mechanism types. These are fragments: `gearing` is your `MechanismGearing`, the same one you give `withGearing`.

#### For elevators

```java
ExponentialProfile.Constraints constraints = ExponentialProfilePIDController.createElevatorConstraints(
    Volts.of(12),        // Maximum voltage during profile
    DCMotor.getNEO(2),   // Motor type and quantity
    Pounds.of(15),       // Carriage mass
    Inches.of(1),        // Drum radius (or sprocket pitch radius)
    gearing              // MechanismGearing object
);
```

#### For arms

```java
ExponentialProfile.Constraints constraints = ExponentialProfilePIDController.createArmConstraints(
    Volts.of(12),        // Maximum voltage during profile
    DCMotor.getKrakenX60(1), // Motor type and quantity
    Pounds.of(8),        // Arm mass (at center of mass)
    Inches.of(18),       // Arm length (to center of mass)
    gearing              // MechanismGearing object
);
```

#### For flywheels

```java
ExponentialProfile.Constraints constraints = ExponentialProfilePIDController.createFlywheelConstraints(
    Volts.of(12),        // Maximum voltage during profile
    DCMotor.getFalcon500(1), // Motor type and quantity
    Pounds.of(2),        // Flywheel mass
    Inches.of(2),        // Flywheel radius
    gearing              // MechanismGearing object
);
```

#### Custom constraints

If the factory methods don't fit your use case, you can create constraints directly:

```java
ExponentialProfile.Constraints constraints = ExponentialProfilePIDController.createConstraints(
    Volts.of(12),                    // Maximum voltage
    RotationsPerSecond.of(100),      // Maximum velocity (kV derived)
    RotationsPerSecondPerSecond.of(200) // Maximum acceleration (kA derived)
);
```

### Using with SmartMotorControllerConfig

```java
SmartMotorControllerConfig config = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(30, 0, 0) // kP, kI, kD
    .withExponentialProfile(ExponentialProfilePIDController.createElevatorConstraints(
        Volts.of(12),
        DCMotor.getNEO(2),
        Pounds.of(15),
        Inches.of(1),
        gearing
    ))
    .withGearing(gearing)
    .withFeedforward(new ElevatorFeedforward(0, 0.5, 0, 0))
    .withTelemetry("Elevator", TelemetryVerbosity.HIGH);
```

## Tuning exponential profiles

Work through these steps in order. Each one depends on the one before.

### Step 1: Set the maximum voltage

The maximum voltage is the most the profile plans to use. Whatever is left over, up to the battery's 12 V, is what the PID has to correct with.

* **8 V:** gentle, a good first test on a real mechanism.
* **10 V:** leaves headroom for the PID. A good setting for most mechanisms.
* **12 V:** everything the battery has, with nothing left for corrections.

Start at 8 V or 10 V.

### Step 2: Add the feedforward

The profile only plans the move. It does not drive the motor: the voltage that follows the plan comes from the feedforward and the PID. So an exponential profile still needs a full feedforward:

* **kS** for friction.
* **kG** for gravity, on arms and elevators. The profile does not know about gravity.
* **kV and kA** for the speed and acceleration the profile asks for.

```java
// For an arm
.withFeedforward(new ArmFeedforward(
    0.1,  // kS - voltage to overcome friction
    0.3,  // kG - voltage to hold horizontal
    1.2,  // kV - voltage per unit of speed
    0.05  // kA - voltage per unit of acceleration
))

// For an elevator
.withFeedforward(new ElevatorFeedforward(
    0.1,  // kS - voltage to overcome friction
    0.2,  // kG - voltage to counteract gravity
    3.0,  // kV - voltage per unit of speed
    0.1   // kA - voltage per unit of acceleration
))
```

{% hint style="info" %}
**The profile's kV and kA are not the feedforward's kV and kA.** The profile's pair only shape the plan. The feedforward's pair turn that plan into voltage. CTRE's Motion Magic Expo example sets both, the gain slot's `kV` and `kA` and the profile's `MotionMagicExpo_kV` and `MotionMagicExpo_kA`, and YAMS keeps them separate in the same way. [Feedforward](/documentation/reference/editor/config/feedforward) covers finding the feedforward's values.
{% endhint %}

### Step 3: Get a starting kV and kA

Start with the maximum voltage and a description of the mechanism, and let YAMS work out a kV and a kA to begin with. Then tune them directly in [Refining the profile live](#refining-the-profile-live):

| Option                              | How                                                                                 | Good for                                                               |
| ----------------------------------- | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| The mechanism                       | The motor, with the moment of inertia or the mass and drum radius                   | A first version, and simulation                                        |
| A maximum velocity and acceleration | The fastest you want the profile to go, and the hardest you want it to accelerate   | Real mechanisms: both numbers are easy to see on a graph and to adjust |
| kV and kA, measured                 | One constant voltage test, see [Measuring kV and kA](#measuring-kv-and-ka-optional) | Starting closer to the real mechanism, so there is less to tune        |

{% hint style="info" %}
**Start slower than you think the mechanism can go.** CTRE's advice for Motion Magic Expo is that it is safer to start from a higher kV and kA than ideal, which is a profile with a lower maximum velocity and acceleration. So if the starting values are in doubt, raise kV and kA, or start from a lower maximum velocity and acceleration, and bring them down once the mechanism follows the profile well.
{% endhint %}

{% hint style="warning" %}
A description from the motor and the mass is theoretical. Real mechanisms have friction, cable drag and other losses, so expect to slow the profile down a little from what the numbers say.
{% endhint %}

### Measuring kV and kA (optional)

This is another way to get starting values, from the real mechanism instead of from a calculation. It needs only a button binding and a graph, and it gives you both from one run.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d44d1a2698b4e9170c46ba5b8fe11fa04ef85ac2%2Fexponential-profile-step-test.png?alt=media" alt="A graph of velocity after a constant 6 volts is applied. It levels off at 2.9 rotations per second, so kV is 6.0 minus kS, divided by 2.9, which is 2.0. It reaches 63 percent of that speed after 0.15 seconds, so kA is kV times 0.15, which is 0.30"><figcaption><p>One voltage step gives both constants. Example values.</p></figcaption></figure>

{% stepper %}
{% step %}

#### Find kS

Raise the voltage from zero in steps of about 0.05 V until the mechanism just starts to move. That voltage is kS. [Drive a motor at a voltage](/documentation/how-to-tuning/live-tuning#drive-a-motor-at-a-voltage) shows how to do it without writing code.
{% endstep %}

{% step %}

#### Apply a constant voltage

Bind a button to a fixed voltage, well below 12 V so the mechanism does not hit a hard stop before it reaches a steady speed:

```java
driver.a().whileTrue(flywheel.setVoltage(Volts.of(6)));
```

Graph `NT:/Mechanisms/<Mechanism>/<Motor>/mechanism/velocity` in AdvantageScope while you hold the button. Leave it in rotations per second: the profile's kV and kA are per rotation of the mechanism.
{% endstep %}

{% step %}

#### Read the steady speed: that gives kV

Once the line goes flat, read the speed.

`kV = (voltage - kS) / steady speed`
{% endstep %}

{% step %}

#### Read the time to 63%: that gives kA

Find the moment the velocity reached 63% of the steady speed, and how long after the voltage was applied that was.

`kA = kV x that time`
{% endstep %}

{% step %}

#### Put them in the config

```java
.withExponentialProfile(ExponentialProfile.Constraints.fromCharacteristics(
    10.0, // maximum voltage the profile may ask for
    2.0,  // kV, volts per rotation per second
    0.30  // kA, volts per rotation per second squared
))
```

{% endstep %}
{% endstepper %}

{% hint style="info" %}
**Gravity gets in the way of this test.** On an elevator, subtract kG as well: `kV = (voltage - kS - kG) / steady speed`. On an arm the pull of gravity changes with the angle, so the speed never settles: start from `createArmConstraints(...)` and refine it live instead.
{% endhint %}

### Refining the profile live

This is Step 4: tune the profile itself.

This is where the profile is actually tuned, by changing kV and kA directly. However you got the starting values, YAMS stores the profile as a maximum voltage, a kV and a kA, and all three can be changed while the robot is running.

{% stepper %}
{% step %}

#### Turn on live tuning

Give the motor `TelemetryVerbosity.HIGH` and start the `Live Tuning` command. [Live tuning](/documentation/how-to-tuning/live-tuning) covers both.
{% endstep %}

{% step %}

#### Graph the profile against the mechanism

In AdvantageScope, put these two on one graph:

* `NT:/Mechanisms/<Mechanism>/<Motor>/closedloop/setpoint/velocity`: what the profile asks for.
* `NT:/Mechanisms/<Mechanism>/<Motor>/mechanism/velocity`: what the mechanism does.
  {% endstep %}

{% step %}

#### Run a move

Command a move long enough for the mechanism to reach its top speed, and watch how closely the second line follows the first.
{% endstep %}

{% step %}

#### Tune `kA` on the way up

Look at the start of the move, while the mechanism is speeding up. If it falls behind the profile, raise `NT:/Tuning/<Mechanism>/<Motor>/closedloop/motionprofile/kA`. A higher `kA` lowers the profile's acceleration. Run the move again and repeat until it keeps up.
{% endstep %}

{% step %}

#### Tune `kV` at top speed

Look at the fastest part of the move. If the mechanism falls behind there, or never reaches the profile's top speed, raise `NT:/Tuning/<Mechanism>/<Motor>/closedloop/motionprofile/kV`. A higher `kV` lowers the profile's top speed.
{% endstep %}

{% step %}

#### Speed it up if there is room

If the mechanism follows the whole move easily with voltage to spare on `NT:/Mechanisms/<Mechanism>/<Motor>/motor/outputVoltage`, lower `kV` and `kA` a little at a time, or raise `NT:/Tuning/<Mechanism>/<Motor>/closedloop/motionprofile/maxInput`. Stop as soon as it starts to fall behind again, and go back one step.
{% endstep %}

{% step %}

#### Put the tuned values in the config

Live values are lost when the robot code restarts, so copy them into the config:

```java
.withExponentialProfile(ExponentialProfile.Constraints.fromCharacteristics(
    10.0, // maxInput: maximum voltage the profile may ask for
    2.2,  // kV, tuned
    0.35  // kA, tuned
))
```

{% endstep %}
{% endstepper %}

### Step 5: Tune the PID gains

With a good feedforward and a profile the mechanism can follow, the PID only fixes what is left over.

* **kP:** corrects position error. Start from the [starting values](/documentation/reference/editor/config/closed-loop-control#withclosedloopcontroller), such as 10 V per meter on an elevator, and double it until the mechanism settles quickly on the setpoint without ringing.
* **kD:** damps oscillation. Add a little if the mechanism rings around the target.
* **kI:** usually not needed with a good feedforward. Check `kG` and `kS` first if it stops short.

## Motor controller support

| Motor Controller         | Trapezoidal Profile                         | Exponential Profile           | Notes                              |
| ------------------------ | ------------------------------------------- | ----------------------------- | ---------------------------------- |
| TalonFX (Kraken, Falcon) | On-device (Motion Magic)                    | On-device (Motion Magic Expo) | Best performance                   |
| TalonFXS                 | On-device (Motion Magic)                    | On-device (Motion Magic Expo) | Best performance                   |
| SparkMax/SparkFlex       | On-device (MAXMotion)                       | SystemCore                    | Exponential runs on the SystemCore |
| Thrifty Nova             | On-device (position), SystemCore (velocity) | SystemCore                    | Exponential runs on the SystemCore |
| FIRST A301               | SystemCore                                  | SystemCore                    | Every loop runs on the SystemCore  |

{% hint style="info" %}
When exponential profiles run on the SystemCore, there's slightly more latency compared to on-device execution. However, the profile calculation is still very fast and suitable for most mechanisms.
{% endhint %}

## Common issues and solutions

### Profile is too slow

* Increase maximum voltage
* Check that your mechanism parameters (mass, length, gearing) are accurate
* Verify motor type matches actual hardware

### Profile overshoots target

* Decrease kP
* Add kD for damping
* Slow the profile down: a profile that asks for more than the mechanism can do overshoots

### Mechanism can't keep up with profile

* Your motor may be undersized for the mechanism
* Reduce maximum voltage
* Check for mechanical binding or excessive friction

### Profile works in sim but not on real robot

* Slow the profile down: lower the maximum velocity and acceleration, or see [Refining the profile live](#refining-the-profile-live)
* Account for friction with kS in feedforward
* Check current limits aren't restricting torque

## Example: Complete Elevator with exponential profile

```java
public class ElevatorSubsystem extends SubsystemBase {

    private final Distance chainPitch = Inches.of(0.25);
    private final int toothCount = 22;
    private final Mass carriageMass = Pounds.of(15);
    private final DCMotor motors = DCMotor.getNEO(2);
    private final MechanismGearing gearing = new MechanismGearing(GearBox.fromReductionStages(5, 4));

    private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
        .withControlMode(ControlMode.CLOSED_LOOP)
        .withDrumRadius(chainPitch, toothCount)
        .withClosedLoopController(15, 0, 0)
        .withExponentialProfile(ExponentialProfilePIDController.createElevatorConstraints(
            Volts.of(10), // Conservative voltage for testing
            motors,
            carriageMass,
            chainPitch.times(toothCount).div(2 * Math.PI),
            gearing
        ))
        .withSimClosedLoopController(15, 0, 0)
        .withFeedforward(new ElevatorFeedforward(0.1, 0.25, 0, 0))
        .withSimFeedforward(new ElevatorFeedforward(0, 0.2, 0, 0))
        .withGearing(gearing)
        .withZeroPower(MotorMode.BRAKE)
        .withStatorCurrentLimit(Amps.of(40))
        .withSoftLimits(Meters.of(0), Meters.of(1.2))
        .withStartingPosition(Meters.of(0))
        .withTelemetry("ElevatorMotor", TelemetryVerbosity.HIGH);

    private final SparkMax leftSpark = new SparkMax(CANPort.CAN_S0, 1, MotorType.kBrushless);
    private final SparkMax rightSpark = new SparkMax(CANPort.CAN_S0, 2, MotorType.kBrushless);
    
    private final SmartMotorController motor = new SparkWrapper(
        leftSpark, 
        motors, 
        motorConfig.withFollowers(Pair.of(rightSpark, true))
    );

    private final Elevator elevator = new Elevator(
        new ElevatorConfig()
            .withHardLimits(Meters.of(-0.05), Meters.of(1.3))
            .withCarriageWeight(carriageMass)
            .withTelemetry("Elevator", TelemetryVerbosity.HIGH),
        motor
    );

    public Command goToHeight(Distance height) {
        return elevator.setHeight(height);
    }

    @Override
    public void periodic() {
        elevator.updateTelemetry();
    }

    @Override
    public void simulationPeriodic() {
        elevator.simIterate();
    }
}
```

## Further reading

* [CTRE Motion Magic Expo Documentation](https://v6.docs.ctr-electronics.com/en/latest/docs/api-reference/device-specific/talonfx/motion-magic.html#motion-magic-expo) - CTRE's explanation of exponential profiles
* [How do I use Exponential Profiles?](/documentation/how-to-motor-controllers-and-sensors/how-do-i-use-exponential-profiles) - Quick how-to guide
* [Trapezoidal/Exponential Motion Profiling Whitepaper](https://www.chiefdelphi.com/t/whitepaper-trapezoidal-exponential-motion-profiling/443468/12?u=nstrike) - Advanced hybrid profiling techniques
* [WPILib Tuning Guide](https://docs.wpilib.org/en/stable/docs/software/advanced-controls/introduction/tuning-turret.html) - General PID and feedforward tuning


# LQR controllers

## What is LQR?

**Linear Quadratic Regulator (LQR)** is an optimal control algorithm that automatically computes controller gains to minimize a cost function balancing state error and control effort. Unlike manually-tuned PID controllers, LQR uses a mathematical model of your system to determine the optimal feedback gains.

{% hint style="info" %}
**Key Difference from PID**: With PID, you manually tune kP, kI, and kD through trial and error. With LQR, you specify *how much you care* about position error vs velocity error vs control effort, and the algorithm computes the optimal gains for you.
{% endhint %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-36a2eeaca2409aacf20b44b4110867789f54f01b%2Flqr-loop.png?alt=media" alt="Before the match, your model of the motor, gearing and moment of inertia, together with your error tolerances and control effort, go into LQR, which computes feedback gains. Every 20 milliseconds on the SystemCore, the encoder reading passes through a Kalman filter, the gains multiply the error between the setpoint and the estimate, and the result is the motor voltage"><figcaption><p>You supply the model and the priorities. LQR supplies the gains.</p></figcaption></figure>

## Why use LQR?

### Advantages

1. **Model-Based Tuning**: LQR uses your mechanism's physical model (mass, gearing, motor characteristics) to compute gains, reducing trial-and-error tuning
2. **Multi-State Control**: Naturally handles both position and velocity simultaneously
3. **Optimal Performance**: Mathematically minimizes a cost function you define
4. **Consistent Behavior**: Gains are derived from physics, making them more predictable across different setpoints

### When to consider LQR

* **Complex mechanisms** where PID tuning is difficult
* **High-performance requirements** where optimal response matters
* **Educational settings** where understanding control theory is valuable
* **Mechanisms with well-characterized models** (accurate mass, inertia, motor constants)

### When PID may be better

* **Simple mechanisms** that tune easily with PID
* **Limited modeling data** (unknown mass, inertia, etc.)
* **Quick prototyping** where tuning time is limited
* **Mechanisms with significant nonlinearities** that LQR's linear model can't capture

## LQR execution in YAMS

{% hint style="warning" %}
**Important**: LQR controllers are **not natively supported** by any motor controller hardware. When you configure an LQR controller in YAMS, the closed loop control **always runs on the SystemCore**. The wrapper starts a `Notifier` that calls `SmartMotorController.iterateClosedLoopController()` every closed loop control period (20 ms by default), so you never call it yourself.
{% endhint %}

### Why SystemCore-Only?

Motor controller vendors (CTRE, REV, ThriftyBot) implement PID controllers on their hardware, but none support LQR natively. LQR requires:

1. Matrix operations (solving Riccati equations)
2. State-space model storage
3. Kalman filter state estimation
4. Multi-state feedback computation

These operations are beyond what current motor controller firmware supports.

### Performance implications

| Aspect          | Motor Controller PID       | SystemCore LQR                     |
| --------------- | -------------------------- | ---------------------------------- |
| **Update Rate** | 1kHz+ (on controller)      | 50Hz (20 ms `Notifier`) by default |
| **Latency**     | Minimal (\~1ms)            | CAN bus round-trip (\~5-20ms)      |
| **CPU Load**    | None on SystemCore         | Small increase on SystemCore       |
| **Best For**    | Fast loops, simple control | Complex control, slower mechanisms |

{% hint style="info" %}
For most FRC mechanisms (arms, elevators), the 50Hz update rate is sufficient. LQR's optimal gains often compensate for the slower update rate compared to motor controller PID.
{% endhint %}

## Configuring LQR in YAMS

In YAMS, you create an `LQRConfig` to specify your mechanism type and tuning parameters, then create an `LQRController` from that config, and finally pass it to `SmartMotorControllerConfig.withClosedLoopController()`.

### LQRConfig overview

`LQRConfig` requires three core parameters:

* **DCMotor**: The motor model (e.g., `DCMotor.getKrakenX60(1)`)
* **MechanismGearing**: Your gear reduction
* **MomentOfInertia**: The rotational inertia of your mechanism. An elevator does not use it: its model comes from the carriage mass and drum radius you give `withElevator`. The constructor still needs a value, so pass any, such as `KilogramSquareMeters.of(0.01)`.

Then you specify the mechanism type with one of:

* `.withFlyWheel()` - For velocity-controlled flywheels
* `.withArm()` - For position-controlled arms
* `.withElevator()` - For position-controlled elevators

### Starting values

Every value below is a starting point. Change one at a time, as in [Tune it live](#tune-it-live).

| Parameter                          | Start at                                                                         | Change it when                                                                   |
| ---------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| Position qelms (arm, elevator)     | `Radians.of(0.1)` (about 6°), `Meters.of(0.05)`                                  | Lower it if the mechanism is slow to reach the setpoint.                         |
| Velocity qelms                     | `RadiansPerSecond.of(1.0)`, `MetersPerSecond.of(0.5)`                            | Lower it if an arm or elevator overshoots, or a flywheel is slow to reach speed. |
| Model trust (standard deviations)  | `Radians.of(0.01)`, `RadiansPerSecond.of(0.1)`, or the same in meters            | Raise it if the estimate lags behind the real mechanism.                         |
| Encoder trust (standard deviation) | `Radians.of(0.01)`, `RadiansPerSecond.of(0.1)` on a flywheel, `Meters.of(0.001)` | Raise it if the output is noisy.                                                 |
| `withControlEffort`                | `Volts.of(12)`, the default                                                      | Lower it for a gentler response that uses less voltage.                          |
| `withMaxVoltage`                   | `Volts.of(12)`, the default                                                      | Lower it to cap the output, for example to 10 V for headroom.                    |

The qelms and trust values have no defaults: `withFlyWheel`, `withArm` or `withElevator` sets them.

### Flywheel LQR configuration

Flywheels use a single-state model (velocity only):

```java
LQRConfig flywheelLQRConfig = new LQRConfig(
        DCMotor.getKrakenX60(1),                           // Motor
        new MechanismGearing(GearBox.fromReductionStages(2)), // Gearing
        KilogramSquareMeters.of(0.005)                     // Moment of inertia
    )
    .withFlyWheel(
        RadiansPerSecond.of(1.0),    // qelms: Velocity error tolerance (rad/s)
        RadiansPerSecond.of(0.01),   // modelTrust: Model standard deviation
        RadiansPerSecond.of(0.1)     // encoderTrust: Encoder standard deviation
    )
    .withControlEffort(Volts.of(12))  // R: Control effort tolerance
    .withMaxVoltage(Volts.of(12));    // Maximum output voltage

LQRController flywheelLQR = new LQRController(flywheelLQRConfig);
```

**Parameter Explanation**:

| Parameter          | Unit             | Description                                                                                        |
| ------------------ | ---------------- | -------------------------------------------------------------------------------------------------- |
| `qelms` (velocity) | RadiansPerSecond | Velocity error tolerance. **Decrease** to penalize velocity errors more heavily (more aggressive). |
| `modelTrust`       | RadiansPerSecond | Standard deviation of your model. **Lower** = trust the model more.                                |
| `encoderTrust`     | RadiansPerSecond | Standard deviation of encoder readings. **Lower** = trust encoder more.                            |
| `controlEffort`    | Volts            | The voltage the LQR treats as acceptable. **Decrease** for gentler control.                        |

### Arm LQR configuration

Arms use a two-state model (position and velocity):

```java
LQRConfig armLQRConfig = new LQRConfig(
        DCMotor.getKrakenX60(1),
        new MechanismGearing(GearBox.fromReductionStages(100)),
        KilogramSquareMeters.of(0.5)  // Arm moment of inertia
    )
    .withArm(
        Radians.of(0.1),              // qelmsPosition: Position error tolerance
        RadiansPerSecond.of(1.0),     // qelmsVelocity: Velocity error tolerance
        Radians.of(0.01),             // modelPositionTrust: Model position std dev
        RadiansPerSecond.of(0.1),     // modelVelocityTrust: Model velocity std dev
        Radians.of(0.01)              // encoderPositionTrust: Encoder position std dev
    )
    .withControlEffort(Volts.of(12))
    .withMaxVoltage(Volts.of(12));

LQRController armLQR = new LQRController(armLQRConfig);
```

**Parameter Explanation**:

| Parameter              | Unit             | Description                                                            |
| ---------------------- | ---------------- | ---------------------------------------------------------------------- |
| `qelmsPosition`        | Radians          | Position error tolerance. **Decrease** for faster position correction. |
| `qelmsVelocity`        | RadiansPerSecond | Velocity error tolerance. **Decrease** for smoother velocity tracking. |
| `modelPositionTrust`   | Radians          | Model position uncertainty.                                            |
| `modelVelocityTrust`   | RadiansPerSecond | Model velocity uncertainty.                                            |
| `encoderPositionTrust` | Radians          | Encoder measurement uncertainty.                                       |

### Elevator LQR configuration

Elevators use a two-state linear model (position and velocity in meters):

```java
LQRConfig elevatorLQRConfig = new LQRConfig(
        DCMotor.getKrakenX60(2),                              // 2 motors
        new MechanismGearing(GearBox.fromReductionStages(10)), // 10:1 reduction
        KilogramSquareMeters.of(0.01)                         // not used by an elevator, but required
    )
    .withElevator(
        Meters.of(0.02),              // qelmsPosition: Position error tolerance (m)
        MetersPerSecond.of(0.5),      // qelmsVelocity: Velocity error tolerance (m/s)
        Meters.of(0.005),             // modelPositionTrust: Model position std dev
        MetersPerSecond.of(0.1),      // modelVelocityTrust: Model velocity std dev
        Meters.of(0.001),             // encoderPositionTrust: Encoder position std dev
        Kilograms.of(5),              // mass: Carriage mass
        Inches.of(1)                  // drumRadius: Spool/drum radius
    )
    .withControlEffort(Volts.of(12))
    .withMaxVoltage(Volts.of(12));

LQRController elevatorLQR = new LQRController(elevatorLQRConfig);
```

**Elevator-Specific Parameters**:

| Parameter    | Unit          | Description                                                  |
| ------------ | ------------- | ------------------------------------------------------------ |
| `mass`       | Kilograms     | Total mass of the elevator carriage and load.                |
| `drumRadius` | Meters/Inches | Radius of the spool or drum that the belt/rope wraps around. |

## Using LQRController with SmartMotorControllerConfig

Once you have an `LQRController`, pass it to `withClosedLoopController()`. This is a fragment for inside a subsystem, which is the `this` passed to the config. The [complete example](#complete-example-lqr-arm) below shows a whole subsystem.

```java
// Create the LQR config and controller
LQRConfig lqrConfig = new LQRConfig(
        DCMotor.getKrakenX60(1),
        new MechanismGearing(GearBox.fromReductionStages(100)),
        KilogramSquareMeters.of(0.5)
    )
    .withArm(
        Radians.of(0.1),
        RadiansPerSecond.of(1.0),
        Radians.of(0.01),
        RadiansPerSecond.of(0.1),
        Radians.of(0.01)
    )
    .withControlEffort(Volts.of(12));

LQRController lqrController = new LQRController(lqrConfig);

// Pass to SmartMotorControllerConfig
SmartMotorControllerConfig config = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(100)))
    .withMomentOfInertia(Inches.of(24), Pounds.of(12))
    .withClosedLoopController(lqrController)  // Pass the LQRController here
    .withFeedforward(new ArmFeedforward(0.1, 0.45, 1.2, 0.05))
    .withZeroPower(MotorMode.BRAKE)
    .withTelemetry("LQRArm", TelemetryVerbosity.HIGH);
```

### With a motion profile

An LQR can follow a [motion profile](/documentation/reference/editor/config/motion-profiles), trapezoidal or exponential, set with the usual `withTrapezoidalProfile` or `withExponentialProfile`. The profile moves the setpoint smoothly, and the LQR tracks the profile's position and velocity instead of jumping straight to the goal.

## Advanced LQR options

### Aggressiveness and measurement delay

`LQRConfig` also has `withAggressiveness(double)` and `withMeasurementDelay(Time)`. In the current release they are stored but not used by the controller, so they change nothing. Use the qelms and the control effort to change how aggressive the LQR is.

### Loop period

`LQRConfig` uses a 20ms (50Hz) period for its discrete-time calculations (see `LQRConfig.getPeriod()`), which matches the default closed loop control period of the `Notifier` that runs the controller. There is currently no setter for the LQR period, so keep the default closed loop control period when using LQR.

{% hint style="info" %}
`SmartMotorControllerConfig.withClosedLoopControlPeriod` changes how often the `Notifier` runs, but `TalonFXWrapper` and `TalonFXSWrapper` throw an `IllegalArgumentException` if it is set, and it does not change the period `LQRConfig` was built with.
{% endhint %}

## Simulation-Only LQR

You can use different controllers for simulation and real robot. This fragment assumes `gearing` and `moi` are defined, as in the [complete example](#complete-example-lqr-arm):

```java
// Create simulation LQR
LQRConfig simLqrConfig = new LQRConfig(DCMotor.getKrakenX60(1), gearing, moi)
    .withArm(Radians.of(0.1), RadiansPerSecond.of(1.0), 
             Radians.of(0.01), RadiansPerSecond.of(0.1), Radians.of(0.01))
    .withControlEffort(Volts.of(12));

LQRController simLqr = new LQRController(simLqrConfig);

SmartMotorControllerConfig config = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withGearing(gearing)
    .withMomentOfInertia(Inches.of(24), Pounds.of(12))
    // Real robot uses PID (runs on motor controller)
    .withClosedLoopController(5.0, 0, 0.5)
    // Simulation uses LQR for validation
    .withSimClosedLoopController(simLqr)
    .withZeroPower(MotorMode.BRAKE);
```

This is useful for:

* Validating LQR tuning in simulation before deploying
* Comparing LQR vs PID performance
* Using LQR's model-based approach to inform PID tuning

## Complete example: LQR Arm

```java
public class LQRArmSubsystem extends SubsystemBase {
    private final SmartMotorController motor;
    private final Arm arm;

    public LQRArmSubsystem() {
        TalonFX talonFX = new TalonFX(1, new CANBus(CANPort.CAN_S0));
        
        // Define mechanism parameters
        DCMotor dcMotor = DCMotor.getKrakenX60(1);
        MechanismGearing gearing = new MechanismGearing(GearBox.fromReductionStages(100));
        MomentOfInertia moi = KilogramSquareMeters.of(0.5);
        
        // Create LQR configuration
        LQRConfig lqrConfig = new LQRConfig(dcMotor, gearing, moi)
            .withArm(
                Radians.of(0.05),             // Tight position tolerance
                RadiansPerSecond.of(0.5),     // Moderate velocity tolerance
                Radians.of(0.01),             // Trust the model
                RadiansPerSecond.of(0.1),
                Radians.of(0.005)             // Trust the encoder
            )
            .withControlEffort(Volts.of(10)) // A little gentler than the full 12 V
            .withMaxVoltage(Volts.of(12));
        
        // Create the LQR controller
        LQRController lqrController = new LQRController(lqrConfig);
        
        // Create motor controller config
        SmartMotorControllerConfig config = new SmartMotorControllerConfig(this)
            .withControlMode(ControlMode.CLOSED_LOOP)
            .withGearing(gearing)
            .withMomentOfInertia(Inches.of(24), Pounds.of(12))
            .withClosedLoopController(lqrController)
            .withFeedforward(new ArmFeedforward(0.1, 0.45, 1.2, 0.05))
            .withSoftLimits(Degrees.of(-10), Degrees.of(110))
            .withStartingPosition(Degrees.of(0))
            .withZeroPower(MotorMode.BRAKE)
            .withStatorCurrentLimit(Amps.of(40))
            .withTelemetry("LQRArm", TelemetryVerbosity.HIGH);
        
        motor = new TalonFXWrapper(talonFX, dcMotor, config);

        ArmConfig armConfig = new ArmConfig()
            .withLength(Inches.of(24))
            .withHardLimits(Degrees.of(-20), Degrees.of(120))
            .withTelemetry("LQRArm", TelemetryVerbosity.HIGH);

        arm = new Arm(armConfig, motor);
    }
    
    public Command goToAngle(Angle target) {
        return arm.setAngle(target);
    }

    @Override
    public void periodic() {
        arm.updateTelemetry();
    }

    @Override
    public void simulationPeriodic() {
        arm.simIterate();
    }
}
```

{% hint style="danger" %}
**Critical**: LQR runs on the SystemCore, in a `Notifier` that calls `SmartMotorController.iterateClosedLoopController()`. The wrapper starts it when the control mode is `ControlMode.CLOSED_LOOP`, whether or not you use a mechanism class. LQR does not support a closed loop tolerance: `withClosedLoopTolerance` together with an `LQRController` throws an `IllegalArgumentException`.
{% endhint %}

## Tuning strategy

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-c3433dd67cdefd5802a64f63272ab298711b2e05%2Flqr-knobs.png?alt=media" alt="Three step responses. Gentle, with a position tolerance of 0.2 radians and a control effort of 6 volts, is slow and uses little voltage. Balanced, with 0.1 radians and 12 volts, is quick and settles cleanly. Aggressive, with 0.02 radians and 12 volts, is fastest and saturates the motor"><figcaption><p>The two settings you will change most. Illustrative responses.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-e12c06bcff1c80ad23a3455d4c66c738fad92074%2Flqr-tuning.gif?alt=media" alt="Animation of an arm making the same 90 degree move three times: gentle, where it is slow and uses little voltage; aggressive, where it overshoots and the voltage saturates; and balanced, where it is quick and settles cleanly"><figcaption><p>The same move with three sets of priorities. Illustrative, not a recording.</p></figcaption></figure>

### Starting point

1. **Begin with the balanced settings**:
   * Position qelms: `Radians.of(0.1)` or `Meters.of(0.05)`
   * Velocity qelms: `RadiansPerSecond.of(1.0)` or `MetersPerSecond.of(0.5)`
   * Control effort: `Volts.of(12)`, the full battery. The control effort is how much voltage LQR treats as acceptable, so a lower value makes it gentler.
2. **Trust values** (standard deviations):
   * Model trust: Start with small values (0.01) if your model is accurate
   * Encoder trust: Use values based on your encoder resolution and noise

### Increasing responsiveness

* **Decrease** position qelms (e.g., `Radians.of(0.1)` → `Radians.of(0.05)`)
* **Increase** control effort, up to the battery's 12 V (e.g., `Volts.of(8)` → `Volts.of(12)`)

### Reducing oscillation

* **Decrease** control effort (e.g., `Volts.of(12)` → `Volts.of(8)`)
* **Decrease** velocity qelms to penalize velocity errors more

### Tune it live

You can change every value above while the robot runs, with [live tuning](/documentation/how-to-tuning/live-tuning). With `TelemetryVerbosity.HIGH`, a motor controller configured with an LQR publishes the LQR's values under `NT:/Tuning/<Mechanism>/<Motor>/closedloop/lqr/` in place of kP, kI and kD. Start the `Live Tuning` command, then type a value, and the LQR is rebuilt with it on the next loop.

| Field, under `closedloop/lqr/` | `LQRConfig` value      | Flywheel | Arm     | Elevator |
| ------------------------------ | ---------------------- | -------- | ------- | -------- |
| `qelms/position`               | Position qelms         |          | Degrees | Meters   |
| `qelms/velocity`               | Velocity qelms         | RPM      | RPM     | m/s      |
| `relms`                        | Control effort         | Volts    | Volts   | Volts    |
| `model/position`               | Model position trust   |          | Degrees | Meters   |
| `model/velocity`               | Model velocity trust   | RPM      | RPM     | m/s      |
| `encoder/position`             | Encoder position trust |          | Degrees | Meters   |
| `encoder/velocity`             | Encoder trust          | RPM      |         |          |
| `maxVoltage`                   | Max voltage            | Volts    | Volts   | Volts    |

The fields use the same units as the tunable setpoints, and start at the values in your config. A field your LQR type does not use is not published.

{% stepper %}
{% step %}

#### Tune the feedforward first

The LQR only replaces kP, kI and kD. kG, kS, kV and kA are still added to its output, and still tuned as in [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order). An arm or elevator whose kG is wrong ends up short of the setpoint, whatever the LQR does.
{% endstep %}

{% step %}

#### Set the response with the qelms and control effort

Command small moves, or a speed on a flywheel, and change one value at a time:

* Too slow: lower `qelms/position` (on a flywheel, `qelms/velocity`), or raise `relms` up to 12 V.
* Overshoots or rings: lower `qelms/velocity` on an arm or elevator, or lower `relms`.
* `motor/outputVoltage` pinned at the limit: the LQR is asking for more than the motor has, so raise the qelms or lower `relms`.
  {% endstep %}

{% step %}

#### Change the trust values last, if at all

`model/` and `encoder/` set how the Kalman filter weighs the model against the encoder. Leave them unless the output is noisy, in which case raise `encoder/position` (on a flywheel, `encoder/velocity`), or the estimate lags the real mechanism, in which case raise `model/position` and `model/velocity`.
{% endstep %}

{% step %}

#### Copy the values into your config

Live tuning changes nothing in your code. Write the values down and put them in your `LQRConfig`. In Java, the units carry over: `Degrees.of(...)`, `RPM.of(...)`, `Meters.of(...)`, `MetersPerSecond.of(...)` and `Volts.of(...)`. In C++, `WithQElems`, `WithStateStdDevs` and `WithMeasurementStdDevs` take radians, rad/s, meters and m/s, so convert the degrees and RPM first.
{% endstep %}
{% endstepper %}

{% hint style="info" %}
**Every value must be above 0.** A change rebuilds the LQR from all the fields, starting from the old LQR's state estimate, so the output does not jump and the mechanism keeps holding its setpoint. A value the LQR cannot use, such as a tolerance of 0, leaves it as it was, with a warning on the Driver Station naming the motor.
{% endhint %}

The [`lqr_mechanisms` example](https://github.com/Yet-Another-Software-Suite/YAMS/tree/master/examples/commands2/lqr_mechanisms) has an LQR arm and an LQR flywheel to practice on in simulation, for Commands v2 and Commands v3. The [YAMS Live Tuner](https://tuning.yassrobotics.com/) shows these fields as an **LQR** group.

### Always test in simulation first

LQR can behave very differently with small parameter changes. Always validate in simulation before testing on the real robot.

## Troubleshooting LQR

### Oscillation

**Symptoms**: Mechanism oscillates around setpoint **Solutions**:

* Decrease control effort to make it gentler
* Decrease velocity qelms to penalize velocity errors
* Check for mechanical issues (backlash, friction)

### Slow response

**Symptoms**: Mechanism responds too slowly to setpoint changes **Solutions**:

* Increase control effort, up to 12 V
* Decrease position qelms to penalize position errors more
* If the config also has a [motion profile](/documentation/reference/editor/config/motion-profiles), raise its limits: the LQR follows the profile's setpoints, so a slow profile gives a slow response whatever the LQR does

### Steady-state error

**Symptoms**: Mechanism doesn't quite reach setpoint **Solutions**:

* Verify feedforward is properly tuned (especially kG for arms/elevators)
* Decrease position qelms, so a small position error costs more
* Ensure model parameters (mass, inertia, gearing) are accurate

### Model mismatch

**Symptoms**: Simulation works but real robot doesn't **Solutions**:

* Re-measure mass and moment of inertia
* Verify gearing ratio is correct
* Measure kV and kA on the real mechanism and compare them with the model, see [Measuring kV and kA](/documentation/understanding/exponential-profiles#measuring-kv-and-ka-optional)
* Account for friction and other losses in feedforward

## LQR vs PID quick reference

| Aspect                | PID                                    | LQR                                         |
| --------------------- | -------------------------------------- | ------------------------------------------- |
| **Tuning Method**     | Trial and error                        | Model-based computation                     |
| **Parameters**        | kP, kI, kD                             | Q matrix (qelms), R matrix (control effort) |
| **States Controlled** | Typically one (position or velocity)   | Multiple (position AND velocity)            |
| **Model Required**    | No                                     | Yes (motor, gearing, inertia)               |
| **Optimality**        | Not guaranteed                         | Mathematically optimal                      |
| **Hardware Support**  | Motor controllers                      | SystemCore only                             |
| **Update Rate**       | 1kHz+ (on controller)                  | 50Hz (SystemCore)                           |
| **YAMS API**          | `withClosedLoopController(kP, kI, kD)` | `withClosedLoopController(LQRController)`   |


# EasyCRT

Chinese Remainder Theorem! Made easy by 6911

{% hint style="info" %}
`EasyCRT` was made entirely by Team 6911!
{% endhint %}

`EasyCRT` finds the absolute angle of a mechanism that turns more than once, usually a turret, from two absolute encoders. Each encoder sits on a pinion with a different tooth count, and both pinions mesh with the same gear. Neither encoder knows the angle on its own, but the pair of readings is unique over a much longer travel than either one.

This page explains how it works, then how to set it up step by step, then how to fix it when it misbehaves.

## How it works

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-74a0c1584597f7420c5a34d6afda8ffeace18952%2Feasycrt-how-it-works.gif?alt=media" alt="Animation: as the turret turns, encoder A and encoder B readings wrap at different rates, and EasyCRT reports the one turret angle that fits both"><figcaption><p>Each encoder wraps many times, at different rates. Only one turret angle fits both readings.</p></figcaption></figure>

1. Encoder A's reading fits several angles of the gear both pinions mesh with (the **shared gear**), one for each number of whole turns the pinion could have made. `EasyCRT` lists every one inside the travel.
2. For each candidate it predicts what encoder B should read.
3. The candidate whose prediction is closest to encoder B's real reading wins.

This is not a textbook Chinese Remainder Theorem solve. It is the same idea done as a search, which keeps working with backlash and sensor noise.

The readings only repeat after the shared gear has turned a long way. That distance is the **unique range**. Past it, two positions give the same pair of readings, so the travel of your mechanism has to fit inside it.

Team 4967 wrote a white paper describing how the Chinese Remainder Theorem works for gears:

{% file src="/files/0AqOwxrFAJi5PO00j2Xy" %}

### What to know before you choose it

* Solve for the absolute angle **once** at startup, then seed the motor controller with the result. Do not use `EasyCRT` as closed loop feedback.
* CRT is sensitive to any delay between the two encoder reads, so it is unreliable while the mechanism moves. Read both encoders while the mechanism is still.
* Backlash between the two encoders, and loose pinions or magnets, cause failures. `solve` returns an empty result instead of a guess when the two readings do not agree, so your code has to handle an empty result.
* `EasyCRT` has no offset or inversion settings. Both encoders must read zero with the mechanism at zero, and both must count up when the mechanism moves in its positive direction.

### Alternatives

CRT is not the only way to find the absolute angle of your turret. Choose whatever is easiest for you:

* A zero sensor (limit switch, magnetic limit switch) and rotating to hit it
* A 10-turn pot on a reduction
* An absolute encoder with a 1:1 reduction
  * Optionally add a slightly less than 1:1 pinion on a second absolute encoder and find how many turns there are algebraically.

## Set it up

{% hint style="info" %}
Coming from the 2026 `EasyCRTConfig` API? See [Upgrading from 2026 to 2027](/documentation/upgrading/upgrading-from-2026-to-2027#easycrt) for the before and after.
{% endhint %}

The whole API:

| Java                        | C++                     | What it does                                                 |
| --------------------------- | ----------------------- | ------------------------------------------------------------ |
| `new EasyCRT(shared, a, b)` | `EasyCRT{shared, a, b}` | Tooth counts of the shared gear and the two encoder pinions. |
| `solve(a, b)`               | `Solve(a, b)`           | Angle of the shared gear, for travel centered on zero.       |
| `solve(a, b, min, max)`     | `Solve(a, b, min, max)` | The same, for travel that is not centered on zero.           |
| `getUniqueRange()`          | `GetUniqueRange()`      | How far the shared gear can turn before the readings repeat. |

`solve` returns an empty `Optional` (`std::nullopt` in C++) when the two readings do not agree on one angle. Everything else (choosing gears, zeroing, inversion, gear trains, checking your margin) is something you do yourself, with the steps below.

### Step 1: Choose tooth counts

The readings repeat together every `lcm(a, b)` teeth of the shared gear, so:

```
unique range (rotations of the shared gear) = lcm(a, b) / shared
```

Pick pinions with no common factor (coprime), so the lcm is their product. Sharing a factor throws range away: 20 and 30 teeth only cover 60 teeth of the shared gear, not 600.

| Pinion A | Pinion B | Teeth covered | Range on a 100 tooth gear | Range on a 200 tooth gear |
| -------- | -------- | ------------- | ------------------------- | ------------------------- |
| 13       | 15       | 195           | 1.95 turns                | 0.975 turns               |
| 17       | 19       | 323           | 3.23 turns                | 1.615 turns               |
| 19       | 21       | 399           | 3.99 turns                | 1.995 turns               |
| 20       | 21       | 420           | 4.20 turns                | 2.10 turns                |
| 25       | 27       | 675           | 6.75 turns                | 3.375 turns               |
| 30       | 31       | 930           | 9.30 turns                | 4.65 turns                |

The range has to be at least your full travel, including how far the mechanism can coast past its soft limits. `getUniqueRange()` returns it, and `solve(a, b, min, max)` throws an `IllegalArgumentException` if the travel you pass is longer.

To check a pair before you build it:

{% tabs %}
{% tab title="Java" %}

```java
Angle range = new EasyCRT(200, 19, 21).getUniqueRange(); // 1.995 rotations
```

{% endtab %}

{% tab title="C++" %}

```cpp
wpi::units::turn_t range = yams::units::EasyCRT{200, 19, 21}.GetUniqueRange(); // 1.995 rotations
```

{% endtab %}
{% endtabs %}

**Check:** the range is longer than your travel, with room on both sides.

### Step 2: Zero the encoders and check their direction

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-7a320da63e9db595441cfc5d96d2fa57138104d3%2Feasycrt-zeroing.gif?alt=media" alt="Animation: the turret is moved to the middle of its travel, both absolute encoders are zeroed there, and solve then reports angles either side of zero"><figcaption><p>Center the turret, zero both encoders there, then check both directions.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-e6bb9cda4aa0c753d22f92fff5ce032a4fcd632a%2Feasycrt-encoder-direction.gif?alt=media" alt="Animation: with encoder B counting down, solve returns empty; after inverting encoder B so both count up, solve returns the turret angle"><figcaption><p>Both encoders have to count up when the turret turns in its positive direction.</p></figcaption></figure>

`EasyCRT` takes the two readings as they are, so the encoders have to be set up first:

* **Zero both encoders with the mechanism at zero.** Use the vendor tool to set each encoder's offset. If an encoder cannot store an offset, subtract it yourself: `crt.solve(encoderA.get().minus(offsetA), encoderB.get().minus(offsetB))`.
* **Both encoders must count up when the mechanism moves in its positive direction.** A pinion turns the opposite way to the gear it meshes with, so the direction depends on the layout (see Step 3). Set the direction on the encoder, or negate the reading before passing it in.
* **Read while the mechanism is still.** The two readings are taken one after the other, so any motion between them looks like disagreement.

{% hint style="warning" %}
Set each offset and inversion in one place only: on the encoder, or in your code before calling `solve`. Doing it in both places gives shifted or mirrored angles.
{% endhint %}

**Check:** turn the mechanism by hand in its positive direction. Both readings go up.

### Step 3: Solve once at startup and seed the motor

There are four common places to put the two encoder pinions on a turret. In every one, the gear both pinions mesh with is the shared gear.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-ef29b1752611515d051de682a60e2ff20ed5186f%2Feasycrt-layouts.png?alt=media" alt="Four EasyCRT gear layouts: pinions on the turret gear, on the drive gear, on a common gear, or on a second gear on the drive shaft"><figcaption><p>The four places to put the CRT pinions. Not to scale.</p></figcaption></figure>

Two gearings are involved, and they are not the same thing:

* **The motor's gearing** (`motorToTurret`) goes in the `SmartMotorControllerConfig` with `withGearing(...)`. It is the whole reduction from the motor to the turret.
* **The shared gear's gearing** is only needed in layout 4, to turn the solved angle into the turret angle.

`setEncoderPosition(...)` always takes the turret angle, and applies the motor's gearing itself. The tooth counts below are examples.

#### Layouts 1, 2 and 3: use the turret's tooth count

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-a504c47301b9b9fe78fb66bbf57decd1fde8a113%2Feasycrt-shortcut.png?alt=media" alt="Turret gear, drive gear and encoder pinion in a row: 200 over 40 times 40 over 19 is 200 over 19, so the drive gear cancels"><figcaption><p>A gear that only meshes passes teeth through one for one.</p></figcaption></figure>

When every gear between the pinions and the turret simply meshes with the next one, the gears in between cancel out: each pinion turns `200 / 19` or `200 / 21` times per turret turn, whichever gear it touches. So in these three layouts you give `EasyCRT` the **turret** gear's tooth count, and `solve` returns the turret angle with no conversion:

| Layout | Where the pinions mesh                                  | Encoder direction                                                            |
| ------ | ------------------------------------------------------- | ---------------------------------------------------------------------------- |
| 1      | On the turret gear                                      | Pinions turn opposite to the turret, so both encoders usually need inverting |
| 2      | On the motor's drive gear, which drives the turret gear | Two meshes away, so the pinions turn the same way as the turret              |
| 3      | On a common gear that meshes with the turret gear       | Two meshes away, the same way as the turret                                  |

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-6d7a6234f354cc6f196daa5b24edc0a8bfaae466%2Feasycrt-layout-1-motion.gif?alt=media" alt="Animation of layout 1: the turret gear turns the drive gear and both encoder pinions, and solve returns the turret angle"><figcaption><p>Layout 1: the pinions mesh with the turret gear.</p></figcaption></figure>

{% tabs %}
{% tab title="Java" %}

```java
// Motor: 10:1 gearbox, then the 40 tooth drive gear on the 200 tooth turret gear (5:1).
MechanismGearing motorToTurret = new MechanismGearing(GearBox.fromReductionStages(10, 200.0 / 40));

SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withGearing(motorToTurret)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(20, 0, 0);
SmartMotorController motor = new SparkWrapper(sparkMax, DCMotor.getNEO(1), motorConfig);

// Layouts 1, 2 and 3: the 200 tooth turret gear, pinion A, pinion B.
EasyCRT crt = new EasyCRT(200, 19, 21);

// Once, at startup, with the turret still. The result is the turret angle,
// and setEncoderPosition applies motorToTurret itself.
crt.solve(encoderA.get(), encoderB.get()).ifPresent(motor::setEncoderPosition);
```

{% endtab %}

{% tab title="C++" %}

```cpp
// Motor: 10:1 gearbox, then the 40 tooth drive gear on the 200 tooth turret gear (5:1).
yams::gearing::MechanismGearing motorToTurret{
    yams::gearing::GearBox::FromReductionStages({10.0, 200.0 / 40.0})};
motorConfig.WithMotorGearing(motorToTurret);
// ... finish motorConfig and build the SmartMotorController `motor` with it.

// Layouts 1, 2 and 3: the 200 tooth turret gear, pinion A, pinion B.
yams::units::EasyCRT crt{200, 19, 21};

// Once, at startup, with the turret still. The result is the turret angle,
// and SetEncoderPosition applies motorToTurret itself.
if (auto turretAngle = crt.Solve(encoderA, encoderB)) {
  motor.SetEncoderPosition(*turretAngle);
}
```

{% endtab %}
{% endtabs %}

<details>

<summary>Layouts 2 and 3 in motion</summary>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-800cba124bd5149365eec1004febe65b2935cb4b%2Feasycrt-layout-2-motion.gif?alt=media" alt="Animation of layout 2: both encoder pinions mesh with the motor drive gear, which drives the turret gear"><figcaption><p>Layout 2: the pinions mesh with the drive gear.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-8406cf61beb1e34cf336600fe5ff685cdf685b96%2Feasycrt-layout-3-motion.gif?alt=media" alt="Animation of layout 3: the turret gear turns the common gear, which turns both encoder pinions"><figcaption><p>Layout 3: the pinions mesh with a common gear.</p></figcaption></figure>

You can also give `EasyCRT` the drive gear's or common gear's own tooth count and scale the result by that stage's `MechanismGearing`, as in layout 4. The answer and the unique range in turret turns are the same.

</details>

#### Layout 4: CRT gears on the drive shaft

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-37e98a4a787aadc9053ea361164a3fb9c130a5ab%2Feasycrt-layout-4-motion.gif?alt=media" alt="Animation of layout 4: a 60 tooth gear shares a shaft with the 40 tooth drive gear, both encoder pinions mesh with the 60 tooth gear, and the shaft angle is scaled to the turret angle"><figcaption><p>Layout 4: the 60 tooth gear on the drive shaft is the shared gear.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-001e92cbae7d8144a3962487ef46a755a54b96e7%2Feasycrt-compound.png?alt=media" alt="A 60 tooth shared gear and a 40 tooth drive gear on the same shaft, with the drive gear meshing with the turret gear, so the tooth counts do not cancel"><figcaption><p>Two different gears on one shaft change the ratio.</p></figcaption></figure>

Both pinions mesh with a second gear fixed to the same shaft as the motor's drive gear. Two different gears on one shaft do not cancel, so the shortcut does not work. Give `EasyCRT` the 60 tooth gear, which makes `solve` return the shaft angle, and multiply by the shaft to turret `MechanismGearing`. The same applies whenever the shared gear sits behind a gearbox stage. The pinions turn the same way as the turret.

{% tabs %}
{% tab title="Java" %}

```java
// Motor: 10:1 gearbox, then the 40 tooth drive gear on the 200 tooth turret gear (5:1).
MechanismGearing motorToTurret = new MechanismGearing(GearBox.fromReductionStages(10, 200.0 / 40));

SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withGearing(motorToTurret)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(20, 0, 0);
SmartMotorController motor = new SparkWrapper(sparkMax, DCMotor.getNEO(1), motorConfig);

// The pinions mesh with a 60 tooth gear on the drive gear's shaft.
// That shaft turns 5 times per turret turn (40 tooth drive gear on the 200 tooth turret gear).
MechanismGearing shaftToTurret = new MechanismGearing(GearBox.fromTeeth(40, 200));
EasyCRT crt = new EasyCRT(60, 19, 21); // gear on the shaft, pinion A, pinion B

crt.solve(encoderA.get(), encoderB.get()).ifPresent(shaftAngle -> {
  // Scale the shaft angle down to the turret, then seed the motor with the turret angle.
  Angle turretAngle = shaftAngle.times(shaftToTurret.getRotorToMechanismRatio());
  motor.setEncoderPosition(turretAngle);
});
```

{% endtab %}

{% tab title="C++" %}

```cpp
// Motor: 10:1 gearbox, then the 40 tooth drive gear on the 200 tooth turret gear (5:1).
yams::gearing::MechanismGearing motorToTurret{
    yams::gearing::GearBox::FromReductionStages({10.0, 200.0 / 40.0})};
motorConfig.WithMotorGearing(motorToTurret);
// ... finish motorConfig and build the SmartMotorController `motor` with it.

// The pinions mesh with a 60 tooth gear on the drive gear's shaft.
// That shaft turns 5 times per turret turn (40 tooth drive gear on the 200 tooth turret gear).
yams::gearing::MechanismGearing shaftToTurret{yams::gearing::GearBox::FromTeeth({40, 200})};
yams::units::EasyCRT crt{60, 19, 21};  // gear on the shaft, pinion A, pinion B

if (auto shaftAngle = crt.Solve(encoderA, encoderB)) {
  // Scale the shaft angle down to the turret, then seed the motor with the turret angle.
  wpi::units::turn_t turretAngle = *shaftAngle * shaftToTurret.GetRotorToMechanismRatio();
  motor.SetEncoderPosition(turretAngle);
}
```

{% endtab %}
{% endtabs %}

Layout 4 also has a shorter unique range. 399 teeth of the 60 tooth gear is `399 / 60 = 6.65` turns of the shaft, which is `6.65 / 5 = 1.33` turns of the turret, against 1.995 in layouts 1 to 3. A bigger gear on the shaft uses the range up faster. The unique range in turret turns is `getUniqueRange()` multiplied by `shaftToTurret.getRotorToMechanismRatio()`.

#### Travel that is not centered on zero

`solve(a, b)` assumes the mechanism's zero is in the middle of its travel, and returns an angle within half the unique range either side of zero. For a turret that goes from 0 to 540 degrees, give the travel:

{% tabs %}
{% tab title="Java" %}

```java
Optional<Angle> angle = crt.solve(encoderA.get(), encoderB.get(), Degrees.of(0), Degrees.of(540));
```

{% endtab %}

{% tab title="C++" %}

```cpp
std::optional<wpi::units::turn_t> angle =
    crt.Solve(encoderA, encoderB, wpi::units::turn_t{0.0}, wpi::units::turn_t{1.5});
```

{% endtab %}
{% endtabs %}

Give the real travel, not the whole unique range. A tighter range leaves fewer candidates, and it keeps a reading taken slightly past an end stop from wrapping to the other end.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-4a32b251553406346497cae7cc4bcadc80a37dbb%2Feasycrt-travel.png?alt=media" alt="Turret travel of minus 200 to plus 200 degrees is the same motion as minus 1000 to plus 1000 degrees of a drive gear that turns 5 times per turret turn"><figcaption><p>The same motion, as turret angles and as shared gear angles.</p></figcaption></figure>

The travel is in shared gear angles. In layouts 1 to 3 with the turret's tooth count, that is the turret angle. In layout 4, convert the turret's travel to shaft angles first:

```java
// Layout 4: turret travel of -200 to 200 degrees, expressed as shaft angles.
double shaftTurnsPerTurretTurn = shaftToTurret.getMechanismToRotorRatio(); // 5
crt.solve(encoderA.get(), encoderB.get(),
    Degrees.of(-200).times(shaftTurnsPerTurretTurn), Degrees.of(200).times(shaftTurnsPerTurretTurn));
```

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-ce059f3d718f7e43afee9447977cadc9318b7724%2Feasycrt-range.png?alt=media" alt="Number line of the turret angle showing the 1.995 turn unique range with the turret travel and hard stops inside it"><figcaption><p>The travel has to fit inside the unique range.</p></figcaption></figure>

{% hint style="info" %}
Pass `setEncoderPosition(...)` the mechanism angle, not the rotor angle: it applies the `MechanismGearing` from the config, so multiplying first would apply the gearing twice. The rotor angle it ends up setting is `turretAngle.times(motorToTurret.getMechanismToRotorRatio())`.
{% endhint %}

{% hint style="warning" %}
Decide what happens when the result is empty. Raising an alert and refusing to move the mechanism is safer than assuming it is at zero.
{% endhint %}

The `BroncBotz_2026` examples have a complete `Turret` class: [Commands v2](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands2/BroncBotz_2026/java/first/robot/subsystems/Turret.java) and [Commands v3](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/BroncBotz_2026/java/first/robot/mechanisms/Turret.java).

**Check:** after a power cycle, the turret's `mechanism/position` matches its real angle at several positions across the travel.

### Step 4: Check your margin

`EasyCRT` has no tolerance setting. It works the tolerance out from the gears:

* Neighboring candidates predict encoder B readings `gcd(a, b) / b` of a rotation apart. For 19 and 21 teeth that is 1/21 of a rotation, about 17 degrees of encoder B.
* A match is accepted when encoder B is within a quarter of that gap of its prediction, about 4.3 degrees here. Anything further off returns empty instead of a guess.

So the backlash and noise between the two encoders, measured at encoder B, has to stay under a quarter of the gap. To measure what you actually have, log the error yourself while moving the mechanism slowly by hand through its travel:

```java
// The tooth counts given to EasyCRT.
static final int SHARED_GEAR_TEETH = 200;
static final int PINION_B_TEETH = 21;

// Encoder B turns SHARED_GEAR_TEETH / PINION_B_TEETH times per turn of the shared gear.
Angle predictedB = solvedAngle.times((double) SHARED_GEAR_TEETH / PINION_B_TEETH);
// The gap between predicted and real encoder B, wrapped to -0.5 to 0.5 rotations.
double errorRotations = MathUtil.inputModulus(
    predictedB.minus(encoderB.get()).in(Rotations), -0.5, 0.5);
// Must stay well under a quarter of 1 / PINION_B_TEETH (here 1/84 of a rotation).
```

If the error gets near the limit:

* Preload the mechanism to one side of its backlash before reading.
* Use a larger pinion B, or pinions with a bigger tooth difference, which widens the gap.
* Check that both encoder magnets and pinions are secure.

The accuracy of the result comes from encoder A alone: an error on encoder A shows up divided by `shared / a`.

## Troubleshooting

{% hint style="danger" %}
**Empty near the ends of travel? Your range affects your reading** (found by Team 2181).

If `solve` comes back empty near the ends of travel, your turret is probably sitting just outside the range you gave. Use a range with room on both sides.

For example, instead of `solve(a, b, Rotations.of(0), Rotations.of(2))` use `solve(a, b, Rotations.of(-0.1), Rotations.of(2.1))`, as long as the range is still shorter than `getUniqueRange()`. `solve(a, b)` already does this for travel centered on zero: it allows half of the unique range either side of zero.

If your turret is outside the unique range, your CRT reading will be very **VERY** off.
{% endhint %}

Two failures are worth seeing in motion.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-c7c3e8fe7fd7cd6792d0da76e9696e99ef9690b3%2Feasycrt-out-of-range.gif?alt=media" alt="Animation: as the real turret angle moves past the end of the unique range, the solved angle jumps to the other end of the range"><figcaption><p>Past the unique range the answer comes from the other end.</p></figcaption></figure>

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d8f174d02a34ff7996a8f0420a3373ce1c3d39e9%2Feasycrt-backlash.gif?alt=media" alt="Animation: as encoder B drifts from its predicted reading, solve goes from the correct angle, to empty, to a wrong angle a different turn away"><figcaption><p>A match must be within a quarter of the gap between candidates. Half way gives no answer, and further gives a wrong one.</p></figcaption></figure>

| Symptom                                                      | Likely cause                                                                                                   |
| ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
| Always empty                                                 | An encoder is not zeroed at the mechanism's zero, or one encoder counts the wrong way.                         |
| Empty in some positions only                                 | Backlash or a loose pinion is using up the margin. See [Step 4: Check your margin](#step-4-check-your-margin). |
| Empty at the ends of travel                                  | The mechanism is past the travel you gave, or the travel is the whole unique range. See the warning above.     |
| Angle is off by a fixed amount                               | Encoder A's zero is off. The result follows encoder A.                                                         |
| Angle is off by a whole number of pinion turns               | The readings were taken while moving, or encoder B's zero is off.                                              |
| Angle is mirrored                                            | Both encoders count the wrong way.                                                                             |
| `solve(a, b, min, max)` throws an `IllegalArgumentException` | The travel is longer than the unique range. Choose different pinions.                                          |

### Checklist

* [ ] Pinion tooth counts share no factor, and the unique range covers the full travel with room to spare.
* [ ] Both encoders read zero with the mechanism at zero.
* [ ] Both encoders count up when the mechanism moves in its positive direction.
* [ ] The solved angle matches the real angle at several positions across the travel.
* [ ] The error on encoder B stays well under a quarter of the gap between candidates.
* [ ] The robot gives the right angle after a power cycle in several positions.
* [ ] The code handles an empty result.


# Battery simulation

YAMS models a single, shared robot battery in simulation instead of letting each mechanism compute its own voltage sag in isolation. Every simulated `SmartMotorController`, whether driven by an `ArmSimSupplier`, `ElevatorSimSupplier`, `DCMotorSimSupplier`, or a hardware wrapper (`SparkWrapper`, `TalonFXWrapper`, `TalonFXSWrapper`, `NovaWrapper`, `A301Wrapper`), reports its current draw into [`BatterySim`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/simulation/BatterySim.html), which combines every mechanism's draw into one realistic loaded-voltage calculation and sets the simulated battery voltage that every motor then runs from.

{% hint style="info" %}
This is automatic. You do not need to call anything for basic voltage sag under combined load, it happens as soon as a mechanism has a sim supplier attached and `simIterate()`/`SimIterate()` is called each loop, same as [Simulation without a mechanism](/documentation/reference/editor#simulation-without-a-mechanism).
{% endhint %}

{% hint style="info" %}
FIRST does not publish the A301's currents, so its motor model, `YMotors.getA301(1)`, uses the NEO 550's for now (100 A stalled, 1.4 A free). An A301's simulated current draw is an estimate until FIRST publishes them.
{% endhint %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-10b7ea0f915fbcc1397707d62934ca9dfc932fc7%2Fbattery-sim-shared.png?alt=media" alt="An arm, an elevator, a shooter flywheel, an intake roller and a swerve drive with eight motors each send their current draw to BatterySim, which adds them to 150 amps and computes 12.0 volts minus 150 amps times 0.020 ohms equals 9.0 volts, the voltage every motor then runs from"><figcaption><p>Every simulated motor reports into one battery, and every motor runs from the result.</p></figcaption></figure>

## Why this matters

Before, if two mechanisms each set the simulated battery voltage from only their own current draw, whichever mechanism updated last would overwrite the other's contribution, so the simulated battery would never actually see the *combined* draw of the whole robot. With a shared `BatterySim`, a flywheel spinning up while an elevator is climbing will sag the simulated bus voltage the same way a real battery would under both loads at once, which is exactly the scenario that trips brownouts on a real robot. See [Limiting Power Consumption](/documentation/how-to-motor-controllers-and-sensors/limiting-power-consumption) for how to guard against that on top of realistic simulation.

{% hint style="warning" %}
**Power consumption is not the only thing that causes brownouts.** The battery simulation only models the current your mechanisms draw. Electrical issues can also cause brownouts and excessive power draw on a real robot, and the simulation cannot see any of them. They include, and are not limited to:

* **Shorts**, such as a pinched wire or a frame short.
* **Incorrect wiring**, such as loose or badly crimped connections, loose battery terminals, or the wrong breaker.
* **Wire limitations**, such as wire that is too thin or too long for the current it carries.

A robot that never browns out in simulation can still brown out for these reasons. If the real robot browns out when the simulation says it should not, check the electrical system before changing current limits.
{% endhint %}

## Battery sag vs battery drain

The battery voltage drops for two different reasons, and the simulation models them separately.

|                  | Battery sag                                                                                          | Battery drain                                                                                                                    |
| ---------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| What it is       | The voltage dropping **while current is being drawn**, because of the battery's internal resistance. | The battery **emptying** as amp-hours are used up over a match.                                                                  |
| How fast         | Instant. It follows the current loop by loop.                                                        | Slow. It builds up over minutes.                                                                                                 |
| Does it recover? | Yes. The voltage comes back as soon as the load stops.                                               | No. It stays until the battery is recharged.                                                                                     |
| What it changes  | The loaded voltage only.                                                                             | The resting voltage goes down and the internal resistance goes up.                                                               |
| In YAMS          | Always on. See [How each mechanism affects the battery](#how-each-mechanism-affects-the-battery).    | Off until you call `BatterySim.enableDischarge(...)`. See [Realistic discharge over a match](#realistic-discharge-over-a-match). |

The two add up. A drained battery starts from a lower resting voltage and has more internal resistance, so the same current sags it further. That is why a move that is fine at the start of a match can brown out at the end of it.

## How each mechanism affects the battery

The loaded voltage is the resting voltage minus the total current times the battery's internal resistance:

`battery voltage = resting voltage - (sum of every motor's supply current) x internal resistance`

With the default 12 V and 20 milliohm battery, every 50 A of total draw costs 1 V.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-643b8d4843a174bd1b8dc0708e1a82998abcabc2%2Fbattery-sim-load.gif?alt=media" alt="Animation of four current bars for a swerve drive, shooter, elevator and arm and a graph of battery voltage. The voltage dips when the swerve drive launches, dips again when the shooter spins up, and drops lowest, to about 8.8 volts, when the elevator and arm move while the drive is pushing"><figcaption><p>A few seconds of a match: the voltage follows the total, and it is lowest when the peaks line up.</p></figcaption></figure>

Mechanisms do not load the battery evenly. Each one has moments when it draws a lot and long stretches when it draws very little.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-5676fc440147bf970eeca17663417c43d4f9a903%2Fbattery-sim-mechanisms.png?alt=media" alt="Six sketches of current over time. Arm: spikes when it starts and stops, then a steady draw to hold against gravity. Elevator: largest going up, steady to hold a height. Flywheel, shooter, rollers: very large while spinning up, small at speed, a bump on every shot. Pivot, turret, wrist: short bursts when starting and stopping. Swerve drive: eight motors, usually the largest draw. All together: the draws add up and overlapping peaks cause the deepest sag"><figcaption><p>When each kind of mechanism draws current.</p></figcaption></figure>

| Mechanism                               | Motors that report             | Draws the most when                                          | What changes it                                                  |
| --------------------------------------- | ------------------------------ | ------------------------------------------------------------ | ---------------------------------------------------------------- |
| `Arm`                                   | 1 or 2                         | Starting and stopping a move, and holding away from vertical | Arm length and mass (MOI), gearing, motion profile acceleration  |
| `Elevator`                              | 1 to 4                         | Accelerating upward, then a steady draw to hold a height     | Carriage mass, drum radius, gearing, motion profile acceleration |
| `FlyWheel` (shooters, rollers, intakes) | 1 to 4                         | Spinning up from rest, and recovering after each shot        | Wheel MOI, target speed, stator current limit                    |
| `Pivot` (turrets, wrists)               | 1                              | Short bursts when starting and stopping                      | MOI, motion profile acceleration                                 |
| `SwerveDrive`                           | 8: four drive and four azimuth | Accelerating, changing direction, and pushing                | Robot mass, drive gearing, drive stator current limit            |

### Swerve drives

A swerve drive is not one load, it is eight. Each module's drive motor and azimuth motor is its own `SmartMotorController`, and each one reports its own supply current to `BatterySim` when `SwerveDrive.simIterate()` runs. Nothing extra is needed to include the drivetrain.

* The **drive motors** dominate. Four of them accelerating a full weight robot is normally the largest draw on the robot.
* The **azimuth motors** draw short bursts when the modules change heading, and little while driving straight.
* Because the drive is the largest load, it also sets the voltage every other mechanism gets. A shooter that reaches its speed with the robot parked can fall short while the robot is accelerating.

{% hint style="success" %}
To keep the peaks from lining up, set stator and supply current limits on the biggest loads and stagger the moves that can wait. See [Limiting Power Consumption](/documentation/how-to-motor-controllers-and-sensors/limiting-power-consumption).
{% endhint %}

## Accurate current draw starts with an accurate MOI

`BatterySim` can only sag voltage as realistically as the current draw it's fed, and that current draw comes straight out of each mechanism's physics simulation (`SingleJointedArmSim`/`DCMotorSim`/`ElevatorSim`). Those models derive current from the torque needed to produce a given acceleration, so if the moment of inertia doesn't match your real mechanism, the simulated current, and therefore the simulated voltage sag, won't either. A default/guessed MOI tends to make mechanisms look artificially light, understating both acceleration current spikes and how much they actually sag the bus.

Set a real MOI on the `SmartMotorControllerConfig` with `.withMomentOfInertia(Distance, Mass)` (estimated from a simple rod/arm model) or `.withMomentOfInertia(MomentOfInertia)` (a known/measured value), see [MOI](/documentation/understanding/turrets-wrists#moment-of-inertia) for the full explanation and an example.

{% hint style="info" %}
This is the same MOI used for PID/feedforward tuning in simulation, so getting it right pays off twice: more realistic control-loop behavior *and* more realistic battery sag under load.
{% endhint %}

## Realistic discharge over a match

By default the simulated battery holds a constant nominal voltage and resistance (12V / 20 mΩ), enough to model voltage sag under instantaneous load, but not a battery getting weaker over the course of a match. Call `BatterySim.enableDischarge(...)` to layer state-of-charge modeling on top: as amp-hours are drawn from the battery, its open-circuit voltage droops along a discharge curve and its internal resistance rises, both becoming more pronounced as the battery empties, the same way a real lead-acid FRC battery behaves late in a match. The amp-hours drawn are also derated by discharge rate, so heavy sustained current drains the modeled capacity faster than the same amp-hours drawn slowly, see [Capacity derating](#capacity-derating) below.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-2f3c0455fba73fccc85b012549c367bc6a649c39%2Fbattery-sim-discharge.png?alt=media" alt="Two graphs of the default discharge model. Resting voltage against state of charge falls slowly from 12.9 volts at full to 12.0 volts at 20 percent, then steeply to 9 volts when empty. Usable capacity against sustained current falls from 100 percent at 0.9 amps to 60 percent at 54 amps. Internal resistance rises from 20 milliohms when full to 60 milliohms when empty"><figcaption><p>The default discharge curves.</p></figcaption></figure>

To turn it on, reset it between runs or read the state of charge, see [How do I enable battery discharge simulation?](/documentation/how-to-simulation-and-logging/how-do-i-enable-battery-discharge-simulation).

{% hint style="warning" %}
Discharge only affects simulation. On a real robot `BatterySim` is never consulted, the SystemCore reports the actual battery voltage from hardware.
{% endhint %}

## Custom discharge curves

`enableDischarge(...)` sags voltage along a curve tuned for a typical FRC sealed lead-acid battery, flat through most of the charge, then dropping off quickly near depletion. Not every sealed lead-acid battery you want to model behaves exactly that way, so call `BatterySim.replaceSOCInterpolation(...)` **before** `enableDischarge(...)` to swap in your own curve.

Reach for this when:

* **You're simulating a well-used competition battery**, which sags earlier and harder than a fresh one, a flatter, lower curve reproduces "that one tired battery" instead of assuming every match starts fresh.
* **You have measured data**, e.g. from putting a real battery on a load tester, feeding in the actual voltage-vs-state-of-charge points gives the most accurate brownout predictions for that specific battery.

The code is in [How do I enable battery discharge simulation?](/documentation/how-to-simulation-and-logging/how-do-i-enable-battery-discharge-simulation#replace-the-state-of-charge-curve-optional).

{% hint style="info" %}
Keys and values should span the full `[0, 1]` state-of-charge range. Querying outside the range you defined just returns the nearest endpoint's voltage instead of extrapolating, so a table missing the low or high end will not sag realistically there.
{% endhint %}

## Capacity derating

Sealed lead-acid batteries are far less [coulombically efficient](https://en.wikipedia.org/wiki/Coulombic_efficiency) than lithium chemistries at high discharge rates. Coulombic efficiency is how much of the charge stored in a battery you actually get back out of it. This is known as the [Peukert effect](https://en.wikipedia.org/wiki/Peukert%27s_law): the faster you discharge a lead-acid battery, the fewer total amp-hours it actually delivers before it's empty. A battery rated for 18 Ah at a light 0.9A discharge (the 20-hour rate its label is based on) might only deliver \~11 Ah at a sustained 54A draw, well within normal FRC match currents.

`enableDischarge(...)` accounts for this by derating the amp-hours consumed against a discharge-current → capacity-fraction curve, so a match spent at high sustained current drains the modeled state of charge faster than the same amp-hours drawn gently would. The default curve is averaged from discharge testing across five FRC battery manufacturers, see [Detailed FRC Battery Comparison for 2026](https://www.chiefdelphi.com/t/detailed-frc-battery-comparison-for-2026/508077). Call `BatterySim.replaceCapacityDerating(...)` **before** `enableDischarge(...)` if you have measured discharge-rate-vs-capacity data for your own battery.

The code is in [How do I enable battery discharge simulation?](/documentation/how-to-simulation-and-logging/how-do-i-enable-battery-discharge-simulation#replace-the-capacity-derating-curve-optional).

## Related pages

* [How do I enable battery discharge simulation?](/documentation/how-to-simulation-and-logging/how-do-i-enable-battery-discharge-simulation)
* [Limiting Power Consumption](/documentation/how-to-motor-controllers-and-sensors/limiting-power-consumption)
* [Simulation without a mechanism](/documentation/reference/editor#simulation-without-a-mechanism)
* [Simulation Only PID + FeedForward](/documentation/understanding/simulation-only-pid-+-feedforward)
* [MOI](/documentation/understanding/turrets-wrists#moment-of-inertia)


# Telemetry

Telemetry is what YAMS tells you about your mechanisms while the code runs: where each one is, where it was asked to go, and what its motors are doing. You watch it live on a dashboard, and you can record it to look at after a match.

## Where to find your mechanism's values

While the code runs, YAMS publishes to NetworkTables, which dashboards such as AdvantageScope and Elastic read. It uses two tables, and nothing goes under `NT:/SmartDashboard`.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-028153a5e05f59f979aecb9ab1b51806a0902b39%2Ftelemetry-tree.png?alt=media" alt="Two NetworkTables trees for an elevator named Elevator with a motor named ElevatorMotor. Under NT Mechanisms are the read-only values such as mechanism/position and motor/outputVoltage. Under NT Tuning are the editable values such as closedloop/feedback/kP, and the Live Tuning command"><figcaption><p>An elevator named <code>Elevator</code> with a motor named <code>ElevatorMotor</code>.</p></figcaption></figure>

| Table            | Holds                                   | Path                                       |
| ---------------- | --------------------------------------- | ------------------------------------------ |
| `NT:/Mechanisms` | What the mechanism is doing. Read-only. | `NT:/Mechanisms/<Mechanism>/<Motor>/<key>` |
| `NT:/Mechanisms` | The mechanism's `Mechanism2d`           | `NT:/Mechanisms/<Mechanism>/mechanism`     |
| `NT:/Tuning`     | Values you can edit                     | `NT:/Tuning/<Mechanism>/<Motor>/<key>`     |
| `NT:/Tuning`     | The `Live Tuning` command               | `NT:/Tuning/<Subsystem>/Live Tuning`       |

`<Mechanism>` and `<Motor>` are the telemetry names given to `withTelemetry(...)` on the mechanism config and on the `SmartMotorControllerConfig`. `<Subsystem>` is the subsystem's `getName()` in Commands v2 (its class name by default), or the Commands v3 `Mechanism`'s name. For the `ArmSubsystem` in the [Arm tutorial](/documentation/tutorials/arm), that is `NT:/Mechanisms/Arm/ArmMotor/...`, `NT:/Tuning/Arm/ArmMotor/...` and `NT:/Tuning/ArmSubsystem/Live Tuning`. See [Live tuning](/documentation/how-to-tuning/live-tuning) for how to use the tunable side.

## The Mechanism2d window

Every mechanism draws itself in a `Mechanism2d`, at `NT:/Mechanisms/<Mechanism>/mechanism`. It is the window you open in the Sim GUI or AdvantageScope in the tutorials' "Simulate it" step. In simulation the mechanism publishes it again on every `simIterate()`, so the drawing moves with the mechanism. It is published on the real robot too, but everything it shows is also in the numeric values, so you don't need it there.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-92566018cca5c925dc61c5a0335e6b4b32c92684%2Ftelemetry-mechanism2d.png?alt=media" alt="The Sim GUI window /Mechanisms/Arm/mechanism for the Arm tutorial&#x27;s arm, at its starting angle of minus 5 degrees. The arm is an orange line from the center of the window to its right edge, with a thinner white setpoint line on top of it. An enlarged view of the pivot shows four short lines: green and pink above the arm for the upper hard and soft limits, and yellow and red below it for the lower soft and hard limits."><figcaption><p>The Arm tutorial's arm in the Sim GUI, with the pivot enlarged on the right.</p></figcaption></figure>

Besides the mechanism itself, it draws a white line for the setpoint and short lines at its limits:

| Color  | Shows                |
| ------ | -------------------- |
| White  | The setpoint         |
| Green  | The upper hard limit |
| Red    | The lower hard limit |
| Pink   | The upper soft limit |
| Yellow | The lower soft limit |

Use them to see at a glance whether the mechanism is heading where you asked, and how close it is to its limits.

{% embed url="<https://docs.wpilib.org/en/stable/docs/software/dashboards/glass/mech2d-widget.html>" %}

## Choosing what a motor publishes

There are two ways to choose: pick a verbosity level, or pick the fields yourself.

### Verbosity levels

`withTelemetry(name, TelemetryVerbosity)` is the quick way. Each level includes the one before it.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-347d143d5360799967545ddf83bb932b69c53df1%2Ftelemetry-verbosity.png?alt=media" alt="Three nested boxes. The outer box is HIGH, which contains MID, which contains LOW. LOW publishes positions and velocities. MID is everything in LOW plus the output voltage and the stator and supply currents. HIGH is everything in MID plus everything tunable: gains, limits and ramp rates, the motor temperature, status booleans and the Live Tuning command"><figcaption><p>HIGH includes MID, and MID includes LOW.</p></figcaption></figure>

| Level  | Adds                                                                                                                                                                                                        | Good for                                              |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| `LOW`  | Positions, velocities and accelerations (`mechanism/*`, `measurement/*`, `rotor/*`, and `externalencoder/*` when there is an external encoder), the setpoints (`closedloop/setpoint/*`) and the active slot | Competition, where you only need to see what happened |
| `MID`  | `motor/outputVoltage`, `current/stator`, `current/supply`                                                                                                                                                   | Checking power draw                                   |
| `HIGH` | Every tunable value, `motor/temperature`, `closedloop/period`, the status booleans, and the `Live Tuning` command                                                                                           | Tuning and development                                |

### Choosing fields yourself

Build a `SmartMotorControllerTelemetryConfig` and enable only what you want:

A fragment from an arm subsystem:

```java
SmartMotorControllerTelemetryConfig motorTelemetryConfig = new SmartMotorControllerTelemetryConfig()
          .withMechanismPosition()
          .withRotorPosition()
          .withMechanismLowerLimit()
          .withMechanismUpperLimit();

SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
      .withClosedLoopController(4, 0, 0)
      .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
      .withSoftLimits(Degrees.of(-30), Degrees.of(100))
      .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
      .withZeroPower(MotorMode.BRAKE)
      .withTelemetry("ArmMotor", motorTelemetryConfig);
```

`withCustom(...)` covers everything else. Use it for a field with no `with*()` method of its own, or to switch several fields in one call. It takes a `BooleanTelemetryField` or `DoubleTelemetryField`, or an array of either, and a boolean:

```java
SmartMotorControllerTelemetryConfig motorTelemetryConfig = new SmartMotorControllerTelemetryConfig()
          .withTelemetryVerbosity(TelemetryVerbosity.LOW)
          .withCustom(SmartMotorControllerTelemetry.DoubleTelemetryField.SupplyCurrent, true)
          .withCustom(new SmartMotorControllerTelemetry.BooleanTelemetryField[]{
              SmartMotorControllerTelemetry.BooleanTelemetryField.MotorInversion,
              SmartMotorControllerTelemetry.BooleanTelemetryField.EncoderInversion
          }, false);
```

In C++ the methods are `WithCustom(field, enabled)` and `WithCustom(std::vector, enabled)`. The Java classes are in `yams.core.telemetry`, and `TelemetryVerbosity` is in `yams.core.telemetry.enums`.

The [`SmartMotorControllerTelemetryConfig` javadoc](https://javadocs.yassrobotics.com/yams/yams/core/telemetry/SmartMotorControllerTelemetryConfig.html) lists every method.

## Recording a match to a DataLog

NetworkTables only shows what is happening now. To look back at a match afterwards, also send the same values to a DataLog file on the SystemCore.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b9e680a59b06ab5795cf6d3e2da6a22b475208de%2Ftelemetry-flow.png?alt=media" alt="Your mechanism feeds MechanismTelemetry, which publishes the same values to NetworkTables, live and on by default and read by dashboards, and to a DataLog file, enabled with withDataLogName and opened in AdvantageScope after the match"><figcaption><p>One set of values, two places to send them.</p></figcaption></figure>

| Destination         | On by default? | Turn it on or off with                | Use it for                   |
| ------------------- | -------------- | ------------------------------------- | ---------------------------- |
| NetworkTables (NT4) | Yes            | `withoutNetworkTables()` turns it off | Watching and tuning live     |
| DataLog file        | No             | `withDataLogName(name)` turns it on   | Reviewing a match afterwards |

Both are set on `SmartMotorControllerTelemetryConfig`. `MechanismTelemetry` does the work: every mechanism, and every `SwerveModule`, owns one, and it sends the same values to both destinations.

To record the arm from the [Arm tutorial](/documentation/tutorials/arm), give its motor a telemetry config with a DataLog name, in place of the `TelemetryVerbosity` it was given:

{% tabs %}
{% tab title="Java" %}

```java
// What the arm motor publishes: the MID fields, live and to a DataLog.
SmartMotorControllerTelemetryConfig armMotorTelemetry = new SmartMotorControllerTelemetryConfig()
    .withTelemetryVerbosity(TelemetryVerbosity.MID)
    .withDataLogName("Arm/ArmMotor");

SmartMotorControllerConfig smcConfig = new SmartMotorControllerConfig(this)
    // ... the rest of the config from the tutorial
    .withTelemetry("ArmMotor", armMotorTelemetry);
```

`SmartMotorControllerTelemetryConfig` is in `yams.core.telemetry`.
{% endtab %}

{% tab title="C++" %}

```cpp
// What the arm motor publishes: the MID fields, live and to a DataLog.
yams::telemetry::SmartMotorControllerTelemetryConfig armMotorTelemetry;
armMotorTelemetry
    .WithTelemetryVerbosity(Cfg::TelemetryVerbosity::MID)
    .WithDataLogName("Arm/ArmMotor");

m_smcConfig
    // ... the rest of the config from the tutorial
    .WithTelemetry("ArmMotor", armMotorTelemetry);
```

{% endtab %}
{% endtabs %}

Every field the config turns on is then also written to the DataLog under `Arm/ArmMotor`. Only the values you read are logged; the values you can type under `NT:/Tuning` are not. To log during matches without filling NetworkTables, add `.withoutNetworkTables()` to the telemetry config. Live tuning then has nothing to edit, so leave it off while you tune.

{% hint style="success" %}
Set a DataLog name for competition matches. It is one line, and it means you can see what actually happened on the field.
{% endhint %}

{% hint style="info" %}
A DataLog uses storage on the SystemCore, and logging everything fills it quickly. Log only what you need. See the [WPILib DataLog docs](https://docs.wpilib.org/en/stable/docs/software/telemetry/datalog.html#custom-data-logging-using-datalog).
{% endhint %}

* [DataLog Best Practices](/documentation/understanding/datalog-best-practices): choosing what to log, and how it works for `SwerveDrive`.
* [How do I view my DataLog in AdvantageScope?](/documentation/how-to-simulation-and-logging/how-do-i-view-my-datalog-in-advantagescope): a step by step walkthrough.

## Swerve drive telemetry

A swerve drive publishes poses, chassis velocities and module states. Those are not single numbers, so they are published as NT4 structs that AdvantageScope understands directly.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-627f3f23380b876348e0529d5e987b6b58706de1%2Ftelemetry-swerve-tree.png?alt=media" alt="The NetworkTables tree for a swerve drive named swerve: pose and gyro at LOW verbosity, chassis/current, chassis/field and states/current at MID, chassis/desired and states/desired at HIGH, the tuning command, and a modules table with one entry per module holding its absolute encoder, its state and its drive and azimuth motors"><figcaption><p>What a swerve drive publishes, and at which verbosity.</p></figcaption></figure>

### Setting it up

`SwerveDrive` and `SwerveModule` have their own telemetry configs. They work the same way as a motor's: every field is off until a verbosity level or a `with*()` method turns it on.

| Config                        | Passed to                                        | Notable fields                                                                       |
| ----------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------ |
| `SwerveDriveTelemetryConfig`  | `SwerveDriveConfig.withTelemetry(name, config)`  | `withPose()`, `withGyro()`, `withCurrentModuleStates()`, `withDesiredModuleStates()` |
| `SwerveModuleTelemetryConfig` | `SwerveModuleConfig.withTelemetry(name, config)` | `withAbsoluteEncoder()`, `withState()`                                               |

```java
SwerveDriveTelemetryConfig driveTelemetryConfig = new SwerveDriveTelemetryConfig()
    .withTelemetryVerbosity(TelemetryVerbosity.HIGH)
    .withPose()
    .withGyro()
    .withCurrentRobotRelativeChassisSpeeds()
    .withFieldRelativeChassisSpeeds()
    .withDesiredRobotRelativeChassisSpeeds()
    .withDesiredModuleStates()
    .withCurrentModuleStates()
    .withDataLogName("swerve");

SwerveDriveConfig driveConfig = new SwerveDriveConfig(this, frontLeft, frontRight, backLeft, backRight)
    .withGyro(gyro::getRotation3d)
    .withTelemetry("swerve", driveTelemetryConfig);
```

`new SwerveDriveTelemetryConfig(TelemetryVerbosity.HIGH)` is shorthand for `new SwerveDriveTelemetryConfig().withTelemetryVerbosity(TelemetryVerbosity.HIGH)`. `SwerveModuleTelemetryConfig` has the same shorthand.

### Things that differ from a motor

* **The name is required.** `SwerveDriveConfig.withTelemetry(...)` always takes the name first: `withTelemetry(name, TelemetryVerbosity)` or `withTelemetry(name, SwerveDriveTelemetryConfig)`. There is no `withTelemetryName(...)`.
* **DataLog is set on the telemetry config.** `SwerveDriveConfig` and `SwerveModuleConfig` have no `withDataLogName(...)`. Use `SwerveDriveTelemetryConfig.withDataLogName(...)` and `SwerveModuleTelemetryConfig.withDataLogName(...)`.
* **A module's state is `HIGH` only.** At `LOW` and `MID` a module publishes only its absolute encoder angle.
* **The motors are configured separately.** Neither swerve config reaches the drive and azimuth motors inside a module. Give each motor's `SmartMotorControllerConfig` its own `.withTelemetry(name, SmartMotorControllerTelemetryConfig)`, as for any other motor. See [DataLog Best Practices](/documentation/understanding/datalog-best-practices).
* **`withCustom(...)` works here too.** It takes a `DoubleTelemetryField`, `StructTelemetryField`, `StructArrayTelemetryField` or `BooleanTelemetryField`, or an array of one, and a boolean.

{% hint style="info" %}
WPILib 2027 renamed `ChassisSpeeds` to `ChassisVelocities` and `SwerveModuleState` to `SwerveModuleVelocity`. The YAMS method and telemetry field names (`withDesiredModuleStates()`, `setSwerveModuleStates(...)`, `withFieldRelativeChassisSpeeds()`) kept their old spelling.
{% endhint %}

<details>

<summary>How struct telemetry works: StructTelemetry and StructArrayTelemetry</summary>

`SmartMotorControllerTelemetry` publishes plain numbers and booleans with `DoubleTelemetry` and `BooleanTelemetry`. Swerve telemetry is built on two generic counterparts:

| Class                     | Publishes                 | Used for                                                  |
| ------------------------- | ------------------------- | --------------------------------------------------------- |
| `StructTelemetry<T>`      | One struct value          | `Pose2d`, `ChassisVelocities`, one `SwerveModuleVelocity` |
| `StructArrayTelemetry<T>` | An array of struct values | The four module `SwerveModuleVelocity[]` fields           |

Both behave like `DoubleTelemetry`: they can be enabled per field, sent to NetworkTables and to a DataLog, and, for fields marked tunable, read back a value edited on the dashboard. You do not normally construct them yourself. The swerve telemetry configs create and manage them.

</details>

### Live tuning

At `HIGH` verbosity `SwerveDriveTelemetryConfig` also publishes tunable keys for auto-align and for the drive and azimuth motors under `NT:/Tuning/<name>/`. See [Tune a swerve drive](/documentation/how-to-tuning/live-tuning/swerve-drive) for the keys and how to use them.

## Units

Values you read under `NT:/Mechanisms` are in rotations and rotations per second, or meters and meters per second for a mechanism with a circumference. Values you type under `NT:/Tuning` are in degrees and RPM, or meters. AdvantageScope can show any value in other units: right-click it in a graph legend and choose **Convert Units...**.

[Live tuning keys and units](/documentation/reference/keys-and-units#units-of-each-key) lists the unit of every key.

## Next

* Watch your mechanism while you tune it: [Step 5: Tune it](/documentation/tutorials/arm/tune)
* Review a match afterwards: [How do I view my DataLog in AdvantageScope?](/documentation/how-to-simulation-and-logging/how-do-i-view-my-datalog-in-advantagescope)


# DataLog best practices

{% hint style="info" %}
Using DataLog will increase your storage usage on the SystemCore and could have negative consequences if left unmanaged. Review [WPILib's DataLog documentation](https://docs.wpilib.org/en/stable/docs/software/telemetry/datalog.html#custom-data-logging-using-datalog) for more information.
{% endhint %}

Every YAMS telemetry field is published to NetworkTables by default. Separately, you can opt any field into a WPILib `DataLog`, the same file format read by AdvantageScope offline, and the one WPILib's `DataLogManager` automatically saves to a USB drive or the SystemCore's local storage during a match. This page covers how to control both destinations independently, and calls out the one place, `SwerveDrive`, where the rules are different.

## The two knobs: NetworkTables and DataLog

For any single-motor mechanism (`Arm`, `Elevator`, `Pivot`, `FlyWheel`, `DifferentialMechanism`, `DoubleJointedArm`) telemetry is controlled per motor controller with `SmartMotorControllerTelemetryConfig`:

```java
SmartMotorControllerTelemetryConfig telemetryConfig = new SmartMotorControllerTelemetryConfig()
    .withTelemetryVerbosity(TelemetryVerbosity.LOW)
    .withStatorCurrent()
    .withTemperature()
    .withDataLogName("motors/shooter")   // log the fields above to DataLog...
    .withoutNetworkTables();             // ...and don't publish them to NT4

SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withClosedLoopController(4, 0, 0)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withTelemetry("ShooterMotor", telemetryConfig);
```

* `withDataLogName(name)` turns on DataLog for every field enabled on that config, under the given prefix.
* `withoutNetworkTables()` (or `withNetworkTables(false)`) stops those fields from being published to NT4 at all. You can freely enable DataLog, NetworkTables, both, or neither, they're independent toggles.
* Which fields get logged is controlled the same way for both destinations, there's only one set of enabled fields, per `withTelemetryVerbosity()` and the individual `with*()` methods described in [Telemetry](/documentation/understanding/telemetry).

{% hint style="success" %}
Set a DataLogName for competition matches. It costs almost nothing to add and gives you a full record to review between matches, often the difference between guessing why a mechanism stalled and knowing exactly why.
{% endhint %}

## Choosing what to log

Every field is disabled by default. `withTelemetryVerbosity()` gives you a cumulative preset (`LOW` → `MID` → `HIGH`, each including everything below it) so you don't have to enable dozens of fields by hand, then layer on or remove individual fields as needed.

A few guidelines:

* **Don't just reach for `HIGH` everywhere.** `HIGH` includes PID gains, feedforward gains, current limits, and every boolean status flag, useful while tuning, but mostly redundant once a mechanism is dialed in. Prefer `LOW` or `MID` plus the handful of fields you actually watch (current, temperature, setpoint and position) for a competition build.
* **Prune before you log, not after.** DataLog files only grow, there's no way to selectively remove a field after the fact without re-recording. Decide what you need before the match, not while reviewing the log afterward.
* **DataLog is not a substitute for NetworkTables during development.** Live tools (Elastic, Shuffleboard, AdvantageScope in live mode) read NT4, not DataLog. Keep NetworkTables on while you're actively tuning, and consider disabling it only for fields you truly don't need live, once you're locking in a competition build.

Need to flip a field that doesn't have its own `with*()` method, or toggle several fields at once? `withCustom(field, value)` takes any `BooleanTelemetryField`/`DoubleTelemetryField` (or an array of either) plus a boolean, and enables or disables them accordingly:

```java
SmartMotorControllerTelemetryConfig telemetryConfig = new SmartMotorControllerTelemetryConfig()
    .withTelemetryVerbosity(TelemetryVerbosity.LOW)
    .withCustom(new SmartMotorControllerTelemetry.DoubleTelemetryField[]{
        SmartMotorControllerTelemetry.DoubleTelemetryField.SupplyCurrent,
        SmartMotorControllerTelemetry.DoubleTelemetryField.StatorCurrentLimit
    }, true);
```

## Enabling/disabling NetworkTables conditionally

`withNetworkTables(boolean)` takes a plain boolean, read once when the config is built, so drive it from a constant you set before you deploy:

```java
// Constants.java: set to true before you deploy for matches.
public static final boolean COMPETITION = false;

SmartMotorControllerTelemetryConfig telemetryConfig = new SmartMotorControllerTelemetryConfig()
    .withTelemetryVerbosity(TelemetryVerbosity.LOW)
    .withDataLogName("motors/shooter")
    .withNetworkTables(!Constants.COMPETITION);
```

This keeps full NT4 telemetry for pit testing and practice, and drops NT4 traffic (while still writing to DataLog) in the code you deploy for matches.

{% hint style="warning" %}
`RobotState.isFMSAttached()` does not work here. The config is built when the robot code starts, before the field connects, so it reads `false` and NetworkTables stays on in every match.
{% endhint %}

## Swerve drive is different

{% hint style="warning" %}
`SwerveDriveConfig`/`SwerveModuleConfig` do **not** use `SmartMotorControllerTelemetryConfig`, they have their own `SwerveDriveTelemetryConfig`/`SwerveModuleTelemetryConfig`. The shape is the same (verbosity preset plus individual `with*()` fields, `withoutNetworkTables()`, `withDataLogName(...)`), but the DataLog name for both the drive-level fields (pose, gyro, chassis speeds, module states) and a module's absolute encoder angle has to go through the telemetry config, neither `SwerveDriveConfig` nor `SwerveModuleConfig` has a `withDataLogName(...)` of its own.
{% endhint %}

`SwerveDriveConfig.withTelemetry(name, TelemetryVerbosity)` and `SwerveModuleConfig.withTelemetry(name, TelemetryVerbosity)` pick a verbosity preset the same way a single-motor mechanism does, both always take the telemetry name as the first argument, there's no name-less overload. For anything more, hand `withTelemetry(name, ...)` a `SwerveDriveTelemetryConfig`/`SwerveModuleTelemetryConfig` instead of a bare `TelemetryVerbosity`, that's what lets you enable individual fields, disable NetworkTables, or set a DataLog name for the drive-level and per-module fields (pose, gyro, chassis speeds, module states, absolute encoder angle).

You can still send this to DataLog:

```java
SwerveDriveConfig driveConfig = new SwerveDriveConfig(this, frontLeft, frontRight, backLeft, backRight)
    .withGyro(gyro::getRotation3d)
    .withTelemetry("swerve", new SwerveDriveTelemetryConfig(TelemetryVerbosity.HIGH)
        .withDataLogName("swerve"));                 // logs pose, gyro, chassis speeds, module states

SwerveModuleConfig frontLeftConfig = new SwerveModuleConfig(driveMotorFL, azimuthMotorFL)
    .withWheelRadius(Meters.of(0.0508))
    .withLocation(new Translation2d(0.381, 0.381))
    .withTelemetry("FrontLeft", new SwerveModuleTelemetryConfig(TelemetryVerbosity.HIGH)
        .withDataLogName("swerve/frontLeft"));       // logs this module's absolute encoder angle (+ state at HIGH)
```

`new SwerveDriveTelemetryConfig(TelemetryVerbosity.HIGH)`/`new SwerveModuleTelemetryConfig(TelemetryVerbosity.HIGH)` are shorthand constructors for `new SwerveDriveTelemetryConfig().withTelemetryVerbosity(TelemetryVerbosity.HIGH)` and the module equivalent. Each module's DataLog name is independent of the drive's `SwerveDriveTelemetryConfig.withDataLogName(...)` above, set it separately per module if you want per-module DataLog prefixes.

{% hint style="info" %}
Neither the drive's nor a module's DataLog name cascades to the drive/azimuth motors that make up that module. Setting one does not log the other, and neither logs the motors.
{% endhint %}

### Getting granular fields out of a swerve module's motors

The drive and azimuth motors of a `SwerveModule` are still ordinary `SmartMotorController`s under the hood. If you want field-level control (or a DataLog name) on just the drive motor or just the azimuth motor, set it on that motor's own `SmartMotorControllerConfig`, before you build the `SwerveModule`, exactly as you would for a standalone motor:

```java
SmartMotorControllerTelemetryConfig driveTelemetry = new SmartMotorControllerTelemetryConfig()
    .withStatorCurrent()
    .withTemperature()
    .withDataLogName("swerve/frontLeft/drive");

SmartMotorControllerConfig driveMotorConfig = new SmartMotorControllerConfig(this)
    .withClosedLoopController(0.1, 0.0, 0.0)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(6.75)))
    .withTelemetry("driveMotor", driveTelemetry);

SmartMotorController driveMotorFL = new TalonFXWrapper(new TalonFX(10, new CANBus(CANPort.CAN_S0)), DCMotor.getKrakenX60(1), driveMotorConfig);
```

This gives you the same fine-grained control (and independent DataLog name) on that one motor that you'd get on any other mechanism's motor, it's only the swerve-level pose/gyro/chassis-speed/encoder fields that are all-or-nothing per verbosity level.

## Related pages

* [Telemetry](/documentation/understanding/telemetry)
* [Swerve Drive](/documentation/tutorials/swerve-drive)
* [How do I view my DataLog in AdvantageScope?](/documentation/how-to-simulation-and-logging/how-do-i-view-my-datalog-in-advantagescope)


# Smart motor controllers

A `SmartMotorController` is how YAMS drives one motor. You describe the motor once in a `SmartMotorControllerConfig` (its gearing, gains, limits and encoders), and a wrapper such as `TalonFXWrapper`, `SparkWrapper`, `NovaWrapper` or `A301Wrapper` applies it to the vendor's motor controller. The same config works on every supported motor controller.

New to YAMS? Read [How YAMS drives a motor](/documentation/tutorials/how-yams-drives-a-motor) first. It explains the three layers (motor controller, mechanism, subsystem), the words rotor, mechanism and measurement, open and closed loop, and the units your gains are in.

## Where to go next

| You want to                                             | Read                                                                                                                                                                                                                   |
| ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Look up what an option does                             | [SmartMotorControllerConfig](/documentation/reference/editor/config), one page per group of options                                                                                                                    |
| Check whether your motor controller supports an option  | [Motor controller feature matrix](/documentation/reference/editor/feature-matrix)                                                                                                                                      |
| Set up followers, external encoders or a vendor config  | [Followers](/documentation/reference/editor/config/followers), [Encoders](/documentation/reference/editor/config/encoders), [`withVendorConfig`](/documentation/reference/editor/config/motor-basics#withvendorconfig) |
| Keep settings already saved on the motor controller     | [`withResetPreviousConfig`](/documentation/reference/editor/config/motor-basics#withresetpreviousconfig)                                                                                                               |
| Use different gains in simulation                       | [Simulation-only PID + feedforward](/documentation/understanding/simulation-only-pid-+-feedforward)                                                                                                                    |
| Stop brownouts                                          | [Limiting power consumption](/documentation/how-to-motor-controllers-and-sensors/limiting-power-consumption)                                                                                                           |
| Choose between a trapezoidal and an exponential profile | [Exponential profiles](/documentation/understanding/exponential-profiles#when-to-use-each-profile-type)                                                                                                                |
| Replace PID with a model based controller               | [LQR controllers](/documentation/understanding/lqr-controllers)                                                                                                                                                        |
| Find your gains                                         | [Live tuning](/documentation/how-to-tuning/live-tuning)                                                                                                                                                                |

{% hint style="warning" %}
Not every option works on every motor controller. See [which options are not supported everywhere](/documentation/reference/editor/config#not-every-option-works-on-every-motor-controller).
{% endhint %}

## Reach the vendor objects yourself

YAMS does not have an option for every vendor setting. For a setting it does not have, start from your own vendor config with [`withVendorConfig`](/documentation/reference/editor/config/motor-basics#withvendorconfig). To call the vendor's API directly, fetch the vendor objects from the `SmartMotorController`. Both methods return `Object`, so cast to the class your wrapper holds:

```java
// A SparkWrapper around a SPARK Flex
SparkFlex sparkFlex = (SparkFlex) smartMotorController.getMotorController();
SparkFlexConfig sparkFlexConfig = (SparkFlexConfig) smartMotorController.getMotorControllerConfig();
```

## Motor options stay on the motor config

A mechanism config such as `ArmConfig` never changes the `SmartMotorControllerConfig`. Soft limits, the starting position, gearing and gains are always set on the motor config. [Mechanism configs](/documentation/reference/mechanism-configs) lists what each mechanism config sets.

## Simulation without a mechanism

A mechanism class simulates its motor for you. A `SmartMotorController` used on its own needs `simIterate()` and `updateTelemetry()` called every loop: see [Running the simulation](/documentation/reference/editor/config/simulation#running-the-simulation).

## Learn more about motors

{% embed url="<https://youtu.be/0BfR_viZSmQ>" %}

{% embed url="<https://youtu.be/pIKvQX5p1PE>" %}

The presentation from the video series continues onto PID, feedforward and motion profiles.

{% file src="/files/Zw793TT7TdZ666pgmjCw" %}

The WPILib docs explain PID and feedforward with interactive simulations: see [tuning a turret position controller](https://docs.wpilib.org/en/stable/docs/software/advanced-controls/introduction/tuning-turret.html).


# SmartMotorControllerConfig

A `SmartMotorControllerConfig` describes one motor: how it is geared, how it is controlled, what it must not do and what it reports. You write it once, in the same way for every vendor, and hand it to a wrapper such as `TalonFXWrapper`, `SparkWrapper`, `NovaWrapper` or `A301Wrapper`.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d1ba4ddca3f93cf600dca36387e9fe00588c5e07%2Fsmc-config-map.png?alt=media" alt="A grid of nine groups of SmartMotorControllerConfig options: motor basics, gearing and units, closed loop control, feedforward, motion profiles, limits and protection, encoders, followers and simulation, each listing its main methods."><figcaption><p>The option groups. Each has its own page.</p></figcaption></figure>

## Where to find each option

| Page                                                                                  | What it covers                                                                                    |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| [Motor basics](/documentation/reference/editor/config/motor-basics)                   | Control mode, inversion, brake or coast, starting from a clean config, vendor configs, telemetry. |
| [Gearing and units](/documentation/reference/editor/config/gearing-and-units)         | Gear ratios, circumference, wheels and drums, cascading elevator stages.                          |
| [Closed loop control](/documentation/reference/editor/config/closed-loop-control)     | PID gains, slots, tolerance, continuous wrapping, output limits, where the loop runs.             |
| [Feedforward](/documentation/reference/editor/config/feedforward)                     | Simple, arm and elevator feedforwards and what each gain does.                                    |
| [Motion profiles](/documentation/reference/editor/config/motion-profiles)             | Trapezoidal, velocity and exponential profiles.                                                   |
| [Limits and protection](/documentation/reference/editor/config/limits-and-protection) | Soft limits, current limits, ramp rates, voltage compensation, temperature cutoff.                |
| [Encoders](/documentation/reference/editor/config/encoders)                           | Starting position, encoder inversion, external encoders and their zero offset.                    |
| [Followers](/documentation/reference/editor/config/followers)                         | Followers on one shaft, and loosely coupled followers.                                            |
| [Simulation](/documentation/reference/editor/config/simulation)                       | Simulation-only gains, starting position, moment of inertia and step size.                        |

## How the config is used

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-7cb7fb9be9c63e0d415bf43596902cf1545a256c%2Fsmc-config-flow.png?alt=media" alt="A flow diagram. Your SmartMotorControllerConfig goes to a wrapper such as TalonFXWrapper, SparkWrapper or NovaWrapper, which translates each option into the vendor&#x27;s own config, which is sent once at startup to the motor controller. An option the controller cannot do throws an exception at startup that names the method to change."><figcaption><p>The same config works for every supported motor controller.</p></figcaption></figure>

```java
SmartMotorControllerConfig config = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withClosedLoopController(4, 0, 0)
    .withFeedforward(new ArmFeedforward(0, 0.3, 1.2))
    .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(360))
    .withSoftLimits(Degrees.of(-20), Degrees.of(100))
    .withStatorCurrentLimit(Amps.of(40))
    .withZeroPower(MotorMode.BRAKE)
    .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH);

SparkMax spark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);
SmartMotorController motor = new SparkWrapper(spark, DCMotor.getNEO(1), config);
```

This is a fragment: it goes inside a subsystem, which is the `this` passed to the config. [Step 1 of the Arm tutorial](/documentation/tutorials/arm/motor-controller) builds the same thing as a complete file.

Three things are worth knowing before reading the option pages:

* **Every `with...()` method returns the config**, so options chain. A few options depend on an earlier one and say so on their page, for example `withClosedLoopTolerance` needs a PID controller first.
* **Options are checked when the wrapper is created.** An option that motor controller cannot do throws an exception, so problems show up at startup and not mid-match. It is usually a `SmartMotorControllerConfigurationException` that names the method to change, and for a few options an `IllegalArgumentException`. Each option says which.
* **The motor's config holds the motor's limits.** Soft limits, starting position and gearing go on the `SmartMotorControllerConfig`, even when a mechanism uses the motor. The mechanism's own config (`ArmConfig`, `ElevatorConfig` and so on) describes the mechanism: its length, mass and hard stops.

## Not every option works on every motor controller

{% hint style="warning" %}
Motor controllers differ. Some options only exist on one of them, and some only work in certain situations, for example only when the closed loop runs on the SystemCore. An option a controller cannot do normally throws a `SmartMotorControllerConfigurationException` or an `IllegalArgumentException` at startup, but check the table for each option you rely on.
{% endhint %}

Every option on the following pages has a table showing where it works. The [motor controller feature matrix](/documentation/reference/editor/feature-matrix#feature-support-matrix) has every option against every motor controller in one place. The ones that most often catch teams out:

* **TalonFX and TalonFXS:** no [`withClosedLoopTolerance`](/documentation/reference/editor/config/closed-loop-control#withclosedlooptolerance), no [`withVoltageCompensation`](/documentation/reference/editor/config/limits-and-protection#withvoltagecompensation), no `SLOT_3`, and [`withEncoderInverted`](/documentation/reference/editor/config/encoders#withencoderinverted) only on a TalonFXS.
* **SPARK MAX and SPARK Flex:** no [supply current limit](/documentation/reference/editor/config/limits-and-protection#withstatorcurrentlimit-and-withsupplycurrentlimit) and no [`withVendorControlRequest`](/documentation/reference/editor/config/motor-basics#withvendorcontrolrequest). Several options only work when the loop runs on the SystemCore, with an exponential profile or an [LQR](/documentation/understanding/lqr-controllers).
* **Thrifty Nova:** two closed loop slots, both soft limits or neither, and [one ramp rate](/documentation/reference/editor/config/limits-and-protection#withopenloopramprate-and-withclosedloopramprate) for open and closed loop control. Like a SPARK, several options only work when the loop runs on the SystemCore. Wrapping the Nova can't do runs the loop on the SystemCore.
* **FIRST A301:** no current limits, ramp rates, voltage compensation, vendor config or [`withFollowers`](/documentation/reference/editor/config/followers#withfollowers) (use loosely coupled followers), and its only external encoder is its own. Every closed loop runs on the SystemCore, and [soft limits](/documentation/reference/editor/config/limits-and-protection#withsoftlimits) only move position setpoints.
* **Everywhere:** [soft limits](/documentation/reference/editor/config/limits-and-protection#withsoftlimits) only work in closed loop mode, and [`withVendorConfig`](/documentation/reference/editor/config/motor-basics#withvendorconfig), [`withExternalEncoder`](/documentation/reference/editor/config/encoders#withexternalencoder) and [`withFollowers`](/documentation/reference/editor/config/followers#withfollowers) only take that vendor's own parts.

Many of these depend on where the closed loop runs, which is explained in [where the loop runs](/documentation/reference/editor/config/closed-loop-control#where-the-loop-runs).

## Changing a config later

Most options can be changed while the robot runs through [live tuning](/documentation/how-to-tuning/live-tuning), which is the quickest way to find gains and limits. Once you have them, put the numbers back in the config so they survive a restart.

## Code reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)


# Motor basics

The options every motor needs, whatever it drives.

{% hint style="warning" %}
Not every option on this page is supported on every motor controller. Each option has a table showing where it works, and an option a controller cannot do throws a `SmartMotorControllerConfigurationException` or an `IllegalArgumentException` at startup. Each option says which. The [config overview](/documentation/reference/editor/config#not-every-option-works-on-every-motor-controller) lists them all together.
{% endhint %}

## `withControlMode`

Chooses whether the motor controller runs a closed loop controller. The default is `ControlMode.CLOSED_LOOP`.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-a48a31fa0da188e6c1bb4094d31caac6d12de543%2Fsmc-control-mode.png?alt=media" alt="Two panels. In OPEN_LOOP your code sends volts or duty cycle straight to the motor and no PID, feedforward or profile runs. In CLOSED_LOOP, the default, your code sends a setpoint to the PID, feedforward and profile, which drive the motor using the encoder position and velocity."><figcaption><p>Open loop sends an output straight to the motor. Closed loop drives to a setpoint.</p></figcaption></figure>

```java
.withControlMode(ControlMode.OPEN_LOOP)   // a roller that only ever gets a voltage
.withControlMode(ControlMode.CLOSED_LOOP) // anything that goes to a position or a speed
```

In `OPEN_LOOP` the closed loop options on the other pages have nothing to act on, and the [soft limits](/documentation/reference/editor/config/limits-and-protection#withsoftlimits) are not enforced on any motor controller.

**Supported on:** every supported motor controller.

## `withMotorInverted`

Chooses which way the motor turns for a positive output.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-305c3bc1fb60370519cf873ff04f59f5b00b75ed%2Fsmc-motor-inverted.png?alt=media" alt="Two motors given the same positive 6 volts. Without inversion the motor turns one way and the position counts up in that direction. With inversion it turns the other way and the position counts up that way instead."><figcaption><p>The same positive voltage, not inverted and inverted.</p></figcaption></figure>

```java
.withMotorInverted(true)
```

Decide it once, with the mechanism free to move and a small voltage, before tuning anything. Encoders have their own inversion: see [Encoders](/documentation/reference/editor/config/encoders#withencoderinverted).

**Supported on:** every supported motor controller.

## `withZeroPower`

Chooses what the motor does when the output is zero: `MotorMode.BRAKE` or `MotorMode.COAST`.

* **`MotorMode.BRAKE`**: a motor that is not powered resists being moved. It stops quickly, and it is hard to turn by hand.
* **`MotorMode.COAST`**: a motor that is not powered moves freely. It keeps going until friction stops it, and it turns easily by hand.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-fb4b34e75628cac3004138ce8661d8c8bb2ffa7a%2Fsmc-zero-power.png?alt=media" alt="A graph of speed against time. When the output goes to zero, a motor in BRAKE mode stops quickly and then resists being moved, and a motor in COAST mode keeps moving and is free to be moved. Either mode is your choice. BRAKE resists movement but does not hold an arm or elevator up, and COAST suits flywheels."><figcaption><p>Brake and coast after the output goes to zero.</p></figcaption></figure>

```java
.withZeroPower(MotorMode.BRAKE)
```

What that looks like on a mechanism once the output is zero:

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-26850cdf90d5a6cfb5aed9433e78480438f2b9df%2Fsmc-zero-power-mechanisms.gif?alt=media" alt="Animation of an elevator, an arm, a pivot and a flywheel, each shown in brake mode and in coast mode. All are driven and then the output goes to zero. In brake mode the pivot stops and stays, the flywheel stops quickly, and the elevator and the arm sink slowly. In coast mode the elevator falls to the bottom, the arm falls onto its hard stop, the pivot keeps turning and the flywheel keeps spinning."><figcaption><p>Not powered, a mechanism in brake mode resists movement and a mechanism in coast mode moves freely.</p></figcaption></figure>

| Mechanism               | Not powered in `BRAKE`      | Not powered in `COAST`                   |
| ----------------------- | --------------------------- | ---------------------------------------- |
| Elevator                | Sinks slowly                | Falls                                    |
| Arm                     | Sinks slowly                | Falls                                    |
| Pivot (turret or wrist) | Stops and stays where it is | Keeps turning, and moves when bumped     |
| Flywheel                | Stops quickly               | Keeps spinning and slows down on its own |

With nothing pulling on it, a mechanism in brake mode does not move while it is not powered, and the same mechanism in coast mode does. Gravity is something pulling on it, so most arms and elevators still sink in brake mode, only slower than they fall in coast mode.

An arm or an elevator can stay up in brake mode, but only when it was built to:

* **An elevator with a constant force spring** that carries the weight of the carriage has nothing left pulling it down.
* **An arm whose motor resists harder than gravity pulls**, through enough gearing or a light enough arm, stays where it stopped.

Both are mechanical, decided when the mechanism is designed, and nothing in your code makes them happen. Treat it as something to strive for when you design a mechanism, not something to expect from one.

{% hint style="info" %}
**Brake mode is an option, not a requirement, and it is not how a mechanism holds its position.** An arm or an elevator does not need brake mode to hold: the closed loop controller and [`kG`](/documentation/reference/editor/config/feedforward) hold it, in either mode, for as long as it is powered. Brake mode only changes what happens when it is not, such as when the robot is disabled.
{% endhint %}

**Supported on:** every supported motor controller.

## `withResetPreviousConfig`

By default YAMS resets the motor controller to factory defaults before applying your config, so settings left over from another robot or a vendor tool cannot surprise you.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-ba628d06d4973f9e80b4c79f0922d331d721e1e1%2Fsmc-config-layers.png?alt=media" alt="Two stacks of layers applied top to bottom. With the reset on, the default, the controller starts from factory defaults, then your vendor config if you gave one, then your SmartMotorControllerConfig options. With the reset off it starts from whatever is already saved on the controller, so old settings you did not set stay."><figcaption><p>What the controller ends up with, with and without the reset.</p></figcaption></figure>

```java
.withResetPreviousConfig(false) // keep what is already saved on the controller
```

**Supported on:** every supported motor controller. An A301 ignores it.

## `withVendorConfig`

Gives YAMS a vendor config to start from, for settings YAMS has no option for. Your `SmartMotorControllerConfig` options are applied on top of it and win where both set the same thing.

```java
.withVendorConfig(new TalonFXConfiguration()
    .withVoltage(new VoltageConfigs().withPeakReverseVoltage(0)))
```

Each wrapper accepts only its own vendor's root config class. The classes and an example for each vendor are in [vendor configuration classes](/documentation/reference/editor/feature-matrix#vendor-configuration-classes), and [How do I use a vendor hardware config?](/documentation/how-to-motor-controllers-and-sensors/how-do-i-use-a-vendor-hardware-config) walks through it.

**Not supported everywhere.** Every controller but the A301 accepts a vendor config, but only its own class. Any other class throws a `SmartMotorControllerConfigurationException`. The A301 has no vendor config, so any vendor config throws one.

| TalonFX                  | TalonFXS                  | SPARK MAX / Flex                        | Thrifty Nova          | A301 |
| ------------------------ | ------------------------- | --------------------------------------- | --------------------- | ---- |
| ✅ `TalonFXConfiguration` | ✅ `TalonFXSConfiguration` | ✅ `SparkMaxConfig` or `SparkFlexConfig` | ✅ `NovaConfig.Config` | ❌    |

## `withVendorControlRequest`

Replaces the control request YAMS would send for position or velocity control with one of the vendor's own.

By default YAMS picks the request for you: a plain position or velocity request, or a Motion Magic one when you set a [motion profile](/documentation/reference/editor/config/motion-profiles). This option is for when you want a different one, most often:

* **Torque control**, with a `TorqueCurrentFOC` request, so the closed loop commands current instead of voltage.
* **Duty cycle output**, with a `DutyCycle` request, instead of YAMS's voltage requests.
* **A request with your own settings on it**, such as `withUpdateFreqHz`, `withOverrideBrakeDurNeutral` or the limit switch options.

### How to use it

Build the request once and give it to the config. YAMS keeps your object and fills in the setpoint every time it commands the motor, so every other setting on it stays as you made it. The value you construct it with is a placeholder: `0` is fine.

{% code title="ArmSubsystem.java" %}

```java
import com.ctre.phoenix6.controls.MotionMagicTorqueCurrentFOC;

private final SmartMotorControllerConfig motorConfig = new SmartMotorControllerConfig(this)
    .withControlMode(ControlMode.CLOSED_LOOP)
    .withClosedLoopController(60, 0, 4)
    .withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(90))
    .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
    .withZeroPower(MotorMode.BRAKE)
    .withTelemetry("ArmMotor", TelemetryVerbosity.HIGH)
    // Motion Magic on torque current instead of voltage.
    .withVendorControlRequest(new MotionMagicTorqueCurrentFOC(0));
```

{% endcode %}

Nothing else changes. `arm.run(Degrees.of(45))`, `arm.runTo(Degrees.of(45), Degrees.of(2))` and every other command work as before, and now send your request.

### Rules

* **One request per config.** A position request replaces the one used for positions, and a velocity request replaces the one used for velocities. The other kind keeps YAMS's default.
* **Match it to your profile.** YAMS only sets up Motion Magic when the config has a motion profile, so use a `MotionMagic` request with a profile and a `Position` or `Velocity` request without one.
* **A `TorqueCurrentFOC` request changes what your gains mean.** The closed loop output is current in amps, not volts, so gains tuned for a voltage request do not carry over. Tune them again from the start.
* **A `TorqueCurrentFOC` request cannot have FOC switched on or off.** It is always FOC, so the FOC toggles on the wrapper throw a `SmartMotorControllerConfigurationException` with one.

### Supported requests

**Not supported everywhere.** Anything that is not on this list throws a `SmartMotorControllerConfigurationException` when the config is applied.

| Motor controller  | Position requests                                                                                                                                                                                     | Velocity requests                                                                                                                                                       |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| TalonFX, TalonFXS | `PositionVoltage`, `PositionDutyCycle`, `PositionTorqueCurrentFOC`, `MotionMagicVoltage`, `MotionMagicDutyCycle`, `MotionMagicTorqueCurrentFOC`, `MotionMagicExpoVoltage`, `MotionMagicExpoDutyCycle` | `VelocityVoltage`, `VelocityDutyCycle`, `VelocityTorqueCurrentFOC`, `MotionMagicVelocityVoltage`, `MotionMagicVelocityDutyCycle`, `MotionMagicVelocityTorqueCurrentFOC` |
| SPARK MAX / Flex  | ❌ Throws a `SmartMotorControllerConfigurationException`                                                                                                                                               | ❌ Throws a `SmartMotorControllerConfigurationException`                                                                                                                 |
| Thrifty Nova      | ❌ Throws a `SmartMotorControllerConfigurationException`                                                                                                                                               | ❌ Throws a `SmartMotorControllerConfigurationException`                                                                                                                 |
| A301              | ❌ Throws a `SmartMotorControllerConfigurationException`                                                                                                                                               | ❌ Throws a `SmartMotorControllerConfigurationException`                                                                                                                 |

On a SPARK, YAMS chooses the REV `ControlType` itself: MAXMotion when the config has a trapezoidal profile, plain position or velocity otherwise.

## `withTelemetry`

Names the motor and chooses how much it publishes.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-347d143d5360799967545ddf83bb932b69c53df1%2Ftelemetry-verbosity.png?alt=media" alt="Three nested boxes. The outer box is HIGH, which contains MID, which contains LOW. LOW publishes positions and velocities, MID adds power, and HIGH adds everything tunable"><figcaption><p>Each verbosity level includes the one below it.</p></figcaption></figure>

```java
.withTelemetry("ArmMotor", TelemetryVerbosity.HIGH)
```

`HIGH` is what [live tuning](/documentation/how-to-tuning/live-tuning) needs. [Telemetry](/documentation/understanding/telemetry) lists every key and how to choose fields one by one with a `SmartMotorControllerTelemetryConfig`.

**Supported on:** every supported motor controller.

## Code reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)


# Gearing and units

These options tell YAMS how the motor's rotation becomes the mechanism's movement. Every position and velocity YAMS reports depends on them, so get them right before tuning.

The options on this page connect the **rotor** (the motor's own shaft), the **mechanism** (the output after the gearing) and the **measurement** (the distance a mechanism moves in a line). [Rotor, mechanism and measurement](/documentation/tutorials/how-yams-drives-a-motor#rotor-mechanism-and-measurement) defines them with a picture.

## `withGearing`

The reduction between the rotor and the mechanism.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-5c324b1b17282afb37cd04f85b88ef1a5bbd27e1%2Fsmc-gearing.png?alt=media" alt="A motor rotor drives a gearbox with 3 to 1 and 4 to 1 stages, 12 to 1 in total, which drives the mechanism&#x27;s output shaft. Twelve rotor rotations are one mechanism rotation. GearBox.fromReductionStages(3, 4) and withGearing(12) mean the same."><figcaption><p>A 12:1 reduction in two stages.</p></figcaption></figure>

```java
.withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4))) // 3:1 then 4:1
.withGearing(12)                                                       // the same, as one number
```

A reduction is a number greater than 1: a "3:1" gearbox is `3`, and a "1:2" overdrive is `0.5`. `GearBox.fromReductionStages` and `Sprocket.fromStages` let you write the stages as they are on the robot.

On an A301 the rotor is inside the A301, so the gearing includes the gearbox on it (135:1, 64:1, 36:1, 27:1, 13.5:1 or 3:1) as well as anything after it: a 64:1 gearbox and a 3:1 chain is `GearBox.fromReductionStages(64, 3)`. YAMS does not detect which gearbox is fitted.

**Supported on:** every supported motor controller.

## `withMechanismCircumference`

How far the mechanism travels in one rotation of its output. Setting it lets you use distances (`Meters`, `Inches`) anywhere YAMS takes an angle.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-6e4de7c98cf2499a173d23fd1cb51213b398f4f8%2Fsmc-circumference.png?alt=media" alt="A drum with its radius marked. One mechanism rotation is one circumference of travel, two times pi times the radius. The same value can be given with withMechanismCircumference, withWheelRadius or withWheelDiameter, withDrumRadius, or withDrumRadius with a chain pitch and tooth count."><figcaption><p>One rotation of the drum is one circumference of travel.</p></figcaption></figure>

```java
.withMechanismCircumference(Meters.of(0.25))
.withWheelRadius(Inches.of(2))            // or withWheelDiameter(Inches.of(4))
.withDrumRadius(Inches.of(1))
.withDrumRadius(Inches.of(0.25), 22)      // chain pitch and sprocket teeth
```

All of these set the same value. Use whichever matches what you can measure. [How do I find my mechanism's circumference?](/documentation/how-to-motor-controllers-and-sensors/how-to-find-your-mechanism-circumference) covers the measuring.

Several options need it first and throw a `SmartMotorControllerConfigurationException` without it: distance `withSoftLimits`, distance `withExternalEncoderZeroOffset`, and anything else that takes a `Distance`.

**Supported on:** every supported motor controller.

## `withCascadingElevatorStages`

Divides the gearing by the number of cascading stages, because each stage adds the same travel again.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-e4288e6df9d07282a5260e7c7086a0d299173364%2Fsmc-cascading-stages.png?alt=media" alt="Three elevators with one, two and three cascading stages. For the same motor movement the carriage travels one, two and three times as far, so the gearing is divided by the number of stages."><figcaption><p>The carriage of a cascading elevator moves further than the first stage.</p></figcaption></figure>

```java
.withGearing(new MechanismGearing(GearBox.fromReductionStages(5, 4)))
.withCascadingElevatorStages(2)
```

Call it after `withGearing`: it changes the gearing that is already set. Continuous elevators, where one belt or rope runs through every stage, do not need it.

**Supported on:** every supported motor controller.

## Code reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)


# Closed loop control

Closed loop control is what takes a mechanism to a setpoint and holds it there. These options need [`withControlMode(ControlMode.CLOSED_LOOP)`](/documentation/reference/editor/config/motor-basics#withcontrolmode), which is the default.

{% hint style="warning" %}
Not every option on this page is supported on every motor controller. Each option has a table showing where it works, and an option a controller cannot do throws a `SmartMotorControllerConfigurationException` or an `IllegalArgumentException` at startup. Each option says which. The [config overview](/documentation/reference/editor/config#not-every-option-works-on-every-motor-controller) lists them all together.
{% endhint %}

For how to find good values, see [live tuning](/documentation/how-to-tuning/live-tuning).

## `withClosedLoopController`

Sets the PID gains.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b3653661abd55c555a07dbe24e673fe997367e8b%2Fsmc-pid.png?alt=media" alt="A graph of position against time moving to a setpoint with three sets of gains: a low kP that is slow, a high kP that overshoots, and kP with kD that is quick and settled. kP pushes harder the further away, kI pushes harder the longer it is off, kD eases off as it gets close. The input is rotations, or meters for a distance mechanism, and the output is volts."><figcaption><p>What the gains do to a move.</p></figcaption></figure>

```java
.withClosedLoopController(4, 0, 0.2)                 // kP, kI, kD
.withClosedLoopController(new PIDController(4, 0, 0.2))
```

Write gains in volts per mechanism rotation, or volts per meter for a [distance based controller](#withlinearclosedloopcontroller). YAMS converts them for each motor controller, so the same numbers behave the same on every vendor: see [Under the hood](#under-the-hood) if you want the details.

Passing an `LQRController` instead replaces the PID with an LQR: see [LQR controllers](/documentation/understanding/lqr-controllers).

**Supported on every motor controller.** Every controller accepts PID gains. An [LQR controller](/documentation/understanding/lqr-controllers) always runs on the SystemCore, on every controller, and so does every loop of an A301, which has no closed loop gains of its own.

| TalonFX | TalonFXS | SPARK MAX / Flex | Thrifty Nova           | A301                         |
| ------- | -------- | ---------------- | ---------------------- | ---------------------------- |
| ✅       | ✅        | ✅                | ✅ PID runs on the Nova | ✅ PID runs on the SystemCore |

### Starting values

These are only places to start, so the first move is gentle and you can see which way to go. Every mechanism ends up somewhere else. Tune the [feedforward](/documentation/reference/editor/config/feedforward#withfeedforward) first, with these PID gains at 0.

| Mechanism          | Start `kP` at | Which means                                                | Start `kI`, `kD` at |
| ------------------ | ------------- | ---------------------------------------------------------- | ------------------- |
| Arm, pivot, turret | `10`          | 10 V per rotation of error, about 0.3 V at 10° off         | `0`, `0`            |
| Elevator           | `10`          | 10 V per meter of error, 1 V at 10 cm off                  | `0`, `0`            |
| Flywheel, roller   | `0.1`         | 0.1 V per rotation per second of error, 1 V at 600 RPM off | `0`, `0`            |

Graph the position (or velocity) against the setpoint and make small moves:

* **It stops short, or creeps up slowly:** `kP` is too low. Double it and try again.
* **It overshoots and rings:** `kP` is too high. Go back about a third, then add `kD`, starting around a tenth of `kP`, until the overshoot goes.
* **It stops a little short every time, even with a good `kP`:** check `kG` and `kS` in the [feedforward](/documentation/reference/editor/config/feedforward) before reaching for `kI`.

The Arm tutorial starts its light, simulated arm at a `kP` of 50; either is a fine place to start because you double or cut it from there. [Step 5 of the Arm tutorial](/documentation/tutorials/arm/tune) walks through this, and [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order) has the order for each mechanism.

### Slots

Each call can name a slot, so one motor can hold several sets of gains and switch between them.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-6f30fa32027a5b581fe4496f84c7bf1b0a1552da%2Fsmc-slots.png?alt=media" alt="Four slots, SLOT_0 to SLOT_3, each holding its own PID gains and feedforward, for example one for holding nothing, one for holding a game piece and one for climbing. SLOT_0 is in use. SLOT_3 is not available on TalonFX or TalonFXS. motor.setClosedLoopSlot switches slot at once."><figcaption><p>Four slots, each with its own gains and feedforward.</p></figcaption></figure>

```java
.withClosedLoopController(4, 0, 0, ClosedLoopControllerSlot.SLOT_0)
.withClosedLoopController(6, 0, 0, ClosedLoopControllerSlot.SLOT_1)
// later, while running
motor.setClosedLoopSlot(ClosedLoopControllerSlot.SLOT_1);
```

**Not supported everywhere.** Selecting `SLOT_3` on a TalonFX or TalonFXS throws an `IllegalArgumentException`, and a feedforward configured for `SLOT_3` on a TalonFX throws a `SmartMotorControllerConfigurationException`. A Thrifty Nova running the closed loop itself has two slots: gains or a feedforward in `SLOT_2` or `SLOT_3` throw a `SmartMotorControllerConfigurationException`.

| TalonFX                 | TalonFXS                | SPARK MAX / Flex | Thrifty Nova                                                                             | A301 |
| ----------------------- | ----------------------- | ---------------- | ---------------------------------------------------------------------------------------- | ---- |
| ⚠️ `SLOT_0` to `SLOT_2` | ⚠️ `SLOT_0` to `SLOT_2` | ✅                | ⚠️ `SLOT_0` and `SLOT_1`, unless the loop [runs on the SystemCore](#where-the-loop-runs) | ✅    |

## `withClosedLoopTolerance`

How close to the setpoint counts as being there.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-3db974c4ed1193e8cef19c427753b905a620218a%2Fsmc-tolerance.png?alt=media" alt="A graph of position moving to a setpoint with a shaded band of plus and minus the tolerance around it. Once the position stays inside the band the mechanism counts as at the setpoint."><figcaption><p>The tolerance is a band around the setpoint.</p></figcaption></figure>

```java
.withClosedLoopController(4, 0, 0)
.withClosedLoopTolerance(Degrees.of(1))
```

Call it after `withClosedLoopController`: it is set on the PID controllers that exist at that moment, and throws a `SmartMotorControllerConfigurationException` if there are none.

**Not supported everywhere.** It throws a `SmartMotorControllerConfigurationException` on a TalonFX or TalonFXS.

| TalonFX | TalonFXS | SPARK MAX / Flex                                                              | Thrifty Nova                                                                  | A301                                                                          |
| ------- | -------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| ❌       | ❌        | ⚠️ not with an [LQR controller](/documentation/understanding/lqr-controllers) | ⚠️ not with an [LQR controller](/documentation/understanding/lqr-controllers) | ⚠️ not with an [LQR controller](/documentation/understanding/lqr-controllers) |

## `withContinuousWrapping`

Tells the controller that the two ends of the range are the same place, so it takes the short way round.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-82e9451b8ee3376396d7a59357a140022e1e60c9%2Fsmc-continuous-wrapping.png?alt=media" alt="Two dials going from 170 degrees to minus 170 degrees. Without continuous wrapping the mechanism goes 340 degrees the long way round. With continuous wrapping from minus 180 to 180 degrees it goes 20 degrees across the seam, the short way."><figcaption><p>From 170° to -170°, without and with continuous wrapping.</p></figcaption></figure>

```java
.withClosedLoopController(50, 0, 0.5)
.withContinuousWrapping(Degrees.of(-180), Degrees.of(180))
```

It needs a closed loop controller first, and cannot be combined with [soft limits](/documentation/reference/editor/config/limits-and-protection#withsoftlimits) or a distance based controller, because a mechanism with ends cannot wrap. Setting both throws a `SmartMotorControllerConfigurationException`, in either order.

It also sets the range an absolute external encoder reads, as [`withWrapping`](/documentation/reference/editor/config/encoders#withwrapping) does. A mechanism with ends whose absolute encoder must read across zero, such as an arm, uses `withWrapping` instead: the encoder reads the same range, but the closed loop never takes the mechanism the other way round, and soft limits still work.

**Not the same everywhere.** A Thrifty Nova wraps continuously itself over any one rotation range, such as -180° to 180°, of an absolute encoder closing its loop and mounted 1:1 on the mechanism. It also wraps its motor's own encoder or a quadrature encoder: YAMS sends each target as the equivalent nearest the mechanism, so the Nova takes the short way. A Nova swerve azimuth seeded from a `CANcoder` runs entirely on the Nova, like a SPARK MAX with one. Only an absolute encoder geared to the mechanism runs the closed loop [on the SystemCore](#where-the-loop-runs): it wraps once per encoder rotation, inside the mechanism's range. An encoder's own range has its own limits: see [`withWrapping`](/documentation/reference/editor/config/encoders#withwrapping).

| TalonFX | TalonFXS | SPARK MAX / Flex | Thrifty Nova                                                                                         | A301 |
| ------- | -------- | ---------------- | ---------------------------------------------------------------------------------------------------- | ---- |
| ✅       | ✅        | ✅                | ✅ on the Nova; an absolute encoder geared to the mechanism [on the SystemCore](#where-the-loop-runs) | ✅    |

## `withClosedLoopControllerMaximumVoltage`

Caps the voltage the closed loop controller may ask for.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b50d833aa97017bbd5e6619e6b38e3a79b82cfcb%2Fsmc-max-voltage.png?alt=media" alt="A graph of closed loop output against time. The controller asks for nearly 12 volts at the start of a move, but the motor only gets the 6 volt maximum until the request drops below it."><figcaption><p>A 6 V maximum on a move that asked for more.</p></figcaption></figure>

```java
.withClosedLoopControllerMaximumVoltage(Volts.of(6))
```

**Not supported everywhere.** On a TalonFX or TalonFXS it is applied as the peak forward and reverse voltage. On a SPARK or Thrifty Nova it throws a `SmartMotorControllerConfigurationException` unless the loop runs on the SystemCore. An A301's loop always runs on the SystemCore, so it always works there.

| TalonFX | TalonFXS | SPARK MAX / Flex                                                                                         | Thrifty Nova                                                                                                                                                                           | A301 |
| ------- | -------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- |
| ✅       | ✅        | ⚠️ only with an exponential profile or an [LQR controller](/documentation/understanding/lqr-controllers) | ⚠️ only when the loop runs on the SystemCore, such as with an exponential profile, a velocity trapezoidal profile or an [LQR controller](/documentation/understanding/lqr-controllers) | ✅    |

## Where the loop runs

Some combinations run on the motor controller, at 1 kHz, and some on the SystemCore, every 20 ms by default. It matters for a few options, and YAMS raises an alert when the loop is on the SystemCore. `getClosedLoopControllerPeriod()` also tells you: 1 ms on the motor controller, the closed loop control period on the SystemCore. The figure does not show the A301: it has no closed loop of its own, so PID, both profiles and LQR all run on the SystemCore.

A Thrifty Nova also runs the loop on the SystemCore when the Nova can't run it: an absolute encoder closing the loop over a range other than 0° to 360° without continuous wrapping, or continuous wrapping of an absolute encoder geared to the mechanism (see [`withContinuousWrapping`](#withcontinuouswrapping)).

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-50dfc119fa120bf4b677e25aa302ef86d283091b%2Fsmc-where-it-runs.png?alt=media" alt="A table of where the closed loop runs. TalonFX and TalonFXS run PID and profiles on the controller and LQR on the SystemCore. SPARK MAX and SPARK Flex run PID and trapezoidal profiles on the controller, and exponential profiles and LQR on the SystemCore. The Thrifty Nova runs PID and trapezoidal position profiles on the controller, and exponential profiles, velocity profiles and LQR on the SystemCore. Below it, three timelines over 240 milliseconds show how often each loop runs: on the controller every 1 millisecond, which is 1 kilohertz and 240 runs; on the SystemCore every 20 milliseconds by default, which is 12 runs; and on the SystemCore at 10 milliseconds, which is 24 runs. withClosedLoopControlPeriod only changes the SystemCore loop. The period of the loop on the controller cannot be changed."><figcaption><p>Where the closed loop runs, and how often.</p></figcaption></figure>

### PID gains do not carry over between the two

PID gains tuned with the loop on the motor controller will never be the same as gains tuned with the loop on the SystemCore, even on the same mechanism. The reason is the closed loop control period:

* **On the motor controller** the loop runs at 1 kHz, once every millisecond, right next to the motor and its encoder. That is 20 runs for every one run of the SystemCore loop at its default period. This period is fixed by the motor controller and cannot be changed.
* **On the SystemCore** the loop runs once every control period, 20 ms by default, and each measurement and each output also has to cross the CAN bus.

A slower loop reacts later to every error, so it cannot use gains as high as a fast one before it starts to oscillate. `kD` and `kI` are affected the most, because they depend directly on the time between two runs of the loop.

What this means in practice:

* **Tune again whenever the loop moves.** On a SPARK or Thrifty Nova that happens when you switch between a trapezoidal profile, which runs on the controller, and an exponential profile or an [LQR controller](/documentation/understanding/lqr-controllers), which run on the SystemCore. Moving a mechanism to a different brand of motor controller can move the loop too.
* **Tune again after changing** [**`withClosedLoopControlPeriod`**](#withclosedloopcontrolperiod)**.** A different period is a different loop.
* **Do not copy gains from another team or another robot** without checking where their loop ran and how fast.

### `withClosedLoopControlPeriod`

Changes how often the SystemCore loop runs. The default is 20 ms. It does not change a loop that runs on the motor controller: that period is fixed at 1 ms (1 kHz).

```java
.withClosedLoopControlPeriod(Milliseconds.of(10))
```

**Not supported everywhere.** Where it is not supported it throws an `IllegalArgumentException` on a TalonFX or TalonFXS, and a `SmartMotorControllerConfigurationException` on a SPARK or Thrifty Nova. Outside closed loop mode it throws an `IllegalArgumentException` on a Nova or an A301.

| TalonFX | TalonFXS | SPARK MAX / Flex                                                                                         | Thrifty Nova                                                                                                                                                                           | A301                        |
| ------- | -------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |
| ❌       | ❌        | ⚠️ only with an exponential profile or an [LQR controller](/documentation/understanding/lqr-controllers) | ⚠️ only when the loop runs on the SystemCore, such as with an exponential profile, a velocity trapezoidal profile or an [LQR controller](/documentation/understanding/lqr-controllers) | ⚠️ only in closed loop mode |

## `withLinearClosedLoopController`

Chooses whether the controller works in rotations or in meters.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-d8e5a04c33cb35b8f4335c31a13830d94901974d%2Fsmc-linear-units.png?alt=media" alt="Two panels. Angle based, the default: error is measured in rotations, kP is in volts per rotation and profile limits are in rotations per second, for arms, pivots, turrets and flywheels. Distance based: error in meters, kP in volts per meter and profile limits in meters per second, for elevators and other linear mechanisms."><figcaption><p>The units the gains and limits are in.</p></figcaption></figure>

```java
.withLinearClosedLoopController(true)  // gains and limits in meters
.withLinearClosedLoopController(false) // gains and limits in rotations
```

It turns on by itself when you give a distance profile, a distance exponential profile or an `ElevatorFeedforward`, and it only takes effect when a [circumference](/documentation/reference/editor/config/gearing-and-units#withmechanismcircumference) is set. [How do I turn off linear closed loop control?](/documentation/how-to-motor-controllers-and-sensors/how-to-disable-linear-closed-loop-control) explains when to turn it off.

**Supported on:** every supported motor controller.

## Under the hood

You do not need this section to use YAMS. It explains what YAMS does with your gains, for when you compare them with a vendor's documentation or another team's numbers.

### How your gains reach the motor controller

You write every gain once, in mechanism units: volts per mechanism rotation, or per meter for a [distance based controller](#withlinearclosedloopcontroller). Every [feedforward](/documentation/reference/editor/config/feedforward) uses the same units, including an `ArmFeedforward`. Each motor controller wants its gains in its own units, so YAMS converts them when it applies the config, and again every time you change a gain while [live tuning](/documentation/how-to-tuning/live-tuning).

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-704c681c0d2f496174a6456fd08f4dd4af09415a%2Fsmc-gain-overview.png?alt=media" alt="Your gains, in YAMS units of volts per mechanism rotation or meter, go to three motor controllers. TalonFX and TalonFXS: the sensor to mechanism ratio is the gear ratio, so the Talon already works in mechanism rotations; a linear mechanism&#x27;s gains are divided by the rotations per meter; kS and kG are volts and do not change; Motion Magic limits go from meters to rotations; gravity is Arm_Cosine or Elevator_Static. SPARK MAX and Flex: gains are per rotation of its encoder and output a duty cycle, so they are divided by 12 V and the gear ratio, velocity gains by 60 more for RPM, kI is multiplied by 1 ms and kD divided by 1 ms, kV and kA are volts per RPM of its encoder, and an arm&#x27;s kG becomes kCos with a kCosRatio of 1 over the ratio. Thrifty Nova: the sensor to mechanism ratio is the gear ratio, so it already works in mechanism rotations; a linear mechanism&#x27;s gains are divided by the rotations per meter; the feedforward goes in its motion profile, with cosine gravity for an arm; exponential profiles and LQR run on the SystemCore."><figcaption><p>Where your gains go.</p></figcaption></figure>

#### Dimensional analysis

The conversion is dimensional analysis. A gain is a number with units, like 4 V per mechanism rotation. To change its units, multiply it by fractions that are each worth exactly 1, such as 1 mechanism rotation over 12 motor rotations on a 12:1 gearbox. A unit that appears on both the top and the bottom cancels. Once only the units the motor controller wants are left, the number in front is its gain.

{% tabs %}
{% tab title="SPARK MAX / Flex" %}
A SPARK's closed loop works on its own encoder, not on the mechanism. Its PID output is a duty cycle from -1 to 1, not volts. So every PID gain loses the gear ratio and the 12 V, and a velocity gain also changes from rotations per second to RPM.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-68652fa7db6370168240583c6b2b72abfd736280%2Fsmc-gain-units-spark.gif?alt=media" alt="An animation of five unit conversions for a 12 to 1 SPARK. Position kP: 4 volts per mechanism rotation, times 1 mechanism rotation over 12 motor rotations, times 1 duty over 12 volts. Mechanism rotations cancel, then volts cancel, leaving 0.0278 duty cycle per motor rotation. Elevator kP: 40 volts per meter, times 0.2 meters per mechanism rotation, then the same gear ratio and voltage, leaving 0.0556 duty cycle per motor rotation. Velocity kP: 0.5 volts per mechanism rotation per second, times 1 mechanism rotation per second over 12 motor rotations per second, times 1 motor rotation per second over 60 RPM, times 1 duty over 12 volts, leaving 5.79e-05 duty cycle per RPM. kD: 0.2 volt seconds per mechanism rotation, through the same gear ratio and voltage, times 1 loop over 0.001 seconds, so seconds cancel and it leaves 1.39 duty cycle loops per motor rotation. kV: 1.0 volt per mechanism rotation per second, through the gear ratio and 60 RPM, leaving 0.00139 volts per RPM, because feedforwards stay in volts."><figcaption><p>Converting a 12:1 mechanism's gains for a SPARK, one unit at a time.</p></figcaption></figure>

| Gain                 | YAMS units                                      | SPARK units                     | YAMS does               |
| -------------------- | ----------------------------------------------- | ------------------------------- | ----------------------- |
| `kP`, position       | V per mechanism rotation (or meter)             | duty cycle per encoder rotation | ÷ (12 V × ratio)        |
| `kP`, velocity       | V per mechanism rotation (or meter) per second  | duty cycle per encoder RPM      | ÷ (12 V × ratio × 60)   |
| `kI`                 | `kP`'s units per second                         | `kP`'s units per 1 ms loop      | × 0.001 s, then as `kP` |
| `kD`                 | `kP`'s units × seconds                          | `kP`'s units × 1 ms loops       | ÷ 0.001 s, then as `kP` |
| `kS`, `kG`           | V                                               | V                               | nothing                 |
| `kV`                 | V per mechanism rotation (or meter) per second  | V per encoder RPM               | ÷ (ratio × 60)          |
| `kA`                 | V per mechanism rotation (or meter) per second² | V per encoder RPM per second    | ÷ (ratio × 60)          |
| Profile velocity     | mechanism rotations (or meters) per second      | encoder RPM                     | × ratio × 60            |
| Profile acceleration | mechanism rotations (or meters) per second²     | encoder RPM per second          | × ratio × 60            |

* **The ratio** is the gearing between the mechanism and the encoder the SPARK uses: your [gearing](/documentation/reference/editor/config/gearing-and-units), or the [external encoder's gearing](/documentation/reference/editor/config/encoders#withexternalencodergearing) when the SPARK uses an external encoder for feedback.
* **The 12 V** is your [voltage compensation](/documentation/reference/editor/config/limits-and-protection#withvoltagecompensation) if you set one, and 12 V if you do not. The SPARK's PID output is a fraction of full output, from -1 to 1, in every closed loop control type YAMS sends: position, velocity and both MAXMotion types. With voltage compensation, full output is the compensation voltage, so the gains are exact. Without it, full output is the battery's voltage, so at 11 V the PID pushes about 8% less than you tuned for.
* **The feedforward is in volts**, not a fraction of full output. The SPARK's `kS`, `kV`, `kA`, `kG` and `kCos` are in volts, and YAMS sends its own feedforward with each setpoint in volts (`ArbFFUnits.kVoltage`), so the feedforward does not change with the battery's voltage.
* **An elevator, or any distance based controller,** has every gain per meter, as on a Talon: `kP`, `kI`, `kD`, `kV` and `kA`, and the profile's limits. `kS` and `kG` are volts either way. YAMS first divides a gain per meter by the mechanism rotations per meter (multiplies, for a profile limit), then converts the result as in the table. An `ElevatorFeedforward` or [`withLinearClosedLoopController`](#withlinearclosedloopcontroller) makes the controller distance based.
* **Position and velocity need different gains.** A SPARK measures position error in rotations and velocity error in RPM, so YAMS writes the position or velocity version of your gains whenever the type of setpoint changes. You still tune only one set.
* **An arm's `kG`** goes to the SPARK's `kCos`, with a `kCosRatio` of 1 over the ratio so the SPARK can turn its encoder's rotations into the arm's angle.
* **In simulation**, REVLib's SPARK applies `kI` and `kD` per second instead of per loop, so YAMS skips the 0.001 s step there.
  {% endtab %}

{% tab title="TalonFX / TalonFXS" %}
YAMS sets the Talon's `SensorToMechanismRatio` to your gear ratio, so the Talon already measures in mechanism rotations and works in volts. An angle based gain goes to the Talon unchanged. Only a [distance based controller](#withlinearclosedloopcontroller) is converted, from meters to mechanism rotations.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-61fe313a0db41d08c1a900017b67b261954f36e6%2Fsmc-gain-units-talon.gif?alt=media" alt="An animation of three unit conversions for an elevator on a Talon whose drum moves 0.2 meters per mechanism rotation. kP: 40 volts per meter times 0.2 meters per mechanism rotation; meters cancel, leaving 8 volts per mechanism rotation. kV: 8 volts per meter per second times 0.2 meters per mechanism rotation, leaving 1.6 volts per mechanism rotation per second. Motion Magic cruise velocity: 1.5 meters per second times 1 mechanism rotation over 0.2 meters, leaving 7.5 mechanism rotations per second."><figcaption><p>Converting an elevator's gains for a Talon, one unit at a time.</p></figcaption></figure>

| Gain                                | YAMS units                                                                        | Talon units                             | YAMS does                                                                                       |
| ----------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `kP`, `kI`, `kD`                    | V per mechanism rotation (or meter)                                               | V per mechanism rotation                | ÷ mechanism rotations per meter when distance based                                             |
| `kS`, `kG`                          | V                                                                                 | V                                       | nothing, and sets `GravityType` to `Arm_Cosine` for an arm or `Elevator_Static` for an elevator |
| `kV`, `kA`                          | V per mechanism rotation (or meter) per second (²)                                | V per mechanism rotation per second (²) | ÷ mechanism rotations per meter when distance based                                             |
| Motion Magic velocity, acceleration | mechanism rotations (or meters) per second (²)                                    | mechanism rotations per second (²)      | × mechanism rotations per meter when distance based                                             |
| Motion Magic Expo `kV`, `kA`        | from the [exponential profile](/documentation/understanding/exponential-profiles) | V per mechanism rotation per second (²) | ÷ mechanism rotations per meter when distance based                                             |

With an [external encoder](/documentation/reference/editor/config/encoders#withexternalencoder), the `SensorToMechanismRatio` is the encoder's gearing and the `RotorToSensorRatio` is the rest of the gearing, so the gains are still per mechanism rotation.
{% endtab %}

{% tab title="Thrifty Nova" %}
The Nova's `sensorToMechanismRatio` is set to the gear ratio, or to the external encoder's gearing when that encoder closes the loop, so it already works in mechanism rotations, like a Talon. Each closed loop slot goes to one of the Nova's two slots:

| YAMS                               | On the Nova                                                                                 | Conversion                                          |
| ---------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| `kP`, `kI`, `kD`                   | the slot's PID (`Pid0` or `Pid1`), outputting volts                                         | ÷ mechanism rotations per meter when distance based |
| `withClosedLoopTolerance`          | the slot's allowable error                                                                  | in mechanism rotations                              |
| Trapezoidal profile                | the slot's motion profile (`Mp0` or `Mp1`) maximum velocity and acceleration                | ÷ mechanism rotations per meter when distance based |
| Feedforward `kS`, `kV`, `kA`, `kG` | the slot's motion profile, with cosine gravity for an arm; they apply without a profile too | elevator `kV`, `kA` ÷ mechanism rotations per meter |

The Nova runs a feedforward without a motion profile too. YAMS sends `kS`, `kV`, `kA` and `kG` to the slot's motion profile either way, and the Nova applies them with or without a motion profile, in plain position and velocity control too. So a swerve drive motor or flywheel keeps its `kS` and `kV` on the Nova, and an arm without a profile keeps its `kG`. A velocity trapezoidal profile, an exponential profile or an [LQR controller](/documentation/understanding/lqr-controllers) runs on the SystemCore, in YAMS units, and the Nova then only receives the voltage the loop asks for.
{% endtab %}

{% tab title="A301" %}
The A301 has no closed loop gains, so nothing is converted. YAMS runs the PID, profiles and feedforward on the SystemCore in YAMS units, per mechanism rotation (or meter), and sends the A301 the voltage the loop asks for.
{% endtab %}
{% endtabs %}

The units are the same on every controller, but [where the loop runs](#where-the-loop-runs) still matters. A loop on the motor controller runs every millisecond, so gains tuned there are not the best gains for a loop on the SystemCore.

## Code reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)


# Feedforward

A feedforward predicts the voltage a move needs from what you know about the mechanism, before any error has built up. The PID then only has to fix what the prediction missed.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-68b307c80b93f93e2148d222a3913f6b033b2496%2Fsmc-feedforward-terms.png?alt=media" alt="A bar of the output voltage split into parts: kS to overcome friction, kG to hold against gravity, kV times velocity to keep moving, kA times acceleration to speed up, and a small PID part that fixes whatever is left. All but the PID part are feedforward, known before the mechanism moves."><figcaption><p>The parts of the output voltage at one moment in a move.</p></figcaption></figure>

## `withFeedforward`

Takes one of WPILib's three feedforward classes.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-76d2ec30e25ac39005667e89eda9aded1fb969e4%2Fsmc-feedforward-types.png?alt=media" alt="Three feedforward types. SimpleMotorFeedforward, for flywheels, rollers and turrets, has kS, kV and kA and nothing to hold up. ArmFeedforward, for arms and pivots, adds kG times the cosine of the angle. ElevatorFeedforward, for elevators, adds a constant kG."><figcaption><p>The three feedforward types.</p></figcaption></figure>

```java
.withFeedforward(new SimpleMotorFeedforward(0.1, 0.12, 0.01))   // kS, kV, kA
.withFeedforward(new ArmFeedforward(0.1, 0.35, 1.2, 0.02))      // kS, kG, kV, kA
.withFeedforward(new ElevatorFeedforward(0.1, 0.4, 3.5, 0.1))   // kS, kG, kV, kA
```

| Gain | What it is for                                        | How to find it                                                                                                                                                                              |
| ---- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kS` | The voltage that just overcomes friction.             | Raise the voltage in steps of about 0.05 V until the mechanism starts to move. [Drive a motor at a voltage](/documentation/how-to-tuning/live-tuning#drive-a-motor-at-a-voltage) shows how. |
| `kG` | The voltage that holds the mechanism against gravity. | The voltage at which it neither rises nor falls. For an arm, measure it with the arm level.                                                                                                 |
| `kV` | The voltage per unit of speed.                        | Volts above `kS` divided by the steady speed it gives.                                                                                                                                      |
| `kA` | The voltage per unit of acceleration.                 | Usually small. Raise it if the mechanism lags at the start of a move.                                                                                                                       |

The units:

* **`kS` and `kG`** are volts.
* **`kV`** is volts per mechanism rotation per second for `ArmFeedforward` and `SimpleMotorFeedforward`, and volts per meter per second for `ElevatorFeedforward`. A `kV` of 2 on an arm adds 2 V for every rotation per second it moves.
* **`kA`** is the same, per second squared.

Giving an `ElevatorFeedforward` makes the controller [distance based](/documentation/reference/editor/config/closed-loop-control#withlinearclosedloopcontroller).

{% hint style="info" %}
**`ArmFeedforward` is per rotation in YAMS, not per radian.** WPILib documents an `ArmFeedforward`'s `kV` and `kA` per radian. In YAMS they are per mechanism rotation, like every other gain, and YAMS converts them for WPILib's math. A `kV` you copied from a per radian calculation is 2π (about 6.28) times too small for YAMS.
{% endhint %}

### Starting values

These are only places to start, so you can see which way to go. Tune `kS` and `kG` first, with the PID gains at 0.

| Gain | Start at                                   | Change it                                                                                |
| ---- | ------------------------------------------ | ---------------------------------------------------------------------------------------- |
| `kG` | `0`                                        | Raise in 0.05 V steps until the arm (held level) or the elevator stays where it is.      |
| `kS` | `0`                                        | Raise in 0.05 V steps until the mechanism is just about to move, then back off a little. |
| `kV` | 12 V divided by the mechanism's free speed | Raise if the speed settles below the setpoint, lower if it settles above.                |
| `kA` | `0`                                        | Raise only if the mechanism lags while it speeds up.                                     |

The mechanism's free speed is the motor's free speed divided by your gearing. A NEO (about 95 rotations per second) through 12:1 gives about 7.9 rotations per second, so `kV` starts near 12 / 7.9 = 1.5. A Kraken X60 (about 100 rotations per second) driving a flywheel 1:1 starts near 0.12. For an elevator, multiply the mechanism's free speed by the [circumference](/documentation/reference/editor/config/gearing-and-units#withmechanismcircumference) to get meters per second first.

Graph velocity against the setpoint velocity during a long move. [Step 5 of the Arm tutorial](/documentation/tutorials/arm/tune) walks through it, and [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order) has the order for each mechanism.

### These are not an exponential profile's `kV` and `kA`

An [exponential profile](/documentation/understanding/exponential-profiles) also has a `kV` and a `kA`. They share the names and the units, but they are separate settings that do different jobs, and changing one pair does not change the other.

|              | Feedforward `kV` and `kA`                                                    | Exponential profile `kV` and `kA`                                                                                                |
| ------------ | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Set with     | `withFeedforward(...)`                                                       | `withExponentialProfile(...)`                                                                                                    |
| What they do | Turn the velocity and acceleration of the setpoint into volts for the motor. | Shape the plan. The maximum voltage divided by `kV` is the profile's top speed, and divided by `kA` is its maximum acceleration. |
| Raising them | Sends the motor more voltage.                                                | Makes the profile slower. No extra voltage is sent.                                                                              |
| Tuned by     | Watching how well the mechanism follows the setpoint.                        | Watching whether the mechanism can keep up with the profile.                                                                     |

A mechanism with an exponential profile needs both pairs: the profile's to plan the move, and the feedforward's to follow it. Do not copy one pair into the other. The profile's values are often set higher than the feedforward's, so the plan asks for less than the motor can give and leaves voltage in reserve.

[Measuring kV and kA](/documentation/understanding/exponential-profiles#measuring-kv-and-ka-optional) on the exponential profiles page measures the profile's pair, and [refining the profile live](/documentation/understanding/exponential-profiles#refining-the-profile-live) tunes them.

### Slots

A feedforward can be given a slot, so it switches together with the [PID gains in that slot](/documentation/reference/editor/config/closed-loop-control#slots).

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-6f30fa32027a5b581fe4496f84c7bf1b0a1552da%2Fsmc-slots.png?alt=media" alt="Four slots, SLOT_0 to SLOT_3, each holding its own PID gains and feedforward, for example one for holding nothing, one for holding a game piece and one for climbing. SLOT_0 is in use. SLOT_3 is not available on TalonFX or TalonFXS. motor.setClosedLoopSlot switches slot at once."><figcaption><p>Each slot holds a feedforward alongside its PID gains, and both switch together.</p></figcaption></figure>

```java
.withFeedforward(new ArmFeedforward(0.1, 0.35, 1.2), ClosedLoopControllerSlot.SLOT_0)
.withFeedforward(new ArmFeedforward(0.1, 0.60, 1.2), ClosedLoopControllerSlot.SLOT_1) // holding a game piece
```

**Supported on:** every supported motor controller.

## Code reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)


# Motion profiles

A motion profile turns a jump in the goal into a smooth path of setpoints for the closed loop controller to follow. Setting one profile replaces any other.

## `withTrapezoidalProfile`

A maximum velocity and a maximum acceleration.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-819eadccd668e12899c097a747bd0d78fb7772b0%2Fsmc-trapezoidal-profile.png?alt=media" alt="Two graphs. Position: the goal is a flat line and the setpoint the PID follows rises to it in a smooth S shape. Velocity: the setpoint&#x27;s velocity ramps up at the maximum acceleration, holds at the maximum velocity, and ramps back down, making a trapezoid."><figcaption><p>The setpoint glides to the goal, and its velocity makes a trapezoid.</p></figcaption></figure>

```java
.withTrapezoidalProfile(DegreesPerSecond.of(180), DegreesPerSecondPerSecond.of(360)) // arms, pivots
.withTrapezoidalProfile(MetersPerSecond.of(1.5), MetersPerSecondPerSecond.of(3))     // elevators
```

The distance version needs a [circumference](/documentation/reference/editor/config/gearing-and-units#withmechanismcircumference) and makes the controller [distance based](/documentation/reference/editor/config/closed-loop-control#withlinearclosedloopcontroller).

Choose limits the mechanism can really reach. If the profile asks for more than the motor can give, the mechanism falls behind and the PID fights to catch up: see [when tuning does not help](/documentation/tutorials/troubleshooting#when-tuning-does-not-help).

### Starting values

A place to start, not an answer. Add the profile after the feedforward and PID hold the mechanism and reach small moves cleanly.

* **Maximum velocity:** about half the mechanism's free speed, which is the motor's free speed divided by your gearing. A NEO (about 95 rotations per second) through 12:1 is about 7.9 rotations per second, so start near 4 rotations per second (about 1400°/s). A heavy arm may need much less.
* **Maximum acceleration:** about twice the maximum velocity, per second, so the mechanism reaches full speed in half a second.

Graph the mechanism's velocity against the setpoint velocity during a long move. If the measured line falls behind the flat top, lower the maximum velocity. If it lags on the ramps or the stator current spikes, lower the acceleration. If it follows easily with voltage to spare, raise them a step at a time. [Step 5 of the Arm tutorial](/documentation/tutorials/arm/tune) and [Tuning order](/documentation/how-to-tuning/live-tuning#tuning-order) walk through it.

### Other ways to set it

* `withProfile(TrapezoidProfile.Constraints)` takes WPILib's constraints directly, in rotations (or meters) per second and per second squared, and replaces any exponential profile. It prints a reminder of those units at startup. Prefer `withTrapezoidalProfile`, which takes units.
* `withTrapezoidalProfileConstraints(TrapezoidProfile.Constraints)` replaces only the numbers of an existing trapezoidal profile, keeping whether it is a position or velocity profile and whether it is in rotations or meters. Live tuning uses it. You rarely need it in a config.

## Velocity profiles for flywheels

For mechanisms that hold a speed, such as a flywheel, the same method takes a maximum acceleration and a maximum jerk instead. Jerk is how quickly the acceleration changes, so limiting it rounds off the start and end of the spin up instead of slamming straight to full acceleration.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-090c5f26ff7f6e15456dcf3f30f05d4aa982a962%2Fsmc-velocity-profile.png?alt=media" alt="A graph of velocity against time. The requested speed jumps up in a step. The setpoint rises to it in a smooth curve limited by a maximum acceleration and a maximum jerk, which is how quickly acceleration changes."><figcaption><p>A velocity setpoint limited by acceleration and jerk.</p></figcaption></figure>

```java
.withTrapezoidalProfile(RotationsPerSecondPerSecond.of(200),
                        RotationsPerSecondPerSecond.per(Second).of(2000))
```

`withVelocityTrapezoidalProfile(true)` marks an existing trapezoidal profile as a velocity profile. The overload above does that for you.

## `withExponentialProfile`

An exponential profile follows what a DC motor can actually do: hard acceleration at first, easing off as it speeds up.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-cd805259e0788a8a85c06cc806a53802c26af5ab%2Fexponential-profile-compare.png?alt=media" alt="A comparison of a trapezoidal profile, which accelerates at a constant rate, and an exponential profile, which accelerates hard at first and eases off as the motor speeds up"><figcaption><p>Trapezoidal and exponential profiles.</p></figcaption></figure>

```java
.withExponentialProfile(Volts.of(10), DCMotor.getKrakenX60(1), KilogramSquareMeters.of(0.5)) // arm or flywheel
.withExponentialProfile(Volts.of(10), DCMotor.getKrakenX60(2), Kilograms.of(8), Inches.of(1)) // elevator
.withExponentialProfile(Volts.of(10), RotationsPerSecond.of(2), RotationsPerSecondPerSecond.of(8))
```

Call it after [`withGearing`](/documentation/reference/editor/config/gearing-and-units#withgearing): the versions that take a motor work the profile out from the gearing that is already set.

`withProfile(ExponentialProfile.Constraints)` also sets an exponential profile from WPILib's constraints directly.

You give it a maximum voltage and either the mechanism (its motor and its moment of inertia, or its mass and drum radius) or a maximum velocity and acceleration. YAMS works out starting values of the profile's kV and kA from those. Tune kV and kA directly from there, as CTRE's Motion Magic Expo documentation describes, and pass your tuned values with `ExponentialProfile.Constraints.fromCharacteristics(maxVoltage, kV, kA)`.

[Exponential profiles](/documentation/understanding/exponential-profiles) explains when to use one and how to tune it.

## Where each profile runs

**Supported on every motor controller.** Every controller accepts both profiles, but they do not run in the same place.

| TalonFX                                               | TalonFXS                                              | SPARK MAX / Flex                                                           | Thrifty Nova                                                                                     | A301                     |
| ----------------------------------------------------- | ----------------------------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------ |
| ✅ on the controller (Motion Magic, Motion Magic Expo) | ✅ on the controller (Motion Magic, Motion Magic Expo) | ✅ trapezoidal on the controller (MAXMotion), exponential on the SystemCore | ✅ trapezoidal position on the controller, exponential and velocity trapezoidal on the SystemCore | ✅ both on the SystemCore |

Where the profile runs decides which other options are available: see [where the loop runs](/documentation/reference/editor/config/closed-loop-control#where-the-loop-runs).

## Code reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)


# Limits and protection

These options stop a mechanism or a motor from hurting itself or the rest of the robot.

{% hint style="warning" %}
Not every option on this page is supported on every motor controller. Each option has a table showing where it works, and an option a controller cannot do throws a `SmartMotorControllerConfigurationException` or an `IllegalArgumentException` at startup. Each option says which. The [config overview](/documentation/reference/editor/config#not-every-option-works-on-every-motor-controller) lists them all together.
{% endhint %}

## `withSoftLimits`

The range the mechanism is allowed to move through.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b4934b97bacb73e6df57d1dc94e5c782997037e8%2Fsmc-soft-limits.png?alt=media" alt="A bar showing a mechanism&#x27;s travel between two hard stops, with a lower and an upper soft limit a little inside them. The mechanism may move between the soft limits. A setpoint asked for beyond the upper limit is moved back to the limit."><figcaption><p>Soft limits sit a little inside the hard stops.</p></figcaption></figure>

```java
.withSoftLimits(Degrees.of(-20), Degrees.of(100))
.withSoftLimits(Meters.of(0), Meters.of(1.2))     // needs a circumference
```

The lower limit must be below the upper limit. Soft limits cannot be combined with [continuous wrapping](/documentation/reference/editor/config/closed-loop-control#withcontinuouswrapping): setting both throws a `SmartMotorControllerConfigurationException`, in either order. They can be combined with [`withWrapping`](/documentation/reference/editor/config/encoders#withwrapping), which only sets the range an absolute encoder reads.

Soft limits rely on the encoder being right. If the mechanism does not start where the encoder thinks it does, the limits are in the wrong place: see [starting position](/documentation/reference/editor/config/encoders#withstartingposition).

**Only in closed loop mode.** Soft limits are only enforced with [`withControlMode(ControlMode.CLOSED_LOOP)`](/documentation/reference/editor/config/motor-basics#withcontrolmode), the default. They are set on the motor controller and stop any output that would go past them, including a voltage or duty cycle. A Thrifty Nova has one enable for both limits, so it needs both an upper and a lower limit: setting only one throws a `SmartMotorControllerConfigurationException`. An A301 has no soft limits of its own, so its loop on the SystemCore enforces them: a position setpoint past a limit is moved to the limit, but a voltage or duty cycle is not stopped.

| TalonFX                     | TalonFXS                    | SPARK MAX / Flex            | Thrifty Nova                                      | A301                                                     |
| --------------------------- | --------------------------- | --------------------------- | ------------------------------------------------- | -------------------------------------------------------- |
| ⚠️ only in closed loop mode | ⚠️ only in closed loop mode | ⚠️ only in closed loop mode | ⚠️ only in closed loop mode, with both limits set | ⚠️ closed loop setpoints only, not voltage or duty cycle |

## `withStatorCurrentLimit` and `withSupplyCurrentLimit`

`withStatorCurrentLimit` limits the current through the motor, which limits its torque and heat. `withSupplyCurrentLimit` limits the current drawn from the battery, which protects the breaker and the battery voltage.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-75f89f9c2884411442900d9c21b991c13d9e279d%2Fpower-supply-stator.png?alt=media" alt="Supply current flows from the battery to the motor controller, and stator current flows from the motor controller through the motor. A supply limit protects the battery and breaker, a stator limit protects the motor and limits torque"><figcaption><p>Supply current and stator current.</p></figcaption></figure>

```java
.withStatorCurrentLimit(Amps.of(40))
.withSupplyCurrentLimit(Amps.of(30))
```

`withOutputCurrentLimit` is another name for `withStatorCurrentLimit`, and `withInputCurrentLimit` is another name for `withSupplyCurrentLimit`. They do exactly the same thing.

[How do I limit power consumption?](/documentation/how-to-motor-controllers-and-sensors/limiting-power-consumption#set-a-starting-limit-on-each-motor) explains how to choose them, with starting limits for common motors, and how to test them against the [battery simulation](/documentation/understanding/battery-simulation).

**Not supported everywhere.** `withSupplyCurrentLimit` is not available on SPARKs. The A301 has no current limits at all: either one throws a `SmartMotorControllerConfigurationException`.

| TalonFX | TalonFXS | SPARK MAX / Flex                                                                           | Thrifty Nova | A301 |
| ------- | -------- | ------------------------------------------------------------------------------------------ | ------------ | ---- |
| ✅       | ✅        | ⚠️ stator limit only: a supply limit throws a `SmartMotorControllerConfigurationException` | ✅            | ❌    |

## `withOpenLoopRampRate` and `withClosedLoopRampRate`

`withOpenLoopRampRate` and `withClosedLoopRampRate` set the shortest time the output may take to go from zero to full.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-bc32dd1cff426cef59e9f2d76b723ed744645101%2Fpower-ramp-rate.png?alt=media" alt="A graph of output against time. Without a ramp rate the output jumps to full at once. With a ramp rate it rises in a straight line over the ramp time"><figcaption><p>The output with and without a ramp rate.</p></figcaption></figure>

```java
.withOpenLoopRampRate(Seconds.of(0.25))
.withClosedLoopRampRate(Seconds.of(0.1))
```

A ramp rate is the last thing to reach for. It slows everything the motor does, including the closed loop controller's reactions. [Lower the biggest load first](/documentation/how-to-motor-controllers-and-sensors/limiting-power-consumption#lower-the-biggest-load-first) lists what to try first.

**Not supported everywhere.** The A301 has no ramp rates: either one throws a `SmartMotorControllerConfigurationException`.

| TalonFX | TalonFXS | SPARK MAX / Flex | Thrifty Nova                                                                                         | A301 |
| ------- | -------- | ---------------- | ---------------------------------------------------------------------------------------------------- | ---- |
| ✅       | ✅        | ✅                | ⚠️ one ramp rate for both: two different values throw a `SmartMotorControllerConfigurationException` | ❌    |

## `withVoltageCompensation`

Scales the output so a duty cycle means the same voltage whatever the battery voltage is.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-ad0869e5e52f1cbfe629b9969bd258f704d0ff1d%2Fsmc-voltage-compensation.png?alt=media" alt="Two panels comparing a 50 percent output at a 12.6 volt and a 10.5 volt battery. Without voltage compensation the motor gets 6.3 volts and then 5.25 volts, so the mechanism slows as the battery drains. With compensation to 12 volts it gets 6 volts both times."><figcaption><p>A 50% output at two battery voltages.</p></figcaption></figure>

```java
.withVoltageCompensation(Volts.of(12))
```

**Not supported everywhere.** It throws an `IllegalArgumentException` on a TalonFX or TalonFXS, and a `SmartMotorControllerConfigurationException` on an A301. Use a voltage request instead of a duty cycle on those.

| TalonFX | TalonFXS | SPARK MAX / Flex | Thrifty Nova | A301 |
| ------- | -------- | ---------------- | ------------ | ---- |
| ❌       | ❌        | ✅                | ✅            | ❌    |

## `withTemperatureCutoff`

Stops the closed loop controller driving the motor once it reaches a temperature.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-24263d80df554541c4bf12ba85717aa6911ed49f%2Fsmc-temperature-cutoff.png?alt=media" alt="A graph against time. The motor temperature climbs until it reaches the cutoff temperature. At that moment the closed loop output drops to zero volts, the motor stops driving, and the temperature falls."><figcaption><p>The output drops to zero at the cutoff temperature.</p></figcaption></figure>

```java
.withTemperatureCutoff(Celsius.of(80))
```

While the motor is at or above the cutoff, the closed loop output is zero, so a mechanism that was being held up will drop. Treat it as a last resort and fix the cause with [current limits](/documentation/how-to-motor-controllers-and-sensors/limiting-power-consumption) or gearing.

{% hint style="danger" %}
On a SPARK MAX, SPARK Flex or Thrifty Nova with a **trapezoidal** position profile, or a PID alone, the cutoff is rejected: the loop runs on the motor controller, and the cutoff is only checked by the loop on the SystemCore. Use an exponential profile if you rely on the cutoff.
{% endhint %}

**Not supported everywhere.** The cutoff is enforced by the closed loop running on the SystemCore, so it only works where the loop runs there. An [LQR controller](/documentation/understanding/lqr-controllers) always runs there, so the cutoff works with LQR on every motor controller. An A301's loop always runs there, so on an A301 it works in closed loop mode.

| TalonFX                                                                        | TalonFXS                                                                       | SPARK MAX / Flex                                                                                         | Thrifty Nova                                                                                                                                                                           | A301                        |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |
| ⚠️ only with an [LQR controller](/documentation/understanding/lqr-controllers) | ⚠️ only with an [LQR controller](/documentation/understanding/lqr-controllers) | ⚠️ only with an exponential profile or an [LQR controller](/documentation/understanding/lqr-controllers) | ⚠️ only when the loop runs on the SystemCore, such as with an exponential profile, a velocity trapezoidal profile or an [LQR controller](/documentation/understanding/lqr-controllers) | ⚠️ only in closed loop mode |

## Code reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)


# Encoders

Every motor has a built in encoder. Many mechanisms add an external one that knows where the mechanism is when the robot turns on.

{% hint style="warning" %}
Not every option on this page is supported on every motor controller. Each option has a table showing where it works, and an option a controller cannot do throws a `SmartMotorControllerConfigurationException` or an `IllegalArgumentException` at startup. Each option says which. The [config overview](/documentation/reference/editor/config#not-every-option-works-on-every-motor-controller) lists them all together.
{% endhint %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-cf3deb50c766192c416ff3ad499bff20148b57aa%2Fsmc-encoder-chain.png?alt=media" alt="A chain from left to right: the rotor with its built in relative encoder, which starts at zero each boot; the gearing set by withGearing; the mechanism; the encoder gearing set by withExternalEncoderGearing; and the external encoder, set by withExternalEncoder, which is often absolute and remembers its position."><figcaption><p>The built in encoder, the external encoder, and the gearing between them.</p></figcaption></figure>

## `withStartingPosition`

What the built in encoder is set to when the robot turns on.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-f34834e0d85e932f7f031858b95b778749e5d83f%2Fsmc-starting-position.png?alt=media" alt="Two panels with an arm that really is at 90 degrees when the robot turns on. With no starting position the encoder says 0 degrees and every angle is 90 degrees wrong. With withStartingPosition(Degrees.of(90)) the encoder says 90 degrees and angles match the real arm."><figcaption><p>An arm that starts at 90°, with and without a starting position.</p></figcaption></figure>

```java
.withStartingPosition(Degrees.of(90))
.withStartingPosition(Meters.of(0))    // needs a circumference
```

Without it, wherever the mechanism happens to be at startup is called zero. [`withSimStartingPosition`](/documentation/reference/editor/config/simulation#withsimstartingposition) sets a different value for simulation only.

### Why it matters for an arm with `kG`

A wrong angle is more than a wrong number on the dashboard. An [`ArmFeedforward`](/documentation/reference/editor/config/feedforward) multiplies `kG` by the cosine of the arm's angle, so it gives the most voltage when the arm is level and none when it is straight up. It uses the angle YAMS thinks the arm is at. If the arm does not start at 0° and you do not say so, that angle is wrong, and a `kG` you tuned carefully is applied in the wrong places.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-5da5569e5dc14654b62af747b2a028bef27c8af1%2Fsmc-starting-position-kg.gif?alt=media" alt="Animation of the same arm with the same tuned kG of 0.60 volts, moving from straight up at 90 degrees down past level and back. The arm is straight up when the robot turns on. With no starting position YAMS thinks the arm is 90 degrees below where it really is, so kG gives its full voltage when the arm is straight up and needs none, gives almost none when the arm is level and needs the most, and pushes the arm down once it is below level. With withStartingPosition of 90 degrees, the voltage kG gives matches the voltage needed to hold the arm at every angle."><figcaption><p>The same tuned <code>kG</code>. Without the starting position it is applied at the wrong angles.</p></figcaption></figure>

| The arm is really | Needed to hold it | `kG` gives, with no starting position | What happens                                                  |
| ----------------- | ----------------- | ------------------------------------- | ------------------------------------------------------------- |
| Straight up, 90°  | Nothing           | All of `kG`                           | The arm is pushed away from where it should rest              |
| Level, 0°         | All of `kG`       | Nothing                               | The arm sags, and the PID has to make up the whole difference |
| Below level, -20° | Most of `kG`      | A negative voltage                    | The arm is pushed down, the wrong way                         |

So set the starting position before you tune `kG`. A `kG` tuned on an arm with the wrong zero only looks right at the one angle it was tuned at.

**Supported on:** every supported motor controller.

## `withEncoderInverted`

Inverts the motor's built in encoder.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-fc710684b7b879e5f11ade075bdc083c645d7f4e%2Fsmc-encoder-inverted.png?alt=media" alt="Two panels. When the encoder reading goes up as the motor output is positive, the PID pushes toward the setpoint. When the encoder reading goes down instead, the PID pushes away from the setpoint and the mechanism runs off."><figcaption><p>What a backwards encoder does to closed loop control.</p></figcaption></figure>

```java
.withEncoderInverted(true)
```

Most built in encoders are fixed to the rotor and follow [`withMotorInverted`](/documentation/reference/editor/config/motor-basics#withmotorinverted), so they rarely need this. Flip the motor first.

**Not supported everywhere.** It only works on a TalonFXS, and throws on every other controller: a `SmartMotorControllerConfigurationException` on a TalonFX, and an `IllegalArgumentException` on a SPARK, Thrifty Nova or A301.

| TalonFX | TalonFXS | SPARK MAX / Flex | Thrifty Nova | A301 |
| ------- | -------- | ---------------- | ------------ | ---- |
| ❌       | ✅        | ❌                | ❌            | ❌    |

## `withExternalEncoderInverted`

Inverts the [external encoder](#withexternalencoder). Use it when the external encoder counts down while the mechanism moves in the positive direction.

```java
.withExternalEncoder(cancoder)
.withExternalEncoderInverted(true)
```

It throws a `SmartMotorControllerConfigurationException` if no external encoder is configured.

**Supported on:** every supported motor controller, with an external encoder.

## `withExternalEncoder`

Attaches an external encoder. It must be one the motor controller can read directly.

```java
.withExternalEncoder(spark.getAbsoluteEncoder())
.withExternalEncoder(new CANcoder(5, new CANBus(CANPort.CAN_S0)))
```

The encoders each wrapper accepts are listed in the [feature matrix](/documentation/reference/editor/feature-matrix#external-encoders). [How do I use absolute encoders on my arm?](/documentation/how-to-mechanisms/how-do-i-use-absolute-encoders-on-my-arm) has a complete example for each vendor.

{% hint style="warning" %}
**The rule for every absolute encoder:** it must never reach its wrap point, where its reading wraps, anywhere in the mechanism's travel. Use real hard stops, keep the travel under one turn of the encoder, and on a 1:1 encoder set the [zero offset](#withexternalencoderzerooffset) at the mechanism's zero with [`withWrapping(Rotations.of(-0.5), Rotations.of(0.5))`](#withwrapping). [Why: absolute encoders and where they wrap](#why-absolute-encoders-and-where-they-wrap) explains it.
{% endhint %}

**Supported on every motor controller.** Every controller accepts an external encoder, but only ones it can read itself. An encoder from another vendor cannot be used. An A301 only accepts its own absolute encoder, which is on its output shaft, after its gearbox: pass the `A301` itself, as in `.withExternalEncoder(a301)`. The A301 does not report that encoder's velocity, so YAMS takes it from the built in encoder.

| TalonFX               | TalonFXS              | SPARK MAX / Flex                                                                                              | Thrifty Nova                                                    | A301                             |
| --------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | -------------------------------- |
| ✅ `CANcoder`, `CANdi` | ✅ `CANcoder`, `CANdi` | ✅ its absolute encoder, its alternate (MAX) or external (Flex) quadrature encoder, or a REV `DetachedEncoder` | ✅ data port absolute or quadrature encoder, Thrifty CAN encoder | ⚠️ its own absolute encoder only |

## `withExternalEncoderGearing`

The reduction between the mechanism and the external encoder, for an encoder that is not mounted 1:1 on the mechanism's output. The default is 1:1.

The number is how many times the encoder turns for one turn of the mechanism. It appears on the right of the diagram at the top of this page.

```java
// The encoder is on an earlier stage and turns 2 times for each mechanism turn.
// Finer resolution, but YAMS warns at startup: the encoder wraps sooner.
.withExternalEncoderGearing(2)

// The encoder is geared down and turns half a turn for each mechanism turn.
// It cannot wrap within one mechanism turn, so there is no warning.
.withExternalEncoderGearing(0.5)

// The same half turn, written as a 1:2 stage.
.withExternalEncoderGearing(new MechanismGearing(GearBox.fromStages("1:2")))
```

Leave it out when the encoder is mounted 1:1 on the mechanism's output, which is the safest place for an absolute encoder. It throws a `SmartMotorControllerConfigurationException` if no external encoder is configured.

On an A301 it is the gearing from the A301's output shaft, where its absolute encoder is, to the mechanism: for example, 3 for a 3:1 chain after the A301's gearbox.

{% hint style="warning" %}
A number above 1 makes the encoder turn further than the mechanism, so it reaches its wrap point sooner. YAMS prints a warning for it, which is safe to ignore **only** if the travel between the hard stops, multiplied by the gearing, is less than one turn: see [Only gear an absolute encoder if it cannot wrap](#only-gear-an-absolute-encoder-if-it-cannot-wrap).
{% endhint %}

**Supported on:** every supported motor controller.

## `withExternalEncoderZeroOffset`

Moves an absolute encoder's zero to the mechanism's zero.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-2cc8e6896a279c79341aa883a0a3fbab3137a13d%2Fsmc-zero-offset.png?alt=media" alt="Two dials. The encoder reads 37 degrees when the mechanism is at its zero. Subtracting a zero offset of 37 degrees makes YAMS report 0 degrees. To find it, move the mechanism to where you want zero, read the external encoder, and use that reading as the offset."><figcaption><p>The offset is what the encoder reads when the mechanism is at zero.</p></figcaption></figure>

```java
.withExternalEncoderZeroOffset(Degrees.of(37))
```

To find it, move the mechanism to where you want zero and read the external encoder. A negative offset is wrapped into the positive range for you. The wrap point moves with the zero offset: see [Zero offsets and wrapping](#zero-offsets-and-wrapping). The distance version needs a [circumference](/documentation/reference/editor/config/gearing-and-units#withmechanismcircumference).

**Not supported everywhere.** On a quadrature encoder it throws a `SmartMotorControllerConfigurationException`.

| TalonFX | TalonFXS | SPARK MAX / Flex                                                        | Thrifty Nova                      | A301 |
| ------- | -------- | ----------------------------------------------------------------------- | --------------------------------- | ---- |
| ✅       | ✅        | ⚠️ absolute encoders only (its absolute encoder or a `DetachedEncoder`) | ⚠️ absolute and CAN encoders only | ✅    |

## `withWrapping`

Chooses the range an absolute encoder reads, and so where its reading wraps. The closed loop does not wrap: it never takes the mechanism the other way round to a setpoint, so it can be used together with [soft limits](/documentation/reference/editor/config/limits-and-protection#withsoftlimits).

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-fef34d3b599c102260e12c07ecf8587d09e7dc46%2Fsmc-wrapping.png?alt=media" alt="Two number lines. Wrapping over 0 to 1 rotation, the encoder reads 0 to 360 degrees, for mechanisms that only use positive angles. Wrapping over minus 0.5 to 0.5 rotations, it reads minus 180 to 180 degrees, for mechanisms that move either side of zero. The reading jumps from one end to the other at the ends of the range."><figcaption><p>The two ranges an absolute encoder usually reads.</p></figcaption></figure>

```java
.withWrapping(Rotations.of(-0.5), Rotations.of(0.5)) // reads -180° to 180°
.withWrapping(Rotations.of(0), Rotations.of(1))      // reads 0° to 360°
```

The range is one rotation. A mechanism that can turn all the way round, such as a turret or a swerve module, uses [`withContinuousWrapping`](/documentation/reference/editor/config/closed-loop-control#withcontinuouswrapping) instead: it sets the same range, and the closed loop also takes the shortest way to a setpoint. Without either, a SPARK, Thrifty Nova or A301 absolute encoder reads 0° to 360°, and a `CANcoder` or `CANdi` keeps the range it has.

**Not the same everywhere.** Each motor controller accepts only the ranges its encoder can read, and throws a `SmartMotorControllerConfigurationException` for any other. Without an absolute encoder, the range has no effect.

| TalonFX                                                   | TalonFXS                                                  | SPARK MAX / Flex                                                                                          | Thrifty Nova                                                                                                                       | A301                                 |
| --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| ✅ `CANcoder`, `CANdi`: any range from \[-1, 0) to \[0, 1) | ✅ `CANcoder`, `CANdi`: any range from \[-1, 0) to \[0, 1) | ⚠️ its absolute encoder: any range from \[-1, 0) to \[0, 1). A `DetachedEncoder`: \[-0.5, 0.5) or \[0, 1) | ✅ any range. With the encoder closing the loop, \[0, 1) or continuous wrapping runs on the Nova, any other range on the SystemCore | ✅ any range from \[-1, 0) to \[0, 1) |

## `withUseExternalFeedbackEncoder`

Chooses which encoder the closed loop controller follows. The default is `true`: the external encoder, when there is one.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-71aec38b5115a5ddd8b804534f3290fccef46594%2Fsmc-external-feedback.png?alt=media" alt="Two panels. With the option on, the default, the PID follows the external encoder. With it off, the PID follows the built in encoder and the external encoder only sets the built in encoder&#x27;s starting position."><figcaption><p>The external encoder as the feedback sensor, or only as the starting point.</p></figcaption></figure>

```java
.withUseExternalFeedbackEncoder(false)
```

**Not the same everywhere.** On a SPARK, Thrifty Nova or A301, `false` still uses an absolute external encoder for the starting position, as in the picture. On a TalonFX or TalonFXS, `false` stops YAMS using the external encoder at all: the built in encoder starts from [`withStartingPosition`](#withstartingposition), and setting the external encoder's inversion or gearing then throws a `SmartMotorControllerConfigurationException`.

| TalonFX                                 | TalonFXS                                | SPARK MAX / Flex | Thrifty Nova | A301 |
| --------------------------------------- | --------------------------------------- | ---------------- | ------------ | ---- |
| ⚠️ `false` ignores the external encoder | ⚠️ `false` ignores the external encoder | ✅                | ✅            | ✅    |

## `withFeedbackSynchronizationThreshold`

When the loop follows the built in encoder, re-seeds it from the external encoder whenever the two disagree by more than this.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-b31a907e438d84ebcaa03c8d7304e367bd8a552e%2Fsmc-feedback-sync.png?alt=media" alt="A graph of position against time. The built in encoder slowly drifts away from the external absolute encoder. When the difference passes the threshold the built in encoder is re-seeded and the two lines meet again."><figcaption><p>The built in encoder is re-seeded when it drifts past the threshold.</p></figcaption></figure>

```java
.withUseExternalFeedbackEncoder(false)
.withFeedbackSynchronizationThreshold(Degrees.of(2))
```

It is not available for distance mechanisms: it throws a `SmartMotorControllerConfigurationException` if a circumference is set.

**Not supported everywhere.** Where it is not supported it throws an `IllegalArgumentException` on a TalonFX or TalonFXS, and a `SmartMotorControllerConfigurationException` on a SPARK.

| TalonFX | TalonFXS | SPARK MAX / Flex                                                                                         | Thrifty Nova                | A301                        |
| ------- | -------- | -------------------------------------------------------------------------------------------------------- | --------------------------- | --------------------------- |
| ❌       | ❌        | ⚠️ only with an exponential profile or an [LQR controller](/documentation/understanding/lqr-controllers) | ⚠️ only in closed loop mode | ⚠️ only in closed loop mode |

## Why: absolute encoders and where they wrap

The rule under [`withExternalEncoder`](#withexternalencoder) is all you need to set an encoder up. This section explains it.

### Keep the wrap point outside the travel

This applies to **every absolute encoder, whether it is geared or mounted 1:1**.

An absolute encoder only knows where it is within one turn of its own shaft. The place where its reading wraps is its **wrap point**. It is clearly marked on an absolute encoder, usually as a white line on the casing and another on the bearing: when the two lines line up, the encoder reads zero. With [`withWrapping`](#withwrapping) over \[0, 1) and no zero offset, that is also where it wraps. Wrapping over \[-0.5, 0.5) moves the wrap point to 180° from the line on the casing. The line itself does not move. A zero offset moves the wrap point too: see [Zero offsets and wrapping](#zero-offsets-and-wrapping). If the encoder passes its wrap point anywhere inside the mechanism's travel, two different mechanism positions give the same reading and YAMS cannot tell them apart.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-cb5a593010909af7cef2a0aa96ab00be12d5829c%2Fsmc-encoder-hard-stops.gif?alt=media" alt="Animation of a disabled arm being pushed by hand. Its 1:1 absolute encoder is drawn with a white line on its casing and one on its bearing. It reads minus 180 to 180 degrees, so its wrap point is 180 degrees from the line on the casing. With a hard stop at 150 degrees the arm stops there and YAMS keeps reporting the right angle. With only a soft limit at 150 degrees the arm is pushed past it and past the wrap point, where the reading jumps by 360 degrees to minus 155."><figcaption><p>A hard stop keeps the encoder away from its wrap point. A soft limit does not, because it does nothing while the robot is disabled.</p></figcaption></figure>

An absolute encoder should only be used when careful installation guarantees that it never reaches its wrap point anywhere in the range of motion:

* **Adequate hard stops.** The mechanism must be physically unable to leave the range. [Soft limits](/documentation/reference/editor/config/limits-and-protection#withsoftlimits) are not enough: they do nothing when the robot is disabled and pushed by hand, and the encoder is read when the robot boots.
* **Less than one encoder turn of travel.** The travel between the hard stops must be less than one rotation of the encoder. A 1:1 encoder on a mechanism that turns all the way round, or more, cannot meet this.
* **The wrap point outside the travel.** On a 1:1 encoder, [`withWrapping(Rotations.of(-0.5), Rotations.of(0.5))`](#withwrapping) should be sufficient. On a geared encoder, also install it so that the encoder never reaches its wrap point anywhere between the hard stops, with some margin at both ends. Move the mechanism from one hard stop to the other by hand and watch the white lines to check.

{% hint style="success" %}
**Without gearing, wrapping over \[-0.5, 0.5) should be sufficient.** With [`withWrapping(Rotations.of(0), Rotations.of(1))`](#withwrapping) the reading goes from 0 to 360° and wraps at the line on the casing. With `withWrapping(Rotations.of(-0.5), Rotations.of(0.5))` it goes from -180° to 180° and wraps 180° from the line. The line on the casing does not move, only the wrap point does. With a [zero offset](#zero-offsets-and-wrapping) set at the mechanism's zero, the wrap point is 180° from the mechanism's zero, so a 1:1 mechanism that stays within 180° of its zero never reaches it.
{% endhint %}

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-651887f365200ae9f7672c0b1be4950fb881d1cb%2Fsmc-encoder-wrapping-range.gif?alt=media" alt="Animation of a 1:1 arm moving between hard stops at minus 40 and 110 degrees, with the two wrapping ranges. The absolute encoder is drawn with a white line on its casing and one on its bearing, which line up at the arm&#x27;s zero in both panels. Wrapping over 0 to 1 rotation, the wrap point is at the line on the casing, inside the travel, so the reading jumps by 360 degrees when the arm goes below zero. Wrapping over minus 0.5 to 0.5 rotations, the wrap point is 180 degrees from the line, where the arm never goes, and the reading follows the arm the whole way."><figcaption><p>Wrapping over [0, 1), the wrap point is at the line on the casing. Over [-0.5, 0.5) it is 180° from it, and the line has not moved.</p></figcaption></figure>

[Gearing the encoder](#withexternalencodergearing) is where this needs real care, because the encoder then turns further than the mechanism and choosing the range alone is no longer enough. [That section](#only-gear-an-absolute-encoder-if-it-cannot-wrap) has its own animation.

### Only gear an absolute encoder if it cannot wrap

Gearing an absolute encoder up gives finer resolution, but it also uses up the encoder's one turn faster, so it reaches its [wrap point](#keep-the-wrap-point-outside-the-travel) sooner.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-2777bfd697577ff93b59d91b18decd29ed7e64a6%2Fsmc-encoder-gearing-wrap.gif?alt=media" alt="Animation of the same arm moving between hard stops 120 degrees apart, read through two encoder gearings. Each absolute encoder is drawn with a white line on its casing and a white line on its bearing, which line up at the wrap point. With a gearing of 2 the encoder turns 240 degrees, the lines never meet, and YAMS always reports the right angle. With a gearing of 4 the encoder needs 480 degrees, the lines meet partway through the travel, and YAMS then reports an angle 90 degrees too low."><figcaption><p>The same arm and hard stops. Both read [0, 1), so they wrap at the line on the casing. With a gearing of 2 the white lines never meet. With a gearing of 4 they do, and the reported angle is wrong.</p></figcaption></figure>

Encoder gearing can and should be used on an absolute encoder **only** when careful installation guarantees that it never wraps anywhere in the range of motion. The [three conditions for every absolute encoder](#keep-the-wrap-point-outside-the-travel) still apply, and the second one gets stricter: the travel between the hard stops, **multiplied by the gearing**, must be less than one rotation. In the animation, 120° x 2 = 240° fits and 120° x 4 = 480° does not.

If you cannot guarantee that, mount the encoder 1:1 on the mechanism's output, where wrapping over \[-0.5, 0.5) should be sufficient.

### Zero offsets and wrapping

The zero offset and the wrapping range work together, and the order matters: **the offset is applied first, and the range is applied to the result**. So the wrap point is measured from the encoder's zero, not from the line on the casing.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-bb493ac7388ec2592bf3492c69936460052e265f%2Fsmc-encoder-zero-offset-wrapping.gif?alt=media" alt="Animation of the same arm and 1:1 absolute encoder, reading minus 180 to 180 degrees, with the encoder installed a quarter turn round. With no zero offset the encoder reads zero where the white lines line up and its wrap point is opposite that, inside the arm&#x27;s travel, so YAMS reports an angle 90 degrees off and then jumps by 360 degrees. With a zero offset of 90 degrees, the place where the encoder reads zero and the wrap point have both moved a quarter turn, the wrap point is outside the travel, and YAMS reports the right angle. The white line on the casing has not moved."><figcaption><p>The zero offset moves the zero, and the wrap point moves with it. The line on the casing stays where it is.</p></figcaption></figure>

| Zero offset                 | Wrapping over \[0, 1)               | Wrapping over \[-0.5, 0.5)                    |
| --------------------------- | ----------------------------------- | --------------------------------------------- |
| None                        | Wraps where the white lines line up | Wraps 180° from where the white lines line up |
| Set at the mechanism's zero | Wraps at the mechanism's zero       | Wraps 180° from the mechanism's zero          |

What this means in practice:

* **The white lines tell you where the wrap is only when there is no zero offset.** Once an offset is set, work from the mechanism's zero instead.
* **Set the zero offset first, then choose the range.** With the offset at the mechanism's zero and wrapping over \[-0.5, 0.5), a 1:1 encoder wraps as far from zero as it can, however it was installed.
* **A geared encoder is still limited to one turn.** The same rule applies to the encoder's own shaft: 180° of the encoder is `180° / gearing` of the mechanism. See [Only gear an absolute encoder if it cannot wrap](#only-gear-an-absolute-encoder-if-it-cannot-wrap).

#### Where each motor controller applies them

The wrap point only moves with the zero offset because the offset is applied first. That is the case on every encoder YAMS supports:

| Encoder                                              | Zero offset applied         | Range applied                                         |
| ---------------------------------------------------- | --------------------------- | ----------------------------------------------------- |
| `CANcoder`, `CANdi` (TalonFX, TalonFXS)              | On the encoder              | On the encoder, after the offset                      |
| SPARK absolute encoder, REV CAN encoder              | On the SPARK or the encoder | On the SPARK or the encoder, after the offset         |
| Nova data port absolute encoder, Thrifty CAN encoder | On the Nova or the encoder  | By YAMS, on the reading the device has already offset |
| A301 absolute encoder                                | By YAMS                     | By YAMS, after the offset                             |

{% hint style="warning" %}
**Gearing does not move the wrap point.** The zero offset is given in mechanism angle and converted for you, but the wrapping range is always one rotation of the **encoder's own shaft**. On a geared encoder, wrapping over \[-0.5, 0.5) wraps `180° / gearing` of the mechanism from zero, not 180°. See [Only gear an absolute encoder if it cannot wrap](#only-gear-an-absolute-encoder-if-it-cannot-wrap).
{% endhint %}

{% hint style="info" %}
An offset you apply yourself is different. If you leave the encoder's zero offset unset and subtract an angle from the reading in your own code, the encoder's range has already been applied, so the wrap point stays where it was and only the numbers shift.
{% endhint %}

## Code reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)


# Followers

Two ways to have more than one motor move one mechanism: **tightly coupled** followers and **loosely coupled** followers.

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-8fdf189e915651eb7bf985c14d6f3e6c63613df0%2Fsmc-followers.png?alt=media" alt="Two panels. Tightly coupled, withFollowers: a leader and a follower are on one shaft or gearbox and the follower copies the leader&#x27;s output. The motors are mechanically locked, there is one closed loop and one config, the followers are the same vendor as the leader, and voltage and duty cycle reach every motor. Loosely coupled, withLooselyCoupledFollowers: two separate motors joined only by the mechanism get the same setpoint and each runs its own PID. They are not mechanically locked, each has its own closed loop and config, vendors can be mixed, and voltage and duty cycle are not forwarded, so the leader moves alone."><figcaption><p>Tightly coupled followers share a shaft. Loosely coupled followers are separate motors.</p></figcaption></figure>

|                        | Tightly coupled: `withFollowers`                            | Loosely coupled: `withLooselyCoupledFollowers`                                   |
| ---------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------- |
| The motors are         | Mechanically locked on one shaft or gearbox                 | Separate, joined only by the mechanism                                           |
| Closed loop            | One, on the leader. Followers copy its output               | One on each motor, on its own encoder                                            |
| Config                 | Only the leader has one                                     | Every motor has its own                                                          |
| Vendors                | Same vendor as the leader                                   | Can be mixed                                                                     |
| Voltage and duty cycle | Reach every motor                                           | **Not forwarded.** The leader moves alone, and the followers stop                |
| Use it for             | Two motors on one gearbox, such as an elevator or a shooter | Two actuators that must arrive together, such as a cross bar lifted at both ends |
| Mechanism classes      | Work with them                                              | Work with them: give the mechanism the leader                                    |

## `withFollowers`

Tightly coupled followers, for motors on the same shaft or gearbox. Each follower copies the leader's output, so only the leader needs a config.

```java
.withFollowers(Pair.of(new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless), false),
               Pair.of(new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless), true))
```

Pass the vendor's motor object, not a `SmartMotorController`. The boolean is whether that follower is inverted relative to the leader: motors facing each other across a gearbox usually are.

**Not supported everywhere.** Followers must be the same vendor as the leader. A TalonFX and a TalonFXS are both CTRE, so either can follow the other. To mix brands, use [`withLooselyCoupledFollowers`](#withlooselycoupledfollowers). An A301 has no follower mode, so its followers are other `A301Wrapper`s, which it sends its voltage in software: `.withFollowers(Pair.of(rightA301Motor, true))`. Anything else throws a `SmartMotorControllerConfigurationException`. See [Several A301s on one mechanism](https://yams.yassrobotics.com/api-reference/java-reference/motor-controllers/a301-wrapper#several-a301s-on-one-mechanism).

| TalonFX                          | TalonFXS                         | SPARK MAX / Flex       | Thrifty Nova          | A301                           |
| -------------------------------- | -------------------------------- | ---------------------- | --------------------- | ------------------------------ |
| ✅ TalonFX and TalonFXS followers | ✅ TalonFXS and TalonFX followers | ✅ SPARK followers only | ✅ Nova followers only | ✅ `A301Wrapper` followers only |

## `withLooselyCoupledFollowers`

Loosely coupled followers are for motors that are not on the same shaft or gearbox but must arrive at the same place: an intake arm driven from both sides, two linear actuators joined by a cross bar, or a shooter with a wheel on each end. Each follower is a full `SmartMotorController` with its own config, its own encoder and its own closed loop. The leader sends it every position and velocity setpoint it is given.

**You can mix brands.** Because each motor closes its own loop, a loosely coupled follower can be any supported motor controller, whatever the leader is, such as a SPARK leading a TalonFX.

**Supported on:** every supported motor controller.

**In simulation.** A mechanism class simulates the leader and its loosely coupled followers together, since they move one mechanism:

* Its simulation has every motor (the leader's `getMechanismDCMotor()`). Give each motor its own `DCMotor`, such as `DCMotor.getNEO(1)`, and the mechanism adds them up.
* Each motor applies its own output, as its motor controller's simulation (`SparkSim`, Phoenix, the Nova or the A301) gives it, with its own current limit. So a follower that isn't driven, such as during manual control, holds the mechanism back, as it does on the robot.
* The mechanism iterates each follower's simulation right after its own, and each follower's encoder reads it. The battery simulation counts their current once.

Without a mechanism class, such as two flywheels on their own shafts, each motor simulates its own load, and you call `simIterate()` on each follower.

### Use them with a mechanism class

A mechanism class such as `Arm`, `Elevator` or `FlyWheel` works with loosely coupled followers. Give the mechanism the leader, and name the followers in the leader's config. The mechanism's commands, such as `arm.setAngle(...)`, then move every motor.

{% tabs %}
{% tab title="Java, Commands v2" %}
{% code title="subsystems/IntakeArmSubsystem.java" %}

```java
public class IntakeArmSubsystem extends SubsystemBase {

  // The right side of the arm. Declare a follower before the leader, which names it.
  private final SparkMax rightSpark = new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless);
  private final SmartMotorController rightMotor = new SparkWrapper(rightSpark, DCMotor.getNEO(1),
      new SmartMotorControllerConfig(this)
          .withControlMode(ControlMode.CLOSED_LOOP)
          .withClosedLoopController(50, 0, 0)
          .withSimClosedLoopController(50, 0, 0)
          .withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
          .withFeedforward(new ArmFeedforward(0, 0, 0))
          .withSimFeedforward(new ArmFeedforward(0, 0, 0))
          .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
          // The right motor faces the other way, so it is inverted here, in its own config.
          .withMotorInverted(true)
          .withZeroPower(MotorMode.BRAKE)
          .withStatorCurrentLimit(Amps.of(40))
          .withStartingPosition(Degrees.of(-5))
          .withSoftLimits(Degrees.of(-20), Degrees.of(30))
          .withTelemetry("IntakeArmRightMotor", TelemetryVerbosity.HIGH));

  // The left side of the arm: the leader, which the Arm drives.
  private final SparkMax leftSpark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);
  private final SmartMotorController leftMotor = new SparkWrapper(leftSpark, DCMotor.getNEO(1),
      new SmartMotorControllerConfig(this)
          .withControlMode(ControlMode.CLOSED_LOOP)
          .withClosedLoopController(50, 0, 0)
          .withSimClosedLoopController(50, 0, 0)
          .withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
          .withFeedforward(new ArmFeedforward(0, 0, 0))
          .withSimFeedforward(new ArmFeedforward(0, 0, 0))
          .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
          .withMotorInverted(false)
          .withZeroPower(MotorMode.BRAKE)
          .withStatorCurrentLimit(Amps.of(40))
          .withStartingPosition(Degrees.of(-5))
          .withSoftLimits(Degrees.of(-20), Degrees.of(30))
          .withTelemetry("IntakeArmLeftMotor", TelemetryVerbosity.HIGH)
          // The right motor is sent every position and velocity setpoint the left motor is given.
          .withLooselyCoupledFollowers(rightMotor));

  private final Arm arm = new Arm(new ArmConfig()
      .withHardLimits(Degrees.of(-25), Degrees.of(35))
      .withLength(Meters.of(0.5))
      .withTelemetry("IntakeArm", TelemetryVerbosity.HIGH),
      leftMotor);

  public Command setAngle(Angle angle) {
    // Moves both motors.
    return arm.setAngle(angle);
  }

  @Override
  public void periodic() {
    arm.updateTelemetry();
    // The Arm only updates the leader. Update each follower yourself.
    rightMotor.updateTelemetry();
  }

  @Override
  public void simulationPeriodic() {
    // Simulates both motors: the Arm iterates its followers.
    arm.simIterate();
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Java, Commands v3" %}
The same arm as a Commands v3 `Mechanism`, with `SmartMotorControllerConfig` and `Arm` from `yams.commands3`. A `Mechanism` has no periodic hook of its own, so the class gets a `periodic()` and a `simulationPeriodic()` that update the arm and the follower, and `Robot.java` calls them.

{% code title="mechanisms/IntakeArmMechanism.java" %}

```java
public class IntakeArmMechanism implements Mechanism {

  // The right side of the arm. Declare a follower before the leader, which names it.
  private final SparkMax rightSpark = new SparkMax(CANPort.CAN_S0, 5, MotorType.kBrushless);
  private final SmartMotorController rightMotor = new SparkWrapper(rightSpark, DCMotor.getNEO(1),
      new SmartMotorControllerConfig(this)
          .withControlMode(ControlMode.CLOSED_LOOP)
          .withClosedLoopController(50, 0, 0)
          .withSimClosedLoopController(50, 0, 0)
          .withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
          .withFeedforward(new ArmFeedforward(0, 0, 0))
          .withSimFeedforward(new ArmFeedforward(0, 0, 0))
          .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
          // The right motor faces the other way, so it is inverted here, in its own config.
          .withMotorInverted(true)
          .withZeroPower(MotorMode.BRAKE)
          .withStatorCurrentLimit(Amps.of(40))
          .withStartingPosition(Degrees.of(-5))
          .withSoftLimits(Degrees.of(-20), Degrees.of(30))
          .withTelemetry("IntakeArmRightMotor", TelemetryVerbosity.HIGH));

  // The left side of the arm: the leader, which the Arm drives.
  private final SparkMax leftSpark = new SparkMax(CANPort.CAN_S0, 4, MotorType.kBrushless);
  private final SmartMotorController leftMotor = new SparkWrapper(leftSpark, DCMotor.getNEO(1),
      new SmartMotorControllerConfig(this)
          .withControlMode(ControlMode.CLOSED_LOOP)
          .withClosedLoopController(50, 0, 0)
          .withSimClosedLoopController(50, 0, 0)
          .withTrapezoidalProfile(DegreesPerSecond.of(90), DegreesPerSecondPerSecond.of(45))
          .withFeedforward(new ArmFeedforward(0, 0, 0))
          .withSimFeedforward(new ArmFeedforward(0, 0, 0))
          .withGearing(new MechanismGearing(GearBox.fromReductionStages(3, 4)))
          .withMotorInverted(false)
          .withZeroPower(MotorMode.BRAKE)
          .withStatorCurrentLimit(Amps.of(40))
          .withStartingPosition(Degrees.of(-5))
          .withSoftLimits(Degrees.of(-20), Degrees.of(30))
          .withTelemetry("IntakeArmLeftMotor", TelemetryVerbosity.HIGH)
          // The right motor is sent every position and velocity setpoint the left motor is given.
          .withLooselyCoupledFollowers(rightMotor));

  private final Arm arm = new Arm(new ArmConfig()
      .withHardLimits(Degrees.of(-25), Degrees.of(35))
      .withLength(Meters.of(0.5))
      .withTelemetry("IntakeArm", TelemetryVerbosity.HIGH),
      leftMotor);

  public Command setAngle(Angle angle) {
    // Moves both motors.
    return arm.setAngle(angle);
  }

  /** Call this from Robot.robotPeriodic(), before the scheduler runs. */
  public void periodic() {
    arm.updateTelemetry();
    // The Arm only updates the leader. Update each follower yourself.
    rightMotor.updateTelemetry();
  }

  /** Robot.simulationInit() runs this in its own Notifier, every robot loop. */
  public void simulationPeriodic() {
    // Simulates both motors: the Arm iterates its followers.
    arm.simIterate();
  }
}
```

{% endcode %}

In `Robot.java`, call `intakeArm.periodic()` from `robotPeriodic()` and start `intakeArm::simulationPeriodic` in a `Notifier` from `simulationInit()`, exactly as for any mechanism in [Where the tutorials put things](/documentation/tutorials/project-setup#where-the-tutorials-put-things). The imports are the ones in [Step 3 of the Arm tutorial](/documentation/tutorials/arm/commands), plus `Meters`, and the `simple_robot-2027` example has a complete [Commands v3 arm mechanism](https://github.com/Yet-Another-Software-Suite/YAMS/blob/master/examples/commands3/simple_robot-2027/src/main/java/first/robot/mechanisms/ArmMechanism.java).
{% endtab %}

{% tab title="C++" %}
Create each follower before the leader, and name it in the leader's config:

```cpp
m_rightMotor.emplace(&m_rightSpark, wpi::math::DCMotor::NEO(1), &m_rightConfig);

m_leftConfig
    // ... config options
    .WithLooselyCoupledFollowers({&m_rightMotor.value()});  // the right motor is sent the left motor's setpoints

m_leftMotor.emplace(&m_leftSpark, wpi::math::DCMotor::NEO(1), &m_leftConfig);
```

Call `UpdateTelemetry()` on each follower, as on the arm. The arm's `SimIterate()` simulates every motor.
{% endtab %}
{% endtabs %}

### What reaches the followers

| The leader is given                                                                                                                 | The followers                                                                              |
| ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| A position or velocity setpoint, such as from `arm.setAngle(...)` or `flywheel.run(...)`                                            | Are sent the same setpoint, and each reaches it with its own closed loop                   |
| A change from live tuning: gains, feedforward, motion profile, current limits, ramp rates, soft limits, gearing or closed loop slot | Are given the same change                                                                  |
| A duty cycle of 0, which stops it                                                                                                   | Stop too\*                                                                                 |
| Any other duty cycle or voltage, such as from `arm.set(...)`, `arm.setVoltage(...)` or SysId                                        | **Are not sent it.** The leader moves alone, and the followers are stopped\*               |
| `setEncoderPosition(...)`, such as when zeroing or homing                                                                           | **Are not sent it.** Set each follower's encoder yourself                                  |
| `updateTelemetry()`                                                                                                                 | **Are not updated.** Call it on each follower yourself                                     |
| `simIterate()`, in a mechanism class                                                                                                | Are iterated by the mechanism, right after it steps. Their own `simIterate()` does nothing |
| `simIterate()`, without a mechanism class                                                                                           | **Are not iterated.** Call it on each follower yourself                                    |
| Its starting config                                                                                                                 | **Are not given it.** Each follower only has its own config                                |

\* A follower whose closed loop runs on the SystemCore only stops in YAMS releases after v2026.10.15. See the first pitfall below.

### Common pitfalls

* **The follower doesn't stop (YAMS v2026.10.15 and earlier).** A follower's closed loop runs on the SystemCore when it is a Thrifty Nova, a SPARK with an exponential profile, or any motor controller with an LQR. In YAMS v2026.10.15 and earlier, stopping the leader doesn't stop that loop, so the follower keeps driving to the last setpoint: on through `arm.set(0)`, and against the leader through `arm.set(...)`, `arm.setVoltage(...)` and SysId. Later releases stop it with the leader. Until you update, stop the follower's closed loop yourself while the leader is driven at a duty cycle or voltage. In Commands v2:

  ```java
  arm.set(dutyCycle)
      .beforeStarting(() -> {
        rightMotor.stopClosedLoopController();
        rightMotor.setDutyCycle(0);
      })
      .finallyDo(rightMotor::startClosedLoopController);
  ```
* **The follower logs nothing.** Call `updateTelemetry()` on each follower, every loop. Without a mechanism class, also call `simIterate()` on it, or it does nothing in simulation.
* **The follower doesn't follow the profile.** The leader sends the follower the final setpoint, so a follower needs the same motion profile as the leader, and the same gearing, gains and feedforward, or it gets there at a different speed.
* **The follower drives the wrong way.** Each motor is inverted in its own config, with `withMotorInverted`. Motors on opposite sides of a mechanism usually face each other, so one of them is inverted.
* **The two sides fight.** Nothing keeps the motors together except the mechanism: each one only follows its own encoder. If they start at different positions, or one side slips, they pull against each other through the mechanism. Give every motor the same starting position, and when you zero or home the mechanism, set every motor's encoder.
* **Manual control moves only one side.** A voltage or duty cycle, such as manual control with a joystick or a SysId routine, only drives the leader, and the followers are stopped. Command each motor yourself, or characterize one side with the other side unpowered. A mechanism class simulates this too: the stopped followers hold the mechanism back.

### Motors that need different setpoints

Loosely coupled followers are sent the leader's setpoints exactly. When the motors need different ones, such as two flywheels spinning at different speeds, command each `SmartMotorController` yourself: see [How do I control a mechanism without a mechanism class?](/documentation/how-to-mechanisms/how-do-i-control-a-mechanism-without-a-mechanism-class) and the [double flywheel tutorial](/documentation/tutorials/double-flywheel/spin-and-followers).

## Code reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)


# Simulation

These options only change what happens in simulation. The real robot ignores them.

Every option on this page is supported on every supported motor controller.

## `withSimClosedLoopController` and `withSimFeedforward`

A second set of gains used only in simulation. They take the same arguments, including [slots](/documentation/reference/editor/config/closed-loop-control#slots), as [`withClosedLoopController`](/documentation/reference/editor/config/closed-loop-control#withclosedloopcontroller) and [`withFeedforward`](/documentation/reference/editor/config/feedforward#withfeedforward).

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-ae62667211c91557f7899aa1a805ed631d789f58%2Fsmc-sim-gains.png?alt=media" alt="A diagram. On the real robot the closed loop controller uses the gains from withClosedLoopController and withFeedforward to drive the real mechanism, which has friction, backlash and flex. In simulation it uses the gains from withSimClosedLoopController and withSimFeedforward to drive a simulated mechanism, an ideal motor and load."><figcaption><p>Real gains for the real mechanism, simulation gains for the simulated one.</p></figcaption></figure>

```java
.withClosedLoopController(4, 0, 0.2)
.withSimClosedLoopController(12, 0, 0)
.withFeedforward(new ArmFeedforward(0.15, 0.35, 1.2))
.withSimFeedforward(new ArmFeedforward(0, 0.3, 1.2))
```

[Simulation-only PID + feedforward](/documentation/understanding/simulation-only-pid-+-feedforward) explains why the two usually differ, with an example.

## `withSimStartingPosition`

Where the simulated mechanism starts, when that should differ from the real [starting position](/documentation/reference/editor/config/encoders#withstartingposition).

```java
.withSimStartingPosition(Degrees.of(45))
```

It is most useful with an absolute encoder: the real robot reads its position from the encoder, and simulation needs to be told one.

## `withMomentOfInertia`

How hard the simulated load is to spin up. An `Arm`, `Pivot` and `FlyWheel` simulate with this value, and so does a `SmartMotorController` simulated on its own. The default is 0.02 kg·m², so set it for anything heavier than a small roller. An `Elevator` uses its carriage mass instead.

```java
.withMomentOfInertia(KilogramSquareMeters.of(0.02))          // from CAD
.withMomentOfInertia(Inches.of(18), Pounds.of(8))           // an arm: a rod of this length and mass, turning about one end
.withWheelMomentOfInertia(Inches.of(4), Pounds.of(1))       // a wheel or roller: a solid disk of this diameter and mass
```

Use exactly one; the last call wins. For a wheel, `withWheelMomentOfInertia` gives about a third of what the arm version gives for the same numbers, so don't use the arm version for wheels.

## `withSimulationPeriod`

How often the simulated physics are stepped. The default is 20 ms, and it is independent of [`withClosedLoopControlPeriod`](/documentation/reference/editor/config/closed-loop-control#withclosedloopcontrolperiod).

```java
.withSimulationPeriod(Milliseconds.of(5))
```

Each `simIterate()` call steps the physics by exactly this period, so it must match how often `simIterate()` is called. To step every 1 ms, as fast as a closed loop on the motor controller runs, call it from a `Notifier`: see [How do I run a high fidelity simulation?](/documentation/how-to-simulation-and-logging/how-do-i-run-a-high-fidelity-simulation)

<figure><img src="https://1354553280-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZM0CFmYiQzcrY4zDcTtZ%2Fuploads%2Fgit-blob-5c09f60c6379acc3d587b2f948f49586ca41e9a3%2Fsmc-simulation.png?alt=media" alt="Two graphs. Simulated speed: a small moment of inertia spins up quickly and a large one more slowly, set by withMomentOfInertia. Simulated position: 20 millisecond steps, the default, make a coarse staircase and 5 millisecond steps make a finer curve, set by withSimulationPeriod."><figcaption><p>Moment of inertia and simulation period.</p></figcaption></figure>

## Running the simulation

A mechanism class steps its motor's simulation for you when you call its `simIterate()`. A `SmartMotorController` used without a mechanism class needs its own `simIterate()` called every loop in simulation, and its own `updateTelemetry()` called every loop, so it publishes values and picks up live tuning. In a Commands v2 subsystem:

```java
@Override
public void periodic() {
  smartMotorController.updateTelemetry();
}

@Override
public void simulationPeriodic() {
  smartMotorController.simIterate();
}
```

In Commands v3, call them from the methods `Robot.java` runs, as in [Where the tutorials put things](/documentation/tutorials/project-setup#where-the-tutorials-put-things). Every simulated motor also draws from the shared [battery simulation](/documentation/understanding/battery-simulation).

### While the robot is disabled

A disabled robot's motors get no power, and the simulation does the same: every simulated motor gets 0 V while the robot is disabled, whatever it was last sent. An arm or an elevator falls onto its lower hard limit, and a flywheel coasts to a stop.

A closed loop that runs on the SystemCore sends nothing while the robot is disabled. It follows the mechanism instead, so when you enable, its PID, motion profile and LQR start from where the mechanism is, not from where it was when the robot was disabled, and the mechanism does not jump.

## Code reference

* [`SmartMotorControllerConfig`](https://javadocs.yassrobotics.com/yams/yams/core/motorcontrollers/SmartMotorControllerConfig.html)




---

[Next Page](https://yams.yassrobotics.com/llms-full.txt/1)

