> For the complete documentation index, see [llms.txt](https://docs.raidrobotics.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.raidrobotics.org/commands-v3-state-machine/guide/mechanisms.md).

# Mechanisms

A **mechanism** is one physical part of the robot with its own motors: an arm, an elevator, an intake. Each one is a class in `subsystems/` that implements Commands v3's `Mechanism`.

The template has two placeholder mechanisms. Each is the pattern to copy for one kind of real mechanism:

| Template     | Is a...                                                  | Copy it for                                                         |
| ------------ | -------------------------------------------------------- | ------------------------------------------------------------------- |
| `Mechanism1` | Pivoting arm that goes to positions and holds them       | Arms, wrists, pivots, turrets, and (with different units) elevators |
| `Mechanism2` | Rollers that spin at a voltage, with a game piece sensor | Intakes, feeders, indexers, simple shooter wheels                   |

## The rules

* **Only this class talks to its motor.** Everything else asks through readings and commands.
* **A mechanism knows nothing about other mechanisms.** Rules that involve two of them live in the [superstructure](https://docs.raidrobotics.org/commands-v3-state-machine/guide/superstructure.md).
* **Commands tell the motor what to do every loop** (`runRepeatedly`) **and don't end on their own.** The state machine decides when to move on.

## The six-part shape

Every mechanism file is laid out the same way, top to bottom, so you always know where to look:

| Part                | What's in it                                                                     |
| ------------------- | -------------------------------------------------------------------------------- |
| **1. Constants**    | What's true about the hardware (gear ratio, limits) and the positions it goes to |
| **2. Hardware**     | The motors and sensors, and the control request, made once                       |
| **3. Constructor**  | Configures the hardware; registers `periodic()` for logging                      |
| **4. Readings**     | Questions other code may ask: `getAngle()`, `isAt(...)`, `hasGamePiece()`        |
| **5. Commands**     | The **only** way anything moves this mechanism: `goTo(...)`, `intake()`          |
| **6. `periodic()`** | Logging                                                                          |

Tuning numbers (gains, ratios, positions, voltages) live in part 1 of the mechanism's own file, not in `Constants.java`. That way you can read a mechanism top to bottom without jumping between files.

## Mechanism1: goes to positions

### Constants

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

```java
public static final double GEAR_RATIO = 50.0;

public static final Angle MIN_ANGLE = Degrees.of(0);
public static final Angle MAX_ANGLE = Degrees.of(110);

public static final Angle STOW = Degrees.of(90);
public static final Angle INTAKE = Degrees.of(5);
public static final Angle SCORE = Degrees.of(60);

private static final Angle TOLERANCE = Degrees.of(2);
```

{% endcode %}

0° is horizontal (pointing forward) and 90° is straight up. The `Arm_Cosine` gravity compensation needs that convention. More positions are just more lines.

### Hardware and control

The motor uses **Motion Magic**: a smooth, speed-limited move to a position, run inside the motor controller at 1 kHz. FOC (a Phoenix Pro feature, about 15% more torque) is on for every request in the project.

```java
private final TalonFX motor = new TalonFX(Constants.CAN.MECHANISM_1_MOTOR, Constants.CAN.MECHANISM_BUS);
private final MotionMagicVoltage request = new MotionMagicVoltage(Rotations.of(0)).withEnableFOC(true);
```

{% hint style="info" %}
Make one request object and reuse it. Creating a new one every loop makes garbage for Java to clean up.
{% endhint %}

### Configuration

The constructor sets up the motor once:

| Setting                      | Value                      | Why                                                                                                                          |
| ---------------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `NeutralMode`                | Brake                      | Holds still when not driven                                                                                                  |
| `SensorToMechanismRatio`     | `GEAR_RATIO`               | Every position the motor reports or accepts is in **mechanism** rotations, so the code thinks in arm angles, not motor turns |
| `GravityType`                | `Arm_Cosine`               | Gravity compensation that scales with the arm's angle                                                                        |
| `kG`, `kS`, `kV`, `kP`, `kD` | 0.35, 0.1, 6.0, 60, 2      | Tuned against the simulated arm                                                                                              |
| Motion Magic cruise / accel  | 1.0 rot/s, 4.0 rot/s²      | In mechanism rotations                                                                                                       |
| Software limits              | `MIN_ANGLE` to `MAX_ANGLE` | The motor refuses to drive past the ends, even if something asks it to                                                       |
| Stator current limit         | 60 A                       | Protects the motor and the battery. RAIDLogs flags a motor that sits at this limit.                                          |

Retune the gains on the real robot in this order (Tuner X's **Control** tab does this live):

1. **kG**: the voltage that just holds the arm level.
2. **kS**: the extra voltage that just starts it moving.
3. **kV**: 12 V ÷ free speed (in mechanism rotations per second).
4. **kP**: raise until it reaches the target crisply. Add **kD** only if it overshoots.

{% hint style="warning" %}
Mechanism 1 has no absolute sensor. The constructor calls `motor.setPosition(STOW)`, so the code **assumes the arm is stowed when the robot turns on**. If it isn't, every position is off by that much. With a CANcoder on the joint, delete that line; see `SimpleSuperstructure-v3`'s `Arm.java`.
{% endhint %}

### Readings and commands

```java
public Angle getAngle()                 // where it is now (measured, not the target)
public boolean isAt(Angle angle)        // within TOLERANCE of that angle

public Command goTo(String name, Angle angle)             // move there and hold
public Command goTo(String name, Supplier<Angle> angle)   // target re-read every loop
```

`goTo` never ends on its own. Give it a name that says *why* it's moving ("Stow", "Score"); it shows up in the log as `Mechanism1.Stow`.

The `Supplier` version reads the target again every loop, so it can follow a target that changes, like an angle worked out from the distance to a goal.

## Mechanism2: spins

`Mechanism2` has the same six-part shape. The difference is the control: there's no position, only "run at this voltage".

### Constants

| Constant           | Value  | Used by                                                |
| ------------------ | ------ | ------------------------------------------------------ |
| `INTAKE_VOLTAGE`   | 8 V    | `intake()`                                             |
| `HOLD_VOLTAGE`     | 0.5 V  | `hold()`, so the piece doesn't slide out               |
| `EJECT_VOLTAGE`    | −6 V   | `eject()`                                              |
| `EJECT_EXTRA_TIME` | 0.25 s | How long `eject()` keeps going after the sensor clears |

### The game piece sensor

A beam break on DIO port `MECHANISM_2_BEAM_BREAK` tells the robot whether it has a game piece:

```java
public boolean hasGamePiece() {
    // A beam break reads true while its beam is clear, so a piece in the way reads false.
    return !beamBreak.get();
}
```

To use a CANrange or a current spike instead, change only this method. Everything else, including the state machine, asks `hasGamePiece()`.

### Commands

| Command    | Does                                                                            | Ends                             |
| ---------- | ------------------------------------------------------------------------------- | -------------------------------- |
| `intake()` | Runs at `INTAKE_VOLTAGE`                                                        | Never on its own                 |
| `hold()`   | Runs at `HOLD_VOLTAGE`                                                          | Never on its own                 |
| `stop()`   | Runs at 0 V                                                                     | Never on its own                 |
| `eject()`  | Runs at `EJECT_VOLTAGE` until the sensor clears, then `EJECT_EXTRA_TIME` longer | By itself, when the piece is out |

`eject()` is the template's example of a **command with steps**: an ordinary method body, top to bottom, that calls `coroutine.yield()` wherever it should wait for the next loop. See [Commands v3 in this project](https://docs.raidrobotics.org/commands-v3-state-machine/concepts/commands-v3.md#a-command-with-steps).

### When the speed has to be exact

For a shooter flywheel, switch the request from `VoltageOut` to `VelocityVoltage` (or `VelocityTorqueCurrentFOC` with Phoenix Pro), and add Slot0 gains like Mechanism 1 has.

## Logging

Each mechanism logs what it was **told** and what it **thinks**, in a table named after its class:

| Entry           | Mechanism1     | Mechanism2       |
| --------------- | -------------- | ---------------- |
| Position        | `Angle (deg)`  |                  |
| Target          | `Target (deg)` | `Target (V)`     |
| At target       | `At Target`    |                  |
| Sensor          |                | `Has Game Piece` |
| Running command | `Command`      | `Command`        |

The motor's own signals (current, temperature, voltage, faults) are already in the `.hoot` file at full rate. Don't copy them here. See [Logging](https://docs.raidrobotics.org/commands-v3-state-machine/guide/logging.md).

## Making a real mechanism

Copy the closest template, rename it, and go down its `TODO`s. The full checklist, including the superstructure and simulator changes, is in [Add a mechanism](https://docs.raidrobotics.org/commands-v3-state-machine/how-to/add-a-mechanism.md).

For an elevator, see `SimpleSuperstructure-v3`'s `Elevator.java`: heights instead of angles, and `Elevator_Static` gravity.


---

# 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
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

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

```
GET https://docs.raidrobotics.org/commands-v3-state-machine/guide/mechanisms.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.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
