# ftc-helper-lib docs: every page > ftc-helper-lib is a Java helper library for FIRST Tech Challenge (FTC) robots, for students with little or no Java. These are its docs for release v0.47.0 (docs updated 2026-11-21), from https://crossbotics.com/ftc-helper/docs/. Use only classes, methods and Tunables names that these docs show. A team's own library version can be older: it is in the project's ftc-helper-lib folder (git -C ftc-helper-lib describe --tags). --- # FTC-Helper-Lib docs URL: https://crossbotics.com/ftc-helper/docs/ Shortcuts for programming an FTC robot in Java. These pages match release **v0.47.0**. **New here?** [Set up](https://crossbotics.com/ftc-helper/docs/setup/), then [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/). Then follow each page's **Next** link: it leads through every section below, in order. ## Start here - [Set up: the tools and the library](https://crossbotics.com/ftc-helper/docs/setup/) - [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/) - [The five files: your robot's code](https://crossbotics.com/ftc-helper/docs/five-files/) - [Add to your robot](https://crossbotics.com/ftc-helper/docs/add-to-robot/) - [Controls](https://crossbotics.com/ftc-helper/docs/controls/) - [Building autos](https://crossbotics.com/ftc-helper/docs/building-autos/) - [Simulator](https://crossbotics.com/ftc-helper/docs/simulator/) - [Tuning](https://crossbotics.com/ftc-helper/docs/tuning/) - [Tests](https://crossbotics.com/ftc-helper/docs/tests/) - [Reference: search every class and method](https://crossbotics.com/ftc-helper/reference/) ## Go deeper: build it by hand Optional. The same things built by hand, with the library's building blocks, to see how they work inside. - [Tutorial 01: OpMode basics with the library](https://crossbotics.com/ftc-helper/docs/tutorials/01-opmode-basics/) - [Tutorial 02: Motors and servos](https://crossbotics.com/ftc-helper/docs/tutorials/02-motors-and-servos/) - [Tutorial 03: Buttons](https://crossbotics.com/ftc-helper/docs/tutorials/03-buttons/) - [Tutorial 04: Drive a mecanum robot](https://crossbotics.com/ftc-helper/docs/tutorials/04-drive-mecanum/) - [Tutorial 05: Drive a standard (tank) robot](https://crossbotics.com/ftc-helper/docs/tutorials/05-drive-tank/) - [Tutorial 06: A fast, clear loop](https://crossbotics.com/ftc-helper/docs/tutorials/06-fast-clear-loop/) - [Tutorial 07: PID: hold a lift at a height](https://crossbotics.com/ftc-helper/docs/tutorials/07-pid-lift/) - [Tutorial 08: A lift that cannot hurt itself](https://crossbotics.com/ftc-helper/docs/tutorials/08-safe-lift/) - [Tutorial 09: Autonomous by hand with AutoDrive](https://crossbotics.com/ftc-helper/docs/tutorials/09-first-auto/) - [Tutorial 10: Autonomous with mechanisms](https://crossbotics.com/ftc-helper/docs/tutorials/10-auto-with-mechanisms/) - [Tutorial 11: Driver assists](https://crossbotics.com/ftc-helper/docs/tutorials/11-driver-assists/) - [Tutorial 12: Organize a whole robot](https://crossbotics.com/ftc-helper/docs/tutorials/12-robot-structure/) - [Tutorial 13: Test your code without a robot](https://crossbotics.com/ftc-helper/docs/tutorials/13-testing/) - [Tutorial 14: Mechanism helpers](https://crossbotics.com/ftc-helper/docs/tutorials/14-mechanisms/) - [Tutorial 15: Telemetry, profiles and tuning](https://crossbotics.com/ftc-helper/docs/tutorials/15-telemetry-profiles-tuning/) - [Tutorial 16: Easy autonomous](https://crossbotics.com/ftc-helper/docs/tutorials/16-easy-autos/) - [Tutorial 17: Launcher](https://crossbotics.com/ftc-helper/docs/tutorials/17-launcher/) - [Tutorial 18: Vision aiming (webcam or Limelight 3A)](https://crossbotics.com/ftc-helper/docs/tutorials/18-vision-aim/) - [Check the hardware (tutorial 19)](https://crossbotics.com/ftc-helper/docs/tutorials/19-testing-procedures/) - [Tutorial 20: Easy TeleOp](https://crossbotics.com/ftc-helper/docs/tutorials/20-easy-teleop/) - [Tutorial 21: Find your numbers](https://crossbotics.com/ftc-helper/docs/tutorials/21-finders/) ## For teams - [Keep the library up to date](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/) - [Starter kit: a whole robot program](https://crossbotics.com/ftc-helper/docs/starter-kit/) · the older six-file starter kit (EasyTeleOp, EasyAuto) - [Coming from last season's code](https://crossbotics.com/ftc-helper/docs/from-last-season/) - [Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/) - [Troubleshooting](https://crossbotics.com/ftc-helper/docs/troubleshooting/) ## Guides - [How it all fits together](https://crossbotics.com/ftc-helper/docs/guides/architecture/) - [Ask an AI agent about the library](https://crossbotics.com/ftc-helper/docs/guides/ask-an-ai-agent/) - [Easy autonomous modes](https://crossbotics.com/ftc-helper/docs/guides/easy-autos/) · make autonomous modes the older way (EasyAuto) - [What runs every loop](https://crossbotics.com/ftc-helper/docs/guides/every-loop/) - [Example: drive, slow mode, and an intake that starts on](https://crossbotics.com/ftc-helper/docs/guides/example-drive-intake/) - [Extending the library](https://crossbotics.com/ftc-helper/docs/guides/extending/) - [Git and GitHub for FTC teams](https://crossbotics.com/ftc-helper/docs/guides/github/) - [How the simulator works](https://crossbotics.com/ftc-helper/docs/guides/how-the-simulator-works/) - [Two parts that must not collide (interlocks)](https://crossbotics.com/ftc-helper/docs/guides/interlocks/) - [Setting up Limelight lighting pipelines](https://crossbotics.com/ftc-helper/docs/guides/limelight-lighting/) - [A new season: what to do](https://crossbotics.com/ftc-helper/docs/guides/new-season/) - [Non-blocking code: keep the loop running](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/) - [Parts catalog: motors, servos, wheels and rollers](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) - [Profiles: practice vs competition](https://crossbotics.com/ftc-helper/docs/guides/profiles/) - [Your robot in the simulator: the robot-file skill](https://crossbotics.com/ftc-helper/docs/guides/robot-file-skill/) - [The BIOBUZZ starter bots: robot files and code](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/) - [Setting up a turret](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/) - [Use only what you need](https://crossbotics.com/ftc-helper/docs/guides/use-only-what-you-need/) - [Your own code at INIT, ▶, every loop and STOP](https://crossbotics.com/ftc-helper/docs/guides/your-own-code/) ## Modules Every class and every function, one page per module. To look one thing up, [search the reference](https://crossbotics.com/ftc-helper/reference/). - [Auto module](https://crossbotics.com/ftc-helper/docs/modules/auto/) - [Control module](https://crossbotics.com/ftc-helper/docs/modules/control/) - [Core module](https://crossbotics.com/ftc-helper/docs/modules/core/) - [Drive module](https://crossbotics.com/ftc-helper/docs/modules/drive/) - [Finders module](https://crossbotics.com/ftc-helper/docs/modules/finders/) - [Gamepad module](https://crossbotics.com/ftc-helper/docs/modules/gamepad/) - [Hardware module](https://crossbotics.com/ftc-helper/docs/modules/hardware/) - [Launcher module](https://crossbotics.com/ftc-helper/docs/modules/launcher/) - [Match module](https://crossbotics.com/ftc-helper/docs/modules/match/) - [Mechanism module](https://crossbotics.com/ftc-helper/docs/modules/mechanism/) - [Odometry module](https://crossbotics.com/ftc-helper/docs/modules/odometry/) - [Pedro module (Pedro Pathing)](https://crossbotics.com/ftc-helper/docs/modules/pedro/) - [Robot module](https://crossbotics.com/ftc-helper/docs/modules/robot/) - [Safety module](https://crossbotics.com/ftc-helper/docs/modules/safety/) - [Telemetry module](https://crossbotics.com/ftc-helper/docs/modules/telemetry/) - [TeleOp module](https://crossbotics.com/ftc-helper/docs/modules/teleop/) - [Testing module](https://crossbotics.com/ftc-helper/docs/modules/testing/) - [Test kit module](https://crossbotics.com/ftc-helper/docs/modules/testkit/) - [Tuning module](https://crossbotics.com/ftc-helper/docs/modules/tuning/) - [Util module](https://crossbotics.com/ftc-helper/docs/modules/util/) - [Vision module](https://crossbotics.com/ftc-helper/docs/modules/vision/) ## Contributing to the library For people who change the library itself, not for robot code. - [Contributing: add or change something in the library](https://crossbotics.com/ftc-helper/docs/contributing/) - [Commenting style](https://crossbotics.com/ftc-helper/docs/commenting-style/) --- # Keep the library up to date URL: https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/ **Before this:** [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/). If you are new to git, read [Git and GitHub for FTC teams](https://crossbotics.com/ftc-helper/docs/guides/github/) first: it explains commit, push, pull and submodule. Your robot project remembers ONE exact version of the library (one git commit: one saved snapshot of the library's files). It does not change by itself. This is good: the robot never changes the night before an event because someone changed the library. **You choose when to update.** ## Why update An old library version keeps its old bugs. A new version brings: - **Fixes.** Another team finds a bug (a lift that could overshoot, an autonomous step that did not stop on time). We fix it once, in the library. You get the fix only when you update. - **Safety.** Limits, timeouts and stall checks get better. A safety fix protects your robot, your hands and the field. - **Game and SDK updates.** FIRST changes the game manual (Team Updates) and the FTC SDK during the season. The library follows: new field numbers for the simulator, changes for a new SDK. - **New features**, like new parts, recipes and simulator checks. A team that never updates fights bugs that are already fixed. A team that updates the day before an event may meet a change it has not tested. So: **update often, but not right before an event.** ## Find out about a new version - **The Simulator button tells you.** Once a day it asks GitHub for the newest version. When a newer version is out, the Run window and the simulator page say so ([the Update library button](#update-the-update-library-button)). - **Watch the library on GitHub.** On the library's page ([github.com/crossbotics/ftc-helper-lib](https://github.com/crossbotics/ftc-helper-lib)), click **Watch** (top right) > **Custom** > tick **Releases** > **Apply**. GitHub then emails you about each new version. (You need a GitHub account. One mentor or the programming lead is enough.) - **Read the [CHANGELOG](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/CHANGELOG.md).** It lists every version, newest first. When changes are waiting for the next version, they are at the top, under "Unreleased". - **The version list:** the [tags page](https://github.com/crossbotics/ftc-helper-lib/tags) shows every version (`v0.16.0`, ...), newest first. - **Check once a week** in the season (for example after the first practice of the week). In the season, new versions can come out several times a week. - **The docs site shows the newest release.** We put docs fixes on the site between releases. So the site can be a little ahead of the `ftc-helper-lib/docs` folder in your project. A box that says "Coming in the next release" describes something that is not in any version yet. If you use an older version, read the `docs` folder in your own project: it matches your version. ## Read the CHANGELOG before you update Open the CHANGELOG and read every version between yours and the new one. Each version has up to three lists: | List | Means | What you do | | --- | --- | --- | | **Added** | something new | nothing, unless you want it | | **Changed** | something works differently now | **read each line**, and check whether your code uses it. You may need to change a line, or test that part again | | **Fixed** | a bug is gone | test the part it names; it may behave a little differently (better) | Look for these words in particular: **renamed**, **removed**, **now**, **default**, **must**, **Tunables**. They mean "your code or your numbers may need a change". Write them down: they are your test list after the update. **The version number tells you a lot** (like `v0.16.0`): - the last number changed (`v0.16.0` -> `v0.16.1`): only fixes. Small risk. - the middle number changed (`v0.16.1` -> `v0.17.0`): new features; read **Changed**. - the first number changed (`v0.x` -> `v1.0.0`): something old works differently. Plan a whole practice for it. ## See which version you have **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash git submodule status ``` It prints the commit (a long code of 40 letters and digits). When the commit has a version tag (a name like `v0.16.0` given to one release), it prints the tag too. For example: ` 3f2c1a9e5b7d40c18a6f2e9b0d4c7a1f8e3b5c62 ftc-helper-lib (v0.16.0)`. Read the tag in brackets. ## Update: the Update library button This is the easiest way. It needs git on the command line: `git --version` in the Terminal must print a version. If it does not, read [git is not recognized](https://crossbotics.com/ftc-helper/docs/troubleshooting/#autonomous-choice-and-git-problems). 1. Commit and push your own work first. **Why:** you can then tell your changes apart from the update. 2. In the list next to the green Run button, pick **Update library**, then click Run. If it is not in the list, close the project and open it again ([the buttons](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/#the-simulator-buttons-you-do-nothing)). 3. It gets the version list from GitHub, switches the `ftc-helper-lib` folder to the newest version, and shows **What changed** (the CHANGELOG parts since your version). Read it: a version can ask you to change a line in your code. 4. Sync (the elephant button), build (the hammer), and fix what the notes say. 5. Do the [checks after an update](#after-an-update-check-everything). 6. Commit the change (`ftc-helper-lib v0.20.2`, for example: the Run window says the exact text). Push only when the checks pass. It commits nothing by itself, and it stops when someone has changed files inside `ftc-helper-lib`. **A specific version, or back to the old one:** open **Run > Edit Configurations**, pick **Update library**, and add `-PlibVersion=v0.20.1` after `updateLibrary` in the **Run** box. **How you know a version is out:** the **Simulator** button checks once a day. When a newer version is out, the Run window and the simulator page (under the Driver Hub) say so: `ftc-helper-lib v0.20.2 is out (this project has v0.20.1)`. It updates nothing. (Offline, it says nothing.) ## Update: the command line Commit and push your own work first, so you can tell your changes apart from the update. **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash cd ftc-helper-lib git fetch --tags git tag --sort=-v:refname ``` The last line lists the versions, newest first (press **q** if the list does not end by itself). Pick the newest one, for example `v0.17.0`, and switch to it. **Where:** the same Terminal tab, now in the `ftc-helper-lib` folder (after the `cd ftc-helper-lib` line). ```bash git checkout v0.17.0 cd .. git add ftc-helper-lib git commit -m "ftc-helper-lib v0.17.0" ``` What the lines do: switch the library to `v0.17.0`, go back to the project folder, and commit the choice. Git may say `You are in 'detached HEAD' state`: that is normal for a submodule on a version tag. Then do the [checks after an update](#after-an-update-check-everything). Push only when they pass. **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash git push ``` **For the newest code instead of a released version:** in the project folder, `git submodule update --remote ftc-helper-lib` gets the newest `main` of the library, with the "Unreleased" changes. Use it to try a fix you are waiting for, never before an event. ## Update: GitHub Desktop GitHub Desktop has no button to change a submodule's version, so you type a few lines in a terminal it opens for you. Those lines need git on the command line. On Windows, GitHub Desktop does not give you command-line git: `git --version` must print a version first ([git is not recognized](https://crossbotics.com/ftc-helper/docs/troubleshooting/#autonomous-choice-and-git-problems)). 1. Commit and push your own work first (**Commit to main**, **Push origin**). 2. Click **Repository > Open in Terminal** (Windows: **Repository > Open in Command Prompt**, or the name of your shell, like Git Bash). A terminal opens in the robot project folder. 3. Type these lines. Use the newest version instead of `v0.17.0`: after the `git fetch --tags` line, `git tag --sort=-v:refname` lists them, newest first. **Where:** that terminal, in the robot project folder. ```bash cd ftc-helper-lib git fetch --tags git checkout v0.17.0 cd .. ``` 4. Back in GitHub Desktop, the **Changes** tab shows `ftc-helper-lib` as changed (a submodule change). Type `ftc-helper-lib v0.17.0` in **Summary** and click **Commit to main**. 5. Do the [checks after an update](#after-an-update-check-everything), then **Push origin**. ## After an update: check everything Do these in order. Each one catches a different kind of problem. 1. **Sync Gradle:** click **Sync Now** in the yellow bar, or **File > Sync Project with Gradle Files**. 2. **Build:** click **Build > Make Project** (the hammer icon). When a red error names a library method, look for it in the CHANGELOG's **Changed** list. That list gives the new name or the new way. 3. **Run your tests** (your saved simulator tests in `simulator/scenarios/`). They run the same checks as last time, so they show what changed. In Android Studio: pick **Simulator tests** in the list next to the green Run button, and click Run. Or type the command. **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash ./gradlew :sim:scenario ``` To run one file: `./gradlew :sim:scenario -Pfile=../simulator/scenarios/main-teleop.sim`. The command first remakes the simulator robot file from `Robot.java` (the robot file format can change with the library). With no tests yet, run each autonomous in the simulator by hand (the **Simulator** button, or `./gradlew :sim:run`) and read its report. Or record a test ([Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/)). 4. **New simulator buttons:** a new library version can bring new ones. The Gradle sync after the update adds the ones you do not have yet (it never replaces yours). 5. **Install the app on the robot** (the green Run button, with the Control Hub connected). 6. **Test on the robot**, on blocks first: every button of TeleOp, then each autonomous at low power (PRACTICE profile), then at match power. Test the parts on your list from the CHANGELOG first. 7. **Commit and push.** Now the team has the new version. Tell them, with the version number. ## After a teammate updates it `git pull` gets their commit, but your `ftc-helper-lib` folder still has the old files until you run this command. **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash git submodule update ``` (GitHub Desktop does this by itself when it pulls.) If `git status` shows `modified: ftc-helper-lib (new commits)` and you did not mean to change it, this command also puts it back to the version the project expects. ## When not to update - **The week before an event.** Use the version you tested. **Why:** a change you have not tested can break the robot when there is no time to fix it. Write the version in your event checklist. - **During an event.** Do not update, even for a fix you read about. Wait until you are home, unless the robot cannot play without it. - **In the middle of a big change of your own.** Finish and commit your work first, so you know which change caused a problem. **The best time:** right after an event, or at the start of a practice week, with time to test. ## Use a specific version Each release has a tag like `v0.16.0`. To use exactly that one (also to go back to an older one), type these lines. **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash cd ftc-helper-lib git fetch --tags git checkout v0.16.0 cd .. git add ftc-helper-lib git commit -m "Use ftc-helper-lib v0.16.0" ``` What the lines do: go into the library folder, download the list of versions, switch to `v0.16.0`, go back to the project folder, and commit the choice. Push it, and the team gets it too. ## Go back to the old version When the new version causes a problem and there is no time to fix it, go back. You lose nothing: the update is only a commit. **Not pushed yet:** switch the library back to the version you had (`git submodule status` before the update said which). **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash cd ftc-helper-lib git checkout v0.16.0 cd .. git add ftc-helper-lib git commit -m "Back to ftc-helper-lib v0.16.0" ``` **Already pushed:** undo the update commit with a revert (a new commit that does the opposite). Then put the library folder where the project now says. **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash git log --oneline git revert --no-edit 3f2c1a9 git submodule update git push ``` `3f2c1a9` stands for the id of the update commit in the `git log` list (press **q** to leave the list). In GitHub Desktop: open the **History** tab, right-click the update commit, and click **Revert Changes in Commit**. Then click **Push origin**. Then tell the library's authors what broke ([an issue](https://github.com/crossbotics/ftc-helper-lib/issues/new/choose)): the version, what you did, and what you saw. ## A new FTC SDK version The FTC SDK (the code from FIRST that every robot app is built on) changes every season (and sometimes during one). We build the library against one SDK version (now **12.0.0**, the 2026-27 release, set in `library/build.gradle`). Your robot app always uses the SDK version in YOUR project's `build.dependencies.gradle`. The library uses 12.0.0 only to compile, and brings no SDK of its own. SDK 12.0 changed AprilTag detections (single tags and "clusters"). We wrote the library's `WebcamTags` for the SDK 12 types, so its vision classes need SDK 12 or newer. Your own AprilTag code may need the fix in the SDK's release notes. So after you update the SDK: 1. Build. If it builds and works, you are done. 2. If the library does not build with the new SDK, check for a newer library version ([update](#update-the-command-line)). 3. If it is still broken, report it, or fix it: [Contributing](https://crossbotics.com/ftc-helper/docs/contributing/). ## Change the library from inside the robot project You can edit the library's files right in Android Studio. But those changes are inside the submodule, so they need their own commit and push to the library repository. Follow [Contributing](https://crossbotics.com/ftc-helper/docs/contributing/). If you change it only in your robot project, the next update loses the change. --- # Add to your robot URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/ **Why one at a time:** when only one part is new, a problem can only be in that part. Every page has the same steps: 1. **What it is:** what the part does, and what it needs on the robot. 2. **Add it to the five files:** the lines for `Robot.java`, `Tunables.java`, `Controls.java`, and `Actions.java` and the autos when you need them. 3. **Find its numbers:** the finder that measures them. 4. **Check it, then tune it:** a short test on the robot, then the numbers to tune. 5. **Look it up:** the reference page with every setting. | Part | Page | | --- | --- | | Lift: a slide that goes to named heights | [Add a lift](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/) | | Arm: a motor that turns to named angles | [Add an arm](https://crossbotics.com/ftc-helper/docs/add-to-robot/02-arm/) | | Claw, wrist and other servo parts | [Add a claw and other servo parts](https://crossbotics.com/ftc-helper/docs/add-to-robot/03-claw/) | | Intake: takes pieces in | [Add an intake](https://crossbotics.com/ftc-helper/docs/add-to-robot/04-intake/) | | Launcher: a flywheel that shoots pieces | [Add a launcher](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/) | | Turret: turns the launcher | [Add a turret](https://crossbotics.com/ftc-helper/docs/add-to-robot/06-turret/) | | Camera: sees the goal, to aim | [Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/) | | Lights: show the drivers what the robot does | [Add lights](https://crossbotics.com/ftc-helper/docs/add-to-robot/08-lights/) | | Odometry: knows where the robot is on the field | [Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/) | | Lift, arm and claw in one move, with a safety rule | [Make parts work together](https://crossbotics.com/ftc-helper/docs/add-to-robot/10-parts-together/) | | Pedro paths: drive smooth paths in autos (a Building autos page) | [Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/) | --- **Next:** [Add a lift](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/). --- # From Blocks to Java: where each block went URL: https://crossbotics.com/ftc-helper/docs/blocks-to-java/ **Before this:** [Set up](https://crossbotics.com/ftc-helper/docs/setup/) (if you are new to Android Studio). Read this page **before** [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/): it gives you the five files this page talks about. **The reading order:** [Set up](https://crossbotics.com/ftc-helper/docs/setup/), [Read Java and make your first edit](https://crossbotics.com/ftc-helper/docs/start-from-zero/), then this page, then Pick your start, then [The five files](https://crossbotics.com/ftc-helper/docs/five-files/), then [Add to your robot](https://crossbotics.com/ftc-helper/docs/add-to-robot/) (only the parts your robot needs). ## The key idea: you never write the loop In Scratch, a game is a `forever` loop: every time around, it checks the keys and moves the sprite. A robot program is the same inside: a **loop** that runs many times a second. Each time around (each "loop"), it reads the gamepads, tells every motor what to do, and updates the Driver Station. **With this library, you do not write that loop.** The library runs it for you. Your job is different: 1. `buttons(...)` in `Controls.java` runs **once**, at INIT. 2. Each line in it **plugs a job into a button**, like snapping a script under a `when [space] key pressed` hat block. Nothing runs yet. 3. After ▶ (start on the Driver Hub), the library's loop watches the buttons and **runs the jobs** at the right moment. ```java @Override protected void buttons(Robot robot, Pad g1, Pad g2) { g2.a.press(robot.claw::open).says("open claw"); // when G2 A pressed: open the claw g2.rt.hold(robot.intake::in, robot.intake::stop); // while G2 RT held: in; let go: stop } ``` (The claw line needs a claw in `Robot.java`. The quickstart example robot has only an intake.) **Why it is built this way:** in one loop, many jobs share the robot. If one job stops to wait, the whole robot stops: no driving, no other button. So **a job must never wait.** Waits happen only inside an **Action** (a list of steps that runs a little every loop, [Actions.java](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/)) and in **autonomous steps** ([The autos](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/)). ## The map: block to Java | Block | In Java with this library | Where | | --- | --- | --- | | `forever` / `repeat until` / `while opModeIsActive()` | Written for you: the library's loop. Of your lines, only `hold(...)`, sticks' `use(...)`, `rumbleWhen(...)` and `show(...)` run every loop. | inside `ControlMap` (the library) | | `when green flag clicked` (the match starts) | `atStart(() -> Actions.deployIntake(this));` | `Robot.java`, in `define()` | | `when [key] pressed` | `g2.a.press(job);` | `Controls.java`, in `buttons(...)` | | `when [key] released` | `g2.a.release(job);` | `Controls.java` | | `if then ... else stop` (while held) | `g2.rt.hold(robot.intake::in, robot.intake::stop);` | `Controls.java` | | on / off switch (toggle) | `g2.b.toggle(robot.claw);` | `Controls.java` | | `wait 0.5 seconds` (in TeleOp) | **Not** `sleep(500)`. In an Action: `Action.named("Spit out").then(r.intake::out).waitSeconds(0.5).then(r.intake::stop)` | `Actions.java` | | `wait until <...>` | `.waitUntil("lift at the top", r.lift::isAtTarget, 2.0)` (2.0 = give up after 2 s) | `Actions.java` | | a stack of blocks, run in order | An Action: `Action.named("...").then(a).waitSeconds(t).then(b)`. In an autonomous: `s.start(...).move(...).action(...)` | `Actions.java`, `autos/` | | `define my block` (a custom block) | `public static Action spitOut(Robot r) { return ...; }` | `Actions.java` | | the slot inside a C-block | a **lambda** `() -> { a(); b(); }`, or a **method reference** `robot.intake::out` | anywhere a job goes | | `set [maxPower] to 0.4` (a number variable) | `public static double maxPower = 0.4;` read as `Tunables.Drive.maxPower` | `Tunables.java` | | `set motor power` / `run motor` | `robot.intake.in()`, `robot.lift.goTo("high")`. The drive motors need no code. | jobs and Actions | | `joystick` (a reporter block) | `g2.leftStickY.use(robot.lift::manual);` (the stick's value, -1 to 1, every loop) | `Controls.java` | | `if then rumble` | `g2.rumbleWhen(robot.intake::isRunning);` (a buzz each time it becomes true) | `Controls.java` | | `say` / `show variable` | `show("Lift ticks", robot.lift::position);` (the value on the Driver Station, every loop) | `Controls.java`, in `buttons(...)` | | `x position` / `y position` / `direction` (where am I?) | `robot.pose()`: `.x`, `.y` (inches) and `.headingDeg`, from the odometry; show it with `show("Where", robot::pose);` ([Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/)) | `Controls.java`, autonomous | | `go to x: y:` | `s.driveTo("To the goal", -30, -30, 45, 0.6)` (x, y, heading, power), with odometry | `autos/` | | `if then ...` | not an `if`. Pick one: `g2.rumbleWhen(...)` (a buzz when it becomes true), `.waitUntil(...)` in an Action (wait for it, then go on), or a `hold(...)` (runs while a button is held) | `Controls.java`, `Actions.java` | | `if ... else` inside an action | **not yet** in an Action. Use two actions on two buttons, one for each case | `Actions.java`, `Controls.java` | | `repeat 3 times` | a `for` loop that adds the steps to the Action 3 times, when the action is made ([cookbook: repeat](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-repeat-steps-several-times)); or press the button again (it runs the action again) | `Actions.java` | | `change [count] by 1` | a variable (a **field**) in `Controls.java`, changed by a button job: see [Count with a button](#count-with-a-button) | `Controls.java` | | `broadcast` / `when I receive` | not needed: a button job or an Action calls the part's method itself (`robot.intake.in()`) | | | `stop all` | Tap gamepad 1 **BACK** (pause; tap again to go on), or **STOP** on the Driver Station. | the drive team | Notes on the table: - **Autonomous steps DO run in order and wait**, like a stack of blocks. `s.move(...)` finishes before the next step starts. **Why the difference:** in an autonomous, no driver is waiting for a button. The library still keeps every part working while a step waits. - **Sticks give numbers.** Up and right are `+`, from -1 to 1. `robot.lift::manual` gets that number every loop. - **You can change a number in `Tunables.java` live:** in the PRACTICE profile, hold GUIDE for 1 s to open the tuning menu ([Tunables.java](https://crossbotics.com/ftc-helper/docs/five-files/02-tunables-java/)). Then copy the good value back into `Tunables.java`. - `atStart(...)` comes from the example robot [`flywheelbot/Robot.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/flywheelbot/Robot.java): its `deployIntake` Action drops the intake into place once, right after ▶ (never in INIT). - `show(...)` goes inside `buttons(...)`, like `rumbleWhen`, as a line of its own. It is in the TeleOp (`Controls.java`) only. ## FTC Blocks: the robot blocks The FTC Blocks editor has blocks for the robot itself. Each one has a place in Java: | FTC Blocks block | In Java with this library | Where | | --- | --- | --- | | `waitForStart` | nothing: the library waits for ▶. Something right after ▶: `atStart(...)` ([cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-run-an-action-when-the-opmode-starts)) | `Robot.java`, in `define()` | | `repeat while opModeIsActive` | nothing: the library's loop | | | `telemetry.addData("key", value)` and `telemetry.update` | `show("Lift ticks", robot.lift::position);` once, in `buttons(...)`. The library shows it every loop as `Lift ticks : 350`. You need no `update` | `Controls.java` | | `gamepad1.left_stick_y` (and the other sticks) | driving is built in. For your own part: `g2.leftStickY.use(robot.lift::manual);` | `Controls.java` | | `if gamepad2.y then ...` | `g2.y.press(...)`, one line, once ([Controls.java](https://crossbotics.com/ftc-helper/docs/five-files/03-controls-java/)) | `Controls.java` | | `set servo.Position to 0.75` | a named position in `Tunables.java` (`open = 0.20, closed = 0.75` in `Tunables.Claw`), then `robot.claw.close()`; any servo: `robot.intakeDeploy.goTo("deployed")` | `Tunables.java`, then `Controls.java` or `Actions.java` | | `set motor.Direction to REVERSE` | drive motors: `.reversed("front_left", "back_left")` in the `drive(...)` line; a part: `.reversed()` on its line | `Robot.java` | | `set motor.Power to 1` | a command of the part: `robot.intake.in()`, `robot.lift.goTo("high")` | `Controls.java`, `Actions.java` | | `sleep 500` | `.waitSeconds(0.5)` in an Action or an autonomous | `Actions.java`, `autos/` | | `if` the drivers chose something before the match | `onlyIf(...)` with a menu choice ([cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-let-the-drivers-choose-before-the-match)) | an autonomous | **The stick-up sign.** In FTC Blocks (and in the plain FTC SDK) a stick pushed **up** gives a **negative** number. So Blocks programs put a "negative" block (or `-1 *`) in front of `gamepad1.left_stick_y`. **Here the sign is already fixed:** every stick value the library hands you (`use(...)`, the driving) is **+ when pushed up or right**. Do not add the minus, or the part moves the wrong way. (You need the minus only when you read `gamepad1.left_stick_y` yourself, outside the library: [signs and units](https://crossbotics.com/ftc-helper/docs/conventions/#gamepad-sticks).) ## Never sleep() or a while loop in a button job This compiles, but it is wrong: ```java // WRONG: the whole robot freezes for half a second g2.dpadLeft.press(() -> { robot.intake.out(); sleep(500); robot.intake.stop(); }); ``` `sleep(500)` stops the library's loop for 0.5 s. During that time, nothing else runs: no driving, no other button, no safety checks. A `while (...) { }` loop in a job does the same, maybe forever. The Driver Station then shows a warning like this: ```text G2:DPAD_LEFT button job took 512 ms: the whole robot stopped that long. No sleep() or while loop in a button job: use an Action with waitSeconds (docs: Actions.java) ``` (The warning starts with the button, `G2:DPAD_LEFT` here. For a job on a gesture or a "buzz when", it starts with `a button job took ...` instead.) Do this instead (the quickstart example's `spitOut` in `Actions.java`): ```java public static Action spitOut(Robot r) { return Action.named("Spit out") .then(r.intake::out) .waitSeconds(0.5) .then(r.intake::stop); } ``` In `Controls.java`, add `g2.dpadLeft.press(Actions.spitOut(robot)).says("spit out");`. **Why it works:** the Action waits "inside itself". Each loop it checks the time and lets the loop go on, so the robot keeps driving. ## Never an if or while in buttons() `buttons(...)` runs **once**, at INIT. So an `if` or a `while` in it is wrong too: ```java // WRONG: checked once, at INIT, and never again if (gamepad2.x) robot.intake.in(); // WRONG: INIT never ends; the robot never starts while (true) { ... } ``` - **An `if`** in `buttons(...)` checks the button **once**, at INIT, when nobody is pressing it, and never again. Nothing happens in the match. - **A `while` loop** in `buttons(...)` never lets INIT finish: the robot is stuck in INIT. - **Do not read `gamepad2.x` (or `gamepad1...`) yourself** in `buttons(...)`. Use the `g1`/`g2` buttons: `g2.x.press(robot.intake::in);`. **Why:** the library checks those buttons every loop for you. What to use instead of an `if`: | You want | Use | | --- | --- | | do something when a button is pressed | `g2.x.press(job)` | | do something while a button is held | `g2.x.hold(job, stopJob)` | | a buzz when a sensor becomes true | `g2.rumbleWhen(robot.intake::isRunning)` | | wait for something, then go on | `.waitUntil("lift at the top", r.lift::isAtTarget, 2.0)` in an Action | | "if A then this, else that" | two actions on two buttons (an Action has no `if`/`else` yet) | ## Count with a button A Blocks `change [count] by 1` is a **field** in Java: a variable that belongs to the whole file, so it keeps its value between loops. Put it in `Controls.java`, inside the class, above `buttons(...)`: ```java private int count = 0; // a whole number, starts at 0; private = only this file uses it ``` In `buttons(...)`, add a button job that changes it, and a `show(...)` line to see it: ```java g2.x.press(() -> count++); // X: count goes up by 1 (count++ means "count = count + 1") show("Count", () -> count); // the Driver Station shows "Count : 3" ``` **Why a field, not a variable inside `buttons(...)`:** a variable made inside `buttons(...)` is gone when it ends (at INIT), and Java does not let a job change it. A field stays as long as the TeleOp runs. **Check it in a simulator test** ([Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/)): a `show(...)` line is on the screen as `Label : value`. So after one press of X, check `expect screen has "Count : 1"`. Check a `true`/`false` value the same way: `expect screen has "Intake on : true"` ([Scenario files](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/)). ## Java punctuation: a short guide - **`;`** ends a statement (one command), like a period. Every line inside `buttons(...)` ends with one. - **A chain goes on over several lines.** A line that starts with `.` continues the line above it: ```java return Action.named("Spit out") // no ; here: the statement goes on .then(r.intake::out) .waitSeconds(0.5) .then(r.intake::stop); // the ; is at the very end ``` - **`{ }`** hold a group of lines together, like the inside of a C-block. Every `{` has its own `}`. - **`"quotes"`** are text, used as it is: a name on the Driver Station, a motor name, a lift height (`"high"`). Words without quotes are names in the code (`robot`, `intake`, `goTo`). - **`return`** hands a result back. `spitOut` builds an Action and `return`s it, so the button can use it. - **`r` and `robot`:** these are only names. A method names its inputs in its first line: `spitOut(Robot r)` calls its robot `r`; `buttons(Robot robot, Pad g1, Pad g2)` calls it `robot`. It is the same robot. **Why short `r`:** Actions use it on every line. - **`this`** means "this object, the one this code is in". In `Robot.java`, `this` is the robot, so `atStart(() -> Actions.deployIntake(this))` hands the robot to the Action. - **`() ->`** starts a lambda: code you hand over now, to run later. **`::`** is a method reference: `robot.intake::out` is the short way to write `() -> robot.intake.out()`. - **`a ? b : c`** picks one of two: if `a` is true, `b`, else `c`. Like the Blocks "if-then-else" value block. `deployAtStart ? Actions.deployIntake(this) : Action.named("Stay folded")` is one Action or the other. ## Next - [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/), if you have not done it yet: get the five files and drive. Then [The five files](https://crossbotics.com/ftc-helper/docs/five-files/). - [Controls.java](https://crossbotics.com/ftc-helper/docs/five-files/03-controls-java/): every kind of button job. - [Actions.java](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/): steps that wait, safely. - [Controls](https://crossbotics.com/ftc-helper/docs/controls/): every way a button can work. --- # Commenting style URL: https://crossbotics.com/ftc-helper/docs/commenting-style/ **Write in plain, everyday, non-technical language.** Say "the robot waits here" instead of "this blocks the thread". Say "a number that can change" instead of "a mutable field". When you cannot avoid a technical word (encoder, PID, servo), explain it in a few everyday words right there, or point to the page that explains it. **Point to other files and docs** when they explain more: "See docs/modules/drive.md", "Tutorial 07 explains PID step by step", "The signs are in docs/conventions.md", "This is the same idea as SafeMotor (safety/SafeMotor.java)". ## The rules 1. **Explain WHY, not only WHAT.** `// clamp the power` says what. `// clamp: a motor only accepts -1..1, and NaN (a bad sensor reading) would make it jump` says why. 2. **Plain, short, non-technical sentences.** Everyday words. Explain any technical word the first time in everyday terms (PID, encoder, tick, lambda, edge...), or link to the doc that explains it. 3. **One comment per idea**, on the line above the code it explains (or at the end of a short line). 4. **Units and signs** wherever a number appears: ticks, inches, degrees, seconds, milliseconds; "positive = left (counterclockwise)". 5. **Always write down safety reasons:** why a motor is stopped, why a limit exists, why we never wait. 6. **Java ideas** that a beginner would not know get a short, everyday-language note the first time they appear in a file (for example "`() -> ...` is a small piece of code we hand over to run later"). These ideas are: lambda `() -> ...`, method reference `lift::stepUp`, ternary `a ? b : c`, `final`, `static`, `interface`, `@Override`, `try/finally`, `synchronized`, `volatile`, generics ``, enum. In examples and tutorial programs (rule 9) that note goes in the docs next to the code (a code annotation or the text), not in the file. 7. **Do not comment the obvious.** `i++` and simple getters need nothing. A comment that only repeats the code is noise. 8. **Section headers** in long classes: `// ---- Setup ----`, `// ---- Every loop ----`. 9. **Examples and tutorial programs keep only the essential comments** (decided 2026-10-23): what a line is, units, "= the name in the robot configuration", "measure this", a safety warning, and a `more: https://crossbotics.com/...` link where it helps. At most 3 `//` lines in a row and 8 lines of `/** */` (`tools/check_docs.py` checks it). **Why:** teams copy these files, and long explanations get in the way of their own code. The WHY (rules 1 and 6) goes in the docs, next to the code that shows it: as a [code annotation](#code-annotations-in-the-docs) or in the text. 10. **Keep comments true.** When code changes, its comments change in the same commit. 11. **Say it once** (docs code boxes). Each part has its own job: - the **code comment** says WHAT the line is, in one line; - the **(+) note** ([code annotation](#code-annotations-in-the-docs)) says WHY, for that one line only: at most about 3 sentences, and no numbers the text or a table already gives; - the **text under the box** says what the step does and what to check. Never write the same sentence twice (in the comment and the note, or the note and the text). Explain a note that every recipe would repeat (what `.part(...)` does) once, where it first appears. ## Code annotations in the docs A docs code box can explain a line without a long comment in the code. Add a marker `(1)!` at the end of the line's `//` comment (or `// (1)!` alone after the code). Then put a numbered list right under the box, one item per marker, in order: ````text ```java title="Robot.java" lift = add(Lift.slide("lift").part("gobilda-5203-435")); // the lift (1)! ``` 1. "lift" is the motor's name in the robot configuration. Its numbers: `Tunables.Lift`. ```` On crossbotics.com each marker becomes a small (+) button that opens its item. The site hides the list itself, and the Copy button copies the code without the markers. On GitHub the marker and the list show as text. The markers are only in the docs: `tools/check_docs.py` takes them out before it compares a box with its Java file. `--fix-cookbook` keeps them on the lines that did not change. ## Format - Javadoc (`/** ... */`) on every public class and method: what it does, parameters (with units and ranges), what it returns, and a short example when useful. - `//` comments inside methods for the steps and the reasons. - Line length: about 110 characters. --- # Contributing: add or change something in the library URL: https://crossbotics.com/ftc-helper/docs/contributing/ ## The six steps (for every change) 1. **Code** in `library/src/main/java/com/crossbotics/ftchelper//`, commented for novice programmers: plain everyday words, the WHY, and pointers to the docs ([Commenting style](https://crossbotics.com/ftc-helper/docs/commenting-style/)). Doc pages follow the [Writing style](https://crossbotics.com/ftc-helper/docs/writing-style/). 2. **Javadoc** on every public class and method: what it does, each parameter (with its unit and range), what it returns, and a short example. Plain words. 3. **Test** in `library/src/test/java/...` for any logic (math, timing, button edges, limits). A unit test cannot call hardware. So put the logic in a plain class (like `SoftLimits` for `SafeMotor`) and test that. 4. **Docs:** update the module page in `docs/modules/` (the method table and an example), and `docs/troubleshooting.md` if it fixes a common problem. 5. **Tutorials, guides and diagrams:** if the change affects how the library is USED, update every tutorial that uses it (both the page in `docs/tutorials/` and its program in `examples/.../tutorials/`). A new feature that students will use needs a place in a tutorial. Add a section to the closest one, or a new tutorial with its own program (and a row in `docs/tutorials/README.md`). Update the guide that covers it (`docs/guides/`), and any diagram that shows it (Mermaid blocks in the pages, SVGs in `docs/images/`). A new module gets a row in the README table and a page in `docs/modules/`. A new docs section (a folder in `docs/`), a moved page or a new rule for teams' code also goes in the ftc-helper skill (`skills/ftc-helper/SKILL.md`). Teams' AI agents use it as their map of the docs. 6. **CHANGELOG.md:** add a line under "Unreleased": Added / Changed / Fixed. Start each entry with one plain sentence (what it does for a team), then the details. The release's "What's new" comes from those sentences. A change is not done until all six are done. ### How the tutorials stay correct - Every tutorial has a complete program in `examples/src/main/java/.../examples/tutorials/`. The build compiles them, so a library change that breaks a tutorial breaks the build. - Tutorial 13's tests (`examples/src/test/...`) run with the build too. - `tools/check_docs.py` fails if a link or heading link is broken, if a public library class is missing from the module pages, or if a tutorial program is not mentioned in a tutorial page. - The [cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/) is the exception: every java block in it is a copy of a marked region (`// recipe: name` ... `// end recipe`) in `examples/.../cookbook/`. `tools/check_docs.py` fails if they differ. Change the Java file, then run `python3 tools/check_docs.py --fix-cookbook` to copy the regions into the page. The simulator test `CookbookTest` INITs and runs every cookbook OpMode. - `tools/check_tunables.py` reads every `Tunables.java` field the robot package reads (`t.number`, `t.flag`, `t.tunable`, ...) and fails if [the Tunables reference](https://crossbotics.com/ftc-helper/docs/reference/tunables/) misses one, names one the code no longer reads, or has a wrong default, "In tuning menu" or REQUIRED cell. It also checks that the example robots' `Tunables.java` files (and the one `:sim:newRobot` writes) use only fields their parts read. It checks that `TunableFields.java` (the lists INIT uses to stop on a misspelled field) lists exactly the fields each part reads. A new number in a module: add its row to the reference and its name to `TunableFields.java`. - `tools/check_docs.py` also checks the skills for teams' AI agents (`skills/`): every path they name must exist, and the ftc-helper skill must list every `docs/` folder. The website makes its docs files for AI chats (`llms.txt`) from the docs at every build, so they need nothing by hand. - The build does not compile code snippets IN the tutorial pages. When you change a program, search its tutorial page for the same lines and update them. - Before a release, read the changed tutorials once from top to bottom as a student would. ## Style - Java 8 (no `var`, no `List.of`). Same as the FTC SDK. - Signs and units from [Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/). Put the sign in the name when it can be confused: `turnClockwise`, `headingCcwDeg`, `distanceIn`, `timeoutMs`. - Nothing in the library may block TeleOp ([Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/)): no `sleep()`, no waiting loops, except in clearly autonomous-only classes like `AutoDrive` (which always check `opModeIsActive()`, have a timeout, and stop motors in `finally`). - Hardware setup methods leave motors at power 0. - Parts stay general: any team, any season. A robot that needs something new gets the general block that is missing, not its own mechanism. Season knowledge (the field, the rules, piece and goal names, scoring) may be in the library as season definitions, kept apart and updated each season. A team's own start spots, routes, positions and tuned numbers belong in TeamCode. - In the docs, text the robot or a tool SHOWS (a Driver Station message, a warning, a Gradle or git error) goes in `...`. Text you TYPE (code, names, commands) stays in backticks. The site shows the two differently, so a student can tell "what you see" from "what you write". Inside ``, write `<` and `&` for `<` and `&`. - Classes that use time take a clock in a second constructor (`LongSupplier clockNanos`) so tests can control time. See `PidController` or `LoopTimer`. A default clock is `Time::nanos` (core), so a test's `PretendClock` moves every part at once (most parts do). Keep `System.nanoTime` only where the time is compared with one from the SDK (camera picture times) or measures the loop itself. ## Build and test You need JDK 17 or newer and the Android SDK. Android Studio installs both. You also need Node.js for the `check_builder.mjs` line. **Where:** a terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :library:testDebugUnitTest :examples:assembleDebug :examples:testDebugUnitTest ./gradlew :sim:testDebugUnitTest :pedro:testDebugUnitTest python3 tools/check_docs.py # links, docs for every class, the Cookbook's code python3 tools/parts_page.py --check # the parts page matches sim/parts/parts.json python3 tools/check_blocking.py # nothing in the loop waits python3 tools/check_tunables.py # every Tunables field the code reads is documented node tools/check_builder.mjs # the simulator's auto builder page code python3 tools/check_tests.py # the community test list and testing/catalogue.json ``` These lines run every test (the library's, the examples', the simulator's and the Pedro module's). They build the examples and every tutorial program, and check the docs, the parts page, the auto builder page and the community test list. All must pass before you push. GitHub runs the same checks on every push (`.github/workflows/build.yml`), except the `:pedro` tests. If Gradle cannot find the Android SDK, make a file `local.properties` in this folder with the line `sdk.dir=/path/to/Android/sdk`. Android Studio shows the path in **Settings > Languages & Frameworks > Android SDK**. ## Working from inside a robot project The library is a submodule, so you can edit it from the robot project in Android Studio and test it on the robot right away. To save the change, type these lines. **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash cd ftc-helper-lib git checkout -b my-change # the submodule is usually on a "detached" commit; make a branch git add -A git commit -m "Add ... to SafeMotor" git push -u origin my-change ``` Then open a pull request on GitHub for the library, and ask the programming lead to review it. After someone merges it, update the robot project to the new version ([Keep it up to date](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/)). ## Help us test, and add a test If you are not changing code, testing helps as much. The test list is in [`testing/`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/testing/README.md): small tests with steps, a pass rule and what to write down. Teams pick the ones that fit their robot on https://crossbotics.com/ftc-helper/testing/ and send the result with the "Test report" form. To add a test: copy a file in `testing/tests/`, change it, and run `python3 tools/check_tests.py --fix` ([how](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/testing/README.md#add-a-test)). ## The simulator: notes for maintainers Teams use the simulator from [Simulator](https://crossbotics.com/ftc-helper/docs/simulator/). These notes are for people who change it. ### Fields: one file per season `sim/fields/.json` holds a season's field: solid elements (the robot bumps into them), floor zones and tape lines, things overhead, and the AprilTags with their position and the way they face. The robot file picks one (`field = biobuzz-2026`). The page draws the field. When the robot bumps into an element, the robot turns red and the panel names the element. When the robot file loads, the simulator refuses a start position that overlaps a wall or an element. A new season is a new file. A script made the BIOBUZZ file from the official field CAD. The script is not in this library yet (ask the maintainer). The same kind of script works for the next CAD. Game pieces in the field file: `pieceTypes` (name, `diameterIn`, `massG`, `color`, `bounce`), `pieces` (where each starts: type, x, y, z), `goals` (name, x, y, the opening's height `z`, `radiusIn`) and `preload` (how many of each type a robot starts with). A season's rules go in `sim/fields/.rules.json`, next to the field file (see [Game rules and the score](https://crossbotics.com/ftc-helper/docs/guides/how-the-simulator-works/#game-rules-and-the-score)). The rules are the points, match times, which pieces and zones are each alliance's, FLOWER heights, the HIVE's tip time and the clean-shot rules. Someone types them from the manual, section by section, so a re-made field file never loses them. For a field file given by path, the simulator looks for the rules file in the same folder, with the same name. The 3D view uses a field's 3D model: a `.glb` file in the same frame, in inches, z up. It sits next to the field file, with the same name. `sim/fields/biobuzz-2026.glb` is BIOBUZZ's, made from FIRST's official field CAD, and every robot file with `field = biobuzz-2026` uses it. A robot file can name another model with `field.model` (a path from the robot file). Without a model, the 3D view builds the field from the field file. ### The auto builder's shared files **Shared with the web builder.** The plan, its checks, the Java, the scenario, the start note, the setup card and the auto sheet come from the same files as the web builder: `pathcore.js`, `stepscore.js`, `mapdraw.js` and `setupcard.js` in `sim/src/test/resources/sim/builder/`. **The library is their source**: change them here, and release them. The web site's `scripts/sync-path-builder.mjs` copies them, with the field file, from the release. `node tools/check_builder.mjs` does three checks: - The Java and the scenario for a set of plans must be letter for letter what the shared files wrote when the fixtures were made (`sim/src/test/resources/builder/fixtures.json`; `--write-fixtures sim/src/test/resources/sim/builder` makes them again after an intended change). - It checks the simulator-only part (`simcore.js`). - When it finds a checkout of the site, it fails when the site's copies differ from the release that the site names. The fixtures are a snapshot: they find a change, but not a first answer that was wrong. So one small plan has its numbers worked out by hand. The site copies these files and the field from that release, never from your working folder. ### The page's helpers The page's helpers (gliding between updates, the striped ball, the labels) are in `sim/.../simview.js`. It is a small file with no other library in it, so another page (like a team's own shot simulator) can load it too. ### Automatic tests `sim/src/test/.../FinderSafetyTest.java` runs whole OpModes with scripted button presses, on every push. For example, it checks that help stops the motors, and that a stick held through help does not count. It checks that the Drive Tuner's push test finds the real wheel size. It also runs every example with the sticks and a trigger held, and checks that no motor stays on by itself at STOP. It looks before the simulator switches the motors off. Its first run found a real bug: every finder crashed at INIT in v0.7.2. **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:testDebugUnitTest ``` `SimRecorderTest` plays a recording session the way the page sends it, and saves the test. It replays the test (PASSED), changes the robot (FAILED), updates the test from a measuring run, and replays it (PASSED). `BuiltAutoTest` runs the [auto builder](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/)'s plans with the example robots (a Simple steps plan on goBILDA's starter bot, a Pedro path on the Pedro robot). It checks that they end near the plan. The builder's page code has its own check (Node.js), also on every push: **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash node tools/check_builder.mjs ``` ## When to release - **Once a week:** the code changes made that week go out together in one release, with one set of notes. Until then they collect under "Unreleased" in `CHANGELOG.md`, and the docs site shows them as "Coming in the next release". - **A larger change** (a new tool, a new module) can go out on its own when it is ready. - **An urgent fix** (something that stops teams) goes out at once, as a bug-fix version. **Why:** each release sends an email to every team that watches the releases. Fewer, fuller releases are easier to follow than many small ones. ## Docs fixes between releases A fix to the docs of something already released (a typo, a clearer step, a wrong number) does not need a release. The site builds its docs from the `docs-live` branch: the last release plus these fixes. 1. Make the fix on `main` as usual, in a commit that changes only `docs/` (and `README.md`). 2. Put the same commit on `docs-live`, check it, and push it. **Where:** a terminal, in the `ftc-helper-lib` folder. ```bash git checkout docs-live git cherry-pick python3 tools/check_docs.py git push origin docs-live git checkout main ``` The check matters: a box fixed on `main` can use code that is not released yet. Then the check fails on `docs-live` (`git reset --hard origin/docs-live` drops the pick), and the fix waits for the release. If the cherry-pick stops with a conflict, the page changed on `main` since the release. Run `git cherry-pick --abort`, then make the fix again by hand on `docs-live` (and keep the `main` one). 3. Deploy the site (crossbotics `./scripts/deploy.sh --go`): the pages update, and no email goes out. On GitHub, a push to `docs-live` runs only the docs checks (`tools/check_docs.py`, `tools/check_tests.py`), not the Gradle build: its code already passed as the release. That is the `docs` job in `.github/workflows/build.yml`. GitHub uses the workflow file of the branch it runs on. So a change to that file reaches `docs-live` with the next release, or sooner when you cherry-pick that commit (only the workflow file). Docs for a feature that is not released yet stay on `main` only: teams must not read about something their version does not have. A release moves `docs-live` to the new tag (step 4 of [Releasing a version](#releasing-a-version)). ## Releasing a version The programming lead does this after merging changes. `vX.Y.Z` is the new version, for example `v0.19.0`. `tools/release.py` does the steps and stops at the first problem, so nobody forgets a step. 1. Get the changelog and the test list ready. The script renames "Unreleased" in `CHANGELOG.md` to the new version and today's date, and sets `since:` on the tests that said `since: unreleased`. **Where:** a terminal, in the `ftc-helper-lib` folder. ```bash python3 tools/release.py prepare vX.Y.Z ``` If it stops after it changed files, run `git restore CHANGELOG.md testing/`, fix the problem and run it again. 2. Read the changes, run the checks in `AGENTS.md`, and commit. 3. Write the notes of the **GitHub release** in a file, `notes.md` in the repo's top folder (git ignores it). They have three parts, in this order (the script stops if one is missing): - **What's new:** 3 to 6 lines in plain words, one per new feature, for a student who will not read the rest. Say what it does for the team, not how it is built. - **Plain words in these first two parts.** Write for an FTC student who does not code: short sentences, no class or method names, no file paths. FTC and robot words are fine (AprilTags, INIT, TeleOp, autonomous, servo, odometry, Driver Station): every FTC team knows them. Bold the feature's name at the start of each line. Read it aloud once: if it needs a programmer to understand, rewrite it. - **Before you update:** anything that works differently now (a button, a default, a renamed page or setting), and what to do about it. If nothing changes, say "Nothing old stops working." Then a link to [Keep it up to date](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/). - **Full change list:** that version's CHANGELOG part, pasted as it is. 4. Publish. The script runs the checks that need no Gradle (the Gradle tests are step 2). Then it tags, pushes `main` and the tag together, and makes the GitHub release. It moves `docs-live` to the release, and checks that `docs-live` holds the same files as the tag. `--dry-run` gets the latest from GitHub and runs only the checks. It pushes nothing. **Where:** a terminal, in the `ftc-helper-lib` folder. ```bash python3 tools/release.py publish vX.Y.Z notes.md ``` GitHub checks the tag too: the build fails if the tag has no changelog heading or a test still says `since: unreleased`. The script moves `docs-live` with a merge commit that holds exactly the tag's files. It does not force-push. If publish stops part way, fix the problem and run the same command: it goes on with the steps not done yet. **Why:** a tag alone sends no message. Teams that click **Watch > Custom > Releases** on GitHub get an email for each release. That is how they learn to update ([Keep it up to date](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/#find-out-about-a-new-version)). Version numbers: change the middle number (0.**19**.0) for new features, the last number (0.19.**1**) for bug fixes, and the first number when something old stops working the same way. ## Writing a tutorial Use the same shape as the others, so students always know where to look: 1. **Title, "You will learn", "You need"** (hardware names, earlier tutorials), links to the full program and the module reference. 2. **Numbered sections** that build the program step by step. Each one: why, the code, what each line does. Explain any new Java idea the first time it appears. 3. **Run it:** what the student should see, as a checklist. 4. **If something goes wrong:** a table of problem -> fix. 5. **Try this:** 2-4 small exercises with hints. 6. **Next:** the next tutorial. Write for a high-school student: short sentences, plain words, the "why" before the "how". Safety first: low power, wheels off the ground, hard stops. ## Ideas for later - A subsystem/command structure for bigger robots. --- # Signs and units URL: https://crossbotics.com/ftc-helper/docs/conventions/ ## Driving ![Robot seen from above: which way is positive](https://crossbotics.com/ftc-helper/docs/images/robot-signs.svg) | Value | Positive means | Where you see it | | --- | --- | --- | | `forward` | robot moves forward | `MecanumDrive.drive`, `TankDrive.arcade`, the mixers | | `strafeRight` | robot moves to its right (mecanum only) | `MecanumDrive.drive`, `MecanumMixer.mix` | | `turnClockwise` | robot turns right (clockwise, seen from above) | same | | IMU heading | robot turned **left** (counterclockwise) | `ImuSetup.headingDeg`, `AutoDrive.turn`, `AutoDrive.turnTo`, `FieldPose.headingDeg` | | `move(..., directionDeg, ...)` | counterclockwise from forward, like a heading: 0 forward, 90 **left**, 180 back, -90 **right** | `AutoDrive.move`, `Steps.move` | | `moveWithTurn(..., directionDeg, headingDeg, ...)` | both counterclockwise, from the start heading (the direction stays fixed on the field, because the robot turns on the way): 90 = left | `AutoDrive.moveWithTurn`, `Steps.moveWithTurn` | **In an autonomous, every angle counts the same way: counterclockwise, 90 = left.** This is true for a move's direction, a turn and a heading. In `Steps`, you can also use words with no angle at all: `forward`, `back`, `left`, `right`, `turnLeft`, `turnRight` ([the autos/ page](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#more-steps)). Before v0.40.0, a move's direction counted clockwise (90 = right). To update an old auto, read the CHANGELOG. **Why TeleOp's turn command is clockwise-positive, but every autonomous angle is counterclockwise-positive:** - The right stick's X is positive when you push it right. Pushing right should turn the robot right. So `drive(forward, strafe, gamepad1.right_stick_x)` works with no sign change. - The FTC SDK's IMU makes the heading grow when the robot turns left. That is the math rule (counterclockwise = positive), and we do not fight the SDK. The names tell you which one you have: `turnClockwise`, `headingCcwDeg` ("CCW" = counterclockwise). ## Gamepad sticks The SDK gives **negative** `left_stick_y` when you push the stick UP (away from you). So "forward" is `-gamepad1.left_stick_y`. Every example in these docs has the minus sign. ## Servos and motors: which way is "bigger"? There is **no standard** for this, so the library makes no promise about it: - A servo position from 0 to 1 is a pulse length: 0 is the short pulse, 1 the long one. Which way a bigger number turns the shaft (clockwise or counterclockwise) depends on the servo's brand and model. - Which way positive power turns a motor also depends on the motor and its gearbox. - `.reversed()` in Robot.java swaps the ends (servo: 0 and 1; motor: + and -). It changes the numbers, not the wiring. So **check each one by test**, never by its label. In the Servo Finder, press D-pad up (a bigger number) and watch which way the part moves. For a motor, use the Motor Finder or the Hardware Check. Then choose the numbers (or `.reversed()`) so they read the way you think about the part. Any order is fine for named positions: a claw's `open` can be higher or lower than `closed`. **Two servos that face each other** (one on each side of a claw, an arm or a pinch): the same number turns them opposite ways, as seen from outside. So such a part uses `alsoServoReversed` (the second servo mirrors the first). Two servos facing the same way use `alsoServo` ([two servos on one part](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/)). ## Units | Thing | Unit | | --- | --- | | Distances (drive) | inches | | Angles | degrees | | Motor power | -1 to 1 | | Servo position | 0 to 1 | | Mechanism positions (lifts, arms) | encoder ticks (counts) | | Time | seconds, unless the name ends in `Ms` (milliseconds) or `Nanos` | ## Wheel order Any array of four wheel values is in this order: `[front-left, front-right, back-left, back-right]` Standard (tank) drive left/right arrays are `[left, right]`. `MecanumMixer.FRONT_LEFT` (0), `FRONT_RIGHT` (1), `BACK_LEFT` (2), `BACK_RIGHT` (3) name the positions. ## Button names: START and ▶ - **▶** is the Driver Hub's start button: press it after INIT to start the OpMode. The screens never call it START. - **■** is the Driver Hub's stop button (STOP). - **START** is the small button on the gamepad (OPTIONS on a PS controller). - In the docs, the Driver Hub's start is always ▶: "press ▶ (start on the Driver Hub)" the first time on a page, then "▶" or "after ▶". The moment the OpMode starts is "at ▶" or "when the OpMode starts (▶)". The gamepad's button is "the gamepad's START button", or "START (OPTIONS on a PS controller)". Code names keep their words (`atStart`, `Btn.START`). - The docs use the Logitech names (A, B, X, Y, LB, RB, LT, RT, BACK, START, GUIDE). The library's screens show the names on YOUR controller: × ○ □ △, L1 R1 L2 R2, SHARE OPTIONS PS on a PlayStation one ([ButtonNames](https://crossbotics.com/ftc-helper/docs/modules/gamepad/#buttonnames)). --- # Cookbook: "How do I...?" URL: https://crossbotics.com/ftc-helper/docs/cookbook/ **To find your question:** use the list below, or the site's search with a word like `lift`, `double-tap` or `park`. **The code works.** Every code block in the cookbook is a copy of real Java files in [`examples/.../cookbook`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/cookbook). Each time the library changes, we build those files and run them in the simulator. A check (`tools/check_docs.py`) makes sure that the pages and the files say the same thing. **If you are new:** do [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/) and [The five files](https://crossbotics.com/ftc-helper/docs/five-files/) first. They put the five files in your robot project, and these recipes go into those files. If you never coded before, read [Words you will meet](https://crossbotics.com/ftc-helper/docs/cookbook/01-the-basics/#words-you-will-meet) first. ## The questions **Start here** - [Coming from Blocks: where did my blocks go?](https://crossbotics.com/ftc-helper/docs/cookbook/01-the-basics/#coming-from-blocks-where-did-my-blocks-go) (if, loop, sleep, REVERSE, variables) - [Where does each line go? The files, whole](https://crossbotics.com/ftc-helper/docs/cookbook/01-the-basics/#where-does-each-line-go-the-files-whole) - [Words you will meet](https://crossbotics.com/ftc-helper/docs/cookbook/01-the-basics/#words-you-will-meet) - Whole robots to start from: the [templates](https://crossbotics.com/ftc-helper/docs/templates/) (ten whole example robots) and the [kit robots](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/) (goBILDA, REV, AndyMark, Studica starter bots) **Driving** - [How do I set up a mecanum drive?](https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/#how-do-i-set-up-a-mecanum-drive) - [How do I set up a tank (standard) drive?](https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/#how-do-i-set-up-a-tank-standard-drive) - [A wheel turns the wrong way. How do I fix it?](https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/#a-wheel-turns-the-wrong-way-how-do-i-fix-it) - [How do I tell the robot how the Control Hub is mounted?](https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/#how-do-i-tell-the-robot-how-the-control-hub-is-mounted) - [How do I make the robot slower (or faster)?](https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/#how-do-i-make-the-robot-slower-or-faster) - [How do I let one driver do everything?](https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/#how-do-i-let-one-driver-do-everything) - [How do I put slow mode on a trigger?](https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/#how-do-i-put-slow-mode-on-a-trigger) - [Driving that is already built in](https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/#driving-that-is-already-built-in) (field-centric, pause, "forward") **Buttons and gestures** - [How do I make a button do something once?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-make-a-button-do-something-once) - [How do I run something only while a button is held?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-run-something-only-while-a-button-is-held) - [How do I switch something on and off with one button?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-switch-something-on-and-off-with-one-button) - [How do I put a tap, a hold and a double-tap on one button?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-put-a-tap-a-hold-and-a-double-tap-on-one-button) - [How do I make a button safe ("hold for 1 second")?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-make-a-button-safe-hold-for-1-second) - [How do I use two buttons together (like a shift key)?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-use-two-buttons-together-like-a-shift-key) - [How do I make the gamepad buzz?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-make-the-gamepad-buzz) - [How do I control a part with a stick?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-control-a-part-with-a-stick) - [How do I move a part's button to another button?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-move-a-parts-button-to-another-button) - [How do I put the launcher's fire button on another button?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-put-the-launchers-fire-button-on-another-button) - [How do I let the parts add their usual buttons by themselves?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-let-the-parts-add-their-usual-buttons-by-themselves) - [How do I move the library's own buttons (slow, field-centric, pause)?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-move-the-librarys-own-buttons-slow-field-centric-pause) - [How do I change the double-tap and hold times?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-change-the-double-tap-and-hold-times) - [How do I switch the alliance during TeleOp?](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-switch-the-alliance-during-teleop) - [Buttons that are already built in](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#buttons-that-are-already-built-in) (button map, pause, switch alliance, set pose) **Mechanisms** - [How do I add an intake on a motor?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-an-intake-on-a-motor) - [How do I add an intake on CR servos?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-an-intake-on-cr-servos) - [How do I make the intake run from the start?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-make-the-intake-run-from-the-start) - [How do I add a lift with set heights?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-a-lift-with-set-heights) - [My lift goes down when it should go up. How do I fix it?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#my-lift-goes-down-when-it-should-go-up-how-do-i-fix-it) - [How do I run one lift on two motors?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-run-one-lift-on-two-motors) - [My motor isn't in the catalog](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#my-motor-isnt-in-the-catalog) - [How do I add an arm that moves in degrees?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-an-arm-that-moves-in-degrees) - [How do I add a claw?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-a-claw) - [How do I run a claw on two servos?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-run-a-claw-on-two-servos) - [How do I add a wrist?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-a-wrist) - [How do I add any servo with named positions (a gate, a fold-out)?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-any-servo-with-named-positions-a-gate-a-fold-out) - [How do I get my servo's full range?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-get-my-servos-full-range) - [How do I send a part to a position from a button?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-send-a-part-to-a-position-from-a-button) - [My robot doesn't have this part yet. How do I keep its code?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#my-robot-doesnt-have-this-part-yet-how-do-i-keep-its-code) - [How do I add a launcher (flywheel and feeder)?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-a-launcher-flywheel-and-feeder) - [How do I feed with two wheels, one on each side?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-feed-with-two-wheels-one-on-each-side) - [How do I add a turret that follows the goal?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-a-turret-that-follows-the-goal) - [How do I fire only when aimed, at the right speed?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-fire-only-when-aimed-at-the-right-speed) **Game pieces** (what is in the robot, and what fires next) - [How do I know which piece is in the robot, and how many?](https://crossbotics.com/ftc-helper/docs/cookbook/05-game-pieces/#how-do-i-know-which-piece-is-in-the-robot-and-how-many) - [How do I stop the intake when the robot is full?](https://crossbotics.com/ftc-helper/docs/cookbook/05-game-pieces/#how-do-i-stop-the-intake-when-the-robot-is-full) - [How do I tell pieces apart by size, or with a second camera?](https://crossbotics.com/ftc-helper/docs/cookbook/05-game-pieces/#how-do-i-tell-pieces-apart-by-size-or-with-a-second-camera) - [How do I use the count (buzz, LEDs, the shot table)?](https://crossbotics.com/ftc-helper/docs/cookbook/05-game-pieces/#how-do-i-use-the-count-buzz-leds-the-shot-table) - [How do I let the next piece pick the shot table?](https://crossbotics.com/ftc-helper/docs/cookbook/05-game-pieces/#how-do-i-let-the-next-piece-pick-the-shot-table) - [How do I tune the piece sensors?](https://crossbotics.com/ftc-helper/docs/cookbook/05-game-pieces/#how-do-i-tune-the-piece-sensors) **Aiming and shooting** (the robot helps the drivers) - [How do I make the whole robot aim at the goal (no turret)?](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#how-do-i-make-the-whole-robot-aim-at-the-goal-no-turret) - [How do I make the gamepad buzz when the aim is on target?](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#how-do-i-make-the-gamepad-buzz-when-the-aim-is-on-target) - [How do I keep aiming when the camera loses the goal?](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#how-do-i-keep-aiming-when-the-camera-loses-the-goal) - [How do I aim with the odometry only (no camera)?](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#how-do-i-aim-with-the-odometry-only-no-camera) - [How do I make the camera work in any venue's light?](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#how-do-i-make-the-camera-work-in-any-venues-light) - [How do I find game pieces with a HuskyLens?](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#how-do-i-find-game-pieces-with-a-huskylens) - [How do I shoot while the robot is driving?](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#how-do-i-shoot-while-the-robot-is-driving) - [How do I use one shot table per game piece?](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#how-do-i-use-one-shot-table-per-game-piece) - [Every shot is a bit short today. How do I trim the speed (a low battery)?](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#every-shot-is-a-bit-short-today-how-do-i-trim-the-speed-a-low-battery) - [How do I add a hood to my launcher?](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#how-do-i-add-a-hood-to-my-launcher) **Turrets and interlocks** (any turret; parts that share space) - [How do I home my turret with a switch?](https://crossbotics.com/ftc-helper/docs/cookbook/07-turrets-and-interlocks/#how-do-i-home-my-turret-with-a-switch) - [How do I set up a turret on a servo?](https://crossbotics.com/ftc-helper/docs/cookbook/07-turrets-and-interlocks/#how-do-i-set-up-a-turret-on-a-servo) - [How do I set up a slip-ring turret (round and round)?](https://crossbotics.com/ftc-helper/docs/cookbook/07-turrets-and-interlocks/#how-do-i-set-up-a-slip-ring-turret-round-and-round) - [How do I stop two parts from hitting each other?](https://crossbotics.com/ftc-helper/docs/cookbook/07-turrets-and-interlocks/#how-do-i-stop-two-parts-from-hitting-each-other) - [How do I pick up and score with a lift, a wrist and a claw?](https://crossbotics.com/ftc-helper/docs/cookbook/07-turrets-and-interlocks/#how-do-i-pick-up-and-score-with-a-lift-a-wrist-and-a-claw) **Actions** (several steps or parts together) - [How do I do several things one after the other?](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-do-several-things-one-after-the-other) - [How do I repeat steps several times?](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-repeat-steps-several-times) - [How do I move two parts at the same time?](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-move-two-parts-at-the-same-time) - [How do I wait half a second (like sleep in Blocks)?](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-wait-half-a-second-like-sleep-in-blocks) - [How do I wait until something is true?](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-wait-until-something-is-true) - [How do I start an action from a button?](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-start-an-action-from-a-button) - [How do I stop every running action?](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-stop-every-running-action) - [How do I run an action when the OpMode starts?](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-run-an-action-when-the-opmode-starts) - [How do I use the same action in an autonomous?](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-use-the-same-action-in-an-autonomous) **Autonomous** - [How do I make my first autonomous (drive 2 feet)?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-make-my-first-autonomous-drive-2-feet) - [How do I drive forward, sideways and turn?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-drive-forward-sideways-and-turn) - [Does my autonomous need a RED version?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#does-my-autonomous-need-a-red-version) - [How do I let the drivers choose before the match?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-let-the-drivers-choose-before-the-match) - [How do I make sure there is time to park?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-make-sure-there-is-time-to-park) - [How do I run a mechanism while the robot drives?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-run-a-mechanism-while-the-robot-drives) - [How do I wait for my alliance partner?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-wait-for-my-alliance-partner) - [How do I write a step the list cannot say?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-write-a-step-the-list-cannot-say) - [How do I change a distance in an autonomous?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-change-a-distance-in-an-autonomous) - [How do I share the same first steps in several autos?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-share-the-same-first-steps-in-several-autos) - [How do I make the start delay shorter, or use a different number on RED?](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-make-the-start-delay-shorter-or-use-a-different-number-on-red) **Several autos and choosing one** (more: [Building autos 3: having multiple autos](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/)) - [How do I build several autos from the same pieces?](https://crossbotics.com/ftc-helper/docs/cookbook/10-several-autos/#how-do-i-build-several-autos-from-the-same-pieces) - [How do I make two autos that differ by one piece?](https://crossbotics.com/ftc-helper/docs/cookbook/10-several-autos/#how-do-i-make-two-autos-that-differ-by-one-piece) - [How do I let the drivers choose the start spot and the plan in INIT?](https://crossbotics.com/ftc-helper/docs/cookbook/10-several-autos/#how-do-i-let-the-drivers-choose-the-start-spot-and-the-plan-in-init) **Odometry and driveTo** (where is the robot on the field?) - [How do I add a goBILDA Pinpoint?](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-add-a-gobilda-pinpoint) - [How do I add a SparkFun OTOS?](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-add-a-sparkfun-otos) - [How do I add dead wheels?](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-add-dead-wheels) - [How do I tune the odometry?](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-tune-the-odometry) - [How do I drive to a point on the field?](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-drive-to-a-point-on-the-field) - [How do I get around field elements on the way to a spot?](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-get-around-field-elements-on-the-way-to-a-spot) - [How do I show where the robot is?](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-show-where-the-robot-is) - [How do I use the robot's position in an action?](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-use-the-robots-position-in-an-action) - [How do I set the pose when autonomous did not run?](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-set-the-pose-when-autonomous-did-not-run) **Pedro paths** (smooth curves, mecanum only) - [How do I add Pedro Pathing to Robot.java?](https://crossbotics.com/ftc-helper/docs/cookbook/12-pedro-paths/#how-do-i-add-pedro-pathing-to-robotjava) - [How do I make a straight path and a curve?](https://crossbotics.com/ftc-helper/docs/cookbook/12-pedro-paths/#how-do-i-make-a-straight-path-and-a-curve) - [How do I follow a path in an autonomous?](https://crossbotics.com/ftc-helper/docs/cookbook/12-pedro-paths/#how-do-i-follow-a-path-in-an-autonomous) - [How do I drive two paths with no stop, slow down, or hold at the end?](https://crossbotics.com/ftc-helper/docs/cookbook/12-pedro-paths/#how-do-i-drive-two-paths-with-no-stop-slow-down-or-hold-at-the-end) - [How do I keep facing the goal along a path?](https://crossbotics.com/ftc-helper/docs/cookbook/12-pedro-paths/#how-do-i-keep-facing-the-goal-along-a-path) - [How do I drive first and turn at the end of a path (or turn first)?](https://crossbotics.com/ftc-helper/docs/cookbook/12-pedro-paths/#how-do-i-drive-first-and-turn-at-the-end-of-a-path-or-turn-first) - [How do I start something partway along a path?](https://crossbotics.com/ftc-helper/docs/cookbook/12-pedro-paths/#how-do-i-start-something-partway-along-a-path) **Telemetry** (lines on the Driver Station) - [How do I show a value on the Driver Station screen?](https://crossbotics.com/ftc-helper/docs/cookbook/13-telemetry/#how-do-i-show-a-value-on-the-driver-station-screen) - [How do I round a number on the Driver Station?](https://crossbotics.com/ftc-helper/docs/cookbook/13-telemetry/#how-do-i-round-a-number-on-the-driver-station) - [How do I show lines from my own autonomous step?](https://crossbotics.com/ftc-helper/docs/cookbook/13-telemetry/#how-do-i-show-lines-from-my-own-autonomous-step) **Lights** (a color the drivers can see) - [How do I add a colored light for the drivers?](https://crossbotics.com/ftc-helper/docs/cookbook/14-lights/#how-do-i-add-a-colored-light-for-the-drivers) - [How do I change a color on a REV Blinkin?](https://crossbotics.com/ftc-helper/docs/cookbook/14-lights/#how-do-i-change-a-color-on-a-rev-blinkin) - [How do I show a color when something is true?](https://crossbotics.com/ftc-helper/docs/cookbook/14-lights/#how-do-i-show-a-color-when-something-is-true) - [How do I show the alliance on the light before the match?](https://crossbotics.com/ftc-helper/docs/cookbook/14-lights/#how-do-i-show-the-alliance-on-the-light-before-the-match) - [How do I flash the light when something happens?](https://crossbotics.com/ftc-helper/docs/cookbook/14-lights/#how-do-i-flash-the-light-when-something-happens) - [How do I flash the light when an action is done?](https://crossbotics.com/ftc-helper/docs/cookbook/14-lights/#how-do-i-flash-the-light-when-an-action-is-done) - [How do I blink the light in the last 20 seconds?](https://crossbotics.com/ftc-helper/docs/cookbook/14-lights/#how-do-i-blink-the-light-in-the-last-20-seconds) **Tuning and finders** (getting the numbers right) - [Where do the numbers go?](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#where-do-the-numbers-go) - [How do I find a servo's open and closed numbers?](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-find-a-servos-open-and-closed-numbers) - [How do I find a lift's limits and heights?](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-find-a-lifts-limits-and-heights) - [How do I change a number while the robot runs?](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-change-a-number-while-the-robot-runs) - [How do I tune the drive for autonomous?](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-tune-the-drive-for-autonomous) - [How do I set the flywheel numbers?](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-set-the-flywheel-numbers) - [How do I build a shot table (speed for each distance)?](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-build-a-shot-table-speed-for-each-distance) - [How do I find my hood's stops and angles?](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-find-my-hoods-stops-and-angles) **Simulator** (try your code with no robot) - [How do I start the simulator?](https://crossbotics.com/ftc-helper/docs/cookbook/16-simulator/#how-do-i-start-the-simulator) - [How do I see my own robot in the simulator?](https://crossbotics.com/ftc-helper/docs/cookbook/16-simulator/#how-do-i-see-my-own-robot-in-the-simulator) - [How do I make the simulator draw my part?](https://crossbotics.com/ftc-helper/docs/cookbook/16-simulator/#how-do-i-make-the-simulator-draw-my-part) - [How do I test my code with a script?](https://crossbotics.com/ftc-helper/docs/cookbook/16-simulator/#how-do-i-test-my-code-with-a-script) ## Not here? - Every class and method: the [reference](https://crossbotics.com/ftc-helper/docs/reference/) and the [module pages](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/README.md#what-is-inside). - Something goes wrong: [Troubleshooting](https://crossbotics.com/ftc-helper/docs/troubleshooting/). - Learn it step by step: [The five files](https://crossbotics.com/ftc-helper/docs/five-files/), then [Add to your robot](https://crossbotics.com/ftc-helper/docs/add-to-robot/). - A question the cookbook does not answer: [tell us](https://github.com/crossbotics/ftc-helper-lib/issues/new/choose). --- # Coming from last season's code URL: https://crossbotics.com/ftc-helper/docs/from-last-season/ Each reusable part of last season's code has a new name in the library, and some parts changed. Game-specific code (launcher, feed, intake, vision, routes) is NOT in the library. | Last season | Now | What changed | | --- | --- | --- | | `input/ControllerBindings` | `gamepad.ControllerBindings` | Same `bindPress`/`bindHold`/`bindToggle`/`bindTriggerPress`/`bindTriggerAxis`. New: `bindRelease`, `bindTriggerHold`, `setTriggerThreshold`, `ignoreHeldButtons` (replaces the per-button "seeded" press), `isDown`, `GUIDE` and `TOUCHPAD` buttons. Fixed: trigger presses no longer borrow the bumper's slot. `registerExtraButtonReader` is now `registerExtraButton`. | | `input/DriveInputScaling.slowScale` | `gamepad.StickShaping.slowScale(trigger, slowest)` | The slowest speed is a parameter instead of a static setting. New: `curve`, `shape`. | | `input/ReverseDriveControl` | `drive.ReverseDrive` | No longer binds a button itself; you bind it (see [drive.md](https://crossbotics.com/ftc-helper/docs/modules/drive/#reversedrive)). | | `utils/RumbleNotifier` | `gamepad.AimRumble` | Same feel and defaults. `setMinMax` is now `setFeel`; `setActive` is `setEnabled`. | | `utils/ToggleRumble` | `gamepad.ToggleRumble` | You set the pattern with `setPattern` instead of a static config class. `isConfirming` is now `isPlaying`. | | `drive/MecanumMixer` | `drive.MecanumMixer` | Same `mix`. `fieldVector` is now `fieldDirection`, and its first number counts counterclockwise (90 = left) since v0.40.0. New: `fieldToRobot` for field-centric TeleOp. | | `drive/MecanumDrive` | `drive.MecanumDrive` | Takes a `DriveConfig` object instead of the static `RobotConfig`. New: `driveFieldCentric`, `setPowers`, `setBrake`. | | `drive/Drivebase` (Auto helpers) | `drive.AutoDrive` | Settings come from `AutoDriveConfig` (same default numbers as `DriveTuning`). `moveWithTwist` is now `moveWithTurn`. New: `turnTo`, a `Result` for each move. Changes below. | | `config/DriveTuning` | `drive.AutoDriveConfig` | Fields renamed in plain words, for example `TURN_KP` is `turnKp`, `AUTO_MOVE_MIN_SPEED` is `moveMinPower`. | | `odometry/FieldPose`, `odometry/PoseStore` | `util.FieldPose`, `util.PoseStore` | `setLastKnownPose`/`consumeLastKnownPose` are now `save`/`consume`; `peek`, `has` and `clear` remain. | | `auto/BaseAuto` + `AutoSequence` | `auto.AutoRoutine`, `auto.EasyAuto` | Same idea (a chain of named steps, endgame/park reserve, remembered heading). Game steps (fire, intake rows) are gone: mechanisms give their own steps. The routine mirrors the steps for RED. | | `subsystems/Launcher`, `control/FiringController`, `config/AutoRpmConfig` | `launcher.Flywheel`, `launcher.Launcher`, `launcher.ShotTable` | General versions: RPM with settle time and shot detection; readiness gating with named checks and a give-up reason; distance table with hood angles. Last season's live speed scale is the speed trim (`robot.launcher.trimBy`, the D-pad), and the flywheel can make up for a low battery (`Flywheel.batteryCompensation`). Battery compensation is off by default. | | `subsystems/Feed` | `launcher.MotorFeeder`, `launcher.ServoFeeder` (`Feeder` interface) | One piece per call; the launcher decides when. | | `subsystems/Intake` jam logic | `mechanism.SpinMotor`, `safety.JamDetector` | General jam detection and back-out; the DECODE packing states are not included. | | `vision/*` | `vision.WebcamTags`, `vision.LimelightTags`, `vision.AimController` | Rewritten for SDK 12 (single tags and clusters). Bearing is + = left for both cameras. No field localization (BIOBUZZ tags move). | | `Alliance`, `TeleOp_Blue`/`TeleOp_Red` | `match.Alliance`, `match.MatchMemory` | One TeleOp for both alliances: it reads the alliance autonomous chose. | | TeleOp auto-stop timer | `match.MatchTimer` | Countdown with cues and gamepad buzzes. | | `config/*` tunables + FTC Dashboard | `tuning.Tunable`, `tuning.TuningMenu`, `core.Profile` | Tune from the gamepad, saved on the hub; Dashboard still optional. | | (new) | `drive.TankDrive` (standard drive), `safety.SafeMotor`, `control.PidController`, `control.SlewRateLimiter`, `telemetry.TelemetryHelper`, `hardware.*` | New helpers. | ## Behavior changes in AutoDrive (on purpose) - **Power limit:** `DriveConfig.powerLimit` now applies to every autonomous move and turn. - **Diagonal distance:** AutoDrive measures distance from the real forward and sideways travel. Before, a 45 degree move stopped short (about 17 of 24 inches), and the strafe correction had no effect on pure strafes. `strafeCorrection` also raises the sideways power, so diagonals keep their direction. **Re-tune `strafeCorrection`** with the steps in drive.md. - **moveWithTurn** finishes its turn only after a successful move, and inside the same time limit. Before, a stuck robot could start turning, and the time limit could nearly double. - **Negative distance** now drives the opposite way. Before, `move(-10, 0, ...)` drove FORWARD 10 inches. - **Stall check** looks at progress over a time window (0.25 in within 0.4 s by default). Before, it checked each loop, so a fast loop could wrongly decide a slow-moving robot was stuck. - `AUTO_STALL_VELOCITY_EPSILON` is gone; `stallProgressIn` and `stallTimeSec` do the whole job. - `turnMinPower` (new, default 0 = old behavior) can stop turns from stalling a little short. - Every move returns `DONE`, `STALLED`, `TIMED_OUT` or `STOPPED`. - We removed unused leftovers (`setRunToPosition`, `restoreBaseRunMode`, the TeleOp `drive()` inside Drivebase). For TeleOp, use `MecanumDrive`. --- # Simulator URL: https://crossbotics.com/ftc-helper/docs/simulator/ The simulator is a pretend Control Hub and Driver Hub. Your OpModes run as they are. The motors, servos, switches, turn sensor (IMU), cameras and the robot on the field are pretend, with simple physics. You drive the robot from a web page, with a gamepad, the keyboard or a phone. - **Good for:** checking buttons and screens, trying an autonomous, testing the finders and camera code, learning the controls, and finding crashes before a meeting. - **Not for:** exact speeds, real shots or real camera pictures. You still tune the real robot ([Tuning](https://crossbotics.com/ftc-helper/docs/tuning/)). ![The simulator page: the Driver Hub on the left, the field in 3D in the middle with the gamepads under it, and the Control Hub's panels on the right](https://crossbotics.com/ftc-helper/docs/images/simulator.png)
flowchart LR
    P["Browser page<br/>Driver Hub + gamepads + Control Hub"] <--> S["Simulator (Java on the laptop)<br/>your OpModes + pretend hardware + physics"]
    C["Real controller<br/>(USB or Bluetooth)"] --> P
    K["Keyboard"] --> P
    Ph["Phone on the same WiFi<br/>(touch gamepad)"] --> S
| # | Page | You learn | Use it | | --- | --- | --- | --- | | 1 | [Start it and drive](https://crossbotics.com/ftc-helper/docs/simulator/01-start-and-drive/) | Start the simulator, read the page, and drive with a gamepad, the keyboard or a phone. | when you have the library in your project | | 2 | [Your robot file](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/) | The text file that tells the simulator about your robot. The simulator makes it from `Robot.java`, and marks what it guessed. | when your robot has the five files | | 3 | [Make it match your robot](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/) | Size and wheels, then the parts and their shapes, where the pieces go in and out, and CAD (your robot's 3D design files). Worked examples for the common setups. | when you want the pretend robot to act like yours | | 4 | [Watch an autonomous](https://crossbotics.com/ftc-helper/docs/simulator/04-watch-an-autonomous/) | Run your autonomous, watch the score, and read the report. | after each change to an autonomous | **Tests:** the simulator can also check your code after every change. That is its own section: [Tests](https://crossbotics.com/ftc-helper/docs/tests/). --- **Next:** [Start it and drive](https://crossbotics.com/ftc-helper/docs/simulator/01-start-and-drive/). **Look it up:** [The robot file](https://crossbotics.com/ftc-helper/docs/reference/robot-file/): every line. [Scenario files](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/): the test language. **Go deeper:** [How the simulator works](https://crossbotics.com/ftc-helper/docs/guides/how-the-simulator-works/): the physics, the game rules and the score, shots, cameras, and what it does not simulate. --- # Read Java and make your first edit URL: https://crossbotics.com/ftc-helper/docs/start-from-zero/ **For:** anyone new to Java. **Before this:** [Set up](https://crossbotics.com/ftc-helper/docs/setup/), pages 1 to 7. At the end you can read a Java file, change one line safely, and make new files in TeamCode. ## Reading Java without writing it You do not need to write Java yet. You need to read it well enough to change one line safely. This small file is the FTC sample `ConceptNullOp.java`, shortened: ```java package org.firstinspires.ftc.robotcontroller.external.samples; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; @TeleOp(name = "Concept: NullOp", group = "Concept") @Disabled public class ConceptNullOp extends OpMode { @Override public void init() { telemetry.addData("Status", "Initialized"); // a line on the Driver Station } ... } ``` What each part is: - **A file** holds one **class** (one piece of a program). The file name and the class name are the same: `ConceptNullOp.java` holds `class ConceptNullOp`. - **The `package` line** (the first line) says which folder the file is in, with dots in place of slashes. It **must match the folder**, or the file does not build. - **`import` lines** name code from other places that this file uses (here, from the FTC SDK). - **`@TeleOp(...)`** and **`@Disabled`** are notes for the Driver Station. `@TeleOp(name = "...")` is the name in the TeleOp list. `@Disabled` hides the OpMode from the list. - **`{` and `}`** (curly brackets) hold a group of lines together. Every `{` has its own `}` further down. The class has one pair. Each part inside it has its own pair. - **`;`** (semicolon) ends a statement (one command), like a period ends a sentence. - **`//`** starts a **comment**: words for people, from `//` to the end of the line. Java ignores them. - **`"text in quotes"`** is text, used as it is (a name on the Driver Station, a motor name). Words **without** quotes are **names** in the code (`telemetry`, `init`). Do not add or remove quotes. - **Capitals count.** `Intake`, `intake` and `INTAKE` are three different names to Java. **Red text is an error.** A name underlined in red, or a red line in the **Build** tab, is an error. Read only the **first** error: the later ones often come from the first. It looks like this: ```text Robot.java:12: error: ';' expected ``` That says: the file (`Robot.java`), the line number (12), and the problem (a `;` is missing). Click it to go to the line. Fix it, then build again. **Why the first:** one missing `;` or `}` can make twenty more errors below it, and they all go away with the first fix. ### Java words You meet these words in the code, and again in these docs. - **variable:** a name that holds a value, like a box with a label. `maxPower` holds `0.4`. - **`double`:** a kind of variable that holds a number with a decimal point (`0.4`, `96`). **`int`** holds a whole number (`3`). - **`boolean`:** a kind of variable that holds only `true` or `false` (yes or no). - **`true` / `false`:** the two answers to a yes/no question, for example "is the button pressed?". - **method:** a named list of commands, like a custom block. `init()` and `buttons(...)` are methods. The `( )` after the name hold its inputs. - **`void`:** written before a method's name when the method hands nothing back. - **`return`:** hands a result back from a method, and ends the method. - **object:** one thing the program made from a class, with its own values: your robot, its intake. `robot.intake.in()` asks the intake object to run its `in` method. - **`public`:** other files may use this name. (`private`: only this file may.) - **`static`:** belongs to the class itself, not to one object, so there is only one. In `Tunables.java`, `public static double maxPower` is one number the whole program shares. ## Copy a file into TeamCode and change one line Now run your own first OpMode: a copy of the FTC sample above. It needs no motors. 1. In the **Project** panel, find the sample: `FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/external/samples/ConceptNullOp.java`. 2. Click it, and copy it (**Edit > Copy**). Click the `teamcode` folder ([Set up 3](https://crossbotics.com/ftc-helper/docs/setup/03-github-and-the-project/#3-open-the-project-in-android-studio)), and paste it (**Edit > Paste**). If Android Studio asks, click **OK** (keep the name). **Why copy:** never change FTC's own files. Your team's code lives only in TeamCode. 3. Open the copy (in `teamcode`). Change **exactly one line**, the first one: Before: ```java package org.firstinspires.ftc.robotcontroller.external.samples; ``` After: ```java package org.firstinspires.ftc.teamcode; ``` **Why:** the file is now in the `teamcode` folder, and the `package` line must match its folder. (Android Studio may change it for you when you paste. Check it anyway.) 4. Delete the whole line `@Disabled`. **Why:** with it, the Driver Station hides the OpMode. 5. Build (hammer), then Run (triangle) to install it. 6. On the Driver Station, pick **Concept: NullOp** in the TeleOp list. Press INIT: it shows `Status: Initialized`. Press ▶: it shows the run time. Then press STOP. Common mistakes: - **Two `package` lines,** or a first line with a typo: the build says `class, interface, or enum expected`. The file must have exactly one `package` line, at the top. - **A deleted `;` or `}`:** the build says `';' expected` or `reached end of file while parsing`. Press **Edit > Undo** until the file is as it was. ### Make a new file or folder Later pages say "make a file" or "make a folder". Do it in the **Project** panel (the **Project** view, [Set up 3](https://crossbotics.com/ftc-helper/docs/setup/03-github-and-the-project/#3-open-the-project-in-android-studio)). You make each kind a different way: 1. **A new Java file** (a class, for example `HardwareCheck.java`): right-click the `teamcode` folder and click **New > Java Class**. Type the name **without** `.java` (`HardwareCheck`), pick **Class**, and press Enter. Android Studio writes the `package` line for you. Then replace everything in the new file with the whole file the page shows (select all with **Edit > Select All**, then paste). Check that the first line is still `package org.firstinspires.ftc.teamcode;`. **Why:** the file name must be the class name, and the `package` line must match the folder. 2. **A Java folder** (a folder of code, for example `autos`): right-click the `teamcode` folder, click **New > Package**, and type `autos` (after the `teamcode.` that is already there). A file in it starts with `package org.firstinspires.ftc.teamcode.autos;`. **Why "Package":** Java calls a folder of code a package. 3. **A plain text file** (not Java: for example `local.properties` or a scenario `my-test.sim`): right-click the folder it goes in, click **New > File**, and type the **full** name with its ending (`local.properties`, `my-test.sim`). Do not add `.txt`. If Android Studio asks what kind of file it is ("Register New File Type Association"), pick **Text**. **Why the full name:** the ending tells the tools what the file is. The tools do not find `my-test.sim.txt`. 4. **A plain folder** (not Java: for example `simulator/scenarios` next to `TeamCode`): right-click the top project folder (the one with `TeamCode` in it), click **New > Directory**, and type `simulator/scenarios`. The `/` makes a folder inside a folder. The example robots put the autonomous programs in a Java folder `autos` inside `teamcode` (kind 2). ## Next 1. If you used Scratch or Blocks before, read [From Blocks to Java](https://crossbotics.com/ftc-helper/docs/blocks-to-java/): it shows where each block you know went. 2. [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/): get the five robot files, then [The five files](https://crossbotics.com/ftc-helper/docs/five-files/) to drive. --- # Starter kit: a whole robot program URL: https://crossbotics.com/ftc-helper/docs/starter-kit/ > **Start with the robot in five files instead.** [The five files](https://crossbotics.com/ftc-helper/docs/five-files/) shows a > shorter way: `Robot.java`, `Tunables.java`, `Controls.java`, `Actions.java` and autos, made from your robot > configuration by `./gradlew :sim:newRobot`, with ready-made modules ([robot module](https://crossbotics.com/ftc-helper/docs/reference/robot-java/)). > This starter kit still works, and we keep it for teams that use it. If you are a new team, start at > [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/). **Before this:** [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/). **Files:** [`examples/.../starter/`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/starter) | # | File | What it is | You change | | --- | --- | --- | --- | | 1 | `RobotSettings.java` | drive type, motor names, IMU mounting, autonomous tuning (a [`RobotConfig`](https://crossbotics.com/ftc-helper/docs/modules/core/#robotconfig), shared by TeleOp and every autonomous) | names, numbers | | 2 | `Robot.java` | your mechanisms (lift, claw, intake...) | add/remove mechanisms | | 3 | `MainTeleOp.java` | the TeleOp, built on [`EasyTeleOp`](https://crossbotics.com/ftc-helper/docs/modules/teleop/): driving, timer cues and tuning menu come with it; the file adds the operator's buttons | button map | | 4 | `StarterAuto.java` | what every autonomous shares | nothing | | 5 | `AutoScoreAndPark.java` | one autonomous (copy for more) | the steps | | 6 | `HardwareCheck.java` | tests every device | nothing | | + | `ServoFinder.java`, `MotorFinder.java`, `FlywheelFinder.java`, `DriveTuner.java`, `Characterizer.java` | [finders](https://crossbotics.com/ftc-helper/docs/tuning/): measure servo ends, lift limits, flywheel gains, wheel size, how the motors move on the robot (feedforward, simulator), and show the code to copy | `Characterizer`: your lift/arm limits and flywheel names |
flowchart LR
    RS["1 RobotSettings"] --> T["3 MainTeleOp"]
    RS --> SA["4 StarterAuto"]
    R["2 Robot"] --> T
    R --> SA
    SA --> A1["5 AutoScoreAndPark"]
    SA --> A2["your next auto"]
    H["6 HardwareCheck"]
## Steps 1. **Add the library** to the robot project: [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/). 2. **Copy the 6 files (and the 5 finder files)** into `TeamCode/src/main/java/org/firstinspires/ftc/teamcode/` and change the first line of each to `package org.firstinspires.ftc.teamcode;`. Delete each `@Disabled` line. 3. **Configure the robot** on the Driver Station with the names in `RobotSettings` and `Robot` (or change the names in the code to match yours). 4. **Hardware Check** (robot on a block): check that it lists every device, and that every motor turns the right way. Fix directions in `RobotSettings` / `Robot`. Write down servo positions. 5. **`Robot.java`**: delete mechanisms you do not have. Find each servo's and lift's limits and positions with the **Servo Finder** and **Motor Finder** ([finders](https://crossbotics.com/ftc-helper/docs/tuning/): small OpModes that measure a number and show the code line to copy). Copy the lines they show. [mechanism.md](https://crossbotics.com/ftc-helper/docs/modules/mechanism/) explains each mechanism type. 6. **Main TeleOp**: drive at the PRACTICE profile's gentle power (a profile is a set of limits: PRACTICE is gentle for the shop, COMPETITION is full power). It starts robot-centric. Double-tap Y to turn field-centric on. Check every button in [the list](#the-buttons). Print that list for the drive team. 7. **Tune** the lift with the tuning menu (GUIDE button, PRACTICE profile), then copy the numbers into `Robot.java` ([tuning guide](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/)). 8. **Autonomous**: tune the drivetrain with the **Drive Tuner** finder, set `calibrationConfirmed = true`, then change `AutoScoreAndPark`'s steps for your game ([easy autos](https://crossbotics.com/ftc-helper/docs/guides/easy-autos/)). 9. **Before the event**: pick the COMPETITION profile, and go through the [testing checklist](https://crossbotics.com/ftc-helper/docs/tests/03-checks-before-practice-and-matches/). ## Robot.java: the mechanisms `Robot.java` sets up the mechanisms once, in the constructor (the code that runs at `new Robot(hardwareMap)`, in INIT). Nothing moves there, so it is safe in INIT. TeleOp and every autonomous make one and use `robot.lift`, `robot.claw` and `robot.intake`. The fields are `public` (TeleOp and autonomous can use them) and `final` (each is set once and never swapped for another one). Each mechanism type: [mechanism.md](https://crossbotics.com/ftc-helper/docs/modules/mechanism/). ```java BulkReads.auto(hardwareMap); // (1)! // Each name in quotes ("lift", "lift_bottom", "claw", "intake") = the device's name in the robot // configuration on the Driver Station. // The lift: named heights, in encoder ticks. Measure yours with the Motor Finder. lift = PositionMotor.create(hardwareMap, "lift") // SAFETY: the software range, ticks. It still needs a physical stop at the top. .limits(0, 2600) // (2)! .lowerSwitch(hardwareMap, "lift_bottom") // optional: skipped if not configured (3)! .slowZone(250, 0.2) // near either end: slow down (ticks, power) (4)! .pid(0.004, 0, 0.0002, 0.05) // P, I, D, F: starting values, tune yours (5)! .position("DOWN", 0) // named heights, ticks .position("LOW", 900) .position("HIGH", 2400) .tunable("Lift"); // in the tuning menu: copy good values back here (6)! // The claw: a servo with named positions, 0 to 1. Measure yours with the Servo Finder. claw = PositionServo.create(hardwareMap, "claw") .position("OPEN", 0.20) .position("CLOSED", 0.75) .travelTime(0.3) // seconds for a full move (0 to 1) (7)! .tunable("Claw"); // The intake: IN at full power, OUT at 70% so pieces are pushed out, not thrown. intake = SpinMotor.create(hardwareMap, "intake") .powers(1.0, -0.7); // Every mechanism, in one group. Add a new mechanism here too, or it is never updated or stopped. all = new Subsystems().add(lift, claw, intake); // (8)! ``` 1. One message reads every sensor and encoder of the hub at once, at the start of each loop. Without it, each read is its own message, and the loop gets slower with every part. 2. The software never drives the lift below 0 or above 2600 ticks (encoder counts: how far the motor shaft has turned). The robot still needs a real, physical stop at the top: the rules ask for one, and software can fail. 3. A touch sensor at the bottom. Each press sets the count back to 0, which removes drift. Until the first press, the lift only goes down, slowly. With no switch in the configuration, the library skips the line. 4. Within 250 ticks of either end, the lift cuts its power, down to 20% right at the end. So the lift does not slam into its stops. 5. These numbers set how hard the lift pushes toward a height. P = 0.004 pushes harder when it is far. I = 0 (not used). D = 0.0002 calms it so it does not overshoot. F = 0.05 is a small steady push up that holds it against gravity. These are starting values: tune yours ([tutorial 07](https://crossbotics.com/ftc-helper/docs/tutorials/07-pid-lift/)). 6. The gains and heights are then in the tuning menu as "Lift/...". Change them from the gamepad in the PRACTICE profile, then copy the good values back into this file ([tuning guide](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/)). The code is the record. 7. A servo cannot say where it is. So the claw uses this time to guess when it has finished moving: about how many seconds the servo takes to move the whole way (0 to 1). 8. The library updates, shows and stops the `all` group for you. It never updates (so never moves) or stops a mechanism that is not in it. ## RobotSettings.java: the drivetrain `RobotSettings` extends the library's [`RobotConfig`](https://crossbotics.com/ftc-helper/docs/modules/core/#robotconfig): the robot described once, which `EasyTeleOp` and `EasyAuto` both read. It is not an OpMode (no `@TeleOp`), so it never shows on the Driver Station. `drive()` makes a fresh set of settings at each call, so one program cannot change another's by mistake. `Profile.pick(0.6, 1.0)`: 60% power in the PRACTICE profile (safer around people and while learning), 100% in COMPETITION ([profiles](https://crossbotics.com/ftc-helper/docs/guides/profiles/)). The IMU is the hub's built-in turn sensor. If its two mounting directions are wrong for your robot, the heading is wrong, and so are field-centric driving and every autonomous turn ([hardware.md](https://crossbotics.com/ftc-helper/docs/modules/hardware/) has a picture). ```java public AutoDriveConfig auto() { AutoDriveConfig c = new AutoDriveConfig(); // Encoder ticks per turn of the motor's output shaft: look up yours on the seller's page. c.ticksPerRev = 537.7; // goBILDA 312 RPM // Start with the real size, then adjust until a 48-inch move really moves 48 inches. c.wheelDiameterIn = 3.78; // 96 mm wheels, then tune // Mecanum wheels slip sideways: tune this on field tiles with the Drive Tuner. c.strafeCorrection = 1.15; // (1)! // SAFETY: autonomous refuses to start while this is false. Set it true only after you checked // the wheel size, motor directions and IMU mounting. c.calibrationConfirmed = false; // true after tuning (2)! return c; } ``` 1. Mecanum wheels slip sideways, so the robot moves less sideways than the wheels turn. 1.15 makes up for that. The [Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/) measures yours on field tiles. 2. A safety switch: the autonomous stops in INIT with a message while it is false. A wrong wheel size, a reversed motor or a wrong IMU mounting makes an autonomous drive somewhere you did not plan. ## The buttons Print this list for the drive team. Gamepad 1 comes from `EasyTeleOp`. Gamepad 2 comes from `MainTeleOp.java`. Each operator button only sets a target: the mechanisms do the moving in their `update()`, so nothing in the TeleOp waits. | Gamepad 1 (driver) | | Gamepad 2 (operator) | | | --- | --- | --- | --- | | left stick | drive | D-pad up/down | lift one position up/down | | right stick X | turn | A / Y | lift DOWN / HIGH | | left trigger | slow (squeeze) | left stick Y | lift by hand | | Y | double-tap: field-centric on/off | right bumper | claw open/close | | BACK | reset "forward" | left bumper | intake on/off | | GUIDE | tuning menu (PRACTICE) | B (hold) | intake reverse | | BACK + START together | debug telemetry on/off | | | The lift by hand has a deadband of 0.1 (the stick must move past 0.1 before it counts). So a bumped stick does not cancel a button height. The gamepad buzzes at 1:00 and 0:20 left (2026-27 BIOBUZZ: FLOWER ownership unlocks at 1:00, and then the final 20 s). ## AutoScoreAndPark.java: an autonomous We wrote it for BLUE. The library mirrors it for RED. `preselectTeleOp` makes the Driver Station pick Main TeleOp after the autonomous. `extends StarterAuto` gives it the shared setup from file 4 (drive, IMU, robot, INIT menu). So this file only says where to start, which extra choices to offer, and the steps. `startHeadingDeg()` is the way the robot faces at the start, compared with "straight away from your driver". TeleOp uses it, so field-centric "forward" is right as soon as TeleOp starts. The step names show on the Driver Station while each one runs, and in the report at the end: make them clear. More: [easy autos](https://crossbotics.com/ftc-helper/docs/guides/easy-autos/), [tutorial 16](https://crossbotics.com/ftc-helper/docs/tutorials/16-easy-autos/). ```java protected void buildRoutine(AutoRoutine r) { // Close the claw on the preloaded piece, then pull 4 in off the wall so the turn does not rub it. r.run("Hold the piece", () -> robot.claw.goTo("CLOSED")) // (1)! .move("Leave the wall", 4, 0, 0.4); // Only if the drivers left "Score" at YES in the INIT menu. if (menu("Score")) { r.step("Start the lift", robot.lift.startStep("HIGH")) // rises during the next moves (2)! .move("Drive to the goal", 24, 0, 0.6) .turn("Face the goal", 45, 0.5) // left 45 on BLUE, right 45 on RED // At most 2 s, so a stuck lift cannot use up the whole autonomous. .waitUntil("Lift up", robot.lift::isAtTarget, 2.0) // (3)! // Open the claw and wait until it should be open (from the claw's travel time). .step("Drop", robot.claw.goToStep("OPEN")) // Start the lift down and go straight on (it comes down during the next steps). .step("Lift down", robot.lift.startStep("DOWN")) // Turn back to heading 0 (the way the robot faced at the start) before parking. .turnTo("Square up", 0, 0.5); } // Everything after thenPark() is the park: it still runs when the steps above ran out of time. r.thenPark() // (4)! .right("Park", 20, 0.7); // right on BLUE, left on RED } ``` 1. `() -> ...` is a **lambda**: a small piece of code the routine runs when it gets to this step. Leaving the wall slowly (40%) keeps the robot from rubbing the wall when it turns. 2. `startStep` starts the lift and goes straight on: the lift rises while the robot drives, which saves time. 3. `robot.lift::isAtTarget` is a **method reference**: it hands over "how to ask the lift if it is there". The routine checks it again and again until it is true, or 2 s have passed. 4. The steps before `thenPark()` stop when `parkReserveSec()` (4 s) is left, so the park always runs. 70% power: the park is a straight, simple move, and time is short. ## Standard (tank) drivetrain In `RobotSettings.drive()` use `DriveConfig.tank()` (4 motors) or `DriveConfig.tankTwoMotor()`. That is all: `MainTeleOp` drives arcade style by itself (left stick forward/back, right stick turn). It has no field-centric mode. Autonomous can only move forward and back, and turn (`move(d, 0 or 180, p)`, `turn`, `turnTo`). --- # Pick your template URL: https://crossbotics.com/ftc-helper/docs/templates/ **For:** a team that starts its robot code. **You need:** the library in your robot project ([Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/)). If you are new to the library, start at [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/): short pages for the same choice, one per start. A **template** is robot code you copy and then change. Start from the one that looks most like your robot: you delete less and type less. Most of them (all but the last row) are a robot in five files: `Robot.java`, `Tunables.java`, `Controls.java`, `Actions.java` and an `autos` folder ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/) explains them). Some have extra files: a finder that knows the robot (`lessonbot/DriveTuner.java`, `odometrybot/OdometryTuner.java`, `turretbot/HoodFinder.java` and `ShotTuner.java`), or Pedro's numbers (`pedrobot/PedroConstants.java`). Copy them with the rest. ## Your robot looks like this: start from that | Your robot looks like... | Start from | What it has | | --- | --- | --- | | **anything, and its configuration is on the Driver Station** | `./gradlew :sim:newRobot` ([Blank slate, way A](https://crossbotics.com/ftc-helper/docs/pick-your-start/03-blank-slate/#way-a-from-your-configuration)) | five files made for you from your configuration, with each part's line and TODO marks, and every setting in `Tunables.java` as `DEFAULT` or `MEASURE` ([the two words](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)) | | a mecanum drive and an intake, no configuration yet | [`quickstart`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/quickstart) ([Blank slate, way B](https://crossbotics.com/ftc-helper/docs/pick-your-start/03-blank-slate/#way-b-copy-the-smallest-files)) | the smallest robot, with STEP marks on every line to change | | a mecanum drive, an intake, a lift and a claw | [`lessonbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/lessonbot) | the example robot of The five files and Add to your robot, and its Drive Tuner | | **goBILDA's FTC StarterBot** (BIOBUZZ) | [`gobildabot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/gobildabot) | tank drive, intake with two corner wheels, flywheel and "windmill" feeder; goBILDA's own names | | **goBILDA's FTC StarterBot with Mecanum Wheels** (BIOBUZZ, Strafer chassis) | [`gobildastraferbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/gobildastraferbot) | mecanum drive, intake with two corner wheels, flywheel and "windmill" feeder; goBILDA's own names | | **REV's DUO FTC Starter Bot** (BIOBUZZ) | [`revbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/revbot) | tank drive, intake, flywheel and CR-servo feeder, the pollen pusher ("poker"); REV's own names | | **AndyMark's Robits BIOBUZZ StarterBot** | [`andymarkbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/andymarkbot) | tank drive, roller intake, the catapult (see the note below); AndyMark's own names | | **Studica's FTC Starter Bot** (BIOBUZZ) | [`studicabot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/studicabot) | tank drive, intake, flywheel and servo flap (see the note below); Studica's own names | | a tank drive and a flywheel shooter | [`flywheelbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/flywheelbot) | intake on from the start, a deploy servo, a flywheel the driver speeds up and down, a servo feeder, a webcam and whole-robot aim (no turret) | | a mecanum drive with a turret and a camera | [`turretbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/turretbot) | a Limelight that the turret follows, speed and hood angle from distance with a POLLEN and a NECTAR table (a hood servo, Hood Finder), a buzz when on target, a folding claw, a Shot Tuner ([Add a launcher](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/)) | | a turret shooter AND a lift with a wrist and a claw (two parts that share space) | [`v2bot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/v2bot) | team 8938's 2026-27 designs: a turret on a magnetic home switch (+/-190 degrees), a hood, odometry, a piece count, a Viper-Slide lift with a wrist and a claw, the lifter's steps as actions, and an [interlock rule](https://crossbotics.com/ftc-helper/docs/guides/interlocks/) that keeps the turret out of the back while the wrist holds the claw low behind the robot | | a mecanum drive with odometry (Pinpoint, OTOS or dead wheels) | [`odometrybot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/odometrybot) | `driveTo` field points, the Odometry Tuner ([Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/)) | | a mecanum drive with odometry and Pedro Pathing | [`pedrobot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/pedrobot) | `odometrybot` plus paths ([Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/)); add Pedro to the project first ([Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/#your-project-add-the-pedro-add-on-once)) | | you already use the older six-file starter kit | [`starter`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/starter) ([Starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/)) | `EasyTeleOp` and `EasyAuto`; kept for teams that use it. New teams: use a row above | **If you are not sure:** use `:sim:newRobot` if your configuration is ready, and `quickstart` if it is not. You can copy single lines from the other templates later (for example the launcher line from `flywheelbot`). **The kit bots** use the same configuration names as each seller's own code, so the files run on that kit as it is. Where each number comes from, and what each kit bot's code does differently (buttons, guessed numbers): [The BIOBUZZ starter bots](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/) ([REV](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#rev-bot-code), [goBILDA](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#gobilda-bot-code), [AndyMark](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#andymark-bot-code), [Studica](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#studica-bot-code)). Two kit mechanisms are not parts of the library, so their templates use the closest part and say so in `Robot.java`: - **AndyMark's catapult:** the library has no catapult. The template drives its motor as an `Indexer` that runs for a set time per press. Tune that time so one press is one throw. The library cannot tell when the catapult is wound, so it cannot wait for "ready" as a flywheel does. - **Studica's flywheel:** the launcher cannot take the 2:1 gear between the motor and the wheels. The flywheel speed in `Tunables.java` is the motor's (the wheels turn at half of it). Tune it by watching shots. The Maverick motors and the servo are not in the parts catalog: `Robot.java` describes them with Studica's numbers ([Parts not in the catalog](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-in-the-catalog)). ## Copy a template into TeamCode If you used `:sim:newRobot`, skip this part: it writes the files into TeamCode for you. For every other template, follow [Copy example files into TeamCode](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/): the `package` lines, the imports, the `@Disabled` lines and the OpMode names. Then build. Check the motor directions with the wheels off the ground ([Robot.java](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/)). Check every part with the Hardware Check: [Check the hardware](https://crossbotics.com/ftc-helper/docs/tutorials/19-testing-procedures/). **Numbers:** every number in `Tunables.java` is a starting value. Find the real ones with the [finders](https://crossbotics.com/ftc-helper/docs/tuning/). The hub saves a number you change live on the robot (in the tuning menu). It keeps using that saved value, even after you edit the number in `Tunables.java`, and another hub does not have it. So copy each new value back into `Tunables.java`. INIT lists the values that differ. **Try it first in the simulator.** The kit bots have robot files. Run one, then pick "REV Bot TeleOp" ([Simulator guide](https://crossbotics.com/ftc-helper/docs/simulator/)). `-PteamCode=none` runs the **library's** example, not your copy. **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) `./gradlew :sim:run -Probot=sim/robots/starter-bot-rev.properties -PteamCode=none` **Your copy in the simulator.** Run your TeamCode with the kit's measured robot file: **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) `./gradlew :sim:run -Probot=sim/robots/starter-bot-rev.properties -PteamCode=../TeamCode` You can also copy that file to `simulator/robot.properties` in your robot project. Then you do not need `-Probot`. Use the kit's file. A file from `:sim:fromRobot` guesses an 18 x 18 in robot. Then the REV, AndyMark and Studica bots start "overlapping the field wall" on BLUE. **What the simulator cannot show yet** (so you know the problem is not in your copy): - The REV, AndyMark and Studica bots do not shoot in the simulator: their robot files have no shot line. Their flywheels may also never say `READY`, because the example speeds are higher than the simulated motor reaches. Tune the speed on the real robot. - An autonomous whose `start(...)` gives no spot (only a note and a heading) starts where the last program left the robot. Press **Back to start** (Control Hub panel, Robot tab) before you run it. - Some INIT lines are normal in the simulator: `!! Drive not tuned: runs in the simulator only` (on the robot, the autonomous waits for the Drive Tuner), a turret's `Turret : no angle from a program before: ...` (turn it to its start angle on the robot), and a camera's `limelight lighting : trying ...` until it sees a tag. ## Next [The five files](https://crossbotics.com/ftc-helper/docs/five-files/): what each file is for. Then [Add to your robot](https://crossbotics.com/ftc-helper/docs/add-to-robot/): one page per part. --- # Tests URL: https://crossbotics.com/ftc-helper/docs/tests/ A test asks one of two questions: - **Is my robot code right?** A simulator test drives your robot on the laptop and checks the result. It finds a break you did not mean to make: a typo, a wrong button, a number in the wrong section. - **Is my robot right?** A check on the real robot finds a loose cable, a reversed motor, a flat battery or a wrong setting before a match. ![Two kinds of tests: simulator tests on the laptop check the robot code (pages 1 and 2); checks on the real robot check the robot (page 3)](https://crossbotics.com/ftc-helper/docs/images/tests-two-questions.svg) | # | Page | You learn | Use it | | --- | --- | --- | --- | | 1 | [Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/) | Record a test in the simulator, read it line by line, set how close is close enough, and update it after a planned change. | when your robot drives and has an autonomous | | 2 | [Run all your tests](https://crossbotics.com/ftc-helper/docs/tests/02-run-all-your-tests/) | Run every test with one button or one command. For programmers: laptop tests in Java. | after every code change, and before you commit | | 3 | [Checks before practice and matches](https://crossbotics.com/ftc-helper/docs/tests/03-checks-before-practice-and-matches/) | A fixed order of checks on the real robot, printable checklists, and what to do when something breaks. | after wiring, after a mechanism change, before practice, and before every match | **Why both:** a simulator test cannot find a loose cable, and a check on the robot cannot find a break in code that you did not run. Do both. --- **Next:** [Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/). --- # Troubleshooting URL: https://crossbotics.com/ftc-helper/docs/troubleshooting/ ## Build problems **Project directory '.../ftc-helper-lib/library' does not exist** The submodule folder is empty: someone cloned the project (copied it from GitHub) without the library in it. Run this command. **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash git submodule update --init ``` **Cannot resolve symbol 'crossbotics' / red imports** Gradle does not know about the library yet. Check steps 2 and 3 in [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/), then **File > Sync Project with Gradle Files**. **Plugin [id: 'com.android.library'] was not found** Your project's top `build.gradle` (the one in the project folder, not in TeamCode) must list the Android library plugin. Every FtcRobotController project does (`id 'com.android.library' version '...' apply false`). If yours is very old, update the SDK. **Errors in the library after an FTC SDK update** See [A new FTC SDK version](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/#a-new-ftc-sdk-version). ## Driver Station errors **INIT STOPPED: the robot did not start.** The library found a mistake at INIT. The line under it says what is wrong and how to fix it: find it below. Nothing moves. Press STOP, fix it, then press INIT again. (After ▶ on the Driver Hub, a mistake shows after every part has stopped. It shows as the FTC app's red line, User code threw an uncaught exception: .... The words after the dash are the same messages as below.) A mistake in your own code (not a library message) shows its kind and where it is. For example: NullPointerException in Robot.java line 42. Open that line. **No DcMotorEx named "..." in the active robot configuration** - or No Servo named "intake_deploy" ... The name in code and the name in the Driver Station configuration differ. The message lists the names that do exist. Fix the spelling, or pick the right configuration on the Driver Station. **When the part is not on the robot yet,** the message ends Not on the robot yet? Add .optional() ... Add `.optional()` to its line in Robot.java. Then INIT goes on and says the part is off. Its buttons and actions skip it until it is in the configuration ([parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)). The [Hardware Check](https://crossbotics.com/ftc-helper/docs/modules/testing/#hardwarecheckopmode) with `robot()` lists every Robot.java device the configuration is missing. **libraryButtons: Two library features are on G1 BACK: "pause / go on" and "debug lines". A button can do only one. ...** - or Two hold-down library features are on ... - or G1 LT is the slow trigger, and also ... - or G1 A cannot open the tuning menu ... In `libraryButtons(...)` in Controls.java, you moved one of the library's features onto a button that already has one. The message ends with the line to change: move that feature to a free button (`lib.debug(g1.start, null)`), or turn it off with `null` (`lib.debug(null, null)`). [Moving the library's buttons](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/). **Tunables.Lift has no max: write max (the top of the safe range, in counts: Motor Finder, B). A safety limit never comes from a library default.** - or has no min - or Tunables.java has no Lift section - or the same for Arm, in deg INIT stops on purpose: a lift or arm must never use a library default for its safe range. Run the [Motor Finder](https://crossbotics.com/ftc-helper/docs/tuning/), then write `min` and `max` in that section of `Tunables.java`. **Tunables.Lift.max must be a public static number (like "public static double max = 1000;"): ...** The field is there but written another way: not `public`, or not a number (for example a `String`). Write it exactly like `public static double max = 2900;`. (Without `static`, it counts as missing: you get has no max instead.) **Tunables.Lift: max (...) must be more than min (...)** The two numbers are swapped or equal. `max` is the top of the safe range, `min` the bottom. **Tunables.Lift.Max looks like "max" (capitals and spelling count). Fix the name in Tunables.java; a position must not look like a setting.** A field name is a known setting with other capitals or an `_` (`Max`, `MAX`, `MIN`, `kp`, `KP`, `k_P`): INIT always stops on this. INIT also stops on a name up to two letters off a setting (`maxPowr`, `maxPwr` for `maxPower`) that the section does not write itself. (`slowZone2` next to a written `slowZone` is a position, not a typo.) Without this stop, the field would quietly become a named position, and the real setting would stay the library's default. Fix the spelling. If it is a position on purpose, give it a name that does not look like a setting. The known names: [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/). **Tunables.Intake.inPowr is not a setting of Intake (did you mean inPower?): the robot would quietly ignore it. ...** - or the same for any part: Tunables.Aim.goalx, Tunables.Launcher.nominalVolt, Tunables.TurretLift.turetFrom A field in that section is not a name the part reads: a typo, other capitals, or a leftover from an older robot. Before, the library quietly skipped the line, and the part used its default. Fix the name (the "did you mean" is the closest real one. Known: lists them all, and so does the [Tunables reference](https://crossbotics.com/ftc-helper/docs/reference/tunables/)), or delete the line. A number you keep for your own code goes in a section of your own (a name no part uses). An autonomous's distances go in its steps, not in `Tunables.java` ([why](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#the-numbers-are-in-the-step)). **!! Tunables.Launcher is not read by any part: your launcher's section is Tunables.Shooter (its device name "shooter" in CamelCase). Move the numbers there** A part reads the section named after its DEVICE (its configuration name in CamelCase), not after its kind: `Launcher.flywheel("shooter", ...)` reads `Tunables.Shooter`, `Indexer.servo("feeder")` reads `Tunables.Feeder`, `Lift.slide("lift_left")` reads `Tunables.LiftLeft`. Until you move the numbers, the part uses the library's defaults. (INIT also says did you mean Tunables.LiftLeft? for a section spelled almost like a part's.) An interlock rule's fields follow the same name: `liftLeftAbove`, not `liftAbove`. **The interlock line says ... held ...: Turret angle unknown (...)** The library does not know the other part's position yet (a turret looking for its home switch, a servo turret before ▶). So it counts that part as maybe in its zone, and this part waits. It goes on by itself when the angle is known. **AutoDriveConfig.calibrationConfirmed is false** - or AUTONOMOUS IS OFF: the drive is not tuned yet (EasyAuto, Auto) The autonomous stops on purpose: a robot with untuned numbers can drive much too far. Tune `AutoDrive`, then set it to `true`: [Tune AutoDrive](https://crossbotics.com/ftc-helper/docs/modules/drive/#tune-autodrive). With the robot in five files, run the Drive Tuner, then set `Tunables.Drive.calibrated = true`. ## Warnings on the Driver Station (!! ... at the top) | Warning | Meaning | | --- | --- | | lift: push it DOWN to the switch to home it | homing (finding where 0 is): drive it down to the switch once | | lift: no switch "lift_bottom" in the configuration | the switch name is wrong or missing: it runs without the switch | | claw: no position called "OPNE" | a typo in a position name: the library ignored the command | | homing failed: switch not found (turret) | the switch never closed: wire, magnet gap, or the wrong direction in `home(...)` | | follower encoder not reading: follower switched off (flywheel) | the second flywheel motor has no encoder cable: plug it in (or use one motor) | | Launcher gave up: flywheel (or hood, Turret...) | it was not ready in time: that part is the problem | | Launcher: defaults from the catalog (gobilda-5203-6000): kF 11.7, kP 1.17, ... | normal on a first run: with no gains written, it starts from the motor's catalog numbers. The wheel gets to speed, but slower after each shot than when tuned: run the [Flywheel Finder](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/) and write its line ([First run](https://crossbotics.com/ftc-helper/docs/reference/tunables/#first-run-what-you-get-before-tuning)) | | Aim odometry: the pose was never set ... | TeleOp ran without autonomous, so the robot does not know where it is: aiming uses the camera only. Run autonomous first, or park on the reset spot and hold gamepad 1 START 1 s ("set pose here", `Tunables.Odometry.resetX, resetY, resetHeading`; [Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/#teleop-starts-where-autonomous-ended)) | | No reset spot: add resetX, resetY, resetHeading to Tunables.Odometry | someone held gamepad 1 START 1 s ("set pose here"), but `Tunables.Odometry` has no spot: add the three numbers (inches and degrees from your wall, for BLUE) | | Alliance now RED (was BLUE) | the alliance switch is on (`lib.switchAlliance(...)`) and someone held gamepad 1 START, then BACK, 1.5 s: the alliance switched. Hold them again to switch back ([ControlMap](https://crossbotics.com/ftc-helper/docs/reference/controls/#controlmap)) | | Alliance now RED: odometry aim OFF until the pose is set (...) | someone switched the alliance on a turned field (`mirrorForRed = false`): the library cannot fix the pose from autonomous. Park on the reset spot and hold gamepad 1 START 1 s ([buttons guide](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/#switching-the-alliance-in-teleop)) | | Set pose here needs odometry: ... | someone held gamepad 1 START 1 s, but the robot has no `odometry(...)` line in Robot.java, so it cannot know where it is ([Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/)). Nothing changed | | Launcher : WAITING_READY left 1 waits for: turret aimed | the launcher holds the piece until that check is true (here: the turret on the goal). Launcher gave up: ... shows for 5 s when it waited too long | | Pose NOT set: stop first ... | someone held "set pose here" while the robot drove (a drive stick pushed) or whole-robot aim was on. Stop, then hold gamepad 1 START 1 s again | | No pause button (libraryButtons freed it): ... | `lib.pause(null)` in `libraryButtons`: nothing pauses the robot. Put it on a button: `lib.pause(g1.back)` | | No slow button (libraryButtons freed it): ... | `lib.slow(null)` with no `slow()` of your own: add one, for example `g1.rt.slow()` | | COMPETITION: "intake_deploy" not in the configuration: IntakeDeploy is OFF (optional part). On the robot? ... | the same as the note below, loud because the COMPETITION profile is on: at an event, a part that is off is most likely a misspelled or lost configuration name. Fix the name (or plug it in) and INIT again. If the part is not built yet, it is safe to play | | "intake_deploy" not in the configuration: IntakeDeploy is off (optional part) | a note, not a problem: the part is marked `optional()` and not on the robot yet. The library skips its commands, buttons (- off: ... not on the robot on the map) and action steps. When you plug it in, add it to the configuration and INIT again ([parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | | Launcher: battery 11.2 V: low. The flywheel gets back to speed slower: charge or swap it | swap in a charged battery: the wheel gets back to speed slower, so shots wait longer | | Aim odometry: ... more than the field allows / Aim: camera says ... odometry ... | the pose is wrong or drifted, or `Tunables.Aim.goalX, goalY` are not where the camera measures to | | goal out of turret range (behind the robot: holding) | the goal is behind the robot: turn the robot toward it | | PRACTICE profile | set COMPETITION at events | | N tuned value(s) differ from the code | the hub uses saved tuning values: copy them into the code, then reset | | ... button job took N ms: the whole robot stopped that long. ... or a button job took N ms: ... | a button job waited: see "A job took N ms" under [Robot behavior](#robot-behavior) | | Lift update took N ms: update() must not wait or sleep | a part's `update()` took more than 25 ms: no wait or `sleep()` in `update()`. It goes away 5 s after the last slow update | | intake_color: not found: no color sensor called ... (or distance sensor) | a piece sensor's name is not in the robot configuration: it sees nothing, and Pieces counts nothing with it. Fix the name | | huskylens: not answering: check the cable... | the HuskyLens does not answer on I2C (with a loose cable or its Protocol Type on UART). Check the cable (its green wire goes to the hub's white wire on a home-made cable), and in its General Settings set Protocol Type to I2C or Auto Detect | | huskylens sees a tag but `target(34)` is null | it says only the number you taught it. Add `.tag(taughtNumber, 34)`, or teach that tag ([how](https://crossbotics.com/ftc-helper/docs/modules/vision/#huskylenscamera)) | | ready_color: no new reading for N s | a piece sensor (or its camera) stopped answering: a loose cable, or a camera that stopped streaming. It sees nothing until readings come back | | Intake: held back by stopsWhen for N s (the count says full) | the piece count says full. If it is not full, hold the in-button (RT) 1 s to pull in anyway, or hold G2's left stick button 1 s: count = 0 ([Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/)) | **EasyTeleOp needs your robot settings** - or EasyAuto needs your robot settings Add `robotConfig()` to the OpMode: `return new RobotSettings();` (starter kit) or `return RobotSettings.config();` (tutorials). See [RobotConfig](https://crossbotics.com/ftc-helper/docs/modules/core/#robotconfig). **Autonomous needs the IMU (turn sensor)** `RobotSettings.imu()` returned null. Return `ImuSetup.get(...)` there: every Control Hub has an IMU. ## Robot behavior **A lift or arm runs past its stop, never stops, or does not move; the flywheel never gets to speed; the robot drives the wrong distance** The encoder count is wrong: its cable is missing, in another motor's port, or counting backward. Run the [Encoder Check](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#encoder-check-each-encoder-cable-in-its-own-port) (Tune and check) with the robot on a block. It names the fault for each motor: | The Encoder Check says | Fix | | --- | --- | | NO COUNTS: encoder cable missing? | plug in the encoder cable, or replace it | | counts on "X" instead: encoder cables swapped? | put each encoder cable in its own motor's port | | counts on "lift_right" instead: plug the encoder cable into "lift_left"'s port | a two-motor lift: the library reads only the first motor's encoder. Move the cable | | counts BACKWARD | the motor's power wires are swapped (red and black), or an outside encoder is mounted the other way | **A route says Park: stopped: a drive stick moved, or it never seems to start** Any drive stick stops a TeleOp route at once. A route that a time starts waits 5 s for the driver to let go of the sticks, and the gamepad buzzes. If the Driver Station says Park: not started: ..., the words say why: [the table](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes). **A route or `routeTo` says STALLED, or the robot touches a box on the way** The pose is wrong, the box is too small, or the margin is too small. Compare the `Pose` line with where the robot is on the field. Then measure the box again, or make the margin bigger ([what the margin is](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes)). Another robot in the way also stops it: a route cannot see robots. A spot closer to a wall than half your robot also ends this way: the robot presses the wall. **INIT stops: ... is on "..." or ... a robot cannot drive in from outside** The spot you gave `routeTo` or `route` is on a box, or other boxes close every way to it. Move the spot. For the second one, a smaller margin in `fieldMap(...)` can also help. **A part does nothing on its buttons, and INIT says Intake: usual buttons not in Controls.java: ...** Since v0.39.0 a part has no buttons until `Controls.java` has its lines. Copy the part's lines from its "buttons to add" in the [reference](https://crossbotics.com/ftc-helper/docs/reference/robot-java/) (for example [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/#buttons-to-add)) into `buttons(...)`. If a button that line wants is already in use, put the part's job on a free one (INIT lists them: G2 free: ...). **A servo turns less than its seller says (a goBILDA 2000 servo: about 270 degrees, not 300)** The hub sends 600 to 2400 microseconds for positions 0 to 1 (the FTC SDK's normal range). The servo's full turn needs 500 to 2500. Add `.fullRange()` to the part in Robot.java (`ServoSetup...fullRange()` or `PositionServo...fullRange()` without the five files). Then measure its positions again: they move when the range changes ([Full range](https://crossbotics.com/ftc-helper/docs/modules/hardware/#full-range)). INIT says cannot change its pulse range for a servo that is not on a REV hub. **My servo positions are off after adding (or removing) `.fullRange()`** You measure positions for one pulse range. Find them again with the Servo Finder (Y while choosing the servo = full range) or the Hood Finder, and copy the new numbers into `Tunables.java`. **Every shot is a little short (or long) today** The wheel is worn, the balls are softer, or the battery is lower than when you tuned. In the match: the operator's D-pad up/down trims every shot speed by 1% (Speed trim : +3% on the Driver Station). Held, it makes 4 steps a second. A double-tap on D-pad down sets it to 0. If it happens every match, the table is off. Multiply its speeds by the trim (or tune it again with the Shot Tuner), and copy the new line into `Tunables.java` ([Add a launcher](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/#speed-trim-and-a-low-battery)). Battery compensation is off by default (nobody has proven it on a robot yet). To try it, read [Add a launcher: speed trim and a low battery](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/#speed-trim-and-a-low-battery). **In an autonomous move the robot turns and stops short (in the simulator or on the field)** A corner touched a wall or a field part, and the robot pivoted on it. `move(...)` drives straight and does not turn by itself. Look at the start spot. On BIOBUZZ's field, a FLOWER stands against your wall about 20 to 27 in right of the center line. A spot at x 36 is only 0.3 in from it, so a move to the left drives into it. Start farther away (the example robots use x 44 to 48), or drive forward first. In the simulator, the robot box turns red on a bump, and a scenario can check `expect bumped none` ([having multiple autos](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/)). **The robot paused when I used the gamepad's START + BACK** (the debug lines, or the alliance switch) You pressed BACK first. BACK is the pause button, and it pauses the moment it goes down. Pressing START after it does not undo that, so you get a plain pause (and no debug lines or switch). Tap BACK to go on. Next time **hold START first, then press BACK** ([Move the library's buttons](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/)). **Y does nothing (no field-centric) in an EasyTeleOp** Field-centric needs mecanum wheels and the IMU. A tank drivetrain, or `imu()` returning null, keeps it off on purpose. **Field-centric "forward" is wrong at the start of TeleOp** The robot did not start autonomous facing straight away from its driver. Set `startHeadingDeg()` in the autonomous (written for BLUE), or press BACK after turning the robot to face away from you. In a Controls.java TeleOp with field-centric on, hold BACK for 1 s: the press pauses the robot, and the hold also resets "forward". Tap BACK again to go on. **The robot drives diagonally, spins, or a wheel fights the others** A motor direction or a motor name is wrong. [Check motor directions](https://crossbotics.com/ftc-helper/docs/modules/drive/#check-motor-directions). **Pushing the stick up drives backward** You forgot the minus: forward is `-gamepad1.left_stick_y`. (The gamepad reports stick up as a negative number.) With the robot in five files, every direction is flipped: reverse the other side ([Wiring checks](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#motor-direction-check-each-wheel-rolls-forward)). **Field-centric goes the wrong way** 1. The IMU orientation (logo/USB) does not match the hub on the robot ([ImuSetup](https://crossbotics.com/ftc-helper/docs/modules/hardware/#imusetup)). 2. The heading was not 0 while facing away from the driver. Point the robot away and press your reset button. **A button action runs over and over** - In `Controls.java`: the job is a `hold(...)` (every loop while held) where you wanted `press(...)` (once per press). - Old style (`ControllerBindings`): `bindHold` where you wanted `bindPress`. **A button does nothing** - In `Controls.java`: check that it is on the right gamepad (`g1` = the driver, `g2` = the operator). - Check whether it is a hold where you pressed (or a press you hold). `heldFor(1.0, ...)` needs 1 s. A `tap` waits to know it is not a double-tap. - When you held it through ▶ (or while the tuning menu closed), let it go and press again. - When the robot is paused (PAUSED on the screen), tap BACK. - Old style (`ControllerBindings`): check that `controls.update(gamepad1, gamepad2)` is in the loop, and that it is the right pad (`Pad.G1` = gamepad1, `Pad.G2` = gamepad2). After `ignoreHeldButtons`, let it go and press again. **A job took N ms: the whole robot stopped that long** A button job has a `sleep()` or a `while` loop that waits (the library reports a job over 20 ms). The program does one thing at a time: while the job waits, nothing else runs, not even driving. Fix: make the steps an [Action](https://crossbotics.com/ftc-helper/docs/reference/steps/#action) and wait with `waitSeconds(...)` (the robot keeps running while it waits). Without the five files: set a target or a state and let the loop do the work ([Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/)). **The robot freezes when I press a button** An action has a `sleep()` or a waiting loop. Actions must be quick. **Why:** the program does one thing at a time, so while it waits, nothing else runs (not even driving). Set a target or a state variable instead and let the loop do the work ([Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/)). **A lift only goes down, and slowly, at the start** It is not homed yet (it has not found where 0 is). Push it down until the lower switch is pressed. Then it works normally. See [Homing](https://crossbotics.com/ftc-helper/docs/modules/safety/#homing-with-a-lower-switch). **A lift will not move** - `getAppliedPower()` is 0 while you push the stick: a limit stopped it. Check `getPosition()` and your limits. It may think it is at the bottom or top. - You turned the motor on with the lift half up, so 0 is in the wrong place. Lower it and restart, or use a lower limit switch for homing. - The motor direction is wrong (positive power must go up). Check with a low power. **The lift stops early or goes past the top** Re-measure the top position with `lift.getPosition()` on telemetry. A slipping belt or string changes the count: add a lower limit switch so it re-zeroes each time it reaches the bottom. **AutoDrive moves the wrong distance** Tune `wheelDiameterIn` and `strafeCorrection`: [Tune AutoDrive](https://crossbotics.com/ftc-helper/docs/modules/drive/#tune-autodrive). **An autonomous move stops past its end (short moves most, or fast ones)** A robot slides a little when it brakes, and a faster one slides further. There are two fixes. Run the [Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/) at the power your moves use (D-pad left/right on its test list). Also set `Tunables.Drive.slowDownIn = 6`, so every move slows down over its last 6 in ([tunables](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava)). Then a short move reaches the end as slowly as a long one. If it still goes past by the same amount every time, shorten that move by that amount. **AutoDrive turns overshoot or stop short** Overshoot: raise `turnKd` or lower `turnKp`. Stop short: raise `turnKp` a little or set `turnMinPower`. The [Move Tuner](https://crossbotics.com/ftc-helper/docs/tuning/10-move-tuner/) measures the turns and finds these numbers for you. **AutoDrive stops early with "robot stuck"** It was blocked, or it moved too slowly. If it was not blocked, raise `moveMinPower` or `stallTimeSec`. **The loop is slow (telemetry shows under ~30 Hz, that is, under 30 loops per second)** Turn on [bulk reads](https://crossbotics.com/ftc-helper/docs/modules/hardware/#bulkreads), send fewer telemetry lines, and remove any `sleep()`. ### My JUnit tests time out or never fire, but only when run together A test used a pretend clock (`PretendClock.use()`) and did not give the real clock back. Time then stands still for every later test. Fix: put `PretendClock.stopUsing()` in that test class's `@After` method ([PretendClock](https://crossbotics.com/ftc-helper/docs/modules/testkit/#pretendclock)). ## Autonomous choice and git problems **The robot ran the wrong autonomous plan, or started in the wrong place** The first option of each INIT menu line runs when nobody changes it. The "Place robot" note says where the robot must stand. Read the menu and the note out loud before ▶: [match day checklist](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/). **An INIT menu option does nothing** The option is spelled differently in `menuChoice(...)` and in `onlyIf(...)` (capitals count). Test each option in the simulator: [Scenario files](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/). **modified: ftc-helper-lib (new commits) in `git status`** Your library folder is at another version than the project expects. If you did not mean to update it, run `git submodule update` in the project folder. See [Keep it up to date](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/#after-a-teammate-updates-it). **The build broke after a library update** Read the CHANGELOG's **Changed** list, or go back to the old version: [Go back to the old version](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/#go-back-to-the-old-version). **'git' is not recognized (Windows)** - or git: command not found The Terminal cannot find git. GitHub Desktop does not fix this: it keeps its own git, and only GitHub Desktop can use that one. 1. Install Git for Windows from [git-scm.com/downloads/win](https://git-scm.com/downloads/win). On the page "Adjusting your PATH environment", keep **Git from the command line and also from 3rd-party software** (the recommended choice). The other choices are fine as they are. 2. Close Android Studio fully and open it again. A Terminal that was open before the install does not see git. 3. Type `git --version` in the Terminal. It prints git version 2... when it works. 4. If it is still not recognized, add git to the PATH (the list of folders Windows looks in for commands) by hand. You need no administrator for this. 1. Find the folder that has `git.exe` in it: `C:\Program Files\Git\cmd`, or `C:\Users\YOUR-NAME\AppData\Local\Programs\Git\cmd` when you installed Git for one user only. 2. Press the Windows key, type `environment`, and open **Edit environment variables for your account**. 3. Select **Path**, then **Edit**, then **New**. Paste the folder from step 1. Click **OK**, then **OK**. 4. Close Android Studio fully, open it again, and do step 3 again. **rejected, CONFLICT, divergent branches or another git message** See [Git and GitHub: problems](https://crossbotics.com/ftc-helper/docs/guides/github/#problems). ## Get more help Write down what you did, what you expected and what happened, and ask the programming lead. If it is a library bug, add a failing test for it: [Contributing](https://crossbotics.com/ftc-helper/docs/contributing/). --- # Writing style for the docs URL: https://crossbotics.com/ftc-helper/docs/writing-style/ Every page in `docs/` follows these rules. Our readers are high-school students, many with little Java and some with English as a second language. The rules come from ASD-STE100 Simplified Technical English and from [stop-slop](https://github.com/hardikpandya/stop-slop). Code comments follow [Commenting style](https://crossbotics.com/ftc-helper/docs/commenting-style/). Finished examples: [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/) and [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/). ## Words - **US English:** color, center, gray, meter, canceled, catalog, license. - **Plain words.** A technical word gets a short explanation the first time a page uses it: "a pipeline (a set of camera settings you save on the Limelight by number)". - **No filler words:** just, really, simply, actually, basically, easily, quickly, of course. - **No vague extremes.** Write "always", "never" or "every" only when it is an exact fact. Not "rarely": write when (for example, "only for a special case"). - **No time estimates** ("10 minutes", "about an hour"). - **Measure from edges, parts, photos or the catalog,** never from the robot's center. ## Sentences - **Short sentences.** One idea per sentence, about 20 words or fewer. - **Active voice.** Name who does it: "the camera reads them at INIT", not "they are read at INIT". The reader is "you". - **Instructions are commands:** "Press INIT." "Copy the two lines." - **Why before how.** Say what a thing is for before you use its name, and what problem a step fixes before the step. - **No questions as labels.** "**With one driver:**", not "**One driver?**". - **No announcements.** Cut "this page has three tables", "here is how", "let's look at". Start with the fact. - **No "not X, it is Y".** Say what it is. - **No em dashes (—).** Use a colon, a comma or a new sentence. In a table, an empty cell is "-". ## Pages - A **"Where:"** line above every command: which terminal, which folder. - Walkthrough pages (setup, pick your start, the five files, building autos) end with **Done when**, **Next** and **Look it up**. - Reference pages start with one line on what the part is, then the tables. No intro text. - A table's question column is "What it tells you", and its cells start with "whether" for a true/false. ## What never changes in a style pass - Code blocks, inline code, and `` and `` markers (tools check them). - Heading text: other pages link to it. - Link targets, numbers and facts. A fact that looks wrong goes to the mentor; do not fix it in a style pass. --- # Set up: the tools and the library URL: https://crossbotics.com/ftc-helper/docs/setup/ **Set up gets the base system ready. It writes no robot code yet.** It installs Android Studio, gets the robot project, adds the library, updates the hubs and makes the robot configuration. After it, you **start using the library**: pick the code you start from, then work through the five robot files. Do these pages in order, once. Each page is one job and ends with **Done when**. If you already did a page, check its "Done when" and go on to the next. | # | Page | Who | | --- | --- | --- | | 1 | [Before you start](https://crossbotics.com/ftc-helper/docs/setup/01-before-you-start/) | everyone | | 2 | [Install Android Studio](https://crossbotics.com/ftc-helper/docs/setup/02-android-studio/) | each laptop | | 3 | [GitHub and the robot project](https://crossbotics.com/ftc-helper/docs/setup/03-github-and-the-project/) | each laptop | | 4 | [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/) | once per project (a mentor or code lead) | | 5 | [Update the hubs](https://crossbotics.com/ftc-helper/docs/setup/05-update-the-hubs/) | once a season | | 6 | [Build and install](https://crossbotics.com/ftc-helper/docs/setup/06-build-and-install/) | each laptop | | 7 | [Make the robot configuration](https://crossbotics.com/ftc-helper/docs/setup/07-robot-configuration/) | once per robot | | 8 | [Every practice: pull, change, commit, push](https://crossbotics.com/ftc-helper/docs/setup/08-every-practice/) | everyone | | 9 | [The Terminal](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/) | when a page gives you a command | ![The setup pages in order: 1 Before you start, 2 Android Studio, 3 GitHub and the project, 4 Add the library, then 5 Update the hubs, 6 Build and install, 7 Configuration, which need the robot's hubs, then 8 Every practice. Only using the simulator: skip from 4 to 8. Page 9, the Terminal, is for when a page gives you a command.](https://crossbotics.com/ftc-helper/docs/images/setup-path.svg) **If you use only the simulator on this laptop:** skip pages 5, 6 and 7. They need the hubs. **After Set up:** start using the library. Pick the code you start from: [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/). **Next:** [Before you start](https://crossbotics.com/ftc-helper/docs/setup/01-before-you-start/). --- # Set up 1: before you start URL: https://crossbotics.com/ftc-helper/docs/setup/01-before-you-start/ ## What you need - A laptop (Mac or Windows) with internet. - A **Control Hub** and a **Driver Hub** (or an Android phone with the Driver Station app). - A USB-C cable for the Control Hub. - A gamepad. - A free **GitHub account**, for each student who changes code. GitHub's rules say you must be 13 or older. **If you use only the simulator,** you need only the laptop and a GitHub account. The simulator is a pretend robot on the laptop. ## How the pieces connect ![The laptop runs Android Studio and installs the app on the Control Hub by USB cable or Wi-Fi. The Control Hub runs the Robot Controller app with your code; motors, servos and sensors plug into it. The Driver Hub runs the Driver Station and talks to the Control Hub by Wi-Fi; the gamepads plug into it. The simulator is a pretend robot on the laptop and needs no hubs.](https://crossbotics.com/ftc-helper/docs/images/setup-hubs.svg) ## The words You meet these words on every page of these docs. | Word | Means | | --- | --- | | **Control Hub** | The robot's computer (made by REV). Motors, servos and sensors plug into it. | | **Driver Hub** | The device the drive team holds. It runs the **Driver Station** app. The gamepads plug into it. | | **Robot Controller app** | The app on the Control Hub. Your code is part of it. | | **Robot project** | The folder of code that becomes the Robot Controller app. Its name is `FtcRobotController`. | | **TeamCode** | The folder in the robot project where your team's code goes. | | **Robot configuration** | The list of motors, servos and sensors on the robot, each with a name. Your code finds each part by its name. | | **OpMode** | One program you pick on the Driver Hub. | | **TeleOp** | An OpMode that people drive with gamepads. | | **Autonomous** | An OpMode that runs on its own at the start of a match. | | **INIT, ▶, STOP** | The Driver Hub's buttons. INIT gets ready (nothing may move). ▶ starts. STOP ends. | | **Android Studio** | The program on the laptop where you write and build the code. | | **Git, GitHub** | Git keeps every saved version of the code. GitHub keeps a copy online, so the team can share it. | | **The library** | ftc-helper-lib: ready-made code for drives, lifts, buttons and autonomous steps. | ## Done when You have the hardware above, and each student who codes has a GitHub account. **Next:** [Install Android Studio](https://crossbotics.com/ftc-helper/docs/setup/02-android-studio/). **Look it up:** [How it all fits together](https://crossbotics.com/ftc-helper/docs/guides/architecture/) and [Git and GitHub for FTC teams](https://crossbotics.com/ftc-helper/docs/guides/github/). --- # Set up 2: install Android Studio URL: https://crossbotics.com/ftc-helper/docs/setup/02-android-studio/ **Android Studio** is the program you write and build the robot code in. ## Steps 1. Go to [developer.android.com/studio](https://developer.android.com/studio) and download Android Studio. **Which version:** FTC SDK 12.0 (the 2026-27 robot software) needs **Narwhal 3 Feature Drop or newer**. The newest version on that page is fine. 2. Install it with the normal settings. 3. Open Android Studio once. 4. Let it finish its first setup. It downloads the **Android SDK** (the tools that make Android apps). Accept the normal choices. 5. **Windows only:** install [Git for Windows](https://git-scm.com/download/win) with the normal settings. Then close Android Studio and open it again. **Why:** the setup pages use git in Android Studio. GitHub Desktop's git does not work there. ## Done when Android Studio opens and shows its **Welcome** window. **Next:** [GitHub and the robot project](https://crossbotics.com/ftc-helper/docs/setup/03-github-and-the-project/). **Look it up:** [The simulator](https://crossbotics.com/ftc-helper/docs/simulator/) and [Troubleshooting: build problems](https://crossbotics.com/ftc-helper/docs/troubleshooting/#build-problems). --- # Set up 3: GitHub and the robot project URL: https://crossbotics.com/ftc-helper/docs/setup/03-github-and-the-project/ You get the **robot project** onto the laptop and open it in Android Studio. Each step has two ways. Use the one your team likes: - **GitHub Desktop:** a free app with buttons ([desktop.github.com](https://desktop.github.com)). - **The command line:** commands you type. On this page you type them in your computer's own terminal, because no project is open in Android Studio yet ([which terminal](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-terminal)). ## 1. Tell git who you are **GitHub Desktop:** 1. Install GitHub Desktop. 2. Open **Settings > Accounts** (Windows: **File > Options > Accounts**). 3. Sign in with your GitHub account. **Command line:** 1. Find your private GitHub email: on github.com, click your picture (top right) > **Settings** > **Emails**. 2. Tick **Keep my email addresses private**. GitHub then shows an address like `12345678+name@users.noreply.github.com`. 3. Type these four lines, one at a time. Change `YOUR-NAME` and the email to your own. Keep the quotes. **Where:** your computer's own terminal (Mac: the **Terminal** app; Windows: **PowerShell**). Android Studio has no project open yet, so it has no Terminal tab. ([Which terminal](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-terminal)) ```bash git --version git config --global user.name "YOUR-NAME" git config --global user.email "12345678+YOUR-NAME@users.noreply.github.com" git config --global pull.rebase false ``` - `git --version` must print `git version 2...`. If it says `not recognized`, read [git is not recognized](https://crossbotics.com/ftc-helper/docs/troubleshooting/#autonomous-choice-and-git-problems). - **Why the private email and a first name:** a public project's history is public. ## 2. Get the robot project Pick **one**. ### A. Your team already has a project on GitHub (the usual way) Ask your mentor or code lead for its address. **GitHub Desktop:** 1. **File > Clone Repository…** 2. Pick the **URL** tab and paste the address. 3. Pick a folder on your laptop. 4. Click **Clone**. ![GitHub Desktop's Clone a Repository window: 1 the URL tab, 2 the box for your team's project address, 3 Choose, to pick a folder on your laptop, 4 Clone.](https://crossbotics.com/ftc-helper/docs/images/setup-github-desktop-clone.svg) **Command line:** **Where:** your computer's own terminal (Mac: the **Terminal** app; Windows: **PowerShell**). Android Studio has no project open yet, so it has no Terminal tab. ([Which terminal](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-terminal)) It starts in your home folder. The clone makes a new folder there, named after the project. ```bash git clone --recurse-submodules https://github.com/OUR-TEAM/OUR-ROBOT.git ``` **Why `--recurse-submodules`:** the library sits inside the project as a **submodule** (a project kept inside another project). This option gets it too. GitHub Desktop gets it by itself. ### B. Your team has no project yet A mentor or code lead does this once for the team. 1. Go to [github.com/FIRST-Tech-Challenge/FtcRobotController](https://github.com/FIRST-Tech-Challenge/FtcRobotController). 2. Click **Fork** (top right), and make the copy under your team's GitHub account. **Why fork:** the team gets its own copy on GitHub to share. 3. Clone your team's copy as in **A** above. 4. Then a mentor adds the library: [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/). ## 3. Open the project in Android Studio 1. **File > Open**. 2. Pick the **top** project folder: the one with `TeamCode` and `FtcRobotController` inside it. **Why the top folder:** Android Studio needs the whole project, not only `TeamCode`. 3. Wait for the first **Gradle sync**. Gradle is the tool that builds the app. A progress bar is at the bottom right. The first sync downloads a lot, so it takes a while. **Why wait:** until the sync is done, Android Studio shows many false red errors. 4. In the **Project** panel (left), click the list at its top (it says **Android**) and pick **Project**. ![The top of the Project panel: a list that says Android, with the folders ftc-helper-lib, FtcRobotController, TeamCode and Gradle Scripts under it. Click the list and pick Project.](https://crossbotics.com/ftc-helper/docs/images/setup-studio-project-view.svg) 5. Open the folders down to `TeamCode/src/main/java/org/firstinspires/ftc/teamcode/`. This is where your team's code goes. ![The robot project's folders: open the top folder in Android Studio. FtcRobotController is FTC's code, do not change it. TeamCode holds build.gradle and src/main/java/org/firstinspires/ftc/teamcode, where your team's code goes. ftc-helper-lib is the library. settings.gradle is in the top folder.](https://crossbotics.com/ftc-helper/docs/images/setup-project-folders.svg) ## Problems | You see | Do this | | --- | --- | | The `ftc-helper-lib` folder is empty | In Android Studio's Terminal tab, in the project folder: `git submodule update --init` | | The build says `Project directory '.../ftc-helper-lib/library' does not exist` | The same command | | There is no `ftc-helper-lib` folder | Nobody has added the library yet: [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/) | ## Done when The project is open in Android Studio, the sync is finished, and you can see the `teamcode` folder. **Next:** [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/). If there is already an `ftc-helper-lib` folder with files in it, skip to [Update the hubs](https://crossbotics.com/ftc-helper/docs/setup/05-update-the-hubs/). **Look it up:** [Git and GitHub for FTC teams](https://crossbotics.com/ftc-helper/docs/guides/github/) and [Troubleshooting: git problems](https://crossbotics.com/ftc-helper/docs/troubleshooting/#autonomous-choice-and-git-problems). --- # Set up 4: add the library URL: https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/ **Skip this page** if there is already an `ftc-helper-lib` folder next to `TeamCode`, with files in it. ## How it works The library goes inside your robot project as a **git submodule**: a project kept inside another project. Your project remembers exactly which version of the library it uses. **Why a submodule:** it works at events with no internet, you can read the library's code in Android Studio, and the whole team gets the same version. ## You need - The robot project open in Android Studio, synced ([page 3](https://crossbotics.com/ftc-helper/docs/setup/03-github-and-the-project/)). - Git in Android Studio's Terminal tab: `git --version` prints `git version 2...` ([the Terminal](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/)). ## Step 1: add the submodule Type this line and press Enter. **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash git submodule add https://github.com/crossbotics/ftc-helper-lib.git ftc-helper-lib ``` A new folder, `ftc-helper-lib`, is now next to `TeamCode`. For a fixed version instead of the newest, read [Use a specific version](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/#use-a-specific-version) after this page. ## Step 2: tell Gradle about the library 1. Open `settings.gradle`. It is in the top project folder, **not** in `TeamCode`. 2. At the bottom you see: ```groovy include ':FtcRobotController' include ':TeamCode' ``` 3. Add these two lines under them: ```groovy include ':ftc-helper-lib' project(':ftc-helper-lib').projectDir = new File(rootDir, 'ftc-helper-lib/library') ``` **Why the second line:** the submodule also holds examples, docs and the simulator. The robot app needs only the `library` folder. ## Step 3: let TeamCode use the library 1. Open `TeamCode/build.gradle`. 2. Find the `dependencies { ... }` block at the bottom. 3. Add one line inside it: ```groovy dependencies { implementation project(':FtcRobotController') implementation project(':ftc-helper-lib') // <- add this line } ``` ## Step 4: sync Click **Sync Now** in the yellow bar at the top of the editor (or **File > Sync Project with Gradle Files**). Wait until it finishes with no red errors. ## Step 5: check that it works 1. In the `teamcode` folder, make a new Java file named `HelperCheck` (right-click `teamcode` > **New > Java Class**). 2. Replace everything in it with this: ```java package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.crossbotics.ftchelper.util.Angles; @TeleOp(name = "Helper Check") public class HelperCheck extends LinearOpMode { @Override public void runOpMode() { telemetry.addData("Library works", Angles.shortestDiff(-170, 170) == 20); telemetry.update(); waitForStart(); } } ``` 3. Build: **Build > Make Project** (or the hammer: [the buttons](https://crossbotics.com/ftc-helper/docs/setup/06-build-and-install/#the-buttons)). When it builds, the library is in. **Why it proves it:** the `import com.crossbotics...` line only works when the library is there. 4. Delete `HelperCheck.java`. ## Step 6: commit and push **Why:** teammates get the library only after you commit and push it. **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash git add .gitmodules ftc-helper-lib settings.gradle TeamCode/build.gradle git commit -m "Add ftc-helper-lib" git push ``` In GitHub Desktop: tick those four, type the message, click **Commit to main**, then click **Push origin**. ## The simulator buttons (you do nothing) At each Gradle sync, the library adds three entries to the run list ([the buttons](https://crossbotics.com/ftc-helper/docs/setup/06-build-and-install/#the-buttons)): - **Simulator:** a pretend robot on your laptop, in your browser ([the simulator](https://crossbotics.com/ftc-helper/docs/simulator/)). - **Simulator tests:** runs your project's simulator tests. - **Update library:** gets the newest library version ([Keep it up to date](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/#update-the-update-library-button)). If they are not in the list, click **File > Close Project**, then open the project again. To turn them off, write `simulatorButtons=false` in your project's `gradle.properties`. ## Done when The test build passed, you deleted `HelperCheck.java`, and you pushed the change. **Next:** [Update the hubs](https://crossbotics.com/ftc-helper/docs/setup/05-update-the-hubs/). **Look it up:** [Keep the library up to date](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/) and [The simulator](https://crossbotics.com/ftc-helper/docs/simulator/). --- # Set up 5: update the hubs URL: https://crossbotics.com/ftc-helper/docs/setup/05-update-the-hubs/ **If you use only the simulator on this laptop,** skip this page: the simulator needs no hubs. Go to [Every practice](https://crossbotics.com/ftc-helper/docs/setup/08-every-practice/). **Why:** the Driver Station app and the Robot Controller app must have the same version: **12.0** for the 2026-27 season. If the versions differ, the Driver Hub shows a version warning, or the two do not connect. Robot inspectors check this at events. ## The Driver Hub (no laptop needed) 1. Charge the Driver Hub. 2. Connect it to a Wi-Fi network with internet. 3. Open the **Software Manager** app on it. 4. Tap **Update All**. Wait until it is done. ## The Control Hub 1. On the laptop, install the **REV Hardware Client 2** ([rhc2.revrobotics.com](https://rhc2.revrobotics.com/download/download.html)). It runs on Windows 10 or 11, macOS 15 or newer, and Linux. 2. Connect the Control Hub to the laptop with a USB cable. Turn the robot on. 3. In the REV Hardware Client, pick the hub. 4. Install the newest **operating system** and **firmware**. REV's own steps: [Updating the Driver Hub](https://docs.revrobotics.com/duo-control/managing-the-control-system/updating-the-driver-hub). This page does not update the **Robot Controller app**. The next page installs it from Android Studio, because your code is part of it. ## Done when The Software Manager says the Driver Hub is up to date, and the REV Hardware Client shows no updates for the Control Hub. **Next:** [Build and install](https://crossbotics.com/ftc-helper/docs/setup/06-build-and-install/). **Look it up:** [Troubleshooting: Driver Station errors](https://crossbotics.com/ftc-helper/docs/troubleshooting/#driver-station-errors). --- # Set up 6: build and install URL: https://crossbotics.com/ftc-helper/docs/setup/06-build-and-install/ **If you use only the simulator on this laptop,** skip this page: the simulator needs no hubs. Go to [Every practice](https://crossbotics.com/ftc-helper/docs/setup/08-every-practice/). **Why:** the robot runs the app that is on the hub, not the code on your laptop. You repeat steps 1, 3 and 4 after every change. ## The buttons The buttons you use are at the top right of Android Studio: ![The top right of Android Studio: 1 the device list (pick the Control Hub), 2 the run list (TeamCode for the robot, or Simulator), 3 Run (build and install, or start the simulator), 4 Stop, 5 Build (the hammer).](https://crossbotics.com/ftc-helper/docs/images/setup-studio-toolbar.svg) ## Steps 1. **Build:** **Build > Make Project** (or the hammer, 5). Wait for the **Build** tab (bottom) to say it finished with no errors. 2. **Connect to the Control Hub.** Turn on the robot. Pick **one**: - **USB (the easiest):** a USB cable from the laptop to the Control Hub's USB-C port. - **Wi-Fi:** join the laptop to the Control Hub's Wi-Fi network (ask your mentor for its name and password). Then type `adb connect 192.168.43.1:5555`. **Where:** Android Studio's [Terminal tab](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/), in any folder. If it says `adb` is not found, use USB. 3. **Pick the hub.** In the device list (1), pick the Control Hub. Its name starts with `REV Robotics`. 4. **Install:** make sure the run list (2) says `TeamCode`, then click **Run** (3). It builds again and installs the app on the Control Hub. 5. **Check on the Driver Hub.** It connects to the robot and shows the TeleOp and Autonomous lists. - FTC's new project shows **empty** lists. That is normal: FTC hides its sample OpModes. ## Problems | You see | Do this | | --- | --- | | Red text, or a red line in the **Build** tab | Read only the **first** error. It names the file, the line and the problem. Fix it, then build again. | | The hub is not in the device list | Try another USB cable (some only charge). Wait 10 seconds after the robot starts. | | The Driver Hub shows a version warning | [Update the hubs](https://crossbotics.com/ftc-helper/docs/setup/05-update-the-hubs/). | ## Done when The Driver Hub connects to the robot after the install. **Next:** [Make the robot configuration](https://crossbotics.com/ftc-helper/docs/setup/07-robot-configuration/). **Look it up:** [Troubleshooting: build problems](https://crossbotics.com/ftc-helper/docs/troubleshooting/#build-problems) and [Driver Station errors](https://crossbotics.com/ftc-helper/docs/troubleshooting/#driver-station-errors). --- # Set up 7: make the robot configuration URL: https://crossbotics.com/ftc-helper/docs/setup/07-robot-configuration/ **If you use only the simulator on this laptop,** skip this page: the simulator needs no hubs. Go to [Every practice](https://crossbotics.com/ftc-helper/docs/setup/08-every-practice/). The **robot configuration** tells the Control Hub which device is in which port, and its name. Your code finds each device by that name. **Why it matters:** the names in the code must be exactly the same. Capitals and `_` count. ## Pick the names first | Your robot | The names | | --- | --- | | A starter bot (goBILDA, REV, AndyMark, Studica) | The seller's names: [the table for your starter bot](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#the-configuration-names). Add a name for each part you added. | | Your own robot | Your own. Short, small letters, `_` between words: `front_left`, `lift`, `claw`. | ## Steps 1. Connect the Driver Hub to the Control Hub. 2. Open the **⋮** menu > **Configure Robot** > **New**. 3. Pick the Control Hub (and the Expansion Hub, if the robot has one). 4. For each port with a device on it: 1. Pick its kind: a motor type, **Servo**, **Continuous Rotation Servo**, or a sensor. 2. Type its name. If a motor type is not in the list, pick the closest one. The library takes the motor's real numbers from your code. 5. Leave the **imu** line as it is. It is the Control Hub's own IMU (the sensor that knows which way the robot faces). 6. Tap **Save**. Give the configuration a name, for example `MyRobot`. 7. Tap **Activate**. ## Done when The Driver Hub shows your configuration's name at the top, and each port with a device has a name. **Next:** [Every practice: pull, change, commit, push](https://crossbotics.com/ftc-helper/docs/setup/08-every-practice/). You use it from now on. **A wrong name** stops the program at INIT, and the Driver Hub then lists the names that do exist. More: [hardware names](https://crossbotics.com/ftc-helper/docs/modules/hardware/). **Look it up:** [Robot.java](https://crossbotics.com/ftc-helper/docs/reference/robot-java/) and [Parts catalog: motors, servos, wheels and rollers](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). --- # Set up 8: every practice: pull, change, commit, push URL: https://crossbotics.com/ftc-helper/docs/setup/08-every-practice/ **Why:** git keeps every saved version of the code. You can undo a mistake, share code between laptops, and get back the exact code that ran at the last event. ## The loop ### 1. Pull first: get the team's newest code **GitHub Desktop:** click **Fetch origin** (top bar). If it changes to **Pull origin**, click it. **Command line:** **Where:** Android Studio's **Terminal** tab, in the **project folder** (a new Terminal tab starts there). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash git pull git submodule update ``` **Why `git submodule update`:** it puts the library at the version the project expects. ### 2. Change, build, test Make one change at a time. Build (hammer), install (Run), and test on the robot. ### 3. Commit: save a snapshot each time a small change works **GitHub Desktop:** 1. The **Changes** tab lists the changed files. Untick a file you do not want. 2. Type a message in **Summary** (bottom left). 3. Click **Commit to main**. **Command line:** **Where:** the same Terminal tab, in the **project folder**. ```bash git status git add TeamCode git commit -m "Auto: park 2 in further left" ``` Read what `git status` lists, so you commit only what you meant to. **A good message** says what changed and why: `Lift: high step 2400 -> 2350 (it hit the stop)`. Not `stuff` or `fix`. ### 4. Push before you leave **GitHub Desktop:** click **Push origin**. **Command line:** **Where:** the same Terminal tab, in the **project folder**. `git push` When the push is refused (`rejected ... fetch first`), a teammate pushed first. Pull (step 1), then push again. ## Team rules 1. **`main` always builds and works.** Never push code that does not build. 2. **Pull before you start.** 3. **Commit often,** one small working change at a time. 4. **Push before you leave.** Until then, your commits are only on your laptop. 5. **Two people, one file:** talk first ("I am changing `Tunables.java`"). ## Done when You pulled at the start, and you pushed your work at the end. **More git** (branches, conflicts, undo, before an event): [Git and GitHub for FTC teams](https://crossbotics.com/ftc-helper/docs/guides/github/). **Set up is done.** **Next:** [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/): the code you start from. **Look it up:** [Troubleshooting: git problems](https://crossbotics.com/ftc-helper/docs/troubleshooting/#autonomous-choice-and-git-problems). --- # Set up 9: the Terminal URL: https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/ ## Which terminal A **terminal** is a window where you type commands. These docs mean **Android Studio's Terminal tab**, except in one place: | Where you type | When | | --- | --- | | **Android Studio's Terminal tab** | Every other time. It opens inside your project. | | **Your computer's own terminal** (Mac: the **Terminal** app; Windows: **PowerShell**) | Only in [Set up 3](https://crossbotics.com/ftc-helper/docs/setup/03-github-and-the-project/), before the project is on the laptop. Android Studio has no project open yet, so it has no Terminal tab. | **Why Android Studio's:** it starts in the right folder, and it uses the same Java as Android Studio. ## Which folder Every command in these docs says where to type it, with a **Where:** line above it. There are two folders: | The **Where:** line says | The folder | It holds | | --- | --- | --- | | **the project folder** | The top folder of the robot project | `TeamCode`, `FtcRobotController`, `ftc-helper-lib` | | **the `ftc-helper-lib` folder** | The library's folder, inside the project folder | `library`, `sim`, `docs` | Git commands (`git ...`) run in the project folder. The library's commands (`./gradlew ...`: the simulator, the file maker) run in the `ftc-helper-lib` folder. ![The robot project's folders: the top folder is the project folder, with FtcRobotController, TeamCode and ftc-helper-lib inside it.](https://crossbotics.com/ftc-helper/docs/images/setup-project-folders.svg) ## Open it and run a command 1. Open the **Terminal** tab at the bottom of Android Studio (or **View > Tool Windows > Terminal**). **It starts in the project folder.** 2. For the `ftc-helper-lib` folder, type `cd ftc-helper-lib` and press **Enter**. 3. Type the command (or paste it). Press **Enter**. 4. Wait for the **prompt** (the text before the cursor) to come back. Then type the next one. ### Check which folder you are in The prompt shows the folder's name, for example `OUR-ROBOT %` or `ftc-helper-lib %`. If you are not sure, type `ls` (Windows: `dir`) and press Enter. It lists what is in the folder: | You see in the list | You are in | | --- | --- | | `TeamCode` and `FtcRobotController` | the project folder | | `library` and `sim` | the `ftc-helper-lib` folder | **If you are lost,** close the Terminal tab and open a new one. A new tab always starts in the project folder. | To | Type | | --- | --- | | Go into the library's folder | `cd ftc-helper-lib` | | Go back up one folder | `cd ..` | | Stop a running command | **Ctrl+C** (on a Mac too) | **Windows:** type `.\gradlew` (PowerShell) or `gradlew.bat` in place of `./gradlew`. ## Read the output - Look at the **last** lines. - `BUILD SUCCESSFUL` is good. - `BUILD FAILED`: the problem is directly above `* What went wrong:`. - The first Gradle command downloads a lot, so it takes a while. These warnings are normal. Ignore them: - `source value 8 is obsolete` (and `target value 8`) - `Java compiler version 21 has deprecated support for compiling with source/target version 8` - `SDK processing. This version only understands SDK XML versions up to 3` - `Deprecated Gradle features were used` - `[Incubating] Problems report` If Android Studio shows "Start AGP Upgrade Assistant", do not click it. The FTC SDK sets its own version. ## Laptop setup for `./gradlew` commands (once per laptop) The **Simulator** buttons need none of this. Only commands you type that start with `./gradlew` do. **Why:** the library is its own Gradle build, separate from your robot project. ### Java The commands need `JAVA_HOME`: the folder where Java is (Java 17 or newer). Android Studio has its own Java. Set it with the line for your laptop. It lasts until you close that tab. **Where:** Android Studio's **Terminal** tab, in any folder. ```bash # Mac export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home" # Windows (PowerShell) $env:JAVA_HOME = "C:\Program Files\Android\Android Studio\jbr" ``` If that folder is not there, find a Java folder: 1. In Android Studio: **Settings > Build, Execution, Deployment > Build Tools > Gradle**. The **Gradle JDK** line names a Java and its folder. Use that folder. 2. On a Mac, type `/usr/libexec/java_home -V` in the Terminal tab (any folder). It lists the Javas on the Mac. 3. If you find none, install a **JDK** 17 or 21, for example Eclipse Temurin from [adoptium.net](https://adoptium.net). You do **not** need the Java from java.com. ### The Android SDK When the first command stops with `SDK location not found`, make a text file `ftc-helper-lib/local.properties`: 1. Right-click the `ftc-helper-lib` folder > **New > File**. 2. Name it `local.properties` (no `.txt`). 3. Write one line in it. Put your user name in place of ``: - Mac: `sdk.dir=/Users//Library/Android/sdk` - Windows: `sdk.dir=C\:\\Users\\\\AppData\\Local\\Android\\Sdk` To see your user name, type `whoami` on a Mac, or `$env:USERNAME` in Windows PowerShell (the Terminal tab, any folder). Android Studio shows the SDK folder in **Settings > Languages & Frameworks > Android SDK**. **Why its own file:** your robot project's `local.properties` does not count. The library is its own build. ## Problems | You see | Do this | | --- | --- | | `git` is `not recognized` (Windows) | [git is not recognized](https://crossbotics.com/ftc-helper/docs/troubleshooting/#autonomous-choice-and-git-problems) | | `JAVA_HOME is not set` | [Java](#java), above | | `SDK location not found` | [The Android SDK](#the-android-sdk), above | **Next:** back to the page that sent you here, or [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/). **Look it up:** [Troubleshooting: build problems](https://crossbotics.com/ftc-helper/docs/troubleshooting/#build-problems) and [Git and GitHub for FTC teams](https://crossbotics.com/ftc-helper/docs/guides/github/). --- # Pick your start URL: https://crossbotics.com/ftc-helper/docs/pick-your-start/ Your robot's code is five files in `TeamCode`: `Robot.java`, `Tunables.java`, `Controls.java`, `Actions.java` and an `autos` folder. You do not type them from nothing. You start from files that are already written, and then change them. **Why:** code that already builds and drives is a safe place to start. You change a few lines, not write a hundred. Pick **one** start: | Your robot | Your start | You get | | --- | --- | --- | | A **starter bot** from goBILDA (tank or Strafer), REV, AndyMark or Studica, built as the seller's guide says | [A starter bot](https://crossbotics.com/ftc-helper/docs/pick-your-start/01-starter-bot/) | The bot's whole code. Every part is in it, with the seller's names. | | A robot **like one of our example robots**: for example mecanum + intake, tank + flywheel, a turret, odometry | [A common setup](https://crossbotics.com/ftc-helper/docs/pick-your-start/02-common-setup/) | That example's code. You delete what your robot does not have. | | **Your own design** | [A blank slate](https://crossbotics.com/ftc-helper/docs/pick-your-start/03-blank-slate/) | The smallest code that drives. Then you add your parts one at a time. | **For a starter bot with your own changes** (a part added, taken off or moved): start from [a starter bot](https://crossbotics.com/ftc-helper/docs/pick-your-start/01-starter-bot/). Then make your changes one at a time: the page says how. **If you are not sure,** pick the start that is most like your robot. You delete less and type less. You can copy single lines from the other starts later. All three starts end in the same place: **the five files in `TeamCode`, and the project builds.** Then the [five files pages](https://crossbotics.com/ftc-helper/docs/five-files/) explain every line, and you make the robot drive. | # | Page | | --- | --- | | 1 | [A starter bot](https://crossbotics.com/ftc-helper/docs/pick-your-start/01-starter-bot/) | | 2 | [A common setup](https://crossbotics.com/ftc-helper/docs/pick-your-start/02-common-setup/) | | 3 | [A blank slate](https://crossbotics.com/ftc-helper/docs/pick-your-start/03-blank-slate/) | | 4 | [Copy example files into TeamCode](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/) (pages 1 to 3 send you here) | **Next:** pick one: [a starter bot](https://crossbotics.com/ftc-helper/docs/pick-your-start/01-starter-bot/), [a common setup](https://crossbotics.com/ftc-helper/docs/pick-your-start/02-common-setup/) or [a blank slate](https://crossbotics.com/ftc-helper/docs/pick-your-start/03-blank-slate/). --- # Start from a starter bot URL: https://crossbotics.com/ftc-helper/docs/pick-your-start/01-starter-bot/ The library has the whole code for each of these starter bots. It uses the same configuration names as the seller's own code, so it runs on the bot as it is. You copy it, change one line, and build. ## 1. Find your bot The folders are in the library, in `ftc-helper-lib/examples/src/main/java/com/crossbotics/ftchelper/examples/`. | Starter bot | Its folder | Its autonomous | | --- | --- | --- | | goBILDA FTC StarterBot (tank) | [`gobildabot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/gobildabot) | `autos/LaunchAndBackUp.java` | | goBILDA FTC StarterBot with Mecanum Wheels (Strafer) | [`gobildastraferbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/gobildastraferbot) | `autos/LaunchAndLeave.java` | | REV DUO FTC Starter Bot | [`revbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/revbot) | `autos/ShootAndLeave.java` | | AndyMark Robits BIOBUZZ StarterBot | [`andymarkbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/andymarkbot) | `autos/ThrowAndLeave.java` | | Studica FTC Starter Bot | [`studicabot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/studicabot) | `autos/ShootAndLeave.java` | goBILDA's folder also has `autos/AutoCookbook.java`: a menu of example steps. Copy it only if you want it. ## Try it first in the simulator You can drive the bot's code before you copy it. The simulator is a pretend robot on your laptop. It runs the library's copy of the code. **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash ./gradlew :sim:run -Probot=sim/robots/starter-bot-rev.properties -PteamCode=none ``` Open http://localhost:8780 and pick **REV Bot TeleOp**. `-PteamCode=none` runs the library's copy of the code, not yours. For another bot, change `rev` in the command: `gobilda`, `gobilda-strafer`, `andymark` or `studica`. The first time, do the [laptop setup](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#laptop-setup-for-gradlew-commands-once-per-laptop). ## 2. Check the configuration names The robot configuration must use the seller's names: [the names for each starter bot](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#the-configuration-names). You made the configuration in [Set up 7](https://crossbotics.com/ftc-helper/docs/setup/07-robot-configuration/). Check each name there. **Why:** the code finds each motor and servo by its name. One wrong letter, and INIT stops. ## 3. Copy the files Copy the bot's folder into `TeamCode`: [Copy example files into TeamCode](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/). Then come back here. ## 4. Check the IMU line Open `Robot.java`. Find the line with `.imu(`. It says where the Control Hub's **logo** faces, then where its **USB ports** face. Look at the hub on your robot. If your team mounted it another way, change the line ([How your Control Hub is mounted](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#how-your-control-hub-is-mounted)). **Why:** the IMU (the sensor in the hub that knows which way the robot faces) must know how the hub sits. Turns in autonomous use it. Change nothing else yet. ## 5. Read your bot's notes Some numbers in your bot's `Tunables.java` are guesses. Each bot's notes say which ones: [REV](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#rev-bot-code), [goBILDA](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#gobilda-bot-code), [goBILDA Strafer](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#gobilda-strafer-bot-code), [AndyMark](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#andymark-bot-code), [Studica](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#studica-bot-code). You measure them later, on the [Tunables.java page](https://crossbotics.com/ftc-helper/docs/five-files/02-tunables-java/). Two kit mechanisms are not parts of the library. Their code uses the closest part and says so in `Robot.java`: - **AndyMark's catapult** runs as an `Indexer`: one press runs its motor for a set time. Tune that time so one press is one throw. - **Studica's flywheel** has a 2:1 gear. The speed in `Tunables.java` is the motor's speed. The wheels turn at half of it. Tune it by watching shots. ## 6. Build In Android Studio, click **Build > Make Project**. ## You changed your starter bot You may have added, taken off or moved a part, or used another motor or servo. Then do steps 1 to 6 first, with the seller's code as it is. Then make your changes **one at a time**: change, build, check. **Why:** when something breaks, you know which change did it. For each kind of change, [You changed your starter bot](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#you-changed-your-starter-bot) says what to change in each file. ## Done when - The bot's files are in `TeamCode`: `Robot.java`, `Tunables.java`, `Controls.java`, `Actions.java`, and the `autos` folder. - **Build > Make Project** ends with no red errors. ## Problems | Problem | Fix | | --- | --- | | A line is red: `cannot find symbol` | A `package` or `import` line still names the example folder. See [Copy example files, step 3](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/#3-change-the-imports). | | INIT stops: a name is not found | The configuration name is not the seller's name. INIT lists the real names. Fix the configuration ([Set up 7](https://crossbotics.com/ftc-helper/docs/setup/07-robot-configuration/)). | | The TeleOp is not on the Driver Station | The `@Disabled` line is still in `Controls.java`. See [Copy example files, step 4](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/#4-delete-the-disabled-lines). | --- **Next:** [The five files](https://crossbotics.com/ftc-helper/docs/five-files/). They explain every line you copied. **Look it up:** [the starter bots: names, numbers and notes](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/). --- # Start from a common setup URL: https://crossbotics.com/ftc-helper/docs/pick-your-start/02-common-setup/ Each example robot is a robot in five files that builds and drives. Pick the one most like your robot. You copy it, and then delete what your robot does not have. **Why:** deleting a line is easier than writing one, and the lines you keep already work together. ## 1. Pick the closest example The folders are in the library, in `ftc-helper-lib/examples/src/main/java/com/crossbotics/ftchelper/examples/`. | Your robot has | Start from | What is in it | | --- | --- | --- | | a mecanum drive and an intake | [`quickstart`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/quickstart) | the smallest robot with a part. A `// STEP` mark on each line to change | | a mecanum drive, an intake, a lift and a claw | [`lessonbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/lessonbot) | the example robot of The five files and Add to your robot, and its Drive Tuner | | a tank drive and a flywheel shooter | [`flywheelbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/flywheelbot) | an intake, a deploy servo, a flywheel, a servo feeder and a webcam that aims the whole robot | | a mecanum drive with a turret and a camera | [`turretbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/turretbot) | a Limelight that the turret follows, a hood, a folding claw, and two finders | | a mecanum drive with odometry (Pinpoint, OTOS or dead wheels) | [`odometrybot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/odometrybot) | autos that drive to field points, and the Odometry Tuner | | odometry and Pedro Pathing | [`pedrobot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/pedrobot) | `odometrybot` plus curved paths | **Odometry** is a sensor set that tracks where the robot is on the field. **Pedro Pathing** is a separate library that drives curved paths. More detail on each one: [Pick your template](https://crossbotics.com/ftc-helper/docs/templates/#your-robot-looks-like-this-start-from-that). **`pedrobot`:** add Pedro to the project first ([Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/#your-project-add-the-pedro-add-on-once)). **Some have extra files.** Copy them with the rest: | Example | Extra files | What they are | | --- | --- | --- | | `lessonbot` | `DriveTuner.java` | a finder for the drive | | `turretbot` | `HoodFinder.java`, `ShotTuner.java` | finders for the hood and the shots | | `odometrybot` | `OdometryTuner.java` | a finder for the odometry | | `pedrobot` | `PedroConstants.java` | Pedro's numbers | `lessonbot` also has `OwnTeleOp.java`: the same TeleOp written as a plain FTC OpMode, to read. Do not copy it. A **finder** is a small program that measures a number on the real robot and shows the line to copy into your code. ## 2. Copy the files Copy the example's folder into `TeamCode`: [Copy example files into TeamCode](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/). Then come back here. ## 3. Make it match your robot Open `Robot.java`. Change only these, then build: 1. **The device names.** These are the names in quotes right after the part's kind, for example `"front_left"` in `Drive.mecanum("front_left", ...)` and `"claw"` in `Claw.servo("claw")`. Each one must be exactly the name in your robot configuration ([Set up 7](https://crossbotics.com/ftc-helper/docs/setup/07-robot-configuration/)). Capitals and `_` count. **Why:** the code finds each device by its name. Leave the other quoted words as they are. `.part("gobilda-2000-torque")` is a catalog id (which motor or servo it is), and words like `"high"` in `goTo("high")` are position names. 2. **The drive motor and wheels:** `.motor(...)` and `.wheel(...)` (or `.wheelMm(...)`) on the drive line ([the drive line](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#the-drive-attribute-by-attribute)). 3. **The IMU line** (`.imu(...)`): where the Control Hub's logo and USB ports face. Change it only if your team mounted the hub another way ([how](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#how-your-control-hub-is-mounted)). 4. **A part your robot does not have:** delete its line in `define()` and its field (`public Claw claw;`). Then build. Each red mark now shows a place that still uses the part. Fix each one, in any file: - A button line in `Controls.java`: delete the whole line, up to its `;`. - An action in `Actions.java` that uses the part: delete the whole action, from `/** ... */` and `public static Action` to its closing `}`. Then delete each line that used that action. - A step in an autonomous: delete the step. If it ends with `;`, put the `;` on the step before it. **Why:** the build finds every place that uses the part for you. Delete whole lines and whole actions: half a line does not build. For example, a robot with no claw, from `lessonbot`: - `Robot.java`: delete `public Claw claw;` and the `claw = add(...)` line. - `Controls.java`: delete the `g2.b.toggle(robot.claw)` line. - `Actions.java`: delete both actions. Each one uses the claw. - Build again. Now the lines that used those actions are red. In `Controls.java`, delete the `g2.rb.press(...)` line, and the `g2.lb.tap(...)` statement: two lines, up to the `;`. - `autos/ScoreAndPark.java`: delete the `.run("Hold the piece", ...)` and `.action(...)` steps. The part's section in `Tunables.java` (for example `public static class Claw`) can stay for now. It does no harm. Delete it when you tidy up. Keep the other numbers as they are for now. You measure them on the [Tunables.java page](https://crossbotics.com/ftc-helper/docs/five-files/02-tunables-java/). When your robot has a part that the example does not have, add it later, one at a time, on the [Robot.java page](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#add-a-part). ## 4. Build In Android Studio, click **Build > Make Project**. ## Done when - The five files are in `TeamCode`: `Robot.java`, `Tunables.java`, `Controls.java`, `Actions.java`, and the `autos` folder. Your configuration names are in `Robot.java`. - **Build > Make Project** ends with no red errors. ## Problems | Problem | Fix | | --- | --- | | A line is red: `cannot find symbol` | A `package` or `import` line still names the example folder ([Copy example files, step 3](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/#3-change-the-imports)). Or the line uses a part you deleted: delete the line. | | INIT stops: a name is not found | A name in `Robot.java` is not the name in the configuration. INIT lists the real names. | | `pedrobot` does not build: `com.pedropathing` not found | Pedro is not in the project yet ([Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/#your-project-add-the-pedro-add-on-once)). | --- **Next:** [The five files](https://crossbotics.com/ftc-helper/docs/five-files/). They explain every line you copied. **Look it up:** [Pick your template](https://crossbotics.com/ftc-helper/docs/templates/): more about each example robot. --- # Start from a blank slate URL: https://crossbotics.com/ftc-helper/docs/pick-your-start/03-blank-slate/ You start with the **smallest robot that works: it drives.** Then you add your parts one at a time, on the five files pages. **Why:** when only one part is new, a problem can only be in that part. There are two ways to get the first files. Pick one: | Your robot | Use | | --- | --- | | It is wired, and its configuration is on the Driver Hub ([Set up 7](https://crossbotics.com/ftc-helper/docs/setup/07-robot-configuration/)) | [Way A: from your configuration](#way-a-from-your-configuration) (best) | | It is not wired yet, or you only use the simulator, or you want to type each part in yourself | [Way B: copy the smallest files](#way-b-copy-the-smallest-files) | ## Way A: from your configuration The library reads your configuration and writes the five files for you, with a line for each part. **Why:** it copies the names for you, so they cannot have typos. 1. **Copy the configuration file off the Control Hub.** It is `/sdcard/FIRST/.xml`, where `` is your configuration's name (for `MyRobot`, it is `MyRobot.xml`). Use Android Studio's **Device Explorer** (**View > Tool Windows > Device Explorer**) with the hub connected, or the REV Hardware Client. Save it in the project folder, next to `TeamCode`. 2. **Run the file maker.** The first time, do the [laptop setup](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#laptop-setup-for-gradlew-commands-once-per-laptop). **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash ./gradlew :sim:newRobot -Pconfig=../MyRobot.xml -PteamCode=../TeamCode ``` Change `MyRobot.xml` to your file's name. It writes `Robot.java`, `Tunables.java`, `Controls.java`, `Actions.java` and `autos/LeaveStart.java` into `TeamCode`. It never writes over your work: if one of the files is already there, it writes nothing and stops. 3. **Check each `TODO` line in `Robot.java`.** A `TODO` is a guess the file maker was not sure of, for example which part a motor drives. 4. **Build:** click **Build > Make Project**. In `Tunables.java`, each number is `DEFAULT` (the library's starting value) or `MEASURE` (a number only your robot can give). Leave them for now. The [Tunables.java page](https://crossbotics.com/ftc-helper/docs/five-files/02-tunables-java/) says how to find each one. ## Way B: copy the smallest files The smallest files are in the library, in the [`firstrobot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/firstrobot) folder: `ftc-helper-lib/examples/src/main/java/com/crossbotics/ftchelper/examples/firstrobot/`. They are a mecanum drive and nothing else. They are the same files the five files pages show. 1. **Copy the folder** into `TeamCode`: [Copy example files into TeamCode](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/). Then come back here. 2. **Change the drive line** in `Robot.java`: your four motor names, your motor and wheels, and the IMU ([the drive line](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#the-drive-attribute-by-attribute), [how your Control Hub is mounted](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#how-your-control-hub-is-mounted)). For a tank drive, read [A tank drive instead](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#a-tank-drive-instead). 3. **Build:** click **Build > Make Project**. Your other parts come later, one at a time, on the [Robot.java page](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#add-a-part). ## Done when - The five files are in `TeamCode`: `Robot.java`, `Tunables.java`, `Controls.java`, `Actions.java`, and the `autos` folder. - **Build > Make Project** ends with no red errors. ## Problems | Problem | Fix | | --- | --- | | `... is already there: nothing written (move it away first)` | One of the five files is already in `TeamCode`. Move it to another folder, then run the command again. | | `./gradlew: No such file or directory` | You are not in the `ftc-helper-lib` folder. Type `cd ftc-helper-lib`. | | A line is red: `cannot find symbol` | A `package` or `import` line still names the example folder ([Copy example files, step 3](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/#3-change-the-imports)). | --- **Next:** [The five files](https://crossbotics.com/ftc-helper/docs/five-files/). They explain every line, and you make the robot drive. **Look it up:** [Robot.java](https://crossbotics.com/ftc-helper/docs/reference/robot-java/), [Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/tunables/) and [Drive](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/). --- # Copy example files into TeamCode URL: https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/ The example files are in the library. Your robot's code must be in `TeamCode`. You copy the files, then change a few lines so that they belong to `TeamCode`. On this page, `` is the name of the folder you copy, for example `gobildabot`. Put the real name there, without the `< >`. ## 1. Copy the files 1. In Android Studio's **Project** panel, pick **Project** in the menu at the top of the panel (not **Android**). **Why:** the **Android** view does not show the library's examples. 2. Open `ftc-helper-lib/examples/src/main/java/com/crossbotics/ftchelper/examples//`. 3. Select every `.java` file in it. Copy them (**Ctrl+C**, Mac: **Cmd+C**). 4. Open `TeamCode/src/main/java/org/firstinspires/ftc/teamcode/`. Right-click `teamcode` and pick **Paste**. Android Studio may show a **Copy** box: press **OK**. 5. Right-click `teamcode`, pick **New > Package**. Type `autos` after the `teamcode.` that is already there. 6. Copy every file from the example's `autos` folder into your new `autos` folder the same way. ## 2. Change the package lines The first line of each file is its `package` line. It must name the folder that the file is in now: | File | Its first line | | --- | --- | | next to `Robot.java` | `package org.firstinspires.ftc.teamcode;` | | in `autos` | `package org.firstinspires.ftc.teamcode.autos;` | Before: ```java package com.crossbotics.ftchelper.examples.gobildabot; ``` After: ```java package org.firstinspires.ftc.teamcode; ``` Android Studio may have changed some of them for you when you pasted. Check every file. **Why:** a file whose `package` line does not match its folder does not build. ## 3. Change the imports The files in `autos` import `Robot`, and some import `Actions`. Those imports still name the example folder. Change each one to `org.firstinspires.ftc.teamcode`. Before: ```java import com.crossbotics.ftchelper.examples.gobildabot.Robot; ``` After: ```java import org.firstinspires.ftc.teamcode.Robot; ``` Do the same in every file that has an `import com.crossbotics.ftchelper.examples` line. Android Studio marks each line it cannot find in red. ## 4. Delete the @Disabled lines Some example OpModes have this line above the class: ```java @Disabled ``` and this import: ```java import com.qualcomm.robotcore.eventloop.opmode.Disabled; ``` Delete both, in every file that has them: `Controls.java`, each autonomous, and each finder. **Why:** `@Disabled` hides an OpMode on the Driver Station. The examples use it, so they do not fill the list. Your copies must show. ## 5. Change the OpMode names In `Controls.java`, find `@TeleOp(name = "...")`. In each autonomous, find `@Autonomous(name = "...", preselectTeleOp = "...")`. Change the names to your own. `group = "Examples"`: change it to your own group, or delete it. Leave `group = "Finders"` on the finder files: the docs look for the finders in that group. **`preselectTeleOp`** must be the TeleOp's name, exactly. **Why:** after the autonomous, the Driver Station picks that TeleOp for you. ## Done when - No `package` or `import` line names `com.crossbotics.ftchelper.examples`. - No `@Disabled` line is left. - **Build > Make Project** ends with no red errors. **Next:** go back to your start page: [a starter bot](https://crossbotics.com/ftc-helper/docs/pick-your-start/01-starter-bot/#4-check-the-imu-line), [a common setup](https://crossbotics.com/ftc-helper/docs/pick-your-start/02-common-setup/#3-make-it-match-your-robot), or [a blank slate](https://crossbotics.com/ftc-helper/docs/pick-your-start/03-blank-slate/#way-b-copy-the-smallest-files). **Look it up:** [Search every class and method](https://crossbotics.com/ftc-helper/docs/reference/javadoc/) and [Troubleshooting: build problems](https://crossbotics.com/ftc-helper/docs/troubleshooting/#build-problems). --- # The five files: your robot's code URL: https://crossbotics.com/ftc-helper/docs/five-files/ Your robot's code is five files in the `teamcode` folder. Each file has one job: | File | What it holds | You change it when | | --- | --- | --- | | [`Robot.java`](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/) | What is on the robot: the drive and each part, with their names | you add, remove or change a part | | [`Tunables.java`](https://crossbotics.com/ftc-helper/docs/five-files/02-tunables-java/) | The numbers: speeds, positions, powers | you measure or tune a number | | [`Controls.java`](https://crossbotics.com/ftc-helper/docs/five-files/03-controls-java/) | The buttons, and the TeleOp | you change what a button does | | [`Actions.java`](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/) | Steps that use several parts together, like "score" | you want one button or step to do several things | | [`autos/`](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/) | The autonomous programs, one file each | you write or change an autonomous | ## Five files? But two autos make more than five Yes. "Five files" counts the five jobs, not the exact number of files. The fifth one, `autos/`, is a folder. It has one file for each autonomous, so a robot with three autos has seven files. You can also see a few small files next to these. For example: a finder (a small program that measures one number for you), or `Routes.java` for routes that several autos share ([Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/)). They do not hold any of the robot's parts, numbers or buttons. Those always stay in the four files and the `autos/` folder. ## Start small, then add These pages build the **smallest robot that works first: it drives.** Then you add one part at a time, and test each one before the next. **Why:** when only one part is new, a problem can only be in that part. When five parts are new, the problem can be anywhere. ## Where your five files come from You do not type them from nothing. You copy them from [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/) (a starter bot, a common setup, or a blank slate), then change them. When you start from a starter bot's or an example's files, these pages still explain every line you see. ## Java you will meet The five files use a few Java ideas again and again. Read the list once. Come back to it when you meet one. | You see | Its name | What it means | | --- | --- | --- | | `class Robot extends RobotDefinition` | **extends** | "built on": your class gets everything the library class does. You fill in the methods it leaves open (here `define()`), each marked `@Override`. | | `ControlMap`, `Auto` | **generics** | the name in angle brackets says which class the library class works with: your `Robot`. | | `Drive.tank(...).motor(...).wheelMm(96)` | **method chaining** | each method gives back the same thing, so the next one adds to it. Read it left to right as one sentence. | | `() -> r.launcher.fire(4)` | **lambda** | a small piece of code you give now, to run later (when a button is pressed, or an action gets to that step). `() ->` means "no inputs, run this". | | `r.intake::in` | **method reference** | the short way to write `() -> r.intake.in()`. | | `Runnable` | | Java's name for "code with no inputs that can run later". A lambda or a method reference is one. | **A name is red in Android Studio:** the file needs an `import` line. Click the name and press **Alt+Enter** (**Option+Enter** on a Mac). If it offers two, pick the one in `com.crossbotics.ftchelper.robot`. ## Done when At the end of the five files pages, the robot drives in TeleOp and runs a short autonomous. **Check yourself:** - Where do you change the launcher's speed? (`Tunables.java`, section `Launcher`.) - The operator wants the claw on X, not B. Which file? (`Controls.java`: `g2.x.toggle(robot.claw)`.) - An action lifts the lift, and the operator moves the lift stick. What happens? (The action stops: the driver always wins.) - Why does `define()` not move anything? (It runs in INIT, and the library moves nothing before ▶.) **Commit after each step that works,** so you can always go back ([Git and GitHub](https://crossbotics.com/ftc-helper/docs/guides/github/)). **Next:** [Robot.java](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/). --- # Robot.java: what is on the robot URL: https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/ `Robot.java` lists what is on your robot: the drive, and each part, with the names from the robot configuration. The buttons are in `Controls.java`, and the speeds are in `Tunables.java`. ## The smallest Robot.java This is a whole `Robot.java` for a robot that only drives. Click a **(+)** to read what a line does. ```java title="Robot.java" import com.crossbotics.ftchelper.robot.Drive; import com.crossbotics.ftchelper.robot.RobotDefinition; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot.LogoFacingDirection; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot.UsbFacingDirection; /** The five files, file 1 of 5: what is on the robot. The smallest robot that drives. */ public class Robot extends RobotDefinition { // (1)! @Override protected void define() { // (2)! drive(Drive.mecanum("front_left", "front_right", "back_left", "back_right") // (3)! .motor("gobilda-5203-312").wheel("gobilda-gripforce-mecanum-104") // (4)! .imu("imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD)); // (5)! } } ``` 1. `extends RobotDefinition`: your robot builds on the library's robot. The library's robot gives it the drive, the safety checks, the screen lines and the simulator. 2. `define()` runs once at INIT. Each line in it adds one thing to the robot. 3. The drive, and its four motor names **in this order**: front left, front right, back left, back right. Each name must be exactly the name in the robot configuration (capitals and `_` count). 4. Which motor drives the wheels, and which wheels: their ids in the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). The library reads the motor's speed and the wheel's size there, to work out speeds and distances. 5. The Control Hub's own IMU (the sensor that knows which way the robot faces), and which way the hub is mounted: where its **logo** faces, then where its **USB ports** face. **The first line of the file** (above the imports) must be: ```text package org.firstinspires.ftc.teamcode; ``` ## Make it your robot ### The drive, attribute by attribute You can put these attributes on the drive line. **Needed?** says which ones you must write. **yes** = the line does not work without it. recommended = it works without it, but less well. optional = only when your robot needs it. | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Drive.mecanum(fl, fr, bl, br)` | **yes**, one of the three | a mecanum drive (it can slide sideways) and its four motor names, in this order | - | | `Drive.tank(left, right)` | **yes**, one of the three | a tank drive, one motor per side | - | | `Drive.tank(fl, fr, bl, br)` | **yes**, one of the three | a tank drive, two motors per side | - | | `.motor(id)` | recommended | the drive motor, by its [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/#motors) id: speeds and distances come from it | Defaults to `gobilda-5203-312` | | `.wheel(id)` | recommended | the wheel, by its [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/#wheels-and-rollers) id: its size comes from the catalog | Defaults to a 96 mm wheel | | `.wheelMm(mm)` | optional | the wheel's diameter in mm, for a wheel that is not in the catalog, or the size the Drive Tuner measured (after `.wheel(...)`: the last one wins) | Defaults to 96 | | `.imu(name, logo, usb)` | recommended | the IMU's name, and where the hub's logo and USB ports face | Defaults to `"imu"`, `UP`, `FORWARD` | | `.reversed(names...)` | optional | exactly these motors run reversed: add it after the first drive test, if needed | Defaults to the left side reversed | | `.gearRatio(r)` | optional | motor turns per wheel turn, when gears, a belt or a chain sit between them | Defaults to 1 | | `.wheelsAtMm(track, base)` | optional | where the wheels sit, side to side and front to back, mm (the simulator only) | the simulator uses its robot file's numbers | | `.noImu()` | optional | no IMU: TeleOp drives robot-centric only, and autonomous will not start | Defaults to the hub's IMU | The drive's numbers (speeds, slow mode, auto turns) are in `Tunables.Drive`: [every drive number](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava). ### Your motor names Use the names from your robot configuration ([Set up 7](https://crossbotics.com/ftc-helper/docs/setup/07-robot-configuration/)). A starter bot's names are in [the table for your starter bot](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/#the-configuration-names). ### A tank drive instead A tank drive (one motor per side, or one name per side) uses `Drive.tank`: ```java title="Robot.java" drive(Drive.tank("left_drive", "right_drive") .motor("gobilda-5203-312").wheelMm(96) .reversed("right_drive") // only the motors that run backward .imu("imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD)); ``` ### Your motor and wheels Find your drive motor and your wheels in the parts catalog, and copy their ids: - [Motors](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/#motors), for example `gobilda-5203-312` for goBILDA's 312 RPM Yellow Jacket. - [Wheels and rollers](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/#wheels-and-rollers), for example `gobilda-gripforce-mecanum-104`, `gobilda-mecanum-96`, `rev-mecanum-75` or `gobilda-hogback-96`. When your wheel is not in the catalog, measure it across in millimeters. Then write `.wheelMm(mm)` in place of `.wheel(id)`. ### How your Control Hub is mounted Look at the hub on the robot. Write where its logo faces, then where its USB ports face: ```java title="Robot.java" drive(Drive.mecanum("front_left", "front_right", "back_left", "back_right") .motor("gobilda-5203-312").wheelMm(96) // Which way the hub's LOGO faces, then which way its USB PORTS face, on the robot. .imu("imu", LogoFacingDirection.LEFT, UsbFacingDirection.UP)); ``` **Why it matters:** the robot uses the IMU to know which way it faces. A wrong mounting makes turns and field-centric driving go the wrong way. **Check it** after the first drive test (it needs `Controls.java`): 1. Run your TeleOp. Hold gamepad 1's small **START** button, then press **BACK**. This shows the debug lines, with the `Heading`. It does not pause the robot. 2. Turn the robot LEFT by hand. The `Heading` must go UP. 3. If it goes down, or barely moves, the logo and USB directions are wrong. Look at the hub again. ### A wheel turns the wrong way Leave this until the first drive test. Without a `.reversed(...)` line, the library reverses the left side. When your robot is built the other way, list **every** reversed drive motor: ```java title="Robot.java" drive(Drive.mecanum("front_left", "front_right", "back_left", "back_right") .motor("gobilda-5203-312").wheelMm(96) // List EVERY reversed drive motor. Without this line the left side is reversed. .reversed("front_right", "back_right") .imu("imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD)); ``` The Motor Direction Check tells you which ones ([Tune and check](https://crossbotics.com/ftc-helper/docs/tuning/)). ## Check it **Build:** in Android Studio, **Build > Make Project** ([the buttons](https://crossbotics.com/ftc-helper/docs/setup/06-build-and-install/#the-buttons)). **Done when:** the build finishes with no red errors. The robot cannot drive yet, because the buttons are in `Controls.java`, the next file. When the build shows red errors, read only the first one. It names the file, the line and the problem. ## Add a part When the robot drives, add your parts **one at a time**, and test each before the next. Each part is two lines in `Robot.java`: 1. At the top of the class: `public` + the kind of part + a name, for example `public Intake intake;`. 2. In `define()`: the line that makes it, with its name from the robot configuration. Every part has these attributes: | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `.part(id)` | recommended | which motor or servo it is, by its [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) id: the starting numbers and the simulator use its real speed and size | Defaults to general starting numbers | | `.optional()` | optional | the part may not be on the robot yet: INIT goes on without it | INIT stops if the part is missing | | `.looks(shapes...)` | optional | how it looks and where it sits, for the simulator | the simulator draws a guess | | `.tunables("Name")` | optional | read its numbers from another `Tunables.java` section | Defaults to the section named after the part | The two common parts come first, each with its usual line and its own attributes. The list at the end of the page has the other parts. ### Intake An intake is rollers or wheels that take pieces in. On one motor: ```java title="Robot.java" // At the top of the class: public Intake intake; Here in define(): // "intake" = the motor's name in the robot configuration. Its numbers: Tunables.Intake. // .part(...): which motor it is (optional, recommended). intake = add(Intake.motor("intake").part("gobilda-5203-1150")); ``` On continuous-rotation (CR) servos: ```java title="Robot.java" // Two continuous-rotation (CR) servos. The one that spins the wrong way is reversed. // "intake", "intake_right" = the servos' names in the robot configuration. Numbers: Tunables.Intake (the 1st name). // .part(...): which servo it is (optional, recommended). intake = add(Intake.crServos("intake", "intake_right").part("gobilda-2000-speed") .reversed("intake_right")); ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Intake.motor(name)` | **yes**, one of the two | an intake on one motor | - | | `Intake.crServos(names...)` | **yes**, one of the two | an intake on CR servos that run together | - | | `.holds(n)` | recommended | how many pieces it carries: count them by hand | Defaults to 4 (the simulator's guess) | | `.withCrServos(names...)` | optional | CR servos that run with the motor, like side wheels next to a roller | - | | `.reversed(names...)` | optional | these devices run the other way, like the second of two facing servos | - | | `.holds(n, "KIND")` | optional | how many of one kind it carries. 0 = it cannot take that kind | every kind counts the same | | `.onAtStart()` | optional | runs in from ▶ until your code stops it | Defaults to off: a button starts it | | `.stopsWhen(test)` | optional | never runs in while the test is true, like "the robot is full" ([Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/)) | it runs whenever asked | Its numbers: `inPower`, `outPower` ([Tunables: Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/#in-tunablesjava)). Every option and command: [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/). ### Launcher A launcher is a flywheel that shoots pieces, and the part that feeds it one piece at a time. ```java title="Robot.java" // A flywheel (in RPM) and the indexer that feeds it one piece at a time. // "launcher", "indexer" = names in the robot configuration. Numbers: Tunables.Launcher, .Indexer. // The motor's catalog id is in the brackets (needed). The indexer's .part(...) is optional, recommended. launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed"))); ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Launcher.flywheel(motor, id)` | **yes** | a flywheel on this motor. The library needs the id for its speed in RPM | - | | `.feeder(Indexer.servo(name))` | recommended, one of the three | a servo arm pushes each piece in | nothing feeds the wheel | | `.feeder(Indexer.crServo(name))` | recommended, one of the three | a CR servo wheel feeds the pieces, like goBILDA's "windmill" | nothing feeds the wheel | | `.feeder(Indexer.motor(name))` | recommended, one of the three | a motor feeds the pieces | nothing feeds the wheel | | `.reversed()` | optional | the flywheel turns the other way | - | | `.spinAtStart()` | optional | spins up at ▶, so the first shot goes at once | Defaults to off: it spins up when asked | | `.hood(...)`, `.feedStop(...)`, `.feedWheel(...)` | optional | a hood, a feed stop, a feed wheel ([Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/)) | - | | `.speedFromDistance(camera)` | optional | the speed follows the camera's distance to the goal | Defaults to one speed, `speedRpm` | Its numbers: `speedRpm`, `readyBandRpm` and the speed control (`kP`, `kF`, ...) ([Tunables: Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava)). The feeder's numbers are in its own section ([Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/#in-tunablesjava)). Every option and command: [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/). ### The other parts | Part | For | Look it up | | --- | --- | --- | | `Lift` | a slide that goes up and down | [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/) | | `Arm` | a part that swings on a hinge | [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/) | | `Claw` | a servo that opens and closes | [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/) | | `Wrist` | a servo that tilts a claw | [Wrist](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/) | | `Positioner` | any servo or motor that goes to set positions, like a fold-out | [Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/) | | `Turret` | a part that turns to aim | [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/) | | `Camera` | a webcam or Limelight | [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/) | | `Lights` | a light strip or Blinkin | [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/) | Each part also gets its numbers in `Tunables.java` and its buttons in `Controls.java`. A part has no buttons until you write its lines there. The next pages show how. --- **Next:** [Tunables.java](https://crossbotics.com/ftc-helper/docs/five-files/02-tunables-java/). **Look it up:** [RobotDefinition and every part](https://crossbotics.com/ftc-helper/docs/reference/robot-java/). **Go deeper:** [how the library fits together](https://crossbotics.com/ftc-helper/docs/guides/architecture/). --- # Tunables.java: the numbers URL: https://crossbotics.com/ftc-helper/docs/five-files/02-tunables-java/ `Tunables.java` holds your robot's **numbers**: how fast it drives, how far the lift goes, how fast the launcher spins. `Robot.java` says which parts the robot has. `Tunables.java` says their numbers. **Why a separate file:** you change numbers all season. In their own file, you can change them without touching the code that works. ## The smallest Tunables.java This is a whole `Tunables.java` for the robot of the [Robot.java page](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/): only the drive. Click a **(+)** to read what a line does. ```java title="Tunables.java" import static com.crossbotics.ftchelper.robot.Starting.*; // DEFAULT and MEASURE (1)! /** The five files, file 2 of 5: the numbers. One section per part, one number per line. */ public class Tunables { public static class Drive { // (2)! public static double maxPower = 0.5; // top wheel power: slow for the first drives (1.0) (3)! public static double practiceMaxPower = DEFAULT; // top wheel power in PRACTICE (same as maxPower) (4)! public static double slowSpeed = DEFAULT; // top power with the slow trigger held (0.3) public static double strafeCorrection = DEFAULT; // sideways moves: the Drive Tuner finds it (1.15) public static double turnKp = DEFAULT; // auto turns: push per degree off (0.012) public static double turnKd = DEFAULT; // auto turns: brake near the end (0.003) public static double moveMinPower = DEFAULT; // auto: least power that moves it (0.30) public static boolean calibrated = false; // true after the Drive Tuner: auto runs then (5)! } } ``` 1. This line lets you write the words `DEFAULT` and `MEASURE` in place of a number. Without it, the build fails with `cannot find symbol`. 2. A **section**: the numbers of one part. The drive's section is always called `Drive`. 3. A number you chose: half power, so the first drives are slow and safe. The library's own value is in brackets at the end of the comment. 4. `DEFAULT`: use the library's starting value (the one in brackets). Leaving the line out does the same, but the line shows you every number you can change. 5. Autonomous drives the robot only when this is `true`. Set it after the Drive Tuner, when moves are the right length. **The first line of the file** (above the import) must be: ```text package org.firstinspires.ftc.teamcode; ``` ## How the file works **One section per part.** The section's name is the part's name in the robot configuration, in CamelCase: each word starts with a capital letter, with no `_` and no spaces. | The part in Robot.java | Its section | | --- | --- | | the drive | `Drive` (always) | | `Intake.motor("intake")` | `Intake` | | `Positioner.servo("intake_deploy")` | `IntakeDeploy` | | `Launcher.flywheel("shooter", ...)` | `Shooter` | **One number per line.** Write it as `public static double name = value;`, or `public static boolean name = true;` for an on/off setting. Always write `public static`, because the library cannot read a number without it. The name must match exactly, with its capitals: `maxPower` works, `MaxPower` does not. **What to write for each number:** | The number | Write | At INIT | | --- | --- | --- | | You know it | the number | the library uses it | | A tuning number you do not know yet (a speed, `kP`) | `DEFAULT` | the library uses its starting value | | A safety limit or a servo position only your robot can give (a lift's `min`, a claw's `open`) | `MEASURE` | the TeleOp and autos **stop** and name the tool that finds it | **Why `MEASURE` stops:** a guessed limit or servo position can drive a part into the frame and break it. A guessed tuning number only makes a part slow or soft. More: [DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure). **Your own numbers.** A section that no part reads is yours, for example `Score` for a wait in one of your actions. Your code reads it as `Tunables.Score.dropWaitSec`. An autonomous's distances stay in its own file ([why](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#the-numbers-are-in-the-step)). ## The drive's numbers | Number | Needed? | What it sets | If you leave it out | Found with | | --- | --- | --- | --- | --- | | `maxPower` | optional | the most power the wheels get | Defaults to 1.0 | test: lower it for new drivers | | `practiceMaxPower` | optional | the most power in the PRACTICE profile | Defaults to `maxPower` (practice at match speed) | test: lower only for a new driver's first day | | `slowSpeed` | optional | the most power while the slow trigger is pulled | Defaults to 0.3 | test | | `strafeCorrection` | recommended (mecanum) | makes autonomous sideways moves the right length | Defaults to 1.15 | the Drive Tuner | | `turnKp` | optional | how hard an autonomous turn pushes, per degree off | Defaults to 0.012 | test: turns stop short (more) or wobble (less) | | `turnKd` | optional | how much an autonomous turn brakes near the end | Defaults to 0.003 | test: turns overshoot (more) | | `moveMinPower` | optional | the least power that still moves the robot | Defaults to 0.30 | test: it stops a little short (more) | | `calibrated` | **yes**, for autonomous | autonomous drives only when it is `true` | Defaults to `false`: autonomous will not drive | the Drive Tuner, then set it | Every drive number, with its units: [Tunables: Drive](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava). ## Tune a number, then copy it back You find most numbers on the robot, with a finder or by testing. Two ways give you a number: - **A finder** (Tune and check, on the Driver Hub) measures it and shows the line to copy, for example `Tunables.Drive: strafeCorrection = 1.210`. The finders: [Tune and check](https://crossbotics.com/ftc-helper/docs/tuning/). - **The tuning menu** changes a number while the robot runs. In the PRACTICE profile, after ▶, hold **GUIDE** for 1 second. Use the D-pad to choose and change a number, and press **A** to save ([tuning menu](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/)). **Copy every number back into `Tunables.java`, then build and install.** The next INIT lists the numbers saved on the hub under "Tuned on this robot (copy into Tunables.java)". **Why:** when you save a number only on the Control Hub, a new hub loses it, and the team's code does not have it. The file is the team's record. ## Check it **Build:** **Build > Make Project** ([the buttons](https://crossbotics.com/ftc-helper/docs/setup/06-build-and-install/#the-buttons)). **Done when:** the build has no red errors. At INIT, the Driver Hub shows one note per part with the numbers it used. A `MEASURE` stops INIT and names the tool that finds the number. ## A part's numbers When you add a part to `Robot.java`, add its section here. The sections below are for the two common parts. Each one shows the part's lines, so you can see what there is to change. Most lines hold `DEFAULT` or `MEASURE`, and a few have example numbers. ### Intake ```java title="Tunables.java" public static class Intake { // "intake" in the configuration public static double inPower = DEFAULT; // power taking pieces in, 0 to 1 (1.0) public static double outPower = DEFAULT; // power pushing pieces out (0.7) } ``` | Number | Needed? | What it sets | If you leave it out | Found with | | --- | --- | --- | --- | --- | | `inPower` | optional | power while it takes pieces in, 0 to 1 | Defaults to 1.0 | test: it throws pieces, or they jam (less) | | `outPower` | optional | power while it pushes pieces out, 0 to 1 | Defaults to 0.7 | test: pieces do not come out (more) | ### Launcher ```java title="Tunables.java" public static class Launcher { // "launcher" in the configuration public static double speedRpm = DEFAULT; // shot speed without the table (60% of top) public static double stepRpm = DEFAULT; // speed change per D-pad press (100) public static double readyBandRpm = DEFAULT; // "at speed" = this close to the target (60) public static double idleRpm = 1500; // spins between shots: quicker first shot (0) public static double shotIntervalSec = DEFAULT; // least time between two pieces (0.25) // The hub's speed control: the defaults for the motor until the Flywheel Finder (INIT shows them). // Then write the Finder's numbers in their place. public static double kP = DEFAULT; // push per speed error (kF / 10) public static double kI = DEFAULT; // fix a steady error (kP / 10) public static double kD = DEFAULT; // brake changes (0) public static double kF = DEFAULT; // steady power for a speed (from the motor) // {inches to the goal, RPM}, blended between rows. Example rows: write the Shot Tuner's instead. public static double[][] speedByDistance = {{24, 2200}, {48, 2550}, {72, 2900}, {96, 3250}}; } ``` | Number | Needed? | What it sets | If you leave it out | Found with | | --- | --- | --- | --- | --- | | `speedRpm` | recommended | the shot speed, in RPM | Defaults to 60% of the motor's top speed | the Shot Tuner, or test | | `kP`, `kI`, `kD`, `kF` | recommended | the hub's speed control | Defaults to numbers worked out from the motor | the Flywheel Finder | | `readyBandRpm` | optional | "at speed" means this close to the target | Defaults to 60 | test: it waits too long to fire (more) | | `idleRpm` | optional | the speed between shots. 0 = stop | Defaults to 0 | test: the first shot spins up too slowly | | `stepRpm` | optional | one D-pad press changes the speed by this | Defaults to 100 | the drivers' choice | | `shotIntervalSec` | optional | the least time between two shots | Defaults to 0.25 | the Flywheel Finder | | `speedByDistance` | optional | the shot table: `{inches, RPM}` rows, for a robot with a camera | Defaults to none: `speedRpm` always | the Shot Tuner | The part that feeds the launcher has its own section, named after its device. For a servo feeder: ```java title="Tunables.java" public static class Indexer { // "indexer" in the configuration public static double rest = MEASURE; // servo position, out of the way (Servo Finder) public static double push = MEASURE; // servo position, piece pushed (Servo Finder) public static double pushSec = DEFAULT; // time to push (0.25, or the servo's speed) public static double returnSec = DEFAULT; // time to come back (the same as pushSec) } ``` `rest` and `push` are **needed**: they are servo positions only your robot can give. The Servo Finder finds them. Every launcher and feeder number: [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava), [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/#in-tunablesjava). ### The other parts | Part | Its numbers | | --- | --- | | Lift, Arm | [Lift and Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#in-tunablesjava): `min` and `max` are **needed** | | Claw, Wrist, Positioner | [Claw, Wrist and Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#in-tunablesjava): the positions are **needed** | | Turret | [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/#in-tunablesjava) | | Camera | [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/#in-tunablesjava) | | Lights | [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/#in-tunablesjava) | --- **Next:** [Controls.java](https://crossbotics.com/ftc-helper/docs/five-files/03-controls-java/). **Look it up:** [every number of every part](https://crossbotics.com/ftc-helper/docs/reference/tunables/). **Go deeper:** [the finders](https://crossbotics.com/ftc-helper/docs/tuning/) and [the tuning menu](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/). --- # Controls.java: the buttons, and the TeleOp URL: https://crossbotics.com/ftc-helper/docs/five-files/03-controls-java/ `Controls.java` is your TeleOp: the program the drivers pick on the Driver Hub. It says what each button does. The library always sets up its own buttons (driving, pause, the button map). Each part's buttons are lines in this file, so you can read and change every one. ## The smallest Controls.java This is a whole `Controls.java`. The robot has no parts yet, so it has no buttons of its own. It drives on the library's buttons. The file writes them out so you can see each one, and it has a line for every free button. Click a **(+)** to read what a line does. ```java title="Controls.java" import com.crossbotics.ftchelper.robot.ControlMap; import com.crossbotics.ftchelper.robot.Pad; import com.crossbotics.ftchelper.teleop.LibraryButtons; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; /** The five files, file 3 of 5: the buttons, and the TeleOp. */ @TeleOp(name = "First Robot TeleOp") // (1)! public class Controls extends ControlMap { // (2)! public static boolean oneDriver = true; // (3)! // Always there: the library's buttons, on gamepad 1. These lines are the defaults (one driver): // without this method the buttons are the same. Change a line to move a button; null = no button. @Override protected void libraryButtons(LibraryButtons lib, Pad g1, Pad g2) { // (4)! lib.swapSticks(false); // left stick: drive and slide; right stick X: turn lib.slow(null); // slow while a trigger is pulled: none (the triggers are free) lib.slowToggle(g1.leftStickButton); // left stick click: slow on / off lib.fieldCentric(g1.rightStickButton); // right stick click, a double tap: field-centric on / off lib.pause(g1.back); // BACK: pause at the press; a tap goes on (5)! lib.resetForward(g1.back); // BACK held 1 s: "forward" is where the robot faces now lib.debug(g1.start, g1.back); // hold START, then press BACK: the debug lines lib.setPose(g1.start); // START held 1 s: set pose here (robots with odometry) lib.buttonMap(g1.guide); // GUIDE: the button map on the Driver Hub lib.tuningMenu(g1.guide); // GUIDE held 1 s: the tuning menu (PRACTICE profile) lib.allianceInInit(g1.x, g1.b); // in INIT: X = BLUE, B = RED } @Override protected void buttons(Robot robot, Pad g1, Pad g2) { // (6)! // Every other button is a line here: each part's buttons, then your own. This robot has no parts yet. // The free buttons: replace free() with a job, e.g. .press(...), .hold(...), .toggle(...), .tap(...). (7)! g1.a.free(); g1.b.free(); // B and X choose the alliance in INIT only: free in the match g1.x.free(); g1.y.free(); g1.lb.free(); g1.rb.free(); g1.lt.free(); // a trigger counts as pressed past half way g1.rt.free(); g1.dpadUp.free(); g1.dpadDown.free(); g1.dpadLeft.free(); g1.dpadRight.free(); g1.rightStickY.free(); // a stick: .use(...) gets its value every loop } } ``` 1. The TeleOp's name in the Driver Hub's list. Change it to your robot's name. 2. `ControlMap`: a TeleOp for the robot in your `Robot.java`. The library runs the loop, drives, and keeps every part updated. 3. `true`: one gamepad. The driver drives and runs the parts, and `g2` lines are on gamepad 1 too. Most teams start here. `false`: add gamepad 2 when you want to split the work, or for jobs that are hard to do while you drive (like arm control). Then the `g2` lines move to gamepad 2 ([One gamepad, and a second one](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/#one-gamepad-and-a-second-one-when-you-want-it)). 4. **Always there:** the library's own buttons, one line each. These lines are the defaults, so without this method the buttons are the same. Change a line to move a button. `null` = no button. 5. BACK pauses the robot at once: every motor stops. Keep it on a button: it is the drivers' safety stop. 6. **Every other button is a line here.** A part has no buttons until you add its lines. The reference has each part's usual lines ([Intake: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/#buttons-to-add), and the same for every part). 7. **Every free button has a line,** so you see what you can use. Replace `free()` with a job. When you add a part's lines, delete the `free()` lines of the buttons they use: one line per button. **The first line of the file** (above the imports) must be: ```text package org.firstinspires.ftc.teamcode; ``` ## Drive it With `Robot.java`, `Tunables.java` and this file, the robot drives. 1. **Build and install:** **Run** in Android Studio ([the buttons](https://crossbotics.com/ftc-helper/docs/setup/06-build-and-install/#the-buttons)). 2. Put the robot on a block, with its wheels off the floor. 3. On the Driver Hub, pick **First Robot TeleOp** and press **INIT**. The screen shows the button map. 4. Press **▶**. Push the left stick forward: all four wheels turn forward. 5. Take it off the block and drive. `Tunables.Drive.maxPower = 0.5` keeps it slow. 6. Check each one: - Stick up = forward, stick down = back, right stick right = turn clockwise. - Mecanum: left stick right = slide right, in a straight line. - Slow: pull LT (two gamepads; the further you pull, the slower), or click the left stick (one gamepad). - Mecanum: double-tap Y, or the right stick click with one gamepad (two buzzes: field-centric on). Turn the robot 90 degrees, and push the stick up. The robot still goes away from you. - Tap BACK: every part stops and the Driver Hub says PAUSED. Tap BACK again: it drives. **Robot-centric and field-centric.** Robot-centric (the start): stick up = the way the robot faces. Field-centric: stick up = away from the driver, whichever way the robot faces. "Away" is the way the robot faced at INIT, or what the autonomous left. When it is wrong: turn field-centric on, point the robot away from you, and hold BACK 1 s (one buzz). **In the simulator:** pick **Simulator** in the run list and click **Run**. Then pick the TeleOp on the simulator's Driver Hub. **Done when:** the robot drives forward, back, sideways (mecanum) and turns, the way the sticks say. When a wheel turns the wrong way, fix it in `Robot.java`: [a wheel turns the wrong way](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#a-wheel-turns-the-wrong-way). ## Two kinds of buttons **The library's own buttons are always there**, on gamepad 1. You write nothing for them, and every TeleOp has them. **Why:** BACK must always pause the robot, even in a file with a mistake. | Job | One gamepad (`oneDriver = true`) | Two gamepads | | --- | --- | --- | | Drive and slide | left stick | left stick | | Turn | right stick, left and right | right stick, left and right | | Slow | left stick click: slow on/off | LT (the further, the slower) | | Field-centric on/off (mecanum) | right stick click (a double tap) | Y (a double tap) | | Pause / go on | BACK (a tap) | BACK (a tap) | | Button map on the screen | GUIDE (a tap) | GUIDE (a tap) | | Tuning menu | GUIDE (held 1 s) | GUIDE (held 1 s) | | Choose the alliance (in INIT) | X = BLUE, B = RED | X = BLUE, B = RED | To move one: [Moving the library's buttons](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/). **Every other button is a line in `buttons(...)`.** A part has no buttons until you add its lines, so every button the robot has is a line you can read in this file. Each part's usual lines, ready to copy: | Part | Usual buttons | The lines | | --- | --- | --- | | Intake | RT: in (hold). LT: out (hold) | [Intake: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/#buttons-to-add) | | Launcher | LB: spin up / down. RB: fire one (tap), keep firing (hold). D-pad up and down: speed | [Launcher: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#buttons-to-add) | | Lift | A, X, Y: heights. D-pad up and down: next height. Left stick: by hand | [Lift: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#buttons-to-add) | | Arm | right stick: by hand | [Arm: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/#buttons-to-add) | | Claw | B: open / close | [Claw: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#buttons-to-add) | | Wrist | D-pad left and right: positions | [Wrist: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/#buttons-to-add) | | Turret | right stick, left and right: by hand. right stick click: follow the goal on / off | [Turret: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/#buttons-to-add) | **INIT tells you what is missing.** When a part's usual buttons are not in `Controls.java`, INIT shows a line for it, for example `Intake: usual buttons not in Controls.java: G2 RT (in (hold)), G2 LT (out (hold))`. INIT counts a button you used for something else as your choice. ## A whole robot's buttons The example [`allbuttons/Controls.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/allbuttons/Controls.java) is a robot with a mecanum drive, an intake, a launcher and two drivers. It has every library button in `libraryButtons(...)`, the intake's and the launcher's usual lines, and a `free()` line for every free button on both gamepads. A test checks that its lines are the parts' usual ones. ## Add your own button Each button line has up to four pieces: ```java // 1. which button 2. how it starts 3. what it does 4. what the drivers see g2.y .press( robot.claw::open) .says("open the claw"); ``` For example, two buttons for a claw and a lift: ```java title="Controls.java" // Once per press. "::" hands over the method; the button runs it later. g2.y.press(robot.claw::open).says("open the claw"); // Several commands: "() ->" starts a small piece of code (a lambda). g2.x.press(() -> robot.lift.goTo("low")).says("lift to low"); ``` **Always add `.says(...)`.** The words go on the button map, so the drivers know what the button does. ### 1. Which button | Buttons | Name in the code | | --- | --- | | Face buttons | `a`, `b`, `x`, `y` | | Bumpers | `lb`, `rb` | | Triggers (pressed past half way) | `lt`, `rt` | | D-pad | `dpadUp`, `dpadDown`, `dpadLeft`, `dpadRight` | | Stick clicks | `leftStickButton`, `rightStickButton` | | Small buttons | `back`, `start`, `guide` | | Sticks (a number from -1 to 1) | `leftStickX`, `leftStickY`, `rightStickX`, `rightStickY` | ### 2. How it starts: the press types | Press type | Write | The job runs | | --- | --- | --- | | Press | `.press(job)` | once, the moment the driver presses it | | Let go | `.release(job)` | once, the moment the driver lets it go | | Hold | `.hold(job)` | every loop while the driver holds it | | Hold, then stop | `.hold(job, stopJob)` | every loop while the driver holds it, then `stopJob` once when the driver lets go | | On / off | `.toggle(part)` | each press switches the part on or off | | On / off, two jobs | `.toggle(onJob, offJob)` | presses take turns | | Tap | `.tap(job)` | once per quick press | | Double tap | `.doubleTap(job)` | once, on the second quick tap | | Several taps | `.taps(3, job)` | once, on the last of 2 to 5 quick taps | | Tap, then hold | `.tapThenHold(job)` | a tap, then press again and hold: every loop while held | | Held for a time | `.heldFor(1.0, job)` | once, after the driver holds it 1 s: a safe "are you sure?" | | Two buttons | `g2.lb.with(g2.y, job)` | once, when the driver presses Y while holding LB | | A stick | `g2.leftStickY.use(robot.lift::manual)` | every loop, with the stick's value | **Gestures can share a button.** `tap`, `doubleTap`, `taps`, `tapThenHold`, `heldFor` and `hold` chain on one button, each with its own job: ```java g2.rb.tap(robot.launcher::fire).says("fire one") .hold(robot.launcher::fireWhileHeld, robot.launcher::ceaseFire).says("keep firing"); ``` `press`, `toggle` and `release` each need a button of their own. [Press types](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/) says when each gesture's job runs, and how to change the double-tap time and the hold time. ### 3. What it does | The job | Example | | --- | --- | | A part's command | `robot.claw::open` | | A few commands | `() -> { robot.claw.open(); robot.intake.stop(); }` | | An action: several steps, like "score" | `Actions.scoreHigh(robot)` (the next page: `Actions.java`) | | A part to switch on and off | `robot.intake` (with `.toggle(...)`) | **A job must never wait.** No `sleep(...)` and no `while` loop: it freezes the whole robot. To do steps one after another, use an action. ### 4. What the drivers see and feel | You want | Write | | --- | --- | | Words on the button map | `.says("open the claw")` | | A buzz when the job runs | `.rumble()`, or `.rumble(2)` for two buzzes | | A buzz when something becomes true | `g2.rumbleWhen(robot.launcher::isReady);` (a line of its own) | | A value on the Driver Hub | `show("Lift", robot.lift::position);` (a line of its own) | ## Change a part's button A part's buttons are your lines: change the button in its line. For example, the intake on the bumpers in place of the triggers: ```java title="Controls.java" // The intake's usual lines are on RT and LT: here the same jobs are on the bumpers. g2.lb.hold(robot.intake::holdIn, robot.intake::stop).says("intake in (hold)"); g2.rb.hold(robot.intake::out, robot.intake::stop).says("intake out (hold)"); ``` ## Check it **Build and install**, then INIT the TeleOp. **Done when:** INIT shows your button map with your words, and each button does its job. INIT stops with a message when a button has two jobs, or when your job is on one of the library's buttons. The message names the button. **If the drive goes wrong:** | Problem | Fix | | --- | --- | | INIT stops with a list of names | A motor name in `Robot.java` does not match the configuration (capitals too) | | It spins or drifts when it should go straight | A motor direction is wrong: [a wheel turns the wrong way](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#a-wheel-turns-the-wrong-way) | | Stick up drives backward | Every direction is flipped: reverse the other side | | It slides on a slant when it should slide sideways | Two motor names are on the wrong wheels (for example `front_left` and `back_left` swapped) | | Field-centric goes the wrong way or circles | The IMU's logo and USB directions ([check it](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#how-your-control-hub-is-mounted)), or "away" is wrong: hold BACK 1 s | | Everything stopped and does not move | It is paused: tap BACK | | Slow even without LT | `maxPower` is low, or `practiceMaxPower` is low in the PRACTICE profile | --- **Next:** [Actions.java](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/). **Look it up:** [every press type and option](https://crossbotics.com/ftc-helper/docs/controls/). **Go deeper:** [the cookbook's button recipes](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/). --- # Actions.java: several parts together URL: https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/ ## Do you need it yet? Maybe not. A job for one part is a button line in `Controls.java`, with no action. Some parts also come with **ready-made actions**, which need no line in `Actions.java`. | Ready-made action | What it does | Use it | | --- | --- | --- | | Fire 1, Fire 2 ... | fires that many pieces. It is done when the last one has left | `robot.launcher.fireAction(2)` | | Fire all | fires every piece the robot holds | `robot.launcher.fireAllAction()` | | Fire at a speed | the same, at this flywheel speed (RPM), then back to the usual speed | `robot.launcher.fireAction(2, 2250)` | | Ready to launch | spins up. It is done when the flywheel is at speed | `robot.launcher.readyAction(3)` (3 = at most 3 s) | | Eject | one piece out at a low speed, like a wrong-color piece | `robot.launcher.ejectAction()` | **You need `Actions.java`** when one button or one autonomous step must do several things in order, or must wait for one part before the next part moves. ## The smallest Actions.java This is a whole `Actions.java`. The robot has no parts yet, so it has no actions. Copy it now: the autonomous files on the next page use it. ```java title="Actions.java" import com.crossbotics.ftchelper.robot.Action; // (1)! /** The five files, file 4 of 5: steps that use several parts together. */ public class Actions { // One method per action: public static Action name(Robot r) { ... }. Use it in Controls.java and in autos. (2)! // This robot has no parts yet, so it has no actions. A part's ready-made actions need no line here. } ``` 1. Every action is an `Action`. This line lets the file use that name. 2. Each action is one method in this class. The next section shows one, line by line. **The first line of the file** (above the import) must be: ```text package org.firstinspires.ftc.teamcode; ``` ## Your first action This robot has the two common parts from the [Robot.java page](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#add-a-part): an intake and a launcher. Its action fires 3 pieces while the intake runs, to push each piece in. Click a **(+)** to read what a line does. ```java title="Actions.java" /** Fires 3 pieces with the intake running, to push each one in. Then the intake stops. */ public static Action fireWithIntake(Robot r) { // (1)! return Action.named("Fire with intake") // (2)! .then(r.intake::in, () -> r.launcher.fire(3)) // (3)! .waitUntil("the shots", () -> !r.launcher.isShooting(), 9.0) // (4)! .then(r.intake::stop); // (5)! } ``` 1. `public static Action`: a method that makes the action. `r` is your robot, so the steps can use `r.intake` and `r.launcher`. You start it with the class name: `Actions.fireWithIntake(robot)`. 2. `Action.named(...)` starts a new action. The Driver Hub shows the name while it runs. 3. `.then(...)` does these now, in the same loop, then goes to the next step. It has two commands, so the intake and the launcher start together. - `r.intake::in` is a **method reference**: "run `r.intake.in()` when the action gets here". - `() -> r.launcher.fire(3)` is a **lambda**: the same, for a command with inputs. 4. `.waitUntil(...)` waits until the test is true: the launcher is not shooting any more. - `"the shots"`: the words on the Driver Hub while it waits. - `9.0`: the **time limit**, in seconds. If the shots are not done in 9 s, the action stops and the Driver Hub says why. A wait never goes on forever. 5. The last step: the intake stops. Then the action is done. ## The steps Every action is built from four steps: | Step | What it does | Example | | --- | --- | --- | | `.then(command)` | does it now, then goes to the next step | `.then(r.claw::open)` | | `.then(command, command, ...)` | does them all now, in the same loop: the parts move together | `.then(r.intake::in, r.claw::close)` | | `.waitSeconds(s)` | waits this many seconds. The robot keeps running: this is `sleep`, done safely | `.waitSeconds(0.5)` | | `.waitUntil("words", test, s)` | waits until the test is true, at most `s` seconds. When it waits too long, the action stops | `.waitUntil("lift up", r.lift::isAtTarget, 2.0)` | **What you can wait for:** each part answers yes / no questions. | Part | Questions | | --- | --- | | Launcher | `isReady()` (at speed), `isShooting()`, `isSpinning()`, `isEjecting()` | | Intake | `isRunning()`, `isPushingOut()` | | Lift, Arm (a motor) | `isAtTarget()`, `isAt("high")` | | Claw, Wrist, Positioner (a servo) | `isDone()`, `isAt("open")`. A servo cannot say where it is: `isDone()` turns true after its travel time, `travelSec` ([Tunables](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#in-tunablesjava)) | | Turret | `isAimed()`, `isHomed()` | | Pieces | `isFull()`, `isEmpty()` | To wait for the opposite, put a `!` in front: `() -> !r.launcher.isShooting()` = "not shooting". ## Start it from a button Write the button's line in `Controls.java`, inside `buttons(...)`, in place of its `free()` line: ```java title="Controls.java" g2.y.press(Actions.fireWithIntake(robot)).says("fire 3 with the intake"); g2.x.press(robot.launcher.fireAllAction()).says("fire all"); // a ready-made action ``` - `press(action)` starts the action. **Press again while it runs, and it stops** (canceled, safely). - The other press types start an action too: `tap`, `doubleTap`, `heldFor`, `with` ([the press types](https://crossbotics.com/ftc-helper/docs/five-files/03-controls-java/#2-how-it-starts-the-press-types)). ## Use it in an autonomous In an autonomous, the same action is a step. The next page explains autonomous files. Below is only the action's line. ```java title="autos/YourAuto.java" s.start("Against our wall, facing the field", 0) .alongside(robot.launcher.readyAction(3)) // spin up while it drives .forward("To the shooting spot", 24, 0.5) .action(Actions.fireWithIntake(robot), 9) // waits until it is done (at most 9 s) .right("Park", 12, 0.5); ``` | Step | What it does | | --- | --- | | `.action(action, s)` | starts the action and waits until it is done, at most `s` seconds (10 if you leave it out). When it takes too long, the autonomous cancels it, the report says so, and the autonomous goes on | | `.alongside(action)` | starts the action and goes on at once: it runs during the next steps | **Why write it once:** fix the action in `Actions.java`, and TeleOp and every autonomous get the fix. The simulator's **auto builder** lists your `Actions.java` actions too, next to the ready-made ones ([the auto builder](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/)). ## The rules every action follows - **It never makes the robot wait.** An action does a little every loop. The robot keeps driving and every other button works while it runs. **Why:** a `sleep()` or a `while` loop in a button job freezes the whole robot until it ends. Put the wait in an action: `.waitSeconds(...)`, `.waitUntil(...)`. - **The driver always wins.** When the driver moves a part the action uses, the action stops. - **One part, one action.** When a second action commands the same part, the first action stops. - **A wait that runs out of time stops the action.** The Driver Hub says why, for example `timed out waiting for the shots`. - **A stopped action leaves its parts safe.** An intake stops, a lift holds its height, and the launcher drops the shots still waiting. A finished action keeps its last commands. - **A part that is not on the robot yet** (`.optional()` in Robot.java): the action skips it and goes on with the other parts. ## An action when the OpMode starts An action can run once, right after ▶, in autonomous and in TeleOp. For example, it folds an intake down. **Where:** `Robot.java`, in `define()`. ```java title="Robot.java" // In Robot.java's define(): this action runs once, right after ▶ (autonomous and TeleOp). atStart(() -> Actions.deployIntake(this)); ``` It never runs in INIT. **Why:** people are still next to the robot in INIT, so the library moves nothing before ▶. This is the library's choice, not a game rule. ## Check it **In the simulator:** pick **Simulator** in the run list next to Android Studio's **Run** button, and click **Run**. Pick your TeleOp, INIT, ▶. Press the action's button. **On the robot:** 1. Put pieces in the robot. Stand clear of the launcher. Keep a hand near STOP. 2. INIT, ▶. Press the action's button. 3. Watch the Driver Hub: `Fire with intake: step 2 of 3 (the shots)`. After it ends: `done`. 4. Press the button, then press it again: the Driver Hub says `canceled`, and the intake stops. **Done when:** one button runs every step in order, and a second press stops it. ## If something goes wrong | Problem | Why, and the fix | | --- | --- | | `timed out waiting for ...` | The part needs more time than the limit, or it never got there. Tune the part, or give the wait more seconds. | | The action stops at once | Something else commands the same part: the driver's stick or button, or another action. | | Nothing happens on the button | Another line uses the same button (INIT stops and names it), or this press canceled the action. | | The robot freezes while a button job runs | The job has a `sleep()` or a `while` loop. Make it an action with `.waitSeconds(...)`. | | `cannot find symbol: Actions` | The file is not in the `teamcode` folder, or its first line is not `package org.firstinspires.ftc.teamcode;`. | --- **Next:** [autos/](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/). **Look it up:** [Action: every step](https://crossbotics.com/ftc-helper/docs/reference/steps/#action). **Go deeper:** [Why commands never wait](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/) and [the cookbook's action recipes](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/). --- # autos/: your autonomous programs URL: https://crossbotics.com/ftc-helper/docs/five-files/05-autos/ On this page you make the smallest auto: the robot drives out of its start spot. With it, your robot is the **smallest robot that works**. It drives in TeleOp, and it runs an autonomous. ## Make the folder **If you started from [Pick your start](https://crossbotics.com/ftc-helper/docs/pick-your-start/):** you already have the `autos` folder and an autonomous in it. Do not make them again. Read this page, and compare your file with the one below. In Android Studio's **Project** panel, right-click the `teamcode` folder, then **New > Package**. Type `autos` after the `teamcode.` that is already there. **Why "Package":** in Java, a folder of code is a package. More help: [make a new file or folder](https://crossbotics.com/ftc-helper/docs/start-from-zero/#make-a-new-file-or-folder). ## The smallest auto Make a new Java file `FirstAuto` in the `autos` folder (right-click `autos`, **New > Java Class**). Replace everything in it with this. Click a **(+)** to read what a line does. ```java title="autos/FirstAuto.java" import com.crossbotics.ftchelper.robot.Auto; import com.crossbotics.ftchelper.robot.Steps; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; /** The five files, file 5 of 5: an autonomous. The smallest one: it drives out of the start spot. */ @Autonomous(name = "First Robot Auto", preselectTeleOp = "First Robot TeleOp") // (1)! public class FirstAuto extends Auto { // (2)! @Override protected void steps(Steps s, Robot robot) { // (3)! s.start("Against our wall, facing the field", 0) // (4)! .forward("Leave the start", 12, 0.4); // (5)! } } ``` 1. `name`: the auto's name on the Driver Station. `preselectTeleOp`: the name of your TeleOp, exactly as in `@TeleOp(name = ...)` in `Controls.java`. When the auto ends, the Driver Station has that TeleOp chosen and ready. 2. `extends Auto`: this file is an autonomous for your robot. `Auto` is the library's autonomous. `` is your `Robot.java`, so every part on the robot is in `robot`. 3. `steps(...)` is a **list of steps, read top to bottom**. Each step starts on a new line with a dot. The last step ends with `;`. 4. `start(...)`: where the drive team puts the robot. - The words show on the Driver Hub in INIT. Write them for a nervous driver. - `0` is the **heading**: the way the robot faces. 0 = straight away from your drivers. TeleOp's field-centric "forward" uses it too, so get it right. 5. `forward(...)`: drive forward. It waits until the move is done, then goes to the next step. - `"Leave the start"`: the step's name, in the report at the end. - `12`: how far, in inches. - `0.4`: the most power it may use (0 to 1). It slows down near the end, so it does not overshoot. **The first lines of the file** (above the imports) must be: ```text package org.firstinspires.ftc.teamcode.autos; import org.firstinspires.ftc.teamcode.Robot; ``` **Why the extra import:** `Robot.java` is in the folder above `autos`, called `teamcode`. This line tells Java where it is. `Controls.java` needs no such line, because it is in the same folder as `Robot.java`. ## The numbers are in the step Write each distance in the step: `12`, not a name from `Tunables.java`. **Why:** - Each auto has its own numbers. When you change one auto, the others do not change. - The [auto builder](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/) can read the auto, change a number, and give you the new file. `Tunables.java` keeps the **robot's** numbers: speeds, positions and gains. They are the same in every auto. ## Tune the drive first On a real robot, an auto **does not move** until you tell it that the drive is tuned. The Driver Hub says `AUTONOMOUS IS OFF: the drive is not tuned yet`. **Why:** the robot only knows how far its wheels turned. If the wheel size is a little wrong, every move is a little wrong. The library stops a robot that could drive much too far. 1. On the Driver Hub, pick **Tune and check** (TeleOp list, group "Finders"). You need no file for it. 2. Pick **Drive Tuner**, then run its **Drive** test, and its **Strafe** test for a mecanum robot. Each one drives 48 inches. Measure, and enter what you measured. 3. Copy the lines it shows into your files. The wheel size goes in `Robot.java`, and the strafe correction goes in `Tunables.java`. 4. In `Tunables.java`, set `calibrated = true` in the `Drive` section. Every step, and what each screen shows: [the Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/). **The simulator does not need this.** There, an auto runs before the Drive Tuner, with the warning `Drive not tuned: runs in the simulator only`. ## What you get with no extra code You wrote only the list of steps. Every auto also gets these: | You get | What it does | | --- | --- | | An INIT menu | **X** = blue alliance, **B** = red. A start delay (0 to 10 s), to keep out of a partner's way. The PRACTICE or COMPETITION profile. D-pad up/down picks a line, left/right changes it. | | The 30 s timer | The steps stop when autonomous ends. Everything stops, even after an error. | | The report | One line per step at the end, like `Leave the start: done`. It is in the robot log, and on TeleOp's INIT screen too. | | The change to TeleOp | The alliance and the robot's heading go to TeleOp, so field-centric stays right. | ### PRACTICE and COMPETITION A **profile** is a mode for the whole robot: autos and TeleOp. The Control Hub saves it, and it stays until someone changes it. | | PRACTICE | COMPETITION | | --- | --- | --- | | For | the shop, tests, first runs | matches | | Wheel power | the same: `maxPower` (unless you set `practiceMaxPower`) | `maxPower` | | Extra lines on the screen | yes | no | | The tuning menu | can open | stays closed | | INIT says | `!! PRACTICE profile` | nothing | **Change it** in any auto's INIT menu: the **Profile** line. COMPETITION is the default, so a new robot is safe at an event. **Before every match:** check that it says COMPETITION. More: [Profiles](https://crossbotics.com/ftc-helper/docs/guides/profiles/). **Red and blue:** a move straight forward or back is the same for both alliances. Moves to the side and turns can need a change for red: [red and blue](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#red-and-blue). ## More steps Start with these steps. Write each one on a new line, before the `;`: | Step | What it does | Example | | --- | --- | --- | | `.forward(name, inches, power)` | drives forward, then waits until it is there | `.forward("To the goal", 24, 0.5)` | | `.back(name, inches, power)` | drives backward | `.back("Off the wall", 6, 0.4)` | | `.left(name, inches, power)`, `.right(...)` | slides to the side, still facing the same way (mecanum only) | `.right("Park", 20, 0.7)` | | `.turnLeft(name, degrees, power)`, `.turnRight(...)` | turns in place | `.turnLeft("Face the goal", 45, 0.4)` | | `.waitSeconds(name, s)` | waits this many seconds | `.waitSeconds("Let it settle", 0.5)` | | `.action(action, s)` | runs an action from `Actions.java`, then waits until it is done (at most `s` seconds) | `.action(Actions.fireWithIntake(robot), 9)` | Write the numbers in these steps as plus numbers. The word says which way. (A minus number goes the other way: `back(..., -6, ...)` drives forward. Use the other word.) **At an angle.** `.move(name, inches, angle, power)` drives at any angle, and `.turn(name, degrees, power)` turns by any angle. Every angle in an autonomous counts the same way: **counterclockwise, 90 = left**, like the IMU (the hub's turn sensor). The same is true for the heading in `start(...)`. More, with a picture: [every angle counts counterclockwise](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/#the-words-in-every-step). More: [signs and units](https://crossbotics.com/ftc-helper/docs/conventions/). An action in an auto: [Actions.java, use it in an autonomous](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/#use-it-in-an-autonomous). ## Check it **In the simulator:** pick **Simulator** in the run list next to Android Studio's **Run** button, and click **Run**. Pick **First Robot Auto** (your auto's name), INIT, ▶. The robot drives forward 12 in. **To run it again,** press **Back to start** first (Control Hub panel, Robot tab). This auto gives no spot on the field, so the simulator leaves the robot where it stopped last time. **On the robot:** 1. Do [Tune the drive first](#tune-the-drive-first). 2. In INIT, pick the **PRACTICE** profile ([above](#practice-and-competition)). It shows the debug lines. For a slow first run, set `maxPower` low in `Tunables.Drive`. 3. Put the robot where the `start` words say. Keep a hand near STOP. 4. INIT, read the words, ▶. Read the report at the end. 5. Measure how far it went. Change the number in the step, build and install, and run it again. **Done when:** the robot drives out of its start spot, and the report says `Leave the start: done`. Your robot now drives in TeleOp and in autonomous. ## If something goes wrong | Problem | Why, and the fix | | --- | --- | | `AUTONOMOUS IS OFF: the drive is not tuned yet` | `calibrated` is `false`. Do [Tune the drive first](#tune-the-drive-first). | | The auto is not on the Driver Station | When it is in the TeleOp list, the file needs `@Autonomous`. When it is in no list, build and install again. | | `cannot find symbol: Robot` | The `import org.firstinspires.ftc.teamcode.Robot;` line is missing. | | It drives the wrong distance | The wheel size is wrong. Run the Drive Tuner's **Drive** test again. | | It drives the wrong way | The heading in `start(...)` is wrong, or the hub's direction in `imu(...)` in `Robot.java`. Check both. | | The TeleOp is not chosen after the auto | `preselectTeleOp` must be the TeleOp's name, exactly. | --- ## Next Your robot is the smallest robot that works. **Next:** [Add to your robot](https://crossbotics.com/ftc-helper/docs/add-to-robot/): add parts, one at a time. Then [Controls](https://crossbotics.com/ftc-helper/docs/controls/) and [Building autos](https://crossbotics.com/ftc-helper/docs/building-autos/): turns, actions, multiple autos, the auto builder, and choices in INIT. **Look it up:** [every step](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto). **Go deeper:** [the cookbook's autonomous recipes](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/). --- # Controls URL: https://crossbotics.com/ftc-helper/docs/controls/ | # | Page | You learn | | --- | --- | --- | | 1 | [How buttons work](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/) | One gamepad or two. The four pieces of a button line. What a job can be, and modes. What INIT checks. | | 2 | [Press types](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/) | Every way to press: tap, hold, double tap, toggle, two buttons together, and more. One line of code each. | | 3 | [What the drivers see and feel](https://crossbotics.com/ftc-helper/docs/controls/03-see-and-feel/) | Words on the button map, buzzes, lights, and values on the screen. | | 4 | [Move the library's buttons](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/) | Driving, pause, field-centric, the menus: put them on other buttons, or free them. | **Start with page 1.** Each page has short examples. Copy the ones your robot needs. **Next:** [How buttons work](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/). --- # How buttons work URL: https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/ ## One gamepad, and a second one when you want it Most teams start with **one gamepad**. One driver drives and runs the parts. The second team member at the field helps: they watch the field, call out game pieces and time, and watch the robot's parts. **Gamepad 2 is optional.** Add it when your team wants to split the work, or for jobs that are hard to do while you drive, like arm control. Then the **driver** (gamepad 1) drives, and the **operator** (gamepad 2) runs the parts. | In the code | One gamepad (`oneDriver = true`) | Two gamepads (`oneDriver = false`) | | --- | --- | --- | | `g1` | gamepad 1, the driver | gamepad 1, the driver | | `g2` | **also gamepad 1** | gamepad 2, the operator | The switch is one line at the top of `Controls.java`. The starting files have `oneDriver = true`. **Where:** `Controls.java`, at the top of the class. ```java title="Controls.java" public static boolean oneDriver = true; // false: gamepad 2 runs the parts ``` **Write the parts' buttons on `g2` from the start.** With one gamepad, `g2` is gamepad 1, so they work now. When you add gamepad 2 later, change `oneDriver` to `false`, and those lines move to gamepad 2. You change no other line. With one gamepad, two lines on the same button stop INIT with a message. The library's own buttons also move a little with one gamepad: slow goes on the left stick click. So the triggers are free for your parts ([Every library button](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/#every-library-button)). ## The buttons The docs use the Logitech names (A, B, LB...). A PlayStation controller has the same buttons with other names. The code name is the same for both. The library's screens (the button map, the tuning menu) show the names on the controller that is plugged in. ![A gamepad with each button's code name, Logitech name and PlayStation name](https://crossbotics.com/ftc-helper/docs/images/gamepad-buttons.svg) | Buttons | Logitech | PlayStation | Name in the code | | --- | --- | --- | --- | | Face buttons | A, B, X, Y | × cross, ○ circle, □ square, △ triangle | `a`, `b`, `x`, `y` | | Bumpers | LB, RB | L1, R1 | `lb`, `rb` | | Triggers (they count as pressed past half way) | LT, RT | L2, R2 | `lt`, `rt` | | D-pad | D-pad | D-pad | `dpadUp`, `dpadDown`, `dpadLeft`, `dpadRight` | | Stick clicks (press the stick down) | left and right stick | L3, R3 | `leftStickButton`, `rightStickButton` | | Small buttons | BACK, START, GUIDE (the middle button) | SHARE, OPTIONS, PS | `back`, `start`, `guide` | | Sticks (a number from -1 to 1, up and right are +) | left and right stick | left and right stick | `leftStickX`, `leftStickY`, `rightStickX`, `rightStickY` | ## The four pieces of a button line Each button line has up to four pieces, like an order from a menu: ```java // 1. which button 2. how it starts 3. what it does 4. feedback g2.lb .tap( robot.launcher::fire) .says("fire one").rumble(); ``` 1. **Which button:** the gamepad, a dot, then the button: `g2.lb`. 2. **How it starts:** the press type, for example `.tap(...)` or `.hold(...)` ([Press types](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/)). 3. **What it does:** the job (below). 4. **Feedback:** what the drivers see and feel. Optional, but always add `.says(...)`: the words go on the button map ([What the drivers see and feel](https://crossbotics.com/ftc-helper/docs/controls/03-see-and-feel/)). **Where:** `Controls.java`, inside `buttons(Robot robot, Pad g1, Pad g2) { ... }`. ```java title="Controls.java" g2.y.press(robot.claw::open).says("open the claw"); g2.x.press(() -> robot.lift.goTo("low")).says("lift to low"); ``` `buttons(...)` runs once, at INIT. It only connects the jobs to the buttons. The library's **loop** then runs many times a second: each time, it reads the gamepads, runs the jobs that are due, and updates every part. You never write the loop. ## What a job can be | Kind | Example | Notes | | --- | --- | --- | | A method of a part | `robot.claw::open` | `::` hands over the method, and the button runs it later | | A few commands | `() -> { robot.claw.open(); robot.intake.stop(); }` | `() ->` starts a small piece of code (a **lambda**) | | An action (several steps) | `Actions.scoreHigh(robot)` | for `press`, `tap`, `doubleTap`, `taps`, `heldFor`, `with`: the gesture starts it, and the same gesture again cancels it ([Actions.java](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/)) | | A part to switch | `robot.intake` | for `toggle(...)` only | | A mode to switch | `robot.turret.followMode()` | for `toggle(...)` only ([Modes](#modes), below) | **A job must never wait.** Put no `sleep(...)` and no `while` loop in a job. The code compiles, but it freezes the **whole robot** until the job ends: no driving, no other button, no part updates. The Driver Station then warns: `... took 512 ms: the whole robot stopped that long. No sleep() or while loop in a button job: use an Action with waitSeconds (docs: Actions.java)`. To wait between steps, make an action with `waitSeconds(...)` or `waitUntil(...)`, and put the action on the button ([Actions.java](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/)). ### Modes A **mode** is a rule a part follows every loop while the mode is on. For example, the turret follows the goal, or the robot turns to face the goal. A mode is for an "always" rule. An action is for steps that end. | Mode | What it does while it is on | | --- | --- | | `robot.turret.followMode()` | the turret turns to the goal ([Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/)) | | `robot.aimMode()` | the whole robot turns to face the goal ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)) | | `robot.launcher.speedMode()` | the launcher sets its speed from the distance to the goal ([Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/)) | | `robot.aim().movingShotMode()` | the aim corrects for the robot's motion, so it can shoot while it drives (needs odometry, [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)) | | `robot.reverseDriveMode()` | the back of the robot acts as the front: forward and slide flip, turning does not | A button switches a mode like a part. **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" g2.rightStickButton.toggle(robot.turret.followMode()).rumble().says("follow the goal on/off"); ``` With `.rumble()`, the drivers feel it: two buzzes = on, one buzz = off. Some modes turn on only when they can work: whole-robot aim needs a goal in view. A press that cannot turn it on gives one buzz (off). An action or an auto can switch a mode too: `robot.turret.followMode().on()` ([Modes in the reference](https://crossbotics.com/ftc-helper/docs/reference/steps/#modes)). ## The library's own buttons Some of gamepad 1's buttons have library jobs: driving, pause, the menus. You write nothing for them. **Why:** BACK must always pause the robot, even in a file with a mistake. | Job | One gamepad (`oneDriver = true`) | Two gamepads | | --- | --- | --- | | Drive and slide | left stick | left stick | | Turn | right stick, left and right | right stick, left and right | | Slow | left stick click: slow on/off | LT (the further, the slower) | | Field-centric on/off (mecanum with an IMU or odometry) | right stick click (a double tap) | Y (a double tap) | | Pause / go on | BACK (a tap) | BACK (a tap) | | Debug lines | START, then BACK | START, then BACK | | Set pose here (odometry) | START (held 1 s) | START (held 1 s) | | Button map on the screen | GUIDE (a tap) | GUIDE (a tap) | | Tuning menu | GUIDE (held 1 s) | GUIDE (held 1 s) | | Choose the alliance (in INIT) | X = BLUE, B = RED | X = BLUE, B = RED | Field-centric on/off needs a **double tap**: two presses within 0.35 s. **Why:** one tap by accident would turn the sticks around. You can move or free every one of these buttons: [Move the library's buttons](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/). ## A part's buttons A part has no buttons until `Controls.java` has its lines. So every button the robot has is a line you can read in this file. Each part's page has its usual lines, ready to copy ("Buttons to add" in the [part pages](https://crossbotics.com/ftc-helper/docs/reference/)). INIT names each usual button of a part that is still free: `Intake: usual buttons not in Controls.java: G2 RT (in (hold)), ...`. ## The rules (INIT checks them) - **One job per button, or several gestures.** A button with `press(...)` and `tap(...)` stops INIT: `Controls.java: G2 B has two jobs`. The same gesture twice stops INIT too: `G2 A has two "tap" jobs`. - **A job of yours on a library button** stops INIT. The message names the button. Move the library's job first ([page 4](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/)). - **Two things on one button:** put both in one lambda: `g2.dpadLeft.press(() -> { robot.claw.open(); robot.intake.stop(); }).says("drop")`. - **`.free()` keeps a button empty**, for example `g2.rightStickX.free()`. INIT then does not name it as free. - **A button that is down as you press ▶** (start on the Driver Hub), or as the tuning menu closes, does nothing until you let it go. **Why:** a thumb that rests on a button must not start a job. ## Done when - Each button line in your `Controls.java` has a `.says(...)`. - INIT shows no stop message about buttons. - A tap of GUIDE shows the button map, and it lists every button you wrote. --- **Next:** [Press types](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/). **Look it up:** [Controls.java reference](https://crossbotics.com/ftc-helper/docs/reference/controls/). **Go deeper:** [the cookbook's button recipes](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/). --- # Press types URL: https://crossbotics.com/ftc-helper/docs/controls/02-press-types/ A **press type** says when the job runs: at the press, while the driver holds the button, on a double tap, and so on. Last season's fire button took about 40 lines of timers and "was it down last loop?" flags. Here it is one line per press type. "Every loop" below means each time round the library's loop, many times a second. ## Every press type **Where:** `Controls.java`, inside `buttons(...)`. | You want | Write | When the job runs | | --- | --- | --- | | Press once | `g2.y.press(robot.claw::open)` | once, the moment the driver presses it | | Let go | `g2.y.release(robot.claw::close)` | once, the moment the driver lets go | | Hold | `g1.a.hold(robot.intake::in)` | every loop while the driver holds it. The intake still runs after the release: add a stop job (next row) | | Hold, then stop | `g1.a.hold(robot.intake::in, robot.intake::stop)` | every loop while held, then the stop job once at the release | | On / off switch | `g1.x.toggle(robot.intake)` | each press switches the part (an intake, a launcher, a claw, a mode) | | On / off, two jobs | `g2.b.toggle(robot.claw::close, robot.claw::open)` | presses take turns: on, off, on... | | Tap (a quick press) | `g2.rb.tap(robot.launcher::fire)` | once per tap | | Double tap | `g2.rb.doubleTap(() -> robot.launcher.fire(3))` | once, on the second quick tap | | Several taps | `g2.x.taps(3, () -> robot.lift.goTo("high"))` (2 to 5) | once, on the last quick tap | | Tap, then hold | `g2.lb.tapThenHold(robot.intake::out, robot.intake::stop)` | a tap, then press again and hold: every loop while held | | Held for a time | `g2.dpadLeft.heldFor(1.0, robot.launcher::stop)` | once, after the driver holds it 1 s: a safe "are you sure?" | | Two buttons together | `g1.rb.with(g1.dpadUp, () -> robot.lift.goTo("high"))` | once, when the driver presses D-pad up while holding RB | | A stick | `g2.rightStickY.use(robot.lift::manual)` | every loop, with the stick's value (-1 to 1) | The method names (`open`, `in`, `fire`...) depend on the part. Each part's page lists its commands ([part pages](https://crossbotics.com/ftc-helper/docs/reference/)). ## Several press types on one button A **gesture** is a way of pressing: a tap, a hold, two taps. One button can have several gestures, chained with dots, each with its own job. `tap`, `doubleTap`, `taps`, `tapThenHold`, `heldFor` and `hold` can share a button. `press`, `release` and `toggle` each need a button of their own. ```java title="Controls.java" // Three gestures on one button: tap, hold, double-tap. g2.rb.tap(robot.launcher::fire).says("fire one") .hold(robot.launcher::fireWhileHeld, robot.launcher::ceaseFire).says("keep firing") .doubleTap(() -> robot.launcher.fire(3)).says("fire three"); ``` `.says(...)` and `.rumble()` belong to the gesture right before them. **One line puts the launcher's firing on a button.** `robot.launcher.fireOn(g2.y)` puts all of its firing (taps, hold, tap then hold) on Y. `spinOn(...)` puts its spin up / down on a button ([cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-put-the-launchers-fire-button-on-another-button)). ## When a gesture's job runs A job runs at once, unless the same button has a longer gesture that starts the same way. Then the library waits only until it knows which gesture it is: - **A button with a hold:** a tap runs when the driver lets go. A tap is a press that ends before the hold starts (`Tunables.Buttons.holdSec`, 0.3 s). With `heldFor` and no hold, any press that ends before the `heldFor` time is a tap. - **A button with a double tap** (or tap-then-hold, or taps): a tap waits 0.35 s for a second tap. **Why:** without the wait, every double tap would also run the tap job first. - **A button with no double tap:** two quick taps run the tap job twice. - **A button with a double tap (or taps):** a second press within 0.35 s counts as the second tap, not as a hold. To hold, wait a moment after the tap. Or use `tapThenHold` for "tap, then hold". - **`heldFor` and `hold` on one button:** both run. The hold starts at 0.3 s, and `heldFor` runs once at its time. ### Change the double-tap time and the hold time You can change two times: - **The double-tap time** (`tapGapSec`, 0.35 s): the most time between the two taps of a double tap. - **The hold time** (`holdSec`, 0.3 s): a press this long is a hold, not a tap. Without a `Buttons` section in `Tunables.java`, the library uses these defaults. Add the section only to change them. Then they are in the tuning menu too. When you tune a value there, copy it back into `Tunables.java`: the file is the record. **Where:** `Tunables.java`, inside `public class Tunables { ... }`. ```java title="Tunables.java" public static class Buttons { public static double tapGapSec = 0.35; // the most time between the taps of a double tap public static double holdSec = 0.3; // a press this long is a hold, not a tap } ``` The library's field-centric double tap always uses 0.35 s. `tapGapSec` does not change it. ## Tap and double tap: two ways | Write | A tap | A double tap | Use it when | | --- | --- | --- | --- | | `.tap(a).doubleTap(b)` | runs `a`, 0.35 s after the driver lets go (it waits to be sure no second tap comes) | runs only `b` | `a` must not run on a double tap | | `.tapOrDoubleTap(a, b)` (the older way) | runs `a` at once | runs `a` (first tap), then `b` (second tap) | both fit together, like intake on/off (tap), then push out (double tap) | `tapOrDoubleTap` always uses 0.35 s, not `Tunables.Buttons`. It is one job, so you cannot chain it with other gestures. ## Two buttons together `g1.rb.with(g1.dpadUp, job)` runs the job once, when the driver presses D-pad up while holding RB. **Why:** a pair is a safe place for big jobs that the drivers use only once in a while, like a climb. These jobs must not run by accident. - The first button (`rb` here) is the **shift key**. It gets no job of its own. - One shift key can start several pairs: `g1.rb.with(g1.dpadUp, ...)`, `g1.rb.with(g1.dpadDown, ...)`. - The second button keeps its own job when the driver presses it alone. While the shift key is down, the second button's own job does not run, and a hold that it started stops. - Neither button may be one of the library's buttons. Both must be on the same gamepad. - `.free()` on a shift key removes its pairs too. ## While the robot is paused A tap of gamepad 1 BACK pauses the robot. While it is paused, no button job runs, with one exception: a hold's stop job (the second job in `hold(job, stopJob)`) still runs at the release. It also runs when the pause starts in the middle of a hold. **Why:** a part that a hold started must stop, and it must stay stopped when the pause ends. Of the library's own buttons, field-centric on/off and slow on/off wait too. Pause, "forward", the menus, the debug lines, set pose and the alliance switch still work. ## Done when - Each button in your `Controls.java` uses the press type the drivers expect. - In the simulator or on the robot, each gesture runs its own job. A tap does not also run the double tap's job. --- **Next:** [What the drivers see and feel](https://crossbotics.com/ftc-helper/docs/controls/03-see-and-feel/). **Look it up:** [Reading a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line). **Go deeper:** [the cookbook's button recipes](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/). --- # What the drivers see and feel URL: https://crossbotics.com/ftc-helper/docs/controls/03-see-and-feel/ The drivers watch the robot, not the Driver Hub. A buzz in their hands or a light on the robot tells them "done" or "ready", and they do not look away. The screen is for the pit and for practice. ## Feedback on a button **Where:** `Controls.java`, at the end of a button line. | You want | Write | What the drivers get | | --- | --- | --- | | Words on the button map | `.says("fire one")` | the line `G2 RB: fire one` at INIT and when the driver taps GUIDE | | A buzz when the job runs | `.rumble()` | one short buzz (a hold: when it starts) | | More buzzes | `.rumble(2)` (1 to 3) | that many short buzzes | | On / off you can feel | `.toggle(part).rumble()` | two buzzes = on, one buzz = off (a claw: two = closed). The same for a [mode](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/#modes) | `.says(...)` and `.rumble()` belong to the gesture right before them. `g2.rb.tap(a).says("one").doubleTap(b).says("three").rumble()` buzzes on the double tap only. **Always add `.says(...)`.** The button map is the only list of every button that the drivers can see. ## Feedback from the robot These lines are not tied to a button. Each one is a line of its own inside `buttons(...)`, ends with `;`, and is not on the button map. **Where:** `Controls.java`, inside `buttons(...)`. | You want | Write | What the drivers get | | --- | --- | --- | | A buzz when something becomes true | `g2.rumbleWhen(robot.launcher::isReady);` | a buzz each time the test becomes true (`rumbleWhen(test, 2)`: two buzzes) | | A color on the robot | `robot.lights.show(LightColor.GREEN).when(robot.launcher::isReady);` | a light while the test is true ([Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/)) | | A value on the Driver Hub | `show("Lift ticks", robot.lift::position);` | the value, read again every loop | **`show(...)`:** you see what the robot "thinks" while you drive. The value must be fast to read: use a method reference or a small lambda. With the Quick start robot, try `show("Intake on", robot.intake::isRunning);`. **In the simulator,** a buzz shakes the gamepad picture. A real controller or a phone buzzes too. ## The button map and the TeleOp's INIT screen - **At INIT** the Driver Hub shows the whole button map, one line per button, with the part that gave it (`G2 A: down [Lift]`). Then it lists the free buttons (`G2 free: ...`). Read it before every match. - **In the match,** tap GUIDE to see the map again. The robot still drives. Tap GUIDE again to close it. - **The alliance:** in INIT, gamepad 1 X = BLUE, B = RED. After an autonomous, its alliance is already set. - **The INIT menu:** D-pad up/down picks **Alliance** or **Profile**, and left/right changes it. A practice that starts straight in TeleOp can switch to PRACTICE here. When your own INIT code uses gamepad 1's D-pad, turn the menu off in `Controls.java`: `@Override protected boolean initMenu() { return false; }`. ## Done when - Each button line has a `.says(...)`, and the button map shows every button. - The drivers feel a buzz for an on / off switch that matters in a match or is easy to miss, like a mode they cannot see. - A light or a buzz tells the drivers when the robot is ready to score. --- **Next:** [Move the library's buttons](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/). **Look it up:** [Controls.java reference](https://crossbotics.com/ftc-helper/docs/reference/controls/). **Go deeper:** [the cookbook's button recipes](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/). --- # Move the library's buttons URL: https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/ **Why move one:** some drivers want slow on the right trigger, or a part needs Y. When you move the library's job, its button is free for your own line in `buttons(...)`. ## Move or free a button The library's own jobs (driving, pause, menus...) have default buttons. You can move every one to another button, or free it (`null`: no button). Do it in one method next to `buttons(...)`. **Where:** `Controls.java`, next to `buttons(...)`. ```java title="Controls.java" @Override protected void libraryButtons(LibraryButtons lib, Pad g1, Pad g2) { lib.fieldCentric(g1.a); // field-centric on/off: A instead of Y lib.slow(g1.rt); // slow on the right trigger: LT is free now lib.pause(g1.x); // pause on X (BACK still resets forward; lib.resetForward(null) frees it) lib.switchAlliance(g1.start, g1.back); // turn ON the alliance switch: hold START, then BACK, 1.5 s } ``` Add `import com.crossbotics.ftchelper.teleop.LibraryButtons;` at the top. In your own `EasyTeleOp`, write `libraryButtons(LibraryButtons lib)`, with `Key.g1(Btn.X)` instead of `g1.x`. ## Every library button | Job | One gamepad (the start) | Two gamepads | How it works | Move it with | | --- | --- | --- | --- | --- | | Drive / strafe, turn | left stick, right stick X | same | every loop | `lib.swapSticks(true)`: right stick drives, left stick X turns | | Slow | none | G1 LT | the further you pull it, the slower (a button: slow while you hold it) | `lib.slow(key)` | | Slow on/off | G1 left stick click | none | a press | `lib.slowToggle(key)` | | Field-centric on/off | G1 right stick click | G1 Y | a double tap (mecanum with an IMU or odometry) | `lib.fieldCentric(key)` | | Pause / go on | G1 BACK | same | pauses at the press, and a tap goes on | `lib.pause(key)` | | Reset "forward" | G1 BACK | same | held 1 s, field-centric only (a tap if its button has no other quick job) | `lib.resetForward(key)` | | Debug lines | G1 START + BACK | same | hold START, then press BACK. It runs when you let go | `lib.debug(key, with)` (`with` null: one button) | | Switch alliance | **off** | off | START, then BACK, both held 1.5 s, after you turn it on | `lib.switchAlliance(g1.start, g1.back)` turns it on | | Set pose here | G1 START | same | held 1 s with the drive sticks let go (robots with odometry). It also works in INIT | `lib.setPose(key)` | | Button map | G1 GUIDE | same | a tap | `lib.buttonMap(key)` | | Tuning menu | G1 GUIDE | same | held 1 s (a tap if its button has no other quick job) | `lib.tuningMenu(key)` | | Choose the alliance (INIT only) | G1 X = BLUE, G1 B = RED | same | a press, before ▶ (start on the Driver Hub) | `lib.allianceInInit(blue, red)` | **BACK, step by step.** A press of BACK pauses the robot **at once**: every motor stops on brake. So a driver who grabs BACK in a panic gets the stop. When you let go fast, the robot stays paused, and a second tap goes on. When you hold BACK 1 s, it also resets "forward" (only with field-centric on; robot-centric shows a note instead). The robot then stays paused until the next tap. Going on is always a tap, at the release, so holding BACK never starts the robot. **START + BACK: press START first.** Hold START, then press BACK: when you let go, you get the debug lines. Held 1.5 s, the pair switches the alliance, if the switch is on. The robot does not pause. **BACK first is always a plain pause.** BACK stops the robot the moment it goes down. When START joins a moment later, it does nothing, so the robot stays paused (a tap of BACK goes on). The reason: the pause has to act at the press. A pair that came later would have to un-pause the robot. Then the robot would stop for a moment and drive on, and that is a surprise. While the pair is down, START's "set pose" does nothing. When you press both in the same instant, it counts as START first. This applies only to pairs with the pause button in them. Any other pair works in either order. **START + A or START + B** pairs a gamepad on the Driver Station. The library cancels START's own job ("set pose here") for that press, so pairing a gamepad never moves the pose. **Set pose here** works only with the drive sticks let go and whole-robot aim off. Otherwise the note says "Pose NOT set: stop first". It also works in INIT: hold START 1 s before the match, so the pose is set before the buzzer. ## Switching the alliance in TeleOp The switch is off until you turn it on. Without it, you choose the alliance in INIT with X = BLUE, B = RED. Turn it on with one line in `libraryButtons(...)`: ```java lib.switchAlliance(g1.start, g1.back); // hold START, then BACK, 1.5 s: BLUE <-> RED ``` A fast press of both (START first) still gives the debug lines. Use the switch when autonomous ran as the wrong alliance. When the alliance switches, the goal flips, and so does the odometry's pose: - On a mirrored field (the reset spot's `mirrorForRed` true), the library mirrors the pose in place: x and the heading flip. - On a field turned half a turn (`mirrorForRed = false`, BIOBUZZ), the library cannot fix the pose. The odometry aim goes off ("Alliance now RED: odometry aim OFF until the pose is set"). It stays off until you park on the reset spot and hold START 1 s ("set pose here"). INIT's `Switch alliance` line says whether the switch is on. ## What INIT checks **INIT names the jobs you freed.** No pause button gives a warning: nothing on the gamepads pauses the robot. No slow at all gives a warning in `Controls.java`. No field-centric button gives a line: driving stays as it starts. With one gamepad, a library job that you put on `g2` goes on gamepad 1. **INIT checks these** (the message names the button): - two library jobs on one button. One quick job and one held job may share a button, like BACK's pause and reset. - the slow trigger with another job. - a pair on two gamepads. - the tuning menu on a button that the menu itself uses (D-pad, A, B, X, Y, LB, RB). - a job of yours on a library button. ## Done when - INIT shows no stop message about the library's buttons. - The button map (a tap of GUIDE) shows each library job on the button you chose. --- **Next:** [Building autos](https://crossbotics.com/ftc-helper/docs/building-autos/). **Look it up:** [Moving the library's buttons](https://crossbotics.com/ftc-helper/docs/reference/controls/#moving-the-librarys-buttons) (the reference). **Go deeper:** [the cookbook's button recipes](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/). --- # Building autos URL: https://crossbotics.com/ftc-helper/docs/building-autos/ | # | Page | You learn | | --- | --- | --- | | 1 | [What an auto can do](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/) | Every step, in groups: drive, turn, wait, parts, aim and shoot. Which steps wait, and which do not. | | 2 | [Put steps together](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/) | Start a part and drive at the same time. Keep time to park. The INIT menu. Red and blue. | | 3 | [Having multiple autos](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/) | One file per plan. Near and far starts. Good names. | | 4 | [Drive to points on the field](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/) | With odometry: `driveTo` a field point, and `routeTo` around field parts. | | 5 | [Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/) | Set up the Pedro add-on. Lines and curves, no stop between parts, face a point, start parts along a path. | | 6 | [The auto builder: steps](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/) | Build an auto on the field in the simulator, run it with your code, and copy the Java. | | 7 | [The auto builder: odometry and Pedro](https://crossbotics.com/ftc-helper/docs/building-autos/07-auto-builder-odometry-and-pedro/) | Build `driveTo` steps and Pedro paths on the field map. | | 8 | [Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/) | Beyond the auto builder: choices in INIT, shared pieces of a route, a number for RED, waits for a part, your own step. | | 9 | [Match day](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/) | The setup card, the checks before each match, and the report after it. | **Where the numbers go.** Each auto keeps its own numbers in its steps: `.forward("To the goal", 24, 0.6)`. `Tunables.java` keeps the robot's numbers only (speeds, positions, gains). **Why:** a change to one auto never changes another, and the auto builder can read and change the numbers. More: [the numbers are in the step](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#the-numbers-are-in-the-step). **Start with page 1.** If you like to see the field before you read code, read pages 6 and 7 (the auto builder) first. **Next:** [What an auto can do](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/). --- # What an auto can do URL: https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/ An auto is a **list of steps, read top to bottom**. Each step is one line that starts with a dot. The last step ends with `;`. Pick the steps your robot needs from the groups below. ## Two kinds of steps - **A step that waits.** The list waits until the step is done. Then the next step starts. A drive waits until the robot is there. - **A step that does not wait.** It starts something, and the next step starts at once. The part keeps working during the next steps. A lift rises while the robot drives. The **Waits?** column in each table says which kind a step is. **Every part keeps working during every step.** A wait does not freeze the robot. A lift keeps its height, and a flywheel keeps its speed. ## The words in every step Most steps have the same parts, for example this step: ```java .forward("To the goal", 24, 0.5) ``` | Part | Here | What it is | | --- | --- | --- | | The step | `forward` | what the robot does | | The name | `"To the goal"` | the step's name in the report at the end. Write what the step is for. | | A number | `24` | how far, in inches. Angles are in degrees, times in seconds. | | The power | `0.5` | the most power the step may use, 0 to 1 | **About the power:** a drive slows down near its end, so it does not overshoot. A very small number still moves the robot: a drive always gets the least power that moves it (`moveMinPower` in `Tunables.Drive`). **Every angle counts counterclockwise:** 0 = forward, 90 = left, 180 = back, -90 = right. Drives, turns and headings all count this way. The words (`left`, `turnRight`) need no angle. ![Every angle counts counterclockwise: 0 forward, 90 left, 180 back, -90 right.](https://crossbotics.com/ftc-helper/docs/images/autonomous-angles.svg) **In each group below,** the code comes first. The comment at the end of a line names the numbers in order. Then a table says what each step does. **The auto builder** ([page 6](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/)) makes every step on this page, except the ones marked "not in the builder". ## Where the robot starts `start` is the first step. It tells the drive team where to put the robot. It does not move the robot. ```java s.start("Against our wall, facing the field", 0) // note, heading s.start("Our wall, left corner tile", -56, -61, 0) // note, x, y, heading ``` | Step | What it does | | --- | --- | | `start(note, heading)` | The note shows on the Driver Hub in INIT. The heading is the way the robot faces: 0 = away from your drivers. | | `start(note, x, y, heading)` | The same, plus the spot on the field in inches. The simulator puts the robot there. Odometry starts there. | ### Field numbers The spot is in **inches on the field**, seen from your drivers' wall, written for BLUE: - **x**: inches right of the field's center line (minus = left). - **y**: inches from the center toward the far wall (minus = your half). - **heading**: the way the robot faces. 0 = away from your wall. Counterclockwise: 90 = left. ![The field seen from your drivers' wall: (0, 0) in the center, x to the right, y toward the far wall, heading 0 away from your wall and 90 to the left. A start spot at (-56, -61) facing 0, and a driveTo point at (-30, -30) facing 45.](https://crossbotics.com/ftc-helper/docs/images/field-numbers.svg) `driveTo` and Pedro paths use the same numbers ([below](#drive-to-a-point-on-the-field)). **Find the numbers:** in the simulator, drag the robot on the field map before ▶. The numbers are under the map. Or let the auto builder write them ([page 6](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/#4-the-start-spot-and-the-note)). ## Drive ```java .forward("To the goal", 24, 0.5) // name, inches, power .back("Off the wall", 6, 0.4) // name, inches, power .left("Slide over", 12, 0.5) // name, inches, power .right("Park", 20, 0.7) // name, inches, power .move("Slide", 12, 45, 0.5) // name, inches, angle, power .moveWithTurn("Swing in", 24, 0, 90, 0.5) // name, inches, angle, heading, power ``` | Step | What it does | Waits? | | --- | --- | --- | | `forward`, `back` | Drives forward or backward. | yes | | `left`, `right` | Slides to the side, still facing the same way. **Mecanum only.** | yes | | `move` | Drives at an angle. 90 = left. A tank drive can only use 0 and 180. | yes | | `moveWithTurn` | Drives and turns at the same time. **Mecanum only.** Both angles count from the way the robot faced at the start. | yes | Write the inches as plus numbers. The word says which way. **A drive does not fix the heading on the way.** It counts wheel turns only. This is true with odometry too: only `driveTo` and `follow` use the odometry ([below](#drive-to-a-point-on-the-field)). After a bump or a long drive, add a `turnTo` to square up. A drive that cannot finish (stuck on a wall) ends by itself. The report then says `STALLED` or `TIMED_OUT`. ## Turn ```java .turnLeft("Face the goal", 45, 0.4) // name, degrees, power .turnRight("Face the wall", 90, 0.4) // name, degrees, power .turn("Face the goal", 45, 0.4) // name, degrees (90 = left), power .turnTo("Square up", 0, 0.4) // name, heading, power .rememberHeading("Before the shot") // name .turnBack("Back as before", 0.4) // name, power ``` | Step | What it does | Waits? | | --- | --- | --- | | `turnLeft`, `turnRight` | Turns in place, this many degrees. | yes | | `turn` | Turns by an angle. 90 = left, -90 = right. | yes | | `turnTo` | Turns to a heading. 0 = the way the robot faced at the start. | yes | | `rememberHeading` | Saves the heading now. | no | | `turnBack` | Turns back to the saved heading. | yes | ## Wait ```java .waitSeconds("Let it settle", 0.5) // name, seconds .waitUntil("Lift at the top", robot.lift::isAtTarget, 2) // name, check, seconds ``` | Step | What it does | Waits? | | --- | --- | --- | | `waitSeconds` | Waits this many seconds. | yes | | `waitUntil` | Waits until the check is true, at most this many seconds. **Not in the builder.** | yes | `robot.lift::isAtTarget` is a **method reference**: it names the method, and the step calls it later. The step calls it again and again until it gives true. If the time runs out, the report says `timed out`, and the list goes on. **Checks you can wait for.** Use the part's name from your `Robot.java` in place of `lift`, `launcher` and so on: | Check | True when | | --- | --- | | `robot.lift::isAtTarget` | a lift or an arm is at its position. Any part with positions has it. | | `robot.claw::isClosed` | the claw is closed | | `robot.launcher::isReady` | the flywheel is at speed, and every other launcher check passes | | `() -> !robot.launcher.isShooting()` | the launcher has fired everything (`!` = "not") | | `robot.pieces::isFull` | the robot holds as many pieces as it can | | `robot.pieces::isEmpty` | the robot holds no pieces | | `() -> robot.aim().isAimed()` | the robot or the turret is aimed at the goal | Write a check with a `!` or with `()` in it as a small piece of code (a **lambda**): `() -> ...`. ## Parts and actions ```java .run("Intake in", robot.intake::in) // name, command .action(Actions.scoreHigh(robot), 5) // action, seconds .alongside(Actions.fireAll(robot)) // action ``` | Step | What it does | Waits? | | --- | --- | --- | | `run` | Starts a part's command. | no | | `action` | Runs an action, and waits until it is done (at most this many seconds). | yes | | `alongside` | Starts an action. It runs during the next steps. | no | - **A command** is one thing a part does: `robot.intake::in`, `robot.claw::close`. A command that needs a word or a number is a lambda: `() -> robot.lift.goTo("high")`. - **An action** is several steps that use parts together. A TeleOp button runs the same action. - When an action runs out of time, it stops safely, and the report says why. **Actions you can use:** | Action | Where it comes from | What it does | | --- | --- | --- | | `robot.launcher.fireAllAction()` | the library | fires every piece the robot holds | | `robot.launcher.fireAction(2)` | the library | fires 2 pieces | | `robot.launcher.fireAllAction(2250)` | the library | fires every piece, at this flywheel speed (RPM) | | `robot.launcher.readyAction(3)` | the library | spins up, and is done at speed (at most 3 s) | | `robot.launcher.ejectAction()` | the library | shoots one piece out slowly, for example a piece of the wrong color | | `Actions.scoreHigh(robot)`, `Actions.grab(robot)`, ... | your `Actions.java` | what you wrote ([Actions.java](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/)) | You choose the names of the actions in your `Actions.java`. The example robots have `fireAll`, `scoreHigh`, `grab`, `grabAndLift`, `stow` and more. Copy one and change it. ## Aim and shoot For a robot with a launcher (a flywheel shooter) or a camera. ```java .readyToLaunch("Ready", 3) // name, seconds .action(robot.launcher.fireAllAction(), 8) // action, seconds .action(robot.launcher.fireAllAction(2250), 8) // action at 2250 RPM, seconds .aimAtGoal("Aim", 3) // name, seconds .aimAtGoal("Aim", 4, 45) // name, seconds, degrees to look each way .waitForGoal("See the goal", 5) // name, seconds ``` | Step | What it does | Waits? | | --- | --- | --- | | `readyToLaunch` | Spins the launcher up and waits until it is at speed. | yes | | `fireAllAction()` in an `action` | Fires every piece the robot holds. `fireAction(2)` fires 2. | yes | | `fireAllAction(rpm)` in an `action` | The same, at this flywheel speed. For a robot with no camera that shoots from more than one spot. | yes | | `aimAtGoal` | Turns the robot to the goal with the camera. With a turret that follows the goal, it waits until the turret is aimed. When no goal is in view, the robot does not turn, and the report says `not seen`. | yes | | `aimAtGoal` with degrees | The same. When the goal is not in view, it turns slowly up to this many degrees each way to find it. | yes | | `waitForGoal` | Waits until the camera sees the goal and the goal is still. It does not turn. After this many seconds, it goes on anyway. With no seconds, it waits until the park time. | yes | To spin up while the robot drives, start it and go on: `.run("Spin up", robot.launcher::spinUp)`. The auto builder lists the ones your robot can do under **What this robot can do** ([page 6](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/#1-robot-and-alliance)). ## Drive to a point on the field For a robot with **odometry** (sensors that track where the robot is on the field). Page 4 explains them: [Drive to points on the field](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/). The numbers are [field numbers](#field-numbers), like the start spot. ```java .driveTo("To the goal", -30, -30, 45, 0.6) // name, x, y, heading, power .routeTo("Park", -56, -36, 0, 0.8) // name, x, y, heading, power .follow("To the goal", TO_GOAL) // name, Pedro path ``` | Step | What it does | Waits? | | --- | --- | --- | | `driveTo` | Drives to a point on the field, and keeps correcting on the way. **Mecanum only.** | yes | | `routeTo` | The same, but around the field parts you list. **Not in the builder.** | yes | | `follow` | Follows a curved path with Pedro Pathing. **Mecanum only.** | yes | ## Your own step, and parking ```java .step("Clear the intake", ctx -> { ... }) // name, your code .parkWithSeconds(3) // seconds ``` | Step | What it does | Waits? | | --- | --- | --- | | `step` | Your own code, for what no other step can say. **Not in the builder.** | your code | | `parkWithSeconds` | Not a move. The steps after it always get the last seconds of the 30. | - | `step`: [Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#write-your-own-step). `parkWithSeconds`: [page 2](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#keep-time-to-park). ## Try it Add a turn and a wait to your `FirstAuto.java`. Each new step goes before the `;`: ```java s.start("Against our wall, facing the field", 0) .forward("Leave the start", 12, 0.4) .turnLeft("Face the goal", 45, 0.4) .waitSeconds("Let it settle", 0.5) .turnTo("Square up", 0, 0.4); ``` Run it in the simulator: pick **Simulator** in the run list next to Android Studio's **Run** button, and click **Run**. Pick your auto, INIT, ▶. ## Done when The robot drives, turns left, waits, and turns back. The report at the end says `done` for every step. ## Problems | Problem | Why, and the fix | | --- | --- | | It turns the wrong way | Angles count counterclockwise: 90 = left. Or use the words `turnLeft` and `turnRight`. | | `Turn first, then move` | A tank drive cannot drive at an angle. Turn, then drive `forward`. | | `needs a mecanum drive` | `left`, `right`, `moveWithTurn` and `driveTo` slide sideways. A tank drive cannot. | | `';' expected` | A step line is missing its dot, or the `;` is not after the last step. | | A step says `timed out` | A wait or an action ran out of time. The list went on. Give it more seconds, or check the part. | **What each word in the report means** (`done`, `STALLED`, ...): [Match day](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/#after-the-match-read-the-report). --- **Next:** [Put steps together](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/). **Look it up:** [every step](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto). **Go deeper:** [the cookbook's autonomous recipes](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/). --- # Put steps together URL: https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/ > **The auto builder writes everything on this page:** `run`, `action`, `alongside`, `parkWithSeconds` > and `mirrorForRed()`. [Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/) covers what it cannot write (menus, your own > steps, ...). ## The example The example robot's (`lessonbot`) auto holds the piece, drives to the goal, scores, and parks. The library has it as a compiled file: [`lessonbot/autos/ScoreAndPark.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/lessonbot/autos/ScoreAndPark.java). ```java @Autonomous(name = "Lesson Bot Score and Park", group = "Examples", preselectTeleOp = "Lesson Bot TeleOp") public class ScoreAndPark extends Auto { @Override protected boolean mirrorForRed() { // (1)! return false; // BIOBUZZ's field is turned half a turn between the alliances } @Override protected void steps(Steps s, Robot robot) { s.start("Against our wall, facing the field", 0) .run("Hold the piece", robot.claw::close) // (2)! .forward("To the goal", 24, 0.6) .action(Actions.scoreHigh(robot), 5) // (3)! .parkWithSeconds(3) // (4)! .right("Park", 20, 0.7); } } ``` 1. `@Override` marks a method that replaces one `Auto` already has. Copy these lines as they are, and change only `false` or `true`: [red and blue, below](#red-and-blue). 2. `run` starts the claw and goes on at once. The claw closes while the robot already drives. 3. `action` runs the "score high" action from `Actions.java`, and waits until it is done (at most 5 s). 4. The steps after this line always get the last 3 seconds: [below](#keep-time-to-park). **The first lines of the file** (above `@Autonomous`), in your own copy: ```text package org.firstinspires.ftc.teamcode.autos; import org.firstinspires.ftc.teamcode.Actions; import org.firstinspires.ftc.teamcode.Robot; import com.crossbotics.ftchelper.robot.Auto; import com.crossbotics.ftchelper.robot.Steps; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; ``` **Why the `Actions` line:** `Actions.java` is in the folder above `autos`, like `Robot.java`. ## Start something, or wait for it You can use a part in three ways. To pick one, decide whether **the next step must wait for it**. | You write | The next step starts | Use it when | | --- | --- | --- | | `.run("Intake in", robot.intake::in)` | at once | one command, and the robot can go on: an intake on, a claw closed, a flywheel spun up | | `.action(Actions.scoreHigh(robot), 5)` | when the action is done | the robot must not move until it is done: a score, a shot | | `.alongside(Actions.fireAll(robot))` | at once, and the action runs during the next steps | several steps that can happen while the robot drives | **Start early, wait late.** Start a slow part with `run` as early as you can. The robot then does two things at once. That saves time in a 30-second match. To wait for the part right before you need it, use `waitUntil` ([Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#wait-until-a-part-is-ready)). ## Keep time to park Parking points come at the very end of the 30 seconds. The park must never run out of time. `.parkWithSeconds(3)` splits the list in two: - **The steps before it** stop when only 3 s are left. The step that is running then stops at once, and the auto skips the rest. - **The steps after it** always run. The report says which steps were `cut short (time for park)` or `skipped (time for park)`. **To choose the seconds,** run the auto. Measure how long the park steps take, and add about 1 second. **Try it:** change `parkWithSeconds(3)` to `parkWithSeconds(28)`, and run the auto in the simulator. The auto cuts the score steps short, and the park still runs. Then change it back. ## The INIT menu Every auto already has an **INIT menu** on the Driver Hub. The drivers use gamepad 1: D-pad up/down picks a line, D-pad left/right changes it. | Line | What it is | | --- | --- | | Alliance | BLUE or RED. **X** = BLUE, **B** = RED. | | Start delay | 0 to 10 s. The auto waits this long before the first step. **Why:** to stay out of a partner's way. | | Profile | PRACTICE (for the shop: debug lines and the tuning menu) or COMPETITION (for matches): [what they change](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#practice-and-competition) | **The menu remembers:** Alliance starts at the last auto's alliance, and the hub saves the Profile. A longer start delay: [`maxStartDelaySec()`](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/). **Your own lines** (park or stay, near or far): [Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#add-choices-to-the-init-menu). Or make one auto file per plan: [Having multiple autos](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/). ## Red and blue You write the auto **for BLUE**. The library changes it for RED. How it changes it depends on the season's field. > **This season, BIOBUZZ (2026-27): the field is ROTATED.** The red half is the blue half turned half a > turn. Write `return false;` in `mirrorForRed()`. RED then drives the same steps, seen from > the red wall. > > Last season, DECODE (2025-26), was **mirrored**. Old autos and old videos from DECODE use `true`. Do not > copy that. | The field | Write | RED then | | --- | --- | --- | | The red half is the blue half **turned half a turn** (BIOBUZZ) | `mirrorForRed()` returns `false` | drives the same steps, seen from the red wall | | The red half is the blue half **mirrored** left to right (DECODE) | `mirrorForRed()` returns `true` | drives the steps mirrored: left becomes right, and turns go the other way | **Write `mirrorForRed()` in every auto.** Without it, the auto uses the robot's setting: `mirrorForRed` in `Tunables.Aim`, else in `Tunables.Odometry`, else `true`. That setting is easy to miss. The auto builder writes `mirrorForRed()` for you (**Red's side** in [step 1](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/#1-robot-and-alliance)). **Where the drivers stand.** In BIOBUZZ and in DECODE, each alliance's drivers stand at their own wall. You need nothing more. A field where both alliances' drivers stand at one wall needs one more method: [`alliancesOnOneWall()`](https://crossbotics.com/ftc-helper/docs/modules/auto/). **One number different on RED** (a wait, a distance): `alliance().pick(blue, red)`, on [Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#a-different-number-for-red). ## The first run on the robot 1. **On blocks,** wheels off the floor. Check that the wheels turn the right way and the parts move. 2. **On the field, in the PRACTICE profile** ([PRACTICE and COMPETITION](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#practice-and-competition)). For the very first runs, set `maxPower` in `Tunables.Drive` lower (0.4), and back to `DEFAULT` when it works. Keep a hand near STOP. 3. Read the report after every run. Measure where the robot ended, and fix the numbers in the steps. 4. When it works every time, run it in the **COMPETITION** profile. ## Done when - Your auto starts a part with `run`, and drives while the part works. - It has a `parkWithSeconds(...)` before its park steps. - It runs as BLUE and as RED in the simulator, and the robot goes the right way both times. ## Problems | Problem | Why, and the fix | | --- | --- | | `cannot find symbol: Actions` | Add `import org.firstinspires.ftc.teamcode.Actions;` at the top of the file. | | RED drives into a wall | `mirrorForRed()` is wrong for this field. Check the field drawing. | | The park did not run | It was before `parkWithSeconds(...)`. Put the park steps after it. | **What each word in the report means** (`done`, `STALLED`, ...): [Match day](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/#after-the-match-read-the-report). --- **Next:** [Having multiple autos](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/). **Look it up:** [every step](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto), [keep time to park](https://crossbotics.com/ftc-helper/docs/reference/steps/#keep-time-to-park). **Go deeper:** [the cookbook's autonomous recipes](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/). --- # Having multiple autos URL: https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/ At an event you play with a new partner in every match. Sometimes you start near the goal, sometimes far. Sometimes your partner needs the space you usually drive through. So you need a few plans, with clear names, that the drive team can pick fast. ## One file per plan The simple way: **each plan is its own auto file.** Each file is one line in the Driver Hub's Autonomous list. The drivers pick the plan by its name. - **The auto builder works with it.** Build each plan in the builder ([page 6](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/)), and copy each one into its own file in `autos/`. Later, **Load** can read each file again. - **Start from a copy.** Copy a working auto file, give the class and the `@Autonomous` name a new name, and change the steps. - **Red and blue need no second file.** The Alliance line in the INIT menu does that ([red and blue](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#red-and-blue)). - **Waiting for a partner at the start needs no second file.** The Start delay line does that. **When it gets too big:** many files that share the same steps, or more plans than the drivers can pick from. Then put the shared steps in one place, or give the drivers a choice in INIT: [Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#one-auto-with-choices-or-several-autos). ## Near and far starts A different start spot is the most common reason for a second plan. Two good ways: - **Two files**, `Near: Preload + Park` and `Far: Preload + Park`. Each has its own `start(...)`. The far one adds its first moves, then the same steps. Pick this when the far route is long and different. - **One file with a Start line** in the INIT menu ([Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#a-whole-example-one-auto-the-drivers-choose)). Pick this when the far route is "the near route, plus a few steps". The builder cannot write it. **Check the far route against the field.** On BIOBUZZ's field a FLOWER stands on your wall between the two start spots. A robot that slides along the wall from the far spot drives into it. So the far route drives off the wall first. Watch every new route in the simulator. ## Names on the Driver Station The drivers read the Autonomous list in a hurry, on a small screen. ```java @Autonomous(name = "Near: Preload + Park", group = "Autos", preselectTeleOp = "Main TeleOp") ``` - **Start the name with the start spot**, then the plan: `Near: Preload + Park`. The drivers look at where the robot is first. - **Say what it scores**, not how the code works. `Near: Preload + Cycle + Park`, not `AutoV3Fixed`. - **No alliance in the name.** One file works for both alliances. Two files `Red Near` and `Blue Near` are twice the work, and one day they do not match. - **`group`** lists autos together. `group = "Autos"` for match autos, `group = "Test"` for test routines. - **`preselectTeleOp`**: your TeleOp's exact name. After the auto, the Driver Station has it chosen. - **Hide old autos** with `@Disabled`, or delete them. A short list is a safe list. - **Start the note with the spot in CAPITALS**: `"NEAR: against our wall, ..."`. A second person checks the note against the robot. ## Done when - Each of your plans is one line on the Driver Hub list, with a clear name. - Each plan runs in the simulator, as BLUE and as RED. ## Problems | Problem | Why, and the fix | | --- | --- | | The drivers picked the wrong auto | The names look alike. Start each name with the start spot, and say what it scores. | | The drivers cannot find the auto | Too many on the list. Add `@Disabled` to the old ones, and use groups. | | A fix in one auto is missing in another | The two files share steps. Fix both, or put the shared steps in `Routes.java` ([Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#routes)). | | Two autos have the same name | Each `@Autonomous(name = ...)` must be different. The Driver Hub shows only one. | --- **Next:** [Drive to points on the field](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/): with odometry. No odometry yet? Go on to [the auto builder](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/). **Look it up:** [every step](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto). **Go deeper:** [cookbook: several autos and choosing one](https://crossbotics.com/ftc-helper/docs/cookbook/10-several-autos/). --- # Drive to points on the field URL: https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/ **You need:** odometry: the `odometry(...)` line in `Robot.java`, and the Odometry Tuner passed ([Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/)). **Odometry** is a sensor set (a Pinpoint, an OTOS, or dead wheels) that tracks where the robot is on the field, all the time. With it, a step can say **where to go** on the field, not only how far to drive. ## Drives and points: the difference | | `forward`, `turn`, ... (pages 1 to 3) | `driveTo` (this page) | | --- | --- | --- | | You say | "24 in forward from here" | "go to x -30, y -30, facing 45" | | On the way | it does not correct | it checks where the robot is, and corrects all the time | | After a bump or wheel slip | every later step is off | the robot still ends at the point | | You change one step | the steps after it move too | the other points stay where they are | | Needs | any drive | odometry, and a **mecanum** drive | ## Field numbers Every point uses the same **field numbers** as the start spot: x, y and heading, in inches and degrees, seen from your drivers' wall, written for BLUE. The picture and the words: [page 1, field numbers](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/#field-numbers). **Give the spot** in every auto that uses `driveTo`: `start(note, x, y, heading)`. The odometry starts there. Without a spot, the odometry starts at (0, 0), and every point is wrong. **Find the numbers:** in the simulator, drag the robot on the field map before ▶. The numbers are under the map. Or use the auto builder ([page 7](https://crossbotics.com/ftc-helper/docs/building-autos/07-auto-builder-odometry-and-pedro/)): it writes them for you. ## Drive to a point: driveTo The odometry robot's auto, a compiled file in the library: [`odometrybot/autos/ToTheGoal.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/odometrybot/autos/ToTheGoal.java). ```java s.start("Against our wall, in the left corner tile, facing the field", -56, -61, 0) .run("Intake on", robot.intake::in) .driveTo("To the goal", -30, -30, 45, 0.6) // x, y, heading, power .run("Intake off", robot.intake::stop) .parkWithSeconds(4) .driveTo("Park", -56, -36, 0, 0.7); ``` - `driveTo(name, x, y, heading, power)`: drives and turns at the same time, to the point and the heading. The step is done when the robot is within 1 inch and 2 degrees. - `driveTo(name, x, y, heading, power, inches)`: your own "close enough", in inches. Use a larger number for a point the robot only drives through. **Why `driveTo` and not a drive by distance:** 1. **It fixes bumps and slip.** After a bump, a `forward` still "finishes", in the wrong place. `driveTo` sees the real pose, so it drives back on course and ends at the point. 2. **It ends at a field place.** When you change one step, the next steps still go to the same places. 3. **It drives and turns at once,** straight at the point, even sideways. **In INIT**, the Driver Station shows `Odometry: Pinpoint ready`, or a warning with the reason, like `Odometry (Pinpoint): X pod not found: check its cable`. Look for it before ▶. **If a driveTo does not finish**, it stops, and the report shows a word: - `STALLED`: the robot is stuck. In the last 8 in, where it is slow on purpose, this means less than 0.1 in closer in 2 s. - `TIMED_OUT`: it took more than 10 s. - `NO_ODOMETRY`: the odometry stopped working (a pod or I2C cable) for more than 0.2 s. The next steps still run, from where the robot is. So put an action that needs the right place (score, drop) right after the `driveTo` that gets there. Read the report after each practice run. **Its heading is the field's.** `turnTo`'s 0 is the way the robot faced at the start. `driveTo`'s 0 is "away from your wall". They are the same only when the robot starts facing the field. With odometry, give headings in `driveTo`. **Red and blue** work like the start spot ([page 2](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#red-and-blue)): - `mirrorForRed()` true: RED flips x and the heading. `(-30, -30, 45)` becomes `(30, -30, -45)`. - `mirrorForRed()` false (BIOBUZZ): RED uses the same numbers, seen from the red wall. ## Go around field parts: routeTo A `driveTo` is one straight line. When the park time comes, the running step stops, wherever the robot is. A straight line home from there can go through a field part. So list the field parts in `Robot.java`, after the `odometry(...)` line: ```java fieldMap(FieldMap.margin(13) // needs: import com.crossbotics.ftchelper.drive.FieldMap; .keepOut("HIVE frame, near", -19.5, -24.8, 19.5, -15.4) .keepOut("HIVE frame, far", -19.5, 15.4, 19.5, 24.8)); ``` - `keepOut(name, x1, y1, x2, y2)`: a box, from two opposite corners, in field numbers. - `margin(13)`: the robot's center stays this far from every box, in inches. Then write `routeTo` where you wrote `driveTo`. It finds its way around the boxes when the step starts: ```java .parkWithSeconds(6) .routeTo("Park", -56, -36, 0, 0.8); ``` The whole file: [`odometrybot/autos/ParkAround.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/odometrybot/autos/ParkAround.java). The auto builder does not make `routeTo` steps yet: write them in the file. **TeleOp can do it too:** a button that drives to a spot, and stops when a driver pushes a stick ([Add odometry: a button that drives to a spot](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/#a-button-that-drives-to-a-spot-in-teleop)). ## Done when - Your auto has a start spot (`start(note, x, y, heading)`). - It drives to a field point with `driveTo`, in the simulator, as BLUE and as RED. - The report says `done` for every point. ## Problems | Problem | Why, and the fix | | --- | --- | | `needs odometry: add an odometry(...) line` | `Robot.java` has no odometry line ([Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/)). | | The report says `skipped: Tunables.Odometry.checked is false` | On a real robot, `driveTo` waits for the Odometry Tuner. Run its loop test, then set `checked = true`. The simulator runs them anyway. | | `needs a mecanum drive` | `driveTo` slides sideways. On a tank drive, use `turnTo`, then `forward`. | | Every point is off by the same amount | The start spot in `start(...)` is not where the robot starts on the field, or it is missing. | | `NO_ODOMETRY` in the report | The odometry stopped answering on the way. Check its cable. | | `STALLED` near a field part | The straight line goes through it. Use `routeTo` with a `fieldMap`. | | RED goes to the wrong side | `mirrorForRed()` is wrong for this field. | | `STALLED` away from field parts | The robot was pushed against something, or the point is out of reach. The next steps still ran. | | `TIMED_OUT` | It did not arrive in 10 s: a point too far for one step, or the heading never settled. Run the [Move Tuner](https://crossbotics.com/ftc-helper/docs/tuning/10-move-tuner/). | | `skipped` with `checked = true` | No time was left before the park time. | | It circles the point, or stops just short | Run the [Move Tuner](https://crossbotics.com/ftc-helper/docs/tuning/10-move-tuner/). | **What each word in the report means** (`done`, `STALLED`, ...): [Match day](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/#after-the-match-read-the-report). ## Try it in the simulator Run the odometry robot's example first. **Where:** the Terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:fromRobot -PteamCode=none -ProbotClass=com.crossbotics.ftchelper.examples.odometrybot.Robot -Pout=build/odometrybot.properties ``` **Where:** the Terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:run -PteamCode=none -Probot=build/odometrybot.properties ``` Open http://localhost:8780, choose **Odometry Bot To the Goal**, press INIT, choose **RED** in the INIT menu (gamepad 1 B), then ▶. The robot drives diagonally to the goal while it turns to 45 degrees, then parks. The simulator runs `driveTo` even with `checked = false`. On the robot, the steps wait for it. **Two places show where the robot is:** - The Driver Station's `Pose` line: where the odometry *thinks* the robot is, seen from your own wall. - The line under the simulator's field map (Control Hub panel, **Robot** tab): where the robot *really* is. The map is always seen from the **red** wall. On RED the two use the same numbers. On BLUE, x and y have the other sign, and the heading differs by 180. **See what bad tuning does:** add `odometry.scaleError = 0.05` (the pods measure 5% too far) at the end of `build/odometrybot.properties`, and run it again as RED. The `Pose` line says the robot is at the goal, but the real robot stops about 2 in short. The Odometry Tuner's Forward test finds this on the robot. Delete the line when you are done. More lines: [the odometry module's simulator lines](https://crossbotics.com/ftc-helper/docs/modules/odometry/#the-simulator). **Your own robot:** pick **Simulator** next to Android Studio's green Run button, and click Run. The simulator writes the odometry lines from your `Robot.java`. You can also run the Odometry Tuner there to learn its tests. Its Spin test always finds your own numbers back, so the real offsets must come from the real robot. --- **Next:** [Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/): curved paths, with no stop between parts. **Look it up:** [driveTo](https://crossbotics.com/ftc-helper/docs/modules/odometry/#driveto), [keep-out boxes and routes](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes). **Go deeper:** [the odometry module](https://crossbotics.com/ftc-helper/docs/modules/odometry/). --- # Add Pedro paths URL: https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/ **You need:** - A robot with a **mecanum** drive and **checked odometry** ([Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/): `Tunables.Odometry.checked = true`). - A charged battery, clear floor, and a laptop that can join the robot's WiFi (for Pedro's tuner). ## 1. What it is A **path follower** drives the robot along a line or a curve, and corrects it all the way. **Pedro Pathing** is a separate library. The library's `pedro` add-on connects it to your robot. - **When you need it:** `driveTo` drives a straight line to a point and ends on it. That is enough for many autos. Pedro is for curves, for paths with no stop between parts, and for facing a point while the robot drives. - **Paths use the same field numbers as `driveTo`** ([Drive to points](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/#field-numbers)): inches, seen from your own drivers' wall. - **Pedro uses your `drive(...)` and `odometry(...)` lines.** You describe the robot only once. - **Pedro must measure your robot** with its own tuner: its top speed, how far it slides when it brakes, and how hard to correct (step 3). Until then, do not trust a path on the real robot. - Pedro paths run in **autonomous** steps. | | `driveTo` ([Drive to points](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/)) | Pedro (this page) | | --- | --- | --- | | How you say where | a point and a heading | a road: lines and curves | | Around a field part | a point in between (it stops there) | a curve (no stop) | | Speed | good | faster, with smooth braking | | Extra setup | none | an add-on, and Pedro's own tuning | **Our advice:** start with `driveTo`. Change to Pedro when you want curves, or when a stop at every point costs you time. One auto can use both. **Words you will meet:** | Word | What it means | | --- | --- | | **path** | the road the robot follows, from a start point to an end point | | **line** | a straight part between two points | | **curve** | a smooth bent part. Pedro uses **Bezier** curves (say "bez-ee-ay") | | **control point** | a point that **pulls** a curve toward it. The robot does **not** drive through it | | **part** | one line or curve. A path can have several parts, with no stop between them | | **follower** | the code that drives the robot along the path (Pedro's `Follower`) | | **Foresight** | Pedro's way of driving. It looks ahead to know when to brake | | **hold** | after the path, keep the robot on the end point, and push back when it is bumped | **How far a curve bends:** with one control point, the middle of the curve is halfway between the middle of the straight line (start to end) and the control point. ## 2. Add it to the five files ### Your project: add the Pedro add-on once **Where:** `settings.gradle`, in the project folder (not in TeamCode), under the two `ftc-helper-lib` lines. ```groovy include ':ftc-helper-lib-pedro' project(':ftc-helper-lib-pedro').projectDir = new File(rootDir, 'ftc-helper-lib/pedro') ``` **Where:** `TeamCode/build.gradle`, in `dependencies { ... }`, under the `ftc-helper-lib` line. ```groovy implementation project(':ftc-helper-lib-pedro') ``` Then click **Sync Now**. Wait until it ends with no red errors. Gradle downloads Pedro itself. ### Robot.java: one line, and Pedro's numbers file **Where:** `Robot.java`, in `define()`, **after** the `odometry(...)` line. ```java title="Robot.java" odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); // Pedro needs odometry // Pedro drives the paths with the drive and odometry lines above. PedroConstants holds the // numbers from Pedro's Foresight tuner (docs/modules/pedro.md#tuning-pedro). follower(Pedro.follower(PedroConstants.foresight)); ``` - Only the `follower(...)` line is new. Keep your own `odometry(...)` line. - When `Pedro` is red, click it and press Alt+Enter (Option+Enter on a Mac) to add the import. - Copy [`PedroConstants.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/pedrobot/PedroConstants.java) into TeamCode, next to `Robot.java`. Make its first line (`package ...`) the same as the first line of your `Robot.java`. Its numbers are from the simulated example robot. Pedro's tuner replaces them (step 3). ### Tunables.java: nothing new Pedro's numbers are in `PedroConstants.java`, not in `Tunables.java`. Paths use `Tunables.Drive.maxPower` and `Tunables.Odometry.checked`, which you already have. ### Controls.java: nothing new Paths run in autonomous. You need no button. ### Actions.java and autos: make paths, then follow them **Make each path once**, in your autonomous class, above `steps(...)`. **Where:** your autonomous class in `autos/`, above `steps(...)`. ```java title="autos/YourAuto.java" // Make each path once. A line: from (x1, y1) to (x2, y2). A curve: start, a control point // that pulls the curve toward it (the robot does not drive through it), end. static final PedroPath OUT = PedroPath.line(-56, -61, -56, -36).keepHeading(0); static final PedroPath TO_GOAL = PedroPath.curve(-56, -36, -44, -36, -30, -30).turnTo(0, 45); ``` - `keepHeading(0)`: the robot keeps facing 0 the whole way. - `turnTo(0, 45)`: it turns from 0 to 45 along the path. **Face one point the whole way**, for example the goal, so the camera or launcher stays on it: ```java title="autos/YourAuto.java" // Keep facing one field point the whole way (here x -60, y 60: put your goal's x and y). static final PedroPath WATCH_GOAL = PedroPath.line(-30, -30, -56, -36).facePoint(-60, 60); ``` **Follow the paths** in the steps. **Where:** a file in `autos/`, inside `steps(...)`. ```java title="autos/YourAuto.java" s.start("Against our wall, in the left corner tile, facing the field", -56, -61, 0) .follow("Out", OUT) // brakes to a stop at its end .follow("To the goal", TO_GOAL) .run("Intake on", robot.intake::in) .follow("Back", WATCH_GOAL) .parkWithSeconds(4) .driveTo("Park", -56, -36, 0, 0.7); // driveTo works too (it ends any hold first) ``` Each `follow` brakes to a stop at its end. Start the next path where the last one ended. **Two parts with no stop, a slow part, and a hold at the end:** **Where:** your autonomous class, above `steps(...)`. ```java title="autos/YourAuto.java" // Two parts with NO stop between them (then), a slow part near the goal (maxSpeed), // and hold the end point while it scores (holdEnd: at most 5 s). static final PedroPath IN_ONE_GO = PedroPath.line(-56, -61, -48, -50).keepHeading(0) .then(PedroPath.curve(-48, -50, -44, -36, -30, -30)).turnTo(0, 45) .maxSpeed(0.6) .holdEnd(); ``` `holdEnd` pushes back when another robot bumps yours while it scores. **Rules for paths:** - **Start each part where the last one ended**, and each path where the robot is: the first at the start spot in `s.start(...)`. - **Headings must match at a join.** When part 1 ends facing 0, part 2 must start at 0 (`turnTo(0, 45)`). Else the robot turns fast at the join. - **A setting after a part is for that part.** `.turnTo(...)` after the curve sets the curve's heading. `.holdEnd()` is for the whole path. `.maxSpeed(...)` slows only its part, so make that part long enough. - **Do not drive straight back along the same line in one path.** In tests, Pedro took a shortcut onto the way back at once. Use two `follow` steps (out, then back), or a curve that turns around. - **Other ways to face:** `.facePath()` faces along the road (the default). `.facePathBackwards()` drives backwards along it. **Plan the path on the field map**, and check that no part goes through a field part. A curve bends toward its control point, so check the bend too. The example path, seen from the red wall: ![The example path: a line from the start to (-48, -50), a curve to the goal at (-30, -30), then a driveTo to park](https://crossbotics.com/ftc-helper/docs/images/biobuzz-pedro-path.svg) **Or draw it:** the [Pedro Path Builder](https://crossbotics.com/ftc-helper/path-builder/) is a web page, with no install. It draws the robot along the path, marks in red where it hits a field part or a wall, and writes the `PedroPath` code. The simulator's auto builder does the same, and runs the path ([page 7](https://crossbotics.com/ftc-helper/docs/building-autos/07-auto-builder-odometry-and-pedro/)). **Drive first, then turn** (or turn first): **Where:** your autonomous class, above `steps(...)`. ```java title="autos/YourAuto.java" // Turn from 0 to 90 only in the last 30% of the line (0.7 to 1): drive first, then turn. static final PedroPath DRIVE_THEN_TURN = PedroPath.line(-56, -61, -30, -30).turnTo(0, 90, 0.7, 1); ``` The two extra numbers say on which stretch it turns: 0 = the start of the part, 1 = its end. `0, 0.3` turns first, then drives. **Start a part along the path**, while the robot keeps driving: **Where:** a file in `autos/`, inside `steps(...)`. When `PathAt` is red, press Alt+Enter. ```java title="autos/YourAuto.java" s.start("Against our wall, in the left corner tile, facing the field", -56, -61, 0) // PathAt: start things ALONG the path, once each, while the robot keeps driving. .follow("To the goal", Paths.IN_ONE_GO, PathAt.part(2, "Intake on", robot.intake::in), // where part 2 starts PathAt.inchesLeft(6, "Intake off", robot.intake::stop)) // 6 in before the end .waitSeconds("Score (the robot holds still)", 0.5); ``` Every way to start a part along the path: | `PathAt` | Starts it | | --- | --- | | `PathAt.fraction(0.5, name, command)` | halfway along the whole path | | `PathAt.inchesLeft(12, name, command)` | 12 in before the end | | `PathAt.inchesDone(12, name, command)` | 12 in after the start | | `PathAt.part(2, name, command)` | where part 2 starts | | `PathAt.near(x, y, inches, name, command)` | when the robot comes this close to a point | In place of a name and a command, `PathAt` can take an action from your `Actions.java`: `PathAt.inchesLeft(12, Actions.scoreHigh(robot))`. `driveTo` takes `PathAt` too. More: [PathAt](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/#pathat). **Try every path in the simulator first.** It runs Pedro like the real robot. So it is the safe place to find a path that hits a wall. The field map draws the plan (orange, dashed) and where the robot went (green). Where the green line leaves the orange one, the robot hit something, or it went too fast to turn or brake. Then move a control point, or slow that part with `maxSpeed(0.5)`. Keep half the robot's width clear on each side of the line. The auto builder draws and runs paths too ([The auto builder: odometry and Pedro](https://crossbotics.com/ftc-helper/docs/building-autos/07-auto-builder-odometry-and-pedro/)). More: [the Pedro module's simulator part](https://crossbotics.com/ftc-helper/docs/modules/pedro/#the-simulator). Run the Pedro robot's example first. **Where:** the Terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:fromRobot -PteamCode=none -ProbotClass=com.crossbotics.ftchelper.examples.pedrobot.Robot -Pout=build/pedrobot.properties ``` **Where:** the Terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:run -PteamCode=none -Probot=build/pedrobot.properties ``` Open http://localhost:8780, choose **Pedro Bot Curve to the Goal**, press INIT, choose **RED** (gamepad 1 B), then ▶. The robot drives a short line, then curves to the goal with no stop, turning to 45. Halfway, the intake starts. In the simulator, `follow` runs even when `Tunables.Odometry.checked` is `false`. ## 3. Find its numbers Pedro's **Foresight tuner** measures your robot. It drives the robot by itself, **at full power**. The PRACTICE limit does not work here. Keep clear of the robot, and keep a hand on STOP. You need the odometry checked first, and a charged battery. 1. **Add Pedro's tuning library.** **Where:** `build.dependencies.gradle`, in the project folder, next to `settings.gradle`. Add one line to each block, and keep the lines that are there. ```groovy repositories { // ...the lines already here... maven { url 'https://repo.dairy.foundation/releases/' } } dependencies { // ...the lines already here... implementation 'com.pedropathing:tuning:1.0.1' } ``` A **repository** is a website that keeps Java libraries, so Gradle can download them. Pedro keeps its tuning library on its own site, so Gradle needs both lines. Click **Sync Now**. The simulator adds the tuning library to its own build too. 2. **Copy Pedro's tuner files.** From [Pedro's Quickstart](https://github.com/Pedro-Pathing/Quickstart), folder `TeamCode/src/main/java/org/firstinspires/ftc/teamcode/pedro`, copy the `procedures` folder and `Tuning.java` into a new `pedro` folder in your TeamCode. To make the folder, right-click the folder with `Robot.java`, choose **New > Package**, and type `pedro`. 3. **Point the tuner at your robot.** **Where:** `pedro/Tuning.java`. Make the whole file this. When your `Robot.java` is in another package, change the `Robot` import: its folder (from its first line) plus `.Robot`. ```java package org.firstinspires.ftc.teamcode.pedro; import com.crossbotics.ftchelper.pedro.PedroTuning; import com.pedropathing.tuning.autotune.Procedure; import com.pedropathing.tuning.autotune.Tuner; import org.firstinspires.ftc.teamcode.Robot; import org.firstinspires.ftc.teamcode.pedro.procedures.ForesightTuner; public class Tuning { @Tuner public static Procedure foresightTuner() { return new ForesightTuner(PedroTuning.localizer(Robot::new), PedroTuning.drivetrain(Robot::new)); } } ``` `Robot::new` means "make a new Robot": the tuner makes one when it starts. So it measures the robot with your own `drive(...)` and `odometry(...)` lines. `@Tuner` puts it on Pedro's web page. 4. Send the code to the robot. Connect the laptop to the robot's WiFi, and open `http://192.168.43.1:10158` in a browser. 5. Choose **Foresight Procedure** and follow the page. The robot drives forward, sideways, brakes and turns, many times. 6. At the end, open the **Java** tab. In `PedroConstants.java`, replace every `c.something.set(...);` line (between `c -> {` and `});`) with the lines from the Java tab. Keep the first and last lines of the file. The tuner does not change your code, so copy the lines in every time. 7. Send the code again. **Before an event, take the tuner out.** Its web page is not allowed at events (rule R704.D). Comment out the `tuning` line in `build.dependencies.gradle` (put `//` in front of it), and move `Tuning.java` and the `procedures` folder out of TeamCode. Build and install again. Your paths still work: they need only `PedroConstants.java`. Put the files back after the event to tune again. ## 4. Check it, then tune it **Check it:** 1. Optional, but useful: Pedro's own **Tests** procedure (its Line and Curve tests) checks the numbers first. Add it to `Tuning.java` the same way, from Pedro's [testing page](https://pedropathing.com/docs/pathing/tuning/test). 2. Make a short path: one straight `PedroPath.line(...)` of about 24 in, in open floor. 3. Set `Tunables.Drive.maxPower` low (0.6) for the first runs. 4. Put the robot on the start spot, facing the start heading. Press INIT, then ▶. Keep a hand on STOP. 5. The robot must drive the line and stop near the end. Pedro calls a path done within about 2.5 in and 11.25 degrees. 6. Then try your real path, still in PRACTICE. Then in COMPETITION. Set `maxPower` back to `DEFAULT`. **If it goes the wrong way, press STOP.** Then check the table below. **Tune it:** run Pedro's tuner again after a change to the robot's weight, wheels or motors. To make "done" tighter, see [When is a path done?](https://crossbotics.com/ftc-helper/docs/modules/pedro/#when-is-a-path-done). The `driveTo` steps in the same auto use the [Move Tuner](https://crossbotics.com/ftc-helper/docs/tuning/10-move-tuner/) numbers. To try `maxPower` without a new build, use [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/). ## Fix a problem | Problem | Why, and the fix | | --- | --- | | `Pedro` or `PedroPath` is red in Android Studio | Add the Pedro add-on (step 2), then Sync | | INIT stops: `follower(...) needs an odometry(...) line too` | The `follower` line needs the `odometry` line above it | | INIT stops: `Pedro.follower needs a mecanum drive(...) line` | Pedro needs mecanum. A tank robot uses `turnTo` and `move` | | Every `follow` says `skipped` in the report | `Tunables.Odometry.checked` is `false`. Do [Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/), step 3 | | It overshoots and comes back, or shakes | `PedroConstants.java` still has another robot's numbers. Do step 3 | | It drives the wrong way at once | STOP. Run the Odometry Tuner again, and check the motor directions | | It stops a little short of the end | Normal: Pedro is done within 2.5 in | | The report says `STALLED` | The robot was stuck, against a wall or a robot. The next steps still run | | The report says `timed out` | The path took more than 10 s. Make it shorter, or give it more time: `.follow("To the goal", TO_GOAL, 15)` | | The tuner's page does not open | The laptop must be on the robot's WiFi. Check the address | | The tuner does not compile | Step 3, item 1: both lines, then Sync | | It is slow | `Tunables.Drive.maxPower` is low (or `practiceMaxPower`, in PRACTICE) | | The report says `STALLED, not fired: Spin up` | The path ended early, so that `PathAt` did not start | More: [the Pedro module, If something goes wrong](https://crossbotics.com/ftc-helper/docs/modules/pedro/#if-something-goes-wrong). ## Done when - `PedroConstants.java` has your robot's numbers from the Foresight tuner. - A 24 in line ends within about 2.5 in of its end point. - Your real path runs in COMPETITION, and the report shows no `skipped` or `STALLED`. --- **Next:** [The auto builder: steps](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/): build an auto on a picture of the field. **Look it up:** [PathFollower and PathAt](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/): every command. [Pedro module](https://crossbotics.com/ftc-helper/docs/modules/pedro/): paths, holds and Pedro's numbers. --- # The auto builder: steps URL: https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/ You can come here first, if you like to see the field before you read code. Step 1 uses the red-and-blue table on [page 2](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#red-and-blue). The **auto builder** is part of the simulator. You tap the field to add drives, and pick the other steps from a list. **Run** drives the plan with **your real code**: your `Robot.java`, your parts and your `Actions.java`. Then you copy the Java. **Why use it:** you see the route on the field before the robot drives it. The builder checks it against the field walls, the field parts and the start rules. It also writes the start note for the drive team. **With no robot code yet:** the [web auto builder](https://crossbotics.com/ftc-helper/path-builder/) is the same builder in a web page, with no install. It writes the same Java. It cannot run your code. ## Open it Start the simulator with your own code. In Android Studio, pick **Simulator** in the run list next to the **Run** button, and click **Run**. Or: **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash ./gradlew :sim:run ``` Open http://localhost:8780. Press **Auto builder** over the 3D view. It takes the Control Hub panel's place. Close it with the **x** to get the hub back. The top of the builder, with a plan on the map. A number on a dark badge is a place the robot drives to. A letter on an orange diamond is a step that does something: ![The auto builder panel: the robot (gobildastraferbot.Robot, a mecanum drive), Run as RED, Red's side "Rotated 180° (like BIOBUZZ)", the field map with a route from the left corner tile (steps 1 to 5, an "Intake on" and a "fireAll" marker), and under it the start spot, the note for the drive team, and the Print setup card and Auto sheet (PDF) buttons.](https://crossbotics.com/ftc-helper/docs/images/auto-builder-plan.png) ## 0. Start from an auto you have (optional) At the top, **Load an existing auto** lists your autos. Pick one and press **Load**. The builder reads its steps. - An older auto can name its numbers (`Tunables.Auto.parkInches`, or a name for a number at the top of the file). The builder works them out from your code, and lists what it could not read. - The builder does not change your file. You copy the Java back when you are done ([step 8](#8-copy-the-java)). ## 1. Robot and alliance - **The robot:** the builder finds your `Robot.java`. Its drive (tank or mecanum), size and parts come from your code. When you have more than one Robot class, pick yours in the list. - **What this robot can do:** a list of the library's ready-made steps for your parts. For example **Fire all** and **Ready to launch** with a launcher, **Aim at the goal** with a camera. Each one is ready, or says what to add. - **Run as:** RED or BLUE. - **Red's side:** **Rotated 180°** (BIOBUZZ) or **Mirrored**. The builder writes `mirrorForRed()` for you ([red and blue](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#red-and-blue)). ![The top of the auto builder, marked: the Robot list (your Robot class), Run as RED or BLUE, Red's side (mirrorForRed()), "What this robot can do" (ready-made steps for your parts), and "Tap adds" (what a tap on the map adds).](https://crossbotics.com/ftc-helper/docs/images/builder-robot-marked.png) ## 2. Add the steps Pick **Simple steps** (any drive). Then: | To add | Do this | | --- | --- | | A drive to a spot | Tap the field there. A spot ahead drives forward. A spot behind backs up. | | A turn to face a spot | Set **Tap adds** to **turn to face**, then tap the spot. | | Any other step | Press its button: drive, strafe (mecanum), turn, turn to, wait, start something, an action, aim at the goal, ready to launch, wait for the goal, park from here. | | A step between two | Point between the two steps in the list, and press the **+** there. Press **Done** when you are finished. | **Change a route on the map:** - **Drag a point** (the blue dot at the end of a drive). The drive and the turn before it change, and the other points stay where they were. - **Put a point between two:** move the pointer over a drive's line. Click the white dot with the plus to split the drive in two. - **Turn a turn:** drag the yellow knob in front of the robot. - **Right-click** a point, a line or the field (or press and hold on a touch screen) for a short menu. **On the map:** a number on a dark badge is a place the robot drives to. An orange diamond with a letter is a step that does something (an action, start something). The same letter is beside the step in the list. ![The map, close up and marked: the green start spot (drag it), the yellow knob in front of it (turn the start), a blue point at the end of a drive (drag it), the dark badge with the step number, the next point, and an orange diamond with the letter A (an action).](https://crossbotics.com/ftc-helper/docs/images/builder-map-marked.png) **A command or an action** opens a list of the ones your code has. Pick one, for example `Actions.scoreHigh(robot)`, or the library's `robot.launcher.fireAllAction()`. **A fire action** has a **flywheel** box. Leave it empty for the usual speed. Type a number (RPM) for this shot's own speed. **Why:** a robot with no camera can shoot from two spots at two speeds. **Mecanum: turn while driving.** Tick it on a drive to make one step that drives and turns at the same time (`moveWithTurn`). **A tank drive cannot slide sideways,** so the builder never makes a strafe for it. ## 3. Edit in 3D (optional) Tick **Edit in the 3D view**. The same points are balls in the 3D view: drag them, or tap the field to add a step. ## 4. The start spot and the note - **Pick a ready-made spot,** or drag the green dot. The robot must touch a field wall. With **Snap** ticked, it lines up with the tile seams, so the drive team can copy it by eye. - **Turn the start** with the yellow knob or the **Face** arrows. - **The numbers** under the map are [field numbers](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/#field-numbers): x, y and heading. - **The note** is what the Driver Hub shows in INIT as `Place robot : ...`. **Write it for me** writes it from the spot, for example "Our wall, tile 3 from left, centered, facing field". About 50 characters fit one line. ![The Start spot part of the builder, with seven numbered marks.](https://crossbotics.com/ftc-helper/docs/images/builder-start-marked.png) 1. A ready-made spot. 2. The field numbers: x, y and heading. 3. Which way the robot faces at the start: the arrows, and 15° turns. 4. **Snap:** the robot lines up with the walls and the tile seams. 5. The note for the drive team. 6. **Write it for me:** writes the note from the spot. 7. The pages to print: the setup card and the auto sheet. The auto sheet (for your partner teams) and the setup card (for your drive team): [Match day](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/#show-your-partners-what-your-robot-does). ## 5. Read the checks Before a run, the builder checks: - the field walls and field parts along the route, - the start rules (touching the wall, on your half, inside the 18 in box), - more than 30 seconds of steps, and the park time, - names left empty. The builder guesses the time from simple speed numbers. The run gives the real time. **A failed check is a warning.** **Run** still works, so you can watch what goes wrong. Fix each warning before you copy the Java. ## 6. Run it Press **Run**. The simulator puts the field's pieces back and puts the robot on the start spot. Then it runs the plan as a real auto: the INIT menu, the 30 s timer, the park time and the report. - A **purple robot** drives the plan. Your robot drives beside it. You see where they part. - The **green line** is the path your robot drove. To run it again, press **Run** again. ## 7. Read the result ![The simulator after a run: the Driver Hub shows "Autonomous finished" and each step done, the 3D view shows the robot after its route, and the builder shows the checks in green and a table: Intake on done, To the goal done 0.7 in off, Fire all done (4 fired), Park done 0.8 in off.](https://crossbotics.com/ftc-helper/docs/images/auto-builder-run.png) ![The checks and the result of a run, with six numbered marks.](https://crossbotics.com/ftc-helper/docs/images/builder-result-marked.png) 1. **The checks,** before the run. Green: fine. Yellow: advice. Red: a problem to fix. 2. **Run in the simulator.** 3. The run's time, of the 30 seconds. 4. **Report:** each step's word from the report. 5. **Off:** how far from the plan the step ended. 6. The result, and what to do next. A table shows each step's word from the report (`done`, `STALLED`, `timed out`, ...) and how far off the plan it ended. **A step can say `done` and still push a field part.** Watch the run. The saved scenario's `expect bumped none` line checks it ([step 8](#8-copy-the-java)). Under the table, **what to change** lists changes to try. Some changes have an **Apply** button, for example a short wait after a drive, so the robot stops rolling before it turns. Press **Run** again to check. ## 8. Copy the Java ![The Java and scenario part of the builder, with five numbered marks.](https://crossbotics.com/ftc-helper/docs/images/builder-java-marked.png) 1. **OpMode:** the auto's name on the Driver Hub. 2. **TeleOp next:** the TeleOp the Driver Hub picks after the auto. 3. **Copy the Java:** the whole file, or only the steps. 4. **Save the scenario:** a test file for this auto. 5. **With the end from the last run:** the test also checks where the robot ended. - **Copy the Java:** the whole file. Make a new file in your `autos` folder. Its name is the name after `public class` in the copied Java. Paste the Java in. - **After Load:** the copy is **only the steps**. Paste them over everything inside `steps(...)` in your file. Your file keeps its comments and its other methods. **First read the list of what Load did not carry over.** The copy leaves out menus (`menuChoice`, `onlyIf`), your own steps and `waitUntil`. When you paste over them, they are gone: a park that ran for one choice then runs every time. Put them back in your file by hand. - **Save the scenario:** a test file that checks the note, the start spot, that each step is `done`, and where the robot ends. Tick **with the end from the last run** to check the end your robot reached in the run. ([Scenario files](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/).) Then stop the simulator (the red Stop button, or **Ctrl+C** in the Terminal) and start it again. Your new auto is in the Driver Hub list, like any auto. The builder keeps your plan in this browser. ## What it cannot do - Menus: `menuChoice`, `menuYesNo`, `onlyIf` ([Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#add-choices-to-the-init-menu)). - A number that differs for RED, `alliance().pick` ([Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#a-different-number-for-red)). - `waitUntil` and your own steps, `step(...)` ([Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#wait-until-a-part-is-ready)). - Pieces in `Routes.java` ([Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#routes)). **Load** cannot read an auto made from them. - `routeTo` ([page 4](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/#go-around-field-parts-routeto)). - A command that is not a part's method or an action, like two calls in one. Write it as a method in `Robot.java` or `Actions.java`, and pick that method. The builder reads only these shapes: `robot.part::method`, `robot::method`, `() -> robot.part.method(...)`, `() -> robot.method(...)`, `Actions.name(robot, ...)` and `robot.part.method(...)` that gives an Action, with plain values (text, numbers, true/false, `robot`). **Why:** the page can reach nothing else in your code or on the laptop, and nothing runs as a script. INIT checks every name before the first step, and names the parts there are when one is wrong. **Why learn the file too:** you change autos at events, often in a hurry, and the builder does not do everything. ## Done when - You built an auto in the builder, and **Run** shows `done` for every step. - You copied it into your `autos` folder, built the project, and it runs from the Driver Hub list in the simulator. ## Problems | Problem | Why, and the fix | | --- | --- | | It found the wrong Robot class | Pick yours in the robot list (step 1). | | **Run** is off | Your robot cannot do this mode (for example a Pedro path with no `follower(...)` line), or the Pedro path is empty. Read the message above **Run**. | | `Robot.java has no part called ...` | The command names a part your robot does not have. Pick one from the list. | | The real robot ends far from the plan | Tune the drive first ([Drive Tuner](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#tune-the-drive-first)). The builder's purple robot drives perfectly. Your robot does not. | | A new auto is not on the Driver Hub | The simulator reads your code when it starts. Stop it (the red Stop button, or **Ctrl+C** in the Terminal) and start it again. | --- **Next:** [The auto builder: odometry and Pedro](https://crossbotics.com/ftc-helper/docs/building-autos/07-auto-builder-odometry-and-pedro/). **Look it up:** [every step](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto). --- # The auto builder: odometry and Pedro URL: https://crossbotics.com/ftc-helper/docs/building-autos/07-auto-builder-odometry-and-pedro/ **You need:** - The auto builder: [The auto builder: steps](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/). - For `driveTo` steps: odometry ([Drive to points](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/)). - For a Pedro path: the Pedro add-on and the `follower(...)` line ([Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/)). What each path setting does is on that page. ## In the auto builder Open the auto builder ([page 6](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/#open-it)). Pick the mode: - **Simple steps:** the drives, turns and actions of page 6. - **Pedro path:** a mecanum robot with odometry. Tap to add lines or curves. Drag the ends and the curve points. Pick each part's heading and speed limit. Tick **Hold the end**. Add things to start along the path (`PathAt`). The Java has a `follow` with a `PedroPath`, or one `driveTo` per part. The builder says when your robot cannot do a mode, and **Run** stays off: - **follow** needs the `follower(...)` line in `Robot.java`. - **driveTo steps** need only odometry. The map in **Pedro path** mode, close up. The path has two parts: a straight line, then a curve: ![The Pedro path on the map, marked: the start, the end of part 1 (a straight line), the control point (a white dot with dashed lines to the curve), the end of part 2, the heading knob (the yellow dot that sets which way the robot faces at the end), and an orange diamond for a PathAt ("Intake on").](https://crossbotics.com/ftc-helper/docs/images/pedro-map-marked.png) - **Drag the ends** to move a part. **Drag the control point** to bend the curve. The robot does not drive through it: it pulls the curve toward it. - **Drag the heading knob** to change which way the robot faces. The settings for the path and each part: ![The Path settings, marked: follow (one Pedro path) or driveTo steps, the path name in the Java, Hold the end, and for a part: line or curve, which way it faces, when it turns, the speed limit, and "+ point" to add a control point.](https://crossbotics.com/ftc-helper/docs/images/pedro-parts-marked.png) **Actions along the path** are the `PathAt` lines: they start something while the robot drives. ![Actions along the path, marked: "+ Add one" (a PathAt), where it starts (here: a part of the path, 0 to 1), how far (0.5 = halfway), a command or an action, and what it starts (robot.intake::in).](https://crossbotics.com/ftc-helper/docs/images/pedro-pathat-marked.png) **A Pedro plan is one path.** Add the steps before and after it in your file. ## Done when - The builder runs your `driveTo` steps or your Pedro path in the simulator, as BLUE and as RED. - The report says `done` for every point or path. - The Java is in your auto file, with the steps before and after it. ## Problems | Problem | Why, and the fix | | --- | --- | | **Run** stays off in Pedro path mode | `Robot.java` has no `follower(...)` line ([Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/)) | | **Run** stays off for driveTo steps | `Robot.java` has no `odometry(...)` line ([Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/)) | | A step or path ends in the wrong place | See the problems on [Drive to points](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/#problems) and [Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/#fix-a-problem) | --- **Next:** [Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/): beyond the auto builder. **Look it up:** [the auto builder, every detail](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/). --- # Advanced autos URL: https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/ ## What this page is for Each part below adds one thing to an auto. Use only the parts you need. | Part | What it does for you | | --- | --- | | [Wait until a part is ready](#wait-until-a-part-is-ready) | The robot drives while a slow part moves. It waits for the part only when it must. | | [One auto with choices, or several autos?](#one-auto-with-choices-or-several-autos) | Pick how to offer plans: one file per plan, or one file with choices in INIT. | | [Add choices to the INIT menu](#add-choices-to-the-init-menu) | Your own lines in the INIT menu, like "Then: Park / Stay". Some steps run only for one choice. | | [Routes](#routes) | Steps that several autos share, written once in `Routes.java`. | | [A whole example](#a-whole-example-one-auto-the-drivers-choose) | One auto file: the drivers choose the start spot and the plan. | | [A different number for RED](#a-different-number-for-red) | One number (a wait, a distance) that is different on RED. | | [Keep code inside the steps](#keep-code-inside-the-steps) | Why a line between two steps runs in INIT, and the fix. | | [Write your own step](#write-your-own-step) | Your own Java code as one step, for what no other step can do. | > **The auto builder cannot write anything on this page.** Build the route in the builder first. Copy the > Java into your file, then add these by hand. **Note:** after you add them, the builder's **Load** may not > read the file again. Keep a copy of the plain plan, so you can change it in the builder later. ## Wait until a part is ready **What it does:** the robot does not stop for a slow part. It drives on, and waits only when it needs the part. **Start early, wait late.** Start a slow part with `run` as early as you can. Then wait for it with `waitUntil` right before you need it: ```java .run("Lift up", () -> robot.lift.goTo("high")) // starts the lift .forward("To the goal", 24, 0.6) // drives while the lift rises .waitUntil("Lift at the top", robot.lift::isAtTarget, 2) ``` **Why:** the robot does two things at once. That saves time in a 30-second match. The checks you can wait for: [page 1, wait](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/#wait). ## One auto with choices, or several autos? **What it means:** you can give the drivers more than one plan in two ways. - **Several autos:** one file per plan ([page 3](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/)). Each plan is its own line in the Driver Hub's Autonomous list. The auto builder can make each one. - **One auto with choices:** one file with your own lines in the INIT menu. The drivers pick the auto, press INIT, then pick the plan with the D-pad. The steps for every choice are in the same file. One auto with choices can replace several autos that are almost the same. Pick by the difference between the plans: | The difference between the plans | Use | | --- | --- | | Red or blue | nothing: the Alliance line is in every menu | | Wait for a partner at the start | nothing: the Start delay line is in every menu | | Wait for a partner in the middle | `menuYesNo` + `onlyIf` | | Park near or far, leave or stay | `menuChoice` + `onlyIf` | | Score 1 piece or 2 | `menuChoice`, or two files | | Another start spot, the same idea | `menuChoice` for the start ([page 3](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/#near-and-far-starts)) | | A different route, nothing shared | a new file | | A test routine (drive a square) | a new file, in its own group, so nobody runs it in a match | **A rule of thumb:** use a menu line for what the drivers decide at the field. Use a new file for what the programmers decide in the pits. Keep the menu small. Two or three of your own lines are fine. Six lines make too many mixes to test. ## Add choices to the INIT menu **What it does:** adds your own lines to the INIT menu. Some steps then run only when the drivers pick one option. Every auto has an **INIT menu** with Alliance, Start delay and Profile ([page 2](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#the-init-menu)). You can add your own lines. **Add your own line,** then mark the steps that run only for one choice: ```java s.start("Against our wall, facing the field", 0) .menuChoice("Then", "Park", "Stay") // a line with two options .forward("To the goal", 24, 0.6) .action(Actions.scoreHigh(robot), 5) .onlyIf("Then", "Park") // only when "Park" is chosen .right("Park", 20, 0.7) .end(); // the end of the onlyIf ``` - `menuChoice(name, option, option, ...)`: a line with options. **INIT starts on the first option.** Make it your safest plan. - `menuYesNo(name, true)`: a YES/NO line. `true` = it starts at YES. Use it with `onlyIf(name)`. - `onlyIf(name, option)` ... `end()`: the steps in between run only for that choice. Every `onlyIf` needs its own `end()`. - Spell the options **exactly** the same in `menuChoice` and `onlyIf`, capitals too. A typo makes a branch that never runs. - **For an "else",** write a second `onlyIf` with the other option. An `onlyIf` can be inside another one: each `end()` closes the last one opened. - `choice(name)` and `isYes(name)` read a line in your own Java, with a plain `if` ([below](#a-whole-example-one-auto-the-drivers-choose)). - The menu cannot ask for a number. A number goes in the step. The indents inside `onlyIf` are only for people. Java does not read them. ## Routes **What it does:** puts the steps that several autos share in one file, `autos/Routes.java`. Each auto then uses them by name. **You do not need it.** One file per plan, each made in the auto builder, is fine ([page 3](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/#one-file-per-plan)). **Pick Routes when** many autos share the same steps, and you fix the same number in many files. | | Copies (one file per plan) | Routes | | --- | --- | --- | | The auto builder | works: **Load** reads each file | does not work: **Load** cannot read an auto made from Routes | | Fix a number | in every file that has the step | once | | Good for | a few plans, made in the builder | many plans that share steps | Each **piece** of a route is a **method** in `Routes.java` (a named group of lines that you run by its name). You build every auto from the pieces. When you fix a piece once, every auto that uses it gets the fix. The library has this example as a compiled file, for the cookbook's robot (a mecanum drive, a lift and a claw): ```java title="autos/Routes.java" package com.crossbotics.ftchelper.examples.cookbook.autos; // In your TeamCode, change the line above to exactly: package org.firstinspires.ftc.teamcode.autos; // and the first two imports below to: import org.firstinspires.ftc.teamcode.Actions; // import org.firstinspires.ftc.teamcode.Robot; import com.crossbotics.ftchelper.examples.cookbook.Actions; import com.crossbotics.ftchelper.examples.cookbook.Robot; import com.crossbotics.ftchelper.robot.Steps; /** The pieces every autonomous is made from. Write each piece once. No @Autonomous: not an OpMode. */ public class Routes { /** Score the piece the robot starts with: hold it, drive to the goal, score. */ public static Steps scorePreload(Steps s, Robot robot) { return s.run("Hold the preload", robot.claw::close) .forward("To the goal", 30, 0.6) .action(Actions.scoreHigh(robot), 5); } /** One more piece: back to the pieces, grab one, forward to the goal, score. */ public static Steps cycle(Steps s, Robot robot) { return s.back("To the pieces", 20, 0.6) .run("Grab", robot.claw::close) .waitSeconds("Let the claw close", 0.3) .forward("Back to the goal", 20, 0.6) .action(Actions.scoreHigh(robot), 5); } /** The park: back toward our wall. It keeps the last 3 seconds for itself, so it always runs. */ public static Steps park(Steps s) { return s.parkWithSeconds(3) .back("Park", 20, 0.7); } } ``` - `public static Steps scorePreload(Steps s, Robot robot)`: a method that adds its steps to the list `s`, and gives the list back. - `Routes.java` has no `@Autonomous` line. It only holds pieces, so it is not an auto. - The numbers are in the steps, like in any auto. You write the piece once, so you write each number once too. **An auto made from pieces** is only a few lines. Each line adds one piece to the same list: ```java title="autos/NearCycle.java" package com.crossbotics.ftchelper.examples.cookbook.autos; // In your TeamCode, change the line above to exactly: package org.firstinspires.ftc.teamcode.autos; // and the first import below to: import org.firstinspires.ftc.teamcode.Robot; import com.crossbotics.ftchelper.examples.cookbook.Robot; import com.crossbotics.ftchelper.robot.Auto; import com.crossbotics.ftchelper.robot.Steps; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; /** Score the preload, one more piece, then park. Only the Routes.cycle line is new. */ @Autonomous(name = "Near: Preload + Cycle + Park", group = "Autos", preselectTeleOp = "Cookbook TeleOp") @Disabled // delete this line in your copy public class NearCycle extends Auto { @Override protected boolean mirrorForRed() { return false; } @Override protected void steps(Steps s, Robot robot) { s.start("NEAR: against our wall, 2nd tile left of center, facing the field", -36, -61, 0); Routes.scorePreload(s, robot); Routes.cycle(s, robot); Routes.park(s); } } ``` Here the lines do not chain the steps with dots. Each line calls a piece, and the piece adds its steps to the same list `s`. The result is the same list as one long chain. A second file, "Near: Preload + Park", is the same without the `Routes.cycle` line. The drivers pick it when the partner needs the pieces. **To copy these files,** change the `package` and `import` lines as the comments say, and delete `@Disabled` ([Copy example files into TeamCode](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/)). In `preselectTeleOp`, write **your** TeleOp's name. ## A whole example: one auto, the drivers choose **What it does:** one auto file holds the plans from [Routes](#routes), a "Park only" plan, and two start spots. The drivers choose the start spot and the plan in INIT: ```java title="autos/ChooseInInit.java" package com.crossbotics.ftchelper.examples.cookbook.autos; // In your TeamCode, change the line above to exactly: package org.firstinspires.ftc.teamcode.autos; // and the first import below to: import org.firstinspires.ftc.teamcode.Robot; import com.crossbotics.ftchelper.examples.cookbook.Robot; import com.crossbotics.ftchelper.robot.Auto; import com.crossbotics.ftchelper.robot.Steps; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; /** ONE autonomous: the drivers choose the start and the plan in INIT. */ @Autonomous(name = "Choose in INIT", group = "Autos", preselectTeleOp = "Cookbook TeleOp") @Disabled // delete this line in your copy public class ChooseInInit extends Auto { @Override protected boolean mirrorForRed() { return false; } @Override protected void steps(Steps s, Robot robot) { // Your menu lines (under the library's Alliance and Start delay lines). The FIRST option of // each is chosen at INIT: make it your safest plan. s.menuChoice("Start", "Near", "Far") .menuChoice("Plan", "Preload + Park", "Preload + Cycle + Park", "Park only"); // The start spot follows the "Start" line: the note and the simulator's robot change with it. s.onlyIf("Start", "Near") .start("NEAR: against our wall, 2nd tile left of center, facing the field", -36, -61, 0) .end() .onlyIf("Start", "Far") .start("FAR: against our wall, 2nd tile right of center, facing the field", 36, -61, 0) // Off the wall first: the FLOWER on our wall stands between the two start spots. .forward("Off the wall", 12, 0.5) .left("Across to the near side", 72, 0.7) .end(); // The plan: plain Java "if". choice(...) = the option chosen, as text. (1)! String plan = s.choice("Plan"); if (!plan.equals("Park only")) Routes.scorePreload(s, robot); if (plan.equals("Preload + Cycle + Park")) Routes.cycle(s, robot); Routes.park(s); } } ``` 1. `s.choice("Plan")` gives the option the drivers chose, as text. `plan.equals("Park only")` asks "is it the same text?". `!` means "not". So the first `if` reads: if the plan is not "Park only", score the preload. What the drivers see after INIT: ```text Place robot : NEAR: against our wall, 2nd tile left of center, facing the field --- Choose (D-pad), then ▶ --- > Alliance: BLUE Start delay: 0 s Start: Near Plan: Preload + Park Profile: COMPETITION X = BLUE B = RED ``` Change **Start** to Far, and the first line at once says `Place robot : FAR: ...`. **Why:** the library reads the steps again each time a menu line changes. So the note always matches the start the drivers chose. ## A different number for RED **What it does:** gives one number a different value on RED. Most autos need nothing more: the library turns or mirrors the steps ([page 2](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#red-and-blue)). Sometimes one thing is different on RED: a wait, a distance, an AprilTag number. `alliance().pick(blueValue, redValue)` gives the right one for the alliance the drivers chose: ```java @Override protected void steps(Steps s, Robot robot) { double parkInches = alliance().pick(20.0, 26.0); // BLUE 20 in, RED 26 in s.start("Against our wall, facing the field", 0) .forward("To the goal", 24, 0.6) .action(Actions.scoreHigh(robot), 5) .parkWithSeconds(3) .right("Park", parkInches, 0.7); } } ``` - `alliance()` is BLUE or RED, from the INIT menu. - `pick(20.0, 26.0)`: the first number for BLUE, the second for RED. Write both with a `.0`. - When the drivers change the Alliance line in INIT, the library reads the steps again. So the number always matches the alliance. **RED differs only** when the field is not the same for both alliances. Check the field drawing. Then run the auto as BLUE and as RED in the simulator. **The auto builder** shows both: **Run as** RED or BLUE. It cannot write `alliance().pick`. Add it in your file. ## Keep code inside the steps **What it means:** every line in `steps(...)` must be a step. A line between two steps runs at the wrong time. The library reads your list of steps **more than once**: 1. In INIT, to learn the menu, the start note and the park time. **No step runs then.** 2. In INIT again, each time the drivers change a menu line. 3. After ▶, to make the real list. Then it runs. So put only steps in `steps(...)`. A line like `robot.claw.close();` between two steps runs in INIT, several times. Put it in a step: `.run("Close the claw", robot.claw::close)`. ## Write your own step **What it does:** runs your own Java code as one step, for something no other step can do. The lines between `{` and `}` are your code: ```java .step("Clear the intake", ctx -> { robot.intake.out(); ctx.waitFor(0.3); // wait 0.3 s; every part keeps working robot.intake.stop(); }) ``` `ctx` is your step's helper (short for "context"). It gives you: | Inside your step | What it does | | --- | --- | | `ctx.waitFor(seconds)` | waits. Every part keeps working | | `ctx.waitUntil(check, seconds)` | waits until the check is true. It gives false if the time ran out | | `ctx.isActive()` | false when the auto is over or the park time came: stop then | | `ctx.secondsLeft()` | the seconds left in the auto | | `ctx.note(text)` | your words in the report, in place of `done` | | `ctx.loop()` | updates every part once: call it in your own loop | | `ctx.telemetry()` | add your own lines to the Driver Hub screen | **Never use `sleep()`.** It freezes every part, and the 30 s timer cannot stop the robot. Use `ctx.waitFor`. ([Why](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/).) ## Done when - One auto file offers a choice in INIT, and each option runs in the simulator. - Each plan runs in the simulator, as BLUE and as RED. ## Problems | Problem | Why, and the fix | | --- | --- | | A menu choice does nothing | The option has a different spelling in `menuChoice` and in `onlyIf` or `equals`. | | The robot ran the wrong plan | Nobody changed the menu, so the first option ran. Read the menu out loud before ▶. | | Every step after an `onlyIf` runs only for one choice | The `end()` is missing. | | `end() without an onlyIf` | One `end()` too many. | | Something moves in INIT | Code is between the steps. Put it in a `run(...)` or a `step(...)`. | | One auto is fixed, another is not | Someone copied the steps. Fix each copy, or move the steps into `Routes.java`. | | `cannot find symbol: Routes` | `Routes.java` must be in the same `autos` folder, with the same `package` line. | | The builder's **Load** cannot read the file | It reads only plain steps. Load the plain copy, or change this file by hand. | **What each word in the report means** (`done`, `STALLED`, ...): [Match day](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/#after-the-match-read-the-report). --- **Next:** [Match day](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/). **Look it up:** [every step](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto). **Go deeper:** [cookbook: several autos and choosing one](https://crossbotics.com/ftc-helper/docs/cookbook/10-several-autos/), [the cookbook's autonomous recipes](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/). --- # Match day URL: https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/ A good auto scores nothing when it starts in the wrong place, or runs the wrong plan. Most auto mistakes at an event are not code mistakes. These checks stop them. ## Before the event - **Pick the autos you bring.** Each partner is different, so you pick the auto in the talk before each match. Bring a few that start in different places or go for different pieces. Give each one good default menu settings, and write them on its setup card. - **Remove what you will not run.** Put `@Disabled` on old and untested autos, and put test routines in `group = "Test"`. - **The first runs of a new auto:** on blocks first, then in PRACTICE, then in COMPETITION ([the first run on the robot](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#the-first-run-on-the-robot)). - **Run every auto on the list** on a real field (or a practice field): as BLUE and as RED, with each menu option, in the COMPETITION profile. - **Save the code you will run:** commit and push it, and tag it ([Git and GitHub](https://crossbotics.com/ftc-helper/docs/guides/github/#before-an-event-backups-and-a-tag)). Then you can always get back to it. - **Print an auto sheet and a setup card** for each auto ([below](#show-your-partners-what-your-robot-does)). ## Show your partners what your robot does Before each match you plan the auto with your alliance partner. They need to know **exactly** what your robot does in auto: where it starts, where it drives, what it scores, and when. Then the two robots do not crash, and they do not go for the same pieces. The auto builder ([page 6](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/)) makes the pages for this. Print them before the event. - **Auto sheet (PDF): for your partner teams.** One page per auto: the start spot, the whole route on the field, and every step in plain words, with its time. Show it in the match talk. Bring one sheet for each auto you can run, so the partner can help pick the one that fits. - **Setup card: for your own drive team.** The start note in big letters, the field with the robot's start spot and heading, what RED does, the start delay, and three checks. The drive team uses it to put the robot down right. Keep one per auto in the drive team's box. To print: press **Auto sheet (PDF)** or **Print setup card**, then **Print or save as PDF**. Black and white is fine. An auto sheet, from the auto builder in the simulator: ![An auto sheet titled "Score and Park": the field map with the start box in the left corner tile, the route and the numbered step ends; beside it the start note, "Red and blue: the same route for both", and the planned time; under it the five steps with their times.](https://crossbotics.com/ftc-helper/docs/images/auto-sheet.png) A setup card, from the web auto builder: ![A setup card: the title "My Auto", the note "Left corner tile, right edge on seam, facing field" in big letters, the field with the robot in the left corner tile facing the field, and three checks for the drive team.](https://crossbotics.com/ftc-helper/docs/images/setup-card.png) ## Before each match A checklist for the drive team: 1. **Talk with the partner:** show your auto sheet. Agree who starts where, who goes where, and who needs a delay. 2. **Choose the auto** on the Driver Station. Read its name out loud. 3. Press **INIT**. **Read the menu out loud:** alliance, start delay, your lines. 4. Set the **Alliance**: **X** = BLUE, **B** = RED. 5. Check that **Profile** says **COMPETITION**. A `!! PRACTICE profile` warning at the top means it does not ([what changes](#practice-and-competition)). 6. **Place the robot** where the `Place robot` note says. A second person checks the note against the robot. 7. **Look for warnings** on the screen: a camera, the odometry, tuned values that differ from the code. 8. Hands off. Press ▶ when the match starts. ### Wrong alliance? | When you see it | What to do | | --- | --- | | In INIT, before ▶ | Press **X** for BLUE or **B** for RED. Read the menu out loud again. | | During auto | You cannot change it. Let the auto run. | | In TeleOp | Hold gamepad 1 **START**, then also hold **BACK**, for 1.5 s. The screen says `Alliance now RED (was BLUE)`. Hold them again to switch back. If you let go before 1.5 s, the alliance stays the same and the debug lines turn on or off. | **The TeleOp switch is off until you turn it on.** Add one line to `Controls.java`: `lib.switchAlliance(g1.start, g1.back);` ([switching the alliance in TeleOp](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/#switching-the-alliance-in-teleop)). With odometry on BIOBUZZ, a switch turns off aiming by odometry. The robot does not aim at a wrong spot: it does not aim by odometry at all. The screen says `odometry aim OFF until the pose is set`. To turn it on again, park on the reset spot and hold START 1 s. TeleOp keeps the alliance from the auto, so a wrong alliance in INIT is wrong in TeleOp too. Turn the switch on before the event, and write **START + BACK, 1.5 s** on the setup card. ### Practice and competition The **Profile** line in INIT has two settings. The Control Hub remembers it until someone changes it. | | PRACTICE (in the shop) | COMPETITION (at an event) | | --- | --- | --- | | Drive power | the same: `maxPower` (unless you set `practiceMaxPower`) | `maxPower` | | Debug lines on the screen | on | off | | Tuning menu (hold GUIDE) | opens | stays closed | | Camera live view | on | off (it costs speed) | | A part that is off | a quiet note | a loud `!!` warning | | The top of the INIT screen | `!! PRACTICE profile` | nothing | | Your own `Profile.pick(a, b)` | `a` | `b` | Safety (limits, time limits, jam checks) is the same in both. COMPETITION is the default. Back in the shop, set PRACTICE again. More: [Profiles](https://crossbotics.com/ftc-helper/docs/guides/profiles/). ## After the match: read the report When the auto ends, the Driver Station shows `Autonomous finished` and one line per step: ```text Start: done Hold the piece: done To the goal: done Score high: timed out Park: done ``` The robot log and TeleOp's INIT screen show the same report, so the drive team can read it while they set up for TeleOp. | The word | It means | | --- | --- | | `done` | The step finished. | | `timed out` | A wait or an action ran out of time. The list went on. | | `STALLED` | A drive could not finish: the robot was stuck. | | `TIMED_OUT` | A drive took too long. | | `STOPPED` | Something outside the drive stopped it: someone pressed STOP, or the 30 seconds ended. | | `NO_ODOMETRY` | A `driveTo` stopped: the odometry did not answer. | | `cut short (time for park)` | The auto stopped the step early, so the park steps had time. | | `skipped (time for park)` | The auto did not start the step: no time was left before parking. | | `skipped: Tunables.Odometry.checked is false` | A `driveTo` on a real robot before the Odometry Tuner. | | `not seen` | `aimAtGoal` did not see the goal, so the robot did not turn. | | `not seen in 5 s: went on` (your seconds) | `waitForGoal` did not see the goal in its time. | | your own words | From your own step, or an action's reason. | **Write down** every step that does not say `done`. Fix it in the pits: - `timed out` on an action: the part is slow, or its numbers are off. Check the part. - `STALLED`: the route hits something. Watch it in the simulator. Use `routeTo` near field parts. - `cut short` or `skipped (time for park)`: the auto is too long. Remove a step, or drive faster. Change the number in the step, test it, and commit. ## Common mistakes | What happens | Why, and the fix | | --- | --- | | The robot ran the wrong plan | Nobody changed the menu, so the first option ran. Read the menu out loud before ▶. | | The robot started in the wrong place | Nobody checked the note. Start the note with the spot in CAPITALS. A second person checks it. | | The robot drove at low power | `maxPower` in `Tunables.Drive` is still low from the first runs. Or someone set `practiceMaxPower`, and the profile was PRACTICE ([what changes](#practice-and-competition)). | | The robot went the wrong way in TeleOp | The alliance was wrong in INIT, and TeleOp kept it. [Wrong alliance?](#wrong-alliance) | | The robot went the wrong way for RED | The alliance was wrong, or `mirrorForRed()` is wrong for this field. | | The drivers could not find the auto | Too many on the list. Add `@Disabled` to the old ones. | | TeleOp was not chosen after the auto | `preselectTeleOp` must be the TeleOp's name, exactly. | | `AUTONOMOUS IS OFF` | `calibrated` is `false` in `Tunables.java` ([Tune the drive first](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#tune-the-drive-first)). | ## Done when - Each auto on the list has run on a field, as BLUE and as RED. - The drive team has a setup card for each auto, and the checklist. - After a match, the drive team reads the report and writes down each step that is not `done`. --- **Next:** [Simulator](https://crossbotics.com/ftc-helper/docs/simulator/): watch your autonomous and fix it on the laptop. **Look it up:** [every step](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto). **Go deeper:** [test an auto with a scenario file](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/). --- # Tuning URL: https://crossbotics.com/ftc-helper/docs/tuning/ Every robot program is full of numbers: where a servo opens, how high a lift may go, how fast a flywheel spins, how big the wheels are. When you guess them, you waste practice time and break parts. The **finders** measure them for you and show the lines to copy into `Tunables.java` and `Robot.java`. ## The tuning order Go from top to bottom. Skip a tool for a part your robot does not have: the **Tune and check** menu leaves it out.
flowchart TB
    subgraph G1["Wiring"]
        H["Wiring checks<br/>devices, wheels, encoders"]
    end
    subgraph G2["Parts that move"]
        direction LR
        S["Servo Finder<br/>ends + positions"] --> HO["Hood Finder<br/>two stops"] --> M["Motor Finder<br/>limits + positions"]
    end
    subgraph G3["The launcher"]
        direction LR
        F["Flywheel Finder<br/>gains + recovery"] --> FS["Feed Stop Finder<br/>hold + release"]
        F --> FT["Feed Time Finder<br/>feedSec"]
    end
    subgraph G4["Driving"]
        direction LR
        D["Drive Tuner<br/>wheel size + strafe"] --> O["Odometry Tuner<br/>pods + offsets"] --> MV["Move Tuner<br/>stops + turns"]
    end
    subgraph G5["Scoring"]
        direction LR
        L["Camera lighting<br/>a setup, not a tool"] --> A["Aim Tuner<br/>camera offset"] --> T["Shot Tuner<br/>shot table"]
    end
    subgraph G6["Last"]
        direction LR
        P["Piece Tuner<br/>sensors"] --> C["Characterizer<br/>how it moves"]
    end
    G1 --> G2 --> G3 --> G4 --> G5 --> G6
| # | Page | It finds | Why it comes here | | --- | --- | --- | --- | | 1 | [Before you tune: the Tune and check OpMode](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/) | nothing: the menu, safety, help | read it once | | 2 | [Wiring checks](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/) | Hardware Check, Motor Direction, Encoder | every other number trusts the wiring, so it comes first | | 3 | [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/) | ends and positions | a servo pushed past its end breaks, so find the ends before code moves it | | 4 | [Hood Finder](https://crossbotics.com/ftc-helper/docs/tuning/04-hood-finder/) | a hood's two stops | the Shot Tuner writes hood positions, so the hood needs its stops first | | 5 | [Motor Finder](https://crossbotics.com/ftc-helper/docs/tuning/05-motor-finder/) | limits and positions | a wrong limit breaks parts, so do it before you drive a mechanism with code | | 6 | [Flywheel Finder](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/) | gains (the numbers that hold its speed) and recovery | the shot table is only true when the wheel holds its speed | | 7 | [Feed Stop Finder](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-stop-finder/), or [Feed Time Finder](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-time-finder/) for a CR servo or motor feeder with no feed stop, pushing parts or feed wheel (a robot gets one or the other) | hold and release; or `feedSec` (how long the feeder runs per shot) | the launcher must feed one piece at a time before you tune shots | | 8 | [Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/) | wheel size and strafe | autonomous moves need the right distances. Autonomous stays off until it passes | | 9 | [Odometry Tuner](https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/) | pod directions and offsets (a pod is a small free wheel that measures how far the robot rolls) | `driveTo` and the shot distance need a true pose (where the robot is on the field, and which way it faces). Path steps stay off until it passes | | 10 | [Move Tuner](https://crossbotics.com/ftc-helper/docs/tuning/10-move-tuner/) | where moves stop, how turns end | it needs the right distances (Drive Tuner) and, with odometry, a true pose to measure with | | 11 | [Camera lighting](https://crossbotics.com/ftc-helper/docs/tuning/11-camera-lighting/) (a setup, not a tool) | the camera setting for each kind of light | the camera must see the tags well before you aim or tune shots | | 12 | [Aim Tuner (own file)](https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/) | camera offset | aim first, so you build the shot table with straight shots | | 13 | [Shot Tuner](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/) | the shot table | it needs a steady wheel, straight aim and a true distance: everything above | | 14 | [Piece Tuner](https://crossbotics.com/ftc-helper/docs/tuning/14-piece-tuner/) | what each sensor sees | nothing moves, so it can also come earlier | | 15 | [Characterizer (own file)](https://crossbotics.com/ftc-helper/docs/tuning/15-characterizer/) | how the motors move | it needs a robot that drives and lifts that work, so it comes last | **After the finders:** - [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/): change a number from the gamepad while your TeleOp runs (the tuning menu in TeleOp, not Tune and check). - [Fix it by what you see](https://crossbotics.com/ftc-helper/docs/tuning/17-fix-by-symptom/): "the lift sags" -> which number to change, and which way. --- **Next:** [Before you tune: the Tune and check OpMode](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/). --- # Before you tune: the Tune and check OpMode URL: https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/ **You need:** a robot with its configuration done, and a block to lift it. ## The Tune and check menu The library adds one OpMode by itself: **Tune and check** (TeleOp list, group "Finders"). You have no file to copy. It holds the Hardware Check and every finder that fits your Robot.java. 1. Pick **Tune and check** and press INIT. A menu shows. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. D-pad up/down picks a tool. **A** opens it, and you see its own INIT screen. Read its safety note. 3. Press **▶** (start) on the Driver Hub. The tool runs, the same as on its own. 4. For another tool, press STOP, then INIT. The menu starts on the last tool. In a tool's INIT, **BACK** goes back to the menu. The menu lists only the tools that fit your robot. It finds Robot.java by itself: any class in `org.firstinspires.ftc.teamcode` that extends `RobotDefinition`. With two robots, D-pad left/right picks one. | Tool | In the menu when | | --- | --- | | Hardware Check | always | | Motor Direction Check | there is a Robot.java | | Encoder Check | there is a Robot.java | | Servo Finder | the configuration has a servo | | Hood Finder | the robot has a hood | | Motor Finder | the robot has a lift or an arm (or there is no Robot.java) | | Flywheel Finder | the robot has a launcher (or there is no Robot.java) | | Feed Stop Finder | the launcher has a `.feedStop(...)` | | Feed Time Finder | the launcher's feeder is a CR servo or a motor, with no feed stop, pushing parts or feed wheel | | Drive Tuner | there is a Robot.java | | Odometry Tuner | Robot.java has an `odometry(...)` line | | Move Tuner | there is a Robot.java | | Shot Tuner | the robot has a launcher | | Piece Tuner | the robot has a piece sensor | Two tools are not in the menu: the **Aim Tuner** and the **Characterizer**. They need your camera or your lifts, so they keep their own file ([Aim Tuner](https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/), [Characterizer](https://crossbotics.com/ftc-helper/docs/tuning/15-characterizer/)). Your own finder files still work: keep them or delete them. ## Before you start - Put the robot on a block for the Servo, Motor and Flywheel finders (wheels off the floor). - Wear eye protection for the Flywheel Finder, Shot Tuner and Aim Tuner. Keep everybody out of the line of fire. - Use a charged battery (12.5 V or more) for the Drive Tuner, the Move Tuner, the Characterizer, the Flywheel Finder and the Shot Tuner. Their numbers are powers and speeds, so they depend on the battery. Their screens show the battery and warn when it is low. Every finder writes the battery at the start (▶) in the results file (`== Drive Tuner, 2026-10-24 14:05, battery 12.8 V ==`). - The simplest way is **Tune and check** (above). It has every finder that fits your robot, with no file to copy. Or use one file per finder. The finders are in the starter kit (`ServoFinder`, `MotorFinder`, `FlywheelFinder`, `DriveTuner`, `Characterizer`) and in the examples (`ExampleShotTuner`, `ExampleAimTuner`: put your launcher and camera in them). Remove `@Disabled` and build. Then they are in the TeleOp list under "Finders". - The robot in five files: the Servo, Motor and Flywheel finders need no code. The Drive Tuner, the Odometry Tuner, the Move Tuner and the Shot Tuner need one line that names your robot. The line makes your `Robot`, so the tuner uses its parts. Examples: `lessonbot`'s [DriveTuner.java](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/lessonbot/DriveTuner.java), the turret robot's [ShotTuner.java](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/turretbot/ShotTuner.java): ```java @Override protected RobotDefinition robot() { return new Robot(); } ``` ## Help on the robot Press **GUIDE** (the center button) in any finder, in INIT or while it runs. A page shows every button and the steps. The Hardware Check has no help page. When your gamepad has no GUIDE button, or GUIDE does nothing, hold the gamepad's **START** for 1 second instead. While help is open, the finder's buttons pause and its motors stop. GUIDE again goes back. Then let go of every stick, trigger and button once: until then, the finder ignores them. Check once on your own Driver Hub and controllers that the help page fits and is easy to read. The screens show the button names on YOUR controller (× ○ □ △ on a PlayStation controller). These pages use the Logitech names ([every name](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/#the-buttons)). **▶** on a screen is always the Driver Hub's start button, never a gamepad button. ## Put the lines into your code Every finder ends with lines for your code. The robot uses the files, not the finder's screen. You cannot copy and paste from the Driver Hub, so there are two ways: - **Type them.** First take a photo of the Driver Hub's screen with a phone. Then type each line from the photo into the file on the laptop. The photo keeps the numbers after you press STOP, and you can zoom in to read each digit. This is fine for a few numbers. Check each digit twice. - **Copy them from the results file.** When you press STOP, the finder saves its lines on the Control Hub. Get that file on the laptop, then copy and paste ([Get the results file on the laptop](#get-the-results-file-on-the-laptop)). This is best for long lines, like a shot table. Each finder shows two kinds of lines. Use the kind that fits your code: | Your code | Copy the lines that start with | Example | | --- | --- | --- | | the robot in five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)) | `Tunables.` or `Robot.java:` | `Tunables.Lift: min = 0, max = 2580, P1 = 1200` = in `Tunables.java`, section `Lift`, set those three numbers | | the older helpers | the rest (`PositionMotor.create(...)`, `c.wheelDiameterIn = ...`) | `PositionMotor.create(hardwareMap, "lift").limits(0, 2580)` | The section is the device's name in CamelCase (each word starts with a capital, with no spaces): `lift` -> `Lift`, `intake_deploy` -> `IntakeDeploy`. When you gave the part its own section with `.tunables("Name")` in Robot.java, copy the numbers into that section instead. The finders call positions P1, P2...: give them real names (`low`, `high`, `open`, `closed`). ### Get the results file on the laptop When you press STOP, every finder adds its lines to `/sdcard/FIRST/ftc-helper/finder-results.txt` on the Control Hub, with the date. The Driver Station says whether it worked. The newest results are at the end. 1. Connect the laptop to the Control Hub: a USB cable, or the robot's Wi-Fi. 2. Open the file with one of these: - the **REV Hardware Client**: its file manager, in the folder `FIRST/ftc-helper/` - **Android Studio**: **View > Tool Windows > Device Explorer**, then `sdcard/FIRST/ftc-helper/` 3. Copy the lines you need into `Tunables.java` or `Robot.java`. ## Done when - **Tune and check** is in the TeleOp list, and its menu shows the tools for your robot. - You know where the results file is. --- **Next:** [Wiring checks: motors and encoders](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/). **Look it up:** [finders module](https://crossbotics.com/ftc-helper/docs/modules/finders/), [How to read a finder's lines](https://crossbotics.com/ftc-helper/docs/reference/tunables/#how-to-read-a-finders-lines). --- # Wiring checks: motors and encoders URL: https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/ **In Tune and check:** always. **You need:** the robot on a block (the wheels spin), lifts and arms at their bottom stop, hands clear. Do these three checks first, on every new robot, and again after you change a motor or a cable. Every other number trusts the wiring. ## Get to the checks 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad up/down** until the arrow (`>`) is on the check you want: **Hardware Check**, **Motor Direction Check** or **Encoder Check**. Then press **A**. ![The Tune and check menu with the arrow on Hardware Check: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-wiring-checks-go-menu.svg) 3. The check's INIT screen shows. Nothing moves yet. Put the robot on a block, and press **▶** (start) on the Driver Hub. ![The Hardware Check's INIT screen: Found 12 devices. Robot on a block! Press start](https://crossbotics.com/ftc-helper/docs/images/hub-hardware-check-go-start.svg) For the next check, press STOP, then INIT again, and pick it in the menu. ## Hardware Check: every device answers The Hardware Check finds every device and moves each motor and servo. It spins a motor in its raw direction, so it does not check `reversed(...)`: the next check does. What to look for, device by device: [Hardware check](https://crossbotics.com/ftc-helper/docs/tests/03-checks-before-practice-and-matches/#3-hardware-check-after-a-wiring-or-configuration-change). ## Motor Direction Check: each wheel rolls forward The Hardware Check spins a motor in its raw direction. This check uses your directions, so it shows what the robot will do. It spins ONE drive motor at a time at 30%, set up exactly as Robot.java says: its direction comes from `reversed(...)` on the drive line. 1. Hold **X** (front-left), **Y** (front-right), **A** (back-left) or **B** (back-right). On a tank drive, X = left and Y = right. The screen shows the motor's name, and "(reversed)" when Robot.java reverses it. ![Hold X: the front-left wheel spins, and the Driver Hub shows X front-left : "front_left" RUNNING](https://crossbotics.com/ftc-helper/docs/images/hub-motor-direction-check-step-hold.svg) 2. Each wheel must roll the way that drives the robot FORWARD. For the robot in five files, the front is the end that Robot.java says. 3. When a wheel rolls backward, add its name to `reversed(...)` on the drive line in Robot.java (or take it out). Build and install the code, then check it again: press STOP, then INIT, open Motor Direction Check, and press ▶. ![Check it again, hold X: the Driver Hub shows X front-left : "front_left" (reversed) RUNNING](https://crossbotics.com/ftc-helper/docs/images/hub-motor-direction-check-step-fixed.svg) 4. When the wrong wheel turns, its name in the robot configuration is on the wrong port. Swap the names on the Driver Hub, not the wires. A wrong direction makes the robot drive in circles, strafe the wrong way, or fight itself. So run the check on every new robot, and again after you change any motor or wire. ## Encoder Check: each encoder cable in its own port A motor's encoder counts its turns. It has its own small cable, plugged into the hub next to the motor's power cable. A lift, an arm, a flywheel's speed and the drive's distances all trust that count. When the cable is in ANOTHER motor's port, the lift reads the wrong motor and never stops. When the cable is missing, the count stays at 0 and the lift pushes into its stop. The check pushes each motor in Robot.java a little (30% power for 0.3 s), one at a time. It reads EVERY motor port's count, and shows a result for each motor: | Result | What it means | Fix | | --- | --- | --- | | OK: counts up (or down) | its own port counted, the way the check pushed it | nothing | | NO COUNTS | no port counted | plug in the encoder cable, or replace it. Or the motor did not turn: check that you saw it move | | counts on "X" instead | another motor's port counted | the encoder cables are swapped: put each one in its own motor's port | | counts on "lift_right" instead: plug the encoder cable into "lift_left"'s port | a two-motor lift or arm: the library reads only the first motor's encoder | move the cable to the first motor's port | | counts BACKWARD | its port counted the other way from the push | the motor's power wires are swapped (red and black), or an outside encoder is mounted the other way | | no counts (fine: nothing reads this encoder) | an intake or feeder with no encoder cable | nothing | | could not read its encoder | the hub did not answer | press **Y** to check again. When the result stays, check the hub's cables | | NOT IN THE CONFIGURATION | Robot.java names a motor the configuration does not have | add it to the configuration, or mark the part `optional()` | 1. Put the robot on a block, with lifts and arms down. In **Tune and check**, open **Encoder Check**, then press **▶**. ![The Encoder Check's INIT screen: Then press start. Hold A: each motor gets a short push](https://crossbotics.com/ftc-helper/docs/images/hub-encoder-check-go-start.svg) 2. Hold **A**. Each motor gets its short push in turn. When you let go of **A**, everything stops at once. ![Hold A: the Driver Hub shows "back_left" (drive) : PUSHING, and OK for the motors before it](https://crossbotics.com/ftc-helper/docs/images/hub-encoder-check-step-hold.svg) 3. Read the results. Fix the cables. Press **Y** to check again. ![Fix the cables, then press Y: the Driver Hub shows "lift" (Lift) : NO COUNTS and 1 problem(s)](https://crossbotics.com/ftc-helper/docs/images/hub-encoder-check-step-again.svg) The check sets up each motor as Robot.java says (its direction). It pushes the motor toward the side where its part has room. It reads that side from your `Tunables.java`: a lift up from its bottom stop, a hood toward `posB`, a turret toward the end of its range that is farther from its start angle. Its count must move the same way. **Watch each part while the check pushes it.** The count turns with the direction setting, so the check cannot see a wrong `reversed()` in Robot.java. Only your eyes can. A lift or arm must move UP, away from its stop. When it moves down, fix `reversed()` on its line in Robot.java. For the drive, use the [Motor Direction Check](#motor-direction-check-each-wheel-rolls-forward). Before each push, the check waits until every port is still (for example, until a flywheel spins down). So it never mistakes one motor for another. When something keeps moving, the screen names it. The check does not check servos, CR servos, a CR servo turret, or a motor whose port reads something else. Those are an odometry pod (the [Odometry Tuner](https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/) checks pods) and a CR servo turret's encoder. Run it on every new robot, and again after you change any motor or cable. ## Fix a mistake - **Hardware Check:** it only reads the devices. There is nothing to undo. - **Motor Direction Check:** a wheel runs only while you hold its button. Let go, and it stops. - **Encoder Check:** press **Y** to run the check again. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code These checks give no numbers to copy. You fix what they find in two places: | The check finds | Fix it in | | --- | --- | | a wheel rolls backward | `reversed(...)` on the drive line in `Robot.java` | | a lift or arm moves down when the check pushes it | `.reversed()` on its line in `Robot.java` | | the wrong wheel turns | the robot configuration on the Driver Hub (swap the names, not the wires) | | an encoder cable is missing, swapped or backward | the cables on the hub | ## Done when - The Hardware Check finds every device. - every drive wheel rolls the way that drives the robot forward. - every motor says OK (or "no counts (fine...)" for a motor whose encoder nothing reads). --- **Next:** [Servo Finder: ends and positions](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/). **Look it up:** [Hardware Check module](https://crossbotics.com/ftc-helper/docs/modules/testing/), [Troubleshooting: robot behavior](https://crossbotics.com/ftc-helper/docs/troubleshooting/#robot-behavior). --- # Servo Finder: ends and positions URL: https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/ **In Tune and check:** yes, when the configuration has a servo. **You need:** the robot on a block. ## Get to the Servo Finder 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Servo Finder**, then press **A**. ![The Tune and check menu with the arrow on Servo Finder: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-servo-finder-go-menu.svg) 3. The Servo Finder's INIT screen shows. Nothing moves yet. Press **▶** (start) on the Driver Hub. ![The Servo Finder's INIT screen: Nothing moves until you nudge it. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-servo-finder-go-start.svg) 4. Press **D-pad up/down** until the arrow is on your servo's name, then press **A**. The names come from the robot configuration. ![Choose a servo: the arrow on claw, then press A](https://crossbotics.com/ftc-helper/docs/images/hub-servo-finder-go-choose.svg) The screen now shows `Start point : 0.500`. Nothing has moved yet. Go on with the steps below. ## A new servo part, step by step With a new servo, the hard part is that you do not know which way it turns, or where its ends are. Go in this order, slowly. Use **Tune and check > Servo Finder**: it knows Robot.java (`reversed()`, a second servo, the servo's catalog part). 1. **Arm off.** Put the servo in, but leave its arm (the horn) off, or its screw loose. Then nothing can hit the frame while you start. 2. **Go to the middle.** Leave the start point at 0.500 and press **A**. The servo goes to the middle of its turn and holds there. ![Press A: the servo arm points straight up, the middle, and the Driver Hub shows Position : 0.500](https://crossbotics.com/ftc-helper/docs/images/hub-servo-finder-step-middle.svg) 3. **Put the arm on in the middle of the part's swing**, so the part can move both ways from here. Tighten the screw. Mark the horn and the shaft with a paint pen, so a new horn later goes on the same tooth ([Put an arm back on](#put-an-arm-back-on)). 4. **Find the direction.** Press **D-pad left** once (a 0.01 step), then press **D-pad up** (bigger) a few times and watch the part. Write it down: "bigger = open", "bigger = up". No standard says which way a servo turns ([why](https://crossbotics.com/ftc-helper/docs/conventions/#servos-and-motors-which-way-is-bigger)). For a catalog servo, the screen shows a **Hint** (goBILDA: "bigger = clockwise (seller)"). But only your test counts, because the part's way depends on how you mount the servo. ![Press D-pad up: the arm turns clockwise, and the Driver Hub shows Position : 0.600 and the Hint line](https://crossbotics.com/ftc-helper/docs/images/hub-servo-finder-step-direction.svg) 5. **Find the first end, slowly.** Move toward one end in small steps (D-pad up/down) until the part BARELY touches the frame. D-pad left makes the step smaller, down to 0.001. **A servo that hums is pushing on something: back off at once.** It gets hot and can strip its gears. Back off 0.01 more and press **X**. ![At one end, press X: the arm is just before the frame, and the Driver Hub shows End X : 0.120](https://crossbotics.com/ftc-helper/docs/images/hub-servo-finder-step-end-x.svg) 6. **Find the other end.** Move the part all the way back with the D-pad, past the middle, to the other end. Use a big step first, then small steps near the frame. Stop just before the frame in the same way, and press **B**. ![At the other end, press B: the arm moved across to just before the other frame, and the Driver Hub shows End B : 0.880](https://crossbotics.com/ftc-helper/docs/images/hub-servo-finder-step-end-b.svg) 7. **Save each position you need** (open, closed, rest, push...): move there and press **A**. Then copy the lines into `Tunables.java` ([Put the numbers in your code](#put-the-numbers-in-your-code)). ![Press A at each position: the Driver Hub shows Tunables.Claw: P1 = 0.210, P2 = 0.770 under Copy into your code](https://crossbotics.com/ftc-helper/docs/images/hub-servo-finder-step-positions.svg) 8. **To make "bigger" go the other way** (for example, bigger = up), add `.reversed()` to the part in Robot.java. Then find the positions again: each old number becomes 1 minus it. **Two servos on one part:** do step 1 for BOTH arms. Choose the FIRST servo: the second moves with it, mirrored. Then put both arms on at the middle (step 3), so they match, and go on from step 4. If they do not quite meet, set `alsoTrim` afterward, in TeleOp. **At ▶**, the part goes straight to its first position from wherever it is, because a servo always knows its own angle. Keep hands clear. ## The finder's buttons ![Servo Finder: X and B mark the two ends, right before the frame; A saves each position between them](https://crossbotics.com/ftc-helper/docs/images/finder-servo.svg) 0. **Full range:** when the part has `.fullRange()` in Robot.java, press **Y** while you choose the servo, so the finder uses the same range. Full range is the servo's whole turn: for a goBILDA 2000 servo, 300 degrees instead of 270 ([why](https://crossbotics.com/ftc-helper/docs/modules/hardware/#full-range)). Positions that you find with one range are wrong with the other. 1. Choose the servo (D-pad, A). A servo cannot tell the program where it is. So first choose a START POINT near where it sits now (D-pad up/down; nothing moves), then press A, and it moves there. Then nudge it with the D-pad. Up/down moves it by the step. Left/right makes the step smaller/bigger (0.1, 0.05, 0.01, 0.005, 0.001). The step starts at 0.05, and the screen shows it. Use a big step to get close, then a small one for the exact spot. 2. Move it toward one end until it BARELY stops pushing on the frame. Listen: a straining servo hums. Back off a little (0.01), and press **X**. Do the same at the other end, and press **B**. From then on, the finder keeps the servo between them. To go past an end, for example to mark it again, hold **LB** while you nudge. The ends are for you: keep every position you save between them. In five files, there are no end lines to copy. The older helpers get the ends as the servo's limits. 3. Move to each position you need (open, closed...) and press **A**. Rename P1, P2 in your code. Five files: the line `Tunables.Claw: P1 = 0.210, P2 = 0.770` becomes `public static double open = 0.210, closed = 0.770;` in `Tunables.Claw`. Keep every position between the ends that the finder shows. **Y** undoes the last saved position. **BACK** chooses another servo, and the lines found so far stay on the screen. **`reversed()` in Robot.java:** in **Tune and check**, the finder turns the servo the same way. The screen says `Direction: reversed, as in Robot.java`, so its numbers go straight into Tunables.java. Either order is fine: `rest` may be higher or lower than `push`, and `open` higher or lower than `closed`. Which way a bigger number turns depends on the servo, because there is no standard. D-pad up shows you ([Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/#servos-and-motors-which-way-is-bigger)). **A part on two servos** (`alsoServoReversed(...)` or `alsoServo(...)` in Robot.java): for example, a claw with a servo for each finger, or two feed arms. Choose the FIRST servo. In **Tune and check**, the second servo moves with it (mirrored or the same way, as Robot.java says), so the two never fight. The screen shows `Moves with it: claw_right (mirrored)`. You cannot choose the second servo alone. The finder does not use `alsoTrim`: check it afterward, in TeleOp. A Servo Finder of your own (not from Tune and check) does not know Robot.java and moves only one servo. It would drag the other, unpowered servo through its gears. So take the other side's arm off first, or unplug the second servo's wire. ## Fix a mistake - **Saved a wrong position (A):** press **Y**. It undoes the last saved position. Press it again for the one before. - **Marked the wrong end (X or B):** move to the right place and press the same button again. The new end replaces the old one. To move past the old end, hold **LB** while you press the D-pad. - **Chose the wrong servo:** press **BACK** and choose again. When you choose a servo again, its ends and positions start over. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code When you have saved both ends and your positions, the screen looks like this. The marked lines are the ones for the robot in five files. The `PositionServo.create(...)` lines above them are for the older helpers. ![The Driver Hub with both ends marked (0.120 and 0.880), two saved positions, and the lines to copy: Tunables.Claw: P1 = 0.210, P2 = 0.770](https://crossbotics.com/ftc-helper/docs/images/hub-servo-finder-done.svg) The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `Tunables.Claw: P1 = 0.210, P2 = 0.770` | the part's section in `Tunables.java`. Rename them: `public static double open = 0.210, closed = 0.770;` | ## Put an arm back on Do this after a new horn, a broken arm, or a repair. Then your numbers in `Tunables.java` stay right. **Keep the servo on while you put the arm on.** A servo with no power turns freely. When you push the horn onto the shaft, the shaft can turn, and the arm goes on one tooth off. A servo with power holds its shaft still. 1. **Look for the paint pen marks** on the horn and the shaft. No marks? Make them before you take the old arm off. 2. **Hold the servo at a known number.** In **Tune and check > Servo Finder**, choose the servo. Set the start point to a number from `Tunables.java`, for example your `rest` (D-pad up/down), and press **A**. The servo goes there and holds. It holds only while the finder runs: do not press STOP yet. 3. **Put the part where that number puts it**, for example against its rest stop. A block or a jig helps you find the same spot each time. 4. **Push the horn on**, with the paint marks lined up. When the teeth do not let the part sit exactly there, use the closest tooth. Do not turn the servo by hand: it is holding. 5. **Tighten the screw** while the servo still holds. Mark the horn and the shaft again. 6. **Check each position.** Press STOP, run your TeleOp, and move the part to each position. A little off (less than one tooth)? Find that position again with the finder and change its number in `Tunables.java`. One spline tooth on a goBILDA servo is about 0.05 in position. **Two servos on one part:** loosen or take off BOTH arms first. Choose the first servo in step 2: both servos go to the number and hold. Put both arms on, then check that they meet. ## Done when every position you use is in `Tunables.java`, between the two ends. --- **Next:** [Hood Finder](https://crossbotics.com/ftc-helper/docs/tuning/04-hood-finder/). **Look it up:** [Claw, Wrist and Positioner: In Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#in-tunablesjava), [ServoFinderOpMode](https://crossbotics.com/ftc-helper/docs/modules/finders/). --- # Hood Finder URL: https://crossbotics.com/ftc-helper/docs/tuning/04-hood-finder/ **In Tune and check:** yes, when the robot has a hood. **You need:** the hood mounted, the flywheel off. ## Get to the Hood Finder 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Hood Finder**, then press **A**. ![The Tune and check menu with the arrow on Hood Finder: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-hood-finder-go-menu.svg) 3. The Hood Finder's INIT screen shows. Nothing moves yet. Press **▶** (start) on the Driver Hub. A motor hood's screen says `Motor hood: nothing is powered` instead. ![The Hood Finder's INIT screen: Servo hood: nothing moves until you choose a start point and press A. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-hood-finder-go-start.svg) ## Steps The Hood Finder is for a launcher's [hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/) (`Tunables.Hood`). It reads the hood from Robot.java, so it works before Tunables.Hood has numbers. A hood with `.fullRange()` gets the same full range here. 1. **A servo hood:** choose a START POINT near where the hood sits (D-pad up/down; nothing moves), and press **A**. Then nudge it with the D-pad. Up/down moves it by the step. Left/right makes the step smaller/bigger (0.1, 0.05, 0.01, 0.005, 0.001). The step starts at 0.05, and the screen shows it. **A motor hood:** nothing is powered. Start the OpMode with the hood on the stop that you want as 0 ticks (the same as before a match). Then move the hood by hand and watch the encoder. ![Press A: the hood's servo goes to the start point, and the Driver Hub shows Position : 0.500](https://crossbotics.com/ftc-helper/docs/images/hub-hood-finder-step-start.svg) 2. Go to one stop until the hood BARELY touches it (a servo hums when it strains). Back off a little, and press **X** (stop A). ![At one stop, press X: the Driver Hub shows Stop A : 0.205](https://crossbotics.com/ftc-helper/docs/images/hub-hood-finder-step-stop-a.svg) 3. Move the hood to the other stop in the same way, and press **B** (stop B). The screen shows `Tunables.Hood: posA = 0.205, posB = 0.648`. That is all you need: the hood then works in servo positions, and the Shot Tuner writes positions into the table. ![At the other stop, press B: the Driver Hub shows Stop B : 0.648 and Tunables.Hood: posA = 0.205, posB = 0.648](https://crossbotics.com/ftc-helper/docs/images/hub-hood-finder-step-stop-b.svg) 4. **Angles (optional).** Measure the hood's angle at each stop, with an angle app on a phone laid on the hood. **Hold LB + D-pad** to type it in BEFORE you press X / B. Then you get `angleA = 0, angleB = 25` too. The finder uses each angle you type for ONE place (a stop or a point), so measure again at the next place. When only one stop has an angle, the finder writes no angles, and the screen says which stop still needs its angle. An angle of 0 counts only when you type it: hold LB and press D-pad up, then D-pad down, so the screen shows `Angle here : 0.0`. ![Hold LB and press the D-pad: the Driver Hub shows Angle here : 25.0](https://crossbotics.com/ftc-helper/docs/images/hub-hood-finder-step-angle.svg) 5. **A linkage** (the angle is not a straight line of the servo position): add points in between. Move there, type in the angle (LB + D-pad), and press **A**. With points and the angles at both stops, you get a `calibration` line INSTEAD of the posA / posB line. The hood reads one or the other, and both together stop INIT. The table's first and last rows are the stops. INIT checks that the angles keep going one way along the hood. The finder shows a point that breaks this as a warning, and writes no table. **Y** undoes the last point. 6. Copy the lines into `Tunables.java`: the robot uses the file, not this screen. Then, for a servo hood, time a stop-to-stop move for `travelSec`. The launcher waits that long before firing (a share of it for a shorter move). ## Fix a mistake - **Saved a wrong point (X, B or A):** press **Y**. It undoes the last point. - **Marked the wrong stop:** move to the right place and press the same button (X or B) again. The new stop replaces the old one. - **Typed a wrong angle:** hold LB and press the D-pad again, before you press X, B or A. After you press, the finder uses the angle: press **Y**, then type the angle and mark the place again. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `Tunables.Hood: posA = 0.205, posB = 0.648` | `Tunables.Hood` | | `angleA = 0, angleB = 25` (optional) | `Tunables.Hood` | | a `calibration` line (a linkage) | `Tunables.Hood`, in place of `posA` / `posB` | | `travelSec` (you time it) | `Tunables.Hood` | ## Done when `posA`, `posB` (or a `calibration` table) and `travelSec` are in `Tunables.Hood`. --- **Next:** [Motor Finder: limits, positions, top speed](https://crossbotics.com/ftc-helper/docs/tuning/05-motor-finder/). **Look it up:** [Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/). --- # Motor Finder: limits, positions, top speed URL: https://crossbotics.com/ftc-helper/docs/tuning/05-motor-finder/ **In Tune and check:** yes, when the robot has a lift or an arm (or there is no Robot.java). **You need:** the robot on a block, the mechanism at its bottom. ## Get to the Motor Finder 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Motor Finder**, then press **A**. ![The Tune and check menu with the arrow on Motor Finder: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-motor-finder-go-menu.svg) 3. The Motor Finder's INIT screen shows. Nothing moves yet. Put the mechanism at its bottom, then press **▶** (start) on the Driver Hub. ![The Motor Finder's INIT screen: Put the mechanism at its BOTTOM before you choose it. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-motor-finder-go-start.svg) 4. Press **D-pad up/down** until the arrow is on your motor's name, then press **A**. The names come from the robot configuration. ![Choose a motor: the arrow on lift, then press A](https://crossbotics.com/ftc-helper/docs/images/hub-motor-finder-go-choose.svg) ## Steps 1. **Put the mechanism at its bottom**, then choose the motor (D-pad, A). Its count starts at 0 there. 2. Move it slowly with the right stick (max power starts at 0.3). Stop a little before the bottom, and press **X**. ![Near the bottom, press X: the Driver Hub shows LOW end (X) : 0](https://crossbotics.com/ftc-helper/docs/images/hub-motor-finder-step-low.svg) 3. Move it up to the top. Stop a little before the top, and press **B**. From now on, the power goes off at those marks. The mechanism coasts a little past them (more at a higher max power), so mark them with some room. ![Near the top, press B: the Driver Hub shows HIGH end (B) : 2580](https://crossbotics.com/ftc-helper/docs/images/hub-motor-finder-step-high.svg) 4. Press **A** at each height you need. A height outside the two marks gets a warning, because the robot stops at min and max and could never get there. **Y** undoes it. ![At each height, press A: the Driver Hub shows Tunables.Lift: min = 0, max = 2580, P1 = 1200](https://crossbotics.com/ftc-helper/docs/images/hub-motor-finder-step-position.svg) 5. Hold **RT** for a speed test: full power up, stopping before the top. The top speed helps you choose a max power and PID gains. ![Hold RT: the Driver Hub shows Top speed : 2310 counts/s](https://crossbotics.com/ftc-helper/docs/images/hub-motor-finder-step-speed.svg) 6. Five files: the line `Tunables.Lift: min = 0, max = 2580, P1 = 1200` becomes `min = 0, max = 2580` and `low = 1200` (your name) in `Tunables.Lift`. When it also says `Robot.java: add .reversed()`, add `.reversed()` to that part in `Robot.java`. An `Arm` reads degrees, not counts: see the [reference](https://crossbotics.com/ftc-helper/docs/modules/finders/#motorfinderopmode). Watch the current (amps). A high number while the part does not move means it is pushing on something. Stop. ## Fix a mistake - **Saved a wrong position (A):** press **Y**. It undoes the last saved position. - **Marked the wrong end (X or B):** move to the right place and press the same button again. The new end replaces the old one. - **Chose the wrong motor:** press **BACK** and choose again. **Put the mechanism at its bottom first**: choosing a motor sets its encoder to 0 where it is now. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `Tunables.Lift: min = 0, max = 2580, P1 = 1200` | `Tunables.Lift`. Rename `P1` to a real name: `low = 1200` | | `Robot.java: add .reversed()` | the part's line in `Robot.java` | ## Done when `min`, `max` and every named height are in `Tunables.java`. --- **Next:** [Flywheel Finder: gains and recovery](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/). **Look it up:** [Lift and Arm: In Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#in-tunablesjava), [MotorFinderOpMode](https://crossbotics.com/ftc-helper/docs/modules/finders/#motorfinderopmode). --- # Flywheel Finder: gains and recovery URL: https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/ **In Tune and check:** yes, when the robot has a launcher (or there is no Robot.java). **You need:** safety glasses, nobody in the line of fire, a charged battery. ## Get to the Flywheel Finder 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Flywheel Finder**, then press **A**. ![The Tune and check menu with the arrow on Flywheel Finder: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-flywheel-finder-go-menu.svg) 3. The Flywheel Finder's INIT screen shows. Nothing moves yet. Put your safety glasses on, then press **▶** (start) on the Driver Hub. ![The Flywheel Finder's INIT screen: Hands away from the wheel. Eye protection on. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-flywheel-finder-go-start.svg) 4. The arrow starts on the flywheel motor: the launcher's motor in Robot.java (from Tune and check), else a name with "fly", "launch" or "shoot" in it. Check the name, then press **A**. Another motor: press **D-pad up/down** first. The names come from the robot configuration. ![Choose the flywheel motor: the arrow on launcher, then press A](https://crossbotics.com/ftc-helper/docs/images/hub-flywheel-finder-go-choose.svg) ## Already have gains in Tunables.java? From Tune and check, when your launcher's part of `Tunables.java` has `kP`, `kI` and `kF`, the finder holds the wheel with **those** gains (and their battery compensation). The `Gains` line shows them: `Gains : Tunables.java (kP 10.00, kI 0.000, kF 14.68, for 13.0 V)`. - Step 1 is not needed: press **B** at once (step 2), set your shot speed, and fine-tune F with **RB** / **LB**. - The `Tunables.Launcher` line keeps your kP, kI and kD, with the new kF. Copy only that line. - After step 1, **Y** switches to the finder's own gains (from the top speed) and back. The F you fine-tuned on each stays. **Why:** F does most of the work, and it fits only the kP and kI it was tuned with. With the finder's own kI, a small F error is hidden while the wheel is held, then shows up in a match with your kI. Tuned with your own gains, F is right for the robot as it is. ## Steps 1. After you choose the motor, let go of A, then hold **A** again: the wheel runs at full power until the speed stops rising. The finder works out the gains from the top speed. From Tune and check, the motor starts in the direction Robot.java gives it: with `.reversed()` on the launcher, the screen shows `Direction : reversed, as in Robot.java`. When the wheel spins the wrong way, let go, press **X** (reverse), and try again. Then the results tell you to add or remove `.reversed()` in Robot.java. **Why the direction matters:** a wheel that spins backward pushes the piece back. The piece jams on the wheel, and the wheel stops when the piece touches it. **`Still speeding up at 5 s`:** full power stops after 5 s, for safety. A heavy wheel (a wheel with added weight) can still speed up then, so its real top speed is higher than the one shown. Extra weight does not lower the top speed much, but it makes the wheel take longer to get there. Because the finder works out F from the top speed, F is then a little high. Check that the wheel turns freely by hand, with no rubbing. Then fine-tune F in step 2 (step 3 below): the error must stay near 0 at your shot speed. ![Let go of A, then hold A: the Driver Hub shows Top speed : 5600 RPM](https://crossbotics.com/ftc-helper/docs/images/hub-flywheel-finder-step-top-speed.svg) 2. Press **B**: the finder holds a speed (60% of the top, or 3000 RPM before step 1). Change it with the D-pad to the speed you shoot at. ![Press B: the Driver Hub shows Target : 3350 RPM and Error : 40 RPM](https://crossbotics.com/ftc-helper/docs/images/hub-flywheel-finder-step-hold.svg) 3. When the measured speed stays below the target at every speed, press **RB** (more F). When it stays above, press **LB**. ![When it stays too slow, press RB: the Driver Hub shows F gain : 12.79 and Error : 5 RPM](https://crossbotics.com/ftc-helper/docs/images/hub-flywheel-finder-step-more-f.svg) 4. Feed one piece with the robot's own feeder, or push it in with a stick. **Never use your fingers**: they would be next to a wheel at full speed. Put safety glasses on. The screen shows the recovery time (on the robot only, because the simulator has no piece to feed). Use it for the launcher's `shotInterval(...)`: make that a little longer than the recovery time. 5. Check that the robot sees each shot (for `stopOnShot`). Set the target to your shot speed with the D-pad. Feed 10 pieces, one at a time. Wait for "Ready: YES" before each. Read two lines: - "Shots seen": the drops of more than 150 RPM (the default `shotDropRpm`). - "Shot drop": every drop, also the ones under 150. It shows the last drop, the smallest drop and how many drops it saw. "Shots seen" shows 10: the default is good. It shows fewer: set `shotDropRpm` in `Tunables.Launcher` to about half the smallest shot drop. Keep it more than `readyBandRpm`. Then fire with no piece in TeleOp: the feed must run its full `feedSec`. The finder always counts with 150, not with your `shotDropRpm`. 6. Five files: copy the `Tunables.Launcher: kP = ..., kI = ..., kD = 0, kF = ..., nominalVolts = ...` line into `Tunables.Launcher` (the section is the motor's name). A slow recovery adds `shotIntervalSec`. `nominalVolts` is the battery voltage at which the finder found the gains. The launcher's battery compensation uses it, so a low battery spins the wheel back up as fast. The compensation is off unless you write `batteryCompensation = true`. The RB/LB F changes are only on the screen: copy the line (with the F you ended on) into `Tunables.java`. ## Fix a mistake - The finder saves no positions, so there is nothing to undo. Each button changes one setting, and you can change it back. **X** again turns the reverse off, **B** again stops the held speed, and **LB** lowers F again after an **RB**. - **Chose the wrong motor, or a bad top-speed test:** press **BACK** and choose the motor again. It starts over, with a new top-speed test. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `Tunables.Launcher: kP = ..., kI = ..., kD = 0, kF = ..., nominalVolts = ...` | `Tunables.Launcher` (the section is the motor's name) | | the recovery time | `shotIntervalSec` in `Tunables.Launcher`: a little longer than the recovery time | | "Shots seen" fewer than the pieces | `shotDropRpm` in `Tunables.Launcher`: about half the smallest "Shot drop" (from the screen) | ## Done when you copied the `Tunables.Launcher` gains line, and the speed holds the target. --- **Next:** [Feed Stop Finder](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-stop-finder/) (a launcher with a feed stop), or [Feed Time Finder](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-time-finder/) (a CR servo or motor feeder with no feed stop, pushing parts or feed wheel). **Look it up:** [Launcher: In Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava). --- # Feed Stop Finder URL: https://crossbotics.com/ftc-helper/docs/tuning/07-feed-stop-finder/ **In Tune and check:** yes, when the launcher has a `.feedStop(...)`. **You need:** the launcher's Robot.java line with `.feedStop(...)`, 5 pieces, and eye protection for the test shots. ## Get to the Feed Stop Finder 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Feed Stop Finder**, then press **A**. ![The Tune and check menu with the arrow on Feed Stop Finder: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-feed-stop-finder-go-menu.svg) 3. The Feed Stop Finder's INIT screen shows. Nothing moves yet. Press **▶** (start) on the Driver Hub. ![The Feed Stop Finder's INIT screen: Nothing moves until you press A. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-feed-stop-finder-go-start.svg) ## Steps A feed stop holds the pieces back, and lets one through at a time. This finder finds both positions, for a launcher with `.feedStop("feed_stop")` in Robot.java. For such a robot, it is in [Tune and check](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#the-tune-and-check-menu). 1. Put a piece behind the feed stop. The wheel stays off. 2. A servo's position is a number from 0 to 1. With the D-pad, pick a start number near where the feed stop sits now (nothing moves yet). **A** moves the servo there. ![Press A: the feed stop goes to the start point, and the Driver Hub shows Position : 0.500](https://crossbotics.com/ftc-helper/docs/images/hub-feed-stop-finder-step-start.svg) 3. D-pad up/down moves it by the step. Left/right makes the step smaller/bigger (0.1, 0.05, 0.01, 0.005, 0.001). The step starts at 0.05, and the screen shows it. 4. Where the stop holds the piece firmly, without straining on the frame, press **X** to save the hold position. ![Where it holds the piece, press X: the Driver Hub shows Hold (X) : 0.150](https://crossbotics.com/ftc-helper/docs/images/hub-feed-stop-finder-step-hold.svg) 5. Move the feed stop with the D-pad until the piece rolls through freely. Press **B** to save the release position. **A** then goes between the two, so you can try them. ![Where the piece rolls through, press B: the Driver Hub shows Release (B) : 0.550 and the line to copy](https://crossbotics.com/ftc-helper/docs/images/hub-feed-stop-finder-step-release.svg) 6. Copy the line it shows, for example `Tunables.Launcher: feedStopHold = 0.150, feedStopRelease = 0.550`. The section is your launcher's: a launcher on `shooter` says `Tunables.Shooter`. ## Find the firing times Two times are in your launcher's section of `Tunables.java`. With both positions saved, the finder finds them too: | Time | What it does | Start value | The finder finds it | | --- | --- | --- | --- | | `feedStopMoveSec` | how long the stop takes to open. The indexer and the pushing parts wait this long before they push | 0.1 s | from the servo's speed in the parts catalog | | `feedStopOpenSec` | the backup time. When the wheel sees no shot, the stop closes after this time | 0.5 s | with test shots | The stop does not stay open for the whole `feedStopOpenSec`. It closes as soon as the wheel sees the shot (the wheel's speed drops). `feedStopOpenSec` is a backup, for a piece that does not reach the wheel. ### The open time The finder works out the open time from the angle between hold and release and the servo's speed from the seller. It adds 25%, because the seller's speed is with no load. For this, Robot.java must name the servo's part. **Where:** `Robot.java`, the launcher's line. ```java title="Robot.java" .feedStop("feed_stop", "gobilda-2000-speed") // the servo's catalog id ``` The screen then shows, for example, `Opens in : about 0.25 s (gobilda-2000-speed, +25%)`. **Why it matters:** a goBILDA torque servo that turns from 0.150 to 0.550 needs about 0.6 s. That is much more than the 0.1 s start value. With 0.1 s, the indexer pushes the piece against a stop that is still half closed. A servo that is not in the catalog: measure the open time with a video (below). ### The backup time: test shots 1. Wear eye protection, and keep everybody out of the line of fire. Put a piece behind the stop, where it sits in a match. 2. Press **LB**. The wheel spins up to your `speedRpm`. While the wheel is on, the D-pad, A, X and B do nothing, so the positions you saved stay. ![Press LB: the wheel spins up, and the Driver Hub shows Wheel (LB = off) : 2990 / 3000 RPM, ready: RB = test shot](https://crossbotics.com/ftc-helper/docs/images/hub-feed-stop-finder-step-wheel.svg) 3. When the screen says `ready`, press **RB**. The stop opens, and the indexer and the pushing parts run as in a match. The finder measures the time until the wheel sees the shot. 4. Put the next piece behind the stop. Do 5 test shots in all. The screen shows each time. ![After 5 test shots with RB: the Driver Hub shows Test shots : 0.31, 0.28, 0.35, 0.30, 0.29 s and the times line to copy](https://crossbotics.com/ftc-helper/docs/images/hub-feed-stop-finder-step-test.svg) 5. Copy the times line, for example `Tunables.Launcher: feedStopMoveSec = 0.25, feedStopOpenSec = 0.55`. The backup time is the longest test shot plus 0.2 s, because a low battery or a worn piece is slower. 6. Press **LB** to stop the wheel. When you change hold or release after the test shots, the finder clears the old times: do the test shots again. ### When the finder warns - **`No shot seen in 3 s`:** the piece did not reach the wheel. Check the release position (the piece must roll through freely). With `.pushedBy(...)`, try a larger `assistSec`. A heavy wheel that slows by less than 150 RPM gives this warning too, even when the piece fired. In that case, measure the time with a video (below). - **`2 pieces in one opening`:** the next piece got past before the stop closed. Check that the hold position catches the next piece. Pieces that sit tight against each other can slip through together: a gap between them, or a faster servo, helps. ### Check the times in TeleOp To check the times as the robot fires in a match, use the PRACTICE profile ([profiles](https://crossbotics.com/ftc-helper/docs/guides/profiles/)): the debug lines show only there. Fire 5 to 10 pieces, and read: ``` Last feed ended : shot seen ``` `shot seen` for every piece is right. `backup time` means that the stop closed before the wheel saw a shot: do the test shots again, or measure with a video. ### Measure the times with a slow-motion video Use a video only when the finder cannot find a time. This happens with a servo that is not in the catalog, or with a heavy wheel that the finder cannot see slow down. A phone's slow-motion video shows what happens too fast for your eyes. 1. Film the feed stop and the wheel from the side, in slow motion. Use 240 frames a second, if the phone can. 2. Fire one piece. 3. Go through the video one frame at a time, and count the frames: - **The open time:** from the frame where the stop starts to move to the frame where it is fully open. - **The piece time:** from the frame where the stop starts to move to the frame where the piece touches the wheel. 4. Change frames to seconds: time = frames ÷ frames a second. For example, 60 frames at 240 frames a second is 0.25 s. 5. Do it 3 times, and use the longest of each time. 6. Set `feedStopMoveSec` to the open time, rounded up to the next 0.05 s. Set `feedStopOpenSec` to the piece time plus 0.2 s. **Why extra time:** a low battery makes the parts slower, and a worn piece can roll slower. ## Fix a mistake - **Saved the wrong hold or release:** move to the right place and press the same button (X or B) again. The new position replaces the old one. While the wheel is on, press **LB** first to stop it. - **A bad test shot** (no piece, or a piece that was not loaded right): stop the wheel with **LB**, then press **X**. It saves the same hold again and clears all the test shots. Then do the 5 test shots again. - A test shot that saw no shot does not count. Its time is not used. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `Tunables.Launcher: feedStopHold = 0.150, feedStopRelease = 0.550` | your launcher's section (a launcher on `shooter`: `Tunables.Shooter`) | | `Tunables.Launcher: feedStopMoveSec = 0.25, feedStopOpenSec = 0.55` | the same section | ## Done when - `feedStopHold`, `feedStopRelease`, `feedStopMoveSec` and `feedStopOpenSec` are in `Tunables.java`. - In 5 test shots, the wheel saw every shot, and no shot let 2 pieces through. --- **Next:** [Drive Tuner: wheel size and strafe correction](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/). **Look it up:** [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/). --- # Feed Time Finder URL: https://crossbotics.com/ftc-helper/docs/tuning/07-feed-time-finder/ **In Tune and check:** yes, when the launcher's feeder is a CR servo or a motor, with no feed stop, no pushing parts (`.pushedBy(...)`) and no feed wheel. **You need:** the launcher and its feeder in Robot.java, 5 pieces or more, and eye protection for the test shots. A robot with a feed stop uses the [Feed Stop Finder](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-stop-finder/) instead. Its test shots time the same thing, for `feedStopOpenSec`. A robot with pushing parts or a feed wheel gets neither finder for `feedSec`: tune it by hand ([fix it by what you see](https://crossbotics.com/ftc-helper/docs/tuning/17-fix-by-symptom/)). ## Why test shots A CR servo or motor feeder runs for `feedSec` per piece, then stops. The time a piece needs changes with where it sits. A piece near the wheel gets there fast. A piece far back takes longer. `feedSec` must be long enough for the piece that starts farthest back. One test shot does not tell you that. Fire several, from every place a piece can sit in a match. The finder keeps each time and gives `feedSec` from the longest. ## Get to the Feed Time Finder 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Feed Time Finder**, then press **A**. 3. The Feed Time Finder's INIT screen shows. Nothing moves yet. Press **▶** (start) on the Driver Hub. ## Steps 1. Wear eye protection, and keep everybody out of the line of fire. 2. Press **LB**. The wheel spins up to your `speedRpm`. 3. Load one piece where a piece sits in a match. 4. When the screen says `ready`, press **RB**. The feeder runs at its `power`. The finder times the piece from the start of the feed to the shot (the wheel's speed drops). The feeder stops at the shot. 5. Do it 5 times or more. Load each piece in a different place, and the farthest back place more than once. The screen shows the times: ``` Test shots : 0.31, 0.42, 0.28, 0.45, 0.33 s (5) Shortest / average / longest : 0.28 / 0.36 / 0.45 s feedSec : 0.55 s (the longest + 0.1); now 0.40 ``` 6. Copy the line it shows, for example `Tunables.Feeder: feedSec = 0.55`. The section is your feeder's. 7. Press **LB** to stop the wheel. **Why the extra 0.1 s:** a low battery and a worn wheel make the feed slower. ## When the finder warns - **`No shot seen in 3 s`:** the piece did not reach the wheel. Check that a piece was loaded, and that the feeder turns the right way (its `power` sign, or `.reversed()` in Robot.java). This test shot does not count. A heavy wheel that slows by less than `shotDropRpm` (150 by default) gives this warning too, even when the piece fired: make `shotDropRpm` smaller. - **`The times differ by ... s`:** a `feedSec` long enough for the slowest piece can push the next piece in too, when it sits close. Set `stopOnShot = true` in the feeder's section. Each feed then stops at the shot, and `feedSec` is only the time limit ([stop on the shot](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/#in-robotjava)). With `stopOnShot = true`, this warning does not show. - **`Test shot stopped part way`:** the wheel went off (LB, help, or STOP) before the shot. That test shot does not count. - **`A piece took almost 3 s`:** `feedSec` cannot be more than 3 s. Check the feeder's `power`, and what slows the piece. ## Fix a mistake - **A bad test shot** (no piece, or two pieces loaded): press **X**. It clears all the times. Then do the test shots again. - A test shot that saw no shot does not count. Its time is not used. **Start over:** press STOP, then INIT, and open the tool again. It starts empty. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java`, not the finder's screen. Take a photo of the screen, and type the line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `Tunables.Feeder: feedSec = 0.55` | your feeder's section (the name in its `.tunables("...")`, or the feeder's own name) | ## Done when - `feedSec` is in `Tunables.java`. - In TeleOp, each press of fire sends one piece, from every place a piece can sit. --- **Next:** [Drive Tuner: wheel size and strafe correction](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/). **Look it up:** [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/), [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/). --- # Drive Tuner: wheel size and strafe correction URL: https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/ **In Tune and check:** yes, when there is a Robot.java. **You need:** a charged battery, tape, 5 ft of clear floor. ## Get to the Drive Tuner 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Drive Tuner**, then press **A**. ![The Tune and check menu with the arrow on Drive Tuner: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-drive-tuner-go-menu.svg) 3. The Drive Tuner's INIT screen shows. Nothing moves yet. Press **▶** (start) on the Driver Hub. ![The Drive Tuner's INIT screen: Tape 48 in long on the floor. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-drive-tuner-go-start.svg) The screen now shows the test list, with the arrow on `Push (by hand)`. Go on with the steps below. ## Steps ![The Drive Tuner floor from above: a tape line marked 0 and 48 in along the robot's left wheels, the push and drive arrow along it, the strafe arrow to the right, and 5 ft of clear floor ahead and to the right (to the left too for the optional Strafe left test)](https://crossbotics.com/ftc-helper/docs/images/finder-drive-tuner.svg) **Set up the floor:** a straight line of tape, marked **0** and **48 in**. Clear 5 ft of floor ahead of the robot and to its right (and to its left, for the optional Strafe left test). **Start each test** with the robot's **left wheels touching the tape** (their outside edge) and the front left wheel's front edge on **0**. **Why the left wheels:** when you push by hand, a wheel edge against a line is easy to keep straight. It is also easy to measure from: forward from 0 to that wheel's front edge, and sideways from the tape to the left wheels. 1. **Start the push test:** with the arrow on `Push (by hand)`, press A. The wheels are now free to roll. ![Press A with the arrow on Push (by hand)](https://crossbotics.com/ftc-helper/docs/images/hub-drive-tuner-step-push-start.svg) 2. **Push and stop:** roll the robot by hand, its left wheels along the tape, until the front left wheel's front edge is on 48 in. Then press B. This gives the wheel size from the encoder counts alone. Every wheel must count up by about the same amount. When one does not, fix its direction or encoder cable first. ![At 48 in, press B: the Driver Hub shows Wheel counts : 2134, 2129, 2140, 2131, about the same for each wheel](https://crossbotics.com/ftc-helper/docs/images/hub-drive-tuner-step-push-end.svg) 3. **The power:** on the test list, D-pad left/right sets the power for the Drive and Strafe tests (`Power : 0.5`; 0.3 to 1.0). Set the power that your autonomous moves use (`.move("...", 24, 0, 0.6)`: 0.6). **Why:** a faster robot slides farther when it stops, so the numbers fit the power you measured them at. When you change the power, the tests must measure right again. For moves of very different lengths, see `Tunables.Drive.slowDownIn` ([tunables](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava)). 4. **Start the drive test:** put the arrow on `Drive forward` and press A. The robot drives 48 in. While it drives, the screen keeps showing the heading and the wheel counts. ![Press A with the arrow on Drive forward, and the Driver Hub shows Power : 0.6](https://crossbotics.com/ftc-helper/docs/images/hub-drive-tuner-step-drive-start.svg) 5. **Measure the drive:** when the robot stops, measure how far it went. Set the real distance with the D-pad, and press A. The tuner uses the new wheel size at once. Run the test again until it measures 48. Wheels slip a little on tiles, so this test has the final word. The tuner does not measure a move that got stuck. ![When it stops, set the distance with the D-pad, then press A: the Driver Hub shows Measured : 47.50 in](https://crossbotics.com/ftc-helper/docs/images/hub-drive-tuner-step-drive-measure.svg) 6. **Strafe test** (mecanum): put the robot back at the start, and press A. It strafes right, away from the tape. Measure from the tape to the left wheels, straight across. The steps are the same as in the Drive test, for `c.strafeCorrection`. There is no push test sideways. When you push a mecanum robot sideways by hand, its wheels' rollers spin, and its encoders count almost nothing. The strafe correction is about the slip of a **powered** strafe, so only the robot strafing by itself can measure it. **Strafe left:** use it only when moves to the left come up short or long while moves to the right are right. Start with the robot's **right** wheels on the tape, and it strafes left. Measure from the tape to the right wheels. The steps are the same, for `Tunables.Drive: strafeCorrectionLeft`. When you do not write it, the left uses `strafeCorrection` too. ![When the Strafe test measures 48 in, press A: the Driver Hub shows Strafe measures 48 in: right, and Tunables.Drive: calibrated = true under Copy into your code](https://crossbotics.com/ftc-helper/docs/images/hub-drive-tuner-step-calibrated.svg) 7. **Turn 90 left** (a check, with nothing to copy): the robot turns 90 degrees left. Put a square against the robot to see it. The screen shows the IMU's heading, and it should say 90. 8. Copy the lines, then switch autonomous on: - five files: `Robot.java: .wheelMm(96.8)` goes in the drive line, after `.wheel(...)` if you used a catalog wheel (the last one wins). `Tunables.Drive: strafeCorrection = 1.180` goes in `Tunables.Drive`. Once the Drive test (and on a mecanum the Strafe test) measures 48 within 0.5 in, the tuner also shows `Tunables.Drive: calibrated = true`: copy that too. - older helpers: the `c.` lines go in `RobotSettings.auto()`, then `c.calibrationConfirmed = true`. ## Fix a mistake - **Typed a wrong distance:** run the same test again. Each run corrects the number in use now, so the next good run fixes a bad one. - **Stop a test that drives:** press **GUIDE** (or hold **START**). The robot stops, and that run is not used. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `Robot.java: .wheelMm(96.8)` | the drive line in `Robot.java`, after `.wheel(...)` (the last one wins) | | `Tunables.Drive: strafeCorrection = 1.180` | `Tunables.Drive` (and `strafeCorrectionLeft`, if you ran Strafe left) | | `Tunables.Drive: calibrated = true` | `Tunables.Drive`. Autonomous moves run only with it | ## Done when the Drive test (and on a mecanum the Strafe test) measures 48 within 0.5 in, and you copied `calibrated = true`. --- **Next:** [Odometry Tuner: directions, offsets and a loop check](https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/). **Look it up:** [Drive: In Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava). --- # Odometry Tuner: directions, offsets and a loop check URL: https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/ **In Tune and check:** yes, when Robot.java has an `odometry(...)` line. **You need:** a 48 in tape strip with a start mark, room to spin. ## Get to the Odometry Tuner 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Odometry Tuner**, then press **A**. ![The Tune and check menu with the arrow on Odometry Tuner: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-odometry-tuner-go-menu.svg) 3. The Odometry Tuner's INIT screen shows. Press **▶** (start) on the Driver Hub. ![The Odometry Tuner's INIT screen: press start on the Driver Hub](https://crossbotics.com/ftc-helper/docs/images/hub-odometry-tuner-go-start.svg) 4. The test list shows. For each test below, press **D-pad up/down** until the arrow is on the test, then press **A** to start it. ![The test list with the arrow on 1 Forward 48 in: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-odometry-tuner-go-choose.svg) ## Steps ![A Pinpoint seen from above: the X pod 84 mm right of the center and the Y pod 168 mm behind it give offsetsMm(-84, -168); the five tests in order](https://crossbotics.com/ftc-helper/docs/images/finder-odometry.svg) The Odometry Tuner is for a robot in five files with an `odometry(...)` line ([odometry](https://crossbotics.com/ftc-helper/docs/modules/odometry/)). It needs your robot, in a small file next to `Robot.java` (the odometry robot's [OdometryTuner.java](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/odometrybot/OdometryTuner.java); the whole file to type: [the odometry module](https://crossbotics.com/ftc-helper/docs/modules/odometry/#the-odometry-tuner)). Put a 48 in strip of tape on the floor, with a mark at its start. In every test, the sticks drive slowly (30%). You can also push the robot by hand. The D-pad chooses, **A** starts, and **B** ends the test. 1. **Forward 48 in:** drive or push the robot 48 in straight forward along the tape, and press B. The screen says "Forward OK" (and how many % off), or "counted BACKWARD". For BACKWARD, add `"x"` to `.reversed(...)` (dead wheels: that pod's port name). The simulator's Pinpoint works the same way. `odometry.reversed = x` in the robot file is a pod wired backward. The code's `.reversed(...)` (and `.offsetsMm(...)`) is what the library tells the Pinpoint. So a robot file that differs from Robot.java shows the same mistakes as a real robot. An OTOS gets `Tunables.Odometry: linearScalar = ...` to copy (multiply it with the one in use). More than 2% off: check the pod type (Pinpoint) or `ticksPerMm(...)` (dead wheels), and the tape. More than 10% off: the screen asks "was it really 48 in?". It is a mistake in the test: measure and run it again. ![At 48 in, press B: the Driver Hub shows Forward OK: 47.6 in for 48 (-0.8% off)](https://crossbotics.com/ftc-helper/docs/images/hub-odometry-tuner-step-forward.svg) 2. **Left 24 in:** drive or push the robot 24 in to its LEFT, and press B. The screen says "Left OK", or "counted RIGHT". For RIGHT, add `"y"` to `.reversed(...)` (dead wheels: the sideways pod's name). Push a tank robot by hand. ![At 24 in to the left, press B: the Driver Hub shows Left OK: 23.8 in for 24](https://crossbotics.com/ftc-helper/docs/images/hub-odometry-tuner-step-left.svg) 3. **Spin 3+ turns:** turn the robot in place at least 3 times with the right stick, and press B. With fewer turns, the screen says how many and asks for more. The tuner measures the turn from the Pinpoint's own heading. For dead wheels and the OTOS, it uses the Control Hub's IMU, so they need `.imu(...)` in `drive(...)`. Without it, the tuner stops at INIT and says so. The tuner shows the offsets as the numbers to change: `Robot.java: in the odometry(...) line, .offsetsMm(-84.2, -167.5)` (three wheels: `.trackWidthIn(..).perpForwardIn(..)`; two: `.parallelLeftIn(..).perpForwardIn(..)`). Change only those numbers: `.reversed(...)` and the pod type stay as you wrote them. With `.podsFromEdgesMm(...)` in the line, write the measured `.offsetsMm(...)` in its place. The tuner cannot measure where an OTOS sits. Measure it from the robot's edges with a tape (`.robotSizeMm(...).mountFromEdgesMm(...)`), and its turn scale [by hand](https://crossbotics.com/ftc-helper/docs/modules/odometry/#otos-turn-scale-by-hand). ![After 3 turns, press B: the Driver Hub shows the line to copy, .offsetsMm(-84.2, -167.5)](https://crossbotics.com/ftc-helper/docs/images/hub-odometry-tuner-step-spin.svg) 4. Copy the numbers into your odometry line, and rebuild. 5. **Loop and back:** start on the mark and drive anywhere, at least 24 in away. A robot that never left the mark proves nothing, and the tuner says so. Come back onto the mark, facing the same way, and press B. Within 1 in and 2 degrees, the screen shows `Tunables.Odometry: checked = true`: set it in `Tunables.java`. Until then, the robot skips autonomous `driveTo` steps. ![Back on the mark, press B: the Driver Hub shows Tunables.Odometry: checked = true](https://crossbotics.com/ftc-helper/docs/images/hub-odometry-tuner-step-loop.svg) ## Fix a mistake - **A bad test** (the robot slipped, or you pressed B at the wrong place): choose the same test and run it again (**A**, then **B**). The new result replaces the old one. - The Forward test does not use a result that is more than 10% off. The screen says so: run it again. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `Robot.java: in the odometry(...) line, .offsetsMm(-84.2, -167.5)` | the odometry line in `Robot.java`. Change only those numbers | | `Tunables.Odometry: linearScalar = ...` (OTOS) | `Tunables.Odometry` (multiply it with the one in use) | | `Tunables.Odometry: checked = true` | `Tunables.Odometry`. Autonomous `driveTo` steps run only with it | ## Done when the Loop test shows `checked = true` and it is in `Tunables.java`. --- **Next:** [Move Tuner: how exactly moves stop and turns end](https://crossbotics.com/ftc-helper/docs/tuning/10-move-tuner/). **Look it up:** [Odometry: In Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/#in-tunablesjava), [Odometry module](https://crossbotics.com/ftc-helper/docs/modules/odometry/). --- # Move Tuner: how exactly moves stop and turns end URL: https://crossbotics.com/ftc-helper/docs/tuning/10-move-tuner/ **In Tune and check:** yes, when there is a Robot.java. **You need:** a charged battery, the Drive Tuner done (`calibrated = true`), clear floor (about 6 ft by 6 ft of tiles; on a game field, see [On a game field](#on-a-game-field)), a tape measure. The Drive Tuner makes a move the right length. The Move Tuner makes it **stop** in the right place. A fast robot slides past the end of a move, and a turn can swing past its heading or stop short of it. Each test drives real autonomous moves, measures them, and changes one number. The tuner uses the new number at once, so you run the test again until it says OK. Every test ends about where it began. ## Get to the Move Tuner 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Move Tuner**, then press **A**. ![The Tune and check menu with the arrow on Move Tuner: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-move-tuner-go-menu.svg) 3. The Move Tuner's INIT screen shows. Nothing moves yet. Press **▶** (start) on the Driver Hub. When the screen says `Run the Drive Tuner first`, do that first ([Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/)). ![The Move Tuner's INIT screen: Clear floor: 5 ft around the robot. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-move-tuner-go-start.svg) 4. The test list shows. For each test below, press **D-pad up/down** until the arrow is on the test, then press **A** to start it. **D-pad left/right** sets the power of the moves and turns (`Power : 0.5`; 0.3 to 1.0). Set the power that your autonomous moves use (`.move("...", 24, 0, 0.6)`: 0.6). **Why:** a faster robot slides farther, so the numbers fit the power you measured them at. ![The test list with the arrow on 1 Creep and Power : 0.5: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-move-tuner-go-choose.svg) ## On a game field Spare tiles off the field are best: the same floor, with nothing in the way. On a game field, the tests fit between the field's parts, because each test ends where it began. Each test needs room on some sides only, and you can put the robot in a new spot before each test: | Test | Clear floor it needs | | --- | --- | | 1 Creep | a few inches ahead, and (mecanum) to the right | | 2 Stops | 24 in ahead of the robot's front edge | | 3 Turns | a circle as wide as the robot's diagonal (an 18 in robot: about 26 in), with the robot in its middle | | 4 Drift | 48 in ahead of the front edge. Mecanum: also 48 in to the right of the right edge | | 5 Move and turn | 24 in to the left of the left edge and 24 in to the right of the right edge, and room to turn | **BIOBUZZ:** only the HIVE frame's two feet are on the floor in the middle of the field. The HIVE is higher than 29 in, so the robot drives under it. Between the frame's feet and each side wall there is a clear strip, about 50 in wide and as long as the field. In that strip: - **Creep, Stops, Turns and Drift:** the robot's front points along the strip (along the side wall). On a mecanum, Drift's 48 in move to the right does not fit. Drift only gives a report, so do it on spare tiles, or skip it. - **Move and turn:** the robot's front points at the side wall, in the middle of the strip. Then its moves to the left and right go along the strip. Keep the robot away from the FLOWERs on the walls, and from the frame's feet. ## Steps Run the tests in this order. Each one uses the numbers that the tests before it found. ![The five tests from above, in order: 1 Creep rolls a few inches forward, then right, and finds moveMinPower. 2 Stops drives 6, 12 and 24 in out and back, and finds slowDownIn. 3 Turns turns left and back, and finds the turn numbers. 4 Drift drives 48 in forward and back, a report only. 5 Move and turn slides 24 in sideways while it turns 90 degrees left, and finds moveTurnScale and moveMaxTurnPower](https://crossbotics.com/ftc-helper/docs/images/move-tuner-tests.svg) 1. **1 Creep** (finds `moveMinPower`): the robot creeps forward, then (mecanum) to the right, with a little more power each step. It stops when the robot rolls. The tuner sets `moveMinPower` to that power x 1.3, for a lower battery. **Why:** each move ends at `moveMinPower`. With too much, the robot arrives fast and slides. With too little, it stalls before the end. ![Press A with the arrow on 1 Creep: the Driver Hub shows moveMinPower now 0.10 and the line to copy](https://crossbotics.com/ftc-helper/docs/images/hub-move-tuner-step-creep.svg) 2. **2 Stops** (finds `slowDownIn`): the robot drives 6, 12 and 24 in, each out and back. Then it tries again with a bigger `slowDownIn` (0, 3, 6, 9, 12) until every move slides 0.5 in or less past its end. The screen shows a line for each try: the worst slide, and how long the 24 in move took. A bigger `slowDownIn` stops better, but every move takes longer, so the tuner keeps the smallest one that is good. ![A 24 in move's power: full power, then down to moveMinPower at the end. With slowDownIn 0 it slows down over the last 2.4 in only, arrives fast and slides past the end. With slowDownIn 6 it slows down over the last 6 in and stops on the end](https://crossbotics.com/ftc-helper/docs/images/move-tuner-slowdown.svg) - `STUCK`: a move stalled before its end. Run Creep first, or clear the path. - `slowDownIn does not help`: every move already ends at `moveMinPower`. Run Creep, then Stops again. ![Press A with the arrow on 2 Stops: the Driver Hub shows a line per slowDownIn tried and OK: slowDownIn 3](https://crossbotics.com/ftc-helper/docs/images/hub-move-tuner-step-stops.svg) 3. **3 Turns** (finds the turn numbers): the robot turns 90, 135 and 45 degrees left, and back each time. The screen shows a line per turn: how far it went past its target, how far off it stopped, and how long it took. Then the tuner changes **one** number: | What the turns do | The tuner changes | | --- | --- | | stop off target (short of it, or past it) and stay there | `turnMinPower` up (0.05, then 0.08, then 0.11), then `turnKp` up | | rock in and out, just outside the tolerance | `turnToleranceDeg` + 0.5 (up to 3) | | swing past the target, or back and forth | `turnKd` up (more brake), or `turnKp` down (less push) | | end on target, but a 90-degree turn takes more than 2 s | `turnKp` up | ![Four turn shapes, heading over time, with the target band: 1 stops off target and stays, turnMinPower up then turnKp up. 2 rocks in and out at the band's edge, turnToleranceDeg up. 3 swings past and back and forth, turnKd up or turnKp down. 4 ends on target but slowly, turnKp up](https://crossbotics.com/ftc-helper/docs/images/move-tuner-turns.svg) **Why `turnMinPower` first:** near the target, the push (`turnKp` x the degrees left) is too weak to move the robot at all. More `turnKp` would also make the turn come in faster and swing more. Run Turns again until it says `OK`. ![Press A with the arrow on 3 Turns: the Driver Hub shows a line per turn and turnMinPower now 0.05](https://crossbotics.com/ftc-helper/docs/images/hub-move-tuner-step-turns.svg) 4. **4 Drift** (a report, nothing to copy): the robot drives 48 in forward and back (on a mecanum, also right and left). The screen shows how much the heading changed on each move. A plain move does not correct its heading. More than 2 degrees: check the weight and the wheels, and use `moveWithTurn` on long moves (it holds the heading). ![Press A with the arrow on 4 Drift: the Driver Hub shows the heading change of each 48 in move](https://crossbotics.com/ftc-helper/docs/images/hub-move-tuner-step-drift.svg) 5. **5 Move and turn** (mecanum; finds `moveTurnScale` and `moveMaxTurnPower`): the robot drives 24 in sideways while it turns 90 degrees (`moveWithTurn`), four times. The screen shows how far the heading was still off when the move ended. When the turn lags, the tuner raises `moveTurnScale` (up to 1), then `moveMaxTurnPower`. When the heading swings past its target, it lowers `moveTurnScale`. Run it again until it says `OK`. ![Press A with the arrow on 5 Move and turn: the Driver Hub shows the heading at the end of each move and moveTurnScale now 0.94](https://crossbotics.com/ftc-helper/docs/images/hub-move-tuner-step-move-turn.svg) 6. **Check with a tape:** without odometry, the tuner measures with the wheel counts. A robot can slide with its wheels locked, and the wheel counts do not see that. So check one move with a tape. Use the Drive Tuner's tape line ([Set up the floor](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/#steps)): the front left wheel's front edge on **0**. Run a 24 in forward move in an autonomous, at your autonomous's power. Read where that wheel edge stops. Within 0.5 in of 24: done. Else, find what you see in the table: | The tape shows | Why | Do this | | --- | --- | --- | | short or long by the same share on every move (run a 48 in move too: 1 in short on 24 and 2 in short on 48) | the wheel size number is wrong | run the [Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/) again, then the Move Tuner again | | past the end, by more than the tuner's screen said | the wheels skid when the move stops, and the wheel counts miss it | in `Tunables.Drive`, make `slowDownIn` 3 bigger. Install, then run the move again | | still past the end with `slowDownIn = 12` | the robot is too fast for this floor | use a lower power for the move (0.6 to 0.5), and run the Move Tuner at that power. Clean the tiles and check the wheels | **Why `slowDownIn`, and not the tuner:** the tuner cannot see the skid, so it thinks the stops are good. A bigger `slowDownIn` makes the robot slower at the end, so it skids less. With an `odometry(...)` line, the tuner measures with the odometry, which sees a skid (`Measures with : the odometry`). Then the tuner finds this number by itself. ## Fix a mistake - **A test went wrong** (something was in the way, the robot hit a wall): run the same test again. Each run starts from the numbers in use now. - **Stop a test that drives:** press **GUIDE** (or hold **START**). The robot stops, and that run is not used. A Stops test that you stop goes back to the `slowDownIn` it had before. - **A number got worse:** the screen's `Now using` and `Turns` lines show the numbers in use. Start over to go back to the numbers in `Tunables.java`. **Start over:** press STOP, then INIT, and open the tool again. It starts from the numbers in `Tunables.java`: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java`, not the finder's screen. Take a photo of the screen, and type each line that starts with `Tunables.Drive:` into `Tunables.Drive`. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | What it does | | --- | --- | | `Tunables.Drive: moveMinPower = 0.10` | the slowest power at the end of a move | | `Tunables.Drive: slowDownIn = 3` | every move slows down over at least its last 3 in | | `Tunables.Drive: turnMinPower = 0.05` | the least turn power while the heading is still off | | `Tunables.Drive: turnKp = ...`, `turnKd = ...` | how hard a turn pushes, and how hard it brakes near the end | | `Tunables.Drive: turnToleranceDeg = 1.5` | a turn is done this close to its heading | | `Tunables.Drive: moveTurnScale = ...`, `moveMaxTurnPower = ...` | how hard `moveWithTurn` turns while it moves | Older helpers: the `c.` lines go in `RobotSettings.auto()`. ## Done when Stops, Turns and (on a mecanum) Move and turn say `OK`, the lines are in `Tunables.Drive`, and one 24 in move ends within 0.5 in on the tape. --- **Next:** [Camera lighting](https://crossbotics.com/ftc-helper/docs/tuning/11-camera-lighting/). **Look it up:** [Drive: In Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava), [Move Tuner in the finders reference](https://crossbotics.com/ftc-helper/docs/modules/finders/#movetuneropmode). --- # Camera lighting URL: https://crossbotics.com/ftc-helper/docs/tuning/11-camera-lighting/ **In Tune and check:** no. The camera tests the light by itself, at each INIT. This page sets it up. **You need:** a camera in Robot.java, AprilTags on the field (or printed ones), and for a Limelight, a laptop and the Limelight's USB-C cable. ## Why the light matters Each place has different light: a bright gym, a dim classroom, spotlights at an event. A camera setting that finds the tags at school can miss them at an event. Then the robot cannot aim, and the Shot Tuner gets no distance. So the camera tests a few settings at INIT, and keeps the one that sees the most tags. Do this setup before the Aim Tuner and the Shot Tuner: both need a camera that sees the tags well. | Camera | What it tests | Turn it on in Robot.java | | --- | --- | --- | | Limelight | its **pipelines**: sets of camera settings that you save on the Limelight by number | `.autoPipelines(0, 1, 2)` | | Webcam | exposures: how long each picture collects light | `.autoExposure()` (auto, 3, 6 and 12 ms) | | HuskyLens | nothing: it has no lighting test | - | ## Set it up ### A Limelight 1. Save 3 pipelines on the Limelight: one for your usual light, one for bright light, and one for dim light. The [Limelight lighting guide](https://crossbotics.com/ftc-helper/docs/guides/limelight-lighting/) has the steps, on a laptop. 2. Add `.autoPipelines(0, 1, 2)` to the camera's line. **Where:** `Robot.java`, inside `define()`, the camera's line. ```java title="Robot.java" camera = add(Camera.limelight("limelight").autoPipelines(0, 1, 2).goal("BLUE SCORING", "RED SCORING")); ``` ### A webcam Add `.autoExposure()` to the camera's line. **Where:** `Robot.java`, inside `define()`, the camera's line. ```java title="Robot.java" camera = add(Camera.webcam("Webcam 1").autoExposure()); // or your own list: autoExposure(6, 3, 12) ``` ## Check it 1. Turn the robot so that the camera sees a tag. Press INIT. 2. Read the lighting line on the Driver Station, for example `limelight lighting : pipeline 2 (9 of 10 pictures saw tags)`. When the camera sees no tag, this line is a warning. 3. Look at the camera's picture: [See what the camera sees](https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/#see-what-the-camera-sees). ## At an event 1. In the queue, press INIT with the robot facing a tag. The test stops at ▶ and keeps the best setting so far, so a tag must be in view. 2. The Driver Station shows the result, and two lines for `Tunables.java`. Copy them into the camera's section (`Tunables.Limelight`). Then every match at this venue uses that setting, with no test. **Where:** `Tunables.java`, inside the camera's section. ```java title="Tunables.java" public static double pipeline = 2; public static boolean autoLighting = false; ``` A webcam shows `public static double exposureMs = 6;` in place of `pipeline`. 3. Back home, set `autoLighting = true` again. ## Fix a mistake - **The robot started with no tag in view:** the test kept the setting it had. Turn to a tag and INIT again. In a match, a button can run the test again: `relight()` ([Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/#buttons-to-add)). - **Back home, the camera misses tags:** check that `autoLighting` is `true` again (step 3 above). ## Done when - At INIT, facing a tag, the lighting line shows a setting and no warning. - A Limelight has its 3 pipelines saved. --- **Next:** [Aim Tuner: camera offset](https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/). **Look it up:** [Camera: Venue lighting](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/#venue-lighting), [how the test works](https://crossbotics.com/ftc-helper/docs/modules/vision/#venue-lighting). --- # Aim Tuner: camera offset URL: https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/ **In Tune and check:** no. It has its own file: it needs your camera. **You need:** its own file, safety glasses, pieces, the target 4-6 ft away, and the [camera lighting](https://crossbotics.com/ftc-helper/docs/tuning/11-camera-lighting/) set up. ## Get to the Aim Tuner 1. On the Driver Hub, open the TeleOp list and pick your Aim Tuner file (group "Finders"). Its name is the one in its `@TeleOp(name = ...)` line, like **Aim Tuner**. Press **INIT**. ![The Driver Hub's TeleOp list with Aim Tuner under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-aim-tuner-opmode.svg) 2. The Aim Tuner's INIT screen shows, with the camera's status. Press **▶** (start) on the Driver Hub. ![The Aim Tuner's INIT screen: Camera : STREAMING 30 fps. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-aim-tuner-go-start.svg) ## What the offset is The camera finds the goal, and the turret or the robot turns until the goal is in the camera's center. But the camera is not on the launcher. So when the goal is in the camera's center, the launcher points a little to the side. The **offset** is the angle that fixes this: the robot aims until the goal sits that far from the camera's center. ![Top view: the camera sits left of the launcher, so the goal looks a little right of the camera's center when the launcher points at it. The angle is bigger for a near goal than for a far one. Shots land left: press D-pad right](https://crossbotics.com/ftc-helper/docs/images/aim-camera-offset.svg) The sign of the offset depends on where the camera sits: ![Three top views: a camera left of the launcher gives a negative offset, a camera right of it gives a positive offset, and a camera on the launcher's line gives 0](https://crossbotics.com/ftc-helper/docs/images/aim-offset-examples.svg) The Aim Tuner finds this angle by test shots. It does not change how fast or how smoothly the robot turns. For the whole robot, `turnKp` and `turnKd` in `Tunables.Aim` set that ([Fix it by what you see](https://crossbotics.com/ftc-helper/docs/tuning/17-fix-by-symptom/)). ## See what the camera sees Before you tune, check the camera's picture. The goal's tag must be in the picture, sharp, and not too dark or too bright. - **A webcam:** the Driver Hub can show its picture. 1. Use the PRACTICE profile ([profiles](https://crossbotics.com/ftc-helper/docs/guides/profiles/)). In COMPETITION the live view is off, because it slows the robot. 2. Press INIT. Do not press ▶ yet. 3. On the Driver Hub, open the menu (the three dots, top right) and choose **Camera Stream**. Tap the picture to get a new one. 4. Close it, then press ▶. A webcam in Robot.java does this by itself. In an Aim Tuner file of your own with the older helpers, add `.liveView(true)` to the webcam. - **A Limelight:** it sends no picture to the Driver Hub. Leave it where it is on the robot, and plug its USB-C cable into a laptop instead of the Control Hub. Open http://limelight.local:5801: the page shows the live picture, with the tags it finds marked. Plug it back into the Control Hub after. ([Limelight lighting](https://crossbotics.com/ftc-helper/docs/guides/limelight-lighting/) has more.) - **No picture? Use the numbers.** While the tuner runs, the screen shows `Bearing : ... deg (left = +)` when the camera sees the goal, and `No target in view.` when it does not. Turn the robot a little to the left: the bearing must go down. ## Steps **Before you start:** the Aim Tuner uses the older helpers' pieces, not `robot()`. It needs your `createCamera()`, and `createTurret()` or `robotConfig()` (to aim by turning the robot), and `createLauncher()` for test shots ([reference](https://crossbotics.com/ftc-helper/docs/modules/finders/#aimtuneropmode)). For a robot in five files, `robotConfig()` is `return new Robot().robotConfig();`. The Characterizer is the same: it needs `robotConfig()`. 1. Park the robot 4-6 ft from the target, facing it. For a turret with a home switch, press **X** first. 2. Hold **A**, and the robot aims. ![Hold A: the Driver Hub shows Still to turn : 0.1 deg](https://crossbotics.com/ftc-helper/docs/images/hub-aim-tuner-step-aim.svg) 3. Still holding **A**, shoot (**RB**). LB stops the flywheel. ![Still holding A, press RB when the Driver Hub shows Launcher : ready](https://crossbotics.com/ftc-helper/docs/images/hub-aim-tuner-step-shoot.svg) 4. When shots go LEFT of the middle, press D-pad RIGHT (aim more to the right). When shots go right, press LEFT. ![Shots go right, so press D-pad left: the Driver Hub shows Offset : -1.5 deg and Tunables.Aim: cameraOffset = -1.5](https://crossbotics.com/ftc-helper/docs/images/hub-aim-tuner-step-offset.svg) 5. Repeat until shots go in the middle, at two or three distances. Copy the offset line (five files, with a turret: `Tunables.Turret: cameraOffset = -1.5`; aiming by turning the whole robot: `Tunables.Aim: cameraOffset = -1.5`). When the offset that works changes with distance, the camera is off to the side of the launcher. Move the camera onto the launcher's line (or as close as you can), or tune at the distance you shoot from most. ## Fix a mistake - **Pressed the D-pad the wrong way:** press it the other way. Each press changes the offset by 0.5 degrees (left and right) or 2 degrees (up and down), so the opposite press undoes it. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `Tunables.Turret: cameraOffset = -1.5` (a turret) | `Tunables.Turret` | | `Tunables.Aim: cameraOffset = -1.5` (the whole robot aims) | `Tunables.Aim` | ## Done when shots go in the middle at two or three distances, and you copied the `cameraOffset` line. --- **Next:** [Shot Tuner: the shot table](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/). **Look it up:** [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/), [AimTunerOpMode](https://crossbotics.com/ftc-helper/docs/modules/finders/#aimtuneropmode). --- # Shot Tuner: the shot table URL: https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/ **In Tune and check:** yes, when the robot has a launcher. **You need:** a charged battery, safety glasses, pieces, the aim tuned. ## Get to the Shot Tuner 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Shot Tuner**, then press **A**. ![The Tune and check menu with the arrow on Shot Tuner: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-shot-tuner-go-menu.svg) 3. The Shot Tuner's INIT screen shows. The flywheel stays off. Choose your alliance: **X** = BLUE, **B** = RED (the `Alliance` line). Only that alliance's goal counts. Point the camera at a tag: the camera's lighting test runs now, as in a match. Wait until its line says it is done, then press **▶** (start) on the Driver Hub. ![The Shot Tuner's INIT screen: The flywheel stays off until you press LB. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-shot-tuner-go-start.svg) ## One table or two A **shot table** is a list of rows: at this distance, this flywheel speed. A bigger or heavier piece needs a different speed. In BIOBUZZ, POLLEN (2.8 in, 25 g) and NECTAR (3.6 in, 41 g) fly differently. So a robot that shoots both needs a table for each. | Your robot shoots | The tables in `Tunables.Launcher` | In a match, the table comes from | | --- | --- | --- | | one kind only (only POLLEN, or only NECTAR) | one: `speedByDistance` | nothing to choose | | both kinds | two: `speedByDistancePollen` and `speedByDistanceNectar` | a piece sensor, or a driver's button (below) | ### One kind only Use the plain `speedByDistance` table. When Robot.java takes the speed from the distance (`.speedFromDistance(...)`), INIT stops without a table, so write one guess row first: **Where:** `Tunables.java`, inside `Tunables.Launcher`. ```java title="Tunables.java" public static double[][] speedByDistance = {{36, 3000}}; // a guess: the Shot Tuner replaces it ``` Load only that kind of piece, and tune. The screen shows no `Table` line. ### Both kinds 1. **Before you tune, write both tables, with one row each.** The tuner shows only the tables that have a row. A guess is fine: the tuner replaces the rows. **Where:** `Tunables.java`, inside `Tunables.Launcher`. ```java title="Tunables.java" public static double[][] speedByDistancePollen = {{36, 3000}}; // a guess: the Shot Tuner replaces it public static double[][] speedByDistanceNectar = {{36, 3200}}; // a guess: the Shot Tuner replaces it ``` 2. **Tune one table at a time, with only that piece loaded.** Pick POLLEN (step 1 below), load only POLLEN, and do every spot. Then pick NECTAR, load only NECTAR, and do every spot again. A NECTAR shot marked in the POLLEN table makes both tables wrong. 3. **Check the `Table` line before you press X.** X saves the point in the table that the screen shows. `Points: POLLEN 4, NECTAR 0` says how many points each table has. 4. **Copy one line for each table** (step 7 below). 5. **Tell the launcher which piece it holds, in a match.** In `Robot.java`, on the launcher's line: - **A piece sensor (best):** `.tableFrom(pieces.nextKind())` picks the table for the next piece, by itself. Both NECTAR colors use one table: add `.tableFor("nectar", "RED_NECTAR", "BLUE_NECTAR")` ([Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/); find the sensor's colors with the [Piece Tuner](https://crossbotics.com/ftc-helper/docs/tuning/14-piece-tuner/)). A robot that holds both kinds at once needs this. - **No sensor:** a driver's button picks the next table: `robot.launcher.tableOn(g2.dpadRight);` in `Controls.java`. The Driver Station shows `Shot table: POLLEN, 48 in (camera)`, so the driver sees which one is in use. - At the start, the launcher uses `.startTable("pollen")`, or NECTAR when you write none. ## It aims and sees like a match A table made from shots that were not aimed, or with another camera setting, does not fit the match. So with your robot in five files and a camera with `goal(...)` in Robot.java, the Shot Tuner uses the robot's own camera and aim, the same code as TeleOp and the autos: - **The camera:** the same camera and settings, and its lighting test in INIT. **Hold Y 0.5 s** to run the test again (aim the camera at a tag first). A short **Y** press still changes what the D-pad changes. - **The goal:** only the goal of the alliance you chose in INIT, read right side up, from fresh pictures. Its distance is the tags' distance, as the launcher reads it in a match. - **The aim:** **RB** turns the whole robot to the goal with TeleOp's aim (`Tunables.Aim`: `toleranceDeg`, the saved `cameraOffset`, the angle aim when `angleAim` is on), then shoots when it is aimed and `Ready`. The `Aim` line shows how far off it is. The robot keeps facing the goal after the shot. Your turn stick still wins. - **No shot** when the camera does not see the goal (an odometry guess does not count here), the robot is not aimed for 2 s, or the flywheel is not `Ready` in 4 s. The screen says why. So the table holds only aimed shots. After each shot the aim lets go: the robot does not turn by itself while you move it to the next spot. A robot whose turret follows the goal: the turret aims in a match, so the tuner shoots where the robot points (point it with the sticks), and the distance is to the first target the camera sees, as before. Its lighting test and alliance choice still run. A camera with no `goal(...)`: the first target with a distance, as before. ## Where the distance comes from The table holds a speed for each **distance** to the goal. The tuner gets the distance in one of three ways. The screen says which one, after the distance: `Distance : 36.2 in (camera, 12 readings)`. | Way | When | You can tune from | | --- | --- | --- | | **camera** | the camera sees the goal | spots where the camera sees the goal | | **odometry** | the camera does not see the goal, and the robot has odometry and a goal point | **any spot on the field**, even with no camera | | **by hand** | neither | spots you measure with a tape | When the camera sees the goal, it wins. The tuner uses the average of the last half second of readings, so one bad picture does not go into the table. ### Tune from any spot with odometry With odometry, the robot knows where it is on the field. It also knows where the goal is, from `Tunables.Aim`. So it can work out the distance from any spot: in front of the goal, from the side, or from far away. Tune from the spots where your drivers shoot in a match. **BIOBUZZ:** the goal is your HIVE's up CELL, near the middle of the field. Straight back from it, you reach the wall after about 4 ft, and the HIVE frame is in the way on one side. So do not test in one line: go out toward your corner. The farthest spot is about 66 in from the goal. ![The BIOBUZZ field from your drivers' wall: the two HIVEs in the middle, the goal on your HIVE, spots 1 to 4 going toward your corner at 30, 42, 54 and 66 in, two side-check spots at 42 in, and the odometry start in the middle](https://crossbotics.com/ftc-helper/docs/images/shot-tuner-test-spots.svg) **Before you start:** 1. **The odometry works.** Robot.java has an `odometry(...)` line, and the [Odometry Tuner](https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/) is done (`Tunables.Odometry: checked = true`). 2. **The goal point is in `Tunables.Aim`:** `goalX` and `goalY`, in inches, for the BLUE goal, seen from your drivers' wall. x counts to the right from the center line, and y counts from the center toward the far wall. Take them from the season's field map ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). The tuner mirrors the goal for RED when the last OpMode you ran chose RED. **Each time you start the tuner:** 1. Put the robot in the **middle of the field**, facing away from your drivers' wall. This is where the odometry starts counting. (In a Shot Tuner file of your own, `startSpotIn()` can give another start spot.) 2. INIT, then **▶**. 3. Check that the screen says `(odometry, ...)` after the distance. Drive straight away from the goal by one field tile (24 in): the distance must grow by about 24 in. 4. Drive with the sticks to your first spot, and tune there (the steps below). Then drive to the next spot. The distance follows the robot. The screen also shows a `bearing`: how far the goal is to the side. Turn the robot with the sticks until the bearing is near 0, so that the robot points at the goal before you shoot. **When the camera also sees the goal,** the screen shows both: `Distance` (from the camera) and `Odometry says` (from the odometry). They should be within a few inches. When they are far apart, the goal point in `Tunables.Aim` is wrong. Or the robot did not start in the middle of the field facing away from you. Fix it before you tune: one table must fit both. **Odometry drifts a little over time,** most after bumps. When the distance looks wrong, press STOP: it saves the points so far in the results file (step 7). Put the robot back in the middle of the field, and INIT again. The new run starts with no points, and its table line has only the new ones. So put the lines of both runs together by hand in `Tunables.java`: one `{distance, speed}` pair per point, nearest first. ## Steps ![Shot Tuner: the robot at the nearest spot, then 1-2 ft further back each time; at each spot shoot 3-5, mark HIT or MISS, and X saves the best speed](https://crossbotics.com/ftc-helper/docs/images/finder-shot-tuner.svg) The Shot Tuner works the way experienced teams tune. At each distance, shoot 3-5 pieces at a speed, and mark each one **HIT** or **MISS**. Try the next speed. Keep the speed with the best **hit ratio** (hits out of shots: 3 in out of 4 beats 2 out of 3). Every button is on **gamepad 1**. 1. **Pick the table** (only with two tables: [One table or two](#one-table-or-two)). Press **Y** until `> Table`. Then **D-pad left / right** picks the table. Load only that kind of piece. ![Press Y, then D-pad: the Driver Hub shows > Table : POLLEN](https://crossbotics.com/ftc-helper/docs/images/hub-shot-tuner-step-table.svg) 2. Park at the nearest distance you will shoot from. The screen shows the distance and where it came from ([Where the distance comes from](#where-the-distance-comes-from)). Press **LB** to start the flywheel (it is off at the start). ![At the nearest spot, press LB: the Driver Hub shows Speed : 2600 RPM, measured 2594, the distance, and Ready : YES](https://crossbotics.com/ftc-helper/docs/images/hub-shot-tuner-step-spin.svg) 3. The speed starts at what your table already gives at this distance (or `Tunables.Launcher.speedRpm`), so you only fine-tune. Shoot 3-5 (**RB** one at a time, or hold **RT**). A robot that aims turns to the goal first ([It aims and sees like a match](#it-aims-and-sees-like-a-match)). ![Press RB: the Driver Hub shows Shots fired : 1, 1 to mark](https://crossbotics.com/ftc-helper/docs/images/hub-shot-tuner-step-shoot.svg) 4. After each shot, press **A** = HIT or **B** = MISS. The marks go to the shots in the order you fired them. Each shot keeps the speed, hood angle and distance it was **fired** with. So when you change the speed or the hood before you mark, the mark does not move. The screen shows `Hits at 2600: 3/4` and every speed tried here (`Tried here: 2500: 1/3, 2600: 3/4 (best)`). Change the speed with the D-pad, and shoot 3-5 again. A short **Y** press steps through what the D-pad changes: SPEED, HOOD with a hood, TABLE with two tables, and DISTANCE. DISTANCE is a distance you type in when neither the camera nor the odometry gives one. 2-3 speeds are usually enough. - **When you pressed the wrong one,** a **left stick click** takes back the last HIT / MISS. That shot waits to be marked again. - **A "shot" with no piece:** the wheel slowed down by itself, so `Shots fired` went up. A **right stick click** drops the last shot that is not marked yet. ![After each shot, press A = HIT or B = MISS: the Driver Hub shows Hits at 2600 : 3/4 and Tried here : 2500: 1/3, 2600: 3/4 (best)](https://crossbotics.com/ftc-helper/docs/images/hub-shot-tuner-step-mark.svg) 5. Press **X** to save. The tuner keeps the speed with the **best hit ratio** at this distance. In a tie, it keeps the one with more shots. You must mark all shots before you save. With no shots marked at all, X only warns. X again within 3 s saves the speed now anyway: a guess, not a tested speed. With a hood, it also saves the hood angle that you fired those shots with. Each point also keeps the flywheel speed **measured** as the pieces were fed. When the flywheel was well under the speed asked for, it **sagged**. The last shot or a low battery slowed it, and it was not back yet. Then the screen warns. Wait for `Ready: YES` between shots and charge the battery, or the table will not match a match. To delete a wrong point, stand there and **hold BACK 1 s**. It is a hold, so that nobody presses it by mistake. ![Press X: the Driver Hub shows Saved 24.2 in -> 2600 RPM (3/4 in) POLLEN](https://crossbotics.com/ftc-helper/docs/images/hub-shot-tuner-step-save.svg) 6. Move 1-2 ft further from the goal (drive with the sticks) and do it again. The spots do not need to be in a line. When the wall or a field part is in the way, go out at another angle ([BIOBUZZ](#tune-from-any-spot-with-odometry)). When the distance moves more than 4 in, the hit counts start again by themselves. The tuner also drops the unmarked shots fired at the old spot. `Points: POLLEN 3, NECTAR 0 (4-6 per table)` says how far you are: 4-6 points per table cover the field. Then go to the next table (step 1). 7. **Copy the tables into `Tunables.java`**: the robot uses the file, not the tuner's screen. There is one line per table, like `public static double[][] speedByDistancePollen = {{24, 2600}, {48, 3100}}; // in Tunables.Launcher` (with a hood: `{{24, 2600, 4}, {48, 3100, 12.5}}`, where the third number is the hood). It replaces the line with the same name in `Tunables.Launcher`. When you press STOP, the tuner also saves the lines on the Control Hub (`/sdcard/FIRST/ftc-helper/finder-results.txt`). Older helpers: the `new ShotTable()` lines go into your Robot class (each with a comment like `// 4/5 in, measured 2531 RPM`). Between the points, the launcher **blends** the speed: halfway between two points, it uses the speed halfway between theirs. Outside them, it uses the nearest point. With `robot()`, the Shot Tuner uses your robot's launcher, camera and drive. A robot with whole-robot aim turns to the goal before each shot. A turret stays still, and its "fire only when aimed" checks are off: point the robot at the goal with the sticks. **With a hood** (`.hood(...)` in Robot.java, or the older helpers' `.hood(servo)`), **Y** also chooses HOOD. The D-pad then steps the hood by a fifth / a fiftieth of its range: 5 / 0.5 deg for a 0-25 deg hood. The hood starts at the table's hood for this distance, like the speed. Each speed and hood angle is its own try in the hit counts (`Tried here: 2550 @ hood 10: 3/4 (best), 2550 @ hood 12.5: 1/3`). X saves the hood angle that you fired the winning shots with. A weak battery changes how far the shots go, so charge the battery before you tune speeds. The screen shows the battery and warns below 12.5 V. The tuner does not use the launcher's speed trim (the D-pad in a match), so the table holds the real speeds. ## Fix a mistake - **Marked HIT when it was a MISS (or the other way):** click the **left stick**. It undoes the last mark, and that shot waits to be marked again. - **A shot counted that did not happen:** click the **right stick**. It drops the newest shot that is not marked yet. - **Saved a wrong speed at this spot (X):** find the right speed, and press **X** again at the same spot. The new point replaces the old one. - **Delete the point at this spot:** hold **BACK** for 1 second. - **Saved a point in the wrong table:** pick that table (**Y**, then the D-pad), stand at the same spot, and hold **BACK** for 1 second. Then pick the right table and tune the spot again. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `public static double[][] speedByDistance = {{30, 2600}, {42, 2850}, ...};` | one kind only: `Tunables.Launcher`, in place of the line with the same name | | `public static double[][] speedByDistancePollen = {{30, 2600}, {42, 2850}, ...};` and the same for `Nectar` | both kinds: `Tunables.Launcher`, in place of the lines with the same names. One line per table | ## Done when - each table has 4-6 points, copied into `Tunables.Launcher`. - with both kinds: the launcher picks the right table in a match (a piece sensor, or a driver's button). --- **Next:** [Piece Tuner: what each sensor sees](https://crossbotics.com/ftc-helper/docs/tuning/14-piece-tuner/). **Look it up:** [Launcher: In Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava). --- # Piece Tuner: what each sensor sees URL: https://crossbotics.com/ftc-helper/docs/tuning/14-piece-tuner/ **In Tune and check:** yes, when the robot has a piece sensor. **You need:** one piece of each kind. ## Get to the Piece Tuner 1. On the Driver Hub, open the TeleOp list and pick **Tune and check** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Tune and check under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-tune-and-check-opmode.svg) 2. The menu shows. Press **D-pad down** until the arrow (`>`) is on **Piece Tuner**, then press **A**. ![The Tune and check menu with the arrow on Piece Tuner: press D-pad, then A](https://crossbotics.com/ftc-helper/docs/images/hub-piece-tuner-go-menu.svg) 3. The Piece Tuner's INIT screen shows. Nothing moves. Press **▶** (start) on the Driver Hub. ![The Piece Tuner's INIT screen: 2 sensor(s). Nothing moves. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-piece-tuner-go-start.svg) ## Steps The Piece Tuner is for a robot with a [`Pieces` or `PieceSensor`](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/) line. Its file names your robot, like the Odometry Tuner (the cookbook's [piece-tuner recipe](https://crossbotics.com/ftc-helper/docs/cookbook/05-game-pieces/#how-do-i-tune-the-piece-sensors)). Nothing moves, so you need no block. 1. Mount the sensor where it will stay. Put a piece at the spot where it sits or passes on the robot. At the intake, that is the spot where the sensor sees it go by. 2. D-pad up/down chooses the sensor. D-pad left/right chooses which kind is in front of it. ![Press D-pad: the Driver Hub shows Sensor 1/2: intake_color and In front of it: < POLLEN >](https://crossbotics.com/ftc-helper/docs/images/hub-piece-tuner-step-choose.svg) 3. Hold that kind of piece in its spot. **A** measures (20 readings, about half a second: hold still). ![Hold the piece still and press A: the Driver Hub shows Measured POLLEN and Tunables.IntakeColor: POLLEN = 74](https://crossbotics.com/ftc-helper/docs/images/hub-piece-tuner-step-measure.svg) 4. Do every kind, then EMPTY (nothing there). ![With nothing there and EMPTY chosen, press A: the Driver Hub shows Measured EMPTY and Tunables.IntakeColor: nearMm = 51](https://crossbotics.com/ftc-helper/docs/images/hub-piece-tuner-step-empty.svg) 5. Copy the lines into `Tunables.java` (for example `Tunables.IntakeColor: POLLEN = 74`), rebuild, and run it again. "It sees" should name each piece you hold up, and NONE with nothing there. The tuner warns about two problems. One: two kinds that read nearly the same (a color sensor too far away, a distance sensor that does not look straight across). Two: EMPTY that looks like a piece. For that, aim the sensor at a far wall or a gray or black background. ## Fix a mistake - **Measured the wrong piece:** put the right piece in front of the sensor, choose its kind, and press **A** again. The new measurement replaces the old one. - **Start this sensor over:** press **B**. It forgets every measurement for this sensor. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | `Tunables.IntakeColor: POLLEN = 74` | the sensor's section in `Tunables.java` | ## Done when "It sees" names each piece you hold up, and NONE with nothing there. --- **Next:** [Characterizer: how the robot really moves](https://crossbotics.com/ftc-helper/docs/tuning/15-characterizer/). **Look it up:** [Pieces and PieceSensor](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/). --- # Characterizer: how the robot really moves URL: https://crossbotics.com/ftc-helper/docs/tuning/15-characterizer/ **In Tune and check:** no. It has its own file: it needs your lifts. **You need:** its own file, a charged battery, 5 ft of clear floor. ## Get to the Characterizer 1. On the Driver Hub, open the TeleOp list and pick **Characterizer** (group "Finders"). Press **INIT**. ![The Driver Hub's TeleOp list with Characterizer under Finders, then press INIT](https://crossbotics.com/ftc-helper/docs/images/hub-characterizer-go-opmode.svg) 2. The Characterizer's INIT screen shows. Nothing moves yet. Clear the floor, then press **▶** (start) on the Driver Hub. ![The Characterizer's INIT screen: Drive test: about 5 ft clear in front and behind. Press start](https://crossbotics.com/ftc-helper/docs/images/hub-characterizer-go-start.svg) ## Steps Run the **Characterizer** last, when the robot drives and its lifts work. It measures how each motor behaves: the power to start moving, the power per speed, how fast it speeds up, and for a lift the power that holds it against gravity. You use these numbers in two places: for feedforward in your code (see [Feedforward](https://crossbotics.com/ftc-helper/docs/modules/control/#feedforward)), and as real numbers for the [simulator](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/#6-real-speeds-optional). 1. In `Characterizer.java`, list your lifts/arms with soft limits a little inside the hard stops (counts from the bottom), and your flywheels. 2. Drive test: about 5 ft clear in front and behind, on tiles. Turn test: room to turn. 3. Lifts start at the BOTTOM. An arm's high limit stays below straight up. 4. The D-pad chooses a test, and **A** runs it. ![Press D-pad, then A: the arrow on Drive (forward and back)](https://crossbotics.com/ftc-helper/docs/images/hub-characterizer-step-choose.svg) 5. **B** stops the test now. The tool stops by itself when something turns the wrong way, goes past a limit, or pushes without moving. ![While a test runs, the screen shows Drive (forward and back): ramp + (B = stop). To stop it now, press B](https://crossbotics.com/ftc-helper/docs/images/hub-characterizer-step-stop.svg) 6. Run each test 2-3 times on a charged battery. ![Press A to run it again: the Driver Hub shows Drive (forward and back): done. Fit r2 0.981 (good)](https://crossbotics.com/ftc-helper/docs/images/hub-characterizer-step-again.svg) Details: [finders module](https://crossbotics.com/ftc-helper/docs/modules/finders/#characterizeropmode). ## Fix a mistake - **Stop a test:** press **B** (or **GUIDE**). The robot stops, and that test gives no numbers. - **A bad test** (the robot hit something, or the lift was not at the bottom): run the same test again with **A**. Its new lines replace the old ones. **Start over:** press STOP, then INIT, and open the tool again. It starts empty: nothing carries over. The lines saved at STOP stay in the results file, the newest at the end. ## Put the numbers in your code The robot uses `Tunables.java` and `Robot.java`, not the finder's screen. Take a photo of the screen, and type each line into the file. Or copy it from the [results file](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#get-the-results-file-on-the-laptop): | The finder shows | Put it in | | --- | --- | | the feedforward numbers | your code ([Feedforward](https://crossbotics.com/ftc-helper/docs/modules/control/#feedforward)) | | the motor numbers | the simulator's robot file ([real numbers](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/#6-real-speeds-optional)) | ## Done when each test ran 2-3 times and the numbers agree. --- **Next:** [Live tuning: change numbers while the robot runs](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/). **Look it up:** [CharacterizerOpMode](https://crossbotics.com/ftc-helper/docs/modules/finders/#characterizeropmode). --- # Live tuning: change numbers while the robot runs URL: https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/ **You need:** a robot whose parts work, and the PRACTICE [profile](https://crossbotics.com/ftc-helper/docs/guides/profiles/) (the menu stays closed in COMPETITION). The finders FIND a number the first time. This menu adjusts numbers you already have: a PID gain, a position, a speed. Building and installing again for each small change is slow. The menu changes the number at once.
flowchart LR
    B["PRACTICE profile<br/>run the TeleOp"] --> C["Open the menu<br/>(hold GUIDE 1 s)"]
    C --> D["change, watch, repeat"]
    D --> E["A = save on the hub"]
    E --> F["COPY the numbers<br/>into Tunables.java"]
## What is in the menu With the robot in five files, you set up nothing. Every part's numbers are in the menu already, and so is every number in your own sections of `Tunables.java` (a section no part reads). Limits (`min`, `max`) are never in the menu, so tuning can never drive a part past a hard stop. Each part's reference page says, for each number, whether the menu has it ([the "In tuning menu" column](https://crossbotics.com/ftc-helper/docs/reference/tunables/#the-in-tuning-menu-column)). ## Open it and change a number **Where:** the Driver Hub, in your TeleOp, after ▶ (start on the Driver Hub). Hold **GUIDE** for 1 s. (A tap of GUIDE shows the button map.) While the menu is open, gamepad 1's buttons and sticks do not drive the robot. Gamepad 2 keeps working. | Button | Does | | --- | --- | | GUIDE, held 1 s | open / close. A tap shows the button map | | D-pad up / down | choose | | D-pad right / left | +/- one step (hold a bumper: x10) | | A | save all on the hub | | X | the chosen one back to the code value | | Y | ALL back to the code values, and deletes the saved values | | B | the changed values as lines to copy into `Tunables.java` (also in the robot log, tag `ftc-helper`). B again: the list | Changed values show the code value next to them: `Lift/kP = 0.0050 (code 0.004)`. ## Copy the numbers back **The code is the record.** A value saved only on the hub is lost with a new Control Hub. Teammates cannot see it, and you can forget it at an event. 1. Press **B** in the menu. It shows the changed values as lines to copy, for example `Lift: kP = 0.0050`. The lines are in the robot log too (tag `ftc-helper`). 2. Put each value in its section in `Tunables.java`. 3. Press **Y** to put every value back to the code values and delete the saved values. The next INIT lists every value you did not copy yet, under "Tuned on this robot (copy into Tunables.java)". A save cannot leave a half-written file: after a power cut, the hub has either the old values or the new ones. ## The battery Numbers that set a power (a hold power, a drive gain) are right only for about the battery you tuned them on. Tuned on a low battery, they are too strong on a charged one. So the menu shows the battery's voltage, and warns below 12.5 V. Each change notes the battery: the copy lines say `Lift: kF = 0.06 // tuned at 12.7 V`. Copy that note into `Tunables.java` too. Tune on a charged battery (12.5 V or more). ## Older programs: add the menu yourself A TeleOp in five files has the menu already. Your own TeleOp (`LinearOpMode`, `EasyTeleOp`) needs two things. **Make numbers tunable.** On mechanisms, add `.tunable(...)`: ```java PositionMotor lift = PositionMotor.create(hardwareMap, "lift") .pid(0.004, 0, 0.0002, 0.05) .position("DOWN", 0).position("HIGH", 2400) .tunable("Lift"); // "Lift/kP".."Lift/kF", "Lift/DOWN", "Lift/HIGH" PositionServo claw = PositionServo.create(hardwareMap, "claw") .position("OPEN", 0.2).position("CLOSED", 0.75) .tunable("Claw"); // "Claw/OPEN", "Claw/CLOSED" ``` For any other number, make a `Tunable`. `static final` makes one `Tunable` for the whole program, made once. The menu still changes its value: ```java // (menu name, value in the code, change per D-pad press), kept between 0.1 and 1.0 static final Tunable SLOW_SPEED = Tunable.number("Drive/slow", 0.35, 0.05).range(0.1, 1.0); ... double speed = slowMode ? SLOW_SPEED.get() : 1.0; // read it EVERY loop ``` For a PID controller you made yourself, call `PidTunables.of("Arm", kP, kI, kD, kF).applyTo(pid)` every loop. **Add the menu to the TeleOp.** The menu uses gamepad 1's D-pad, A, X, Y and bumpers. Without a pause, pressing Y in the menu ("reset all") would ALSO do whatever Y does for the driver. So give the menu key its own small button list. Pause the driver's gamepad-1 buttons (and sticks) while the menu is open: ```java TuningMenu tuning = new TuningMenu(gamepad1); ControllerBindings menuKey = new ControllerBindings().bindPress(Pad.G1, Btn.GUIDE, tuning::toggle); // tuning::toggle = run toggle() on press ControllerBindings driver = new ControllerBindings()...; // gamepad 1 buttons ControllerBindings operator = new ControllerBindings()...; // gamepad 2 buttons (keep working) boolean menuWasOpen = false; // was the menu open last loop? // loop: menuKey.update(gamepad1, gamepad2); operator.update(gamepad1, gamepad2); tuning.update(); // the menu reads gamepad 1 (only while open) if (tuning.isOpen()) { menuWasOpen = true; tuning.addTelemetry(t); // and ignore gamepad 1's sticks } else { if (menuWasOpen) driver.ignoreHeldButtons(gamepad1, gamepad2); // a button held from the menu does not fire menuWasOpen = false; driver.update(gamepad1, gamepad2); } ``` The starter kit's `MainTeleOp` already has this code. ## FTC Dashboard (practice only) > **Not at events (2026-27 rule R704.D):** the game manual bans "additional logging/streaming > services, such as those hosted by third party plugins and tools such as FTC Dashboard, FTControl > Panels, and others". Only the Driver Station app may stream telemetry. Use these tools at home and > in practice only. **Take them out of the robot project before an event**: remove or comment out > their Gradle lines, then build and install again. The library's own tuning menu works through the > Driver Station, so the rule allows it. [FTC Dashboard](https://acmerobotics.github.io/ftc-dashboard/) shows graphs. It also lets you change `public static` fields (settings that belong to the class, not to one object) from a laptop browser. Teams used it in the 2025-26 season. You add it in the robot project, not in this library. Add its Maven repository and dependency (where to download it, and its name and version) to `build.dependencies.gradle`. Then put `@Config` on a class with `public static` fields. It works alongside the tuning menu. Use the one that fits the job: Dashboard for graphs, and the menu at the field without a laptop. ## Done when - The menu opens in PRACTICE, and a change shows on the robot. - Every value you keep is in `Tunables.java`, and INIT lists no "Tuned on this robot" lines. --- **Next:** [Fix it by what you see](https://crossbotics.com/ftc-helper/docs/tuning/17-fix-by-symptom/). **Look it up:** [Tunable](https://crossbotics.com/ftc-helper/docs/modules/tuning/), [Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/tunables/). --- # Fix it by what you see URL: https://crossbotics.com/ftc-helper/docs/tuning/17-fix-by-symptom/ **You need:** the finders done for the part ([the tuning order](https://crossbotics.com/ftc-helper/docs/tuning/)). Find what you see in the first column. Change the setting in the middle column, in the direction it says. Change one number at a time, and test after each change. The [tuning menu](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/) changes most of them while the robot runs. Then copy the good value back into `Tunables.java`. When the last column names a finder, run that finder again: a guess is worse than a measurement. | What you see or want | Setting | Which way | | --- | --- | --- | | **Driving** | - | - | | The robot is too fast for the drivers | [`Drive.maxPower`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | less | | A brand-new driver needs a slower robot for a day | [`Drive.practiceMaxPower`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | less, then back to `DEFAULT` | | Fine moves with the slow trigger are too slow or too jumpy | [`Drive.slowSpeed`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | more / less | | Double taps are missed, or single taps wait too long | [`Buttons.tapGapSec`](https://crossbotics.com/ftc-helper/docs/reference/controls/#buttons-in-tunablesjava) | more / less | | **Autonomous moves** | - | - | | Autonomous does not run ("AUTONOMOUS IS OFF") | [`Drive.calibrated`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | `true`, after the Drive Tuner | | Sideways moves are short or long (mecanum) | [`Drive.strafeCorrection`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | Drive Tuner | | Turns stop a few degrees off target | [`Drive.turnMinPower`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava), then [`Drive.turnKp`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | Move Tuner (Turns), or more | | Turns wobble or overshoot | [`Drive.turnKp`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) / [`Drive.turnKd`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | Move Tuner (Turns), or less / more | | Turns rock near the end and take long to finish | [`Drive.turnToleranceDeg`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | Move Tuner (Turns), or more | | The robot stops just before the end of a move | [`Drive.moveMinPower`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | Move Tuner (Creep), or more | | Moves slide past the end | [`Drive.slowDownIn`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | Move Tuner (Stops), or more (try 6) | | `moveWithTurn` ends its move before the turn is done | [`Drive.moveTurnScale`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava), then [`Drive.moveMaxTurnPower`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | Move Tuner (Move and turn), or more | | Path steps do not run on the real robot | [`Odometry.checked`](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/#in-tunablesjava) | `true`, after the Odometry Tuner | | The odometry's distances are off (OTOS) | [`Odometry.linearScalar`](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/#in-tunablesjava) | Odometry Tuner | | **Intake** | - | - | | Pieces are thrown or jam on the way in | [`Intake.inPower`](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/#in-tunablesjava) | less | | Pieces do not come out | [`Intake.outPower`](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/#in-tunablesjava) | more | | **Lift, arm, servos** | - | - | | A lift or arm is slow to arrive, or shakes | [`kP`](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#in-tunablesjava) | more / less | | A lift sags | [`kF`](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#in-tunablesjava) | more | | A lift or arm slams into its ends | [`slowZone`](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#in-tunablesjava) | more | | A claw does not open or close far enough | [positions](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#in-tunablesjava) | Servo Finder | | Actions go on before a servo arrives | [`travelSec`](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#in-tunablesjava) | more | | **Launcher** | - | - | | Shots land short or long | [`speedRpm`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) (or the shot table) | Shot Tuner, or more / less | | The flywheel is slow to reach speed, or its speed swings | [`kP`, `kF`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | Flywheel Finder | | The flywheel suddenly speeds up now and then | [`kD`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | 0 (the Flywheel Finder's line has `kD = 0`: copy each number to its own name) | | In the Flywheel Finder, the wheel stops when a piece touches it | the direction | `Direction` must say "as in Robot.java"; else press X ([why](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/#steps)) | | It waits too long before it fires | [`readyBandRpm`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | more | | With the speed from the camera, it waits to fire and the `Shot distance` line wobbles | [`distanceSmoothSec`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | more (and check the shot table for a steep part) | | Shots land at different distances | [`readyBandRpm`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | less | | The second of two quick shots lands short | [`shotIntervalSec`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | more | | The first shot takes too long to spin up | [`idleRpm`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | more (uses more battery) | | One D-pad press changes the speed too much or too little | [`stepRpm`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | less / more | | **Feeding** | - | - | | It feeds two pieces at once | [`feedSec`](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/#in-tunablesjava) | less | | It feeds two at once, but less `feedSec` feeds none from farther back | [`stopOnShot`](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/#in-tunablesjava) | true | | It feeds no piece | [`feedSec`](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/#in-tunablesjava) | more | | It feeds the near pieces but not the ones far back | [`feedSec`](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-time-finder/) | the Feed Time Finder's number | | The Flywheel Finder's "Shots seen" is less than the pieces fed | [`shotDropRpm`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | less | | With `stopOnShot`, the wheels still run the full `feedSec` after a shot | [`shotDropRpm`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | less | | An eject pushes out two pieces | [`ejectFeedSec`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | set it, then less | | With the speed from the camera, a shot waits while its speed keeps changing | [`lockSpeedWhileFiring`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | true | | With `stopOnShot`, the wheels stop before the piece gets to the flywheel | [`shotDropRpm`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | more | | A pusher comes back before the piece is gone | [`pushSec`](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/#in-tunablesjava) | more | | **Aiming** | - | - | | Aim is slow, or swings past the goal | [`Aim.turnKp`](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#in-tunablesjava) | more / less | | Shots miss although it says "AIMED" | [`Aim.toleranceDeg`](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#in-tunablesjava) | less | | The robot or turret aims a little to one side | [`cameraOffset`](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#in-tunablesjava) | Aim Tuner | | A turret swings too hard | [`Turret.maxPower`](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/#in-tunablesjava) | less | | The wires allow a turret to turn more or less | [`Turret.min`, `max`](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/#in-tunablesjava) | Motor Finder | | **Camera and sensors** | - | - | | The camera pictures are too dark or noisy | [`Camera.gain`](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/#in-tunablesjava) | more / less | | A HuskyLens's turn angles are too big or too small | [`Camera.hfovDeg`](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/#in-tunablesjava) | measure it | | A color sensor sees pieces that are not there | [`nearMm`](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/#in-tunablesjava) | less | | A color sensor mixes up kinds of piece | [`hueTolerance`](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/#in-tunablesjava) | less | When nothing here fits, read [Troubleshooting](https://crossbotics.com/ftc-helper/docs/troubleshooting/): it covers error messages, and problems with wiring and code. ## Done when - The robot does what you want, and each changed number is in `Tunables.java`. --- **Next:** [Tests](https://crossbotics.com/ftc-helper/docs/tests/): check your code and your robot after every change. **Look it up:** [Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/tunables/), [Troubleshooting](https://crossbotics.com/ftc-helper/docs/troubleshooting/). --- # Reference URL: https://crossbotics.com/ftc-helper/docs/reference/ **Look it up.** These pages list every option, number and command. They do not teach. To learn a thing step by step, start at [the five files](https://crossbotics.com/ftc-helper/docs/five-files/). ## The robot file by file | Page | What is on it | | --- | --- | | [Robot.java](https://crossbotics.com/ftc-helper/docs/reference/robot-java/) | what every part shares: `drive(...)`, `add(...)`, optional parts, shapes for the simulator | | [Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/tunables/) | how the numbers work: DEFAULT and MEASURE, units, what INIT checks, the tuning menu | | [Controls.java](https://crossbotics.com/ftc-helper/docs/reference/controls/) | button lines, press types, gamepad names, one or two drivers | | [Steps for autos](https://crossbotics.com/ftc-helper/docs/reference/steps/) | every autonomous step, actions, keep time to park | ## One page per part Each part's page has the same four parts: what you write in `Robot.java`, its numbers in `Tunables.java`, its commands, and the buttons to add. | Part | What it is | | --- | --- | | [Drive](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/) | the wheels: mecanum or tank | | [Odometry](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/) | where the robot is on the field: Pinpoint, OTOS or dead wheels | | [PathFollower](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/) | Pedro paths, and actions along a path | | [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/) | a roller on a motor and/or CR servos: in, out, on at the start | | [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/) | a slide on a motor with named heights and a bottom switch | | [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/) | an arm on a motor with named angles in degrees | | [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/) | a servo that opens and closes | | [Wrist](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/) | a servo with named positions that tilts a claw | | [Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/) | any servo with named positions: deploy, fold, gate | | [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/) | turns to aim, inside its limits | | [Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) | a rule that keeps two parts apart | | [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/) | a flywheel: spin up, fire, speed from distance | | [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/) | feeds one piece at a time | | [Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/) | tilts the shot: its angle from the shot table | | [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/) | a Limelight, webcam or HuskyLens: the alliance's goal | | [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/) | where the goal is, for everything that aims | | [Pieces and PieceSensor](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/) | which piece is where, and how many the robot holds | | [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/) | a colored light for the drivers | ## More - [Parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/): motors and servos, with their numbers. - [Troubleshooting](https://crossbotics.com/ftc-helper/docs/troubleshooting/): what you see, and the fix. - [Search every class and method](https://crossbotics.com/ftc-helper/docs/reference/javadoc/): the Javadoc. --- # Controls.java URL: https://crossbotics.com/ftc-helper/docs/reference/controls/ Every button line, press type and gamepad name; the library's own buttons; one or two drivers. `Controls.java` is the TeleOp ([`EasyTeleOp`](https://crossbotics.com/ftc-helper/docs/modules/teleop/) underneath). Learn it step by step: [Controls.java](https://crossbotics.com/ftc-helper/docs/five-files/03-controls-java/), then [Controls](https://crossbotics.com/ftc-helper/docs/controls/). ## ControlMap ```java @TeleOp(name = "TeleOp") public class Controls extends ControlMap { public static boolean oneDriver = false; // true: everything on gamepad 1 @Override protected void buttons(Robot robot, Pad g1, Pad g2) { g2.y.press(Actions.scoreHigh(robot)).says("score high"); } } ``` - The library's own buttons (driving, pause, menus) are always there. - Every other button, a part's too, is a line in `buttons(...)` ([Buttons to add](#buttons-to-add-every-part)). - A `Pad` has every input by name. Buttons: `a b x y lb rb lt rt back start guide dpadUp dpadDown dpadLeft dpadRight leftStickButton rightStickButton` (a trigger counts as pressed past half way). Sticks: `leftStickX leftStickY rightStickX rightStickY` (up and right +). | In `Controls.java` | What it does | | --- | --- | | `buttons(Robot robot, Pad g1, Pad g2)` | your button lines | | `useStandardButtons()` | override it to return true: each part then adds its usual buttons by itself, as before v0.39.0. The default is false, and INIT names a part's usual button that is still free | | `libraryButtons(LibraryButtons lib, Pad g1, Pad g2)` | moves or frees the library's own buttons ([Moving the library's buttons](#moving-the-librarys-buttons)) | | `robot()`, `oneDriver()` | reads the robot and the one-driver switch | ## Reading a button line Every button line has the same four pieces: ```java // 1. which button 2. how it starts 3. what it does 4. its words g2.rt .hold(robot.intake::holdIn, robot.intake::stop) .says("in (hold)"); ``` 1. **Which button:** `g1` is gamepad 1 (the driver), `g2` is gamepad 2 (the operator), then the button: `rt` is the right trigger. With one driver (`oneDriver = true`), `g2` lines go on gamepad 1. 2. **How it starts**, and 3. **what it does:** | Written | The job runs | | --- | --- | | `.press(job)` | once, when the button goes down | | `.hold(job, stopJob)` | `job` every loop while the button is held, then `stopJob` once when it is let go | | `.toggle(part)` | each press switches the part: on, off, on... A claw: open, closed. A launcher: spinning, stopped. With `.rumble()`: two buzzes = on, one = off | | `.use(job)` | a stick: `job` gets the stick's value (-1 to 1) every loop | | `.heldFor(1.0, job)` | once, after the button is held 1 s (a safe "are you sure?") | | `.tap(job)`, `.doubleTap(job)` | once per quick tap; once on two quick taps. Chain them on one button | `robot.intake::stop` hands over the intake's `stop` command, for the button to run later. `() -> robot.lift.goTo("high")` is a small piece of code with its own words in it (a **lambda**). 4. **`.says("...")`:** the words on the button map. INIT shows the map (every button and its words), and a tap of GUIDE shows it during the match. Without `.says`, the map shows only the press type, like `G2 RT: hold`, so the drivers cannot tell what it does. [Controls](https://crossbotics.com/ftc-helper/docs/controls/) has every press type. ## Buttons to add (every part) A part has **no buttons** until you add its lines to `buttons(...)` in `Controls.java`. Each part's page has its usual lines under **Buttons to add**. Copy them as they are, or change a button or the words. - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **To use another button:** change `g2.rt` to, for example, `g2.lb`. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. You do not change them. A line on a button gamepad 1 already uses (its sticks, the stick clicks, BACK) stops INIT. INIT names the button: give the line a free one. - **On gamepad 1, with two drivers:** write `g1` and a free button, for example `g1.rb`. Gamepad 1's LT is slow mode, so do not use it. If you pick a button the library uses, INIT stops and names it. - Each line has: which button, how it starts (`.hold`, `.toggle`, `.press`...), what it does, and `.says("...")` ([Reading a button line](#reading-a-button-line)). ## Every job on a button | On a button | What it does | | --- | --- | | `press(Runnable)` | once per press | | `press(Action)` | starts it; a second press cancels it | | `release(Runnable)` | once when the driver lets go | | `hold(whileHeld)`, `hold(whileHeld, onRelease)` | every loop while held (and once on release) | | `toggle(Toggleable)` | switches a part on/off (an intake, a launcher, a claw, a mode: a `Toggleable`, anything one button switches on and off) | | `toggle(onEnable, onDisable)` | each press flips between the two | | `tapOrDoubleTap(tap, doubleTap)` | the "no waiting" double-tap: a tap runs `tap` at once; a second tap within 0.35 s (`Pad.DOUBLE_TAP_SEC`) runs `doubleTap` after it (the first tap has already run `tap`: e.g. tap = intake on/off, double-tap = push out). For a tap that must not run on a double-tap, use `tap(...).doubleTap(...)` (the tap waits 0.35 s) | | `tap(job)`, `doubleTap(job)`, `taps(n, job)`, `heldFor(sec, job)` | **gestures**, several on one button: once per quick tap; on the second quick tap; on the n-th (2 to 5); once after held `sec` s. Each also takes an `Action` | | `hold(...)` with other gestures | every loop while held, from 0.3 s on (`Tunables.Buttons.holdSec`), so a quick tap stays a tap | | `tapThenHold(whileHeld)`, `tapThenHold(whileHeld, onRelease)` | a quick tap, then press again and hold: every loop while held | | `with(other, job)` | a pair: hold this button (the shift key, no job of its own) and press `other` (same gamepad) to run `job` once. Pressed alone, `other` keeps its own job | | `rumble()`, `rumble(n)` | feedback: buzzes when the job (or the gesture right before it) runs; a toggle buzzes 2 = on, 1 = off | | `slow()` | one driver (or two after `lib.slow(null)`): on a trigger, drives slower the further it is pulled (down to `slowSpeed`); on a button, slow while held | | `free()` | no job: the button stays free | | `says(words)` | the words on the help page | | `needs(part...)` | the job needs these parts: while one is not on the robot ([`optional()`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet), not in the configuration) the button does nothing and the map says `- off: IntakeDeploy not on the robot`. A part's own buttons and `toggle(part)` know their part already | | on a pad: `g2.rumbleWhen(test)`, `rumbleWhen(test, n)` | feedback from the robot: a buzz each time `test` becomes true | | on a pad: `g2.rumbleWhenAimed()` | buzzes while the aim is close, the closer the stronger ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)) | | on a stick: `use(DoubleConsumer)` | gets its value every loop (small dead zone, gentle curve) | | on a stick: `free()`, `says(words)`, `needs(part...)` | as on a button | | in `buttons(...)`: `show(label, value)` | your own value on the Driver Station, read again every loop, e.g. `show("Lift ticks", robot.lift::position);` or `show("Ready", () -> robot.launcher.isReady());`. The Driver Station hides it while the tuning menu or the button map is open. `value` must not wait. An error in it shows as `error: ...` and does not stop the OpMode | - **While the robot is paused** (BACK), no button or stick job runs, with one exception. A hold's stop job (the second job of `hold(job, stopJob)`) still runs when the driver lets go of the button, or when the pause starts during a gesture's hold. So the part stays stopped. - **A gesture's job runs at once,** unless the button has a longer gesture that starts the same way. Then it waits until it knows which one the driver means (the driver lets go, or `Tunables.Buttons.tapGapSec`, 0.35 s, passes). - Both times are in `Tunables.Buttons` (optional: leave it out for the defaults; [Buttons in Tunables.java](#buttons-in-tunablesjava)) and the tuning menu. Copy a tuned value back into `Tunables.java`. ## Moving the library's buttons Every library job can go on another button, or none (`null`): ```java @Override protected void libraryButtons(LibraryButtons lib, Pad g1, Pad g2) { lib.fieldCentric(g1.x).slow(g1.rt); // Y and LT are free for buttons(...) lib.setPose(g1.dpadDown); // hold D-pad down 1 s: set pose here lib.switchAlliance(g1.start, g1.back); // optional: turn on the alliance switch in TeleOp } ``` | [`LibraryButtons`](https://crossbotics.com/ftc-helper/docs/modules/teleop/#moving-the-librarys-buttons) | Default | | --- | --- | | `pause(key)`, `resetForward(key)` | G1 BACK (a press pauses at once, a tap goes on; held 1 s also resets "forward", field-centric only) | | `debug(key, with)` | G1 START + BACK (hold START, then press BACK: debug lines, when let go; BACK first is only a pause) | | `switchAlliance(key, with)` | **off**; `switchAlliance(g1.start, g1.back)` turns it on (START, then BACK, both held 1.5 s) | | `setPose(key)` | G1 START held 1 s, drive sticks let go, in INIT or the match (robots with odometry: [`resetPose()`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition)); START + A/B (pairing a gamepad) cancels it | | `slow(key)`, `slowToggle(key)` | G1 LT (one driver: left stick click, on/off) | | `fieldCentric(key)` | G1 Y (one driver: right stick click) | | `buttonMap(key)`, `tuningMenu(key)` | G1 GUIDE (a tap: the map; held 1 s: the tuning menu) | | `allianceInInit(blue, red)` | G1 X = BLUE, G1 B = RED (INIT only) | | `swapSticks(true)` | false (the left stick drives, the right stick X turns) | The whole table, with how to move each: [Move the library's buttons](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/). **INIT names freed library jobs:** no pause button (a warning), no slow at all (a warning), no field-centric button (a line). ## The standard map This is the map for two drivers. With `oneDriver = true`, the operator's buttons move to gamepad 1. | Input | Gamepad 1 (driver) | Gamepad 2 (operator) | | --- | --- | --- | | Left stick | drive (and strafe) | lift by hand (Y), or a hood by hand (Y): see below | | Right stick | turn (X) | arm by hand (Y), turret by hand (X) | | LT / RT | slow (the further, the slower) / free | intake out (hold) / intake in (hold, or on/off) | | LB / RB | free | launcher spin up/down / fire one (hold: keep firing) | | A / X / Y / B | free / free / double-tap: field-centric on/off (mecanum) / free | lift lowest / second / highest / claw | | D-pad up/down | free | lift next height, or launcher speed | | D-pad left/right | free | wrist | | BACK | press: **pause** everything at once (stopped on brake), a tap again: go on; held 1 s (field-centric on): also "forward" = away from you now (with odometry: the pose stays, only the driver's "forward" changes), still paused | turret following on/off (with a turret; else free) | | START (OPTIONS on a PS controller) | hold 1 s: **set pose here** (with odometry: the pose becomes `Tunables.Odometry`'s reset spot) | free | | START + BACK | hold START, then press BACK: debug lines (when let go); with `lib.switchAlliance(g1.start, g1.back)`, both held 1.5 s: **switch the alliance**. BACK first is only a pause | - | | GUIDE | tap: the button map, without the free buttons (during the match too); hold 1 s: the tuning menu (PRACTICE) | free | **Two parts, one stick:** a lift and a launcher's hood both usually use gamepad 2's left stick Y. Two lines on one stick stop INIT ("two jobs"). Give one of them another stick, e.g. `g2.rightStickY.use(robot.lift::manual).says("lift by hand");`. **What INIT checks:** when a module's button is taken, the module gets none, and INIT notes it. Two jobs on one button in Controls.java, or a job on one of the library's buttons, stop INIT with the button's name. INIT shows the whole map and the free buttons. ## One driver - The left stick click switches slow on/off, and the right stick click switches field-centric. - To put slow on a trigger instead, give it `.slow()`. `g1.lt.slow();` slows the robot the further you pull LT (down to `slowSpeed` at a full squeeze, like the two-driver LT). On a button, `.slow()` is slow while held. - Write the switch exactly as `public static boolean oneDriver = true;`. INIT stops with a message if it is not static. ## Reset "forward" Reset "forward" works only with field-centric on. In robot-centric driving, the held BACK shows a note instead ("forward" means nothing there). ## Switch the alliance It is optional, and off by default. Turn it on with `lib.switchAlliance(g1.start, g1.back)`. 1. On gamepad 1, hold the small START button. 2. Then press and hold BACK too. Hold both for 1.5 s. (BACK first is only a pause.) 3. Both gamepads buzz twice. The Driver Station says `Alliance now RED (was BLUE)`. - Everything that reads `robot.alliance()` follows at once: the camera's goal tag (`Camera.goal()`), the aim's goal point (mirrored for RED), light rules you wrote with it, and `MatchMemory` (a TeleOp started again gets it). - The pose follows too, because autonomous ran as the wrong alliance. On a mirrored field (the reset spot's `mirrorForRed` true), the library mirrors it in place (x and heading flip). On a turned field (`mirrorForRed = false`, BIOBUZZ), the pose counts as not set. So the aim's odometry backup is off until you use "set pose here" (the note says so). - INIT's `Switch alliance` line says whether it is on. ## Set pose here For robots with odometry, when autonomous was stopped early or did not run. 1. Park the robot on the reset spot. 2. Let go of the drive sticks (and turn whole-robot aim off). 3. Hold gamepad 1 START for 1 s, in INIT (before the match) or during it. 4. Gamepad 1 buzzes twice. The Driver Station says `Pose set: x -56, y -61 in, heading 0 (BLUE)`. While the robot moves, it says `Pose NOT set: stop first`. - START + A or B (pairing a gamepad on the Driver Station) never sets it. - INIT shows the button, the spot and the mirroring used for RED (`Reset spot for RED: ...`). - The spot: `Tunables.Odometry.resetX, resetY, resetHeading, mirrorForRed` ([`resetPose()`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition)). ## Drive to a spot by itself `route(...)` in `buttons(...)` makes a job that drives the robot to a field spot, around the boxes of `fieldMap(...)`. Any drive stick stops it. How it works, and what it cannot do, is in [keep-out boxes and routes](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes). ```java Runnable park = route("Park", -56, -36, 0, 0.8); g1.dpadLeft.tap(park).says("drive to the park spot (a drive stick stops it)"); atSecondsLeft(10, park); ``` | In `Controls.java` | What it does | | --- | --- | | `route(label, xIn, yIn, headingDeg, power[, toleranceIn])` | makes the job (a `Runnable`). Mistakes stop INIT. It starts when a button or a time runs it | | `atSecondsLeft(seconds, job)` | runs a job once when this many seconds of TeleOp are left. A `route(...)` job waits up to 5 s for the driver to let go of the drive sticks | | `routeRunning()` | whether a route drives the robot now | | `stopRoute()` | ends a running route | ## Buttons in Tunables.java Section `Buttons` (a fixed name), for button gestures (double tap, hold). Module: [ControlMap](#controlmap). **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it. A few lines have example numbers. ```java title="Tunables.java" /** Optional: slower gestures, e.g. for new drivers. Leave the section out for the defaults (in brackets). */ public static class Buttons { // a fixed name: always Buttons public static double tapGapSec = 0.45; // most time between the taps of a double-tap (0.35) public static double holdSec = 0.4; // a press this long is a hold, not a tap (0.3) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `tapGapSec` | the most time between the two taps of a double tap (not the library's field-centric double tap: always 0.35 s) | seconds | 0.35 | yes, at once | test | double taps are missed (more) or single taps wait too long (less) | | `holdSec` | how long a press is held before it counts as a hold | seconds | 0.3 | yes, at once | test | holds start by accident (more) | --- **Look it up:** [`ControlMap` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/ControlMap.html) (every method). **The other pages:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Search every class and method URL: https://crossbotics.com/ftc-helper/docs/reference/javadoc/ The Javadoc lists **every public class, method and setting** of the library, with what it does, its inputs and what it gives back. The library makes it from the explanations in the code (Javadoc comments), so it matches the version you have. It has a **search box**: type a name (`parkWithSeconds`, `PositionMotor`, `slow`) to jump to it. The [reference pages](https://crossbotics.com/ftc-helper/docs/reference/) explain each part, with examples. The Javadoc is for looking one method up. For "how do I...?" questions, with code to copy, see the [cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/). ## Open it **Online:** [crossbotics.com/ftc-helper/reference](https://crossbotics.com/ftc-helper/reference/) (the newest release). Or make it on your computer, for the version you have. **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ([Which folder](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/#which-folder)) ```bash ./gradlew :library:reference ``` Then open `library/build/reference/index.html` in a browser. Making it needs the same setup as building the library ([Contributing](https://crossbotics.com/ftc-helper/docs/contributing/)). Your robot project never makes it by itself, so it adds no time to your robot's builds. ## Read a page Each class page starts with what the class is for, often with a short example. Below it, each method shows its name and inputs (`move(double inches, double directionDeg, double maxPower)`) and a sentence on what it does. Then it shows each input (`@param`) and what it gives back (`@return`). The word before each input is its type: `String` is text, `double` is a number with a decimal point. You call a "static" method on the class (`Action.named("Score")`), and the others on an object you made (`robot.lift.goTo("high")`). --- # Aim URL: https://crossbotics.com/ftc-helper/docs/reference/parts/aim/ The part that says where the goal is, for everything that aims: `robot.aim()`. **It uses the camera first, and the odometry as a backup.** A following turret, a launcher's speed from distance, whole-robot aim and the aim buzz all use it. Learn it step by step: [Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/). ## In Robot.java Aim has no line of its own. It comes with: | Attribute | Needed? | What it gives | | --- | --- | --- | | a [camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/) with `.goal(blue, red)` | one of the two | the goal from the camera | | an [`odometry(...)`](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/) line, and `Tunables.Aim.goalX, goalY` | one of the two | the goal from where the robot is (the backup) | **The camera first.** While the camera sees the goal (a picture newer than 150 ms, `cameraMaxAgeMs`), Aim uses the camera. When the camera does not see it, and the robot has odometry and a goal point, Aim works out the goal's direction and distance from where the robot is. ## In Tunables.java Section `Aim` (a fixed name). Every line is optional. Leave out what you do not use. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" /** Aiming (every line is optional; leave out what you do not use). */ public static class Aim { // a fixed name: always Aim // The goal on the field, in inches, seen from your drivers' wall (the same numbers as driveTo). public static double goalX = 13; // inches right of center (BIOBUZZ) public static double goalY = -13; // inches from center, - = our half (BIOBUZZ) public static boolean mirrorForRed = false; // BIOBUZZ: turned, not mirrored (true) public static double turnKp = DEFAULT; // whole-robot aim: push per degree off (0.02) public static double turnKd = DEFAULT; // brake near the goal (0.002) public static double maxTurnPower = DEFAULT; // the most it turns by itself (0.5) public static double toleranceDeg = DEFAULT; // "aimed" within this, degrees (2) public static double aimDriveSpeed = DEFAULT; // aim mode on: forward and strafe at this share (0.5) public static double rumbleDeg = DEFAULT; // rumbleWhenAimed(): buzz within this (4) public static boolean aimOnFire = false; // no turret: a fire press turns to the goal first } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `goalX`, `goalY` | the goal on the field, seen from YOUR drivers' wall like every field number in your code (x right of the center line, y from the center toward the far wall), written for BLUE: the odometry backup aims at it when the camera does not see the goal. Write both: with only one, there is no odometry backup. BIOBUZZ: 13, -13 | inches | none: camera only | no | the field map | once per season (both, or neither) | | `mirrorForRed` | ONE setting for the whole robot: RED's numbers (the goal point, the routes, the start and reset spots) are BLUE's mirrored (true) or the same numbers from the red wall (false). The library takes the first one written: this one, `Tunables.Odometry.mirrorForRed`, your autonomous's `mirrorForRed()` | true/false | true | no | the game's field | BIOBUZZ: `false` | | `cameraMaxAgeMs` | a camera picture older than this does not count as "sees the goal" | ms | 150 | no | test | the camera is slow and the goal flickers to "odometry" | | `maxGoalDistance` | the odometry backup is off while it says the goal is farther than this (a wrong pose) | inches | 170 | no | the field size | another field size | | `cameraOdometryAgree` | warns when the camera and the odometry differ by more than this | inches | 6 | no | test | too many warnings with a good pose | | `goalSteadySec` | `waitForGoal`: how long the goal must stay in view and still before the step goes on (a tipped HIVE can swing) | s | 1 | no | test | shots after the wait miss while the HIVE still moves (more); the wait is too long (less; 0 = go on when first seen) | | `goalSteadyDeg` | `waitForGoal`: how far left or right the goal may move meanwhile | degrees | 2 | no | test | a still goal never counts as still (the camera's numbers jump: more) | | `goalSteadyIn` | `waitForGoal`: how much nearer or farther the goal may move meanwhile | inches | 2 | no | test | the same | | `turnKp` | whole-robot aim: turn power per degree off | power per degree | 0.02 | yes, at once | test | aim is slow (more) or swings (less) | | `turnKd` | whole-robot aim: brakes the turn as it gets close | power per degree/s | 0.002 | yes, at once | test | aim overshoots (more) | | `maxTurnPower` | whole-robot aim: the most turn power | 0 to 1 | 0.5 | yes, at once | test | aim is too fast or too slow | | `minTurnPower` | whole-robot aim: the least power that still turns the robot | 0 to 1 | 0 | yes, at once | test | aim stops a few degrees short | | `toleranceDeg` | whole-robot aim counts as aimed within this | degrees | 2 | yes, at once | test | shots miss although "AIMED" (less) | | `aimDriveSpeed` | whole-robot aim on: the share of the driver's forward and strafe (the turn is not slowed) | 0.1 to 1 | 0.5 | yes, at once | test | the goal drifts off while the robot moves (less); too slow to drive (more); 1 = full speed | | `aimOnFire` | quick turn on fire (no turret, aim mode off): a fire press with the goal in view turns the robot to the goal, then fires | true/false | false | no | test | the robot fires before it points at the goal (turn it on) | | `aimOnFireSec` | quick turn on fire: the most a press waits for the turn before it fires anyway | seconds | 0.5 | no | test | shots wait too long (less), or fire before the turn is done (more) | | `lockMarginDeg` | once LOCKED (or AIMED), it stays so until the error passes `toleranceDeg` + this, so it does not flicker at the edge | degrees | 1 | no | test | LOCKED flickers (more) | | `sweepStepDeg` | `aimAtGoal(label, sec, sweepDeg)`: the robot turns this much between two looks while it sweeps for the goal | degrees | 15 | no | test | the robot turns past the goal between looks (less) | | `sweepPower` | the sweep's turn power | 0-1 | 0.3 | no | test | the sweep is too slow, or the picture blurs (less) | | `cameraOffset` | whole-robot aim (no turret): a camera that is not on the robot's center line. A turret has its own, `Tunables.Turret.cameraOffset`. The Aim Tuner prints the line for the one your robot uses | degrees | 0 | yes, at once | test | the robot aims a little to one side | | `angleAim` | aim into the opening, not at the tags: on at ▶ ([Aim into the opening](#aim-into-the-opening)) | true/false | false | no | test | the goal's opening is in front of its tags, and shots from an angle miss to one side | | `goalFrontIn` | for the angle aim: how far the opening is in front of the tags, along the way they face | inches | 0 | yes, at once | the field's drawings (BIOBUZZ: 3) | shots from an angle still miss toward the back (more) or the front (less) | | `rumbleDeg` | the aim buzz starts this close to the goal | degrees | 4 | yes, at once | test | the drivers want it earlier or later | | `shootOnMove` | shooting while driving: on at ▶ | true/false | false | no | test | only after you tune it on the real robot | | `flightSec` | shooting on the move: the piece's time in the air | seconds | 0 | yes, at once | test (film a shot) | moving shots land behind (more) or ahead | | `flightSecPerIn` | shooting on the move: more flight time per inch of distance | seconds per inch | 0 | yes, at once | test | far moving shots miss but near ones hit | | `maxLeadIn` | shooting on the move: the most it aims ahead | inches | 24 | yes, at once | test | fast moves need more lead | | `cameraLatencyMs` | shooting on the move: the camera's delay, instead of its own timestamp | ms | the camera's own timestamp | yes, at once | test | the camera's timestamp is wrong | | `shooterForwardIn`, `shooterLeftIn` | where the shooter (turret pivot or launcher exit) is from the robot's center | inches | 0 | no | measure from the edges (below) | the shooter is not at the center | | `cameraForwardIn`, `cameraLeftIn` | where a camera on the robot's body is from the center | inches | 0 | no | measure from the edges (below) | a body camera that is not at the center | More lines, with example numbers: ```java title="Tunables.java" public static class Aim { // Tunables.java (every line optional; all: see below) public static double goalX = 13, goalY = -13; // the goal on the field, inches (odometry backup) public static boolean mirrorForRed = false; // default true; BIOBUZZ's turned field: false public static double turnKp = 0.02, turnKd = 0.002, maxTurnPower = 0.5, minTurnPower = 0, toleranceDeg = 2; public static double cameraOffset = 0, rumbleDeg = 4; public static double maxGoalDistance = 170, cameraOdometryAgree = 6; // inches: odometry checks public static boolean shootOnMove = false; // shooting while driving (below): off until tuned public static double flightSec = 0.8, flightSecPerIn = 0, maxLeadIn = 24; // flightSec default 0: no lead until written public static double shooterForwardIn = 0, shooterLeftIn = 0, cameraForwardIn = 0, cameraLeftIn = 0; } ``` ### The goal point - It uses `driveTo`'s numbers: seen from your drivers' wall, x inches right of the field's center line, y from the center toward the far wall, written for BLUE. - `mirrorForRed` (default true, like autonomous): RED mirrors x. Write `false` for a field turned half a turn: then RED uses the same numbers from the red wall. - One shot table fits both distances only when the camera and the odometry measure to the same place. So put the point where the camera measures to (the goal's tags). - INIT shows the alliance and the choice: `Aim: RED, goal x 13, y -13 in (the same numbers from each wall: Tunables.Aim.mirrorForRed = false)`. - `mirrorForRed` is one setting for the whole robot (autonomous routes, the aim, TeleOp's reset spot). The library takes `Tunables.Aim.mirrorForRed`, else `Tunables.Odometry.mirrorForRed`, else your autonomous's `mirrorForRed()` (a TeleOp uses the last autonomous's), else true. INIT warns when two of them differ ([the three mirrorForRed settings](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/)). ### A wrong pose must not aim the robot The odometry is only as good as its pose: the auto's start spot, carried into TeleOp. - The backup is OFF until something sets the pose: the auto ran in this match, or your code called `robot.odometry().setPose(...)`. Until then, Aim uses the camera only, and the Driver Station warns: `Aim odometry: the pose was never set ...`. - Holding BACK to reset "forward" does not count. It changes only what "forward" means for the driver. It does not change the pose. - The backup is also off while the odometry says the goal is farther than `maxGoalDistance` (170 in: more than the field allows). - While the camera and the odometry both see the goal, and their distances differ by more than `cameraOdometryAgree` (6 in), the Driver Station warns: `Aim: camera says 60 in, odometry 48 in: ...`. ## Whole-robot aim For a robot with no turret. Turn it on with one line in `Controls.java` ([Buttons to add](#buttons-to-add)). - While it is on, the robot turns to face the goal. The driver still controls forward and sideways, at half speed (`aimDriveSpeed`, 0.5). Why: at full speed the robot moves faster than the aim can turn. The goal then drifts off, and the robot only turns back to it when it stops. Slower, the aim keeps the goal centered while the robot moves. The aim's turn keeps its full power. - Moving the turn stick still turns it by hand. - It is off at ▶. - Its numbers: `turnKp`, `turnKd`, `maxTurnPower`, `minTurnPower` (the least power that turns the robot), `toleranceDeg` and `cameraOffset`. - This `cameraOffset` is `Tunables.Aim`'s, for the whole robot. A turret has its own in `Tunables.Turret`. The Aim Tuner prints the line for the one your robot uses. - The Driver Station shows `Aim : camera, 1.5 deg off AIMED`. **Turret-following and whole-robot aim are separate modes. Use one.** A [turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/) that follows the goal (`follows(camera)`, `followsOdometry()`) aims by itself. `robot.aimMode()` is for a robot with no turret, or one that does not follow. Both at once would chase the same error with two motors, and swing back and forth. So `robot.aimMode()` stops at INIT with a message on a robot whose turret follows the goal. ### The aim lock rules These rules took about 60 commits last season. Now they are the defaults. - **Our goal only:** the camera gives this match's alliance goal (`goal("BLUE SCORING", "RED SCORING")`), never the other alliance's. It gives only the CELL that reads right side up (the up CELL), never a down CELL's underside ([Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/)). - **The button turns aim on only with the goal in view.** A press with no goal leaves it off (with `.rumble()`: one buzz instead of two). The Driver Station says `Aim mode not on: no goal in view` for 3 s. The library does not check code that calls `robot.aimMode().on()`. - **A short hold:** a picture stays good for `cameraMaxAgeMs` (150 ms) when the tag drops out for a moment. - **No flicker:** once LOCKED (or AIMED), it stays so until the error passes `toleranceDeg` + `lockMarginDeg` (2 + 1 degrees). So the Goal line, the buzz and a launcher's "aimed" check do not flicker at the edge. ## Seen, in range, LOCKED On a robot that can aim (a camera with `goal(...)`, or the odometry backup), TeleOp always shows one line, so the drivers know when to shoot: `Goal : LOCKED (camera, 52 in, 0.8 deg off)`. Each stage includes the ones before it: | Stage | It means | | --- | --- | | **not seen** | the goal is not known | | **seen** | the goal is known. It also says "out of the shot table's range" when its distance is outside the launcher's `speedByDistance` rows | | **in range** | the distance is inside the table, or the launcher has no table | | **LOCKED** | the robot's front, or a following turret, is within `toleranceDeg`. Aim mode does not have to be on | Your code can use it too: - For lights: `robot.aim().stage() == Aim.Stage.LOCKED`. - To fire only when the robot points at the goal (no turret; aim mode on or off; never blind): `.requireReady("aimed", () -> aim().stage() == Aim.Stage.LOCKED)` on the launcher line, as the `flywheelbot` example does. ## Aim in an auto `s.aimAtGoal("Aim", 3)`: - It turns the whole robot to the goal: up to 4 turns, a fresh reading after each, until it is within `toleranceDeg`. It uses `maxTurnPower`. - With a turret that follows the goal, it waits until the turret is aimed. - It never turns blind. With no goal, it waits up to the time limit, and the report says `not seen`. - The auto builder has it as "+ Aim at the goal". **With a sweep:** `s.aimAtGoal("Aim", 4, 45)`. - When the goal is not in view, the robot turns slowly (`sweepPower`, 0.3) in steps of `sweepStepDeg` (15), up to 45 degrees to the left, then to the right. It looks after each step. - Once it sees the goal, it aims. - When it never sees the goal, it turns back to where it started, and the report says `not seen (swept)`. - It never turns blind past the sweep. ## Quick turn on fire It turns the robot, so it is **off unless you set it**: `Tunables.Aim.aimOnFire = true`. ```java title="Tunables.java" public static class Aim { // Tunables.java public static boolean aimOnFire = true; // RB with the goal in view: turn to it, then fire } ``` For a robot with no turret, with aim mode off: - A press of the fire button (the launcher's RB, or `robot.launcher.fire()`) with the goal in view turns the robot to the goal. The piece waits until the robot is within `toleranceDeg`, at most `aimOnFireSec` (0.5 s: a press always fires). - When the shots are done (and the driver lets go of the button), the driver controls the turn again. The turn stick still wins. - With no goal in view at the press, it fires as before, with no turn. - When the goal is lost during the turn (a turn blurs the picture), it waits, up to `aimOnFireSec`, then fires. - It uses whole-robot aim's numbers (`turnKp` and the others). - It does nothing with aim mode on (it aims already), with a turret that follows the goal, or while the launcher sprays (the last seconds, or tap-then-hold). SPRAY does not wait, so a turn would throw pieces to the side. - An auto's `fire(n)` and fire actions do not turn. Use `aimAtGoal`. - While it turns, `errorDeg()`, `isAimed()` and the aim buzz follow it. The launcher's "not ready" list says `turning to the goal`. ## Shooting on the move Turn it on with `shootOnMove = true`. **It is off by default: tune it on the real robot first** ([Add a camera: Shooting while moving](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/#shooting-while-moving)). - A piece keeps the robot's speed. So the goal every part gets (`goal()`, the turret, `isAimed()`, the launcher's distance) becomes the **virtual goal**: the goal - the shooter's speed x `flightSec` (+ `flightSecPerIn` x the distance), at most `maxLeadIn` (24 in) away. - Aim first brings a camera's picture forward to now: it adds the robot's turn and move since the camera took it. Aim takes the picture's age from the camera's own timestamp, or from `cameraLatencyMs` when you write it. - It needs odometry (the robot's speed). - It works with a turret that follows the goal (camera on the turret, `cameraOnBody()`, or `followsOdometry()`), and with whole-robot aim (a fixed shooter). - `shooterForwardIn, shooterLeftIn`: the turret's pivot (or a fixed launcher's exit) from the robot's center, inches. Measure from the edges, not the middle: forward = length / 2 - (from the front edge), left = width / 2 - (from the left edge). The distance is from there, and a turning robot swings it sideways. - `cameraForwardIn, cameraLeftIn`: a camera on the body. Aim treats a camera on the turret as if it sits at the pivot. - INIT shows `Moving shot: ON: flight 0.80 s ...`. TeleOp shows `Aim: moving shot: lead 12.3 deg, 18 in` while the robot moves, and a debug line with every number. - When it is off, nothing changes. - The math: [MovingShot](https://crossbotics.com/ftc-helper/docs/modules/vision/#movingshot). ## Aim into the opening Some goals have their opening in front of their AprilTags, not right behind them. BIOBUZZ: the 4 tags are under the CELL, and the CELL's opening is about 3 in in front of them (from the field's drawings). - Straight on, the opening is behind the tags, on the same line. The aim needs no change. - From an angle, the opening is off to one side of the tags: toward the front, the way the tags face. Aimed at the tags, the shot goes toward the back edge of the opening. Up close it can miss. - With the angle aim on, Aim points at the spot `goalFrontIn` inches in front of the tags, not at the tags. The camera says which way the tags face, so Aim works out the side and the size by itself. - BIOBUZZ, `goalFrontIn = 3`: at 45 degrees from straight on, about 4 degrees at 32 in and about 2 degrees at 55 in. From the other side, the other way. - The distance for the speed stays the tags' distance (the shot table was made with it). - It needs a camera that knows which way the tags face: a webcam (and the simulator's). With a Limelight, it does nothing. - On at ▶ with `angleAim = true` and `goalFrontIn` set. A button can switch it on and off: `g1.a.toggle(robot.aim().angleAimMode())`. Try shots from an angle with it on and off. - It works with whole-robot aim, quick turn on fire, `aimAtGoal` in an auto, and a turret that follows. - A tag's facing is the noisiest part of what the camera measures. Aim uses the middle of the last 5 pictures' corrections, so one odd picture does not swing the aim. - TeleOp shows `Angle aim: +3.9 deg toward the opening`, or why it does nothing (`no face direction from this camera`, `no goal in view`). Check that line before you trust it in a match. - When the camera loses the goal and the odometry backup takes over, the aim goes back to the goal point (no correction): it can turn a few degrees. ## Commands | Command | What it does | | --- | --- | | `mode()` (= `robot.aimMode()`) | whole-robot aim. It stops with a message on a robot whose turret follows the goal | | `movingShotMode()` | shooting on the move on/off. It is on from ▶ with `shootOnMove = true` | | `angleAimMode()` | [aim into the opening](#aim-into-the-opening) on/off. It is on from ▶ with `angleAim = true` | | `turnFor(driverTurn)` | TeleOp's turn for an OpMode with its own drive (the Shot Tuner): `driving.turnAssist(robot.aim()::turnFor)`. While `mode()` is on it turns to the goal; the stick still wins | | Question | What it tells you | | --- | --- | | `goal()`, `source()` | the goal now (null if neither), and CAMERA, ODOMETRY or NONE | | `fromOdometry()` | the goal from the odometry alone (a [TargetObservation](https://crossbotics.com/ftc-helper/docs/modules/vision/) with id `ODOMETRY`), or null (no pose set, or farther than `maxGoalDistance`) | | `odometryProblem()` | why the odometry backup is off now, "" if it works | | `disagreement()` | the camera/odometry distance warning, "" if they agree | | `hasGoalPoint()` | whether `Tunables.Aim` has `goalX` and `goalY` | | `canAim()` | whether the robot can find the goal at all (a camera with a goal, or the odometry backup) | | `camera()` | the [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/) that aims the robot (the first with `goal(...)`), or null | | `turretAims()` | whether a turret follows the goal (then `mode()` cannot be used) | | `stage()` | NOT_SEEN, SEEN, IN_RANGE or LOCKED now (`Stage.words()`: "not seen" ... "LOCKED") | | `aimsOnFire()`, `isTurningToFire()` | whether quick turn on fire is set (`aimOnFire`); whether a fire press is turning the robot now | | `errorDeg()` | degrees off now (NaN = unknown). While shooting on the move: off the virtual goal | | `isAimed()` | whether it is aimed: the whole robot within `toleranceDeg`, or the following turret's `isAimed()` (on the goal now) | | `rumbleDeg()` | the buzz's `rumbleDeg` | | `buzzErrorDeg()` | the buzz's error. Also the camera's bearing on a robot with no turret and the aim off | | `isMovingShot()` | whether shooting on the move is on and the robot moves (over 2 in/s or 5 deg/s) | | `lead()` | the last lead (a [MovingShot](https://crossbotics.com/ftc-helper/docs/modules/vision/#movingshot) `Result`: `leadDeg`, `leadIn`, `distanceIn`), null if none | | `Aim.sourceOf(observation)` | CAMERA, ODOMETRY or NONE for that observation | ## Buttons to add Aim has no buttons until you add its lines to `Controls.java` ([how to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line)). ```java title="Controls.java" g1.rb.toggle(robot.aimMode()).says("aim the robot at the goal on/off").rumble(); // whole-robot aim g2.rumbleWhenAimed(); // the aim buzz g2.a.toggle(robot.aim().movingShotMode()); // shooting on the move on/off g1.a.toggle(robot.aim().angleAimMode()).rumble(); // aim into the opening on/off ``` **The aim buzz** (`rumbleWhenAimed()`, an [AimRumble](https://crossbotics.com/ftc-helper/docs/modules/gamepad/)): - It buzzes that gamepad while the aim is within `rumbleDeg`. The closer, the stronger and longer. - It follows a turret that is following, or whole-robot aim. - A robot with no turret buzzes with aim mode off too. The driver turns it by hand, and it buzzes when the camera sees the goal straight ahead (`buzzErrorDeg()`). - It is only the buzz: a launcher's "aimed" check stays off while nothing aims. - It does not buzz with no goal in view, or while paused. --- **Look it up:** [`Aim` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Aim.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Arm URL: https://crossbotics.com/ftc-helper/docs/reference/parts/arm/ ## In Robot.java ```java title="Robot.java" arm = add(Arm.motor("arm", "gobilda-5203-117").gearRatio(2)); ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Arm.motor(name, motorId)` | **yes** | an arm on one motor. `motorId` is the motor from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) | - | | `.gearRatio(r)` | recommended | motor turns per arm turn | 1 | | `.bottomSwitch(name)` | optional | a switch at the bottom, like the [lift's](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#where-0-is) | 0 degrees is where the arm is when the program starts | | `.alsoMotor(name)` | optional | a second motor, turning the same way ([Two motors](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm)) | one motor | | `.alsoMotorReversed(name)` | optional | a second motor, turning the other way ([Two motors](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm)) | one motor | | `.reversed()` | optional | the arm turns the other way. Use it when positive power moves the arm down | - | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.looks(shapes...)` | optional | how it looks in the simulator ([Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)) | a plain box | | `.tunables("Name")` | optional | read another `Tunables` section | the device's name in CamelCase | **Where 0 is:** without a bottom switch, 0 degrees is where the arm is when the program starts. ## In Tunables.java The section's name is the device's name in CamelCase: `arm` reads `Tunables.Arm`. An arm's numbers are in **degrees**. The table of every number, with the arm's defaults, is on the [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#in-tunablesjava) page. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class Arm { // "arm" in the configuration public static double min = MEASURE; // lowest safe angle, degrees, 0 = at INIT public static double max = MEASURE; // highest safe angle, degrees (Motor Finder) public static double kP = DEFAULT; // push toward the target (0.02) public static double kI = DEFAULT; // fix a small steady miss (0) public static double kD = DEFAULT; // brake near the target (0.001) public static double kF = 0.1; // hold up against gravity (0) public static double stowed = MEASURE; // a named angle, degrees: any name you like public static double pickup = MEASURE; // a named angle (Motor Finder) public static double score = MEASURE; // a named angle (Motor Finder) } ``` ## Commands The same as the [Lift's](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#commands), in degrees: `goTo(name)`, `stepUp()`, `stepDown()`, `manual(power)`, `hold()`, `stop()`, and the questions `isAtTarget()`, `isAt(name)`, `position()`, `positions()`, `part()`, `secondMotorName()`, `isPresent()`. Its zone for an [interlock rule](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/): `arm.zoneAbove()` or `arm.zoneBelow()`. ## Buttons to add A part has **no buttons** until you add its lines to `Controls.java`. These are the usual ones. Copy them, or change the button ([how to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line)). - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. You do not change them. - **On gamepad 1, with two drivers:** write `g1` and a free button, for example `g1.rb`. Gamepad 1's LT is slow mode, so do not use it. If you pick a button the library uses, INIT stops and names it. ```java title="Controls.java" g2.rightStickY.use(robot.arm::manual).says("by hand"); ``` The operator's right stick Y moves the arm by hand. For named angles, add lines like the [Lift's](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#buttons-to-add): `g2.y.press(() -> robot.arm.goTo("score")).says("score");`. --- **Look it up:** [`Arm` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Arm.html) and [`MotorPositions`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/MotorPositions.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Camera URL: https://crossbotics.com/ftc-helper/docs/reference/parts/camera/ ## In Robot.java ```java title="Robot.java" camera = add(Camera.limelight("limelight").goal("BLUE SCORING", "RED SCORING")); camera = add(Camera.webcam("Webcam 1")); camera = add(Camera.huskyLens("huskylens").tag(1, 34).tag(2, 35).goal("BLUE SCORING", "RED SCORING")); ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Camera.limelight(name)` | **yes**, one of the three | a Limelight | - | | `Camera.webcam(name)` | **yes**, one of the three | a webcam | - | | `Camera.huskyLens(name)` | **yes**, one of the three | a HuskyLens | - | | `.goal(blueGroup, redGroup)` | recommended | each alliance's HIVE, like `goal("BLUE SCORING", "RED SCORING")`. Aiming uses it ([The goal](#the-goal-is-our-hives-up-cell)) | `goal()` gives null, and nothing aims | | `.autoPipelines(n...)` | optional | a Limelight: the pipelines the lighting test tries at INIT ([Venue lighting](#venue-lighting)) | no test: `pipeline` | | `.autoExposure()` | optional | a webcam: the lighting test tries auto, 3, 6 and 12 ms | no test: `exposureMs` | | `.autoExposure(ms...)` | optional | a webcam: the exposures the test tries, like `autoExposure(6, 3, 12)` | - | | `.tag(taughtNumber, tagNumber)` | HuskyLens | the number you taught it, and the tag's real number. A HuskyLens says the taught number | - | | `.colors()`, `.objects()` | HuskyLens, optional | it looks for taught colors, or one object, instead of tags | tags | | `.label(taughtNumber, name)` | HuskyLens, optional | a name for `target(name)` | - | | `.upsideDown()` | webcam, optional | the webcam is mounted upside down: left is left again, and the tags read right side up ([Upside down](#a-webcam-upside-down)) | an upside-down webcam aims the wrong way, and it takes the down CELL for the goal | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | a warning at INIT (below) | The camera starts in INIT. When the robot configuration has no camera of that name, INIT shows a warning and goes on. The OpMode runs, and the camera sees nothing. ### The goal is our HIVE's up CELL `goal("BLUE SCORING", "RED SCORING")` names each alliance's HIVE. - `goal()` gives that HIVE's CELL whose tags read right side up now: the up CELL, the one you can score in ("RED SCORING" or "RED AUDIENCE": a tip swaps them). - A CELL whose tags read upside down (a down CELL, for example seen from under the HIVE) cannot be the goal. Then `goal()` gives null, and the Driver Station says `Goal : not seen (RED SCORING is upside down (a down CELL))`. - Aiming, the turret, the shot table's distance, LOCKED and the launcher's "aimed" checks all use `goal()`. - `target("RED SCORING")` still gives that group, upside down or not. - How the camera tells up from down: [vision.md](https://crossbotics.com/ftc-helper/docs/modules/vision/#taggroup). ### A HuskyLens - It says the number you taught it. List each one with its tag's real number: `tag(taughtNumber, tagNumber)`. - Measure `hfovDeg` (its view angle). Write `sizeIn` for a rough distance: the shot table needs it. - INIT says what is missing. - It has no lighting test. - Its limits, and how to teach it: [vision.md](https://crossbotics.com/ftc-helper/docs/modules/vision/#huskylenscamera). ### Venue lighting Each venue has different light: a bright gym, a dim classroom, spotlights at an event. A camera setting that finds the tags at school can miss them at an event. So the camera can test a few settings in INIT and keep the one that sees the most AprilTags ([how the test works](https://crossbotics.com/ftc-helper/docs/modules/vision/#venue-lighting)). The settings it tests depend on the camera: | Camera | What it tests | Turn it on in Robot.java | | --- | --- | --- | | Limelight | its **pipelines**. A pipeline is a set of camera settings that you save on the Limelight by number. Save one for your usual light, one for bright light and one for dim light ([how](https://crossbotics.com/ftc-helper/docs/guides/limelight-lighting/)) | `.autoPipelines(0, 1, 2)` | | Webcam | exposures: how long each picture collects light | `.autoExposure()` (auto, 3, 6 and 12 ms) | | HuskyLens | nothing: it has no lighting test | - | ```java title="Robot.java" camera = add(Camera.limelight("limelight").autoPipelines(0, 1, 2).goal("BLUE SCORING", "RED SCORING")); camera = add(Camera.webcam("Webcam 1").autoExposure()); // or your own list: autoExposure(6, 3, 12) ``` **At an event:** 1. In the queue, press INIT with the robot facing a tag. The test stops at ▶ and keeps the best setting so far, so a tag must be in view. 2. The Driver Station shows the result, for example `limelight lighting : pipeline 2 (9 of 10 pictures saw tags)`. While the camera sees no tag, this line is a warning. 3. It also shows two lines for `Tunables.java`. Copy them into the camera's section (`Tunables.Limelight`). Then every match at this venue uses that setting, with no test: ```java title="Tunables.java" public static double pipeline = 2; public static boolean autoLighting = false; ``` A webcam shows `public static double exposureMs = 6;` instead of `pipeline`. 4. Back home, set `autoLighting = true` again. **When no setting saw a tag,** TeleOp shows a warning at the top of the Driver Hub (`Webcam 1 lighting: NO TAGS SEEN`) until the camera sees a tag, so the driver knows the aim may not work. **Do the test again** with `relight()` when the robot started with no tag in view, or the light changed ([Buttons to add](#buttons-to-add)). - In the match it takes up to 5 s (or `lightingAfterStartMs`, when you set it). - The camera sees no targets until it is done, so the aim stops too. - The TeleOp screen shows `Webcam 1 lighting: ...` from then on. - If no setting sees a tag, it keeps the setting it had. - With no `autoExposure` or `autoPipelines`, or with `autoLighting = false`, it does nothing. It gives false, and the TeleOp screen says so for 5 s. ### A webcam upside down A webcam mounted upside down sees an upside-down picture. Left and right swap, so whole-robot aim turns the wrong way. Every tag reads upside down, so the down CELL looks like the up CELL: the camera aims at the wrong one. Add `.upsideDown()`: ```java title="Robot.java" camera = add(Camera.webcam("Webcam 1").upsideDown().goal("BLUE SCORING", "RED SCORING")); ``` The library then turns each reading back: left is left, and the up CELL is the goal again. The live view on the Driver Station stays upside down. In the simulator robot file, `:sim:fromRobot` writes `roll=180` on the camera's line. A robot file you wrote yourself needs it too ([Cameras](https://crossbotics.com/ftc-helper/docs/reference/robot-file/#cameras)). A Limelight has its own setting on its web page (Settings, Orientation): `upsideDown()` is for a webcam only, and INIT stops if you add it to a Limelight or a HuskyLens. ### Live view Use it to check the brightness. - A webcam shows its picture in the PRACTICE profile. INIT says `Webcam1 live view: on (PRACTICE): Driver Station menu > Camera Stream, in INIT`. - A Limelight's live picture: plug it into a laptop and open http://limelight.local:5801. Nobody has tested it through the Control Hub yet. ## In Tunables.java The section's name is the camera's name in CamelCase: `limelight` reads `Limelight`, `Webcam 1` reads `Webcam1`. The camera reads them once, at INIT. They are not in the tuning menu: change them in `Tunables.java` and install again. Leave them out to keep the defaults. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class Limelight { // "limelight" in the configuration public static double pipeline = 0; // a Limelight: the pipeline to use (0) public static boolean autoLighting = true; // try a few settings at INIT, keep the best (true) public static double pitchDeg = DEFAULT; // its tilt up, degrees (0 = level) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `liveView` | a webcam: show its picture (the Driver Station's Camera Stream, in INIT) in the PRACTICE profile; never in COMPETITION (it costs speed) | true/false | true | no | none | `false` to save speed in practice too | | `pipeline` | a Limelight: the pipeline to use | number | 0 | no | the lighting test at INIT | the test found a better one at this venue | | `autoLighting` | try a few settings at INIT and keep the best (`autoPipelines` / `autoExposure`) | true/false | true | no | none | `false` to skip the test at a venue you know | | `exposureMs` | a webcam: a fixed exposure when the test is off (-1 = the camera's own) | ms | -1 | no | the lighting test at INIT | the test found a better one | | `gain` | a webcam: the gain for a fixed exposure (-1 = the camera's highest) | number | -1 | no | test | pictures are too dark or noisy | | `lightingSettleMs` | the test: wait after each switch | ms | 300 | no | none | pictures are still changing | | `lightingPictures` | the test: pictures per setting | count | 10 | no | none | results vary | | `lightingMinPictures` | the test: pictures with tags a setting needs | count | 3 | no | none | a bad setting wins | | `lightingAfterStartMs` | the test: keep trying this long after ▶ (no targets meanwhile) | ms | 0 | no | none | only for a special case | | `pitchDeg` | a webcam or Limelight: its tilt up; then bearings and distances are along the floor ([CameraTilt](https://crossbotics.com/ftc-helper/docs/modules/vision/#cameratilt)) | degrees (+ = up) | 0 (level) | no | measure (a level app on the camera's face) | the camera is tilted; after a change, make the shot table again | | `hfovDeg` | a HuskyLens: its view angle, left edge to right edge of the picture | degrees | 60 (a guess) | no | measure ([how](https://crossbotics.com/ftc-helper/docs/modules/vision/#huskylenscamera)) | always: measure yours | | `sizeIn` | a HuskyLens: the real size of what it looks at, for a rough distance (none: no distance) | inches | none | no | measure | the longest side it shows: a tag's black square, a ball's width | `pitchDeg` is also the simulator robot file's `pitch`. ### CameraFix Section `CameraFix` (a fixed name). **ALPHA: nobody has tested it on a robot. Not for BIOBUZZ:** its tags move with the HIVE. It works only with `cameraFix(camera)` in Robot.java. It corrects the odometry's x and y from the camera: [Camera fix (alpha)](https://crossbotics.com/ftc-helper/docs/modules/odometry/#camera-fix-alpha). | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `enabled` | the camera fix on or off | true/false | false | no | none | to try it (not in BIOBUZZ) | | `turnDegBlue` | the turn from the Limelight's field frame to ours, on BLUE | degrees | 0 | no | Camera Fix Check | the check says another turn | | `turnDegRed` | the same on RED | degrees | 0 | no | Camera Fix Check | the same | | `maxAgeMs` | the fix skips a picture older than this | ms | 100 | no | none | only for a special case | | `maxSpeedInPerSec` | faster than this: no fix | inches per second | 20 | no | none | only for a special case | | `maxTurnDegPerSec` | turning faster than this: no fix (the heading lags in the picture) | degrees per second | 30 | no | none | only for a special case | | `maxJumpIn` | the fix refuses a bigger difference (a bad picture) | inches | 12 | no | none | only for a special case | | `blend` | how much of the difference the fix applies, per picture | 0-1 | 0.2 | no | none | the pose jumps (less) | | `minTags` | the fix skips a picture with fewer tags | count | 2 | no | none | only for a special case | ## Commands | Command | What it does | | --- | --- | | `relight()` | does the lighting test again. It gives false when there is no test to do | | `checkInInit(t)`, `started()` | TeleOp's INIT and START work for the camera (the lighting test), for an OpMode that does not run the robot's (the Shot Tuner) | | Question | What it tells you | | --- | --- | | `goal()` | the alliance's goal now, or null ([The goal](#the-goal-is-our-hives-up-cell)) | | `target(name)`, `target(id)` | that group or tag, or null when the camera does not see it | | `source()` | the [`TargetSource`](https://crossbotics.com/ftc-helper/docs/modules/vision/) inside | | `lighting()` | the lighting test itself | | `knowsGoal()` | whether Robot.java gives it a `goal(...)` | | `liveViewOn()` | whether the webcam's live view is on | | `isLimelight()`, `isWebcam()`, `isHuskyLens()` | which kind it is | | `isPresent()` | whether the part is on the robot (an `optional()` part may not be) | ## Buttons to add The camera has no usual buttons. To do the lighting test again, put `relight()` on a button in `Controls.java`. The driver aims the camera at a tag, then holds the button for 0.5 s. The hold stops a bump from starting it: ```java title="Controls.java" g1.y.heldFor(0.5, robot.camera::relight).rumble().says("camera: lighting test again (aim at a tag)"); ``` Robot 1 uses this line, with one driver. **With two drivers:** gamepad 1's Y is the library's field-centric button (a double-tap), so INIT stops on this line. Put it on the operator's BACK instead: `g2.back.heldFor(0.5, robot.camera::relight)`. The driver aims at a tag, and the operator holds BACK. [How to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line). --- **Look it up:** [`Camera` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Camera.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Claw URL: https://crossbotics.com/ftc-helper/docs/reference/parts/claw/ A Claw, a [Wrist](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/) and a [Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/) share most of their options, numbers and commands (`ServoPositions`). This page lists the shared ones. ## In Robot.java ```java title="Robot.java" claw = add(Claw.servo("claw").part("gobilda-2000-torque")); // Tunables.Claw: open, closed (both needed) ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Claw.servo(name)` | **yes** | a claw on one servo | - | | `.part(id)` | recommended | which servo it is, from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). When you do not write `travelSec`, the library takes it from the servo's catalog speed | `travelSec` is 0.3 s | | `.alsoServo(name)` | optional | a second servo, turning the same way as the first for the same position ([Two servos](#two-servos-on-one-part)) | one servo | | `.alsoServoReversed(name)` | optional | a second servo turning the other way (two servos that face each other, mirror images) ([Two servos](#two-servos-on-one-part)) | one servo | | `.reversed()` | optional | the servo turns the other way | - | | `.fullRange()` | optional | the servo's whole turn ([below](#a-servos-full-range)) | the FTC SDK's normal range | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.looks(shapes...)` | optional | how it looks in the simulator ([Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)). It can ride on a wrist: `Shape.claw().on(wrist)` | a plain box | | `.tunables("Name")` | optional | read another `Tunables` section | the device's name in CamelCase | - A servo does not move until the first command after ▶. - When you write no positions, INIT says that the library's positions are guesses. Find yours with the Servo Finder. ## Two servos on one part Some parts have two servos: a claw with a servo for each finger, or an arm with a servo on each side. Name the second servo on the same line, like [`alsoMotor`](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm). ```java title="Robot.java" claw = add(Claw.servo("claw_left").alsoServoReversed("claw_right")); // they face each other (usual) arm = add(Positioner.servo("arm_left").alsoServo("arm_right")); // both turn the same way ``` - Both servos get the same position at the same moment: from every command, pause, stop and interlock rule. - The Tunables section takes the first servo's name. - Two horns (the arms on the servo shafts) can sit a spline tooth apart. `alsoTrim` (raw position, -0.2 to 0.2, default 0) fixes that: the library adds it for the second servo, so the two still meet. - It works on a Claw, a Wrist, a Positioner and a servo [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/). - On a CR servo [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/) (two feed wheels), both servos get the same power. There is no `alsoTrim`. - No standard says which way a bigger number turns a servo. It depends on the servo, so test it: [Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/#servos-and-motors-which-way-is-bigger). ## A servo's full range `.fullRange()` gives the servo its whole turn. - The hub sends a servo a pulse: 600 microseconds (us) for position 0, and 2400 us for 1. That is the FTC SDK's normal range, and the library keeps it. - Most FTC servos take 500 to 2500 us. So on the normal range they turn a bit less than the seller says. For example, a goBILDA 2000 servo turns 270 degrees over 0 to 1, and its seller says 300. - At INIT, `.fullRange()` sends the servo's whole pulse range. It takes the range of the catalog part in `part(...)`, or else 500 to 2500 us. Then 0 to 1 turns all 300 degrees. - It works on a Claw, Wrist or Positioner, and on `Hood.servo`, `Turret.servo` and `Indexer.servo`. - **Measure your positions after you turn it on.** When the range changes, the same number points somewhere else. The Servo Finder has the same switch: press Y while you choose. - A servo that cannot change its pulse (not on a REV hub) keeps its range. INIT says so. - The hub keeps a pulse range until the next INIT. ```java title="Robot.java" wrist = add(Wrist.servo("wrist").part("gobilda-2000-speed").fullRange()); // 0 to 1 = 300 degrees ``` Recipe: [How do I get my servo's full range?](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-get-my-servos-full-range) ## In Tunables.java The section's name is the device's name in CamelCase: `claw` reads `Claw`, `intake_deploy` reads `IntakeDeploy`. This table is for a Claw, a [Wrist](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/) and a [Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/). Every number except `travelSec` and `alsoTrim` is a named position (0 to 1). **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). The wrist's and the positioner's lines are on their pages. ```java title="Tunables.java" public static class Claw { // "claw" in the configuration // The Servo Finder shows "Tunables.Claw: P1 = 0.210, P2 = 0.770": write P1 as open, P2 as closed. public static double open = MEASURE; // servo position, open (Servo Finder) public static double closed = MEASURE; // servo position, closed (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `travelSec` | how long the servo takes for a full move, from position 0 to 1 (a shorter move takes its share). A servo cannot say when it has arrived, so the library uses this as its guess | seconds | 0.3 (with `.part(...)`: from the servo's catalog speed, [First run](https://crossbotics.com/ftc-helper/docs/reference/tunables/#first-run-what-you-get-before-tuning)) | no | test: time a move, divide by its distance (below) | actions go on before it arrives (more) | | `alsoTrim` | with a second servo (`alsoServo`, `alsoServoReversed`): a raw position the library adds for it, so the two meet | raw position, -0.2 to 0.2 | 0 | yes, at the next move | test: watch both sides | the two sides do not line up | | `` | every other number is a named position, 0 to 1. A Claw needs `open` and `closed` | servo position 0 to 1 | Claw: open 0.20, closed 0.75. Wrist: down 0.15, level 0.5, up 0.85. Positioner: stowed 0.0, deployed 0.5 (only when none are written; INIT says they are guesses) | yes, at once | Servo Finder (P1, P2...) | it does not open, close or reach far enough | ### Timing travelSec - `travelSec` is the time for a FULL move, 0 to 1. The library scales it by how far each move goes. - A mounted servo usually cannot go from 0 to 1. So time a move between two of your positions, and divide: `travelSec = measured seconds / |positionB - positionA|`. - Example: 0.6 s from `stowed = 0.20` to `deployed = 0.74` gives 0.6 / 0.54 = 1.1. If you write the 0.6 itself, the part counts as "arrived" after about half of the real move. - Or leave it `DEFAULT`. With `.part(...)`, the library takes it from the servo's catalog speed. - Some parts keep falling after the servo has moved, like a fold-out that drops by gravity. `travelSec` does not count that time. Add `.waitSeconds(...)` to the action for it. ## Commands Use them in `Controls.java`, `Actions.java` and autos: `robot.claw.close()`. | Command | What it does | | --- | --- | | `open()`, `close()` | opens, closes | | `toggle()` | open or closed | | `goTo(name)` | goes to a named position | | Question | What it tells you | | --- | --- | | `isClosed()` | whether it is closed | | `isDone()` | whether it should have arrived: a guess from `travelSec` | | `isAt(name)` | whether it is at that named position | | `positions()` | the names of its positions | | `part()` | the [`PositionServo`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#positionservo) inside | | `secondServoName()` | the second servo's name, or null | | `zone()` | its zone for an [interlock rule](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) | | `isPresent()` | whether the part is on the robot (an `optional()` part may not be) | `goTo(name)`, `isDone()`, `isAt(name)`, `positions()`, `part()` and `secondServoName()` are on a Wrist and a Positioner too. ## Buttons to add A part has **no buttons** until you add its lines to `Controls.java`. These are the usual ones. Copy them, or change the button ([how to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line)). - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. You do not change them. - **On gamepad 1, with two drivers:** write `g1` and a free button, for example `g1.rb`. Gamepad 1's LT is slow mode, so do not use it. If you pick a button the library uses, INIT stops and names it. ```java title="Controls.java" g2.b.toggle(robot.claw).says("open / close"); ``` The operator's B opens and closes the claw. --- **Look it up:** [`Claw` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Claw.html) and [`ServoPositions`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/ServoPositions.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Drive URL: https://crossbotics.com/ftc-helper/docs/reference/parts/drive/ ## In Robot.java ```java title="Robot.java" drive(Drive.mecanum("front_left", "front_right", "back_left", "back_right") .motor("gobilda-5203-312").wheelMm(96).imu("imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD)); drive(Drive.tank("left_drive", "right_drive").motor("gobilda-5203-312").wheelMm(96).reversed("right_drive")); ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Drive.mecanum(fl, fr, bl, br)` | **yes**, one of the three | a mecanum drive and its four motor names | - | | `Drive.tank(left, right)` | **yes**, one of the three | a tank drive on two motors | - | | `Drive.tank(fl, fr, bl, br)` | **yes**, one of the three | a tank drive on four motors | - | | `.motor(id)` | recommended | the drive motor's catalog id ([parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/)). The other parts use `part(id)` | `gobilda-5203-312` | | `.wheelMm(mm)` | recommended | the wheel diameter, mm | 96 | | `.wheel(id)` | optional | the wheel by its catalog id ([Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)), like `"gobilda-hogback-96"` or `"gobilda-gripforce-mecanum-104"`. The library takes its diameter from the catalog | `wheelMm` | | `.gearRatio(r)` | optional | motor turns per wheel turn | 1 | | `.wheelsAtMm(track, wheelBase)` | optional | for the simulator: the distance between wheel centers side to side, and front to back, mm | a guess | | `.reversed(names...)` | optional | exactly these motors run reversed | the left side is reversed | | `.imu(name, logo, usb)` | optional | the IMU, and how the hub is mounted | "imu", UP, FORWARD | | `.noImu()` | optional | the robot has no IMU | the IMU above | The drive cannot be `optional()`: a robot always drives. ## In Tunables.java Section `Drive` (a fixed name). The drive reads it once, at INIT. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class Drive { // a fixed name: always Drive public static double maxPower = 0.6; // top wheel power: slow for first drives (1.0) public static double practiceMaxPower = DEFAULT; // top wheel power in PRACTICE (same as maxPower) public static double slowSpeed = DEFAULT; // top power with the slow trigger held (0.3) public static double strafeCorrection = DEFAULT; // sideways moves: Drive Tuner (1.15) public static double turnKp = DEFAULT; // auto turns: push per degree off (0.012) public static double turnKd = DEFAULT; // auto turns: brake near the end (0.003) public static double moveMinPower = DEFAULT; // auto: least power that moves it (0.30) public static boolean calibrated = false; // true after the Drive Tuner: auto runs then } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `maxPower` | the most power the wheels get (COMPETITION profile) | 0 to 1 | 1.0 | yes, next INIT | test | the robot is too fast for the drivers | | `practiceMaxPower` | the most power in the PRACTICE profile | 0 to 1 | the same as `maxPower` | yes, next INIT | test | a brand-new driver, for a day; drivers should practice at match speed | | `slowSpeed` | the most power while the driver pulls the slow trigger all the way (a small squeeze slows it a little) | 0 to 1 | 0.3 | yes, next INIT | test | fine moves are too slow or too fast | | `strafeCorrection` | mecanum wheels slip sideways. This makes a sideways move in autonomous as long as asked | times | 1.15 | yes, next INIT | Drive Tuner | sideways moves are short or long | | `strafeCorrectionLeft` | the same for moves to the LEFT, when the robot slips differently that way (when you leave it out, `strafeCorrection` counts both ways) | times | `strafeCorrection` | yes, next INIT | Drive Tuner (Strafe left) | moves to the left are short or long, moves to the right are right | | `turnKp` | autonomous turn: how hard it turns per degree off | power per degree | 0.012 | yes, next INIT | Move Tuner (Turns) | turns stop short (more) or wobble (less) | | `turnKd` | autonomous turn: brakes the turn as it gets close | power per degree/s | 0.003 | yes, next INIT | Move Tuner (Turns) | turns overshoot (more) | | `turnMinPower` | autonomous turn: the least turn power while the heading is still off, so a turn does not stop a little short. 0 = off (`driveTo` and routes then use 0.08) | 0 to 0.3 | 0 | yes, next INIT | Move Tuner (Turns) | turns stop a few degrees short | | `turnToleranceDeg` | autonomous turn: done when the heading is this close (for 0.15 s) | degrees | 1.0 | yes, next INIT | test | turns take long to end (more); the heading must be closer (less) | | `moveMinPower` | the least power that still moves the robot (autonomous) | 0 to 1 | 0.30 | yes, next INIT | Move Tuner (Creep) | the robot stops a little before the end of a move | | `slowDownIn` | autonomous: a short move can slide past its end. With this, every move slows down over at least its last this-many inches (and also over its last 10%). Then a short move reaches the end about as slowly as a long one, and slides about the same. `driveTo` and routes already slow down over their last 8 in | inches, 0 to 48 | 0 (only the last 10%) | yes, next INIT | Move Tuner (Stops) | short moves slide past the end; moves at different speeds end in different places | | `moveTurnScale` | `moveWithTurn`: the heading correction while moving is multiplied by this | 0 to 1 | 0.60 | yes, next INIT | Move Tuner (Move and turn) | the turn is not done when the move ends (more); the heading swings past its target (less) | | `moveMaxTurnPower` | `moveWithTurn` and routes: the most turn power while moving | 0.05 to 1 | 0.35 | yes, next INIT | Move Tuner (Move and turn) | the turn lags even at `moveTurnScale` 1 | | `calibrated` | autonomous drives the robot only when this is `true`. Until then INIT says `AUTONOMOUS IS OFF` (the simulator runs it anyway, and says so) | true/false | false | no | Drive Tuner, then set it | after the Drive Tuner, once moves are right | **`calibrated`:** first tune with the Drive Tuner ([Tune the drive first](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#tune-the-drive-first)). The Drive Tuner and the Shot Tuner need the whole robot: `@Override protected RobotDefinition robot() { return new Robot(); }`. Every finder shows `Tunables.` lines for you to copy ([finders](https://crossbotics.com/ftc-helper/docs/tuning/)). ## Commands | Command | What it does | | --- | --- | | `robot.reverseDriveMode()` | a mode where the back of the robot acts as the front: it flips forward and strafe. It does not flip the turn. Field-centric driving ignores it. It is off at ▶ | | Question | What it tells you | | --- | --- | | `isMecanum()` | whether it is a mecanum drive | | `motorNames()` | the motor names, in order | | `isReversed(name)` | whether that motor runs reversed | In an auto, the drive's steps are `drive`, `strafe`, `turn` and the others ([Steps for autos](https://crossbotics.com/ftc-helper/docs/reference/steps/)). ## Buttons The drive's buttons are the library's own, on gamepad 1: the sticks, slow, and field-centric. You do not add them. To move them, see [Controls.java](https://crossbotics.com/ftc-helper/docs/reference/controls/). **Reverse drive** is one line in `Controls.java`: ```java title="Controls.java" g1.x.toggle(robot.reverseDriveMode()).rumble(); ``` While it is on, the Driver Station says `Drive : REVERSED: the back is the front`. --- **Look it up:** [`Drive` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Drive.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Hood URL: https://crossbotics.com/ftc-helper/docs/reference/parts/hood/ ## In Robot.java ```java title="Robot.java" launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .hood(Hood.servo("hood").part("gobilda-2000-torque")) // or Hood.motor("hood", "gobilda-5203-117") .speedFromDistance(camera)); ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `.hood(...)` on the launcher | **yes** | the launcher's hood. The launcher takes its angle from the shot table's third column, and waits for it before it feeds | no hood | | `Hood.servo(name)` | **yes**, one of the two | a hood on a standard servo | - | | `Hood.motor(name, motorId)` | **yes**, one of the two | a hood on a motor with an encoder. Its encoder counts (ticks) start from where the hood is at INIT, so start with the hood on stop A | - | | `.part(id)` | recommended (servo) | which servo it is, from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). The library takes `travelSec` from its speed | `travelSec` 0.5 | | `.reversed()` | optional | it turns the other way | - | | `.fullRange()` | optional, servo only | the servo's whole turn ([full range](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/)), at INIT and in the Hood Finder. Find `posA`/`posB` after you turn it on | the normal range | | `.shotAngles(atA, atB)` | optional | for the simulator: the launcher's shot angle with the hood at `angleA` and at `angleB`. The simulated shot follows the hood servo | - | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.looks(shapes...)` | optional | how it looks in the simulator ([Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)) | a plain box | | `.tunables("Name")` | optional | read another `Tunables` section | the device's name in CamelCase | With a hood, the shot table gets a third column: the hood angle ([Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/)): ```java public static double[][] speedByDistance = {{24, 2200, 4}, {48, 2550, 12}, {72, 2900, 18}}; // Tunables.Launcher ``` The library has no hood on a CR servo with an absolute encoder yet. One can fit the same way: anything that is an [`AngleDevice`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#angledevice) can be a hood of the [plain launcher](https://crossbotics.com/ftc-helper/docs/modules/launcher/#launcher) (`new Launcher(...).hood(myHood)`). ## In Tunables.java The section's name is the device's name in CamelCase (`hood` reads `Hood`, `shooter_hood` reads `ShooterHood`). A servo hood's numbers are in servo positions, a motor hood's in encoder counts. When you write `angleA` and `angleB` (or a `calibration`), "angle" below is your angle, in degrees or any scale you chose. Without them, the angle is the position itself. Every default that says "of the range" fits degrees, positions and counts. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class Hood { // "hood" in the configuration // posA and posB: the servo positions a hair off the hood's two hard stops. Never past them. public static double posA = MEASURE; // servo position at stop A (Hood Finder) public static double posB = MEASURE; // servo position at stop B (Hood Finder) // Optional: the hood's angle at each stop (any scale, e.g. 0 = steep end, 30 = flat end). public static double angleA = MEASURE; // the angle at stop A (an angle app) public static double angleB = MEASURE; // the angle at stop B (an angle app) public static double travelSec = DEFAULT; // stop to stop, seconds (0.5, or the servo's) public static double startAngle = DEFAULT; // where it goes at ▶ (angle A) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `posA` | the position a hair off one hard stop: a hard limit | 0 to 1 / counts | REQUIRED, unless `calibration` | yes, at once | Hood Finder | the hood or its servo was moved | | `posB` | the position a hair off the other hard stop | 0 to 1 / counts | REQUIRED, unless `calibration` | yes, at once | Hood Finder | the same | | `angleA`, `angleB` | the hood's angle at `posA` and `posB` (both, or neither) | your angle unit | none: the angle is the position | no | Hood Finder | you want the table in degrees | | `calibration` | instead of `posA`/`posB`: `{position, angle}` rows for a linkage. The first and last rows are the stops | position, angle | none | no | Hood Finder | the hood is not a straight gear | | `startAngle` | where it goes at ▶ | angle | angle A | no | none | another start angle | | `stepAngle` | one step of `step(n)` | angle | 1/25 of the range | no | none | the drivers want bigger steps | | `byHandPerSec` | the speed with the stick pushed all the way | angle per second | the range in 2.5 s | no | test | the stick is too fast | | `trimMax` | the most hood trim | angle | 1/5 of the range | no | none | you need more trim | | `tolerance` | a motor hood: how close counts as arrived | angle | 1/50 of the range | no | test | the launcher waits too long (more) | | `travelSec` | a servo hood: time from stop to stop (`posA` to `posB`) | seconds | 0.5 (with `.part(...)`: from the servo's catalog speed) | yes, at once | test (time it) | it fires before the hood arrives (more) | | `kP` | a motor hood: power per count off | power per count | 0.005 | yes, at once | test | slow (more) or shakes (less) | | `maxPower` | a motor hood: the most power | 0 to 1 | 0.5 | yes, at once | test | it hits its stops hard | **Calibration.** `posA` and `posB` are the servo positions (encoder ticks for `Hood.motor`) a hair off the hood's two hard stops. They are the hood's **hard limits**: the library keeps every angle (a table row, a trim, a stick) between them. Both must be in `Tunables.java`, or INIT stops. The [Hood Finder](https://crossbotics.com/ftc-helper/docs/tuning/04-hood-finder/) finds them. Then pick one of these: | You write | The hood's "angle" is | The table's third column holds | | --- | --- | --- | | `posA`, `posB` only | the servo position (or ticks) itself: you measure nothing more | servo positions, `{48, 2550, 0.42}` | | `posA`, `posB`, `angleA`, `angleB` | your angle, on a straight line between the two stops (any scale, either way round) | angles, `{48, 2550, 12}` | | `calibration = {{0.20, 0}, {0.32, 8}, {0.45, 18}, {0.65, 30}}` | a linkage or cam: {position, angle} rows, and the library blends between them. The first and last rows are the stops | angles | A servo hood with angles: ```java public static class Hood { // Tunables.java public static double posA = 0.20, posB = 0.65; // a hair off its two stops (Hood Finder) public static double angleA = 0, angleB = 25; // optional: its angle there public static double travelSec = 0.5; // stop to stop (a servo cannot say where it is) } ``` A motor hood never pushes further past a stop. The hood does not move in INIT. It goes to `startAngle` at ▶. ## Commands Use them through the launcher: `robot.launcher.hood().setAngle(12)`. | Command | What it does | | --- | --- | | `setAngle(a)` | goes to an angle (kept inside the stops) | | `goToStart()` | goes to `startAngle` | | `step(n)` | moves `n` x `stepAngle`. While the table sets the angle, this is a trim | | `byHand(stick)` | moves with the stick, every loop | | `trimBy(a)`, `setTrim(a)`, `resetTrim()` | change the hood trim, which the library adds to the table's angle | | Question | What it tells you | | --- | --- | | `angle()` | where it is now: the encoder, or the time estimate (like `Turret.angle()`) | | `targetAngle()` | where it is going | | `isAtTarget()` | whether it is there (a servo: whether it should be there by now) | | `followsTable()` | whether the shot table sets the angle now | | `trim()` | the hood trim | | `minAngle()`, `maxAngle()`, `startAngle()` | its range; its start | | `usesAngles()` | whether `angleA`/`angleB` or `calibration` are written | | `isMotor()`, `isReversed()` | whether it is a motor hood; whether it turns the other way | | `pulseRangeUs()` | `{500, 2500}` with `fullRange()`, or null without it | | `part()` | the [`AngleDevice`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#angledevice) the launcher drives | | `isPresent()` | whether the part is on the robot (an `optional()` part may not be) | **Ready.** The launcher feeds only when the hood has arrived. Until then, its why-not-ready list says "hood". A motor hood knows from its encoder when it is within `tolerance`. A servo hood uses a time estimate: `travelSec` for the whole range, a share of it for a shorter move. The library does not send changes under 1/100 of the range, so a distance that jitters a little does not move the hood. Then the hood never stays "moving". The Driver Station shows `Hood : 12.5 deg (table, trim +1.0 deg)` (`moving` until it should be there). ## Buttons to add A part has **no buttons** until you add its lines to `Controls.java`. These are the usual ones. Copy them, or change the button ([how to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line)). - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. You do not change them. A line on a button gamepad 1 already uses (its sticks, the stick clicks, BACK) stops INIT. INIT names the button: give the line a free one. - **On gamepad 1, with two drivers:** write `g1` and a free button or stick. If you pick a button the library uses, INIT stops and names it. ```java title="Controls.java" g2.leftStickY.use(robot.launcher.hood()::byHand).says("hood angle (up = bigger angle)"); ``` **By hand and the trim.** The usual operator stick is left stick Y: up = a bigger angle. - While the shot table sets the angle, the stick is a **hood trim**. The library adds it to the table's angle, at most +/- `trimMax`. The launcher's double-tap of D-pad down sets it back to 0, and so does every INIT. - With a fixed speed, a table without hood angles, or before the camera has seen the goal, the table does not set the angle. Then the stick moves the hood itself. - The speed trim fixes shots that land short or long. The hood trim fixes shots that arrive at the wrong slope: they bounce off the rim, or worn balls launch flatter. Use the speed trim first. --- **Look it up:** [`Hood` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Hood.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Indexer URL: https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/ ## In Robot.java ```java title="Robot.java" launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed"))); // in a launcher (usual) feeder = add(Indexer.servo("feeder").part("gobilda-2000-speed")); // on its own ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Indexer.servo(name)` | **yes**, one of the three | a servo arm that pushes each piece, then comes back | - | | `Indexer.crServo(name)` | **yes**, one of the three | a CR servo that feeds for `feedSec` per piece | - | | `Indexer.motor(name)` | **yes**, one of the three | a motor that feeds for `feedSec` per piece | - | | `.part(id)` | recommended | which servo or motor it is, from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). The library takes a servo indexer's `pushSec` and `returnSec` from it | `pushSec` 0.25 | | `.reversed()` | optional | it turns the other way | - | | `.alsoServoReversed(name)` | optional, servo or CR servo | a servo indexer: a second arm on the other side. The two pinch together behind the piece and push it in ([two servos on one part](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/)). A CR servo indexer: a second wheel on the other side of the piece. It gets the same power and spins the other way, so the two wheels squeeze the piece in | one servo | | `.alsoServo(name)` | optional, servo or CR servo | a second servo that turns the same way as the first. For two CR servo wheels, use it when one servo is mounted upside down | one servo | | `.fullRange()` | optional, servo only | the servo's whole turn ([full range](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/)). Measure `rest` and `push` again after you turn it on | the normal range | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.looks(shapes...)` | optional | how it looks in the simulator ([Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)) | a plain box | | `.tunables("Name")` | optional | read another `Tunables` section | the device's name in CamelCase | A servo indexer goes to `rest` at ▶. A [feed wheel](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#feed-wheel) is an indexer too: `.feedWheel(Indexer.crServo("feeder_wheel"))` on the launcher. Two CR servo wheels, one on each side of the piece, squeeze it into the launcher: ```java title="Robot.java" // "feeder_left", "feeder_right" = the servos' names in the robot configuration. Numbers: Tunables.FeederLeft. launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.crServo("feeder_left").alsoServoReversed("feeder_right").part("gobilda-2000-speed"))); ``` Both servos get the same `power` for `feedSec`. Test the direction first: set `feedSec` long, fire with no piece, and watch both wheels pull in. If both pull out, add `.reversed()`. If one pulls out, use `.alsoServo(...)` in place of `.alsoServoReversed(...)`. **Stop on the shot.** A fixed `feedSec` must be long enough for the piece that starts farthest back. Then a piece that starts near the flywheel gets too much time, and the wheels can push the next piece in behind it. Set `stopOnShot = true`: each feed stops when the flywheel sees the shot (its speed drops), and `feedSec` is only the time limit. It is for a CR servo or motor feeder only: on a push servo or a feed wheel, INIT stops. It is `boolean`, not `double`: ```java title="Tunables.java" public static class FeederLeft { // "feeder_left" in the configuration: it runs both wheels public static double power = DEFAULT; // wheel power (1) public static double feedSec = DEFAULT; // the most time the wheels run per shot (0.4) public static boolean stopOnShot = true; // stop when the flywheel sees the shot: true or false } ``` - **SPRAY:** the wheels do not stop on a shot. They keep turning from one piece to the next, and each feed runs the full `feedSec`. So in SPRAY the robot feeds one piece each `feedSec`: keep `feedSec` short (near `shotIntervalSec`), not long "to be safe". - **First check that the flywheel sees your shots.** In the [Flywheel Finder](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/), feed 10 pieces, one at a time, and read "Shots seen" and "Shot drop". If "Shots seen" shows fewer than 10, set `shotDropRpm` in the [launcher's Tunables](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) to about half the smallest shot drop. - **Then check for false shots.** Fire with no piece: the wheels must run the full `feedSec`. If they stop early, the robot saw a shot that was not there: make `shotDropRpm` bigger. - If no number passes both checks, leave `stopOnShot` off and tune `feedSec`. **Find `feedSec`.** The [Feed Time Finder](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-time-finder/) in Tune and check fires test shots, times each piece to the shot, and gives `feedSec` from the longest. Fire 5 or more, from every place a piece can sit. Add `.feedWheelOutWith(intake)` to the launcher to run both wheels backward while the intake pushes out. Then the pieces in the feeder come out too ([Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/)). ## In Tunables.java The section's name is the device's name in CamelCase: `Indexer.servo("feeder")` reads **`Feeder`**, `windmill` reads `Windmill` (not `Indexer`). **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). A servo indexer: ```java title="Tunables.java" public static class Indexer { // "indexer" in the configuration public static double rest = MEASURE; // servo position, out of the way (Servo Finder) public static double push = MEASURE; // servo position, piece pushed (Servo Finder) public static double pushSec = DEFAULT; // time to push (0.25, or the servo's speed) public static double returnSec = DEFAULT; // time to come back (the same as pushSec) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `rest` | a servo indexer: where it waits | 0 to 1 | 0.0 | yes, at once | Servo Finder | it blocks the pieces | | `push` | a servo indexer: where it pushes a piece into the wheel | 0 to 1 | 0.5 | yes, at once | Servo Finder | it does not push pieces far enough | | `pushStep` | a servo indexer: one step of `adjustPush(...)` (a D-pad trim of `push` in TeleOp) | servo position | 0.01 | yes, at once | test | a step is too big or too small | | `pushSec` | a servo indexer: time to push | seconds | 0.25 (with `.part(...)`: the servo's catalog time from `rest` to `push`, at least 0.25) | yes, at once | test | it comes back before the piece is gone (more) | | `alsoTrim` | a servo indexer with a second servo (`alsoServoReversed`): a raw position the library adds for it, so the two arms meet. Not for two CR servo wheels (INIT stops) | raw position, -0.2 to 0.2 | 0 | yes, at the next move | test: watch both arms | one arm pushes further than the other | | `returnSec` | a servo indexer: time to come back | seconds | 0.25 (with `.part(...)`: the same as `pushSec`) | yes, at once | test | the next piece jams on it (more) | | `power` | a motor or CR servo indexer: power while it feeds (- = the other way; to change the direction, use `.reversed()`: the simulator feeds only on + power) | -1 to 1 | 1.0 | yes, at once | test | it feeds pieces too hard or too softly | | `feedSec` | a motor or CR servo indexer: time for one piece. With `stopOnShot`: the time limit | seconds | 0.4 | yes, at once | Feed Time Finder (in a launcher) | it feeds two (less) or none (more) | | `stopOnShot` | a motor or CR servo indexer: true = each feed stops when the flywheel sees the shot (its speed drops), and `feedSec` is only the time limit. Not in SPRAY: there the wheels keep turning. Not for a feed wheel | true / false | false | no (at INIT) | test: Flywheel Finder, "Shots seen" | it feeds two pieces at once, and the pieces start in different places (true) | | `alwaysOn` | a feed wheel (`Launcher.feedWheel(...)`): true = it runs all the time the launcher is spun up (not while it idles); false = only while firing | true / false | false | no (at INIT) | test | the pieces wait too long for the wheel (true) or it uses battery for nothing (false) | | `stageSec` | a feed wheel, only while firing: it runs this long before the arm pushes (the piece gets to the arm; with a feed stop, the arm also waits for it to open) | seconds | 0.2 | yes, at once | test | the arm pushes before the piece is there (more) | | `stopSec` | a feed wheel, only while firing: it stops this long after the arm starts to push. Below 0 = before the push; 0 = as the push starts | seconds, -2 to 2 | 0.3 | yes, at once | test | it pushes the next piece in behind (less) or the piece stops on the arm (more) | ## Commands Use them in `Controls.java`, `Actions.java` and autos: `robot.feeder.feedOne()`. In a launcher, use the launcher's `fire()` instead: the launcher runs its indexer. | Command | What it does | | --- | --- | | `feedOne()` | feeds one piece | | `clearJam()` | clears a jam | | `adjustPush(steps)` | a servo indexer: moves `push` by steps x `pushStep` (a D-pad trim in TeleOp) | | `onFeed(runnable)` | runs your code each time a feed really starts | | `stop()` | stops | | Question | What it tells you | | --- | --- | | `isBusy()` | whether it still moves: a feed, or the arm coming back | | `isFeeding()` | whether a feed runs: true from its start until it ends (normally, jammed or stopped) | | `isJammed()` | whether it is jammed | | `pushNow()` | the `push` position in use (with the trim) | | `isServo()`, `isReversed()` | whether it is a servo indexer; whether it turns the other way | | `secondServoName()` | the second servo's name | | `isPresent()` | whether the part is on the robot (an `optional()` part may not be) | **With [Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/):** the counter counts the piece out only once it has gone: its ready sensor sees it leave, or the feed ends without a jam. When a feed stops part way or jams, the count stays as it was. ## Buttons to add An indexer in a launcher needs no button: the launcher's RB feeds. An indexer on its own needs a line in `Controls.java`: - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. You do not change them. - **On gamepad 1, with two drivers:** write `g1` and a free button, for example `g1.rb`. Gamepad 1's LT is slow mode, so do not use it. If you pick a button the library uses, INIT stops and names it. ([How to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line).) ```java title="Controls.java" g2.rb.press(robot.feeder::feedOne).says("feed one"); // an indexer on its own, not in a launcher ``` --- **Look it up:** [`Indexer` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Indexer.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Intake URL: https://crossbotics.com/ftc-helper/docs/reference/parts/intake/ ## In Robot.java ```java title="Robot.java" intake = add(Intake.motor("intake").part("gobilda-5203-1150")); intake = add(Intake.motor("intake").part("gobilda-5203-1150").onAtStart()); intake = add(Intake.crServos("intake", "intake_right").part("gobilda-2000-speed").reversed("intake_right")); intake = add(Intake.motor("intake").part("gobilda-5203-117") .withCrServos("left_wheel", "right_wheel").reversed("right_wheel")); ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Intake.motor(name)` | **yes**, one of the two | an intake on one motor | - | | `Intake.crServos(names...)` | **yes**, one of the two | an intake on CR servos that run together | - | | `.part(id)` | recommended | which motor or servo it is, from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) | the simulator guesses its speed | | `.holds(n)` | recommended | how many pieces it carries. Count them by hand: load pieces until no more fit | 4 (the simulator's guess) | | `.withCrServos(names...)` | optional | CR servos that run with the motor, like side wheels next to a roller | - | | `.reversed(names...)` | optional | these devices run the other way, like the second of two facing servos | all run the same way | | `.reversed()` | optional | the whole intake runs the other way | - | | `.holds(n, "KIND")` | optional | how many of one kind it carries. 0 = it cannot take that kind | every kind counts the same | | `.onAtStart()` | optional | runs in from ▶ until your code stops it | off: a button starts it | | `.stopsWhen(test)` | optional | never runs in while the test is true, like "the robot is full" ([Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/)). Pushing out still works | it runs whenever asked | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.looks(shapes...)` | optional | how it looks in the simulator ([Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)) | a plain box | | `.tunables("Name")` | optional | read another `Tunables` section | the device's name in CamelCase | **About `holds`:** - The simulator uses it, and so does [Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/): the robot is "full" at this number. - INIT warns when it is above the game's limit. BIOBUZZ: no more than 4 at a time (G407). - The simulator takes as many as you write, also above the limit. Then it gives the G407 foul: 6 at once, or 5 for more than 3 s twice ([the simulator's rules](https://crossbotics.com/ftc-helper/docs/guides/how-the-simulator-works/#game-rules-and-the-score)). - It does not stop the real intake by itself. To stop at a count, use [Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/) and `.stopsWhen(...)` ([cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/05-game-pieces/#how-do-i-stop-the-intake-when-the-robot-is-full)). - A name matches every kind that has it in its name: "NECTAR" is red and blue NECTAR. - With `holds(n)` too, it is a mix: `.holds(4).holds(1, "NECTAR")` = 4 pieces, at most 1 NECTAR. - goBILDA's starter bot cannot take a NECTAR: `.holds(4).holds(0, "NECTAR")`. ## In Tunables.java The section's name is the device's name in CamelCase: `intake` reads `Intake`, `front_roller` reads `FrontRoller`. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class Intake { // "intake" in the configuration public static double inPower = DEFAULT; // power taking pieces in, 0 to 1 (1.0) public static double outPower = DEFAULT; // power pushing pieces out (0.7) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `inPower` | power while it takes pieces in | 0 to 1 | 1.0 | yes, at once | test | it throws pieces, or they jam (less) | | `outPower` | power while it pushes pieces out | 0 to 1 | 0.7 | yes, at once | test | pieces do not come out (more) | ## Commands Use them in `Controls.java`, `Actions.java` and autos: `robot.intake.in()`. | Command | What it does | | --- | --- | | `in()` | runs in until you stop it | | `out()` | pushes out until you stop it | | `stop()` | stops | | `toggle()` | on or off | | `reverse()`, `endReverse()` | pushes out while the driver holds a button, then goes back to what it was doing | | `holdIn()` | in while the driver holds a button. With `stopsWhen`: hold it 1 s = in anyway. For `g2.rt.hold(robot.intake::holdIn, robot.intake::stop)` | | `inAnyway()` | runs in even though `stopsWhen` says no, until `stop()` or `out()`. Use it when the count is wrong | | `inOn(button)`, `outOn(button)` | put "in" and "out" on a button the right way for this intake ([Buttons to add](#buttons-to-add)) | | Question | What it tells you | | --- | --- | | `isRunning()` | whether it runs, in or out | | `isPushingOut()` | whether it pushes out now: `out()`, or a held `reverse()` | | `isHeldBack()`, `heldBackSec()` | whether `stopsWhen` keeps it from running in, and for how many seconds | | `holdsInAll()` | the `holds(n)` number | | `limitFor("KIND")` | how many of that kind it can carry | | `isPresent()` | whether the part is on the robot (an `optional()` part may not be) | In an auto: `.run("Intake in", robot.intake::in)` ([what an auto can do](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/)). ## Buttons to add A part has **no buttons** until you add its lines to `Controls.java`. These are the usual ones. Copy them, or change the button ([how to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line)). - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. You do not change them. - **On gamepad 1, with two drivers:** write `g1` and a free button, for example `g1.rb`. Gamepad 1's LT is slow mode, so do not use it. If you pick a button the library uses, INIT stops and names it. ```java title="Controls.java" robot.intake.inOn(g2.rt); robot.intake.outOn(g2.lt); ``` | Your Robot.java | `inOn(g2.rt)` does | `outOn(g2.lt)` does | | --- | --- | --- | | plain | in while held | out while held | | `.onAtStart()` | a press switches it on and off | out while held | | `.stopsWhen(...)` | in while held; held 1 s = in anyway | out while held | | both | a press switches; held 1 s = in anyway | out while held | With `stopsWhen`, the Driver Station warns when `stopsWhen` has kept the intake from running in for more than 2 s. So the drivers notice when the count says "full" too soon. --- **Look it up:** [`Intake` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Intake.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Interlock URL: https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/ A rule that keeps two parts apart. Two parts that share space (a turret over the back and a lift at the back; an arm and an intake) must never be in their zones at the same time. You write one line in `Robot.java` and the numbers in `Tunables.java`. The library checks the rule every loop, whoever moves the parts. Learn it with examples: [Two parts that must not collide](https://crossbotics.com/ftc-helper/docs/guides/interlocks/). ## In Robot.java ```java title="Robot.java" // Robot.java, after the parts: turretLift = keepApart("TurretLift", turret.zone(), lift.zoneAbove()); ``` `keepApart(name, zone, zone)` makes the rule. The name is its `Tunables` section. Write it after the two parts. | Zone | What it is | Its Tunables fields (in the rule's section) | | --- | --- | --- | | `part.zone()` | between two numbers (a turret's repeats every 360 degrees) | `From`, `To` | | `part.zoneAbove()` | from there to the top | `Above` | | `part.zoneBelow()` | from there to the bottom | `Below` | | `Zone.when(words, condition)` | a condition for something the library cannot move (your own sensor) | none | - Parts with a zone: [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/), [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/), [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/), [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/), [Wrist](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/), [Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/), [Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/). - A rule with a part that is not on the robot yet ([`optional()`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) is off: `Interlock TurretLift: off (Lift is not on the robot)`. It then does nothing and needs no Tunables. ## In Tunables.java The section's name is the rule's name: `keepApart("TurretLift", turret.zone(), lift.zoneAbove())` reads `TurretLift`. - `` is the part's section name (its device's name in CamelCase) with a small first letter: `Turret` -> `turretFrom`. - `LiftLeft` (device `lift_left`) -> `liftLeftAbove`, not `liftAbove`. INIT stops on it and says "did you mean liftLeftAbove?". - Each part's own units: degrees (turret, arm), counts (lift), servo position 0 to 1 (claw, wrist, positioner). - The rule reads them once, at INIT. They are never in the tuning menu: a zone that changed while the parts move could let them hit. **Copy into `Tunables.java`.** The section's name is the rule's name. Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" // The rule's own section, named like the rule in Robot.java. Each zone in its part's units. public static class TurretLift { // keepApart("TurretLift", ...) in Robot.java public static double turretFrom = MEASURE; // degrees: where the turret's zone starts public static double turretTo = MEASURE; // degrees: where it ends (robot's back) public static double liftAbove = MEASURE; // counts: the slide is up from here public static double liftStopSec = 0.2; // a heavy slide takes longer to stop (0.15) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `From`, `To` | `part.zone()`: the zone between two numbers | the part's units | REQUIRED with `zone()` | no | measure: move the part by hand to the edges | the parts or their places changed | | `Above` | `part.zoneAbove()`: the zone from there to the top | the part's units | REQUIRED with `zoneAbove()` | no | measure | the same | | `Below` | `part.zoneBelow()`: the zone from there to the bottom | the part's units | REQUIRED with `zoneBelow()` | no | measure | the same | | `Margin` | the extra safety distance around the zone (the stop distance already covers coasting) | the part's units | turret: the larger of 3 deg and 2 x its `tolerance`; lift, arm: the larger of 2 x its `tolerance` and 1/50 of its range; hood: 1/50 of its range; claw, wrist, positioner: 0.02 | no | test | the parts come too close (more) | | `StopSec` | a turret, lift or arm: how long it takes to stop from full speed once its power is cut. Its stop distance is its speed x (2 x the slowest of the last 25 loops + half this) ([interlocks](https://crossbotics.com/ftc-helper/docs/guides/interlocks/)) | seconds, 0 to 2 | 0.15 | no | test: full stick toward the zone, see where it stops | it still ends up past its waiting point (more), or it waits too far out (less) | **INIT lists each rule.** It stops, and gives the reason, for: - a missing section or number, - an empty zone, - a zone outside the part's range, or one that covers all of it, - a negative margin, - a `StopSec` outside 0 to 2 s, - a part with no position. ## How it works **Who yields:** - **Whoever is in its zone first keeps it. The other part waits outside its own zone**, two margins away, with its target kept. It goes on when the first one leaves. - When both want in at once, the first zone in `keepApart` goes first. But if one moves too fast to stop before its zone, that one goes first. - When both are in their zones (pushed there, or found there at ▶), each may only move out. **Stop distance:** - Every loop the rule measures each motor part's speed (its encoder). It works out how far the part would still go if told to stop now: speed x (2 x the slowest of the last 25 loops + half its `StopSec`). - A part kept out may only use the power that lets it stop in time. So it slows down as it comes near its waiting point, and brakes when it must, even with slow loops (a camera, a busy hub). - The margin is extra safety on top. - A servo needs none: the rule never sends it past the fence (the zone's edge). **More rules:** - A turret whose way to its target crosses its zone goes the other way round if its range allows (a slip ring, or -270 to 270). If not, it waits at the edge. - When the rule does not know a part's position, it counts the part as in its zone. For example: a turret not homed yet, or a servo still moving. A moving servo counts as anywhere between where it was and where it was sent, until its `travelSec` is over. - Every command goes through it: buttons, sticks, actions, autonomous steps, a following turret, shooting on the move. - A held turret is never `isAimed()`. **On the Driver Station:** one line per rule while it holds something. - `TurretLift : Lift held at 110 counts: Turret is between 130 and 218 deg` - Held because the other part's position is not known: `TurretLift : Lift held at 110 counts: Turret angle unknown (not homed yet)` ## Commands An interlock has no commands. You can ask it these questions: | Question | What it tells you | | --- | --- | | `name()` | the rule's name (its Tunables section) | | `isHolding()` | whether a part is held back now | | `status()` | the Driver Station line ("" when nothing is held) | | `words()` | the rule in words: `Turret between 130 and 218 deg / Lift above 270 counts` | | `isOff()` | whether one of its parts is not on the robot ([`optional()`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)). Then the rule does nothing and needs no Tunables | | `Zone.part()` | the zone's part (null for a condition) | | `Zone.words()` | the zone in words | An interlock has no buttons. --- **Look it up:** [`Interlock` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Interlock.html) and [`Zone`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Zone.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Launcher URL: https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/ A flywheel that shoots game pieces, and the [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/) that feeds it one piece at a time. It can also have a [Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/), a feed stop, a feed wheel, and parts that push the pieces in. Learn it step by step: [Robot.java, add a part](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#launcher). ## In Robot.java ```java title="Robot.java" launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed"))); launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .speedFromDistance(camera).requireReady("turret aimed", () -> turret.isAimed())); ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Launcher.flywheel(motor, id)` | **yes** | a flywheel on this motor. The id is the motor's catalog id: the library needs it for the speed in RPM | - | | `.feeder(Indexer.servo(name))` | recommended, one of the three | a servo arm pushes each piece in ([Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/)) | nothing feeds the wheel | | `.feeder(Indexer.crServo(name))` | recommended, one of the three | a CR servo wheel feeds the pieces, like goBILDA's "windmill" | nothing feeds the wheel | | `.feeder(Indexer.motor(name))` | recommended, one of the three | a motor feeds the pieces | nothing feeds the wheel | | `.reversed()` | optional | the flywheel turns the other way | - | | `.speedFromDistance(camera)` | optional | the launcher sets the speed from the camera's distance to the goal. With odometry and `Tunables.Aim.goalX, goalY`, it uses the odometry's distance while the camera does not see the goal ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)) | one speed, `speedRpm` | | `.speedFromOdometry()` | optional | the launcher sets the speed from the odometry's distance only (no camera) | one speed, `speedRpm` | | `.requireReady(what, check)` | optional | one more check before each feed, for example "the turret is aimed" | - | | `.spinAtStart()`, `.spinAtStart(on)` | optional | spins up at ▶ (autonomous and TeleOp), ready for the first shot. `spinAtStart(false)` waits for LB. `spinAtStart` in Tunables wins over both | on with a separate feeder (an indexer or a feed stop): a spinning wheel cannot throw a piece the feeder has not pushed in. Else off | | `.hood(Hood)` | optional | the launcher's [hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/). The launcher takes its angle from the shot table's third column, and waits for it before it feeds | no hood | | `.feedStop(servo)` | optional | a [feed stop](#feed-stop): a servo that holds the pieces back until a shot is allowed | no feed stop | | `.feedStop(servo, part)` | optional | the same, with the servo's catalog id (`"gobilda-2000-speed"`). The Feed Stop Finder then works out `feedStopMoveSec` | no part: the finder cannot work out the open time | | `.pushedBy(intake...)` | optional | the parts that push a piece into the wheel, in order ([piece path](#piece-path)). Add the intake **before** the launcher | nothing pushes | | `.feedWheel(Indexer)` | optional | a [feed wheel](#feed-wheel): a CR servo or motor that moves each piece up to the `feeder` (a push arm). It needs `.feeder(...)` too | no feed wheel | | `.feedWheelOutWith(intake)` | optional | the feed wheel runs backward while that intake pushes out (`out()`), so the pieces in the feeder come out too. A shot that is being fed wins. It needs `.feedWheel(...)`, or a feeder that spins (`Indexer.crServo` or `Indexer.motor`): with no feed wheel, the feeder itself runs backward | - | | `.startTable(name)` | optional | the shot table at the start | the plain `speedByDistance` (named `main`, shown as `MAIN`), if there is one. Else the first by name: `nectar` before `pollen` | | `.tableFrom(() -> name)` | optional | code (a game-piece sensor) picks the table. Each time its answer changes to a table's name, the launcher uses that table. null, "NONE" and "UNKNOWN" change nothing | the drivers pick the table | | `.tableFor(table, kinds...)` | optional | which table some game-piece kinds use, for example `.tableFor("nectar", "RED_NECTAR", "BLUE_NECTAR")`. A kind named like a table ("POLLEN") needs no line | - | | `.shotAngle(deg)` | optional | for the simulator: which way a piece leaves, in degrees up from the wheel shape's forward. For a wheel mounted level, that is the robot's forward. 135 = up and out of the back | - | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.looks(shapes...)` | optional | how it looks in the simulator ([Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)) | a plain box | | `.tunables("Name")` | optional | read another `Tunables` section | the motor's name in CamelCase | For a motor not in the catalog, use `Motors.custom(...)` ([Parts not in the catalog](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-in-the-catalog)). ## In Tunables.java The section's name is the flywheel motor's name in CamelCase: a launcher on the motor `launcher` reads `Launcher`, one on `shooter` reads **`Shooter`** (not `Launcher`). Its feeder has its own section: a feeder on `feeder` reads `Feeder` ([Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/)). **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it. A few lines have example numbers ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class Launcher { // "launcher" in the configuration public static double speedRpm = DEFAULT; // shot speed without the table (60% of top) public static double stepRpm = DEFAULT; // speed change per D-pad press (100) public static double readyBandRpm = DEFAULT; // "at speed" = this close to the target (60) public static double idleRpm = 1500; // spins between shots: quicker first shot (0) public static double shotIntervalSec = DEFAULT; // least time between two pieces (0.25) // The hub's speed control: the defaults for the motor until the Flywheel Finder (INIT shows them). // Then write the Finder's numbers in their place. public static double kP = DEFAULT; // push per speed error (kF / 10) public static double kI = DEFAULT; // fix a steady error (kP / 10) public static double kD = DEFAULT; // brake changes (0) public static double kF = DEFAULT; // steady power for a speed (from the motor) // {inches to the goal, RPM}, blended between rows. Example rows: write the Shot Tuner's instead. public static double[][] speedByDistance = {{24, 2200}, {48, 2550}, {72, 2900}, {96, 3250}}; } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `speedRpm` | the shot speed when no shot table sets it. At most the motor's top speed | RPM | from the parts catalog: 60% of the motor's top speed, to 10 RPM (6000 RPM motor: 3600) | yes, at once | Shot Tuner or test | shots land short or long | | `stepRpm` | one D-pad press changes a fixed speed by this | RPM | 100 | yes, at once | none | the drivers want bigger or smaller steps | | `readyBandRpm` | "at speed" means within this of the target | RPM | 60 | no | test | it waits too long to fire (more) or shots vary (less) | | `shotDropRpm` | a drop of more than this after "at speed" counts as a shot: the Shot Tuner's shot count, `stopOnShot`, the feed stop and the Feed Stop Finder's test shot use it. Keep it more than `readyBandRpm`: at or under it, INIT shows a note, because the wheel's normal wobble can count as a shot | RPM | 150 | no (at INIT) | Flywheel Finder ("Shots seen" and "Shot drop") | it misses shots (less) or counts shots with no piece (more) | | `idleRpm` | the speed between shots (0 = stop) | RPM | 0 | no | test | the first shot takes too long to spin up | | `shotIntervalSec` | the least time between two shots | seconds | 0.25 | no | Flywheel Finder (the recovery) | quick shots land short (more) | | `maxFiringQueue` | a tap on RB or `fire()`: the most shots that may wait at once. The launcher ignores more taps. The piece being fed now does not count. 0 = no queue: the launcher ignores a press while a shot is on its way (waiting or being fed). `fire(n)` and actions have no limit | shots | 4 | no | none | taps fire more (or fewer) shots than the drivers mean (0: one press, one shot) | | `speedByDistance` | the shot table: rows of `{inches, rpm}`, or `{inches, rpm, hood}` with a [hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/). The launcher blends between rows | inches, RPM | none: `speedRpm` | no | Shot Tuner | the field, the balls or the wheel changed | | `speedByDistance` | one more table per game piece, e.g. `speedByDistancePollen` (its name is "pollen") | inches, RPM | none | no | Shot Tuner | pieces fly differently | | `kP` | the hub's speed control: push per speed error | hub units | from the parts catalog: kF / 10 (6000 RPM motor: 1.17) | no | Flywheel Finder | after the Flywheel Finder | | `kI` | the hub's speed control: slow fix of a steady error | hub units | from the parts catalog: kP / 10 (6000 RPM motor: 0.117) | no | Flywheel Finder | the same | | `kD` | the hub's speed control: brakes changes | hub units | 0 | no | Flywheel Finder | the same | | `kF` | the hub's speed control: the steady power for a speed | hub units | from the parts catalog: 32767 / the motor's top speed in counts per second (6000 RPM motor: 11.7) | no | Flywheel Finder | the same | | `nominalVolts` | the battery voltage the gains were found at (battery compensation), 9 to 14 | volts | 12.8 (INIT notes that it assumes this) | no | Flywheel Finder | after the Flywheel Finder | | `batteryCompensation` | with a written `kF`: scales F by the battery voltage (nobody has proven it on a real robot yet). Without your own `kF` it stays off, with a note | true/false | false | no | none | to try it: `true`, then the 4-shot test ([below](#speed-trim-and-battery-compensation)) | | `trimStepPercent` | one speed trim step | percent | 1 | no | none | the drivers want bigger steps | | `trimMaxPercent` | the most speed trim, at most 50 | percent | 15 | no | none | you need more trim (better: fix the table) | | `redTrimPercent` | makes every shot speed this much faster on the RED alliance (the field halves differ a little) | percent | 0 | no | test, at an event | shots on one half land short or long | | `blueTrimPercent` | the same on the BLUE alliance | percent | 0 | no | test, at an event | the same | | `quickBandRpm` | QUICK mode: after a volley's first piece, the launcher feeds within this of the speed | RPM | 3 x `readyBandRpm` | no | firing stats (the drop) | QUICK shots land short (less) or it waits too long (more) | | `quickMaxWaitSec` | QUICK mode: after a volley's first piece, the launcher feeds after this wait at most | seconds | 0.3 | no | firing stats (the recovery) | the same | | `sprayEnabled` | allows SPRAY: no wait for the speed, at the end of TeleOp and when QUICK will not fit before the park in autonomous | true/false | false | no | none | the drivers want it | | `sprayLastSec` | with `sprayEnabled`: the last seconds of TeleOp that SPRAY (0 = never by itself) | seconds | 5 | no | none | the drivers want more or less | | `sprayOnTapHold` | with `sprayEnabled`: a tap, then a hold of the fire button sprays while held | true/false | true | no | none | the drivers spray by accident (false) | | `spinAtStart` | spins the wheel up at ▶, so it is at speed for the first shot. Wins over `spinAtStart(...)` in `Robot.java` | true/false | true with a separate feeder (an indexer or a feed stop), else false | no | none | save the battery (false), or a robot without a feeder of its own whose drivers want it (true) | | `fallbackDistanceIn` | with the speed from the distance: the distance to use before the camera has seen any goal | inches | none: `speedRpm` | no | none | the first shot of the match has no goal in view | | `distanceMedianOf` | with the speed from the camera's distance: the launcher uses the middle of this many pictures, so one or two bad pictures never change the speed ([DistanceFilter](https://crossbotics.com/ftc-helper/docs/modules/vision/#distancefilter)); 1 = off | pictures, 1-15 | 5 | no | none | the speed follows the distance too slowly (lower), or glitches still get through (higher) | | `distanceJumpIn` | a distance change bigger than this needs 3 pictures that agree before the launcher uses it (except after the goal was out of view for 0.5 s); 0 = no jump check | inches | 12 | no | none | real moves are held back (higher), or glitch runs get through (lower) | | `distanceJumpAgreeIn` | for the jump check: how close each of the 3 pictures must be to the one before | inches | 4 | no | none | a real jump is never used: the camera's numbers jump about more (higher) | | `distanceSmoothSec` | with the speed from the camera's distance: the speed eases into each new camera distance over about this time (the odometry's is used at once), so small moves of the camera's distance do not restart "ready". The cost: while the robot drives toward or away from the goal, the speed lags (at 10 in/s and 0.3 s, about 3 in behind) | seconds, 0-3 | 0 (off) | no | test | firing waits while the camera's distance wobbles (0.2 to 0.3), or shots fired on the move land long or short (less) | | `feedStopHold` | with `.feedStop(...)`: the servo position that holds the pieces back | servo position 0-1 | 0 (a guess, INIT says so) | no | Feed Stop Finder | after the Feed Stop Finder | | `feedStopRelease` | with `.feedStop(...)`: the servo position that lets a piece through | servo position 0-1 | 0.5 (a guess) | no | Feed Stop Finder | the same | | `feedStopMoveSec` | with `.feedStop(...)`: how long it takes to open; the indexer and the pushing parts wait this long | seconds | 0.1 | no | Feed Stop Finder (with the servo's part) | a slow servo is still part-closed when the piece comes (more) | | `feedStopOpenSec` | with `.feedStop(...)`: the backup time it stays open when the wheel sees no shot | seconds | 0.5 | no | Feed Stop Finder (test shots) | pieces get stuck (more) | | `assistSec` | with `.pushedBy(...)`: how long the parts push each piece in, at most (less when the wheel sees the shot) | seconds | 0.25 | no | test | pieces do not reach the wheel (more) | | `ejectRpm` | `ejectAction()`: the low speed that pushes one piece out | RPM | 600 | no | test | the piece does not clear the robot (more) or flies too far (less) | | `ejectSec` | `ejectAction()`: how long the eject lasts | seconds | 1 | no | test | the piece is still in the robot at the end (more) | | `ejectFeedSec` | `ejectAction()` with a spinning feeder (CR servo or motor): it runs only this long, so it pushes one piece and not the next one too; 0 = its own `feedSec` | seconds | 0 | no | test | two pieces come out (less), or none does (more) | | `lockSpeedWhileFiring` | with the speed from the distance: while a tapped shot (CAREFUL) waits for "ready" and feeds, its speed stays fixed. The camera's distance can still move then, but it does not move that shot's speed or restart "ready"; `Shot distance` shows the distance the shot uses. It lets go if the distance moves more than 4 in (the robot drove: the old speed would miss). A held stream (QUICK) and SPRAY keep following the distance | true/false | false | no | none | firing waits, or a shot's speed changes while it waits (true) | **The shot table** (`speedByDistance`): - Rows are `{inches, rpm}`. The launcher blends the speed between rows. With no goal in view, it keeps the last speed. - The camera's distance goes through a [glitch filter](https://crossbotics.com/ftc-helper/docs/modules/vision/#distancefilter) first: `distanceMedianOf`, `distanceJumpIn`, `distanceJumpAgreeIn`. With `distanceSmoothSec` (off by default), the speed then eases into each new camera distance. Why: on a steep part of the table, a 1 in wobble of the camera's distance changes the speed by more than half the ready band, and "ready" starts again. Eased, the speed moves in small steps the wheel follows, so it stays ready. With no goal in view it holds the last speed; a new sighting after 0.5 s comes in at once. - One table per game piece: `speedByDistancePollen`, `speedByDistanceNectar`. Any name after `speedByDistance` works. - With a [hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/), a row is `{inches, rpm, hood}`. The launcher blends the hood between rows like the speed. Rows with two numbers still work: then you set the hood by hand. ```java public static double[][] speedByDistancePollen = {{24, 2200}, {48, 2550}, {72, 2900}}; // Tunables.Launcher public static double[][] speedByDistanceNectar = {{24, 2400}, {48, 2800}, {72, 3200}}; // a button: g2.x.press(() -> robot.launcher.useTable("nectar")); an action: .then(() -> r.launcher.useTable("nectar")) ``` The Driver Station shows `Shot table: POLLEN, 48 in (camera)`. In place of `camera` it says `odometry`, or `last seen` while it sees no goal. With one table, it shows `Shot distance: 48 in (camera)`. **The first run** ([First run](https://crossbotics.com/ftc-helper/docs/reference/tunables/#first-run-what-you-get-before-tuning)): - `kP`, `kI`, `kD` and `kF` are the hub's speed control. The [Flywheel Finder](https://crossbotics.com/ftc-helper/docs/tuning/) finds them, and `nominalVolts`, the battery voltage they were found at. - The library starts the ones you do not write from the parts catalog, for the motor in `Launcher.flywheel(...)`. It does not use the hub's own gains. F = 32767 / its top speed in counts per second, P = F / 10, I = P / 10, D = 0. A 6000 RPM motor gets kF 11.7, kP 1.17, kI 0.117. - When you do not write `speedRpm`, it is 60% of the motor's top speed (3600). - INIT says `Starting gains (worked out, not tuned): Launcher` until you write your own (the Flywheel Finder). The robot log has the values: `Launcher: defaults from the catalog (gobilda-5203-6000): kF 11.7, kP 1.17, kI 0.117, speed 3600 rpm. Run the Flywheel Finder, then the Shot Tuner`. - A written number always wins. `DEFAULT` in place of a number is the same as no line. ## Commands Use them in `Controls.java`, `Actions.java` and autos: `robot.launcher.fire()`. | Command | What it does | | --- | --- | | `spinUp()` | spins up to the shot speed | | `idle()` | goes back to `idleRpm` | | `toggle()` | spins up, or goes back to idle | | `fire()` | spins up if needed, and feeds as soon as it is at speed. It gives up after 3 s and says why. Each `fire()` adds one shot, up to `maxFiringQueue` waiting (Tunables, default 4). The launcher ignores more taps. With `maxFiringQueue = 0` there is no queue: the launcher ignores a press while a shot is on its way. A press of RB counts the same way | | `fire(n)` | fires n pieces. No limit | | - | When it fires while idle (the driver switched the wheel off), it spins up for the shots and goes back to idle after the last one | | `fireWhileHeld()`, `ceaseFire()` | the launcher's RB job. Every press fires at once, like a tap on `fire()` (one more shot, up to `maxFiringQueue`). While held, it feeds the next piece as soon as the last is fed (QUICK). A tap, then a second press within `Buttons.tapGapSec` that is held, sprays while held (SPRAY, with `sprayEnabled` and `sprayOnTapHold`). On release, the hold adds no more shots, and the taps' shots still go. When you put your own double tap or long press on the same button, a press no longer fires at once | | `fireAction(n)`, `fireAllAction()` | ready-made [actions](https://crossbotics.com/ftc-helper/docs/reference/steps/#action): fire n pieces ("Fire 2"), or every piece the robot holds ("Fire all": a `Pieces` part's count, else the intake's `holds(...)`, else 4). It is done when the last one has left. Its time limit is 3 s + 2 s a piece. `.action(robot.launcher.fireAction(1))` in an autonomous, `g1.y.press(robot.launcher.fireAllAction())` in TeleOp. It runs only the launcher: the intake keeps doing what it does | | `fireAction(n, rpm)`, `fireAllAction(rpm)` | the same, at this flywheel speed (RPM), then back to the usual one (`speedRpm` or the shot table). A stopped action goes back too. For a robot with **no camera** that shoots from a spot it knows: `.action(robot.launcher.fireAllAction(2250))`. The auto builder's **flywheel** box on a fire action writes it. A speed above the motor's top speed stops INIT | | `readyAction(timeoutSec)` | a ready-made action: spins up, and is done when ready ("Ready to launch") | | `ejectAction()`, `eject()` | pushes one piece out at a low speed (`ejectRpm` 600, `ejectSec` 1) ("Eject"). It feeds once the wheel is near that speed (a wheel at shooting speed slows first). Then the wheel goes back to what it was doing | | `useSpeed(rpm)`, `useNormalSpeed()` | uses one speed from now on (the speed trim still applies) until `useNormalSpeed()`. For most code, the fire actions above are better: they go back by themselves | | `adjust(steps)` | changes the speed by +/- steps x `stepRpm` (not saved) | | `step(direction)` | the launcher's own D-pad job: one step (+1 / -1). With a shot table it changes the trim, else the speed by `stepRpm` | | `repeatStep(direction)`, `repeatEnd()` | while held: a step after 0.5 s, then 4 a second, and `repeatEnd()` on release (`g2.dpadUp.hold(() -> robot.launcher.repeatStep(1), robot.launcher::repeatEnd)`) | | `trimBy(change)`, `setTrim(percent)`, `resetTrim()` | changes the [speed trim](#speed-trim-and-battery-compensation): every shot speed (table or fixed) +/- that many percent, for example `trimBy(+2)`. The launcher keeps it within +/- `trimMaxPercent` and the motor's top speed. `resetTrim()` also clears `adjust` | | `useLastTrim()` | uses the trim from last time (a double-tap of D-pad up does this). The launcher never applies it by itself | | `useTable(name)`, `nextTable()` | picks the shot table to use ("pollen" for `speedByDistancePollen`; capitals do not matter); picks the next one. With a name that has no table, it warns and keeps the one in use | | `shotMode(mode)` | sets the [shot mode](#firing-shot-modes-feed-stop-piece-path) by hand: `ShotMode.CAREFUL`, `QUICK`, `SPRAY`. `null` = the launcher chooses (the default) | | `fireOn(button)`, `spinOn(button)` | in `Controls.java`: puts RB's whole fire job (or LB's spin up / down) on another button, for example `robot.launcher.fireOn(g2.y)`. `null` = no button. INIT shows no note for the moved job (a job you push off the new button still gets one). Call it again to move it again | | `speedOn(up, down)`, `tableOn(button)` | puts the speed steps and the next table on buttons ([Buttons to add](#buttons-to-add)) | | Question | What it tells you | | --- | --- | | `isReady()` | whether it is at speed and every check is OK | | `writtenGains(tunables)` | the gains written in Tunables.java, {kP, kI, kD, kF, nominalVolts or NaN}, or null (the Flywheel Finder in Tune and check holds with them) | | `isShooting()` | whether it fires now | | `isSpinning()` | whether it is spun up (or spins up); false when idle | | `targetRpm()` | the speed it goes to | | `maxFiringQueue()` | the most shots `fire()` (or a press of RB) lets wait at once | | `isSprayingOnHold()` | whether it sprays now, from a tap then a hold | | `sprayOnTapHold()` | whether a tap then a hold sprays | | `sprayEnabled()` | whether SPRAY is allowed | | `shotModeNow()` | the shot mode in use | | `fixedSpeedRpm()` | the speed from `useSpeed(...)` | | `trim()` | the speed trim, in percent | | `atMotorLimit()` | whether the trimmed speed is cut to the motor's top speed ("(motor limit)"). More trim up does nothing | | `lastTrimOffered()` | the trim used last time (since the robot app started), offered at INIT: "+3%", or "" if none | | `allianceTrim()` | this alliance's trim from Tunables (`redTrimPercent`, `blueTrimPercent`), in percent | | `speedMode()` | the [mode](https://crossbotics.com/ftc-helper/docs/reference/steps/#modes) that sets the speed from the distance to the goal | | `tableName()`, `tableNames()`, `tableField(name)` | the table in use; all tables; a table's field name | | `table(name)` | a shot table as `Tunables.java` has it (null if none). The Shot Tuner starts from it | | `speedRpm()` | `Tunables.Launcher.speedRpm`. The Shot Tuner starts from it | | `distanceIn()`, `distanceSource()` | the distance to the goal; where it came from (camera or odometry) | | `spinsAtStart()` | whether it spins up at ▶ | | `hood()` | its [hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/) | | `feeder()`, `feedWheel()` | its feeder; its feed wheel | | `feedStopName()` | its feed stop's name | | `feedStopPart()`, `feedStopMoveSec()` | its feed stop's catalog servo (null if Robot.java gives none); `feedStopMoveSec` as read at INIT | | `feedTest(hold, release, moveSec, backupSec)` | for the Feed Stop Finder only: a [test shot](https://crossbotics.com/ftc-helper/docs/modules/finders/#feedtest) with those numbers | | `hasTimedFeeder()` | true for a CR servo or motor feeder with no feed stop, pushing parts or feed wheel: the Feed Time Finder is for it | | `feedTimeTest(limitSec)` | for the Feed Time Finder only: a [test shot](https://crossbotics.com/ftc-helper/docs/modules/finders/#feedtimetest) that times the feeder until the shot | | `pushers()` | the parts that push the pieces in | | `isEjecting()` | whether it ejects now | | `part()` | the plain [launcher](https://crossbotics.com/ftc-helper/docs/modules/launcher/#launcher) inside | | `isPresent()` | whether the part is on the robot (an `optional()` part may not be) | In an auto: `.readyToLaunch("Ready", 3)` before the drive to the shooting spot, then `.action(robot.launcher.fireAllAction())` ([what an auto can do](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/)). ## Firing: shot modes, feed stop, piece path Before each piece, the launcher picks how strict it is. You do not need to set it. | Mode | Waits for the speed | Feed stop | When | | --- | --- | --- | --- | | CAREFUL | every piece: within `readyBandRpm` for 0.15 s, and every check | opens for each piece | a tap of the fire button; autonomous while there is time | | QUICK | the first piece like CAREFUL; the next ones within `quickBandRpm`, or after `quickMaxWaitSec` | opens for each piece | a held fire button; autonomous when CAREFUL will not fit before the park time | | SPRAY | no: the wheel only has to turn at half its speed or more | stays open until the last piece | only with `sprayEnabled = true`: the last `sprayLastSec` of TeleOp, and autonomous when QUICK will not fit either | In autonomous, the launcher counts the time to the park (`parkWithSeconds(...)`, [keep time to park](https://crossbotics.com/ftc-helper/docs/reference/steps/#keep-time-to-park)): the pieces still to fire x the time a piece takes in each mode. It measures that time from the last volleys, or else estimates it. While it fires, the Driver Station says `Fire: QUICK (12 s left)`. `robot.launcher.shotMode(ShotMode.CAREFUL)` sets a mode by hand (`null` = choose again). ### Feed stop Add `.feedStop("feed_stop")` only if the robot has one. - It goes to `feedStopHold` at ▶. It never moves in INIT: nothing moves before the match. - It opens to `feedStopRelease` for a piece. It closes when the wheel sees the shot (its speed drops), or after `feedStopOpenSec` (0.5 s). - The indexer and the pushing parts wait `feedStopMoveSec` (0.1 s) while it opens. - In CAREFUL and QUICK it closes after each piece. Then a running intake cannot push a piece into a wheel that is not ready. In SPRAY it stays open until the last piece. - A roller or belt indexer (a CR servo, a motor) stops when the stop closes. - The launcher sends it a new position only when the position changes. - Find `feedStopHold`, `feedStopRelease`, `feedStopMoveSec` and `feedStopOpenSec` with the **Feed Stop Finder** (in [Tune and check](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#the-tune-and-check-menu)). For `feedStopMoveSec`, give the servo's part: `.feedStop("feed_stop", "gobilda-2000-speed")`. ### Piece path Add `.pushedBy(intake)` only if a part must push the pieces into the wheel. - For each piece, the intake runs in for at most `assistSec` (0.25 s), or until the wheel sees the shot. It does this even when the driver has it off. Then it goes back to what it was doing. - **Add the intake before the launcher** in `define()` (`intake = add(...)` first): `pushedBy(intake)` needs it. - When the driver pushes out, that still wins. - A robot that needs no push leaves it out, and nothing extra runs. (Last season's intake ran 250 ms after each shot, always.) ```java intake = add(Intake.motor("intake")); // first: the launcher's pushedBy(...) needs it launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feedStop("feed_stop", "gobilda-2000-speed") // only if the robot has one; the part is optional .pushedBy(intake)); // only if the intake must push the pieces in public static double feedStopHold = 0.15, feedStopRelease = 0.55; // Tunables.Launcher: examples, yours differ (Feed Stop Finder) public static boolean sprayEnabled = true; // optional: SPRAY at the end public static double redTrimPercent = 0, blueTrimPercent = 0; // optional // autonomous: .readyToLaunch("Ready", 3) before the drive to the shooting spot, then .action(robot.launcher.fireAllAction()) ``` ### Feed wheel Add `.feedWheel(Indexer.crServo("feeder_wheel"))`, with a push arm as the `feeder`. The wheel moves the pieces up to the arm. The arm pushes each one into the flywheel, then comes back. The wheel's numbers go in its own section (`Tunables.FeederWheel`, [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/)). With `.feedWheelOutWith(intake)` it also runs backward while the intake pushes out. Then a piece stuck between the wheel and the arm comes back out. With no feed wheel, `.feedWheelOutWith(intake)` works on a feeder that spins (a CR servo or a motor) too: then the feeder itself runs backward. A shot fired while the intake pushes out runs the feeder forward at once. The piece may have backed off a little, so it may need a longer `feedSec`. It runs in one of two ways, set with `alwaysOn`: - **Only while firing** (`alwaysOn = false`, the default): for each piece, the wheel starts and runs for `stageSec` (0.2 s), so the piece gets to the arm. Then the arm pushes while the wheel still turns. The wheel stops `stopSec` (0.3 s) after the push starts. A `stopSec` below 0 stops it before the push; 0 stops it as the push starts. The next shot waits until the wheel stops. - **Always on** (`alwaysOn = true`): the wheel runs all the time the launcher is spun up (not while it idles at `idleRpm`). So a piece is always at the arm. The arm pushes at once (no `stageSec`). More: - With a feed stop, the arm also waits for the stop to open (`feedStopMoveSec`). - The launcher runs the feed wheel: the wheel's own `feedOne()` and `stop()` do nothing. - A canceled fire stops the wheel (only while firing), and the arm never pushes. - In the simulator, a push sends a piece only if the wheel ran right before it. **A squeeze feeder** is a common kind. The feed wheel pinches the piece against pads on the arm. So the arm's `rest` position also sets the gap the piece is squeezed through. When the gap is too wide, the piece slips. When it is too tight, the piece jams, or the wheel stalls. Find it with the Servo Finder's smallest step (0.001) and a real piece. To draw it in the simulator, give the arm `looks(Shape.arm()...angle("rest", 0).angle("push", 40))` (its angle at the two positions; it tilts with the servo), and give the wheel a roller: `looks(Shape.roller("gobilda-gecko-48-rex-15a")...axis("up"))`. ```java launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("feeder_arm").part("gobilda-2000-torque")) // pushes up, comes back .feedWheel(Indexer.crServo("feeder_wheel").part("gobilda-2000-speed"))); // stages each piece public static class FeederWheel { public static boolean alwaysOn = false; public static double stageSec = 0.2, stopSec = 0.3; } ``` ### Firing stats and alliance trim **Firing stats** are debug lines, in the PRACTICE profile only (at an event they are noise). For each piece: its mode, the speed when it was fed, the drop, the time back to ready, and the time since the last piece. Then one line per volley with the average and the worst ([ShotStats](https://crossbotics.com/ftc-helper/docs/modules/launcher/#shotstats)). Use them to set `quickBandRpm`, `quickMaxWaitSec` and `shotIntervalSec`. **Alliance trim:** the two field halves are not always the same. So `redTrimPercent` and `blueTrimPercent` (0 at first) make every shot on that alliance a little faster or slower, on top of the speed trim. You keep one table and two small trims. ## Speed trim and battery compensation **Speed trim** is a fix during a match, when every shot is a bit short or long (a worn wheel, softer balls). - `trimBy(+2)` makes every shot speed 2% faster than the table (or `speedRpm`) says. - It starts at 0 at every INIT, and it is the same for every shot table. - It stops at +/- `trimMaxPercent` (15), and at the motor's top speed (`(motor limit)`). - It is the launcher's first line on the Driver Station: `Speed trim: +3% READY`. - The launcher keeps the trim used last time until the robot app restarts. INIT offers it: `Trim last time: +3% (double-tap D-pad up after ▶ to use it)`. The launcher never applies it by itself. - The Shot Tuner never uses it, so it records clean tables. With `kF` set (and battery compensation on, below, or a charged battery), a trim you need match after match means the wheel or the balls changed: the table is off. Put the trim into the table, then trim back to 0. For example, for a +3% trim all season, multiply every speed by 1.03. So `{48, 2550}` becomes `{48, 2627}` (2550 x 1.03 = 2626.5), in every row of every table. Or tune the table again with the Shot Tuner. **Battery compensation** is OFF by default. `batteryCompensation = true` with `kF` set turns it on. - The F gain gives the same POWER for a speed, and the same power spins the wheel slower on a weaker battery. The hub's I gain makes up for that only slowly. - So every 0.25 s the launcher reads the battery and gives the hub F x (`nominalVolts` / volts). Tuned at 12.6 V, at 11.5 V it is F x 1.10. Then the wheel gets back to speed after a shot as fast at 11.5 V as on a full battery. - "volts" is the highest reading of the last second. So a dip while the drive pulls hard does not raise F. - The library asks the hubs on its helper thread (`Devices.batteryReader()`), so the loop never waits. - Under 11.5 V the Driver Station warns. - `nominalVolts` comes from the Flywheel Finder. Without it the launcher uses 12.8 V (`Flywheel.DEFAULT_NOMINAL_VOLTS`, a charged battery under load). - Details: [Flywheel](https://crossbotics.com/ftc-helper/docs/modules/launcher/#battery-compensation). > **Battery compensation: OFF by default. Nobody has proven it on a real robot yet.** Testing teams: please > try it and tell us what you see. > The RPM control already fixes a low battery by itself, but slowly (the small I gain). Compensation > only makes that faster: it helps the first shot after spin-up and quick shots in a row. It cannot help > when the battery is too low for the speed you ask (the motor is already at full power). > - **Turn it on:** `public static boolean batteryCompensation = true;` in `Tunables.Launcher` (with `kF` > set, and `nominalVolts` from the Flywheel Finder; without it INIT says it assumes 12.8 V). > - **Test it on your robot:** with a battery at about 11.5 V, fire 4 shots fast and watch the > launcher's measured RPM against its target on the Driver Station. Do it with compensation off, then > on. If you see no difference, leave it off. If the wheel overshoots after a battery swap, turn it > off and tell us. ```java public static double kP = 1.17, kI = 0.117, kD = 0, kF = 11.70, nominalVolts = 12.6; // Tunables.Launcher public static double trimStepPercent = 1, trimMaxPercent = 15; // optional (the defaults) // a button: g2.y.press(() -> robot.launcher.trimBy(+3)); an action: .then(() -> r.launcher.setTrim(+5)) ``` ## Buttons to add A part has **no buttons** until you add its lines to `Controls.java`. These are the usual ones. Copy them, or change the button ([how to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line)). - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. You do not change them. - **On gamepad 1, with two drivers:** write `g1` and a free button, for example `g1.rb`. Gamepad 1's LT is slow mode, so do not use it. If you pick a button the library uses, INIT stops and names it. - Its feeder (an indexer in the launcher) needs no button: RB feeds. ```java title="Controls.java" robot.launcher.spinOn(g2.lb); robot.launcher.fireOn(g2.rb); robot.launcher.speedOn(g2.dpadUp, g2.dpadDown); robot.launcher.tableOn(g2.dpadRight); ``` | Line | What the button does | | --- | --- | | `spinOn(g2.lb)` | spins up / down | | `fireOn(g2.rb)` | a tap fires one (more taps: more shots). Held, it keeps firing. With SPRAY on, a tap then a hold sprays. It calls `fireWhileHeld()`, then `ceaseFire()` on release | | `speedOn(g2.dpadUp, g2.dpadDown)` | a tap is one speed step. Held, one more step after 0.5 s, then every 0.25 s (4 a second). With a shot table, the steps trim the speed in percent (`trimStepPercent`); with a fixed speed, +/- `stepRpm`. A double-tap of `down` goes back to no trim (and sets the hood trim back to 0). When last match's trim is offered at INIT, a double-tap of `up` uses it | | `tableOn(g2.dpadRight)` | picks the next shot table. It works only with two tables or more | Each one puts its own words on the button map. Each works only when the button is free. --- **Look it up:** [`Launcher` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Launcher.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Lift URL: https://crossbotics.com/ftc-helper/docs/reference/parts/lift/ ## In Robot.java ```java title="Robot.java" lift = add(Lift.slide("lift").part("gobilda-5203-435").bottomSwitch("lift_bottom")); ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Lift.slide(name)` | **yes** | a lift on one motor. Its encoder counts the height | - | | `.part(id)` | recommended | which motor it is, from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). When you do not write `kP`, `kD`, `slowZone` and `tolerance`, the library starts them from this motor, scaled to its counts per turn. INIT says so ([First run](https://crossbotics.com/ftc-helper/docs/reference/tunables/#first-run-what-you-get-before-tuning)) | the library's numbers for a lift | | `.bottomSwitch(name)` | recommended | a switch at the bottom that sets 0. Until the lift has pressed the switch once, the lift only goes down, slowly | 0 is where the lift is at INIT ([below](#where-0-is)) | | `.alsoMotor(name)` | optional | a second motor, turning the same way ([Two motors](#two-motors-on-one-lift-or-arm)) | one motor | | `.alsoMotorReversed(name)` | optional | a second motor, turning the other way ([Two motors](#two-motors-on-one-lift-or-arm)) | one motor | | `.reversed()` | optional | the lift turns the other way. Use it when positive power moves the lift down. With two motors it turns both | - | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.looks(shapes...)` | optional | how it looks in the simulator ([below](#in-the-simulator)) | a plain box | | `.tunables("Name")` | optional | read another `Tunables` section | the device's name in CamelCase | ### Where 0 is - **With a bottom switch:** the switch sets 0. - **Without one, 0 is where the lift is at INIT.** The encoder starts from there. - So press INIT with the lift all the way down. Do this for TeleOp too, after an autonomous that left the lift up. If you do not, `max` is too high by that much. INIT reminds you. ### In the simulator - `.looks(Shape.slide().atMm(...).sizeMm(...).travelMm(421))`: `travelMm` is the stage's travel from `min` to `max`. - A wrist or claw can ride on it: `Shape.arm().on(lift)` ([Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)). ## Two motors on one lift or arm Some lifts and arms have two motors: a slide with a motor on each side, or an arm driven from both ends. Name the second motor on the same line. ```java title="Robot.java" lift = add(Lift.slide("lift_left").part("gobilda-5203-435").alsoMotorReversed("lift_right")); // they face each other (usual) lift = add(Lift.slide("lift_left").part("gobilda-5203-435").alsoMotor("lift_right")); // both turn the same way arm = add(Arm.motor("arm_left", "gobilda-5203-117").alsoMotorReversed("arm_right")); ``` | Attribute | What it sets | | --- | --- | | `alsoMotor(name)` | a second motor, turning the same way as the first for the same power | | `alsoMotorReversed(name)` | a second motor turning the other way (two motors that face each other, mirror images) | - Both motors get exactly the same power at the same moment: every command, the stick, `stop()`, pause (BACK), the limits, interlock rules and actions. - The library reads only the **first** motor's encoder. Plug the encoder cable into it. - The Tunables section takes the first motor's name. - `.reversed()` turns both. **Pick `alsoMotor` or `alsoMotorReversed` by test.** Two motors that push against each other get hot and can break a gearbox. So take the chain or belt OFF first. Push the lift up a little with the stick (or with the Motor Finder, one motor at a time). Both motors must turn the way that lifts. If one turns the wrong way, use the other method. **What you see:** - INIT shows `LiftLeft: two motors, "lift_left" (its encoder is read) and "lift_right" (turns the other way, same power)`. - `:sim:fromRobot` writes `motor.lift_right = lift, part=..., with=lift_left, mirrored=true`. In the simulator both turn one slide. - Inside, the lift's [`SafeMotor`](https://crossbotics.com/ftc-helper/docs/modules/safety/#safemotor) sends every power to both (`alsoPowers`). ## In Tunables.java The section's name is the device's name in CamelCase: `lift` reads `Lift`, `lift_left` reads `LiftLeft`, not `Lift`. With two motors ([`alsoMotor`](#two-motors-on-one-lift-or-arm)) it is the FIRST motor's name. A Lift's numbers are in encoder **counts** (the encoder's steps), an [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/)'s in **degrees**. This table is for both. - `min` and `max` must be in `Tunables.java` (from the [Motor Finder](https://crossbotics.com/ftc-helper/docs/tuning/)), or INIT stops. - Every other number has a default, so the lift works before you tune it. - Every number that is not a setting is a named height. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). The arm's lines are on the [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/#in-tunablesjava) page. ```java title="Tunables.java" public static class Lift { // "lift" in the configuration public static double min = MEASURE; // lowest safe point, counts (Motor Finder) public static double max = MEASURE; // highest safe point, counts (Motor Finder) public static double kP = DEFAULT; // push toward the target (from the motor) public static double kI = DEFAULT; // fix a small steady miss (0) public static double kD = DEFAULT; // brake near the target (from the motor) public static double kF = DEFAULT; // hold up against gravity (0.05) public static double down = MEASURE; // a named height, counts: any name you like public static double low = MEASURE; // a named height (Motor Finder) public static double high = MEASURE; // a named height (Motor Finder) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `min` | the bottom of the safe range: it never goes below | counts / degrees | REQUIRED | no | Motor Finder (X) | the part touches its bottom stop | | `max` | the top of the safe range: it never goes above. Must be more than `min` | counts / degrees | REQUIRED | no | Motor Finder (B) | the part touches its top stop | | `kP` | how hard it pushes toward its target, per unit off | power per unit | Lift 0.004 (with `.part(...)`: scaled to the motor, [First run](https://crossbotics.com/ftc-helper/docs/reference/tunables/#first-run-what-you-get-before-tuning)), Arm 0.02 | yes, at once | test | slow to arrive (more) or shakes (less) | | `kI` | a push that grows while it stays short | power | 0 | yes, at once | test | it stops a little short and stays there | | `kD` | brakes it as it gets close | power | Lift 0.0002 (with `.part(...)`: scaled to the motor), Arm 0.001 | yes, at once | test | it overshoots (more) | | `kF` | a steady push that holds it up against gravity | power | Lift 0.05, Arm 0 | yes, at once | test | the lift sags (more) | | `maxPower` | the most power it ever gets | 0 to 1 | Lift 1.0, Arm 0.6 | no | test | it moves too violently | | `slowZone` | it slows down within this distance of `min` and `max` | counts / degrees | Lift 250 (with `.part(...)`: about half a motor turn), Arm 15 | no | test | it slams into its ends (more) | | `slowZonePower` | the power at the very end of the slow zone | 0 to 1 | 0.2 | no | test | it stalls near an end (more) | | `tolerance` | how close counts as "arrived" | counts / degrees | Lift 20 (with `.part(...)`: 1/27 of a motor turn), Arm 3 | no | test | actions wait too long (more) | | `` | every other number is a named position (`down`, `low`, `high`); any name | counts / degrees | Lift: down 0, low 900, high 2400. Arm: stowed 0, score 90 (only when none are written) | yes, at once | Motor Finder (positions P1, P2...) | a new scoring height | ## Commands Use them in `Controls.java`, `Actions.java` and autos: `robot.lift.goTo("high")`. An [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/) has the same commands (they share `MotorPositions`). | Command | What it does | | --- | --- | | `goTo(name)` | goes to a named height. Capitals do not matter. A typo shows a warning and does nothing | | `stepUp()`, `stepDown()` | goes to the next height up or down | | `manual(power)` | moves by hand. 0 holds it where the driver let go | | `hold()` | holds where it is | | `stop()` | stops | | Question | What it tells you | | --- | --- | | `isAtTarget()` | whether it is at its target | | `isAt(name)` | whether it is at that named height | | `position()` | where it is now, in counts | | `positions()` | the names of its heights | | `part()` | the [`PositionMotor`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#positionmotor) inside | | `secondMotorName()` | the second motor's name, or null | | `zoneAbove()`, `zoneBelow()` | its zone for an [interlock rule](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) | | `isPresent()` | whether the part is on the robot (an `optional()` part may not be) | ## Buttons to add A part has **no buttons** until you add its lines to `Controls.java`. These are the usual ones. Copy them, or change the button ([how to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line)). - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. You do not change them. - **On gamepad 1, with two drivers:** write `g1` and a free button, for example `g1.rb`. Gamepad 1's LT is slow mode, so do not use it. If you pick a button the library uses, INIT stops and names it. ```java title="Controls.java" g2.a.press(() -> robot.lift.goTo("down")).says("down"); g2.x.press(() -> robot.lift.goTo("low")).says("low"); g2.y.press(() -> robot.lift.goTo("high")).says("high"); g2.dpadUp.press(robot.lift::stepUp).says("next height up"); g2.dpadDown.press(robot.lift::stepDown).says("next height down"); g2.leftStickY.use(robot.lift::manual).says("by hand"); ``` | Button | Does | | --- | --- | | A | the `down` height | | X | the `low` height | | Y | the `high` height | | D-pad up, down | the next height | | left stick | by hand | --- **Look it up:** [`Lift` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Lift.html) and [`MotorPositions`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/MotorPositions.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Lights URL: https://crossbotics.com/ftc-helper/docs/reference/parts/lights/ ## In Robot.java ```java title="Robot.java" lights = add(Lights.gobilda("light")); // Robot.java: a goBILDA RGB Indicator Light ("Servo" in the configuration) lights = add(Lights.blinkin("blinkin")); // or a REV Blinkin LED Driver and its LED strip ("REV Blinkin LED Driver") ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Lights.gobilda(name)` | **yes**, one of the two | a goBILDA RGB Indicator Light. In the configuration it is a "Servo" | - | | `Lights.blinkin(name)` | **yes**, one of the two | a REV Blinkin LED Driver and its LED strip. In the configuration: "REV Blinkin LED Driver" | - | | `.alsoLight(names...)` | optional | more lights of the same kind that always show the same as this one (the same color, blinking and flashes). Lights that show different things: two `add(...)` lines instead | one light | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.tunables("Name")` | optional | read another `Tunables` section | the device's name in CamelCase | You choose which color shows when in `Controls.java` ([Commands](#commands)). In the simulator, the light is a dot on the robot and on the 3D view. ## In Tunables.java The section's name is the device's name in CamelCase (`light` reads `Light`, `blinkin` reads `Blinkin`). **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class Light { // "light" in the configuration public static boolean allianceAtInit = true; // show the alliance in INIT, flash it at ▶ (true) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `allianceAtInit` | shows the alliance (red or blue) during INIT and flashes it at ▶. A `robot.lights.allianceAtInit(...)` line in Controls.java wins over this one | true/false | true | no | none | `false`: your rules show in INIT too | ## Commands You write which color shows when in `Controls.java`, inside `buttons(...)`: one line per rule. Every file that names a color (`Controls.java`, and `Actions.java` if an action flashes the light) needs `import com.crossbotics.ftchelper.robot.LightColor;` at the top. ```java robot.lights.show(LightColor.WHITE).forSeconds(0.2) // a flash first (it beats every rule): .whenCountGoesUp(() -> robot.launcher.part().getShotsFired()); // one short flash per piece fired robot.lights.show(LightColor.YELLOW).blinking().inLastSeconds(20); // then the most important rule robot.lights.show(LightColor.GREEN).when(robot.launcher::isReady); // ready to fire robot.lights.show(LightColor.PURPLE).when(() -> robot.turret.followMode().isOn()); // a turret robot robot.lights.show(LightColor.PURPLE).when(() -> robot.aimMode().isOn()); // or: whole-robot aim on (no turret) robot.lights.otherwise(LightColor.OFF); // when no rule is true ``` | Command | What it does | | --- | --- | | `show(color).when(test)` | shows that color while `test` is true | | `show(color).blinking().when(test)` | blinks 2 times a second. `blinking(1)`: once a second (any number above 0, at most 5) | | `show(color).whenStarts(test)` | a 0.5 s flash each time `test` turns from false to true. Put `.forSeconds(1)` first for a longer flash | | `show(color).whenCountGoesUp(count)` | a 0.5 s flash each time the number goes up. `() -> robot.launcher.part().getShotsFired()` flashes once per piece fired (`whenStarts(robot.launcher::isShooting)` would flash once for all of a `fire(3)`). Shots closer together than the flash run into one long flash: `.forSeconds(0.2)` first keeps them apart | | `show(color).inLastSeconds(20)` | shows it in the last 20 s of TeleOp's 2:00, counted from ▶ | | `otherwise(color)` | when no rule is true (default `OFF`) | | `flash(color)`, `flash(color, seconds)` | flashes now, over every rule: from a button or an action step | | `clearRules()` | removes every rule | | `allianceAtInit(false)` | turns off the alliance at INIT ([below](#the-alliance-at-init)) | | `allianceColors(blue, red)` | the colors for the alliance at INIT, for a light that shows red or blue badly | | `blinkinPattern(color, pattern)` | a Blinkin only: your own pattern for a color, e.g. `blinkinPattern(LightColor.BLUE, BlinkinPattern.BLUE_VIOLET)` | | Question | What it tells you | | --- | --- | | `color()` | the color the rules pick | | `showing()` | what is lit this instant (OFF in a blink's dark half) | | `isFlashing()` | whether a flash shows now | | `showsAllianceAtInit()` | whether the alliance at INIT is on | | `isPresent()` | whether the part is on the robot (an `optional()` part may not be) | ### How the rules work - **The first true rule wins**, in the order written. A flash beats every rule while it lasts, wherever it is written (write it first, so the file reads in that order). Nobody can see a flash in the color of the rule under it: give it another color. - **Any true/false works:** `robot.intake::isRunning`, a mode (`() -> robot.turret.followMode().isOn()`), or your own (`() -> robot.lift.position() > 1000`). A rule that fails counts as false, and the Driver Station warns. - The light works from INIT (the drivers see it light up) and goes dark at STOP. An action never "claims" it. - **At most one change every 0.1 s** (`Lights.MIN_CHANGE_SEC`). Even a rule that turns on and off every loop, or flash after flash, switches the light on and off at most 5 times a second (R202 J below). A change that comes sooner waits a loop or two. A flash shorter than 0.1 s may not show. ### Colors `LightColor`: `RED`, `ORANGE`, `YELLOW`, `GREEN`, `BLUE`, `PURPLE`, `WHITE`, `OFF`. Each light turns them into its own signal: | LightColor | goBILDA position | Blinkin pattern | | --- | --- | --- | | RED | 0.280 | RED | | ORANGE | 0.333 | ORANGE | | YELLOW | 0.388 | YELLOW | | GREEN | 0.500 | GREEN | | BLUE | 0.611 | BLUE | | PURPLE | 0.700 | VIOLET | | WHITE | 1.0 | WHITE | | OFF | 0.0 | BLACK | - The goBILDA numbers are from the seller's chart (3118-0808-0002, Product Insight #4, checked 2026-10-21): off below 1100 microseconds, red to violet up to 1900, white above. That is with the hub's normal servo signal (0 = 600, 1 = 2400 microseconds). - RED and PURPLE sit a little inside that window. The chart's 0.277 and 0.722 are right on its edges. - The Blinkin (REV-11-1105) uses the SDK's `RevBlinkinLedDriver`. With no signal it shows its own rainbow "color waves". ### Game rules (2026-27 manual) - The referees can switch off lights that flash faster than about 5 times a second (R202 J), or very bright lights (R202 F). So `blinking(...)` takes at most 5 times a second (a bigger number is an error), and the light never changes faster than every 0.1 s. - A light in your alliance's color is allowed: the manual has no rule against it (R202 F and J, R401, R402 checked). The ROBOT SIGNS must still show it (R401, R402). - Do not shine lights onto the field (G302 example). ## The alliance at INIT A wrong alliance pick in INIT makes the robot aim at the other alliance's goal all match. The drive team sees the light from the field, not the Driver Station's small text. So the light shows the alliance. It is on by default, on every robot with a light. - **INIT:** solid `RED` or `BLUE` once the alliance is picked (TeleOp: gamepad 1 X or B, or the one autonomous left; autonomous: its INIT menu). Before the alliance is picked: **white blinking once a second** ("choose the alliance"). Your rules wait until ▶. - **▶:** a 1 s flash of the alliance (TeleOp after autonomous: the one it got), then your rules. - **Alliance switched in TeleOp** (the opt-in `lib.switchAlliance(...)`): a 1 s flash of the new one. - Keep your rules' colors away from red and blue (the examples use purple and orange). Then nobody reads "intake on" as "BLUE alliance". To turn it off, in `Tunables.java` (the light's section, named after its device, for example `Tunables.Light`): ```java public static class Light { public static boolean allianceAtInit = false; // the rules show in INIT too, and no alliance flashes } ``` Or in `Controls.java`: `robot.lights.allianceAtInit(false);`. For a light that shows red or blue badly, pick two other colors: `robot.lights.allianceColors(LightColor.PURPLE, LightColor.ORANGE);` (blue's color first). For a Blinkin, you can set a pattern of your own: `robot.lights.blinkinPattern(LightColor.BLUE, BlinkinPattern.BLUE_VIOLET);` (`import com.qualcomm.hardware.rev.RevBlinkinLedDriver.BlinkinPattern;`). ## Buttons to add Lights need no button. A button can flash the light: `g2.a.press(() -> robot.lights.flash(LightColor.GREEN))`. --- **Look it up:** [`Lights`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Lights.html) and [`LightColor`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/LightColor.html) in the Javadoc (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Odometry URL: https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/ The sensor that knows where the robot is on the field: a goBILDA Pinpoint, a SparkFun OTOS, or dead wheels (free-turning wheels with encoders that roll on the floor). Learn it step by step: [Drive to a point](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/#drive-to-a-point-driveto), and [Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/). The [odometry module](https://crossbotics.com/ftc-helper/docs/modules/odometry/) has everything, with sketches of the offsets. ## In Robot.java ```java title="Robot.java" odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); // in define(), after drive(...) ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Odometry.pinpoint(name)` | **yes**, one of the five | a goBILDA Pinpoint | - | | `Odometry.otos(name)` | **yes**, one of the five | a SparkFun OTOS | - | | `Odometry.threeWheels(left, right, perp)` | **yes**, one of the five | three dead wheels on encoder ports | - | | `Odometry.twoWheels(parallel, perp)` | **yes**, one of the five | two dead wheels, and the drive's IMU | - | | `Odometry.custom(make)` | **yes**, one of the five | your own pose source, made at INIT from the robot's devices (odometry with AprilTags, or another library's localizer). It must use the library's frame: x right, y away, heading 0 = away, counterclockwise + | - | | `.offsetsMm(xPodLeft, yPodForward)` | Pinpoint | where the pods sit, mm: the forward pod's distance LEFT of the center (right = -), the sideways pod's distance FORWARD of the center (back = -). The Odometry Tuner measures them | - | | `.robotSizeMm(length, width)` | with an `...FromEdgesMm` | the frame's size, mm (bumpers off). The library takes the middle of it as the robot's center | INIT stops if an `...FromEdgesMm` needs it | | `.podsFromEdgesMm(forwardPodFromLeft, sidewaysPodFromFront)` | Pinpoint, in place of `offsetsMm` | where the pods sit, from the robot's edges: the forward pod's wheel from the LEFT edge, the sideways pod's wheel from the FRONT edge, mm. The library works out `offsetsMm`. The last of the two you write wins | - | | `.podsSwingarm()` | Pinpoint, optional | goBILDA swingarm pods instead of 4-bar pods | 4-bar pods | | `.ticksPerMm(n)` | Pinpoint, optional | other pods: encoder counts per mm of wheel travel | goBILDA's pods | | `.reversed(...)` | optional | pods that count the wrong way (the Odometry Tuner says which): `"x"` and/or `"y"` for a Pinpoint, the motor port names for dead wheels. A name that is not a pod stops INIT | none reversed | | `.mountIn(forward, left, headingDeg)` | OTOS | where it sits: inches forward of the center, inches left, and its arrow's direction (counterclockwise degrees) | - | | `.mountFromEdgesMm(fromFront, fromLeft, headingDeg)` | OTOS, in place of `mountIn` | where it sits, from the robot's edges: its middle from the FRONT edge and from the LEFT edge, mm, and its arrow's direction. Needs `robotSizeMm` | - | | `.trackWidthIn(in)` | three wheels: **yes** | the distance between the left and right forward pods, inches | INIT stops | | `.parallelLeftIn(in)` | two wheels | how far LEFT of the center the forward pod is, inches (right = -) | - | | `.perpForwardIn(in)` | dead wheels | how far FORWARD of the center the sideways pod is, inches (back = -) | - | **Keep-out boxes:** `fieldMap(FieldMap.margin(13).keepOut(...))` in `Robot.java` lists the places the robot must not drive through, for `s.routeTo(...)` and `route(...)` ([keep-out boxes and routes](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes)). ## In Tunables.java Section `Odometry` (a fixed name). The odometry reads it once, at INIT. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class Odometry { // a fixed name: always Odometry public static boolean checked = false; // true after the Odometry Tuner's Loop test // "Set pose here" (TeleOp: hold gamepad 1 START 1 s on this spot), written for BLUE. public static double resetX = -56; // inches right of center, - = left public static double resetY = -61; // inches from center, - = our half public static double resetHeading = 0; // degrees, 0 = facing the field // RED: false = the same numbers from the red wall; true (or left out) = mirrored left-right. public static boolean mirrorForRed = false; // BIOBUZZ: false } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `checked` | like `Drive.calibrated`, for the odometry: `driveTo` and path steps run on a real robot only when this is `true`. Until then INIT warns `Odometry not checked` (the simulator runs them anyway) | true/false | false | no | Odometry Tuner | after the Odometry Tuner's loop check passes | | `linearScalar` | OTOS only: corrects its distances | times | 1.0 | no | Odometry Tuner | the OTOS says 48 in when the robot drove 50 | | `angularScalar` | OTOS only: corrects its turns | times | 1.0 | no | test (turn 10 times, compare) | the heading drifts after many turns | | `resetX`, `resetY` | the "set pose here" spot for `resetPose()`: x, y seen from your wall, written for BLUE. Write both: with only one, there is no reset spot | inches | none: no reset spot | no | measure on the field | you want a button that resets the pose at a known spot | | `resetHeading` | the heading at the reset spot | degrees | 0 | no | measure on the field | the robot faces another way at that spot | | `mirrorForRed` | ONE setting for the whole robot (routes, start and reset spots, the aim's goal point): RED uses BLUE's numbers mirrored (true) or the same numbers from the red wall (false). Write it once, in `Aim` or here. The library takes `Aim`'s first, then this one, then your autonomous's `mirrorForRed()`. INIT shows the choice and where it came from | true/false | `Tunables.Aim.mirrorForRed`, else true | no | the game's field | BIOBUZZ's field is turned half a turn: `false` | ### Where mirrorForRed comes from `mirrorForRed` says whether RED's half is a mirror image of BLUE's. The whole robot uses ONE answer: the routes, the start and reset spots, and the aim's goal point. The library takes the first one it finds: | Order | Where | Note | | --- | --- | --- | | 1 | `Tunables.Aim.mirrorForRed` | | | 2 | `Tunables.Odometry.mirrorForRed` | | | 3 | your autonomous's `mirrorForRed()` method | in TeleOp: the last autonomous's | | 4 | none written | true | Write it in one place. On BIOBUZZ's turned field: `false`. INIT shows the answer and where it came from. When your autonomous's `mirrorForRed()` disagrees with Tunables, INIT warns you to write it in one place. ## What it does - It gives `robot.pose()` every loop: where the robot is. - It makes `driveTo` steps in autos work ([Steps for autos](https://crossbotics.com/ftc-helper/docs/reference/steps/)). - TeleOp starts where the auto ended. - The library updates the odometry first in each loop, before every part. - "Set pose here": `resetPose()` ([Robot.java](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition)) puts the robot on the reset spot. In TeleOp: hold gamepad 1 START 1 s on that spot. ## Commands | Question | What it tells you | | --- | --- | | `kindName()` | the kind, in words | | `names()` | the device names | | `podTicksPerMm()` | a Pinpoint's encoder counts per mm | | `isReversed(which)` | whether that pod counts the other way | --- **Look it up:** [`Odometry` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Odometry.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # PathFollower and PathAt URL: https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/ A **PathFollower** is a small plug that a path-following add-on fills in. With it, the core library never needs that other library. The [pedro module](https://crossbotics.com/ftc-helper/docs/modules/pedro/) is one add-on. **PathAt** starts things along a path while the robot drives. Learn it step by step: [Follow a curved path: Pedro](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/). ## In Robot.java ```java title="Robot.java" follower(Pedro.follower(PedroConstants.foresight)); // in define() ``` Then `follow(label, path)` steps in autos ([Steps for autos](https://crossbotics.com/ftc-helper/docs/reference/steps/)). ## What it does - The library updates it every loop, right after the odometry. - It drives the wheels only while a path runs. ## Commands A path-following add-on must give these. Your autos use them through `follow` steps. | Command | What it does | | --- | --- | | `follow(path, mirrorX)` | starts a path (mirrored for RED when routes are mirrored) | | `cancel()` | stops now | | `check(path)` | at INIT: stops with an error (throws) when it cannot follow this kind of path | | Question | What it tells you | | --- | --- | | `isBusy()` | whether the path still runs | | `remainingIn()` | inches left on the WHOLE path (all its parts), for the "stuck" check. Because it counts the whole path, `PathAt.inchesLeft` and `fraction` are right | | `isReady()` | whether its pose source is ready. While it is not, the step ends `NO_ODOMETRY` | | `totalIn()` | optional (it has a default): the path's length | | `partNow()` | optional: the part it drives now (from 1) | | `parts(path)` | optional: how many parts a path has | [PathAt](#pathat) uses the three optional ones. When an add-on does not give them, PathAt takes the distance left at the start as the length, and `PathAt.part(n)` fires at the end. ## PathAt PathAt starts things ALONG a `follow` (or `driveTo`) step, while the robot keeps driving. Each one fires once. More: [pedro module, Do things along the path](https://crossbotics.com/ftc-helper/docs/modules/pedro/#do-things-along-the-path). | Command | Fires | | --- | --- | | `PathAt.inchesDone(in, label, command)` | after `in` inches of the path | | `PathAt.inchesLeft(in, label, command)` | when `in` inches are left | | `PathAt.fraction(f, label, command)` | when that much of the WHOLE path is done (0.5 = halfway, all parts counted) | | `PathAt.part(n, label, command)` | where part `n` of a `then` path starts (INIT stops if the path has fewer parts) | | `PathAt.near(x, y, withinIn, label, command)` | when the robot is within `withinIn` of a field point (mirrored for RED) | For example `PathAt.inchesLeft(12, "Spin up", robot.launcher::spinUp)` (your own part names). Each also takes an [Action](https://crossbotics.com/ftc-helper/docs/reference/steps/#action) from your `Actions.java` instead of a label and a command: `PathAt.inchesLeft(12, Actions.scoreHigh(robot))`, or any action you wrote. `name()` gives its label. --- **Look it up:** [`PathFollower`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/PathFollower.html) and [`PathAt`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/PathAt.html) in the Javadoc (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Pieces and PieceSensor URL: https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/ ## In Robot.java ```java title="Robot.java" public Pieces pieces; // at the top of Robot.java pieces = add(Pieces.kinds("POLLEN", "RED_NECTAR", "BLUE_NECTAR") // your kinds: also Tunables names .comingIn(PieceSensor.color("intake_color")) // sees each piece come in .readyToFire(PieceSensor.color("ready_color")) // optional: the next to fire .max(4) // BIOBUZZ G407: at most 4 .startsWith(4, "POLLEN")); // the preload intake = add(Intake.motor("intake").part("gobilda-5203-1150").stopsWhen(() -> pieces.isFull())); // no 5th piece ``` **Pieces:** | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Pieces.kinds(names...)` | **yes** | your kinds of game piece. They are also the names in `Tunables.java` | - | | `.comingIn(sensor)` | recommended | the sensor that sees each piece come in | nothing counts in | | `.readyToFire(sensor)` | optional | the sensor where the next piece waits. It sees each one leave | the count follows the feeds | | `.max(n)` | optional | the robot is "full" at this number. BIOBUZZ G407: at most 4 | the intake's `holds(n)` ([Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/)) | | `.startsWith(n, "KIND")` | optional | the preload | empty | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | **PieceSensor** (one spot each): | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `PieceSensor.color(name)` | **yes**, one of the three | a color sensor | - | | `PieceSensor.distance(name)` | **yes**, one of the three | a distance sensor | - | | `PieceSensor.camera(webcamName)` | **yes**, one of the three | a second webcam | - | | `.kinds(names...)` | only for a sensor alone | the kinds it tells apart. In `Pieces`, it gets the kinds from `Pieces.kinds(...)` | - | | `.box(left, top, right, bottom)` | optional, camera only | the box of the picture to read, from the center: -1 = left or bottom edge, 1 = right or top edge | the middle quarter (-0.25, 0.25, 0.25, -0.25) | A sensor alone, with no count: `add(PieceSensor.color("x").kinds("POLLEN"))`. ### The sensors | Sensor | Part (checked 2026-10-21) | Tells apart | Cannot | | --- | --- | --- | --- | | `PieceSensor.color(name)` | REV Color Sensor V3, REV-31-1557 ($20.75): color + distance 1-10 cm (Broadcom APDS-9151) | every color: yellow POLLEN, red and blue NECTAR | see a piece more than ~5 cm away; mount it 1-2 cm from the piece | | `PieceSensor.distance(name)` | REV 2m Distance Sensor, REV-31-1505 ($31.50): 5-200 cm, 1 mm resolution, 25° cone (VL53L0X) | sizes: a 3.6 in NECTAR is 20 mm bigger than a 2.8 in POLLEN | colors (red from blue NECTAR); read closer than 5 cm | | `PieceSensor.camera(webcamName)` | a second UVC webcam, SDK `PredominantColorProcessor` | colors, from farther away | distance: "is one there" means "the box is colorful" (`minSaturation`); a gray background helps | **BIOBUZZ numbers** (game manual TU01, section 9.8): - POLLEN: about 2.8 in (7.1 cm) yellow balls (AndyMark am-5851_yellow). - NECTAR: about 3.6 in (9.1 cm) red or blue balls (am-5852_red, am-5852_blue). - They are "not perfectly spherical and may vary in size". - G407: a robot may not CONTROL more than 4 at a time. - G408: never control the OPPONENT's NECTAR. So a team that picks up NECTAR needs color, not only size. ### Where to put the sensors - **The intake sensor:** put it where each piece passes once and is already held (past the rollers). Then a piece that bounces out does not count, and the intake does not stop with a piece half in. - The sensor sees two touching pieces as one, unless they are different kinds, or the distance dips between them (`gapMm`; check it with two touching pieces). A gap between pieces (a spacer, or a short indexer step) is safer. - **The ready sensor:** put it where the next piece waits, so it sees each one leave. ### A second webcam When the robot also has an AprilTag webcam: - Each camera gets its own VisionPortal (the SDK object that runs a camera). The color camera uses 320x240 pictures and no live view. - The Driver Station can show one portal, unless the code splits the view with `VisionPortal.makeMultiPortalView`. - Two webcams share the Control Hub's USB. Plug them into different USB ports (one is USB 3.0), or use a Limelight for the AprilTags. - When a camera is missing or fails to start, the library warns, and the camera sees nothing. The OpMode goes on. ## In Tunables.java One section per sensor, named after its device in CamelCase (`intake_color` reads `IntakeColor`). `Pieces` itself reads no numbers. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class IntakeColor { // "intake_color" in the configuration public static double POLLEN = MEASURE; // the kind's hue, degrees (Piece Tuner) public static double nearMm = DEFAULT; // a piece is there below this distance (40) public static double hueTolerance = DEFAULT; // how far from a kind's hue still counts (30) public static double minSaturation = DEFAULT; // how colorful it must be, 0 to 1 (0) public static double steadyMs = DEFAULT; // a reading must stay this long (30) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `` | one per kind, the same name as in `kinds(...)`, e.g. `POLLEN`: the kind's hue (color sensor, camera) or the mm the sensor reads with it (distance sensor) | degrees 0 to 360 / mm | none: that kind reads `UNKNOWN` (INIT says so) | yes, at once | Piece Tuner | new lights at a venue, or a moved sensor | | `nearMm` | color and distance sensors: a piece is there below this distance | mm | 40 (color), 100 (distance) | yes, at once | Piece Tuner | it sees pieces that are not there | | `hueTolerance` | color sensor, camera: how far from a kind's hue still counts | degrees | 30 | yes, at once | Piece Tuner | kinds are mixed up (less) | | `sizeToleranceMm` | distance sensor: how far from a kind's size still counts | mm | 8 | yes, at once | Piece Tuner | kinds are mixed up (less) | | `minSaturation` | color sensor, camera: how colorful it must be (0 to 1) | 0 to 1 | 0.35 (camera), 0 (color) | yes, at once | Piece Tuner | the background counts as a piece (more) | | `steadyMs` | a reading must stay this long before it counts | ms | 30 | yes, at once | test | flickers count as pieces (more) | | `gapMm` | color and distance sensors: a dip this big between two touching pieces counts as two (0 = off) | mm | 8 | yes, at once | test with two touching pieces | two pieces count as one | | `gain` | color sensor: its gain | number | the sensor's own | no | test | readings are too dark | A section with tuned numbers: ```java public static class IntakeColor { public static double POLLEN = 75, RED_NECTAR = 8, BLUE_NECTAR = 215; // hues (degrees), from the Piece Tuner public static double nearMm = 40; // a piece is there below this } ``` **When a piece "is there":** - A piece is there when the distance is below `nearMm`. - A color sensor with no distance reading (not a REV Color Sensor V3) uses its color instead: a piece is there when the saturation is at least `minSaturation`, and at least 0.2 (gray is "empty"). - For a camera, a piece is there when the box is at least `minSaturation` colorful. - A piece that is there but matches no kind's number reads `UNKNOWN`. Find the numbers with the **Piece Tuner** ([`PieceTunerOpMode`](https://crossbotics.com/ftc-helper/docs/modules/finders/#piecetuneropmode)). It shows each sensor's readings and writes the lines to copy into `Tunables.java`. When you change a number in the tuning menu and save it, copy it back into `Tunables.java`. The saved value is only on this Control Hub, and the file is the record. ## Commands Use them in `Controls.java`, `Actions.java` and autos: `robot.pieces.count()`. **Pieces:** | Command | What it does | | --- | --- | | `pieceIn(kind)`, `pieceOut()` | changes the count by hand (a claw, a button) | | `clear()` | sets the count to 0 | | `set(kinds...)` | sets the whole list by hand | | Question | What it tells you | | --- | --- | | `count()`, `count(kind)` | how many it holds (a piece being fed counts until it has gone); how many of one kind | | `next()` | the next to fire: a kind, `Pieces.UNKNOWN`, or `Pieces.NONE` (empty). During a feed: the one after it | | `nextIs(kind)` | whether the next is that kind | | `isFull()`, `isEmpty()` | whether it is full; whether it is empty | | `isFullFor(kind)` | whether no more of that kind fits (the intake's `holds(n, "KIND")`) | | `held()` | the list, next to fire first | | `atIntake()`, `atReady()` | what each sensor sees now | | `maxPieces()` | the number where it is full | | `comingInSensor()`, `readyToFireSensor()` | its two sensors | | `nextKind()` | `next` as a `Supplier`: for a part that asks every loop | | `whenFull()`, `whenEmpty()`, `whenNextIs(kind)` | conditions (`BooleanSupplier`) for lights, `rumbleWhen`, `stopsWhen`, an action's wait | | `isPresent()` | whether the part is on the robot (an `optional()` part may not be) | **PieceSensor:** | Question | What it tells you | | --- | --- | | `kind()` | the kind it sees now (after `steadyMs`) | | `sees(kind)`, `seesPiece()` | whether it sees that kind; whether it sees any piece | | `rawKind()` | the kind of this reading, before the steady check | | `isWorking()` | whether it gives new readings | | `hueDeg()`, `saturation()`, `distanceMm()`, `measured()` | the raw readings | | `hasDistance()`, `measuresSize()` | whether it has a distance reading; whether it tells kinds apart by size | | `kindNames()`, `sensorType()`, `problem()` | its kinds; its type; what is wrong, if anything | | `arrivals()`, `readings()` | how many pieces it saw come; how many readings it had | ### How it counts - **In:** each new piece the intake sensor sees counts one IN, with its kind. A piece is new when the spot was empty, or a different kind is right behind. With color and distance sensors, it is also new when the distance went up and down again by `gapMm`: two touching pieces of the same kind. - **Out:** each feed of an [`Indexer`](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/) (alone or in a launcher) counts one OUT, the oldest first. The robot fires in the order the pieces came in. It counts a piece out only once it has gone: the ready sensor sees it leave the slot, or, without a ready sensor, the feed ends without a jam. - A jammed feed, or one stopped part way, counts nothing. With a ready sensor, a feed while the slot is empty counts nothing either. - **Pushing out:** while the intake pushes out (`out()` or a held `reverse()`), each piece that leaves past the intake sensor counts one OUT (the newest), and nothing counts in. So backing a jam out and taking it in again counts right. - **The ready sensor**, if there is one, has the last word on the next piece. It corrects the kind, and it adds a piece it sees that was never counted. - After a shot, Pieces trusts the ready sensor again once the slot reads empty, or a new steady reading begins (the next piece). The end of the feed is not enough: the sensor's answer lags a little (`steadyMs`). Its old reading would put the fired piece back in the count. After a jammed feed (nothing went), Pieces trusts the sensor again at once. **The count is a helper, and it can be wrong.** A piece that bounces out, or two pieces read as one, make it wrong. So the drivers are responsible for G407 (at most 4) until the robot has a hardware stop. When the count is wrong: - Hold the operator's **left stick button** for 1 s: count = 0 ([Buttons to add](#buttons-to-add)). - To pull in when the count says full, hold the intake's in-button (RT) for 1 s. The Driver Station warns when the intake has been held back for more than 2 s. **A sensor that is missing or stops answering** never stops the OpMode: - When the robot configuration has no color or distance sensor of that name, INIT warns, and the sensor sees nothing. - When a sensor (or camera) has no new reading for 0.5 s, it warns ("no new reading"). It then sees nothing until readings come back (`isWorking()` is false), and Pieces counts nothing with it. - The loop never waits for a sensor. A REV 2m Distance Sensor reading can take up to 0.2 s. So the library reads it on a helper thread, and throws away a reading older than 0.25 s. ### Hooks for other parts A shot table per kind, picked by the next piece: ```java launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .speedFromDistance(camera) .tableFrom(pieces.nextKind()) // the next piece picks the table... .tableFor("nectar", "RED_NECTAR", "BLUE_NECTAR")); // ...both NECTAR colors use "nectar" ``` - "POLLEN" uses the `pollen` table by its name. "NONE" and "UNKNOWN" keep the table in use. A driver's button still works until the next piece changes ([Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/)). - Lights (`import com.crossbotics.ftchelper.robot.LightColor;` in Controls.java): `robot.lights.show(LightColor.GREEN).when(robot.pieces.whenFull());` and `robot.lights.show(LightColor.ORANGE).when(robot.pieces.whenEmpty());` ([Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/)). - To never feed with nothing in: `Launcher...requireReady("a piece to fire", () -> !pieces.isEmpty())`. - To stop the intake when full: `.stopsWhen(() -> pieces.isFull())` on the intake ([Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/)). ### Not done yet, and the simulator - The count does not carry over from the autonomous into the TeleOp. The TeleOp starts with `startsWith(...)`. A ready sensor corrects an empty count. - The simulator ([robot file](https://crossbotics.com/ftc-helper/docs/reference/robot-file/#game-pieces): `color.NAME = at=ready`, `distance.NAME = at=intake, acrossMm=150`) simulates color and distance sensors. It does not simulate the camera. ## Buttons to add A part has **no buttons** until you add its lines to `Controls.java`. These are the usual ones. Copy them, or change the button ([how to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line)). - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. But with one driver, the left stick button is the library's slow switch: give `clear` another button. - **On gamepad 1, with two drivers:** write `g1` and a free button, for example `g1.rb`. Gamepad 1's LT is slow mode, so do not use it. If you pick a button the library uses, INIT stops and names it. ```java title="Controls.java" g2.leftStickButton.heldFor(1.0, robot.pieces::clear).says("piece count = 0"); ``` --- **Look it up:** [`Pieces`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Pieces.html) and [`PieceSensor`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/PieceSensor.html) in the Javadoc (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Positioner URL: https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/ A Positioner shares most of its options, numbers and commands with the [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/). The Claw page lists the shared ones. ## In Robot.java ```java title="Robot.java" intakeDeploy = add(Positioner.servo("intake_deploy").part("gobilda-2000-torque")); // Tunables.IntakeDeploy: stowed, deployed ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Positioner.servo(name)` | **yes** | a positioner on one servo | - | | `.part(id)` | recommended | which servo it is, from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). When you do not write `travelSec`, the library takes it from the servo's catalog speed | `travelSec` is 0.3 s | | `.alsoServo(name)`, `.alsoServoReversed(name)` | optional | a second servo ([Two servos](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#two-servos-on-one-part)) | one servo | | `.reversed()` | optional | the servo turns the other way | - | | `.fullRange()` | optional | the servo's whole turn ([full range](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#a-servos-full-range)) | the FTC SDK's normal range | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.looks(shapes...)` | optional | how it looks in the simulator ([below](#in-the-simulator)) | a plain box | | `.tunables("Name")` | optional | read another `Tunables` section | the device's name in CamelCase | ### In the simulator - It swings an arm shape: `.looks(Shape.arm()...angle("stowed", 90).angle("deployed", 20))`. - It can push a passive part over: `Shape.dropsWhen` ([Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)). ## In Tunables.java The section's name is the device's name in CamelCase: `intake_deploy` reads `IntakeDeploy`. Every number except `travelSec` and `alsoTrim` is a named position (0 to 1). You choose the names. The table of every number, and how to time `travelSec`, is on the [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#in-tunablesjava) page. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). A positioner (a fold-out): ```java title="Tunables.java" public static class IntakeDeploy { // "intake_deploy" in the configuration public static double stowed = MEASURE; // servo position, folded (Servo Finder) public static double deployed = MEASURE; // servo position, folded out (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) } ``` ## Commands Use them in `Controls.java`, `Actions.java` and autos: `robot.intakeDeploy.goTo("deployed")`. | Command | What it does | | --- | --- | | `goTo(name)` | goes to a named position | | `next()` | goes to the next position, in the order written in `Tunables.java`. After the last comes the first | The questions are the [Claw's](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#commands): `isDone()`, `isAt(name)`, `positions()`, `part()`, `secondServoName()`, `zone()`, `isPresent()`. ## Buttons to add A positioner has no usual buttons: you choose when it moves. For example, put it on a button in `Controls.java`: ```java title="Controls.java" g2.x.press(() -> robot.intakeDeploy.goTo("deployed")).says("deploy"); ``` You can also move it at ▶ in `Robot.java`, or in an action. To read a button line, see [Controls.java](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line). --- **Look it up:** [`Positioner` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Positioner.html) and [`ServoPositions`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/ServoPositions.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Turret URL: https://crossbotics.com/ftc-helper/docs/reference/parts/turret/ A part that turns to aim, inside its limits, by hand or following the camera's goal. Learn it step by step: [Setting up a turret](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/). That page has every way to build a turret (what turns it, how it knows its angle, its range, homing, a hood, a camera), with the exact lines for each. ## In Robot.java ```java title="Robot.java" turret = add(Turret.motor("turret", "gobilda-5203-117").gearRatio(5).follows(camera)); // a motor turret = add(Turret.motor("turret", "gobilda-5203-312").gearRatio(2.75).homeSwitch("turret_home")); turret = add(Turret.servo("turret").part("gobilda-2000-speed").follows(camera)); // a servo turret = add(Turret.crServo("turret").part("axon-max-mk2").encoder("turret_enc", 8192)); // CR servo + Through Bore turret = add(Turret.crServo("turret").part("axon-max-mk2").analogEncoder("turret_pos").continuous()); // slip ring + absolute encoder ``` **What turns it.** Write one of these: | Made with | What it is | | --- | --- | | `Turret.motor(name, motorId)` | a motor. Its encoder counts the angle | | `Turret.servo(name)` | a standard servo (it goes to an angle by itself). It uses `posA`, `angleA`, `posB`, `angleB` and `travelSec` in Tunables, with no PID control and no homing. A servo cannot say where it is, so **at ▶ the library sends it to `startAngle`** (or to the middle of its range when there is none). In TeleOp after autonomous, it goes where autonomous left it, so it does not jump. From then on the library knows its angle: the stick, following and interlock rules work from the first loop | | `Turret.crServo(name)` + `encoder(port, countsPerRev)` | a CR servo with an encoder on a motor port (REV Through Bore: 8192). The port may also run another part's motor: the turret reads only its count | | `Turret.crServo(name)` + `analogEncoder(port)` | a CR servo with an absolute encoder on an analog port. It knows its angle at once (`encoderOffset`) | **The options:** | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `.gearRatio(r)` | recommended | how many turns the counting device makes per turret turn: the motor (a motor turret) or the encoder (a CR servo turret) | 1 | | `.part(id)` | recommended | which servo it is, from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) | - | | `.reversed()` | optional | the turret turns the other way. Use it when + power turns it clockwise | - | | `.encoderReversed()` | optional | flips a CR servo's encoder. Use it when the encoder counts the wrong way | - | | `.homeSwitch(name)` | optional | a touch sensor or a magnetic switch (a "Digital Device", active low). The turret homes (finds its angle on the switch) at ▶, slowly (`homeAngle`, `homeDirection`, `homingPower`, `homingTimeout`). It sets its angle again each time it passes the switch. When the switch is missing from the configuration, INIT shows a note and the turret uses `startAngle` | no homing: it starts at `startAngle` | | `.continuous()` | optional | a slip ring: no limits, always the shortest way, never "out of range". The angle shows -180 to 180 | it stays inside `min` and `max` | | `.follows(camera)` | optional | follows the camera's goal. With odometry and `Tunables.Aim.goalX, goalY`, the odometry takes over while the camera does not see it ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)) | it does not follow | | `.followsOdometry()` | optional | follows the goal with no camera: from the odometry and `Tunables.Aim`'s goal point | it does not follow | | `.cameraOnBody()` | optional | the camera is on the robot, not on the turret | the camera is on the turret | | `.fullRange()` | optional | a servo turret: the servo's whole turn (500-2500 us, a goBILDA 2000 servo 300 degrees instead of 270). Measure `posA`/`posB` after you turn it on ([full range](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#a-servos-full-range)) | the FTC SDK's normal range | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.looks(shapes...)` | optional | how it looks in the simulator ([Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)) | a plain box | | `.tunables("Name")` | optional | read another `Tunables` section | the device's name in CamelCase | A following turret and whole-robot aim are separate modes: see [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/). ## In Tunables.java The section's name is the device's name in CamelCase: `turret` reads `Turret`. Its angles are in degrees: 0 = straight forward, counterclockwise +. [Setting up a turret](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/) says which lines your turret needs. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class Turret { // "turret" in the configuration public static double min = MEASURE; // furthest right, degrees (Motor Finder) public static double max = MEASURE; // furthest left, degrees: 0 = forward, + = left public static double startAngle = DEFAULT; // where you set it by hand before INIT (0) public static double kP = DEFAULT; // push per degree off (0.02) public static double kD = DEFAULT; // brake near the target (0.001) public static double maxPower = DEFAULT; // the most power (0.8) public static double tolerance = DEFAULT; // "aimed" within this, degrees (1.0) public static double cameraOffset = DEFAULT; // aims a little to one side: Aim Tuner (0) } ``` | Field | What it does | Units | Default | In tuning menu | Found by | When to change | | --- | --- | --- | --- | --- | --- | --- | | `min`, `max` | the range: it never turns past them (`continuous()` ignores them) | degrees | min -90, max 90 | no | measure (turn by hand, read the angle) | the wires or the robot allow more or less | | `startAngle` | where it points at INIT with no switch and no angle from the program before | degrees | 0 (the middle of `min` to `max` when 0 is outside it, with an INIT note). A servo turret: the middle of the range | no | put it there by hand | your start mark is not straight forward | | `kP` | how hard it turns toward the goal, per degree off | power per degree | 0.02 | yes, at once | test | slow to aim (more) or shakes (less) | | `kI` | a push that grows while it stays short | power | 0 | yes, at once | test | it stops a degree short | | `kD` | brakes it as it gets close | power | 0.001 | yes, at once | test | it overshoots (more) | | `maxPower` | the most power | 0 to 1 | 0.8 | no | test | it swings too hard | | `tolerance` | how close counts as aimed | degrees | 1.0 | no | test | the launcher waits too long (more) | | `slowZone` | it slows down within this of `min` and `max` | degrees | 10 | no | test | it hits its ends hard (more) | | `slowZonePower` | the power at the very end of the slow zone | 0 to 1 | 0.25 | no | test | it stalls near an end (more) | | `cameraOffset` | the camera is turned this much from the turret's forward (the turret's own; whole-robot aim uses `Tunables.Aim.cameraOffset`) | degrees | 0 | no | Aim Tuner | shots go a little to one side | | `outOfRangeHold` | an odometry goal this far past a limit, behind the robot, makes it hold where it points | degrees | 10 | no | test | it swings limit to limit when the goal is behind | | `keepAngle` | TeleOp starts from the angle the last program ended at (within 5 minutes) | true/false | true | no | none | you turn the turret by hand between programs: `false` | | `homeAngle` | with a home switch: the turret's angle where the switch closes | degrees | REQUIRED with `homeSwitch(...)` | no | measure ([how](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/)) | the switch moved | | `homeDirection` | with a home switch: which way it turns to find it (+1 counterclockwise, -1 clockwise) | +1 / -1 | from `startAngle` toward `homeAngle` | no | none | it looks the long way round | | `homingPower` | with a home switch: the power while it looks for it | 0 to 1 | 0.2 | no | test | homing is too slow (more) or hits hard | | `homingTimeout` | with a home switch: it stops with a fault when it does not find the switch in time | seconds | 5 | no | test | a slow turret needs longer | | `encoderOffset` | an absolute encoder: its reading with the turret straight forward | degrees | 0 | no | read it at INIT ([how](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/)) | the encoder was moved | | `posA`, `angleA` | a servo turret: one servo position and the turret's angle there | 0 to 1, degrees | REQUIRED for `Turret.servo` | no | Servo Finder | the servo or linkage changed | | `posB`, `angleB` | a servo turret: a second position and its angle | 0 to 1, degrees | REQUIRED for `Turret.servo` | no | Servo Finder | the same | | `travelSec` | a servo turret: time from `posA` to `posB` (not 0 to 1) | seconds | 0.6 (with `.part(...)`: from the servo's catalog speed) | no | test (time it) | it fires before it arrives (more) | ### What each number does, in more words - **`min`, `max`:** degrees, counterclockwise +, 0 = forward. It never turns past them. When the goal is outside, the turret waits at the limit, and the Driver Station says "goal out of turret range". Past +/-180 it picks the way round that stays inside them. - **`startAngle`:** where it points at INIT with no switch. For a motor or CR servo turret, the default is 0. When 0 is outside `min` to `max`, the default is the middle of the range, and INIT shows a note. For a servo turret, it is where the turret goes at ▶, inside its range. It is optional, and its default is always the middle of the range (not 0). - **`kP`, `kI`, `kD`, `maxPower`, `tolerance`, `slowZone`, `slowZonePower`:** a motor or CR servo turret only. A servo turret reads none of these. - **`cameraOffset`:** the turret's own. The library adds these degrees to where the turret points. Whole-robot aim has its own `Tunables.Aim.cameraOffset` ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). - **`outOfRangeHold`:** default 10. An odometry goal this many degrees past a limit, behind the robot, makes it HOLD where it points. So it does not swing from limit to limit as the heading wobbles. It follows again once the goal is back within half of that. - **With a switch:** `homeAngle` (needed), `homeDirection`, `homingPower`, `homingTimeout`. - **An absolute encoder:** `encoderOffset`. - **A servo turret:** `posA`, `angleA`, `posB`, `angleB`, `travelSec`, and `startAngle`. - **`keepAngle`** (default true): TeleOp starts from the angle the last program ended at (within 5 minutes, the same robot app run). So it does not home again after autonomous. The library sends a servo turret there at ▶, instead of to `startAngle`. - **When someone turned the turret by hand since the last program:** an INIT stopped before ▶ forgets the carried angle. So turn the turret to `startAngle`, stop the OpMode in INIT (before ▶), and press INIT again. ## Commands Use them in `Controls.java`, `Actions.java` and autos: `robot.turret.aimAt(45)`. | Command | What it does | | --- | --- | | `aimAt(deg)` | turns to an angle (it stops following) | | `manual(power)` | moves it by hand. Following pauses while the stick moves | | `followMode()` | the mode that follows the goal. It is on from ▶ with `follows` or `followsOdometry`. Switch it with a button ([below](#buttons-to-add)) | | `stop()` | stops | | `static forgetAngles()` | forgets the angle carried from the last program (tests; turning it by hand between programs) | | Question | What it tells you | | --- | --- | | `isAimed()` | whether it is at the target within the tolerance. While FOLLOWING: whether it is at the goal NOW (a goal seen this moment, homed, in range, not held by an interlock, error within the larger of `tolerance` and `Tunables.Aim.toleranceDeg`). So a launcher that waits for it never fires after the goal is lost. A held turret is never `isAimed()` | | `isHomed()` | whether it knows its angle (homed on its switch, or no switch) | | `isHeld()` | whether an [interlock rule](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) holds it back from where it should point | | `isOutOfRange()` | whether the goal is past its range (at a limit, or holding while it is behind) | | `angle()` | the angle | | `aimErrorDeg()` | degrees from the goal now (NaN = unknown) | | `aimSource()` | where the goal came from: CAMERA, ODOMETRY, NONE | | `part()` | the `launcher.Turret` inside | | `zone()` | its zone for an [interlock rule](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) (degrees, repeats every 360) | | `isPresent()` | whether the part is on the robot (an `optional()` part may not be) | **On the Driver Station:** - One line: `Turret : 12 deg AIMED following: camera`. `AIMED` shows only when `isAimed()`: while following, at a goal seen now. Instead of `camera` it can say `odometry`, or `no goal` (it holds where it points). - After ▶: `homing: looking for the switch`. - A servo turret before ▶: `not sent anywhere yet (at ▶: 0 deg)`. ## Buttons to add A part has **no buttons** until you add its lines to `Controls.java`. These are the usual ones. Copy them, or change the button ([how to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line)). - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. You do not change them. - **On gamepad 1, with two drivers:** write `g1` and a free button, for example `g1.rb`. Gamepad 1's LT is slow mode, so do not use it. If you pick a button the library uses, INIT stops and names it. ```java title="Controls.java" g2.rightStickX.use(v -> robot.turret.manual(-v)).says("by hand (right = clockwise)"); g2.rightStickButton.toggle(robot.turret.followMode()).rumble().says("follow the goal on/off"); // only with follows(...) ``` The operator's right stick X turns the turret by hand. A click of the same stick switches following on and off: 2 buzzes = on, 1 buzz = off. Robot 1 uses the same click for its auto-aim. **With one driver:** this line goes on gamepad 1's right stick click, which is also the library's field-centric button. Move field-centric first, as Robot 1 does. In `libraryButtons(...)` in `Controls.java`, write `lib.fieldCentric(null);`. In `buttons(...)`, put field-centric on hold RT, then click the right stick: ```java title="Controls.java" g1.rt.with(g1.rightStickButton, () -> driving().toggleFieldCentric()).says("field-centric on/off"); ``` --- **Look it up:** [`Turret` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Turret.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Wrist URL: https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/ A Wrist shares most of its options, numbers and commands with the [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/). The Claw page lists the shared ones. ## In Robot.java ```java title="Robot.java" wrist = add(Wrist.servo("wrist").part("gobilda-2000-speed")); // Tunables.Wrist: any positions, e.g. down, level, up ``` | Attribute | Needed? | What it sets | If you leave it out | | --- | --- | --- | --- | | `Wrist.servo(name)` | **yes** | a wrist on one servo | - | | `.part(id)` | recommended | which servo it is, from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). When you do not write `travelSec`, the library takes it from the servo's catalog speed | `travelSec` is 0.3 s | | `.alsoServo(name)`, `.alsoServoReversed(name)` | optional | a second servo ([Two servos](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#two-servos-on-one-part)) | one servo | | `.reversed()` | optional | the servo turns the other way | - | | `.fullRange()` | optional | the servo's whole turn ([full range](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#a-servos-full-range)) | the FTC SDK's normal range | | `.optional()` | optional | the part may not be on the robot yet ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | INIT stops when its device is missing | | `.looks(shapes...)` | optional | how it looks in the simulator ([below](#in-the-simulator)) | a plain box | | `.tunables("Name")` | optional | read another `Tunables` section | the device's name in CamelCase | ### In the simulator - A wrist swings an arm shape: `.looks(Shape.arm().on(lift)...angle("folded", -90).angle("flower", -213))`. - A claw can ride on it: `Claw ... .looks(Shape.claw().on(wrist)...)`. - More: [Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts). ## In Tunables.java The section's name is the device's name in CamelCase: `wrist` reads `Wrist`. Every number except `travelSec` and `alsoTrim` is a named position (0 to 1). You choose the names. The table of every number, and how to time `travelSec`, is on the [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#in-tunablesjava) page. **Copy into `Tunables.java`.** Change only what you need. `DEFAULT` keeps the starting value. `MEASURE` means you must measure it ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). ```java title="Tunables.java" public static class Wrist { // "wrist" in the configuration public static double down = MEASURE; // servo position: any name you like public static double level = MEASURE; // servo position (Servo Finder) public static double up = MEASURE; // servo position (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) } ``` ## Commands Use them in `Controls.java`, `Actions.java` and autos: `robot.wrist.goTo("level")`. | Command | What it does | | --- | --- | | `goTo(name)` | goes to a named position | | `next()` | goes to the next position, in order of value. After the last comes the first | | `previous()` | goes to the previous position, in order of value | The questions are the [Claw's](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#commands): `isDone()`, `isAt(name)`, `positions()`, `part()`, `secondServoName()`, `zone()`, `isPresent()`. ## Buttons to add A part has **no buttons** until you add its lines to `Controls.java`. These are the usual ones. Copy them, or change the button ([how to read a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line)). - `g2` is gamepad 2, the operator's. The driver on gamepad 1 drives, and the operator runs the parts. - **With one driver:** set `oneDriver = true` in `Controls.java`. Then the `g2` lines go on gamepad 1. You do not change them. - **On gamepad 1, with two drivers:** write `g1` and a free button, for example `g1.rb`. Gamepad 1's LT is slow mode, so do not use it. If you pick a button the library uses, INIT stops and names it. ```java title="Controls.java" g2.dpadLeft.press(robot.wrist::previous).says("previous position"); g2.dpadRight.press(robot.wrist::next).says("next position"); ``` The operator's D-pad left and right go to the previous and the next position. --- **Look it up:** [`Wrist` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Wrist.html) and [`ServoPositions`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/ServoPositions.html) (every method). **The other parts:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # The robot file URL: https://crossbotics.com/ftc-helper/docs/reference/robot-file/ ## The commands Run every command from the `ftc-helper-lib` folder. A `-P` word after the command is an option: `-Pname=value` gives a setting, and a few options (like `-Plan`) are only on or off. **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:run -Probot=sim/robots/my-robot.properties -Plan ``` `-PteamCode=` points at your robot project's TeamCode. Without it, a command finds `../TeamCode` when the library sits in a robot project. `-PteamCode=none` runs the library's own examples. With `-Plan`, anyone on that WiFi can open the page and run OpModes. Use it on a team or home network, not on open school WiFi. | Command | Does | Options | | --- | --- | --- | | `./gradlew :sim:run` (the **Simulator** button) | the simulator page; first makes the robot file from `Robot.java` | `-Probot=FILE` (default: your `simulator/robot.properties`, else the library's example), `-Plan` (phones on the WiFi), `-Pport=8781` (another port, to run two at once; default 8780), `-PteamCode=DIR`, `-PnoFromRobot` (use the robot file as it is), `-Popen` (open the page in the browser, as the button does) | | `./gradlew :sim:scenario -Pfile=a.sim` (the **Simulator tests** button: no `-Pfile`) | runs test scripts ([Scenario files](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/)); with no `-Pfile` in a robot project: every test in `simulator/scenarios`; first makes the robot file from `Robot.java` | `-Pfile=a.sim,b.sim` (a comma list) or a folder (every `.sim` in it), `-Probot=`, `-PteamCode=`, `-PnoFromRobot` | | `./gradlew :sim:fromRobot` | only makes the robot file from your `Robot.java` (`:sim:run` and `:sim:scenario` do it first) | `-ProbotClass=` (which class), `-Pout=FILE`, `-Pfield=NAME` (default `biobuzz-2026`) | | `./gradlew :sim:updateLibrary` (the **Update library** button) | switches the library folder to its newest release and prints what changed; commits nothing ([Keep it up to date](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/#update-the-update-library-button)) | `-PlibVersion=v0.20.1` (a specific version, or back) | | `./gradlew :sim:installButtons` | adds the **Simulator** and **Simulator tests** buttons to Android Studio now (a Gradle sync in Android Studio adds them too) | | | `./gradlew :sim:fromConfig -Pconfig=FILE.xml` | a first robot file from a robot configuration | `-Pout=FILE`, `-Pfield=NAME` | | `./gradlew :sim:newRobot -Pconfig=FILE.xml` | the five files (Robot.java, ...) from a configuration | `-PteamCode=DIR`, `-Ppackage=` (default `org.firstinspires.ftc.teamcode`) | | `./gradlew :sim:fit` | fits Characterizer logs ([Real speeds](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/#6-real-speeds-optional)) | `-Plog=`, `-Probot=`, `-Pwrite`, `-Pforce` | **Other libraries in TeamCode** (Road Runner, FTC Dashboard...): put their Gradle lines in `simulator/sim-dependencies.gradle` in the robot project. Pedro Pathing needs none: it comes with the library's `pedro` module. ```groovy repositories { maven { url = 'https://maven.brott.dev/' } } dependencies { testImplementation 'com.acmerobotics.dashboard:dashboard:0.4.16' } ``` ## An example ```properties field = biobuzz-2026 # the season's field (sim/fields/biobuzz-2026.json) field.model = fields/biobuzz-2026.glb # optional: the field's 3D model for the 3D view (path from this file) robot.lengthIn = 18 # size, for bumping into field elements robot.widthIn = 18 robot.heightIn = 18 # the chassis box with no shapes, and which overhead field parts it bumps (with shapes, the shapes decide the size rules) robot.tallestIn = 12 # optional: a part the shapes do not draw reaches this high (size rules count it) start.x = -56 # where it starts (inches from the field center; y away from the drivers) start.y = -61.55 # BIOBUZZ G304: touching the wall, outside the LOADING ZONE start.heading = 0 # degrees, counterclockwise; 0 = facing away from the drivers drive.type = mecanum drive.motors = front_left, front_right, back_left, back_right drive.part = gobilda-5203-312 # from the parts catalog: speed, encoder counts, current drive.wheelDiameterIn = 3.90 # the REAL wheel (the Drive Tuner should find it) drive.gearRatio = 1 # motor turns per wheel turn (default 1) drive.strafeEfficiency = 0.85 # mecanum: how much of a strafe really happens (default 0.85) imu = imu motor.lift = lift, part=gobilda-5203-312, min=0, max=2750, gravity=0.06 motor.flywheel = flywheel, part=gobilda-5203-6000, feeder=feeder, shotDrop=0.15 # feeder: a motor, CR servo or servo servo.claw = 0.5, part=gobilda-2000-torque crservo.feeder = # the flywheel's feeder (a CR servo here) camera.front = name=Webcam 1, forward=7, up=12, pitch=20 # see "Cameras" touch.lift_bottom = lift, below=20 ``` ## Every setting | Line | Default | Means | | --- | --- | --- | | `field = NAME` | `biobuzz-2026` | the field file in `sim/fields/` | | `field.model = FILE` | the library's model of the field (`sim/fields/.glb`, BIOBUZZ has one) | the field's 3D model for the 3D view (path from the robot file) | | `parts = FILE.json` | none | your own parts catalog, added to the library's ([parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/)) | | `battery = V` | 12.8 | battery volts at the start (the page's slider: 11 to 13.5) | | `robot.lengthIn`, `robot.widthIn` | 18 | the footprint, for bumping into field parts | | `robot.heightIn` | 18 | the chassis box with no shapes, and which overhead field parts it bumps | | `robot.chassisHeightIn` | 4 with shapes, else `heightIn` | the height of the chassis box | | `robot.tallestIn` | none | a part the shapes do not draw reaches this high (the size rules count it) | | `drive.type` | `none` | `mecanum`, `tank` (2 or 4 motors) or `none` (a test rig) | | `drive.motors = a, b, ...` | none | the wheel motors | | `drive.part` | none | the wheels' motor from the catalog | | `drive.wheelDiameterIn` | 3.78 | wheel size | | `drive.trackWidthIn`, `drive.wheelBaseIn` | 15, 13 | left-right and front-back wheel spacing | | `drive.mirrored` | `left` | which side's motors are mounted mirrored (turn the other way for the same power) | | `drive.strafeEfficiency` | 0.85 | how much of the asked strafe the robot makes (mecanum) | | `drive.kS`, `drive.accelSec`, `drive.turnDegPerCount` | 0, 0.15, worked out | from the Characterizer ([Real speeds](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/#6-real-speeds-optional)) | | `imu = NAME` | none | the IMU's name | | `missing = a, b` | none | devices described in this file but NOT in the configuration: a part not on the robot yet ([Your robot file](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#5-measure-numbers-and-missing-parts)) | | `odometry = KIND NAMES` | none | pretend odometry from the robot's true motion: `pinpoint NAME`, `otos NAME`, `threeWheels L, R, P` or `twoWheels PAR, PERP` ([odometry](https://crossbotics.com/ftc-helper/docs/modules/odometry/#the-simulator)) | | `odometry.offsetsMm = X, Y` | 0, 0 | Pinpoint: where the pods sit (X pod mm left, Y pod mm forward); sets the raw pod counts the Odometry Tuner's Spin test reads | | `odometry.mountIn = F, L, H` | | OTOS: where it sits (written from Robot.java); the pretend OTOS reports the center's pose, so it does not change the simulation | | `odometry.trackWidthIn` | 12 | three dead wheels: left to right pod, inches | | `odometry.parallelLeftIn`, `odometry.perpForwardIn` | 0, 0 | dead wheels: the forward pod's inches left (two wheels), the sideways pod's inches forward | | `odometry.ticksPerIn` | 505.3 | dead wheels: pod counts per inch (goBILDA 4-bar pods) | | `odometry.reversed = names` | none | these pods count backward (as wired; the code's `reversed(...)` turns them back): dead-wheel port names, or `x`/`y` for a Pinpoint's pods | | `odometry.scaleError` | 0 | noise: 0.01 = it measures 1% too far (wheel slip, a wrong pod size) | | `odometry.driftDegPerMin` | 0 | noise: the heading creeps this many degrees per minute | | `motor.NAME = KIND, ...` | | a motor: `free`, `lift` or `flywheel`, then `part=`, `ticksPerRev=` (catalog, else 537.7 or 28 for a flywheel), `rpm=` or `maxTicksPerSec=` (catalog, else 2780), `min=`, `max=` (counts), `gravity=` (0), `kS=` (0), `accelSec=`, `coastSec=`, `feeder=` (a motor, CR servo or servo that feeds a flywheel; a motor or CR servo feeds only on + power, so backward feeds nothing), `feederPush=` (a servo feeder: where it goes to push; a push counts once it is half way there. Without it, once it is 0.15 from its start. `:sim:fromRobot` writes it from `Tunables` `push`), `shotDrop=` (0.15: how much a shot slows the wheel), `stage=CRSERVO` (a feed wheel that brings the pieces to a servo `feeder`: a push sends a piece only if this wheel ran at least 0.05 s before the arm started to move out; `:sim:fromRobot` writes it for [`feedWheel(...)`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/)), `stop=SERVO`, `stopOpen=` (0.5) (a feed stop: pieces get through only while that servo is within 0.05 of `stopOpen`; `:sim:fromRobot` writes it for [`feedStop(...)`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#firing-shot-modes-feed-stop-piece-path)), `drivenBy=CRSERVO` (no motor on this port: only an encoder, on a shaft that CR servo turns, e.g. a CR servo turret's Through Bore), `with=FIRST` (a second motor on the same slide or arm as the motor `FIRST`: both turn one shaft and both push, so each carries half its `gravity`; `mirrored=true`: its shaft turns the other way, two motors facing each other. `:sim:fromRobot` writes it for [`alsoMotor`](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm)) | | `servo.NAME = START, ...` | start 0.5 | a servo: `part=` (catalog), or `rangeDeg=` and `secPer60=` for one not in the catalog. `pwm=500-2500`: the robot's code uses the servo's full range (`.fullRange()`; `:sim:fromRobot` writes it); the start position and every position in the file are then in that range. Like the hub, the simulated servo gets the normal 600-2400 us at each INIT and the code's `setPwmRange` after, so 0 to 1 turns a goBILDA 2000 servo 270 degrees, or 300 with full range | | `servo.speed` | 1.0 | positions per second for a servo with no part | | `crservo.NAME =` | | a continuous servo (the value is not used) | | `light.NAME = gobilda` or `blinkin` | | a colored light ([`Lights`](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/)): a goBILDA RGB Indicator Light (a servo) or a REV Blinkin; the page shows its color on the robot, on the 3D view and in the Servos tab | | `touch.NAME = MOTOR, below=N` | below 20 | a switch pressed while that motor is within N counts of its `min` (reads `getState()` false when pressed) | | `touch.NAME = MOTOR, at=C, width=W` | width 10 | a switch part way along: pressed while that motor is within W counts of C (counts from where it starts), e.g. a turret's home switch | | `analog.NAME = MOTOR, offsetDeg=D` | offsetDeg 0 | an absolute encoder on that motor's shaft (0 to 3.3 V per turn), reading D degrees at the start: a CR servo turret's angle sensor | | `color.NAME = at=ready` | | a color sensor with distance (REV Color Sensor V3) that sees the piece at one spot: `at=ready` (next to fire) or `at=intake` ([game pieces](#game-pieces)) | | `distance.NAME = at=intake, acrossMm=150` | `acrossMm=150` | a distance sensor across a channel: `acrossMm` minus the piece's size when one is there ([game pieces](#game-pieces)) | | `camera.NAME = ...` | | a webcam or Limelight ([cameras](#cameras)); `on=turret`: it turns with the turret | | `huskylens.NAME = ...` | | a HuskyLens ([cameras](#cameras)); `taught=` says what it was taught | | `shape.NAME = TYPE, ...` | | a part to draw and check ([robot shapes](#robot-shapes)). Sizes when `size=` is left out: slide 2x2x12, arm 10x2x2, turret 8x8x2, claw 3x1x3, roller 2x12x2, flywheel 4x2x4 | | `collect.NAME = shape=a+b, motor=M, holds=N` | `reach=0.75`, `holds=4` | takes pieces in ([game pieces](#game-pieces)); `crservo=` instead of `motor=`, `inward=-`; `limits=NECTAR:0+POLLEN:3`: the most of one kind (`0` = never that kind; a name matches every kind that contains it). Preload pieces that do not fit wait on the tiles behind the robot | | `shoot.NAME = shape=S, ...` | `angle=40`, `share=0.5` | shoots pieces: `spin=`, `speed=` (a fixed speed, in/s), `table=` (a shot table, path from the robot file), `flywheel=` (which flywheel, when there are two), `hood=SERVO, hoodAt0=A, hoodAt1=B` (the angle follows a hood servo: A with the servo at 0, B at 1) | | `grab.NAME = shape=S, servo=V, closedBelow=X` | `reach=0.5` | a claw that holds a piece (`closedAbove=` for one that closes toward 1) | | `start.x`, `start.y`, `start.heading` | | where the robot starts | | `preload = on/off` | on | the field file's preload in the robot at the start | | `physics = engine/simple` | engine | the physics engine, or the old "a bump stops the move" rule | | `tunable.SECTION.FIELD = N` | none | a stand-in for a Tunables number written `MEASURE`: the simulator uses N in its place ([MEASURE in the simulator](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#5-measure-numbers-and-missing-parts)) | A flywheel's rim speed comes from its `flywheel` shape. The diameter is the larger of the shape's forward and up sizes. ## Robot shapes The simulator can draw the robot as simple shapes: the chassis box, plus parts from a short menu, each moved by its motor or servo. The 3D view draws them. The simulator checks the size rules with them: the 18 in start cube, and 18 x 24 in and 29 in tall (R105), now and **at full reach** (every moving part tried over its whole range). The Control Hub panel shows the sizes in green or red. ```properties robot.chassisHeightIn = 4 # shape.NAME = TYPE, on=PARENT, at=forward,left,up, size=forward x left-right x up, then what moves it shape.lift = slide, at=-7,0,4, size=2x8x8, axis=up, motor=lift, ticksPerIn=344 shape.arm = arm, on=lift, at=0,0,8, size=9x1.5x1.5, axis=left, motor=arm, gear=3.5, start=-90 shape.wrist = arm, on=arm, at=9,0,0, size=2.5x1.5x1.5, servo=wrist, pos0=-90, pos1=90 shape.claw = claw, on=wrist, at=2.5,0,-1.5, size=2x0.5x3, servo=claw, pos0=0, pos1=3 shape.intake = roller, at=8,0,1.5, size=2x14x2, motor=intake shape.flywheel = flywheel, at=-1,0,4, size=4x2x4, motor=flywheel ``` Any shape can also take `tilt=DEG`: mounted at an angle on its parent, turned about the left-right line, front up +. A roller can take `reversed=yes`: it turns the other way from its motor, through gears. It can also take `soft=yes`, for soft tubing or flaps that bend. Game pieces touch a soft roller, but the field does not stop it, and it still counts for the size rules. | Type | What it is | Where `at` points | Moves by | | --- | --- | --- | --- | | `box` | a part that does not move | the middle of its bottom | nothing | | `slide` | a lift or extension: a fixed stage and a moving stage along `axis` (up, down, forward, back, left, right); `size=` is ONE stage | the bottom of the fixed stage | motor: `ticksPerIn=` or `spoolIn=` (spool diameter, one-stage only: a cascade's top moves faster than its string); servo: `pos0=`/`pos1=` inches | | `arm` | turns about a hinge; `axis` is the hinge line (`left`, the default: + raises the front; 0 = level forward, +90 up, -90 down) | the hinge; the box reaches forward from it | motor: `ticksPerDeg=`, or `gear=` (motor turns per arm turn: counts per degree = the motor's counts per turn x gear / 360), and `start=` degrees at the bottom stop; servo: `pos0=`/`pos1=` degrees | | `turret` | turns about up (+ = left) | the middle of its bottom | like `arm` | | `claw` | two fingers: `size=` palm depth x finger thickness x finger length; the fingers point up from the palm (in the claw's frame) and open left-right | the middle of the palm | servo: `pos0=`/`pos1=` the gap in inches | | `roller` | an intake roller (a cylinder along `axis`, default across the robot) | its center | spins with its `motor=` or `crservo=` | | `flywheel` | a launcher wheel | its center | spins with its `motor=` | Notes: - `passive=yes` (arm or slide): gravity or springs move it, not the code (a floating intake, a sprung flywheel mount). The simulator draws it at `start=`. The size rules try its whole range (`minDeg=`/`maxDeg=` or `travel=`). `drop=SERVO>0.6` (or `<`) with `fallsTo=`: once that servo passes the position, the part falls to that end and stays. An example is an intake folded up at the start and pushed over at ▶. A new match puts it back. `Robot.java` writes these with `Shape.passive()` and `Shape.dropsWhen(...)` ([robot module](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)). - `on=` puts a part on another (default: the chassis). A part on a slide rides on its moving stage (`at=0,0,` is the moving stage's top). A part on an arm turns with it. Its `at=` is from the hinge, so `at=9,0,0` is the tip of a 9 in arm. - Directions are the robot's: forward, left, up. `at=` is in inches from the parent's mounting point. - The range of motion comes from the motor's hard stops (`min=`/`max=` on `motor.NAME`), the servo's `pos0`..`pos1`, or `travel=` (slide) / `minDeg=`, `maxDeg=` (arm, turret). The size check at full reach uses it. A real robot needs hard stops there too: inspectors check the biggest it can get. - With `physics = engine` (the default), the shapes' boxes also bump into the field and push game pieces. - Mistakes stop the simulator with the line's name: - an unknown parent, motor or servo. - a loop. - a moving part with no range of motion. Give the motor `min=` and `max=`, or `travel=` / `minDeg=` `maxDeg=`. - a word with no `=` after the first one. `at=-7,0,4` is fine: it is a list of numbers. - A `#` after a space starts a note. `color=#ff0000` is a color, not a note. - Nothing may go below the tiles. The panel and `expect size floor ok` show it. A part there would hit the floor on a real robot, so the shapes or the hard stops are wrong. Scenario checks: `expect size start ok` (fits the 18 in cube now), `expect size match ok` (18 x 24 x 29 now), `expect size most ok` (every pose at full reach), `expect size floor ok` (nothing below the tiles now). `fail` instead of `ok` checks the opposite. Also `print size`, and `print cad` (see CAD models below). How the simulator checks "at full reach": it tries every combination of the moving parts' important values. A slide or claw is biggest at an end of its range. The simulator tries a hinge (arm, turret) at both ends, at each multiple of 90 degrees, and every few degrees between. That is every 5 degrees or less with a few moving parts, and coarser with many, to stay under 50,000 poses. The panel shows the worst pose. It is a careful check, not a proof: leave a little margin, and measure the real robot at its hard stops. ## Game pieces Which robot shapes handle the pieces. `:sim:fromRobot` writes these lines from Robot.java. ```properties # take in a piece within 0.75 in of the intake shape while motor "intake" turns inward (power above 0.2; # inward=- if negative power takes in; crservo= instead of motor=); it holds 4. Several shapes with + # (shape=intake+left_spinner+right_spinner): a piece comes in at any of them collect.intake = shape=intake, motor=intake, holds=4 # each flywheel shot (motor.flywheel = flywheel, feeder=feeder) sends a held piece off this shape. # The feeder is a motor or CR servo (a piece each time it starts; one more every 0.3 s from 0.45 s on # while it keeps running), or a servo that pushes # (an indexer: it feeds while it is more than 0.15 away from where it starts). The shot leaves # 45 degrees up from the shape's forward (angle= defaults to 40), at half the wheel's rim speed shoot.launcher = shape=flywheel, angle=45, share=0.5 # the claw holds a piece in its fingers while servo "claw" is below 0.3, and drops it when it opens # (a claw that closes toward 1: closedAbove=0.5 instead) grab.claw = shape=claw, servo=claw, closedBelow=0.3 ``` A robot with a `collect.` or `shoot.` line starts with the field file's preload inside it. BIOBUZZ: 4 POLLEN, and `holds=4` is the game's rule (no more than 4 at a time). A robot with only a `grab.` line gets the preload on the tiles, touching its back. A robot with none of the three gets none. With a `shoot.` line, a shot needs a piece: no piece, no shot. A piece that comes into a goal (a FLOWER top) scores. It drops onto that FLOWER's stack and stays there ([Game rules and the score](https://crossbotics.com/ftc-helper/docs/guides/how-the-simulator-works/#game-rules-and-the-score)). "Back to start" puts the pieces back. The Control Hub panel shows what the robot holds, what it shot and what scored. The 3D view and the field from above draw the pieces. **Piece sensors** (for [`Pieces` and `PieceSensor`](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/)): ```properties # a color sensor at the "ready to fire" slot: it sees the next piece to fire (the oldest held) in the # field file's color, 15 mm away; nothing there: dark gray, 120 mm color.ready_color = at=ready # at=intake: it sees each piece the intake takes in, for 0.25 s color.intake_color = at=intake # a distance sensor across a 150 mm channel: 150 minus the piece's size (reads 79 mm with a POLLEN, 59 mm with a NECTAR) distance.intake_distance = at=intake, acrossMm=150 ``` ## Cameras ```properties # name = the name in the robot configuration. Where it sits: inches forward/left/up from the robot's # center on the floor; yaw (+ = turned left) and pitch (+ = tilted up) in degrees. roll = turned around the # lens, in degrees (180 = upside down). hfov = how wide it sees, in degrees (Logitech C920 at 640x480: about 70; # C270: 42.5). Defaults: 0, 0, 10, 0, 0, 0, 70.4, 640, 480. camera.front = name=Webcam 1, forward=7, left=0, up=12, yaw=0, pitch=20, hfov=70.4, width=640, height=480 ``` For a robot in five files, `:sim:fromRobot` makes this line from Robot.java. Its `pitch` is the camera's `pitchDeg` in Tunables when you wrote one, else 30 (a guess). A webcam with `.upsideDown()` gets `roll=180`. Change `forward`, `up` and `hfov` to your robot's. **Limelight 3A**: the same settings with `limelight.` (hfov default 54.5, from its spec sheet). ```properties limelight.ll = name=limelight, forward=6, left=-3, up=14, yaw=0, pitch=25 ``` **HuskyLens**: the same settings with `huskylens.`. It gives boxes in its 320 x 240 screen. The hfov default 60 is a guess: use the number you measured. `taught=` lists what you taught it, in order: tag numbers, or piece names from the field file for colors and objects. `-` skips a number. ```properties huskylens.h = name=huskylens, forward=6, up=12, pitch=30, hfov=60, taught=34|35|36|37 huskylens.p = name=piececam, forward=8, up=8, pitch=-15, taught=POLLEN|NECTAR ``` **A camera on a turret** (or an arm or slide): add `on=` and the shape's name. The camera then turns (and moves) with that part. Measure forward/left/up/yaw with the turret pointing straight forward (its angle 0). `:sim:fromRobot` writes `on=turret` by itself when Robot.java has a turret that `follows(camera)` (without `cameraOnBody()`). It also puts the flywheel on the turret, so the shots go where the turret points. Without `on=`, the camera stays fixed to the chassis while the turret turns. The turret then turns to its limit, or stops off the goal while it says AIMED. ```properties shape.turret = turret, at=0,0,8, size=6x6x2, motor=turret, ticksPerDeg=7.467 limelight.ll = name=limelight, forward=6, left=0, up=12, yaw=0, pitch=30, on=turret ``` **Pretend venue lighting** lets you try the library's [lighting test](https://crossbotics.com/ftc-helper/docs/modules/vision/#venue-lighting). `goodPipelines=1|2` on a `limelight.` line finds tags only on those pipelines. `goodExposureMs=4-10` on a `camera.` line finds tags only with a manual exposure in that range. Put 0 in the range for the camera's own automatic exposure. Without them, every setting finds tags. ```properties limelight.ll = name=limelight, forward=6, up=14, pitch=25, goodPipelines=2 camera.front = name=Webcam 1, forward=7, up=12, pitch=20, goodExposureMs=5-8 ``` ## CAD models ```properties cad.units = mm # the unit in the export window: mm, cm, m or in (required) cad.axes = y,-x,z # the CAD axes that point the robot's forward, left and up (required) cad.origin = 0,0,0 # the robot's center on the floor, in CAD units (default 0,0,0) robot.model = cad/chassis.stl # drawn in place of the chassis box shape.lift = slide, ..., model=cad/lift-stage.stl, baseModel=cad/lift-base.stl shape.arm = arm, ..., model=cad/arm.stl ``` - `cad.axes`: look at the CAD's axis triad. Onshape and SolidWorks have up = z (if the robot's front points along +y: `y,-x,z`). Fusion usually has up = y (front along +x: `x,-z,y`). A minus sign means the other way. The simulator refuses a choice that would draw the robot mirrored. - `model=` rides the moving part: a slide's moving stage, an arm or turret, a claw's palm (its fingers stay boxes, so the gap shows), a roller (it spins), a box. `baseModel=` is a slide's fixed stage. - `cadPose=` on a shape: the value (inches or degrees) that the part is at in the CAD, when that is not the start. - A roller's or flywheel's model must hold only the parts that spin (wheels, hubs, shaft). The size rules count a spinning model as the whole circle it sweeps. So a servo bracket in it would make the robot look bigger than it is. - When the `robot.model` CAD already draws a fixed `box` shape (a tower, a hood), you can delete the box: the CAD now decides the size there. Keep the box only if it should bump into things on its own. **5. Check it.** `print cad` in a scenario prints the settings in words. Then it prints each model next to the box it covers: its size, and how far its middle is from the box's. "FAR from its box" means that `cad.origin`, `cad.axes` or the shape's `at=` is wrong (for `robot.model`, almost always `cad.origin`). "25 times smaller" means that `cad.units` is wrong. Then make each `size=` close to its CAD size, because the boxes are what bump into things. Look at the 3D view too. - The simulator can read up to 12,000,000 triangles in all. It simplifies a model with more than 300,000 for the 3D view: small details like bolt threads blur, and `print cad` says so. The size rules use each model's outside (its convex hull), plus a small margin (about 1/200 of the part's size). So they never call a robot smaller than its CAD. A roller's model counts as everything it reaches while it spins. - CAD from a seller (a kit's STEP or Onshape files) belongs to the seller. Keep it in your team's repository, not in a public one, unless the seller's terms allow it. ## Physics ```properties robot.massKg = 15 # the robot's mass (default 15) drive.grip = 1.0 # how hard the wheels can push, as a share of the robot's weight (about 1 on tiles) physics = engine # the default; "simple" = the old rule: a bump stops the whole move, no sliding ``` --- # Robot.java URL: https://crossbotics.com/ftc-helper/docs/reference/robot-java/ What every part shares: `define()`, `drive(...)`, `add(...)`, parts that are not on the robot yet, parts not in the catalog, and shapes for the simulator. Each part has its own page: [Reference](https://crossbotics.com/ftc-helper/docs/reference/). Learn it step by step: [Robot.java: what is on the robot](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/). Package: `com.crossbotics.ftchelper.robot`. Worked examples: [`examples/.../gobildabot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/gobildabot) (goBILDA's starter bot), [`flywheelbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/flywheelbot) and [`turretbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/turretbot). The [cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/) has code to copy. ## The five files A team's whole robot program is five files. Each file answers one question. Each mechanism is a **module**: one line in `Robot.java` that brings its own numbers and autonomous steps. Its buttons are lines in `Controls.java`. | File | Answers | Changes when | Reference | | --- | --- | --- | --- | | `Robot.java` | What is on the robot, and its name in the configuration? | a part is added, moved or renamed | this page | | `Tunables.java` | What are the numbers? | tuning (speeds, positions, PID) | [Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/tunables/) | | `Controls.java` | Which button does what? (It is also the TeleOp.) | the drivers change their minds | [Controls.java](https://crossbotics.com/ftc-helper/docs/reference/controls/) | | `Actions.java` | Which steps use several parts together? | a new combo move | [Action](https://crossbotics.com/ftc-helper/docs/reference/steps/#action) | | `autos/` | What does the robot do on its own? | new or changed autonomous programs | [Steps for autos](https://crossbotics.com/ftc-helper/docs/reference/steps/) | For a new robot, `./gradlew :sim:newRobot` writes the five files from the robot configuration ([Making the files](#making-the-files)). A part added later is one line in `Robot.java`. Its numbers and its simulator lines come with it. Its buttons are lines in `Controls.java`.
flowchart LR
    R["Robot.java<br/>drive + modules"] --> C["Controls.java<br/>(TeleOp)"]
    R --> A["autos/*.java"]
    T["Tunables.java<br/>numbers"] --> R
    X["Actions.java"] --> C
    X --> A
    R --> S["simulator robot file<br/>(:sim:fromRobot)"]
## Every class | Class | Use it to | Page | | --- | --- | --- | | `RobotDefinition` | describe the robot in `Robot.java`: `drive(...)` and one `add(...)` per mechanism | [below](#robotdefinition) | | `Drive` | the drivetrain: mecanum or tank, motor names, motor, wheel, IMU | [Drive](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/) | | `Odometry` | where the robot is on the field: a goBILDA Pinpoint, a SparkFun OTOS, or dead wheels | [Odometry](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/) | | `PathFollower`, `PathAt` | a path-following add-on (Pedro), and things to start along a path | [PathFollower](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/) | | `Intake` | a roller on a motor and/or CR servos: in, out, on at the start | [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/) | | `Lift` | a slide on a motor with named heights and a bottom switch | [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/) | | `Arm` | an arm on a motor with named angles in degrees | [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/) | | `Claw` | a claw servo: open, closed | [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/) | | `Wrist` | a wrist servo with named positions | [Wrist](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/) | | `Positioner` | any servo with named positions (deploy, fold, gate) | [Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/) | | `Turret` | a turret inside its limits, by hand or following the camera's goal | [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/) | | `Interlock` | two parts that must never be in their zones at the same time | [Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) | | `Launcher` | a flywheel and its indexer: spin up, fire, speed from distance | [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/) | | `Indexer` | feeds one piece at a time (servo, CR servo or motor) | [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/) | | `Hood` | a launcher's hood (servo or motor): its angle from the shot table, by hand, a trim | [Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/) | | `Camera` | a Limelight or webcam; the alliance's goal | [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/) | | `Aim` | aim the robot or the turret at the goal | [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/) | | `Pieces`, `PieceSensor` | which game piece is at a spot (color sensor, distance sensor, second webcam); how many the robot holds and which fires next | [Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/) | | `Lights`, `LightColor` | a colored light for the drivers (goBILDA RGB Indicator Light or REV Blinkin): which color when | [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/) | | `Action` | steps across several parts that never block (never make the loop wait) | [Action](https://crossbotics.com/ftc-helper/docs/reference/steps/#action) | | `Mode` | a rule a module follows every loop while the mode is on | [Modes](https://crossbotics.com/ftc-helper/docs/reference/steps/#modes) | | `ControlMap`, `Pad`, `Toggleable` | `Controls.java`: the TeleOp and the button map; anything one button switches on and off | [Controls.java](https://crossbotics.com/ftc-helper/docs/reference/controls/) | | `Auto`, `Steps` | one autonomous as a list of steps | [Steps for autos](https://crossbotics.com/ftc-helper/docs/reference/steps/) | | `Feature` | what the library does by itself for your robot, ready or not (`robot.features()`) | [below](#what-your-robot-can-do) | | `EncoderMotor` | one motor for the [Encoder Check](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#encoder-check-each-encoder-cable-in-its-own-port) (`robot.encoderMotors()`) | [below](#robotdefinition) | | `Motors` | the encoder counts and speed of common motors, by catalog id (a part's name in the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/), e.g. `"gobilda-5203-312"`) | [below](#motors) | | `Shape`, `Parts` | how each part looks and where it sits, for the simulator; wheels, rollers and servos by catalog id | [below](#shapes-and-parts) | | `Module`, `MotorPositions`, `ServoPositions`, `Devices` | what the modules share (most code does not use these by name) | [below](#module) | ## RobotDefinition ```java public class Robot extends RobotDefinition { public Intake intake; public Lift lift; public Claw claw; @Override protected void define() { drive(Drive.mecanum("front_left", "front_right", "back_left", "back_right") .motor("gobilda-5203-312").wheelMm(96) .imu("imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD)); // .part(...): which motor or servo it is, by the id on its label (optional, recommended) intake = add(Intake.motor("intake").part("gobilda-5203-1150")); lift = add(Lift.slide("lift").part("gobilda-5203-435").bottomSwitch("lift_bottom")); claw = add(Claw.servo("claw").part("gobilda-2000-torque")); atStart(() -> Actions.deployIntake(this)); // optional: an action right after ▶ (start) } } ``` - **Name each part** with `.part(...)`. For a launcher, an arm or a motor turret, write the motor's id in its brackets. For the drive, use `.motor(...)`. It is optional, but recommended. With the part named, the starting values come from that part's real numbers, and the simulator moves it like the real one ([First run](https://crossbotics.com/ftc-helper/docs/reference/tunables/#first-run-what-you-get-before-tuning)). For a part not in the catalog, see [Parts not in the catalog](#parts-not-in-the-catalog). - **`define()` only describes the robot.** It runs in INIT, and also without a robot (to write the simulator file). The OpMode classes make the hardware (`setup`) and update every part each loop. Nothing moves in INIT. - **What INIT checks:** a device name used twice, two parts (or a part and an interlock rule) that read the same Tunables section, an indexer added twice. Each stops INIT with the name. | In `define()` | What it does | | --- | --- | | `drive(Drive d)` | the drivetrain (required) ([Drive](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/)) | | `odometry(Odometry o)` | optional: what tells the robot where it is on the field ([Odometry](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/)) | | `follower(PathFollower.Maker m)` | optional: a path follower, e.g. `follower(Pedro.follower(...))` ([PathFollower](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/)). It needs an `odometry(...)` line | | `T add(T module)` | a mechanism. It gives the mechanism back, so you can keep it in a field (`lift = add(...)`) | | `add(...optional())` | a part that may not be on the robot yet: while its device is not in the configuration, the part is off and INIT does not stop ([Parts not on the robot yet](#parts-not-on-the-robot-yet)) | | `atStart(Supplier)` | an action that runs once right after ▶ (start on the Driver Hub), in autonomous and TeleOp | | `Interlock keepApart(name, zoneA, zoneB)` | an interlock rule: two parts never in their zones at the same time. Write it after the parts' `add` lines. Its numbers are in `Tunables.` ([Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/)) | | `tunables(Class)` | the Tunables class, if it is not `Tunables` in the same folder | | `addOwn(Subsystem)`, `everyLoop(Runnable)` | your own code with the robot's loop (also after INIT, from `Controls.java`): [Your own code every loop](#your-own-code-every-loop) | | `chassisMm(l, w, h)`, `heightMm(h)`, `fixed(Shape...)` | for the simulator: the chassis box, the whole robot's height, parts the code does not move ([Shapes](#shapes-and-parts)) | | `fieldMap(FieldMap.margin(13).keepOut(...))` | the places the robot must not drive through, for `routeTo(...)` and `route(...)` ([keep-out boxes and routes](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes)) | | `cameraFix(camera)` | ALPHA: nobody has tested it, and it is not for BIOBUZZ. A Limelight corrects the odometry ([camera fix](https://crossbotics.com/ftc-helper/docs/modules/odometry/#camera-fix-alpha)) | | For your code | What it does | | --- | --- | | `run(Action)`, `cancel(Action)`, `cancelAll()` | starts or stops actions | | `atInit(Runnable)`, `duringInit(Runnable)`, `atStop(Runnable)` | runs your own code once at INIT, every pass of INIT, and at STOP | | `wasStarted()` | whether ▶ was pressed | | `pauseAll()`, `resume()`, `togglePause()`, `isPaused()` | stops every part and holds it stopped, goes on again, switches between the two, and tells whether it is paused ([Pause](#pause-and-stop)) | | `setAlliance(Alliance)` | sets this match's alliance. The OpMode classes do this for you, so use it only in your own plain OpMode | | `driveWith(gamepad)`, `driveWith(forward, strafeRight, turnRight)` | drives from a gamepad, or from your own numbers (forward, strafe right and turn right are +). Only in your own plain OpMode, after `robot.init(this)`. Anywhere else it stops with an error | | `interlocks()` | the interlock rules from `define()` (read only) | | `alliance()` | this match's alliance (from autonomous's menu; TeleOp remembers it) | | `notes()` | INIT notes: missing Tunables sections or fields (the library uses its defaults), parts that are off (not in the configuration) | | `checkConfiguration(hardwareMap)` | one line per device Robot.java names that is NOT in the configuration, and what that means ("INIT will stop", or "optional, so the part is off"). The [Hardware Check](https://crossbotics.com/ftc-helper/docs/modules/testing/#hardwarecheckopmode) shows it | | `modules()`, `drive()`, `all()` | the parts, the drivetrain, the update group | | `encoderMotors()` | every motor Robot.java names, as `EncoderMotor`s for the [Encoder Check](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#encoder-check-each-encoder-cable-in-its-own-port): the drive first, then each part's. See the `EncoderMotor` table below. No hardware needed | | `pose()` | where the robot is now, from the odometry: a [`FieldPose`](https://crossbotics.com/ftc-helper/docs/modules/util/#fieldpose) (x in right, y in away from your wall, heading 0 = away, counterclockwise +). It is a copy, and null with no odometry line | | `odometry()`, `odometrySpec()`, `odometryChecked()` | the running [`PoseTracker`](https://crossbotics.com/ftc-helper/docs/modules/odometry/#posetracker) (null before `setup`), the odometry line as written, and `Tunables.Odometry.checked` | | `resetPose()` | "set pose here": the pose becomes the reset spot in `Tunables.Odometry` (`resetX`, `resetY` inches, `resetHeading` degrees, as seen from your wall, written for BLUE; RED mirrored like the start spot). It gives false (nothing changed) with no odometry or no spot. TeleOp's G1 START held 1 s calls it ([Set pose here](https://crossbotics.com/ftc-helper/docs/reference/controls/#set-pose-here)) | | `resetPose(x, y, headingDeg)` | the same with a spot of your own (for BLUE, mirrored for RED). It stops with a message if there is no odometry | | `follower()`, `hasFollower()`, `makeOdometry(hardwareMap)` | the running path follower (null before `setup`), whether there is a follower line, and the odometry alone for a tool (Pedro's tuners) | | `robotConfig()` | the drive settings for `EasyTeleOp`/`EasyAuto` | | `simLines()` | the simulator robot file's lines from the code | | `setup(hardwareMap)` | makes every module's hardware (the OpMode classes call it in INIT). `setup(devices)` with [pretend devices](https://crossbotics.com/ftc-helper/docs/modules/testkit/) in a test | | `startForTests()` | in a JUnit test only: what ▶ does (each part's start, the `atStart` actions). The OpMode classes do it themselves ([testkit](https://crossbotics.com/ftc-helper/docs/modules/testkit/)) | | `checkTunables()` | the Tunables name checks of INIT, without a robot: one line per problem (a field no part reads, a section that looks meant for a part). `:sim:fromRobot` prints them | | `sectionWarnings()` | after `setup`: INIT's warnings about Tunables sections no part reads that look meant for one | | `tunablesClass()` | the Tunables class found (null if none) | | `static changedTunables()` | values tuned on the robot that differ from Tunables.java, as lines to copy back | | `static freshRobotApp()` | tests and the simulator only: forget what one program leaves for the next (the last autonomous's alliance, pose and report, turret angles, launcher trims, tuned numbers in memory), as if you turned the robot on that moment. Never use it in robot code | | `static sectionName(device)` | the Tunables section a device reads: "intake_deploy" -> `IntakeDeploy` | | `EncoderMotor` | What it is | | --- | --- | | `name`, `reversed`, `part` | the motor's name, whether it is reversed, and its catalog id | | `encoderRead` | whether something reads its encoder (false for an intake, for example) | | `pushSign()` | +1 or -1: which way it has room, from Tunables.java | | `skip()` | why it is not checked, e.g. its port reads an odometry pod | | `isOptional()` | whether the part is `optional()` | | `alsoMotors()` | a second motor pushed with it, like a lift's second motor | ## Tunables.java The numbers of every part are in `Tunables.java`: one section per part, named after the device's configuration name in CamelCase. [Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/tunables/) explains how it works, the names and what INIT checks. Each part's own numbers are in the **In Tunables.java** table on its page. ## DEFAULT and MEASURE You can write two words in `Tunables.java` in place of a number you do not have yet: `DEFAULT` (the library's starting value) and `MEASURE` (INIT stops until you measure it). They come from `Starting`. [DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure) has the whole story. ## Your own code every loop Code the library has no part for (a bucket of your own, a value to log) runs with the robot's loop: ```java // Controls.java, in buttons(robot, g1, g2) (it has the hardwareMap; an autonomous: in steps(...)) robot.addOwn(new Bucket(hardwareMap)); // class Bucket implements Subsystem robot.everyLoop(() -> lastHeight = robot.lift.position()); // a small piece of code ``` | Write | What it does | | --- | --- | | `addOwn(part)` | your part (a class that `implements Subsystem`). Its `update()` runs every loop after ▶, after the library's parts. Its `stop()` runs at STOP **and when the robot pauses** (BACK), so a motor in it stops with the rest. It is not updated while paused. Nothing runs in INIT: make its hardware in its constructor, and never move anything there. Use it in `define()` for a part with no hardware, or after INIT | | `everyLoop(code)` | runs a `Runnable` every loop after ▶ (not while paused). It has no `stop()`: for code that moves a motor, use `addOwn` | Pause stops every part in `all()` that is not the library's own, including one added the old way with `robot.all().add(...)`. A second motor on a lift or arm needs none of this: use `alsoMotor` ([Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/)). ## What your robot can do The library does some things by itself, once your robot has the parts for them. `robot.features()` lists them. It works them out from Robot.java alone (no hardware). Each one is **ready**, with the line to use it, or **not ready**, with what to add. The simulator's auto builder shows this list ("What this robot can do"), and its Action list starts with the ready actions. | Feature | Kind | Needs | The line | | --- | --- | --- | --- | | Fire 1, Fire 2 ... Fire all | action | a launcher | `robot.launcher.fireAction(2)`, `robot.launcher.fireAllAction()` | | Ready to launch | auto step | a launcher: spins up and waits until ready | `.readyToLaunch("Ready", 3)`, the action `robot.launcher.readyAction(3)` | | Wait for the goal | auto step | a camera with `goal(...)`: waits until it sees the goal, still, then goes on | `.waitForGoal("Wait for the goal")` (no limit), `.waitForGoal("Wait for the goal", 10)` | | Shot modes: CAREFUL, QUICK, SPRAY | automatic | a launcher ([Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/)) | (nothing to write; SPRAY: `sprayEnabled = true`) | | Feed stop | automatic | a feed stop servo | `.feedStop("feed_stop")` on the launcher | | Piece path: parts that push a piece in | automatic | an intake that pushes pieces into the wheel | `.pushedBy(intake)` on the launcher | | Feed wheel: stages each piece for the arm | automatic | a CR servo (or motor) wheel before a push arm | `.feedWheel(Indexer.crServo("feeder_wheel"))` on the launcher | | Firing stats (debug lines) | automatic | a launcher (PRACTICE profile only) | (nothing to write) | | Alliance trim | automatic | a launcher | `Tunables.Launcher` `redTrimPercent`, `blueTrimPercent` | | Eject | action | a launcher: one piece out at a low speed (`ejectRpm`, `ejectSec`) | `robot.launcher.ejectAction()` | | Aim at the goal | auto step | a drive, and a camera with `goal(...)` (or `odometry(...)` + `Tunables.Aim` `goalX, goalY`); with a following turret, the turret | `.aimAtGoal("Aim", 3)` | | Aim at the goal with a sweep | auto step | the same. When the goal is not in view, the robot turns slowly up to the sweep each way to find it, then aims (it turns back to where it started if it never sees the goal). A turret that follows the goal does not sweep | `.aimAtGoal("Aim", 4, 45)` | | Remember heading, turn back | auto step | a drive (without odometry pods it uses the IMU: better than nothing) | `.rememberHeading("Remember")` ... `.turnBack("Back", 0.5)` | | Reverse drive | TeleOp toggle | a drive: the back is the front (robot-centric driving; field-centric ignores it) | `g1.x.toggle(robot.reverseDriveMode()).rumble()` | | Camera live view (webcam) | automatic | a webcam, PRACTICE profile (never at an event): Driver Station menu > Camera Stream, in INIT. A Limelight: plug it into a laptop (its own web page) | `liveView = false` in the webcam's section (`Tunables.Webcam1`) turns it off | | Camera fix (ALPHA, untested; not for BIOBUZZ) | automatic | off unless you turn it on. **BIOBUZZ teams: ignore it; your robot is not affected.** A Limelight + `odometry(...)` + `cameraFix(camera)`, and `Tunables.CameraFix.enabled = true` ([Odometry: camera fix](https://crossbotics.com/ftc-helper/docs/modules/odometry/#camera-fix-alpha)) | `cameraFix(camera);` in Robot.java | | Aim mode (the whole robot turns to the goal): it stays aimed while you drive | TeleOp toggle | the same, and no following turret. Mecanum: drive and strafe while it stays aimed; tank: forward and back only | `g1.rb.toggle(robot.aimMode())` | | Turret follows the goal | TeleOp toggle | a turret with `follows(camera)` or `followsOdometry()` (the robot drives at full speed while it aims) | `g2.rightStickButton.toggle(robot.turret.followMode())` | | Goal line on the Driver Station: seen, in range, LOCKED | automatic | what aiming needs | (nothing to write) | | Buzz when aimed | TeleOp | what aiming needs | `g1.rumbleWhenAimed();` | | Quick turn on fire: RB turns the robot to the goal, then fires | TeleOp (Tunables) | whole-robot aim's needs | `Tunables.Aim.aimOnFire = true` | | Shoot while moving | TeleOp toggle | aiming, and `odometry(...)` (the speed). Tune it first | `g2.a.toggle(robot.aim().movingShotMode())` | We keep this table by hand (it reads better than a generated one). A test (`FeaturesTest`) fails when a feature in the code has no row here. **The buttons stay yours.** The library never takes a button by itself: two features could want the same one. The list gives the line, and you pick the button in `Controls.java`. The buttons in the lines are only examples: pick free ones (INIT lists them, `G1 free: ...`). With one driver (`oneDriver = true`), RB on gamepad 1 is the launcher's fire button, so put aim mode somewhere else. ```java for (Feature f : robot.features()) telemetry.addLine(f.toString()); // ready action: Fire 2 robot.launcher.fireAction(2) ... ``` | `Feature` | What it is | | --- | --- | | `kind` | `AUTO_STEP`, `ACTION`, `TOGGLE` or `AUTOMATIC` (`kind.words()`: "auto step" ...) | | `name`, `code`, `needs`, `note` | what it is called, the line to use it ("" for automatic), what it needs, a short note | | `ready()`, `missing` | whether it has what it needs; what to add ("" when ready) | ## Parts not in the catalog For a motor or servo that is not in the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) (another seller, a custom gearbox), describe it in Robot.java with the seller's numbers. The call gives back its id, and the id works wherever a catalog id goes (`Launcher.flywheel`, `Arm.motor`, `Turret.motor`, `Hood.motor`, `Drive...motor(...)`, `.part(...)`): ```java launcher = add(Launcher.flywheel("launcher", Motors.custom("my-flywheel-motor", 28, 5800))); // counts per turn, free RPM claw = add(Claw.servo("claw").part(Parts.customServo("my-servo", 270, 0.16))); // turn in degrees, s per 60 deg (~5 V) lift = add(Lift.slide("lift").part(Motors.unknown("old-lift-motor"))); // numbers not known yet ``` | Method | What it does | | --- | --- | | `Motors.custom(id, countsPerRev, freeRpm)` | a motor of your own: encoder counts per output turn (as the SDK reports them; goBILDA's "Encoder Resolution" at the output shaft, REV's "Encoder Counts per Revolution") and free speed at 12 V (goBILDA's "No-Load Speed", REV's "Free Speed"). Either may be `Double.NaN` ("I don't know this one"). It refuses a catalog id | | `Motors.unknown(id)` | a motor whose two numbers are not known | | `Motors.find(id)`, `Motors.get(id)` | a catalog or custom motor (`find`: null if none; `get`: stops with the list) | | `Parts.customServo(id, rangeDeg, secPer60Deg)` | a servo of your own: its whole turn, and seconds per 60 degrees at about 5 V (if the seller lists 4.8 V and 6 V, use 4.8 V). **Reference level** (most teams never need it): the library takes the turn over 500-2500 us. `customServo(id, rangeDeg, secPer60Deg, pulseMinUs, pulseMaxUs)` gives the seller's own pulse range | | `Parts.unknownServo(id)` | a servo whose numbers are not known | | `Parts.findServo(id)` | a catalog or custom servo, or null | - **Its numbers work like a catalog part's:** starting values (`DEFAULT`, or no line), INIT says `defaults from my-flywheel-motor (custom)`, and `:sim:fromRobot` writes them into the robot file (`motor.launcher = flywheel, ticksPerRev=28, rpm=5800`; `servo.claw = 0.30, rangeDeg=243, secPer60=0.16`). - **When the numbers are not known,** the starting values are the general ones. INIT says so, and how to do better: `Lift: the counts per turn of old-lift-motor are not known, so general defaults (kP, kD, slowZone, tolerance made for a goBILDA 312 RPM motor). Give them with Motors.custom(...), or tune them in the tuning menu`. The same words show for a part with no `.part(...)` at all (`no part in Robot.java`). - **Counts per turn are needed** for a launcher, an arm, a motor turret and the drive (they turn counts into RPM or degrees). With none, Robot.java stops and says so. - A launcher whose top speed is not known uses general defaults made for a 6000 RPM motor. - Safety numbers (`min`, `max`, stops) stay yours, whatever the part. ## Parts not on the robot yet Teams build a robot in steps: the drive first, then the intake, the deploy servo when it arrives. Write the whole robot in Robot.java now, and mark the parts that are not built yet with `optional()`: ```java intakeDeploy = add(Positioner.servo("intake_deploy").part("gobilda-2000-torque").optional()); // Robot.java ``` - **Without `optional()`,** a device missing from the robot configuration stops INIT: `No Servo named "intake_deploy" in the active robot configuration. ... Not on the robot yet? Add .optional() to IntakeDeploy's line in Robot.java ...`. - **With it,** INIT goes on and says once `"intake_deploy" not in the configuration: IntakeDeploy is off (optional part)`. The part is **off** until its device is in the configuration. Then it works, with no code to change. - **Leaving the line out is worse:** then every action, button and autonomous that uses the part must change too, and change back later. Team 8938 kept a `HAS_DEPLOY_SERVO` switch for this. `optional()` does it for every part. **A part inside a part** can be optional too. For example, a launcher's feeder that is not built (or was taken off): ```java launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.crServo("windmill").part("gobilda-2000-torque").optional())); // Robot.java ``` Without `"windmill"` in the configuration, the launcher still spins, and `fire()` feeds nothing. The pieces must reach the wheel another way, for example pushed in by the intake. The launcher still counts each `fire()` as a shot, and a piece count (`Pieces`) does not go down. So with `stopsWhen(pieces::isFull)` on an intake that also feeds the wheel, the intake could stop when full. Leave `stopsWhen` out on such a robot. The other way round does not work: a feeder cannot be on while its launcher is off. What "off" means, everywhere: | Where | A part that is off | | --- | --- | | Commands | ignored (`goTo`, `in`, `spinUp`...): no error, nothing moves | | Questions | never hold anything up: "done" questions are true (`isDone`, `isAtTarget`, `isAt` the position it was last sent to, `isHomed`, a turret's `isAimed`); "busy" ones are false (`isRunning`, `isSpinning`, `isReady`, `isShooting`, `isBusy`, `isJammed`); sensors see nothing. `isPresent()` is false | | Telemetry | its line is `- (not on the robot)` (a servo part that is on the robot but has had no command yet says `not sent yet`) | | INIT | PRACTICE: a note. **COMPETITION: a loud warning at the very top** (above every other warning), `!! COMPETITION: "intake_deploy" not in the configuration: IntakeDeploy is OFF (optional part). On the robot? Check its name in the configuration, then INIT again`. At an event, a part that is off is most likely a misspelled or lost name | | [Actions](https://crossbotics.com/ftc-helper/docs/reference/steps/#action) | the action skips the step's command to it and goes on. It also skips a wait right after a step that only used parts that are off (nothing to wait for). `status()` ends with `skipped IntakeDeploy (not on the robot)`, `skipped()` lists them; an autonomous's report says it on the step | | Buttons | a part's own buttons (with `useStandardButtons()` true), `toggle(part)` and any button given `.needs(part)` do nothing; the button map says `- off: IntakeDeploy not on the robot` (COMPETITION: `- !! OFF: ...`) | | [Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) rules | a rule with it is off (nothing to hit), and needs no Tunables section: INIT says `Interlock TurretLift: off (Lift is not on the robot)` | | [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/) | a following turret that is off does not aim: you may use whole-robot aim (`robot.aimMode()`) | | Tunables | its section may be missing or unfinished: no stop. Wrong numbers (max below min) give only a note: `Fix its Tunables before adding it: ...`. Its numbers are **hidden from the tuning menu** (it says `Not on the robot (hidden): IntakeDeploy`): changing them would do nothing. Saved values are kept, and they come back the day the part is there | | Simulator | `:sim:fromRobot` still writes it. Leave it out of the simulated configuration with `missing = intake_deploy` in the robot file, or `set device intake_deploy missing` in a scenario ([simulator guide](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#5-measure-numbers-and-missing-parts)) | | [Hardware Check](https://crossbotics.com/ftc-helper/docs/modules/testing/#hardwarecheckopmode), finders | the check lists it as `optional, so the part is off (fine)`; the Hood Finder and Shot Tuner say it is not in the configuration; the Piece Tuner leaves its sensors out | - **Several devices** (a lift with a switch, a two-servo intake, a launcher with its feeder and hood): only the **first** device, the one named in the `add` line, decides. When it is missing, the whole part is off, with everything inside it. When it is there, every other device must be there too, as always (half a part is a wiring mistake: INIT stops and names the device). A feeder or hood can be `optional()` on its own. - **Not for the drive** (a robot always drives) or the odometry. Leave the `odometry(...)` line out until it is on the robot: `driveTo` needs it. - **Your own code:** `if (robot.intakeDeploy.isPresent()) ...` for anything the library cannot see. - **A part that is off at INIT stays off for the whole program.** Plug it in and add it to the configuration, then INIT again. - **Careful at events:** with `optional()`, a misspelled or lost configuration name does not stop INIT; the part is only off. So in the COMPETITION profile it is a loud `!!` warning (PRACTICE: a note). Read the INIT screen before each match, or take `.optional()` off once the part is built (then a missing device stops INIT). | Method | What it does | | --- | --- | | `optional()` | on any part's `add` line: it may not be on the robot yet | | `isOptional()` | whether the part is marked `optional()` | | `isPresent()` | false only for an optional part whose device was not in the configuration at INIT | | `Button.needs(part...)`, `Stick.needs(part...)` | in Controls.java, after the job: the button is off while one of these parts is | | `Action.skipped()` | the parts this run skipped (empty when all were there) | | `Interlock.isOff()` | whether the rule is off because one of its parts is | ## Shapes and parts `Robot.java` can also say what each part IS (its catalog id) and how it LOOKS (a `Shape`). Then `./gradlew :sim:fromRobot` writes the simulator robot file with no TODO shape guesses. The 3D view draws the robot, the simulator checks the size rules on it, and each shape moves with its part. So the simulator shows whether the controls do what they should (the intake drops, the rollers spin, a piece is fired). Worked example: [`flywheelbot/Robot.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/flywheelbot/Robot.java). A lift with a wrist and a claw riding on it: [`v2bot/Robot.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/v2bot/Robot.java). Typing the numbers is hard. Shape the robot with the mouse in the simulator, and copy the Java it prints ([Edit robot: shape your robot](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/#3-shape-the-parts-with-edit-robot)). **Name the part, give only what is not known.** A part in the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) brings its numbers: a motor its speed and encoder counts, a servo its speed and range, a wheel or roller its diameter (and width, when the seller gives it). You always give the places yourself. **A servo's range** is how far positions 0 to 1 turn it. On the hub's normal 600-2400 us, a goBILDA 2000 servo turns 270 degrees (its seller's 300 needs `.fullRange()`: [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/)). In code: `Parts.servoPart(id)` gives `rangeDeg` (the seller's), `pulseMinUs`/`pulseMaxUs`, `sdkRangeDeg()` (270), `degreesOver(lowUs, highUs)`, `fullMoveSec(fullRange)` (the time for 0 to 1) and `moveSec(from, to, fullRange)` (the time between two positions, from the seller's speed with no load). ```java drive(Drive.tank("left_drive", "right_drive").motor("gobilda-5203-312").wheel("gobilda-hogback-96") .wheelsAtMm(380, 290).reversed("right_drive")); chassisMm(400, 400, 100); // the chassis box, mm heightMm(300); // the whole robot // One shape: inside looks(...), on the part's line. intakeDeploy = add(Positioner.servo("intake_deploy").part("gobilda-2000-torque") .looks(Shape.arm().name("kicker").atMm(150, 90, 100).sizeMm(60, 20, 15) .angle("stowed", 90).angle("deployed", 20))); // Two shapes: name each one first, then give the names to looks(...). Shape intakeArm = Shape.arm().name("intake_arm").atMm(150, 0, 100).sizeMm(110, 200, 20) .range(-15, 90).startAt(90).dropsWhen(intakeDeploy, "deployed", -15); Shape intakeRoller = Shape.roller("gobilda-gecko-48-rex").on("intake_arm").atMm(110, 0, 0).lengthMm(300); intake = add(Intake.motor("intake").part("gobilda-5203-1150").holds(3).looks(intakeArm, intakeRoller)); launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000").feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .looks(Shape.flywheel("gobilda-hogback-96").atMm(-40, 0, 170)).shotAngle(75)); fixed(Shape.box("tower").atMm(-90, 0, 40).sizeMm(50, 180, 260)); ``` **One shape or several on a part:** - **One shape:** write it inside `looks(...)` on the part's line, as for the kicker and the flywheel above. Its settings can go on the next line (8 spaces further in). - **Two or more shapes** (an intake arm and its roller), or one long shape: give each shape a name first, on its own lines, with its comment above it: `Shape intakeArm = Shape.arm()...;`. Then the part's line ends with `.looks(intakeArm, intakeRoller)`. **Why:** each shape reads as one sentence, the part's line stays short, and you never have to count closing brackets. - Write the named shapes in `define()`, above the line that adds the part. A shape that rides on another part (`on(lift)`) goes below that part's line. - The names are only for your code (camelCase, like any Java variable). The shape's name in the simulator is `name("intake_arm")`, or the part's name when you do not give one. - Each `Shape` belongs to one part. Make a new one for each part, even when two look the same. - The simulator's [Edit robot](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/#3-shape-the-parts-with-edit-robot) mode prints shapes the same way: one shape inline, several as named shapes. | On a part | What it does | | --- | --- | | `part(id)` | the main motor's or servo's catalog id (a typo stops with the list of ids). A launcher's motor is in `Launcher.flywheel(name, id)`, the drive's in [`Drive.motor(id)`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/). On a CR servo the id is only a note (the simulator turns every CR servo at one speed) | | `looks(Shape...)` | how it looks. Every part that moves takes shapes: Intake, Positioner, Launcher, Indexer, Lift, Arm, Wrist, Claw, Turret and Hood. A part with no `looks(...)` gets a guessed shape marked TODO (from the chassis, the other parts and the catalog: [simulator guide](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#2-the-simulator-makes-it-from-robotjava)) | | `Shape` | What it is | Moved by | | --- | --- | --- | | `roller(ids...)` | a cylinder. Several ids (90 mm and 60 mm rollers taking turns) draw one as big as the biggest. In the simulator every roller of an Intake takes pieces in, and any roller drags the pieces it touches | spins with its part's motor or CR servo | | `flywheel(id)`, `flywheel()` | a launcher wheel (no id: give `diameterMm` and `lengthMm`) | spins with the launcher's motor | | `arm()` | swings about a hinge: `atMm` is the hinge, `sizeMm(length, width, thickness)` reaches forward at 0 degrees | a Positioner's, Wrist's or Claw's servo (`angle(position, deg)` twice); an Arm's motor (its Tunables degrees, from `min`); a Hood's servo or motor (its angles: Tunables `angleA`/`angleB` or its calibration table); or nothing (`passive`) | | `turret()` | turns about the up line: `atMm` is the middle of its bottom, `sizeMm` its box. Parts ride it with `on(turret)` | a Turret's motor, servo or CR servo (its Tunables angles) | | `slide()` | moves in a straight line along its axis (default up): `sizeMm` is one stage | a Lift's motor (`travelMm`: how far the stage moves from its `min` to its `max`), or nothing (`passive`, `travelMm`) | | `claw()` | two fingers that open and close; it can hold a game piece in the simulator | a Claw's servo | | `box(name)` | does not move: `atMm` is the middle of its bottom | nothing | | Setting | What it sets | | --- | --- | | `atMm(forward, left, up)` / `atIn` | from the middle of the chassis on the tiles, or from the hinge (or middle) of the shape it rides on | | `sizeMm(forward, left, up)` / `sizeIn` | its box (not needed for a catalog roller or flywheel) | | `lengthMm(mm)`, `diameterMm(mm)` | a roller's length along its axle (needed when the catalog has no width); a part not in the catalog | | `axis(dir)` | `up`, `down`, `forward`, `back`, `left`, `right`: a roller's axle (`up` = lying flat), an arm's hinge | | `on(part)`, `on("name")` | rides on another part's first shape, or on a shape by its name | | `name(n)` | its name in the robot file (default: the part's name, then `name_2`...) | | `angle(position, deg)` | an arm on a servo: its angle at a named position. Give two (0 = level forward, +90 up) | | `passive()`, `range(min, max)`, `startAt(deg)`, `travelMm(mm)` | moved by gravity or springs, not the code: the simulator draws it at its start, and the size rules try its whole range (its hard stops) | | `dropsWhen(servoPart, position, toDeg)` | a passive arm that a servo pushes over: once the servo is three quarters of the way to the position, it falls to `toDeg` and stays (a folded intake) | | `note(text)` | where a number came from ("est.", "measured 2026-10-20"), written after the line | | `color(c)` | its color in the 3D view, e.g. `"#2fa84f"` | | `tiltDeg(deg)` | mounted at an angle on its parent, about the left-right line (front up +): a spinner kept level on an arm that is down at -40 degrees has 40 | | `soft()` | a soft roller (surgical tubing, flaps): it bends against the field, so in the simulator only game pieces touch it. It still counts for the size rules | | `reversed()` | a roller that turns the other way from its motor (geared) | **Mistakes stop with the part's name:** - a typo in an id (with the known ids); - a roller with no length; - an arm with fewer than two angles, or an unknown position name (the names in `angle(...)` must be positions in that part's Tunables section); - shapes on a part that cannot take them; - a setting that does not fit the shape (`angle` on a passive arm, `range` on a servo arm, `travelMm` on anything but a slide, `lengthMm` on a box or arm); - riding `on` a part that has no shape; - an intake whose looks have no roller; - one `Shape` given to two parts, or two parts with one name in the robot file; - a `shotAngle` outside 0 to 180. A part without `looks(...)` gets a guessed shape marked `TODO measure`. It starts from the chassis (`chassisMm`), the height (`heightMm`), the other parts (a claw on the end of the lift, arm or wrist) and the catalog. The guess keeps the robot inside the size rules ([simulator guide](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#2-the-simulator-makes-it-from-robotjava)). ## Motors `Motors.get("gobilda-5203-312")` gives `countsPerRev` and `freeRpm`. `Motors.all()` lists them. The ids are the simulator's [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) (a test keeps the two the same). For a motor of your own, see [Parts not in the catalog](#parts-not-in-the-catalog). ## Module `Module` is what every mechanism shares. | Method | What it does | | --- | --- | | `name()` | its Tunables section | | `deviceName()` | its first device's name in the configuration | | `tunables(section)` | reads another Tunables section | | `optional()`, `isOptional()`, `isPresent()` | [Parts not on the robot yet](#parts-not-on-the-robot-yet) | | `stop()` | switches it off now (a launcher fully off, until `spinUp()`/`fire()`). It counts as the driver's command: an action using that part stops. To let a launcher coast while it stays ready, use `idle()` | | `Devices` | What it does | | --- | --- | | `Devices.has(name)` | whether the configuration has a device with that name | | `Devices.of(hardwareMap)` | where modules find their hardware on the robot. Tests give pretend devices | | `Devices.batteryVolts()` | the battery now (NaN in tests). It waits for the hubs, so do not use it in the loop | | `Devices.batteryReader()` | the same, for code in the loop (it asks the hubs on the library's helper thread) | A new kind of module is a change to the library (its parts are package-private, see AGENTS.md). In team code, use the plain parts ([mechanism](https://crossbotics.com/ftc-helper/docs/modules/mechanism/)) in your own class, and call it from Controls.java and your autos. ### Pause and stop **Pause** (gamepad 1 BACK in a Controls.java TeleOp, or `robot.pauseAll()` / `resume()` / `togglePause()`, `isPaused()`): - every part stops at once with its motors on brake, and the wheels hold still; - actions wait (their time limits too); - the Driver Station says PAUSED. When the robot goes on, each part does what it did before: an intake runs again, a lift goes on to its height, a launcher spins up again. STOP at the end of a program (TeleOp or autonomous) brakes everything the same way. ## Making the files **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder**. ```bash ./gradlew :sim:newRobot -Pconfig=path/to/config.xml -PteamCode=../TeamCode ``` It writes `Robot.java`, `Tunables.java`, `Controls.java`, `Actions.java` and `autos/LeaveStart.java` from the robot configuration (the XML file the Driver Station keeps on the Control Hub). It never overwrites a file. - Each device gets its module from its name and type: "lift" is a Lift, a servo called "claw" a Claw, one called "light" or "led" and a REV Blinkin are Lights. - A servo called "hood" goes on the launcher, `.hood(Hood.servo("hood"))`, with a `TODO` for the Hood Finder. - A goBILDA Pinpoint or SparkFun OTOS becomes the `odometry(...)` line (offsets 0 and a `TODO` for the Odometry Tuner) with a `Tunables.Odometry` section. - It marks every guess it is not sure of with a `TODO` in Robot.java. **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder**. ```bash ./gradlew :sim:fromRobot -PteamCode=../TeamCode ``` It writes (or refreshes) `simulator/robot.properties` from Robot.java and Tunables.java: every device name, the drive, each module's lines (from its part and shapes when Robot.java gives them, [Shapes](#shapes-and-parts)). Lines it writes end with `# from Robot.java`. It keeps your own lines (measured, from photos or CAD). It stops if the file describes a device differently from the code. See the [simulator guide](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#2-the-simulator-makes-it-from-robotjava). --- **Look it up:** [`RobotDefinition` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/RobotDefinition.html) (every method). **The other pages:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Scenario files URL: https://crossbotics.com/ftc-helper/docs/reference/scenario-files/ A scenario file (`.sim`) is a test: a short script that drives the simulator like a person and checks what happens. The page's recorder writes one for you ([Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/)). A team's tests are in `simulator/scenarios/` in the robot project; the library's own are in `sim/scenarios/`. ## Run them **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:scenario -Pfile=../simulator/scenarios/main-teleop.sim ./gradlew :sim:scenario # in a robot project: every test in simulator/scenarios ``` **Each file starts like a robot right after you turn it on**: a fresh simulator, the field at the match start, and nothing kept from the file before. It keeps none of these: the alliance and the autonomous report, a turret's angle, a launcher's trim, numbers tuned in the tuning menu or saved on the pretend Control Hub. The Tunables numbers are the ones in your code. When you run several files, the command ends with a list of which passed. ## Every command and check ```text # lines starting with # are notes robot ../robots/starter-bot-rev.properties # optional: run this scenario with this robot file (path from # the scenario's folder) instead of the usual one init "Main TeleOp" # INIT an OpMode (waits for its first screen) start # press ▶ press g1.a # press and let go (held until the OpMode surely saw it) hold g1.left_stick_y -1 # set a stick or button and keep it release g1.left_stick_y # let go (release g1.all / release all) wait 0.5 # seconds loops 3 # wait for 3 OpMode loops push 24 0 2 # roll the robot by hand: forward in/s, right in/s, seconds set battery 12.0 set touch lift_bottom on # hold a switch pressed (off = let go) set pose -56 -61.55 0 # put the robot somewhere (x y heading) set autotimer off # no 30 s autonomous stop set teletimer off # no 2:00 TeleOp stop set gamepad 1 ps # gamepad 1 is a PS controller: the screens say × ○ □ △ (letters = A B X Y; # the recorder does not write it: add it by hand) set preload off # the robot holds no preload (now and after each reset); on: it does set field start # every game piece back where the match starts it (the robot stays) set device intake_deploy missing # take a device out of the configuration from the next INIT # (a part not on the robot yet); present = put it back set encoder lift none # a wiring fault for the Encoder Check: lift's port has no encoder # cable; set encoder lift flywheel = it has the flywheel's cable # (swapped); set encoder lift own = right again. Works at once set tunable IntakeDeploy.deployed 0.6 # a Tunables number for this file only (before init; see below) expect screen has "Ready" # or: screen not "..." expect value "Lift" > 500 # the number on the screen line that starts with Lift expect time < 25 # seconds since ▶ (e.g. how long an autonomous took) expect touch lift_bottom pressed # or: open expect error none # or: error has "..." expect phase RUNNING # IDLE | INIT | RUNNING | STOPPED expect step 3 done # the autonomous report's 3rd step (after "Start"): done, STALLED ... expect motor lift power > 0.1 # power | ticks | velocity | amps; > < >= <= = (= VALUE TOLERANCE) expect servo claw target = 0.53 0.01 # target | actual expect light status = GREEN # what a light (light.NAME = gobilda or blinkin) shows: GREEN, RED, off ... expect shape intake_arm < 0 # a shape's angle (arm, turret), inches (slide) or gap (claw) expect robot y > -30 # x | y | heading | imu | shots expect bumped none # or: bumped "Red HIVE" expect camera "Webcam 1" sees 31 # a tag id in the picture; or: sees none | sees "RED SCORING" (webcam only: # a Limelight reports single tags; LimelightTags makes the groups) expect size most ok # size start|match|most ok|fail (see "Robot shapes") expect stored >= 1 # game pieces in the robot; also: launched, scored, cell, tips, left (see "Game pieces") expect points "red" >= 20 # the alliance's match points now ("blue" too) expect clean >= 1 # shots that went cleanly into an up CELL (see "Game pieces") set piece POLLEN 30 -20 # put a game piece on the field (x y [z]) expect within 2 motor lift ticks > 500 # wait up to 2 s for it to become true expect within 30 phase STOPPED # e.g. wait for an autonomous to finish stop print screen # also: print motors | servos | cameras | size | pieces | robot | cad (not counted as checks) ``` The simulator ignores a note after `#` (outside quotes). A misspelled check fails with a message, and it never passes. Button presses wait for the OpMode's loops. The simulator counts the loops by the OpMode's screen updates, or by `loop()` calls in an iterative OpMode. It cannot count the loops of an OpMode that never sends telemetry. Then each step waits 3 s, and the report says so. Gamepad names: `g1.`/`g2.` plus `a b x y lb rb lt rt back start guide ls rs`, `dpad_up` (or `up`), `left_stick_x` (or `lx`), `right_trigger` (or `rt`) and the other SDK names. The report shows each line as ok or FAIL, with the value it saw. The command fails when any check failed. ## Button names **Button names in a scenario are not the Java names.** A scenario uses the FTC SDK's names (or the short names). `Controls.java` uses the library's names. These are the ones that differ: | In `Controls.java` (Java) | In a scenario | | --- | --- | | `g2.dpadUp`, `dpadDown`, `dpadLeft`, `dpadRight` | `g2.dpad_up` (or `g2.up`), `dpad_down` (`down`), `dpad_left` (`left`), `dpad_right` (`right`) | | `leftStickButton`, `rightStickButton` | `left_stick_button` (or `ls`), `right_stick_button` (or `rs`) | | `leftStickX`, `leftStickY`, `rightStickX`, `rightStickY` | `left_stick_x` (`lx`), `left_stick_y` (`ly`), `right_stick_x` (`rx`), `right_stick_y` (`ry`) | | `lb`, `rb` | `lb`, `rb` (or `left_bumper`, `right_bumper`) | | `lt`, `rt` | `lt`, `rt` (or `left_trigger`, `right_trigger`); a value from 0 to 1 | | `a b x y back start` | the same | So `g2.dpadLeft.press(...)` in Java is `press g2.dpad_left` in a scenario. ## Another number for one test: set tunable **Another number for one test: `set tunable`.** A Tunables number written as `MEASURE` stops INIT until you measure it on the robot. In the simulator, the robot file's stand-in takes its place ([MEASURE in the simulator](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#5-measure-numbers-and-missing-parts)), so most tests need nothing. A test that wants another value sets it: `set tunable IntakeDeploy.deployed 0.6` sets `Tunables.IntakeDeploy.deployed` to 0.6 for this file only. It wins over the stand-in. `set tunable IntakeDeploy.deployed MEASURE` checks that INIT stops. - Put it before `init` (or after `stop`), because the parts read their numbers at INIT. While an OpMode is in INIT or running, the line fails. - It works for numbers (`double`, `int`, `float`, `long`) and `true`/`false`. `MEASURE` and `DEFAULT` work too. - It sets the field in the Tunables class that your Robot.java uses. The simulator finds that class the way INIT finds it: `Tunables` next to Robot.java, or the class you give with `tunables(...)`. It also sets the field in every other class named Tunables that has it. - At the end of the file, the number goes back to the value in your code. The next file starts fresh. - A misspelled name fails and names what exists: `Tunables.IntakeDeploy has no field "deployd" (did you mean deployed?)`. When you measure the real number, write it in Tunables.java. Delete the `set tunable` line when it only stood in for the `MEASURE`. ## Check a show(...) line **Check a `show(...)` line.** A `show("Intake on", ...)` line is on the screen as `Label : value` (the label, a space, a colon, a space, the value). Check it with its words: ```text expect screen has "Intake on : true" ``` `expect value "Intake on" = true` does not work. `expect value` compares numbers only, and the scenario stops with `"true" is not a number. To check words on the screen (true/false, a name), use: expect screen has "Label : true"`. ## The recorder Learn it first: [Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/). The page writes a test for you. Open **Tests**, over the 3D view: - **Record a test**: the field starts fresh. The running OpMode stops, the robot goes to its start spot, every piece goes back, and the Tunables numbers are the ones the code wrote. A test runs with the code, not with numbers tuned on the page. A red bar shows the time. Choose an OpMode, INIT, choose the alliance, press ▶, and do the job. Then press **Stop recording**. **Record from now** starts with the robot where it is (a `set pose` line). It is faster to start, but less reliable. - What it writes: - `init`, `start`, `stop`. - every gamepad change from any source (keyboard, controller, on-screen, phone) as `press` (a tap shorter than 0.35 s), `hold` and `release`. A stick changes in steps of 0.25, and a sweep counts where it ended. When three or more let go at once, it writes `release g1.all`. - the time between them as `wait`. Before ▶, a wait is at most 1 s, because the wait changes nothing. - the robot or a piece moved by hand (`set pose`, `set piece`, `push`, `set field start`). - the page's settings that differ from a fresh simulator (`set battery`, `set preload off`, `set scatter`, `set autotimer off`). - An autonomous that ends by itself in the middle of the recording becomes `expect within T phase STOPPED`. It writes only commands of the [scenario language](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/). The auto builder's Run is not one of them, so record your own autonomous instead. - **Stop recording** opens the checks. The simulator suggests them from what it sees now. - **Goal checks** (ticked): the autonomous finishes (`phase STOPPED`, within 1.5 times the time it took), each step of its report that is `done`, pieces shot, scored or picked up and the points (`>=`), no error, no bumping into anything, a TeleOp still running. For a driving test with no pieces: where the robot ends. - **Details** (not ticked): where the robot ends (x and y give or take 3 in, the heading 5 degrees), the time since ▶ (`<` 1.5 times), and Driver Station lines. A Driver Station line check keeps only the line's steady part: the recorder cuts the line off from the first number on, because numbers change from run to run. You can change every check's numbers, operator and `within` time before you save. The checks that wait come first, then the others. - **Save** writes `simulator/scenarios/NAME.sim` in the robot project (letters, digits, `-` and `_`). It asks before it replaces a file. The file gets a header: made by the recorder, the date, the OpMode, and how to run it. When the page runs another robot file than `simulator/robot.properties`, the test gets a `robot` line. When you started with `-PteamCode=none` (no robot project), use **Download** instead. - **Run it now** runs the test on the page while you watch, from a fresh start like `:sim:scenario`. The page's gamepads and buttons wait, and **Stop the test** ends it. The result: PASSED, or FAILED with each failed line and the value it saw. - **Run all tests** (in the Tests menu) runs every test in `simulator/scenarios`, one after another. Each runs exactly like `:sim:scenario`: a new simulator of its own, with the test's `robot` line. The page's robot waits meanwhile. The bar says `Running all tests: 2 of 5`, and **Stop the test** ends the run. The result: passed or failed for each test, with the failed lines. Click a test's name to open it, to run it alone or update it. The run uses the code that the simulator started with. So after a code change, stop the simulator and start it again first. - **Open a test** lists the tests in `simulator/scenarios` (or opens a file from the computer) and runs one. It can fail after a change that you made **on purpose**. Then **The change was on purpose: update the test** runs it once more and measures. A `within` may then wait up to 3 times as long, to see how long it takes now. The page then shows each failed check with its new number: - `=` takes the value seen. - `>=`/`>` and `<=`/`<` take the value seen as the new limit. - `time <` and a late `within` take 1.5 times what it took. The steps, the tolerances and the checks that passed stay. A word check (`phase`, `step`, `screen`, `error`) cannot take a number, so the page lists it for you to change by hand. Press **Save the update**, then run the test again. The page reads and writes only `.sim` files in `simulator/scenarios`, by a plain name (no folders). It does this only for a page on the computer that runs the simulator. A phone joined with `-Plan` cannot. --- # Steps for autos URL: https://crossbotics.com/ftc-helper/docs/reference/steps/ ## Auto ```java @Autonomous(name = "Score and Park", preselectTeleOp = "TeleOp") public class ScoreAndPark extends Auto { @Override protected void steps(Steps s, Robot robot) { s.start("Back wall, 2nd tile from the left, facing the field", 0) .menuYesNo("Score", true) .run("Hold the piece", robot.claw::close) .forward("Leave the wall", 4, 0.4) .onlyIf("Score") .run("Lift up", () -> robot.lift.goTo("high")) .forward("Drive to the goal", 24, 0.6) .waitUntil("Lift at the top", robot.lift::isAtTarget, 2.0) .run("Drop", robot.claw::open) .end() .parkWithSeconds(4) .right("Park", 20, 0.7); } } ``` What `Steps` can do: | Step | What it does | | --- | --- | | `start(where, headingDeg)` | where to place the robot (shown in INIT) and which way it faces | | `start(where, xIn, yIn, headingDeg)` | the same, plus the spot in inches. The simulator puts the robot there in INIT ([The start spot](#the-start-spot)) | | `menuYesNo(label, yes)`, `menuChoice(label, options...)` | a choice for the drivers in INIT | | `onlyIf(label)` / `onlyIf(label, option)` ... `end()` | the steps in between run only for that choice. A `start(...)` or `parkWithSeconds(...)` in between is used only for that choice, and the INIT note follows the menu ([choose the start in INIT](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#a-whole-example-one-auto-the-drivers-choose)) | | `isYes(label)`, `choice(label)` | reads a choice | | `forward(label, inches, power)`, `back(...)` | drive forward / backward | | `left(label, inches, power)`, `right(...)` | slide to the robot's left / right, still facing the same way (mecanum only) | | `move(label, inches, directionDeg, power)` | drive at an angle: counterclockwise, like a heading (0 forward, 90 left, 180 back, -90 right) | | `turnLeft(label, degrees, power)`, `turnRight(...)` | turn left / right by this many degrees | | `turn(label, degrees, power)`, `turnTo(label, headingDeg, power)` | turn by an angle / to a heading (counterclockwise: 90 = left, the same rule as a move) | | `moveWithTurn(label, inches, directionDeg, headingDeg, power)` | drive AND turn at the same time (mecanum only). The direction is fixed on the field, counterclockwise from the start heading (0 = the way the robot faced at the start, 90 = its left then). It ends facing `headingDeg` (0 = the start heading, counterclockwise +). A tank drive cannot: use `forward`, then `turnTo` | | `aimAtGoal(label, timeoutSec)` | turn to the goal with the camera (or the odometry backup), or wait for a following turret. The report says "not seen" when there was no goal ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)) | | `aimAtGoal(label, timeoutSec, sweepDeg)` | the same, with a sweep when the goal is not in view: up to `sweepDeg` each way, slowly, then aim ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). A turret that follows the goal does not sweep: the step waits for the turret | | `waitForGoal(label)` | WAIT until the camera sees the goal and the goal is still, then go on ([waitForGoal](#waitforgoal)) | | `waitForGoal(label, timeoutSec)` | the same, but at most `timeoutSec`: then it goes on anyway, and the report says "not seen in 10 s: went on" (or "seen, never still") | | `rememberHeading(label)`, `turnBack(label, maxPower)` | save the heading now; later turn back to it (without odometry pods it uses the IMU: better than nothing). The same as `AutoRoutine`'s `rememberHeading` / `returnToHeading` | | `readyToLaunch(label, timeoutSec)` | spin the launcher up and WAIT until it is ready to fire, then go on. The speed keeps following the distance in the next steps ([Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/)). To spin up while the next step drives instead: `.run("Spin up", robot.launcher::spinUp)` | | `driveTo(label, xIn, yIn, headingDeg, power[, toleranceIn][, PathAt...])` | drive to a field point and heading with the odometry, correcting all the way (mecanum; needs `Tunables.Odometry.checked` on a robot) ([driveTo](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/#drive-to-a-point-driveto)). [`PathAt`](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/) starts things on the way | | `routeTo(label, xIn, yIn, headingDeg, power[, toleranceIn])` | `driveTo`, but around the boxes of `fieldMap(...)`, from wherever the robot is when the step starts ([routes](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes)) | | `follow(label, path[, timeoutSec][, PathAt...])` | follow a path with the robot's [path follower](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/) ([pedro](https://crossbotics.com/ftc-helper/docs/modules/pedro/)). [`PathAt`](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/) starts things along it | | `run(label, command)` | start something and go on at once | | `waitSeconds(label, seconds)`, `waitUntil(label, condition, timeoutSec)` | wait (the robot keeps running). A step always has a label (it shows in INIT and the report). An [Action](#action)'s `waitSeconds(seconds)` has none | | `action(action[, timeout])` | run an [Action](#action) and wait until it is done | | `alongside(action)` | run an action during the next steps | | `step(label, AutoStep)` | your own step | | `parkWithSeconds(s)` | the steps after it get the last s seconds ([Keep time to park](#keep-time-to-park)) | ### waitForGoal `waitForGoal(label)` waits until the camera sees the goal (from `goal(...)` on a camera; the camera only, not the odometry backup) and the goal is still. Then it goes on. - **Still** means in view and moving less than 2 degrees and 2 inches for 1 s (`Tunables.Aim` `goalSteadySec`, `goalSteadyDeg`, `goalSteadyIn`). A tipped HIVE can swing. - **Use it** for a start where the goal is not in view yet, e.g. behind the HIVE: wait for a tip, then fire. - **No time limit.** If the camera never sees the goal, it waits until `parkWithSeconds` takes over (the library skips the steps between) or autonomous ends. - It does not turn the robot. - An upside-down CELL (a down CELL) is not the goal: it keeps waiting. ### The start spot You write the spot in `start(where, xIn, yIn, headingDeg)` for BLUE, as seen from your wall: - x = inches right of the center line; y = inches from the center toward the far wall (negative = your half). - RED works like the routes: mirrored, or, on a turned field like BIOBUZZ with `mirrorForRed()` false, the same numbers seen from the red wall. - When both alliances' drivers stand at one wall (not BIOBUZZ, not DECODE), override `alliancesOnOneWall()` to return true. - With odometry, the first step ("Start") sets the pose to the spot (mirrored for RED the same way). At the end, the whole pose goes to TeleOp. Without a spot, the pose starts at (0, 0). ### When the steps run - The library reads the steps in INIT (for the menu, the start position and the park time; nothing runs). - It reads them again in INIT whenever a menu choice changes. So a `start(...)` inside an `onlyIf` follows the menu ([one file, the drivers choose in INIT](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#a-whole-example-one-auto-the-drivers-choose)). - They run after ▶. - [`EasyAuto`](https://crossbotics.com/ftc-helper/docs/modules/auto/#easyauto) does everything else: the alliance and delay menu, mirroring for RED, the timer, stopping everything, the report. - When its steps are done, the auto ends at once (even with time left), so the Driver Station moves to its TeleOp. TeleOp's INIT shows the report and the alliance (or lets the drivers choose it: X = BLUE, B = RED). - Until `Tunables.Drive.calibrated` is true, it says "AUTONOMOUS IS OFF" and does nothing. In the simulator it runs anyway, with a warning. - `newRobot()` makes the robot from `extends Auto`. You never need it. It is `protected` so the simulator's [auto builder](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/) (its "Built Auto") can run a plan with whichever Robot class your project has. ## Keep time to park Parking points come at the very end of autonomous, so the steps that park must never run out of time. `parkWithSeconds(4)` in the list splits the steps in two: - **The steps before it** (main steps) run while more than 4 s of the 30 s are left. When the 4 s mark comes, the step that is running stops at once (a move stops, a wait stops waiting). The library skips the main steps not started yet. - **The steps after it** (park steps) always run, until autonomous ends. - The report at the end (Driver Station, and TeleOp's INIT) says which main steps were "cut short (time for park)" or "skipped (time for park)". - **Choose the seconds** from a timed run: how long the park steps take, plus about a second. - Without `parkWithSeconds`, every step is a main step, and nothing keeps time for the end. - It is [`EasyAuto`](https://crossbotics.com/ftc-helper/docs/guides/easy-autos/#time-for-parking)'s `thenPark()` and `parkReserveSec()` in one call. - The step that was stopped can leave the robot anywhere, so a straight `driveTo` home can go through a field element. With `routeTo`, the park goes around the boxes you list: [keep-out boxes and routes](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes). ## Action An action is a list of steps across several parts. It never blocks (never makes the loop wait). You write actions in `Actions.java`. ```java public static Action scoreHigh(Robot r) { return Action.named("Score high") .then(() -> r.lift.goTo("high")) .waitUntil("lift at the top", r.lift::isAtTarget, 2.0) .then(r.claw::open) .waitSeconds(0.3) .then(() -> r.lift.goTo("down")); } // Controls.java: g2.y.press(Actions.scoreHigh(robot)); an autonomous: s.action(Actions.scoreHigh(robot)); ``` | Method | What it does | | --- | --- | | `named(name)` | makes a new action | | `then(Runnable...)` | does these at once (several parts together), then goes on | | `waitSeconds(s)` | waits (the robot keeps running) | | `waitUntil(what, condition, timeoutSec)` | waits until true. If it times out, the action STOPS and says why | | `waitUntil(condition, timeoutSec)` | the same, with "the condition" as its words | | `name()`, `isRunning()`, `status()`, `result()` | its name; whether it runs; its status, like "Score high: step 2 of 5 (lift at the top)"; its result, like "done", "canceled", "stopped: Lift moved by hand" | | `skipped()` | the parts this run skipped because they are not on the robot ([Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | - **Never blocks:** an action does a little every loop. - **Parts are claimed:** an action owns the parts it commands while it runs. Another action that commands one of them stops it ("taken by ..."). The driver stops it too by moving the part by hand (a button, or a stick away from the middle): the driver always wins. - **Press again to cancel** (a button bound with `press(action)`). - **A stopped action** (canceled, taken over, timed out) stops what it started, safely. A lift or arm holds its height, a turret holds its angle, the launcher drops shots still waiting, and an intake stops. An action that finishes keeps its last commands. A failed action in an autonomous says why in the report. - **A part that is not on the robot yet** (`optional()`): the action skips its commands, and the waits right after a step that only used such parts. The action goes on with the other parts. - Ready-made actions from your parts: [What your robot can do](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#what-your-robot-can-do). ## Modes A `Mode` is a rule a module follows every loop while it is on: `Turret.followMode()`, `Launcher.speedMode()`, `robot.aimMode()` ([whole-robot aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). | Method | What it does | | --- | --- | | `on()`, `off()`, `toggle()` | switches it | | `isOn()` | whether it is on | A button switches it with `g2.rightStickButton.toggle(robot.turret.followMode())`. Modes are for "always" rules, actions for steps that end. --- **Look it up:** [`Auto`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Auto.html), [`Steps`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Steps.html), [`Action`](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Action.html) in the Javadoc. **The other pages:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Tunables.java URL: https://crossbotics.com/ftc-helper/docs/reference/tunables/ Every number has a default, except the ones marked **REQUIRED**. When Robot.java names the part's motor or servo, the library takes the default from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) ([First run](#first-run-what-you-get-before-tuning)). Copy only the lines you want to change. The part pages list every number the library reads from `Tunables.java`. A script (`tools/check_tunables.py`) reads the library's code and checks the pages against it. So the list is complete: if a part reads a new number, the check fails until the number is on its page. ## Each part's numbers | Section | Part page | | --- | --- | | `Drive` (fixed name) | [Drive](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/#in-tunablesjava) | | `Odometry` (fixed name) | [Odometry](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/#in-tunablesjava) | | `CameraFix` | [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/#camerafix) | | `Aim` (fixed name) | [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#in-tunablesjava) | | `Buttons` (fixed name) | [Controls.java](https://crossbotics.com/ftc-helper/docs/reference/controls/#buttons-in-tunablesjava) | | the intake's device name | [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/#in-tunablesjava) | | the lift's device name | [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#in-tunablesjava) | | the arm's device name | [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/#in-tunablesjava) | | the claw's device name | [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#in-tunablesjava) | | the wrist's device name | [Wrist](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/#in-tunablesjava) | | the positioner's device name | [Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/#in-tunablesjava) | | the turret's device name | [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/#in-tunablesjava) | | the name in `keepApart("TurretLift", ...)` | [Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/#in-tunablesjava) | | the launcher's motor name | [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava) | | the indexer's device name | [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/#in-tunablesjava) | | the hood's device name | [Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/#in-tunablesjava) | | the camera's device name | [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/#in-tunablesjava) | | each piece sensor's device name | [Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/#in-tunablesjava) | | the light's device name | [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/#in-tunablesjava) | ## Find a setting by what you want This table moved to [Fix it by what you see](https://crossbotics.com/ftc-helper/docs/tuning/17-fix-by-symptom/) in the Tuning section. ## When you add a part 1. Add the part to `Robot.java` (one line, with its part number: `.part("gobilda-5203-435")`). The name in quotes (`Lift.slide("lift")`) is the device's name in the robot configuration on the Driver Station, exactly. Its section in `Tunables.java` is that name in CamelCase: `"lift"` reads `Lift`. 2. Press INIT. The part works with the library's starting values. INIT shows one note per part with the values it used. 3. If INIT stops and asks for a number (a lift's `min` and `max`, a turret's stops), add the part's section to `Tunables.java` with that number. The message names the tool that finds it. 4. Optional: write a line for each setting in the part's table, set to `DEFAULT`, with a short comment. Write `MEASURE` for the numbers only your robot can give. Then the file shows every setting the part has, and you can change one when you need to. Leaving a line out does the same as `DEFAULT`. The [Cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/) shows each part's section this way. ## What Tunables.java is `Tunables.java` is the file with your robot's **numbers**: how far the lift goes, how fast the launcher spins, where the claw opens. `Robot.java` says WHICH parts the robot has. `Tunables.java` says their numbers. **Why a separate file:** you change numbers all season, and you can change them without touching the code that works. ```java public class Tunables { public static class Lift { // the part's section public static double min = 0, max = 2580; // REQUIRED for a lift (Motor Finder) public static double kP = 0.004; // optional: the default is used if you leave it out public static double down = 0, high = 2400; // a lift's other numbers are named heights } public static class Team { // your own section: no part reads it public static double rumbleAtSec = 20; // your Controls.java buzzes the gamepads then } } ``` - **A section is a part.** `public static class Lift { ... }` holds the numbers of the part whose device is called `lift` in the robot configuration. The section's name is the device's name in CamelCase: each word starts with a capital letter, with no spaces and no `_`. `lift` reads `Lift`, `intake_deploy` reads `IntakeDeploy`, `Webcam 1` reads `Webcam1`, a launcher on the motor `shooter` reads `Shooter`, `Indexer.servo("feeder")` reads `Feeder`. It is never the module's kind (`Launcher`, `Indexer`), unless that is the device's name. To use another name, write `.tunables("Name")` on the part in `Robot.java`. - **Some sections have fixed names:** `Drive`, `Odometry`, `Aim` and `Buttons`. An [interlock rule](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) uses the name you give it in `keepApart("TurretLift", ...)`. - **A field is one number.** Write it as `public static double name = value;` (`int` works too), `public static boolean name = true;` for an on/off setting, and `public static double[][] name = {{24, 2200}, {48, 2550}};` for a table. `public static` is needed: the library cannot read a field without it. - **Names count, with their capitals.** `maxPower` is a setting. `MaxPower` and `maxpower` are not. - **A part that is not on the robot** ([`optional()`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet), device not in the configuration) needs no section. Nothing about its numbers stops INIT, not even a Lift's `min`/`max`. - **Safety:** a tuned position stays inside `min`..`max`. The library reads limits once, and you cannot tune them. - **An autonomous's distances** are not here: they are in its steps ([why](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#the-numbers-are-in-the-step)). ### Your own sections A section no part reads, like `Team` with a number your `Controls.java` uses: - Your code reads it as usual: `Tunables.Team.rumbleAtSec`. - Every `public static` number in it that is not `final` is in the tuning menu too ("Team/rumbleAtSec"). The menu writes its value into the field. A TeleOp reads the field each time; an autonomous reads it when it builds its steps, at INIT. - Tune it in the TeleOp and save it (A): your code uses it at once, with no rebuild. **Then copy the good value into `Tunables.java`** (INIT lists it). A new Control Hub loses a value saved only on the old hub. - `final` numbers, true/false settings and tables are not in the menu. They stay as written. - INIT never checks the names in your own sections. ### FTC Dashboard and the tuning menu - `public static` fields: FTC Dashboard can show them too, **at home and in practice only**. Rule R704.D (2026-27) bans tools like FTC Dashboard at events, so take it out of the robot project before one ([tuning guide](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/#ftc-dashboard-practice-only)). The library's tuning menu is allowed. - The menu's names ("Lift/kP") are shared by the whole robot app: keep one Robot class per app. ## What INIT checks When you press INIT, the library reads `Tunables.java` and tells you what it found: | You wrote | INIT does | Why | | --- | --- | --- | | no line for an optional number | uses the default; the INIT screen does not mention it (the robot log has `Tunables.Lift: kD, kF not written: library defaults used (fine)`) | a missing number is not a problem: the default works. Add the line to change it | | no section at all for a part | uses every default; the robot log says so (not the screen) | the same | | no line for a number that has a starting value from the parts catalog (a launcher's gains and speed, a lift's `kP` with `.part(...)`, a servo's `travelSec` with `.part(...)`) | uses it; the robot log has ONE note per part with the values, where they came from and the tool that tunes them: `Launcher: defaults from the catalog (gobilda-5203-6000): kF 11.7, kP 1.17, kI 0.117, speed 3600 rpm. Run the Flywheel Finder, then the Shot Tuner` | a number worked out for YOUR motor works much better than a fixed one made for another motor. It is still a start: tune it, then write it ([First run](#first-run-what-you-get-before-tuning)) | | no positions for a Claw, Wrist, Positioner or servo Indexer | uses the library's guesses and says so: `Claw: no positions written: open 0.2, closed 0.75 are library guesses, not your servo's: find yours with the Servo Finder before the first TeleOp` | guessed positions can push a part into the frame | | no line for a REQUIRED number | **stops**: `Tunables.Lift has no max: write max (the top of the safe range, in counts: Motor Finder, B). A safety limit never comes from a library default.` | a wrong limit breaks the robot. A default could be wrong for your robot | | a name in Lift, Arm, Claw, Wrist or Positioner that looks like a setting (`Max`, `k_P`, `maxPowr`) | **stops**: `Tunables.Lift.Max looks like "max" (capitals and spelling count)` | in these parts every other name is a named position, so a typo would quietly become a position | | a name in Lift or Arm close to a gain that is not written (`kPP` with no `kP`) | runs, and INIT's note names it: the library uses it as a position, and the gain keeps its default | the same | | a name no part reads, in any part's section (`inPowr` in `Intake`, `goalx` in `Aim`, a leftover `spinPower`) | **stops**: `Tunables.Intake.inPowr is not a setting of Intake (did you mean inPower?): the robot would quietly ignore it. Fix the name (capitals count) or delete the line. Known: inPower, outPower` | a misspelled line is never read, so the part would quietly use its default (a safety number too). The "did you mean" appears when the name looks like a real one | | a section no part reads that is named like a part's kind (`Tunables.Launcher` for the launcher on `shooter`), or spelled almost like a part's section (`Tunables.Liftleft`) | **warns** (`!!`, every profile): `Tunables.Launcher is not read by any part: your launcher's section is Tunables.Shooter (its device name "shooter" in CamelCase). Move the numbers there` (or `did you mean Tunables.LiftLeft?`) | every number in it would be quietly ignored. INIT only warns here: a section no part reads may be your own (`Tunables.Team`), and a part's required numbers (a lift's `min`/`max`, a servo turret's `posA`...) already stop INIT when its real section is missing | **The name check** covers `Drive`, `Odometry`, `Aim`, `Buttons`, every part on the robot and every interlock rule. These names are yours to pick and always pass: - named positions (any number in Lift, Arm, Claw, Wrist, Positioner); - a piece sensor's kinds (`POLLEN`); - a launcher's `speedByDistance...` tables; - an interlock rule's `From`, `To`, `Above`, `Below`, `Margin`, `StopSec` for its own two parts. A field of the part that your robot does not use (a servo turret's `posA` on a motor turret) passes too. INIT never checks your own sections (`Team`), or the section of an `optional()` part that is not on the robot (it may be unfinished). The part tables list every name the check knows. ### A name that looks like a setting In Lift, Arm, Claw, Wrist and Positioner, every number that is not a known setting is a named position. So these field names stop INIT (the setting of Claw, Wrist and Positioner is `travelSec`): - **Always:** a known setting with other capitals or an `_` added: `Max`, `MAX` or `MIN` for `max`/`min`, `kp`, `KP` or `k_P` for `kP`. (All capitals is a common habit: it stops too.) - **Only when that setting itself is not written:** for names of 5 letters or more, up to two letters off (`maxPowr` or `maxPwr` for `maxPower`). So `slowZone2` next to a written `slowZone` is a position, but `slowZon` with no `slowZone` stops INIT. The message: `Tunables.Lift.Max looks like "max" (capitals and spelling count). Fix the name in Tunables.java; a position must not look like a setting.` Older versions quietly made it a position called `Max`, and `max` stayed the library default. ### REQUIRED numbers A safety limit never comes from a library default. These numbers are REQUIRED (none of them for a part that is `optional()` and not on the robot): - a Lift's or Arm's `min` and `max`; - a Hood's `posA` and `posB` (or its `calibration`); - a servo Turret's `posA`, `angleA`, `posB`, `angleB`; - a Turret's `homeAngle` with a home switch; - an interlock rule's zone numbers. | The mistake | INIT stops with | | --- | --- | | `max` not written | `Tunables.Lift has no max: write max (the top of the safe range, in counts: Motor Finder, B). A safety limit never comes from a library default.` (an Arm's are in `deg`; `min` points to Motor Finder X) | | no section at all | `Tunables.java has no Lift section: ...` | | `max` not above `min` (Lift or Arm) | `Tunables.Lift: max (...) must be more than min (...)` | | `min` or `max` not a `public static` number | `Tunables.Lift.max must be a public static number (like "public static double max = 1000;"): ...` | **Check on the laptop:** `./gradlew :sim:fromRobot` (it writes the simulator's robot file) runs the same name checks and prints what INIT would stop on or warn about. In a JUnit test, `robot.checkTunables()` gives the same lines ([testing](https://crossbotics.com/ftc-helper/docs/tests/03-checks-before-practice-and-matches/)). **Measured servo numbers and the servo's range.** You measure servo positions (named positions, `posA`/`posB`, `rest`/`push`, a hood's `calibration`) for the pulse range the servo had at the time. Adding or removing `.fullRange()` on a part in Robot.java changes where each position points: measure them again ([Full range](https://crossbotics.com/ftc-helper/docs/modules/hardware/#full-range)). ## DEFAULT and MEASURE `DEFAULT` and `MEASURE` are two words you can write in place of a number you do not have yet. Then every setting is in the file from day one, and the file shows what is still to do. Pick the word like this: | The number | Write | | --- | --- | | You know it | the number | | A safety limit (a lift's `min`/`max`, a stop) you do not know yet | `MEASURE` | | A servo position only your robot can give (a fold-out's `stowed`/`deployed`, a claw's `open`/`closed`, a wrist's angles) | `MEASURE` | | A tuning number (`kP`, a speed, a servo's `travelSec`...) you do not know yet | `DEFAULT` | **Why positions are `MEASURE`:** the library's guesses (a Positioner's `stowed` 0.0 and `deployed` 0.5) are not your servo's. With `DEFAULT` the servo goes to a guess at the first command after ▶ (start on the Driver Hub). A guess can push the part into the frame. With `MEASURE` your TeleOp and autos stop at INIT until the [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/) gives the numbers. A part that is `optional()` and not plugged in does not stop, so the simulator still runs before you mount the servo. A wrong tuning number only makes a part slow or soft, so `DEFAULT` (a starting value from the part) is fine there. Add this line at the top of `Tunables.java`, under the `package` line and above `public class Tunables`: ```java import static com.crossbotics.ftchelper.robot.Starting.*; public static class Launcher { public static double kP = DEFAULT, kI = DEFAULT, kD = DEFAULT, kF = DEFAULT; public static double speedRpm = DEFAULT; } public static class Lift { public static double min = MEASURE, max = MEASURE; // INIT stops until you write them public static double kP = DEFAULT; public static double down = 0, high = MEASURE; } ``` | You write | INIT does | | --- | --- | | `DEFAULT` | uses the library's starting value, the same as leaving the line out. The library works it out from the part Robot.java names (the parts catalog, or your own part's numbers) where it can, else it uses its own default. In the PRACTICE profile, INIT shows one short line naming the numbers left at a LIBRARY guess (`Library starting values (DEFAULT): Launcher.stepRpm, Launcher.readyBandRpm`). The parts catalog's numbers (the seller's, such as a servo's speed) are fine as they are, so they go to the robot log only, and the warnings and the button list stay in view. The exception is control gains worked out from the catalog (a flywheel's kF/kP): INIT shows `Starting gains (worked out, not tuned): Launcher` in every profile. The robot log has each value and where it came from (`Launcher: defaults from the catalog (gobilda-5203-6000): kF 11.7, kP 1.17, kI 0.117, speed 3600 rpm. Run the Flywheel Finder, then the Shot Tuner`; `default from my-motor (custom)`; for a number with no part value: `Tunables.Launcher: DEFAULT, library defaults: stepRpm 100`), and so does the tuning menu. The tuning menu shows the same source next to the value. Its "copy into Tunables.java" lines are real numbers | | `DEFAULT` and no part in Robot.java (or a part whose numbers are not known) | uses the general default, and shows a note that says so and how to do better: `Lift: no part in Robot.java, so general defaults (kP, kD, slowZone, tolerance made for a goBILDA 312 RPM motor). Add .part(...) (or Motors.custom(...)), or tune them in the tuning menu` | | `DEFAULT` on a REQUIRED (safety) number | **stops**: `Tunables.Lift.max = DEFAULT, but it is a safety number: a safety limit never comes from the parts catalog or a library default. Write MEASURE until you know it, then the number (...)` | | `MEASURE` | **stops** and names the tool that finds it: `Tunables.Lift.min = MEASURE: find it on the robot: the bottom of the safe range, in counts: Motor Finder, X. Write the number in place of MEASURE.` | - Without the import line, the build fails with `cannot find symbol` and `symbol: variable DEFAULT` (or `MEASURE`). - **The word, or no line:** both give the same starting value. Write the word: then the file shows what is still to tune. - **The older name:** `DEFAULT_FROM_CATALOG` (v0.17.1 to v0.17.4) is the same word. Code that uses it keeps working. New code and these docs write `DEFAULT`. - **Only on number lines.** Use these words only on lines that start `public static double` (an `int` cannot hold them). On `int`, `boolean` or `{ }` (table) lines, leave the line out instead. - **In code:** `Starting.isDefaultFromCatalog(v)` and `Starting.isMeasure(v)` tell them apart from a number. Each is its own "not a number" bit pattern. **When INIT stops on `MEASURE`:** only your TeleOp and your autos stop. The Motor Finder and the Servo Finder still run: they do not read `Tunables.java`. For a lift's `min` and `max`: 1. On the Driver Station, choose **Motor Finder**, press INIT, then ▶ (start). 2. Put the lift at the bottom. Choose `lift` (D-pad, then A): its count starts at 0 there. 3. Move it with gamepad 1's right stick. Press **X** a little above the bottom block (`min`) and **B** a little below the top block (`max`). 4. It shows the numbers: `Tunables.Lift: min = 0, max = 2580`. 5. Write each number in place of `MEASURE`, build, and INIT your TeleOp again. - A part that is `optional()` and not on the robot does not stop on `MEASURE`. - **In the simulator,** INIT does not stop. `./gradlew :sim:fromRobot` writes a stand-in for each `MEASURE` in the simulator's robot file (`tunable.IntakeDeploy.deployed = 0.5`). The simulator uses that stand-in in place of `MEASURE` ([MEASURE in the simulator](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#5-measure-numbers-and-missing-parts)). The real robot never reads that file, so it still stops. - `:sim:newRobot` writes every part's settings this way. - For a part not in the catalog, [describe it in Robot.java](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-in-the-catalog). ## First run: what you get before tuning A new robot runs before any number is tuned. Every number has a safe starting value. When Robot.java names the motor or servo (`Launcher.flywheel("launcher", "gobilda-5203-6000")`, `.part("gobilda-5203-435")`), the library works out the starting value from that part's numbers. They come from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) (the seller's numbers, with the date they were checked). INIT shows one note per part with the values it used, where they came from and the tool that tunes them. A number you write always wins. Writing [`DEFAULT`](#default-and-measure) does the same as leaving the line out. **With no part named, or a part whose numbers are not known** (`Motors.unknown`, a custom part with `Double.NaN`), the library uses the general default (the plain one in each part's table). INIT says so. > **Always name the part.** Write the part number on each part's line in `Robot.java`: > `.part("gobilda-5203-1150")` on an intake, lift, claw or wrist. On a launcher, an arm or a > turret, write the motor's id in the brackets (`Launcher.flywheel("launcher", "gobilda-5203-6000")`). The number is on > the motor's or servo's label; the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) lists them. **Why:** > `DEFAULT` then starts from that part's real numbers (a lift's gains, a servo's move time, a flywheel's > speed control). The simulator moves the part like the real one, and the code says what is on the robot. > For a part not in the catalog, use [`Motors.custom(...)` or `Parts.customServo(...)`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-in-the-catalog). > A robot works without it, but INIT notes "no part in Robot.java, so general defaults". | Part | Not written | What it starts with | Tune it with | | --- | --- | --- | --- | | Launcher | `kF`, `kP`, `kI`, `kD` | REV's formula with the motor's top speed: F = 32767 / (top RPM x counts per turn / 60), P = F / 10, I = P / 10, D = 0. A goBILDA 6000 RPM motor: kF 11.7, kP 1.17, kI 0.117. The library does not use the hub's own gains (the numbers the Control Hub uses when the code gives none: P 10, I 3, F 0): with no F, the wheel only creeps up to speed | [Flywheel Finder](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/) | | Launcher | `speedRpm` | 60% of the motor's top speed, to 10 RPM (6000 RPM motor: 3600). This leaves room above it for the speed control to recover after a shot and on a tired battery, and gives a gentle first shot | [Shot Tuner](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/) | | Lift with `.part(...)` | `kP`, `kD`, `slowZone`, `tolerance` | the plain defaults (made for a goBILDA 312 RPM motor, 537.7 counts a turn) scaled to your motor's counts per turn, so it acts the same per motor turn. A 435 RPM motor: kP 0.0056, kD 0.00028, slowZone 179, tolerance 14 | the tuning menu ([Add a lift, step 4](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/#4-check-it-then-tune-it)) | | Claw, Wrist, Positioner with `.part(...)` | `travelSec` | the servo's catalog speed at the hub's 5 V over its whole move (goBILDA 2000 torque: 270 degrees at 0.25 s per 60 = 1.13 s) | time a move and divide by its distance ([how](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#in-tunablesjava)) | | Hood, servo Turret with `.part(...)` | `travelSec` | the same, over the move from `posA` to `posB` | time it | | servo Indexer with `.part(...)` | `pushSec`, `returnSec` | the same, from `rest` to `push`, at least 0.25 s | watch a feed | | Claw, Wrist, Positioner, servo Indexer | every position | the library's guesses, with a note: they are NOT your servo's | [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/) before the first TeleOp | **Never a starting value:** safety numbers stay REQUIRED (a lift's or arm's `min`/`max`, a hood's or servo turret's stops, interlock zones, a turret's `homeAngle` with a switch). Battery compensation stays off until you write your own `kF`. ## Units Each part uses one unit. The table header says which. | Part | Positions and limits in | Speeds and times in | | --- | --- | --- | | Lift | encoder **counts** (ticks), 0 = where it was at INIT (or the bottom switch) | power 0 to 1 | | Arm, Turret | **degrees**. Arm: 0 = where it was at INIT. Turret: 0 = straight forward, counterclockwise + | power 0 to 1 | | Claw, Wrist, Positioner, Indexer (servo), Hood (servo) | **servo position, 0 to 1** | seconds | | Hood (motor) | encoder **counts** | power 0 to 1 | | Launcher | **RPM** (turns per minute) of the flywheel | seconds | | Drive, Aim, Odometry | **inches** and **degrees** on the field | power 0 to 1 | | PieceSensor | hue in **degrees** (0 to 360) or size in **mm** | milliseconds (`Ms`) | A name that ends in `Sec` is seconds, `Ms` milliseconds, `In` inches, `Mm` millimeters, `Deg` degrees, `Rpm` RPM, `Percent` percent. ## The "In tuning menu" column You can change some numbers while the robot runs. In the PRACTICE profile, after ▶, hold **GUIDE** for 1 s. Use the D-pad to choose and change, and **A** to save on the Control Hub ([tuning guide](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/)). The numbers you tune most are [`Tunable`](https://crossbotics.com/ftc-helper/docs/modules/tuning/)s ("Lift/kP"). | In tuning menu says | What it means | | --- | --- | | **yes, at once** | in the tuning menu; the robot uses the new value in the same run | | **yes, next INIT** | in the tuning menu; the robot uses the new value from the next INIT (it reads the number once, at INIT) | | **no** | not in the tuning menu: change it in `Tunables.java` and install again. Limits are never in the menu, so tuning can never drive a part past a hard stop | **Copy every tuned value back into `Tunables.java`.** The code is the record. The next INIT lists them under "Tuned on this robot (copy into Tunables.java)", for example `Tunables.Lift.kP = 0.0050 (code 0.004)`. **Why:** a new Control Hub loses a value saved only on the old one, and the file is the team's record. ## How to read a finder's lines The [finders](https://crossbotics.com/ftc-helper/docs/tuning/) measure numbers on the robot and show the lines to copy. Each line names the section first: | The finder shows | Copy into Tunables.java | | --- | --- | | `Tunables.Lift: min = 0, max = 2580, P1 = 1200` | in `public static class Lift`: set `min`, `max` and a position. Rename `P1` to a real name (`high`) | | `Tunables.Claw: P1 = 0.210, P2 = 0.770` | in `Claw`: rename them `open` and `closed` | | `public static double[][] speedByDistance = {{24, 2200}, {48, 2550}}; // in Tunables.Launcher` | the whole line, into `Launcher` (replace the old one) | | `Tunables.Odometry: checked = true` | in `Odometry`: `public static boolean checked = true;` | The finders are: [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/), [Motor Finder](https://crossbotics.com/ftc-helper/docs/tuning/05-motor-finder/), [Flywheel Finder](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/), [Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/), [Odometry Tuner](https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/), [Aim Tuner](https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/), [Shot Tuner](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/), [Hood Finder](https://crossbotics.com/ftc-helper/docs/tuning/04-hood-finder/), [Piece Tuner](https://crossbotics.com/ftc-helper/docs/tuning/14-piece-tuner/). "Test" in the part tables means: try it on the robot and change it by hand. ## Parts with no Tunables - **Pieces** (the counter): its numbers are in `Robot.java` (`max(4)`, `startsWith(...)`). Each sensor has its own section ([Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/#in-tunablesjava)). - **Pedro paths** ([pedro module](https://crossbotics.com/ftc-helper/docs/modules/pedro/)): Pedro uses its own constants file, not `Tunables.java`. It also uses `Tunables.Drive.maxPower` (or `practiceMaxPower`). - **Shapes** (`looks(...)`), **part ids** (`part(...)`) and **gear ratios**: in `Robot.java`, because they describe the robot, not a number you tune. --- **Look it up:** [`Starting` in the Javadoc](https://crossbotics.com/ftc-helper/reference/com/crossbotics/ftchelper/robot/Starting.html) (`DEFAULT`, `MEASURE`). **The other pages:** [Reference](https://crossbotics.com/ftc-helper/docs/reference/). --- # Build it by hand URL: https://crossbotics.com/ftc-helper/docs/tutorials/ These tutorials build robot programs by hand, with the library's building blocks, one idea at a time. They show how a robot program works inside: what a PID is, what a bulk read is, why software limits do not replace hard stops. **They are optional.** The docs sections, from [Set up](https://crossbotics.com/ftc-helper/docs/setup/) to [Tests](https://crossbotics.com/ftc-helper/docs/tests/), are enough to build and run a robot with the five files. Do them when you want to know how the parts work inside, or when you need a part that has no five-files module. Each tutorial has a **complete program** you can copy into TeamCode and run. A test builds and checks those programs every time the library changes. The [module pages](https://crossbotics.com/ftc-helper/docs/#modules) are the reference: every class, every method. The tutorials give the "how and why": what to write, in what order, and what to check on the robot. **Used Scratch or Blocks before:** read [From Blocks to Java](https://crossbotics.com/ftc-helper/docs/blocks-to-java/) first. ## The tutorials | # | Tutorial | You learn | Robot needed | | --- | --- | --- | --- | | 01 | [OpMode basics with the library](https://crossbotics.com/ftc-helper/docs/tutorials/01-opmode-basics/) | the shape of every program, imports, fields, lambdas, `try`/`finally` (Java basics) | Control Hub + gamepad only | | 02 | [Motors and servos](https://crossbotics.com/ftc-helper/docs/tutorials/02-motors-and-servos/) | `MotorSetup`, `ServoSetup`, `Hw`, encoders, servo ranges | 1 motor, 1 servo | | 03 | [Buttons](https://crossbotics.com/ftc-helper/docs/tutorials/03-buttons/) | `ControllerBindings`: every kind of binding, toggles with rumble, triggers | gamepad only | | 04 | [Drive a mecanum robot](https://crossbotics.com/ftc-helper/docs/tutorials/04-drive-mecanum/) | `MecanumDrive`, stick shaping, slow mode, field-centric, reverse | mecanum chassis | | 05 | [Drive a standard (tank) robot](https://crossbotics.com/ftc-helper/docs/tutorials/05-drive-tank/) | `TankDrive`, arcade vs tank style, 2 or 4 motors | standard chassis | | 06 | [A fast, clear loop](https://crossbotics.com/ftc-helper/docs/tutorials/06-fast-clear-loop/) | bulk reads, `LoopTimer`, telemetry layout | any drivetrain | | 07 | [PID: hold a lift at a height](https://crossbotics.com/ftc-helper/docs/tutorials/07-pid-lift/) | what P, I, D and F do; `PidController`; live tuning | a lift with an encoder | | 08 | [A lift that cannot hurt itself](https://crossbotics.com/ftc-helper/docs/tutorials/08-safe-lift/) | `SafeMotor`: soft limits, homing, slow zone; why hard stops still matter | a lift (+ bottom switch) | | 09 | [Autonomous by hand with AutoDrive](https://crossbotics.com/ftc-helper/docs/tutorials/09-first-auto/) | `AutoDrive`, tuning distance and turns | any drivetrain | | 10 | [Autonomous with mechanisms](https://crossbotics.com/ftc-helper/docs/tutorials/10-auto-with-mechanisms/) | loop hook, results, INIT choices, mirroring, pose handoff, by hand | drivetrain + lift | | 11 | [Driver assists](https://crossbotics.com/ftc-helper/docs/tutorials/11-driver-assists/) | heading snap with PID, `AimRumble`, `SlewRateLimiter` | mecanum + IMU | | 12 | [Organize a whole robot](https://crossbotics.com/ftc-helper/docs/tutorials/12-robot-structure/) | `Robot` and subsystem classes by hand (what five files does for you) | drivetrain, lift, claw | | 13 | [Test your code without a robot](https://crossbotics.com/ftc-helper/docs/tutorials/13-testing/) | JUnit tests for team code, run on a laptop | none | | 14 | [Mechanism helpers](https://crossbotics.com/ftc-helper/docs/tutorials/14-mechanisms/) | `PositionMotor`, `SpinMotor`, `PositionServo`, `SpinServo`, `Subsystems`: what the modules are made of | lift, servo, intake | | 15 | [Telemetry, profiles and tuning](https://crossbotics.com/ftc-helper/docs/tutorials/15-telemetry-profiles-tuning/) | driver vs debug telemetry, practice/competition, live tuning, match timer | a lift | | 16 | [Easy autonomous](https://crossbotics.com/ftc-helper/docs/tutorials/16-easy-autos/) | `EasyAuto`, the layer under the five-files autonomous | tuned drivetrain + lift + claw | | 17 | [Launcher](https://crossbotics.com/ftc-helper/docs/tutorials/17-launcher/) | flywheel, hood, feeder, shot table, by hand | a shooter | | 18 | [Vision aiming](https://crossbotics.com/ftc-helper/docs/tutorials/18-vision-aim/) | webcam, Limelight 3A or HuskyLens through one interface, safe aiming | camera + drivetrain | | 19 | [Check the hardware](https://crossbotics.com/ftc-helper/docs/tutorials/19-testing-procedures/) | the Hardware Check and a testing order | any robot | | 20 | [Easy TeleOp](https://crossbotics.com/ftc-helper/docs/tutorials/20-easy-teleop/) | `EasyTeleOp`, the layer under `Controls.java` (also used by the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/)) | drivetrain + lift + claw | | 21 | [Find your numbers](https://crossbotics.com/ftc-helper/docs/tutorials/21-finders/) | the finders: servo ends, lift limits, flywheel gains, wheel size, camera offset, shot table | the parts to measure | Tutorials 07, 09 and 12 take longer than the others, because tuning takes time. **New to Java:** do 01 first. It explains imports, fields and lambdas (`() -> ...`), and every lesson uses them. ## Before you start 1. The library is in your robot project: [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/). 2. Read [Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/) once. It saves you hours of fixing a robot that turns the wrong way. 3. The robot configuration on the Driver Station is the list of devices and their names. Make it match the names in the tutorial, or change the names in the code. Each tutorial lists the names it uses. ## How to use a tutorial program The programs are in the library at [`examples/.../examples/tutorials/`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials). 1. Copy the file into `TeamCode/src/main/java/org/firstinspires/ftc/teamcode/`. 2. The `package` line must match the folder the file is in. So change the first line to `package org.firstinspires.ftc.teamcode;`. Tutorial 12's files go in a folder `robot` there, with `package org.firstinspires.ftc.teamcode.robot;`. They also need `RobotSettings`. 3. Delete the `@Disabled` line, so the program shows on the Driver Station. 4. Build, then run it from the Driver Station. **Better: type it yourself.** Each tutorial builds the program step by step. When you type it, you make mistakes and fix them, and you learn more than from a copy. Use the full file to check your work. ## Safety for every tutorial - Start with low power (`powerLimit = 0.4`, or a small multiplier). Raise it after the program works. - Lift the wheels off the ground the first time a drivetrain runs. - Keep a hand near the Driver Station STOP button. - For lifts and arms, find the hard stops before you run anything. --- # Tutorial 01: OpMode basics with the library URL: https://crossbotics.com/ftc-helper/docs/tutorials/01-opmode-basics/ **You will build:** a small program that counts A presses and shows the loop speed on the Driver Station. **You need:** a Control Hub (or a Robot Controller phone), a Driver Station, gamepad 1. You need no motors. **Full program:** [`Tut01HelloLibrary.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut01HelloLibrary.java). To copy a program into TeamCode: [Copy example files into TeamCode](https://crossbotics.com/ftc-helper/docs/pick-your-start/04-copy-into-teamcode/). --- ## 1. The four parts of an OpMode An **OpMode** is a program you pick on the Driver Station. A `LinearOpMode` runs from top to bottom, like a recipe: ```java @TeleOp(name = "Tutorial 01: Hello Library", group = "Tutorials") public class Tut01HelloLibrary extends LinearOpMode { @Override public void runOpMode() { // 1. INIT: runs once, when the driver presses INIT. Set up hardware here. waitForStart(); // 2. waits here until the driver presses ▶ (start) try { while (opModeIsActive()) { // 3. RUN: repeats about 50-200 times per second, until STOP } } finally { // 4. STOP: always runs at the end. Stop the motors here. } } } ``` - `while (opModeIsActive()) { ... }` is a **loop**: the code inside the braces runs again and again while the OpMode runs. Each time, it reads the gamepads, decides, and sets motor powers. - The robot cannot react while it sleeps. So never put `sleep()` in a TeleOp loop. - Code in `finally` runs when the loop ends **for any reason**: the driver pressed STOP, or your code crashed. So put `drive.stop()` there. Then a bug never leaves a motor running. ### The top of the file ```java @TeleOp(name = "Tutorial 01: Hello Library", group = "Tutorials") // (1)! @Disabled // hides this program on the Driver Station: delete this line in your copy (2)! public class Tut01HelloLibrary extends LinearOpMode { // (3)! // A field: button actions can change it. private int presses = 0; // (4)! // The SDK calls runOpMode() when the driver presses INIT. @Override // (5)! public void runOpMode() { ``` 1. `@TeleOp` puts the program in the Driver Station's TeleOp list, with this name, in the "Tutorials" group. `@Autonomous` puts it in the Autonomous list. 2. Every tutorial file has `@Disabled`, so the lists stay short. Delete it in your copy, or your program does not show on the Driver Station. 3. The class name must match the file name. `extends LinearOpMode` gives you `hardwareMap`, `gamepad1`, `gamepad2` and `telemetry` (the text on the Driver Station screen). 4. `private` = only this file can use it. `int` = a whole number. [Why it is a field](#a-field-for-what-a-button-changes). 5. `@Override` says "this replaces a method the SDK already has". ## 2. Imports `import` lines at the top of the file tell Java where each class lives. `com.qualcomm...` is the FTC SDK. `com.crossbotics...` is this helper library. To add one, click the red class name and press **Alt+Enter** (Mac: **Option+Enter**). `ControllerBindings` has small "inner" names (`Pad`, `Btn`, `Trigger`). Import them too, so you can write `Pad.G1` instead of `ControllerBindings.Pad.G1`: ```java import com.crossbotics.ftchelper.gamepad.ControllerBindings; import com.crossbotics.ftchelper.gamepad.ControllerBindings.Btn; import com.crossbotics.ftchelper.gamepad.ControllerBindings.Pad; ``` ## 3. Set up in INIT ```java LoopTimer loopTimer = new LoopTimer(); ControllerBindings controls = new ControllerBindings() .bindPress(Pad.G1, Btn.A, () -> presses++); ``` - `new LoopTimer()` makes a loop-speed meter. - `new ControllerBindings()` makes the button list. `.bindPress(...)` adds one job: "when gamepad 1's A goes down, add one to `presses`". - `() -> presses++` is a **lambda**: a small piece of code you hand over to run LATER, each time the driver presses A. For more than one line, use braces: `() -> { presses++; telemetry.speak("hi"); }`. ### A field for what a button changes A **field** is a variable made inside the class but outside any method, like `presses`. Java does not let a lambda change a variable made inside a method. A lambda may change a field. Rule of thumb: *anything a button changes is a field.* ## 4. The loop ```java waitForStart(); controls.ignoreHeldButtons(gamepad1, gamepad2); while (opModeIsActive()) { loopTimer.update(); controls.update(gamepad1, gamepad2); TelemetryHelper.section(telemetry, "Hello"); telemetry.addData("A presses", presses); TelemetryHelper.flag(telemetry, "B held", controls.isDown(Pad.G1, Btn.B)); // (1)! TelemetryHelper.value(telemetry, "Loop speed", loopTimer.getHz(), "Hz"); // (2)! telemetry.update(); } ``` 1. `isDown` tells you whether B is held right now. It binds no action to B. 2. Loops per second (Hz). Higher is better: the robot reacts faster. - `ignoreHeldButtons`: a button held at ▶ does nothing until the driver lets go ([Tutorial 03](https://crossbotics.com/ftc-helper/docs/tutorials/03-buttons/) explains why). - `controls.update(...)` reads the gamepads and runs the jobs. Call it once per loop. - Add the telemetry lines, then call `telemetry.update()` **once**, at the end of the loop. ## Run it 1. INIT: the screen says "Ready". Press ▶. 2. Press A a few times: the count goes up by exactly one per press, also when you hold A. 3. Hold B: "B held : yes". 4. Loop speed: probably 100+ Hz with nothing connected. ## If something goes wrong | Problem | Fix | | --- | --- | | Red class name, and Alt+Enter offers no import | The library is missing: [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/). | | "Variable used in lambda expression should be final" | The variable a button changes must be a **field**. Move it out of `runOpMode`. | | The OpMode is not on the Driver Station | Delete the `@Disabled` line, build, and install again. | ## Try this 1. Add a binding so B **resets** the count to 0. (Hint: `bindPress(Pad.G1, Btn.B, () -> presses = 0)`.) 2. Show the loop time in milliseconds with `loopTimer.getAverageMs()`. 3. Put `sleep(100);` inside the loop. Watch the loop speed, and how late the program sees an A press. This is why TeleOp loops must never sleep. Take it out again. --- **Next:** [Tutorial 02: Motors and servos](https://crossbotics.com/ftc-helper/docs/tutorials/02-motors-and-servos/). **Look it up:** [gamepad.md](https://crossbotics.com/ftc-helper/docs/modules/gamepad/), [telemetry.md](https://crossbotics.com/ftc-helper/docs/modules/telemetry/), [util.md](https://crossbotics.com/ftc-helper/docs/modules/util/). --- # Tutorial 02: Motors and servos URL: https://crossbotics.com/ftc-helper/docs/tutorials/02-motors-and-servos/ **You will build:** a program that moves an arm with the stick and opens and closes a claw with buttons. **You need:** one motor named `arm` (with its encoder cable plugged in), one servo named `claw`. Optional: a touch sensor named `arm_touch`. **Full program:** [`Tut02MotorAndServo.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut02MotorAndServo.java) --- ## 1. Get and set up the motor An **encoder** is a sensor on the motor that counts how far the shaft has turned. That count is the **position**, in "ticks". Without the library, a motor needs five separate lines in the right order. With the library, it is one chain: ```java DcMotorEx arm = MotorSetup.get(hardwareMap, "arm") .brake() .resetEncoder() .runWithoutEncoder() .done(); ``` - `get(hardwareMap, "arm")`: find the motor named "arm" in the active configuration. When the name is wrong, the error lists the names that do exist. - `.brake()`: at power 0 the motor resists turning, so the arm does not fall. - `.resetEncoder()`: the encoder count becomes 0 **here**. So start with the arm in a known place. - `.runWithoutEncoder()`: power goes straight to the motor. Your code can still READ the encoder. - `.done()`: power 0, and hand back the motor. **Order matters:** reset first, then the run mode. A reset leaves the motor in a "stopped" mode until your code sets a run mode. ## 2. Get and set up the servo ```java Servo claw = ServoSetup.get(hardwareMap, "claw") .range(0.20, 0.75) .done(); ``` A servo goes to a position from 0 to 1. But your claw works only in a smaller range, for example from 0.20 (fully open) to 0.75 (fully closed). Past those, the claw pushes into the frame, the servo stalls, and it gets hot. After `.range(0.20, 0.75)`, **0 means 0.20 and 1 means 0.75.** So `setPosition(0)` opens, `setPosition(1)` closes, and the servo can never go further. `.done()` hands you the servo. The servo does not move until you first set a position. To swap which end is 0, add `.reversed()`. **Find the two numbers** with the [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/). To use the servo's whole turn (`.fullRange()`), set it before you find them: [Full range](https://crossbotics.com/ftc-helper/docs/modules/hardware/#full-range). ## 3. A part that might not be there ```java TouchSensor touch = Hw.tryGet(hardwareMap, TouchSensor.class, "arm_touch"); ``` When there is no device with that name, `tryGet` returns `null` (Java's word for "nothing here") and the program goes on. Use it for parts that are only on some robots. **Always check for null** before you use the part: ```java if (touch != null) TelemetryHelper.flag(telemetry, "Touch", touch.isPressed()); ``` For parts the robot cannot work without, use `Hw.get(...)`. It stops with a clear message. ## 4. Buttons and the loop ```java ControllerBindings controls = new ControllerBindings() .bindPress(Pad.G1, Btn.A, () -> claw.setPosition(CLAW_OPEN)) .bindPress(Pad.G1, Btn.B, () -> claw.setPosition(CLAW_CLOSED)) .bindPress(Pad.G1, Btn.X, () -> MotorSetup.of(arm).resetEncoder().runWithoutEncoder().done()); ``` `CLAW_OPEN` and `CLAW_CLOSED` are named numbers (0 and 1): a name says what a number means. `MotorSetup.of(arm)` works on a motor you already have. Here X zeroes the encoder again, then sets the run mode again, because a reset stops the motor. In the loop: ```java double power = StickShaping.shape(-gamepad1.left_stick_y, 0.05, 1) * 0.5; arm.setPower(power); TelemetryHelper.motor(telemetry, "Arm", arm); TelemetryHelper.servo(telemetry, "Claw", claw); ``` - The minus: the SDK says "stick up" is negative. - `shape(..., 0.05, 1)` ignores tiny stick noise. `* 0.5` limits the arm to half power while you test. - `TelemetryHelper.motor` shows power, encoder position, and speed on one line. - `TelemetryHelper.servo` shows the position you last asked for. A servo cannot report its true position. In `finally`, put `arm.setPower(0);`. ## Run it **Safety:** this arm has no limits in code yet. Its hard stop is the metal or plastic end of its travel, and only you stop the arm there. Know where that stop is, keep hands clear, and use short, gentle pushes. 1. Put the arm in its rest position. Press INIT and ▶. Position shows 0. 2. Push the stick up gently. The arm moves up and the position goes UP. **If the position goes down when the arm goes up**, add `.reversed()` to the motor chain. Later tutorials need positive power to move the mechanism in its "positive" direction. 3. A and B open and close the claw, inside the range you set. X sets the position back to 0. ## If something goes wrong | Problem | Fix | | --- | --- | | Position stays 0 while the arm moves | The encoder cable is not plugged in, or it is in another port. | | Servo buzzes and gets warm at one end | The range goes past the mechanical end. Make the range smaller. | | Servo does not move at all | The servo is on the wrong port, or the configuration says "Continuous Rotation" for it (it must be "Servo"). | More wiring problems: [Wiring checks](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/). ## Try this 1. Change the motor to `.coast()`. Raise the arm and let go of the stick. Watch the arm: this is why arms and lifts use `.brake()`. 2. Add a third claw position, "half open" at 0.5, on the Y button. 3. Make the stick control the arm at full power only while the driver holds the right bumper. (Hint: `gamepad1.right_bumper ? 1.0 : 0.5`.) --- **Next:** [Tutorial 03: Buttons](https://crossbotics.com/ftc-helper/docs/tutorials/03-buttons/). **Look it up:** [hardware.md](https://crossbotics.com/ftc-helper/docs/modules/hardware/). --- # Tutorial 03: Buttons URL: https://crossbotics.com/ftc-helper/docs/tutorials/03-buttons/ **You will build:** a test program that shows every kind of button job on telemetry. **You need:** a Control Hub and gamepads 1 and 2. You need no motors. **Full program:** [`Tut03Buttons.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut03Buttons.java) --- ## 1. The problem buttons have ```java if (gamepad1.a) presses++; ``` The loop runs about 100 times per second, and a quick tap keeps A "down" for about 10 of them. So this line adds about 10 per tap. To get **one action per press** by hand, you need an extra variable for every button. `ControllerBindings` does it for every button at once, and keeps all the jobs in one list. ## 2. The kinds of jobs ```java ControllerBindings controls = new ControllerBindings() .bindPress(Pad.G1, Btn.A, () -> presses++) // once, when A goes down .bindHold(Pad.G1, Btn.B, () -> holdLoops++) // every loop while B is down .bindRelease(Pad.G1, Btn.X, () -> releases++) // once, when X comes up .bindToggle(Pad.G1, Btn.Y, () -> { slowMode = true; confirm.play(true); }, // 1st press: ON () -> { slowMode = false; confirm.play(false); }); // 2nd press: OFF ``` | You want | Use | Example | | --- | --- | --- | | do something once | `bindPress` | open the claw, go to a set height | | keep doing it while the button is held | `bindHold` | run the intake | | something when the driver lets go | `bindRelease` | stop the intake | | a mode that flips on/off | `bindToggle` | slow mode, field-centric | - `Pad.G1` is gamepad 1 (the driver). `Pad.G2` is gamepad 2 (the operator). Bind the same job to both, and either driver can do it. - A job must be quick. Never wait or sleep inside one: the whole robot freezes until the job ends. - `bindToggle` starts OFF. The curly brackets `{ }` hold two steps in one lambda. - Two jobs on ONE button run in the order you added them. ## 3. Feedback with rumble A toggle is invisible: the driver must look at the screen to see whether slow mode is on. `ToggleRumble` buzzes the gamepad: **two buzzes = ON, one buzz = OFF**. Use the same rule for every toggle on your robot, so drivers learn it once. ```java ToggleRumble confirm = new ToggleRumble(gamepad1); ``` ## 4. Choosing from a list with the D-pad ```java static final String[] HEIGHT_NAMES = {"Floor", "Low", "Middle", "High"}; private int heightIndex = 0; ... .bindPress(Pad.G1, Btn.DPAD_UP, () -> heightIndex = Math.min(heightIndex + 1, HEIGHT_NAMES.length - 1)) .bindPress(Pad.G1, Btn.DPAD_DOWN, () -> heightIndex = Math.max(heightIndex - 1, 0)) ``` `HEIGHT_NAMES` is an **array**: a list of values in one variable. `heightIndex` is the place in the list, counting from 0, so `HEIGHT_NAMES[0]` is "Floor". `Math.min` and `Math.max` stop the number at the ends of the list. ## 5. Triggers Triggers give a number from 0 (let go) to 1 (fully pulled). ```java .bindTriggerPress(Pad.G1, Trigger.RT, () -> shots++) // once per pull past halfway .bindTriggerAxis(Pad.G1, Trigger.LT, value -> leftTrigger = value) // the value, every loop ``` - `bindTriggerPress` / `bindTriggerHold` treat the trigger as a button: "pressed" means past 0.5. When drivers fire by accident, change that with `.setTriggerThreshold(0.8)`. - `bindTriggerAxis` hands you the number every loop. `value -> ...` is a lambda with one input. ## 6. The "held through ▶" guard ```java waitForStart(); controls.ignoreHeldButtons(gamepad1, gamepad2); ``` Drivers often hold a button while the match starts (▶ is the start button on the Driver Hub). Without this line, a held button's press job runs in the very first loop: a surprise action at the start of the match. With it, **a button held at ▶ does nothing until the driver lets go of it once.** ## 7. The loop ```java while (opModeIsActive()) { controls.update(gamepad1, gamepad2); // once per loop, before you use the results ...telemetry... } ``` Without `controls.update(...)`, no button does anything. This program has no `try`/`finally`, because it has no motors to stop. ## Run it 1. INIT. **Hold A**, press ▶, keep holding: the A count stays 0. Let go and press: 1. 2. Tap A many times: exactly one per tap. Gamepad 2's A also counts. 3. Hold B: the count runs up fast (`bindHold`). Hold X: nothing. Let go: +1 (`bindRelease`). 4. Y: two buzzes and "Slow mode : yes". Y again: one buzz, "no". 5. D-pad up and down: the height name changes and stops at Floor and High. 6. Right trigger past halfway: one shot per pull. Left trigger: the number follows it. ## If something goes wrong | Problem | Fix | | --- | --- | | Nothing happens | Check that `controls.update(gamepad1, gamepad2)` is inside the loop. Check that the gamepad is assigned (Start+A for gamepad 1, Start+B for gamepad 2). | | A counts many times per press | That job uses `bindHold`. Use `bindPress`. | | No rumble | Some gamepads have no rumble motors. The Logitech F310 does not rumble. | | "Cannot assign a value to final variable" | The variable must be a **field** ([Tutorial 01](https://crossbotics.com/ftc-helper/docs/tutorials/01-opmode-basics/#a-field-for-what-a-button-changes)). | ## Try this 1. Make the right bumper toggle a "turbo" mode with its own rumble confirmation. 2. Make the D-pad list wrap around: up from High goes to Floor. (Hint: `% HEIGHT_NAMES.length`. `%` gives the remainder after dividing, so it wraps 4 back to 0.) 3. Use `bindHold` and `bindRelease` together on gamepad 2's A: hold = "intake running", let go = "intake stopped". --- **Next:** [Tutorial 04: Drive a mecanum robot](https://crossbotics.com/ftc-helper/docs/tutorials/04-drive-mecanum/) or [Tutorial 05: Drive a standard (tank) robot](https://crossbotics.com/ftc-helper/docs/tutorials/05-drive-tank/). **Look it up:** [gamepad.md](https://crossbotics.com/ftc-helper/docs/modules/gamepad/). --- # Tutorial 04: Drive a mecanum robot URL: https://crossbotics.com/ftc-helper/docs/tutorials/04-drive-mecanum/ **You will build:** a TeleOp that drives a mecanum robot, with slow mode, field-centric driving and reverse drive. **You need:** a mecanum chassis with motors `front_left`, `front_right`, `back_left`, `back_right`, the hub's IMU (`imu`), and a block to lift the wheels off the ground. **Full program:** [`Tut04MecanumDrive.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut04MecanumDrive.java) --- ## 1. How mecanum wheels move Each mecanum wheel has rollers at 45 degrees. The robot spins the four wheels in different combinations to drive forward, sideways ("strafe"), turn, or all three at once. The library does the math (in `MecanumMixer`). You only say what you want ([Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/)): ```java drive.drive(forward, strafeRight, turnClockwise); // each -1 to 1 ``` ## 2. Set up the drive ```java DriveConfig driveConfig = DriveConfig.mecanum(); driveConfig.powerLimit = 0.6; MecanumDrive drive = new MecanumDrive(hardwareMap, driveConfig); ``` `DriveConfig` holds the motor names, which motors are reversed, and the power limit. The defaults (`front_left` ... `back_right`, left side reversed) fit most goBILDA and REV chassis. For other names: `driveConfig.frontLeft = "fl";`. `powerLimit = 0.6` means no wheel ever gets more than 60%. Keep it low until everything works. ## 3. Check the motor directions FIRST With one motor reversed wrongly, the robot spins or drifts, and nothing else makes sense. With the robot on a block, run [`MotorDirectionCheck`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/MotorDirectionCheck.java) and hold X, Y, A, B to spin one wheel each. Every wheel must roll the way that moves the robot **forward**. Flip a wrong one in your config, for example `driveConfig.backRightReversed = true;`. More: [Motor Direction Check](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#motor-direction-check-each-wheel-rolls-forward). ## 4. The basic drive loop ```java double forward = -gamepad1.left_stick_y; double strafe = gamepad1.left_stick_x; double turn = gamepad1.right_stick_x; drive.drive(forward, strafe, turn); ``` The minus on `left_stick_y`: the SDK says "up" is negative. ## 5. Make the sticks feel good ```java double forward = StickShaping.shape(-gamepad1.left_stick_y, 0.05, 2); double strafe = StickShaping.shape(gamepad1.left_stick_x, 0.05, 2); double turn = StickShaping.shape(gamepad1.right_stick_x, 0.05, 2); ``` `StickShaping.shape(value, deadband, exponent)` changes the raw stick number before it goes to the motors: - **Deadband 0.05:** a stick at rest is often not at exactly 0. Without a deadband, the robot creeps. - **Exponent 2:** half stick gives a quarter of the power. Small moves become precise, and a full push is still full power. Try 1 (straight) and 3 (very soft), and pick one. ## 6. Slow mode on a trigger ```java double speed = StickShaping.slowScale(gamepad1.left_trigger, 0.3); drive.drive(forward, strafe, turn, speed); ``` Trigger let go = full speed. Pulled all the way = 30%. Use it to line up to score. ## 7. Field-centric driving With **robot-centric** driving, "stick up" means "where the robot faces". When the robot faces the driver, everything feels backwards. With **field-centric** driving, "stick up" always means "away from the driver". For that, the robot must know its **heading** (which way it faces, in degrees). The **IMU**, a turn sensor inside the Control Hub, measures it. ```java IMU imu = ImuSetup.get(hardwareMap, "imu", RevHubOrientationOnRobot.LogoFacingDirection.UP, RevHubOrientationOnRobot.UsbFacingDirection.FORWARD); ... drive.driveFieldCentric(forward, strafe, turn, ImuSetup.headingDeg(imu), speed); ``` **The two directions must match how YOUR hub is mounted.** Wrong values give a wrong heading, and field-centric driving goes the wrong way. How to read them and check them: [How your Control Hub is mounted](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#how-your-control-hub-is-mounted). The heading is 0 where the robot pointed when the IMU started. So give the driver a button that says "forward is where the robot points now". The driver points the robot away first: ```java .bindPress(Pad.G1, Btn.BACK, imu::resetYaw) ``` `imu::resetYaw` is a short way to write `() -> imu.resetYaw()`. Yaw is the IMU's word for heading. In the program, Y toggles between the two styles, with a rumble to confirm. ## 8. Reverse drive To load from the back, the driver may want the back to act as the front. `ReverseDrive` does that, for forward and strafe only: ```java ReverseDrive reverse = new ReverseDrive(); .bindPress(Pad.G1, Btn.L_STICK_BTN, () -> confirm.play(reverse.toggle())) ... drive.drive(reverse.apply(forward), reverse.apply(strafe), turn, speed); ``` `reverse.toggle()` flips the mode and returns the new state, so `confirm.play(...)` buzzes twice for ON and once for OFF. In field-centric mode the robot's front does not matter, so the program uses reverse only in robot-centric mode. In `finally`, put `drive.stop();`. ## Run it 1. With the wheels off the ground, push the stick up: all wheels roll forward. Then drive on the floor. 2. Stick up = forward, stick right = slides right, right stick right = turns clockwise. 3. Left trigger slows the robot down. 4. Y (two buzzes): field-centric. Turn the robot 90 degrees and push stick up: it still goes away from you. 5. Point the robot away and press BACK: it resets "forward". 6. Click the left stick (two buzzes): the back is now the front. ## If something goes wrong | Problem | Fix | | --- | --- | | Spins when it should go straight | A motor direction is wrong. Section 3. | | Slides diagonally when strafing | Two motor names are on the wrong wheels (for example front_left and back_left swapped). | | Field-centric goes the wrong way, or circles | The IMU directions do not match the hub, or the driver did not reset "forward" with the robot facing away. | | Robot creeps with sticks let go | Raise the deadband to 0.08. | | "MecanumDrive needs a MECANUM DriveConfig" | You used `DriveConfig.tank()`. Use `DriveConfig.mecanum()` or `TankDrive`. | ## Try this 1. Change the exponent to 3 for turning only. Check whether aiming is easier. 2. Put field-centric ON by default. 3. Make a "precision mode" toggle that sets a fixed `speed = 0.35`, instead of the trigger. --- **Next:** [Tutorial 05: Drive a standard (tank) robot](https://crossbotics.com/ftc-helper/docs/tutorials/05-drive-tank/), or [Tutorial 06: A fast, clear loop](https://crossbotics.com/ftc-helper/docs/tutorials/06-fast-clear-loop/) when you have no tank drive. **Look it up:** [drive.md](https://crossbotics.com/ftc-helper/docs/modules/drive/), [hardware.md: ImuSetup](https://crossbotics.com/ftc-helper/docs/modules/hardware/#imusetup), [gamepad.md](https://crossbotics.com/ftc-helper/docs/modules/gamepad/). --- # Tutorial 05: Drive a standard (tank) robot URL: https://crossbotics.com/ftc-helper/docs/tutorials/05-drive-tank/ **You will build:** a TeleOp that drives a standard (tank) robot, with a button to switch between two driving styles. **You need:** a standard chassis with two motors `left_drive` and `right_drive` (or four: `front_left`, `front_right`, `back_left`, `back_right`). **Full program:** [`Tut05TankDrive.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut05TankDrive.java) --- ## 1. How a standard drive moves A standard drive (also called tank, differential, or "skid steer") has normal wheels on a left side and a right side. Both sides forward = drive forward. Left forward, right back = spin right. It cannot move sideways. ## 2. Set up the drive ```java DriveConfig driveConfig = DriveConfig.tankTwoMotor(); // DriveConfig.tank() for 4 motors driveConfig.powerLimit = 0.6; TankDrive drive = new TankDrive(hardwareMap, driveConfig); ``` | Your robot | Config | Motor names | | --- | --- | --- | | 2 motors | `DriveConfig.tankTwoMotor()` | `left_drive`, `right_drive` (same as the FTC samples) | | 4 motors | `DriveConfig.tank()` | `front_left`, `front_right`, `back_left`, `back_right` | `powerLimit = 0.6` keeps every wheel at 60% or less while you test. With 4 motors, both motors on a side always get the same power. The motors on the left face the other way, so the library reverses the left side by default. Check it with [`MotorDirectionCheck`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/MotorDirectionCheck.java): set its `config()` to `DriveConfig.tankTwoMotor()` and lift the wheels off the ground. X = left, Y = right. Both must roll forward. ## 3. Arcade style One stick moves forward and back, and the other turns. For most new drivers, this style is the easiest. ```java drive.arcade(StickShaping.shape(-gamepad1.left_stick_y, 0.05, 2), StickShaping.shape(gamepad1.right_stick_x, 0.05, 2), speed); ``` The library adds and subtracts for you: left = forward + turn, right = forward - turn. When a side goes past full power, the library scales both sides down together, so the robot keeps the curve you asked for. ## 4. Tank style Each stick drives one side, like a bulldozer. It is very direct, and some drivers like it better. BOTH sticks' Y need the minus. ```java drive.tank(StickShaping.shape(-gamepad1.left_stick_y, 0.05, 2), StickShaping.shape(-gamepad1.right_stick_y, 0.05, 2), speed); ``` ## 5. Let the driver choose ```java .bindToggle(Pad.G1, Btn.X, () -> { tankStyle = true; confirm.play(true); }, () -> { tankStyle = false; confirm.play(false); }) ``` Let each driver try both styles for a practice session. Keep the one they drive best with. Slow mode and `drive.stop()` in `finally` work the same as on [mecanum](https://crossbotics.com/ftc-helper/docs/tutorials/04-drive-mecanum/#6-slow-mode-on-a-trigger). ## 6. Autonomous on a standard drive `AutoDrive` ([Tutorial 09](https://crossbotics.com/ftc-helper/docs/tutorials/09-first-auto/)) works on a standard drive too, but only forward/back and turns: `move(24, 0, ...)`, `move(24, 180, ...)`, `turn(...)`, `turnTo(...)`. A sideways move gives an error that says "turn first, then move". ## Run it 1. With the wheels off the ground, push the stick up: both sides roll forward. 2. On the floor, arcade style drives and turns as expected. Right stick right = turn right. 3. X (two buzzes): tank style. Both sticks up = forward. Left up, right down = spin right. ## If something goes wrong | Problem | Fix | | --- | --- | | Spins when both sides should go forward | One side's direction is wrong: flip `frontLeftReversed` or `frontRightReversed`. (With 2 motors, the library stores `left_drive` and `right_drive` as the "front" motors.) | | Turns the wrong way in arcade | Left and right motor names are swapped. | | "TankDrive needs a TANK DriveConfig" | Use `DriveConfig.tank()` or `tankTwoMotor()`. | | 4-motor robot: one wheel fights the others | That one motor's direction is wrong. Use MotorDirectionCheck. | ## Try this 1. Add `ReverseDrive` to arcade mode ([Tutorial 04](https://crossbotics.com/ftc-helper/docs/tutorials/04-drive-mecanum/#8-reverse-drive)). 2. Make turning gentler than driving: multiply the turn by 0.7. 3. With 4 motors: change the config to `DriveConfig.tank()` and check all four with MotorDirectionCheck. --- **Next:** [Tutorial 06: A fast, clear loop](https://crossbotics.com/ftc-helper/docs/tutorials/06-fast-clear-loop/). **Look it up:** [drive.md: TankDrive](https://crossbotics.com/ftc-helper/docs/modules/drive/#tankdrive), [gamepad.md](https://crossbotics.com/ftc-helper/docs/modules/gamepad/). --- # Tutorial 06: A fast, clear loop URL: https://crossbotics.com/ftc-helper/docs/tutorials/06-fast-clear-loop/ **You will build:** a drive program that shows its loop speed. A turns bulk reads on and off. B shows and hides the debug telemetry. **You need:** a mecanum drivetrain (change to `TankDrive` for a standard one). **Full program:** [`Tut06FastLoop.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut06FastLoop.java) --- ## 1. Why loop speed matters Your robot reads, decides and sets the powers once per loop. At 25 loops per second, the robot reacts 40 ms (milliseconds, thousandths of a second) late. A PID (Tutorial 07) gets jumpy, and driving feels mushy. At 100+ loops per second, the robot feels instant. ## 2. Measure it ```java LoopTimer loopTimer = new LoopTimer(); ... while (opModeIsActive()) { loopTimer.update(); // first thing in the loop ... TelemetryHelper.value(telemetry, "Loop", loopTimer.getHz(), "Hz"); } ``` Measure before and after every change. A guess is often wrong. ## 3. Bulk reads A **hub** is the Control Hub or Expansion Hub the motors and sensors plug into. Each time your code reads an encoder or a sensor, the Control Hub sends a message to the hub and waits for the answer: about 2 ms. Four drive encoders plus a lift encoder cost about 10 ms per loop, all of it waiting. A **bulk read** asks the hub for ALL its readings in one message. There are two ways: **AUTO (easy, start here):** ```java BulkReads.auto(hardwareMap); // one line in INIT ``` **MANUAL (fastest):** you clear the saved readings yourself, once, at the top of every loop: ```java List hubs = BulkReads.manual(hardwareMap); ... while (opModeIsActive()) { BulkReads.clear(hubs); // FIRST line of the loop ... } ``` **If you forget `clear` in MANUAL mode, the readings never change.** Then the robot acts very strangely: for example, a PID never sees the lift move. That is why AUTO is the safe default. `List` is a list of hubs: Java calls a hub a `LynxModule`. The A button sets the hub mode directly, for the demo only, then calls `loopTimer.reset()` so the old loop speed does not mix in. ## 4. Telemetry the driver can use During a match, the driver looks at the screen for half a second. Put what the driver needs at the top, and hide the rest: ```java // What the driver needs: at the top. TelemetryHelper.section(telemetry, "Driver"); TelemetryHelper.flag(telemetry, "Bulk reads (A)", bulk); TelemetryHelper.value(telemetry, "Loop", loopTimer.getHz(), "Hz"); // Debug numbers: at the bottom, and only when asked for. if (showDebug) { // (1)! TelemetryHelper.section(telemetry, "Debug (B)"); for (int i = 0; i < wheels.length; i++) TelemetryHelper.motor(telemetry, names[i], wheels[i]); // (2)! } telemetry.update(); ``` 1. The debug section also reads the encoders. So the bulk-read difference shows most with the debug section on. 2. `wheels` comes from `drive.getMotors()`, and `names` is `{"FL", "FR", "BL", "BR"}` in the same order. `section` puts a `--- Driver ---` heading line. `motor` puts power, position and speed on ONE line. Telemetry also costs loop time, so show debug only when you need it. Call `telemetry.update()` **once** per loop. ## Run it 1. Press ▶ (start on the Driver Hub). Write down the Hz with bulk reads ON. 2. Press A (bulk reads OFF). The Hz drops, because each wheel read is now a separate message. 3. Press B to show the debug section. The Hz drops a little more. A typical result: 60 Hz without bulk reads, 150+ Hz with them. ## If something goes wrong | Problem | Fix | | --- | --- | | Readings frozen | The program uses MANUAL mode without `BulkReads.clear(hubs)` at the top of the loop. | | Hz is very low (< 30) even with bulk reads | Look for `sleep()` in the loop, or a camera process that runs. Turn off debug telemetry. | ## Try this 1. Change the program to `BulkReads.auto(hardwareMap)` and remove the `clear` line. Compare Hz with MANUAL. 2. Add 20 telemetry lines in a `for` loop. Watch how much the Hz drops. --- **Next:** [Tutorial 07: PID: hold a lift at a height](https://crossbotics.com/ftc-helper/docs/tutorials/07-pid-lift/) **Look it up:** [hardware.md: BulkReads](https://crossbotics.com/ftc-helper/docs/modules/hardware/#bulkreads), [util.md: LoopTimer](https://crossbotics.com/ftc-helper/docs/modules/util/#looptimer), [telemetry.md: TelemetryHelper](https://crossbotics.com/ftc-helper/docs/modules/telemetry/#telemetryhelper) --- # Tutorial 07: PID: hold a lift at a height URL: https://crossbotics.com/ftc-helper/docs/tutorials/07-pid-lift/ **You will build:** a lift that goes to three heights on buttons and holds there, with gains you change from the gamepad. **You need:** a lift (slide, elevator or arm) with a motor named `lift` and its encoder cable. Positive power must move it UP (Tutorial 02). **Turn the robot on with the lift at the bottom.** **Full program:** [`Tut07LiftPid.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut07LiftPid.java) > **Safety:** this program keeps the power low, but it has no software limits. Tutorial 08 adds them. > Stay near STOP, and find your hard stops first. --- ## 1. The idea Heights are in encoder **ticks** (the counts from Tutorial 02). For example, you want the lift at 1200 ticks, and it is at 400. The **error** is 1200 - 400 = 800. A **PID controller** turns the error into a power, every loop. It adds up to four parts. For each part, you choose a number, called its **gain**. The gain sets how strong that part is: | Part | Gain | What it does | Like... | | --- | --- | --- | --- | | **P** proportional | `kP` | power = kP x error. Far = push hard, close = push gently. | a spring | | **I** integral | `kI` | adds up the error over time. Fixes a small error that never goes away. | a slow, stubborn push | | **D** derivative | `kD` | looks at how fast the error shrinks and pushes against it. Stops overshoot. | a shock absorber | | **F** feedforward | `kF` | a fixed push every loop, no matter what. Holds the lift up against gravity. | a counterweight | Most lifts work well with **P + D + a little F**. Many lifts never need I. ## 2. Make the controller Write the heights first, in ticks: ```java // 0 = where the lift was at INIT. TOP must be below the real top of the lift. static final int BOTTOM = 0, MIDDLE = 1200, TOP = 2400; // encoder ticks: measure yours (1)! ``` 1. Measure yours: move the lift by hand and read the position on telemetry (Tutorial 02). Keep TOP a little below the hard stop at the top. Then make the controller: ```java PidController pid = new PidController(gains[0], gains[1], gains[2], gains[3]) // kP, kI, kD, kF .setOutputLimits(-0.4, 0.7) // never more than 40% down or 70% up .setIntegralLimit(0.2) // I can never add more than 0.2 power .setTolerance(20); // within 20 ticks counts as "there" ``` - **Output limits** stop a bad gain from slamming the lift. Up gets more, because it fights gravity. - **Integral limit:** without it, I builds up while the lift is stuck, then shoots it past the target ("windup"). - Make the controller **once**, in INIT. It remembers the last error (for D) and the sum (for I). A new controller every loop forgets all of that. ## 3. Use it every loop ```java double power = pid.calculate(target, lift.getCurrentPosition()); lift.setPower(power); ``` Target and measurement go in, and power comes out. Run it every loop, also at the target: then it holds the lift up against gravity. ## 4. Change the target with buttons ```java .bindPress(Pad.G1, Btn.A, () -> newTarget(BOTTOM, pid)) .bindPress(Pad.G1, Btn.Y, () -> newTarget(TOP, pid)) ... private void newTarget(int ticks, PidController pid) { target = ticks; pid.reset(); // forget the old I and D memory } ``` Call `reset()` each time the target changes. Otherwise the I sum and the last error from the old target give a kick at the start of the new move. ## 5. Tune it live A rebuild for each of many small changes is slow. So this program changes the gains from the gamepad: ```java .bindPress(Pad.G1, Btn.DPAD_RIGHT, () -> selected = (selected + 1) % gains.length) // next gain .bindPress(Pad.G1, Btn.DPAD_UP, () -> changeGain(pid, true)) // bigger .bindPress(Pad.G1, Btn.DPAD_DOWN, () -> changeGain(pid, false)) // smaller ... pid.setGains(gains[0], gains[1], gains[2], gains[3]); ``` - Each press multiplies the gain by 1.25 (up) or 0.8 (down), so small and large gains both change by a sensible amount. A gain at 0 first jumps to a small value (0.001 for P, 0.0001 for I and D). - F goes in steps of 0.01 and never below 0, because a negative F pushes the lift down. - `%` is the remainder after dividing, so after the last gain the choice wraps round to the first. **Write the final numbers down.** The program loses them when the OpMode stops. ## 6. The tuning recipe Tune in the order kP, kD, kF, then kI only if needed. The steps are in [Add a lift: tune it](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/#4-check-it-then-tune-it). In this program, kP is selected at the start (0.002). A, X and Y switch between targets after each change. ## Run it 1. Put the lift at the bottom. Press ▶ (start on the Driver Hub). Position shows 0. 2. Press X: the lift goes toward MIDDLE. With the starting kP, it may stop short. Now tune it, and watch "Error" and "At target". ## If something goes wrong | Problem | Fix | | --- | --- | | Lift goes the wrong way and hits the end | Press STOP first. Positive power moves the lift down: add `.reversed()` to the motor (Tutorial 02). | | Shakes, overshoots or sags | See the PID table in section 1, or [Add a lift: fix a problem](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/#fix-a-problem). | | Drops when the OpMode stops | This is normal: the motor gets no power after STOP. `.brake()` slows the drop. | ## Try this 1. Set a target between the buttons with the right stick: `target += (int) (-gamepad1.right_stick_y * 20)`. Keep it between 0 and TOP with `MathUtil.clamp`. 2. Show `pid.getLastError()` as a bar of `#` characters, so you can see it shrink. 3. Tune once with an empty lift and once with a game piece on it. Check whether the same gains work. --- **Next:** [Tutorial 08: A lift that cannot hurt itself](https://crossbotics.com/ftc-helper/docs/tutorials/08-safe-lift/) **Look it up:** [control.md: PidController](https://crossbotics.com/ftc-helper/docs/modules/control/#pidcontroller) --- # Tutorial 08: A lift that cannot hurt itself URL: https://crossbotics.com/ftc-helper/docs/tutorials/08-safe-lift/ **You will build:** the lift from Tutorial 07, now with limits it cannot drive past, a bottom switch, and stick control that takes over from the buttons. **You need:** the lift from Tutorial 07 (motor `lift`, positive = up) and its PID gains. A touch sensor at the bottom named `lift_bottom` is best. **Full program:** [`Tut08SafeLift.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut08SafeLift.java) --- ## 1. What can go wrong with a lift - **Driven past the top:** the string snaps, the slide pulls apart, or the robot breaks the 29 in height rule. - **Driven into the bottom:** the motor stalls and gets hot, or the belt skips. - **Encoder drift** (the belt skips, or the robot turned on with the lift up): every height is wrong. `SafeMotor` handles all three in software. **It does not replace hard stops**: a hard stop is a physical block that the lift hits at each end. Rule R105 B says the robot must stay inside its size limits without software. The software stops the motor before it hits the block. The block holds when the software is wrong. ## 2. Wrap the motor ```java DcMotorEx liftMotor = MotorSetup.get(hardwareMap, "lift") .brake().resetEncoder().runWithoutEncoder().done(); SafeMotor lift = new SafeMotor(liftMotor) .setLimits(BOTTOM, MAX) // 0 to 2600 ticks .setSlowZone(250, 0.2) // within 250 ticks of an end, slow down to 20% .setMaxPower(0.9); ``` - **Soft limits** (limits in software, not metal): power that pushes past 0 or 2600 becomes 0. Power AWAY from the limit always works, so the lift never gets "stuck at the top". - **Slow zone:** close to an end, `SafeMotor` lowers the power toward that end, so the lift does not slam. - **Max power:** the most power the motor ever gets. 90% is gentler on the motor and the string. Set MAX a little below the real top. Then the soft limit stops the lift before the hard stop. ## 3. The bottom switch and homing ```java TouchSensor bottom = Hw.tryGet(hardwareMap, TouchSensor.class, "lift_bottom"); if (bottom != null) lift.setLowerSwitch(bottom::isPressed); ``` `bottom::isPressed` is short for the lambda `() -> bottom.isPressed()`. With a lower switch: - The switch always stops downward power, whatever the encoder says. - When the lift presses the switch, `SafeMotor` sets the position to 0 (**homing**). So each time the lift reaches the bottom, it fixes the encoder drift. - **Until the first homing, the lift only goes DOWN, slowly (30%).** `SafeMotor` does not know the position yet, so up is not safe. The driver pushes the lift down once at the start. When the lift is already on the switch, it homes at once. Without a switch, position 0 is wherever the lift was when the robot turned on. So always turn the robot on with the lift at the bottom. ## 4. The pattern: set heights + hand control ```java private Integer target = null; // null = by hand ... .bindPress(Pad.G2, Btn.A, () -> goTo(BOTTOM, pid)) .bindPress(Pad.G2, Btn.Y, () -> goTo(TOP, pid)) .bindPress(Pad.G2, Btn.B, () -> target = null) // stop holding ``` Then, every loop: ```java lift.update(); // FIRST: switches and homing controls.update(gamepad1, gamepad2); double stick = StickShaping.shape(-gamepad2.left_stick_y, 0.1, 1); if (stick != 0 || lift.isWaitingForHoming()) target = null; // the stick takes over if (target == null) { lift.setPower(stick); } else { lift.moveTo(target, pid); } ``` - `target` is an `Integer` (not `int`), so it can be `null`: "no set height, by hand". - **A touch on the stick cancels the set height,** so the driver is always in control. The 0.1 deadband stops a bumped stick from canceling it. - Before homing, the zero is not known, so the program cancels set heights until the lift is down. - B forgets the target. With the stick at rest, the brake holds the lift. - `moveTo(target, pid)` is `pid.calculate` + `setPower`, with the limits applied. The PID gains are yours from Tutorial 07. - **Safety:** `lift.update()` comes first every loop, and **every power for this motor goes through the SafeMotor**. A direct call to `liftMotor.setPower(...)` skips the limits. ## 5. Telemetry that explains itself ```java if (lift.isWaitingForHoming()) telemetry.addLine("Push the lift DOWN to the switch to home it."); TelemetryHelper.value(telemetry, "Asked power", lift.getRequestedPower(), 2); TelemetryHelper.value(telemetry, "Sent power", lift.getAppliedPower(), 2); ``` When "Asked" is 0.5 and "Sent" is 0, a limit stopped the lift. So when the lift does not move, these two lines show why. ## Run it 1. With a switch, start with the lift a little UP. Telemetry asks you to home it. Stick up: nothing. Stick down: the lift goes down slowly and reaches the switch. The position becomes 0. 2. Stick up: the lift moves, then slows near the top and stops at MAX. Stick down: it moves away at once. 3. Press Y: the lift goes to TOP. Touch the stick: that cancels the button target. 4. Hold the stick down at the bottom: "Asked -0.5, Sent 0". ## If something goes wrong | Problem | Fix | | --- | --- | | Only goes down, slowly | The lift is not homed yet. Push it down to the switch. | | Will not go down at all | `SafeMotor` thinks the lift is at 0, or the switch is pressed. Check `At bottom` and the switch wiring. | | Stops early at the top | MAX is too low, or the position drifted. Home again at the bottom. | | Goes past the top | Press STOP. Positive power is not "up" (reverse the motor), or MAX is wrong. | | Hums at the bottom when holding BOTTOM | The F push in the PID does that. It is normal. Or use `target = null` at the bottom. | ## Try this 1. Make B "go to bottom, then let go": when the lift reaches BOTTOM (`pid.atTarget()`), set `target = null`. 2. Add an upper limit switch with `setUpperSwitch(...)`. 3. Let the driver home the lift again on demand: add a button that sets `target = null` and drives down at -0.3 until `lift.isAtLower()`. --- **Next:** [Tutorial 09: Autonomous by hand with AutoDrive](https://crossbotics.com/ftc-helper/docs/tutorials/09-first-auto/) **Look it up:** [safety.md: SafeMotor](https://crossbotics.com/ftc-helper/docs/modules/safety/#safemotor), [control.md: PidController](https://crossbotics.com/ftc-helper/docs/modules/control/#pidcontroller) --- # Tutorial 09: Autonomous by hand with AutoDrive URL: https://crossbotics.com/ftc-helper/docs/tutorials/09-first-auto/ **You will build:** a settings file, a tuner that measures your drivetrain, and an autonomous that drives a square. **You need:** a drivetrain that drives correctly in TeleOp (Tutorial 04 or 05), the IMU, a tape measure and tape. **Full programs:** [`RobotSettings.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/RobotSettings.java), [`Tut09DriveTuner.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut09DriveTuner.java), [`Tut09FirstAuto.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut09FirstAuto.java) --- ## 1. One place for the settings TeleOp and autonomous must use the same motor names, directions and IMU setup. When you write them twice, one day someone changes only one copy. So make one class that every program uses: ```java public final class RobotSettings { public static DriveConfig drive() { DriveConfig c = DriveConfig.mecanum(); // or tank() / tankTwoMotor() c.powerLimit = 0.8; // easier to control while learning return c; } public static AutoDriveConfig auto() { AutoDriveConfig c = new AutoDriveConfig(); c.ticksPerRev = 537.7; // goBILDA 312 RPM motor c.wheelDiameterIn = 3.78; // 96 mm wheels; tuned below c.strafeCorrection = 1.15; // tuned below (mecanum only) c.calibrationConfirmed = false; // change to true after tuning (section 3) return c; } public static IMU imu(HardwareMap hardwareMap) { return ImuSetup.get(hardwareMap, "imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD); } } ``` - `static` means you call the method on the class itself: `RobotSettings.drive()`. Each call makes fresh settings, so one program cannot change another's by mistake. - `ticksPerRev` is how many encoder ticks make one turn of the motor's output shaft. Find it on your motor's product page ("encoder resolution at the output shaft"): goBILDA 312 RPM = 537.7, 435 RPM = 384.5. - Mecanum wheels slip sideways: the robot moves less sideways than the wheels turn. `strafeCorrection` makes up for that. - **Safety:** `calibrationConfirmed` is a safety switch. Autonomous refuses to run while it is false, so an untuned robot does not charge across the field. - The IMU directions must match YOUR hub (Tutorial 04, section 7). Wrong directions give wrong turns. From now on, use this class in your TeleOp too: `new MecanumDrive(hardwareMap, RobotSettings.drive())`. ## 2. How AutoDrive works `AutoDrive` uses the wheel encoders to measure distance and the IMU to measure turns: ```java AutoDrive auto = new AutoDrive(this, RobotSettings.drive(), RobotSettings.auto(), RobotSettings.imu(hardwareMap)); waitForStart(); auto.move(24, 0, 0.6); // 24 inches, direction 0 (forward), up to 60% power auto.turn(-90, 0.5); // turn 90 degrees to the RIGHT (negative = right) ``` Each call **waits until the move is done**, then the next line runs. That is fine in autonomous, and only there. A move also stops by itself when it takes too long (10 s), or when the robot is stuck. Directions for `move` count counterclockwise, like a heading: 0 forward, 90 left, 180 back, -90 right. A standard drive only does 0 and 180. For turns, positive = left, like the IMU ([Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/)). ## 3. Tune it An untuned `AutoDrive` drives the wrong distances, so it does not run until `calibrationConfirmed = true`. The tuner program runs one test and shows the result: ```java while (opModeInInit()) { if (gamepad1.a) test = "forward 48"; if (gamepad1.b) test = "right 48"; ... } ``` - You choose the test with the gamepad during INIT (nothing moves in INIT), then press ▶. - The tuner sets `calibrationConfirmed = true` for itself only, because it is how you check calibration. - Every test runs at half power, so the measurements repeat well. - "Wheel ticks" are the four encoder counts. When they are very different, look for a slipping wheel or a wrong motor setting. The math for each test: - **Distance (A, forward 48):** new `wheelDiameterIn` = old x (real distance / 48). Example: the robot went 50 in with 3.78, so 3.78 x 50/48 = 3.94. Repeat until it is right within half an inch. - **Strafe (B, right 48, mecanum only):** new `strafeCorrection` = old x (48 / real distance). - **Turns (X and Y, 90 left and right):** `turnKp` and `turnKd` are the P and D of the turn (Tutorial 07). When the turn overshoots, raise `turnKd` or lower `turnKp`. When it stops short, raise `turnKp` a little. The library's finders do the same jobs, step by step: the [Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/) for distance and strafe, and the [Move Tuner](https://crossbotics.com/ftc-helper/docs/tuning/10-move-tuner/) for turns. Write every final number in `RobotSettings`. ## 4. The first real autonomous ```java waitForStart(); auto.move(24, 0, 0.6); // forward 24 in auto.turn(-90, 0.5); // right 90 auto.move(24, 0, 0.6); auto.turn(-90, 0.5); auto.move(24, 0, 0.6); auto.turn(-90, 0.5); auto.move(24, 0, 0.6); auto.turnTo(0, 0.5); // face exactly where we started ``` The robot drives a square. With good tuning, it ends where it started. - `turn` is "turn BY this much". `turnTo` is "turn TO this heading" (0 = the direction at the start). `turnTo` fixes small errors that build up from many turns. - Every `AutoDrive` move stops the wheels when it ends, so the program needs no motor stop. ## Run it 1. Put the robot on a field tile corner, facing along a seam. 2. Press INIT, then ▶. The robot drives the square. 3. Measure how far from the start the robot ends. Under 2 inches is good. ## If something goes wrong | Problem | Fix | | --- | --- | | "calibrationConfirmed is false" | This stop is on purpose. Tune, then set it to true in `RobotSettings.auto()`. | | Turns the wrong way or spins forever | The IMU directions do not match the hub (Tutorial 04, section 7), or a motor direction is wrong. | | Stops early: "robot stuck" | Something blocked the robot, or `moveMinPower` is too low to move it. Raise it a little. | | Drifts sideways on long moves | A little drift is normal. Use `turnTo` between moves to fix the heading. | ## Try this 1. Drive a triangle (turns of 120 degrees). 2. With mecanum, drive a square WITHOUT turning: use directions 0, 90, 180, -90. 3. Print the `AutoDrive.Result` of each move on telemetry. Push the robot against a wall in one move, and look for `STALLED`. --- **Next:** [Tutorial 10: Autonomous with mechanisms](https://crossbotics.com/ftc-helper/docs/tutorials/10-auto-with-mechanisms/) **Look it up:** [drive.md: AutoDrive](https://crossbotics.com/ftc-helper/docs/modules/drive/#autodrive), [drive.md: AutoDriveConfig](https://crossbotics.com/ftc-helper/docs/modules/drive/#autodriveconfig) --- # Tutorial 10: Autonomous with mechanisms URL: https://crossbotics.com/ftc-helper/docs/tutorials/10-auto-with-mechanisms/ **You will build:** an autonomous that raises the lift while it drives, with alliance and start delay chosen on the gamepad in INIT. **You need:** a tuned drivetrain (Tutorial 09) and the lift from Tutorial 08. **Full program:** [`Tut10AutoWithLift.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut10AutoWithLift.java) --- ## 1. The lift The lift is the one from Tutorial 08, with the numbers from Tutorial 07: ```java // "lift" = the name in the robot configuration. The encoder starts at 0 here. DcMotorEx liftMotor = MotorSetup.get(hardwareMap, "lift") .brake().resetEncoder().runWithoutEncoder().done(); // Soft limits 0 to 2600 ticks, slow near the ends. The lift also needs a real hard stop. SafeMotor lift = new SafeMotor(liftMotor).setLimits(0, 2600).setSlowZone(250, 0.2); // (1)! PidController liftPid = new PidController(0.004, 0, 0.0002, 0.05).setTolerance(20); // tutorial 07 (2)! ``` 1. 2600 is a bit above `LIFT_UP` (2400). So a wrong target or a bug cannot drive the lift into its top. Near an end, the power goes down to at most 0.2, so the lift does not slam. **Safety:** the lift also needs a physical hard stop ([Tutorial 08](https://crossbotics.com/ftc-helper/docs/tutorials/08-safe-lift/#1-what-can-go-wrong-with-a-lift)). 2. kP, kI, kD, kF and the tolerance in ticks, from Tutorial 07. Start the robot with the lift DOWN: `resetEncoder()` makes the current position 0. ## 2. The problem: moves wait While `auto.move(...)` runs, none of YOUR code runs. A lift PID in your loop gets no updates, and the lift sags or overshoots. ## 3. The loop hook A **hook** is a job you hand to someone else's code, so it runs at the right moment. Give `AutoDrive` a job to run once per loop **inside** every move and turn: ```java auto.setLoopHook(() -> { lift.update(); // (1)! lift.moveTo(liftTarget, liftPid); // (2)! }); ``` 1. First: read the lift's switch and position. 2. Then: PID power toward the target, with the limits applied. Now the lift keeps working during every move. To raise the lift while the robot drives, change the target and then drive: ```java liftTarget = LIFT_UP; // start raising... auto.move(30, 0, 0.6); // ...while driving ``` `liftTarget` is a field, because the hook (a lambda) reads it. Keep the hook quick: no `sleep`, and no loops that wait. ## 4. Choose the plan in INIT Before ▶ (start on the Driver Hub), the drivers make choices. Use a small `ControllerBindings` in an INIT loop: ```java ControllerBindings setup = new ControllerBindings() .bindPress(Pad.G1, Btn.X, () -> red = false) .bindPress(Pad.G1, Btn.B, () -> red = true) .bindPress(Pad.G1, Btn.DPAD_UP, () -> delaySec = Math.min(delaySec + 1, 10)) .bindPress(Pad.G1, Btn.DPAD_DOWN, () -> delaySec = Math.max(delaySec - 1, 0)); while (opModeInInit()) { setup.update(gamepad1, gamepad2); telemetry.addData("Alliance (X blue / B red)", red ? "RED" : "BLUE"); telemetry.addData("Start delay (D-pad)", "%.0f s", delaySec); telemetry.update(); } if (isStopRequested()) return; ``` - `opModeInInit()` is true until ▶ (or STOP). Read buttons in INIT, but never move: that is the library's safety rule. - `Math.min` and `Math.max` keep the delay between 0 and 10 seconds. A delay keeps you out of your partner's way. ## 5. Mirror the route for red and blue The red side of the field is often a mirror image of blue. Write the route once, for blue. Then flip left and right for red: ```java double side = red ? -1 : 1; auto.turn(90 * side, 0.5); // blue: left 90, red: right 90 ``` Mirror sideways moves the same way: `auto.move(12, 90 * side, 0.5)`. Forward and back do not change. Check your game's field first: some fields are rotated, not mirrored. For a rotated field, flip the forward and back parts too. ## 6. React to a stuck move Every move returns how it ended: ```java AutoDrive.Result r = auto.move(30, 0, 0.6); // ...while driving if (r == AutoDrive.Result.STALLED) { auto.move(4, 180, 0.4); // blocked: back off and try once more auto.move(6, 0, 0.4); } ``` `STALLED` means something blocks the robot. To push on wastes time and can burn out the motors. The other results are `DONE`, `TIMED_OUT` and `STOPPED` (the match ended). ## 7. Wait for a mechanism, safely Between moves, the hook does not run. To wait for the lift, keep it working yourself, and always add a time limit: ```java ElapsedTime wait = new ElapsedTime(); while (opModeIsActive() && !liftPid.atTarget() && wait.seconds() < 2.0) { lift.update(); lift.moveTo(liftTarget, liftPid); idle(); } ``` Use three conditions, every time: **the match is still on, the job is not done, the time is not up.** A loop without a time limit can wait forever and waste the whole autonomous. **Do not use `sleep(...)`**, also not for a start delay. While the code sleeps, nothing runs: no telemetry, no mechanism updates. Wait with a loop instead, like the start delay in the program: ```java ElapsedTime delay = new ElapsedTime(); while (opModeIsActive() && delay.seconds() < delaySec) { telemetry.addData("Waiting", "%.1f s", delaySec - delay.seconds()); telemetry.update(); idle(); } ``` ## 8. Clean up and hand over to TeleOp ```java } finally { lift.stop(); PoseStore.save(new FieldPose(0, 0, auto.headingDeg())); } ``` `finally` runs also when the match ends in the middle of a move. A **pose** is the robot's x, y and heading. `PoseStore` keeps the saved pose until TeleOp reads it. Here the program knows only the heading. With odometry, you save x and y too: [Add odometry: TeleOp starts where autonomous ended](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/#teleop-starts-where-autonomous-ended). ## Run it 1. Press INIT. Press B (red), then D-pad up twice (2 s delay). The screen shows your choices. 2. Press ▶. The robot waits 2 s, drives forward while the lift rises, turns RIGHT (red), and drives on. 3. Run it again as blue: the robot turns LEFT. 4. Put a box in the way of the first move: the robot backs off and tries again. ## If something goes wrong | Problem | Fix | | --- | --- | | Lift sags during moves | The program sets no loop hook, or the hook does not call `moveTo`. | | Lift keeps going after the program ends | Put `lift.stop()` in `finally`. | | Choices do not change in INIT | Put `setup.update(gamepad1, gamepad2)` inside the `opModeInInit()` loop. | | Red and blue go the same way | A turn or sideways move does not use `side`. | | Waits forever | A loop that waits has no time limit. Add `&& timer.seconds() < ...`. | ## Try this 1. Add a choice of two routes ("near" and "far") on the D-pad left/right. 2. Lower the lift on the way back without stopping: set `liftTarget = LIFT_DOWN` before the move. 3. When the first move is `STALLED` twice, skip to "park" instead of trying the rest. --- **Next:** [Tutorial 11: Driver assists](https://crossbotics.com/ftc-helper/docs/tutorials/11-driver-assists/) **Look it up:** [drive.md: AutoDrive](https://crossbotics.com/ftc-helper/docs/modules/drive/#autodrive), [safety.md: SafeMotor](https://crossbotics.com/ftc-helper/docs/modules/safety/#safemotor), [util.md: PoseStore](https://crossbotics.com/ftc-helper/docs/modules/util/#posestore) --- # Tutorial 11: Driver assists URL: https://crossbotics.com/ftc-helper/docs/tutorials/11-driver-assists/ **In the five files:** one line in `Controls.java` gives the aim buzz and whole-robot aim ([What the drivers see and feel](https://crossbotics.com/ftc-helper/docs/controls/03-see-and-feel/), [Aim: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#buttons-to-add)). **Build it by hand** to see how an assist works inside: PID on the IMU, a buzz from an error, and a ramp. **You will build:** a mecanum TeleOp where a D-pad press turns the robot to face an exact direction, the gamepad buzzes when it is lined up, and starts are smooth. **You need:** a mecanum robot with the IMU, and `RobotSettings` from Tutorial 09. Do Tutorials 04 and 07 first. A standard drive works the same way with `TankDrive.arcade`. **Full program:** [`Tut11HeadingHold.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut11HeadingHold.java) --- ## 1. Snap to a heading To line up square to a wall by hand takes time. With a snap, the driver presses a D-pad direction, and the robot turns to face exactly that way while the driver keeps driving. This is PID (Tutorial 07) on the heading: ```java PidController headingPid = new PidController(0.015, 0, 0.002) .setAngleMode(true) .setOutputLimits(-0.6, 0.6) .setTolerance(2); ``` Headings wrap around at 180. From 170 to -170 is a 20 degree turn, not 340. `setAngleMode(true)` makes the controller always take the short way. - kP 0.015 is the turn power per degree of error. There is no I. - kD 0.002 slows the turn near the target, so the robot does not swing past. - `setOutputLimits(-0.6, 0.6)` stops a snap from being violent. - Within 2 degrees counts as "pointed right". The D-pad headings are field headings. 0 is the way the robot faced when the heading was last zeroed, and positive is left (counterclockwise). So D-pad LEFT = 90 = face left. BACK resets the heading to 0: press it when the robot faces straight away from you. ## 2. Hand control back to the driver ```java private Double targetHeading = null; // null = driver turns by hand ... .bindPress(Pad.G1, Btn.DPAD_UP, () -> snapTo(0, headingPid)) .bindPress(Pad.G1, Btn.DPAD_LEFT, () -> snapTo(90, headingPid)) ... double turn = StickShaping.shape(gamepad1.right_stick_x, 0.05, 2); if (turn != 0) targetHeading = null; // the driver takes over if (targetHeading != null) { turn = -headingPid.calculate(targetHeading, heading); } drive.driveFieldCentric(forward, strafe, turn, heading); ``` This is the same pattern as the lift in Tutorial 08: a button sets a target, and a touch on the stick cancels it. `targetHeading` is a `Double` (capital D), so it can be `null`. ### Why the minus sign? The IMU and the PID count **counterclockwise** (left = positive). The drive's turn is **clockwise** (right = positive), so it matches the stick. The minus sign flips one into the other ([Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/)). Without it, the robot turns AWAY from the target, faster and faster. ## 3. Feel it The driver watches the robot, not the screen. A buzz says "you are pointed right": ```java AimRumble aimFeel = new AimRumble(gamepad1).setThreshold(3); ... aimFeel.update(Angles.shortestDiff(targetHeading, heading)); ``` Inside 3 degrees, the gamepad buzzes, and it buzzes stronger as the robot gets closer. `Angles.shortestDiff` gives the error between two headings the short way around. Use it every time you need that error. ## 4. Smooth starts A tall robot that goes from 0 to full speed in one loop can tip, and its wheels slip. The "slew rate" is how fast a value may change. A `SlewRateLimiter` lets a value change only that fast: ```java SlewRateLimiter forwardRamp = new SlewRateLimiter(2.5, 6.0); // speed up 2.5/s, slow down 6/s ... double forward = forwardRamp.calculate(StickShaping.shape(-gamepad1.left_stick_y, 0.05, 2)); ``` 2.5 per second means 0 to full in 0.4 s. The robot may slow down faster (6 per second), so it still stops quickly. Use one limiter per value (forward and strafe here). Turning has no limiter, so aiming stays quick. ## Run it 1. Point the robot away from you, or press BACK to reset "forward". Press ▶ (start on the Driver Hub). 2. Turn the robot by hand, then press D-pad up: the robot turns back to face forward, and the gamepad buzzes. 3. Hold the left stick forward and press D-pad left: the robot drives AND turns to face left. 4. Push the right stick during a snap: the snap stops, and you turn by hand. 5. Slam the left stick forward: the robot speeds up smoothly. Let go: it stops quickly. ## If something goes wrong | Problem | Fix | | --- | --- | | Turns away from the target, faster and faster | The minus sign in section 2 is missing. | | Shakes around the target | `kP` is too big, or `kD` is too big. Lower them. | | Stops a few degrees short | Raise `kP` a little. When that small error is good enough, use a bigger tolerance. | | Goes the long way around | `setAngleMode(true)` is missing. | | No buzz | The gamepad has no rumble motors, or the error never gets inside the threshold. | ## Try this 1. Add the right bumper as "snap to the nearest 45 degrees". (Hint: `Math.round(heading / 45) * 45`.) 2. Make the ramp gentler only while the lift is up, because a tall robot tips more easily. 3. Use `PidController.atTarget()` to show a big "LOCKED" line at the top of telemetry. --- **Next:** [Tutorial 12: Organize a whole robot](https://crossbotics.com/ftc-helper/docs/tutorials/12-robot-structure/). **Look it up:** [Control module](https://crossbotics.com/ftc-helper/docs/modules/control/) (`PidController`, `SlewRateLimiter`), [Gamepad module: AimRumble](https://crossbotics.com/ftc-helper/docs/modules/gamepad/#aimrumble). --- # Tutorial 12: Organize a whole robot URL: https://crossbotics.com/ftc-helper/docs/tutorials/12-robot-structure/ **In the five files:** `Robot.java` lists the parts, and the library makes, updates and stops them for you ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). **Build it by hand** to see what that structure does inside: a `Robot` class and one class per mechanism (a "subsystem"), shared by TeleOp and autonomous. **You will build:** a whole robot program (drive, lift, claw) split into small classes, with a TeleOp and an autonomous that share them. **You need:** Tutorials 08-10 done. A drivetrain, a lift (`lift`, optional `lift_bottom`) and a claw servo (`claw`). **Full programs:** the [`robot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/robot) folder: `Robot`, `Lift`, `LiftHeights`, `Claw`, `MainTeleOp`, `MainAuto` (and `RobotSettings` from Tutorial 09). --- ## 1. Why organize? By now one OpMode has the drive, the IMU, the lift with its limits and PID, the claw, the buttons and telemetry. Autonomous needs most of it AGAIN. Copies drift apart: someone fixes the lift limit in TeleOp and forgets autonomous. The fix: **each mechanism gets its own class that knows everything about it.** OpModes only say WHAT to do ("lift to HIGH", "open the claw"), never HOW. ``` robot/ LiftHeights.java the set heights (no hardware: testable, Tutorial 13) Lift.java lift motor, limits, PID, modes Claw.java claw servo and its positions Robot.java makes all the mechanisms, updates them, stops them MainTeleOp.java buttons -> robot actions (short!) MainAuto.java a route -> robot actions (short!) RobotSettings.java drive config, auto tuning, IMU (Tutorial 09) ``` In your TeamCode, put these in a folder `robot` (package `org.firstinspires.ftc.teamcode.robot`). ## 2. The set heights: `LiftHeights` ```java public enum LiftHeights { BOTTOM(0), LOW(800), MIDDLE(1600), HIGH(2400); public final int ticks; public LiftHeights up() { return this == HIGH ? HIGH : values()[ordinal() + 1]; } public LiftHeights down() { return this == BOTTOM ? BOTTOM : values()[ordinal() - 1]; } public static LiftHeights closestTo(int position) { ... } } ``` An **enum** is a fixed list of named values. `LiftHeights.HIGH` is clearer than `2400` all over the code, and the numbers live in ONE place. `up()`/`down()` step through the list. `ordinal()` is a value's place in the list (BOTTOM = 0, LOW = 1, ...), and `values()` is the whole list. The enum uses no hardware, so Tutorial 13 can test it. ## 3. A subsystem: `Lift` The `Lift` class holds everything from Tutorial 08: ```java public class Lift { private final SafeMotor motor; private final PidController pid = ...; private LiftHeights target = null; // null = by hand private double handPower = 0; public Lift(HardwareMap hardwareMap) { ...MotorSetup, SafeMotor, optional switch... } public void goTo(LiftHeights height) { target = height; pid.reset(); } public void stepUp() { ... } public void stepDown() { ... } public void manual(double power) { handPower = power; if (power != 0) target = null; } public void update() { // once every loop motor.update(); if (motor.isWaitingForHoming()) target = null; if (target == null) motor.setPower(handPower); else motor.moveTo(target.ticks, pid); } public boolean isAtTarget() { ... } public void stop() { ... } public void addTelemetry(Telemetry telemetry) { ... } } ``` The real file adds these: - `MAX_TICKS = 2600` is above HIGH (2400) and below the real top, so the lift never runs into its physical stop under power. - The constructor resets the encoder, so turn the robot on with the lift DOWN. Nothing moves in a constructor, so it is safe in INIT. - `update()` runs `moveTo` every loop, also at the target: that holds the lift up against gravity. Before homing (Tutorial 08), the zero is not known, so `update()` cancels a set height. - After hand control, `stepUp()` steps from the set height closest to the lift (`LiftHeights.closestTo`). - `stop()` also forgets the target and the hand power, so the next `update()` does not start the lift again. The pattern for every subsystem: - **Constructor** (the method with the class's name, run by `new Lift(...)`): get and set up the hardware. - **Commands** that only change state (`goTo`, `manual`): quick, safe to call from a button. - **`update()`**: the one place that talks to the motors, once per loop. - **Questions** (`isAtTarget`) and **`addTelemetry`**. - **`stop()`**. `Claw` is the same idea, smaller: `open()`, `close()`, `toggle()`, `isOpen()`. Its servo is `private`, so no other class can send it a wrong position. A servo cannot report where it is, so `Claw` remembers what it last told the servo. ## 4. The whole robot: `Robot` Other classes can read `public final` fields (`robot.lift`), but they can never swap them for another object. ```java public class Robot { public final IMU imu; public final Lift lift; public final Claw claw; public Robot(HardwareMap hardwareMap) { BulkReads.auto(hardwareMap); imu = RobotSettings.imu(hardwareMap); lift = new Lift(hardwareMap); claw = new Claw(hardwareMap); } public void update() { lift.update(); } public void stop() { lift.stop(); } public void addTelemetry(Telemetry telemetry) { lift.addTelemetry(telemetry); claw.addTelemetry(telemetry); } } ``` The drivetrain is NOT in `Robot`: TeleOp drives with `MecanumDrive`, and autonomous with `AutoDrive`. Both read `RobotSettings.drive()`, so they still match. Only the lift needs `update()`, for its PID. ## 5. TeleOp becomes short ```java Robot robot = new Robot(hardwareMap); // the IMU setup makes the way the robot faces NOW heading 0 MecanumDrive drive = new MecanumDrive(hardwareMap, RobotSettings.drive()); ControllerBindings controls = new ControllerBindings() .bindPress(Pad.G1, Btn.BACK, robot.imu::resetYaw) .bindPress(Pad.G2, Btn.DPAD_UP, robot.lift::stepUp) .bindPress(Pad.G2, Btn.DPAD_DOWN, robot.lift::stepDown) .bindPress(Pad.G2, Btn.A, () -> robot.lift.goTo(LiftHeights.BOTTOM)) .bindPress(Pad.G2, Btn.Y, () -> robot.lift.goTo(LiftHeights.HIGH)) .bindPress(Pad.G2, Btn.RB, robot.claw::toggle); ``` The button list IS the driver's control sheet. `robot.lift::stepUp` is short for `() -> robot.lift.stepUp()`. The loop runs `controls.update`, `robot.lift.manual(stick)`, `robot.update()`, the drive and telemetry. ## 6. Autonomous uses the same classes ```java robot = new Robot(hardwareMap); AutoDrive auto = new AutoDrive(this, RobotSettings.drive(), RobotSettings.auto(), robot.imu); auto.setLoopHook(robot::update); // the lift keeps working during every move ... robot.claw.close(); robot.lift.goTo(LiftHeights.HIGH); // rises during the next move (loop hook) auto.move(30, 0, 0.6); waitForLift(2.0); // at most 2 s: a stuck lift cannot use up the auto robot.claw.open(); pause(0.3); // let the piece fall ``` The loop hook runs `robot.update()` again and again during every move. Without it, the lift gets no updates (no PID) while the robot drives. `waitForLift` and `pause` keep calling `robot.update()` while they wait (Tutorial 10), so the lift keeps holding its height. **Do not use `sleep()` while a mechanism must hold position:** `sleep` stops all your code, including the lift's PID. ## 7. Hand-over from autonomous TeleOp sets up the IMU again, and that makes "0" the way the robot faces now. So `MainAuto` saves its heading with `PoseStore.save(...)` in `finally`, and `MainTeleOp`'s `DriverHeading` adds it back. Then field-centric "forward" is right from the start of TeleOp. Start autonomous with the robot facing straight away from the driver ([DriverHeading](https://crossbotics.com/ftc-helper/docs/modules/drive/#driverheading)). ## Run it 1. Copy the `robot` folder and `RobotSettings` into TeamCode (fix the package lines). 2. Run Main Auto: the claw closes, the lift rises while the robot drives, the claw opens, and the lift lowers on the way back. 3. Run Main TeleOp: telemetry shows "Heading: from autonomous". The D-pad steps the lift through LOW, MIDDLE, HIGH. The right bumper toggles the claw. The stick takes over the lift. ## If something goes wrong | Problem | Fix | | --- | --- | | Lift does nothing in TeleOp | The loop does not call `robot.update()`. | | Lift sags during auto moves | `auto.setLoopHook(robot::update)` is missing. | | Lift drops while the claw opens | The code uses `sleep()` instead of `pause()`. | | Two OpModes behave differently | An OpMode sets up something that belongs in `Robot`/`RobotSettings`. Move it there. | ## Try this 1. Add an `Intake` subsystem with `in()`, `out()`, `stop()`. Bind it on gamepad 2. 2. Give `Lift` a `scoreHeightFor(...)` that picks a height from the game situation. 3. Make `Robot.addTelemetry` show only the lines the driver needs. Add a `debug` flag for the rest. --- **Next:** [Tutorial 13: Test your code without a robot](https://crossbotics.com/ftc-helper/docs/tutorials/13-testing/). **Look it up:** [Safety module](https://crossbotics.com/ftc-helper/docs/modules/safety/) (`SafeMotor`), [Control module](https://crossbotics.com/ftc-helper/docs/modules/control/), [Drive module: DriverHeading](https://crossbotics.com/ftc-helper/docs/modules/drive/#driverheading), [Auto module](https://crossbotics.com/ftc-helper/docs/modules/auto/) (`AutoDrive`). --- # Tutorial 13: Test your code without a robot URL: https://crossbotics.com/ftc-helper/docs/tutorials/13-testing/ **In the five files:** simulator tests check your whole robot with no Java to write ([Run all your tests](https://crossbotics.com/ftc-helper/docs/tests/02-run-all-your-tests/)). **Build it by hand** to test one piece of your code in a fraction of a second: small automatic tests (JUnit) that run on a laptop. This page is the only one that teaches them. **You will build:** six small tests that run on a laptop. Most of them test the `LiftHeights` class from Tutorial 12. **You need:** Tutorial 12 done (the `LiftHeights` class). You need no robot. **Full program:** [`LiftHeightsTest.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/test/java/com/crossbotics/ftchelper/examples/tutorials/robot/LiftHeightsTest.java) --- ## 1. Why test without a robot? The whole team shares the robot, and the battery runs out. Many bugs have nothing to do with hardware: a wrong list index, a sign error, a height out of range. A test finds those in one second, on any laptop, every time you change the code. ## 2. What you can test | Testable on a laptop | Needs the robot | | --- | --- | | math, lists, choices (`LiftHeights.up()`) | whether the motor turns | | "with these numbers, the PID gives this power" | whether the PID is tuned well | | button logic (`ControllerBindings` with a pretend `Gamepad`) | whether the driver likes it | | limits (`SoftLimits.limit(...)`) | whether the hard stop is in the right place | **Tip:** keep logic in small classes with no hardware (like `LiftHeights`), so it is easy to test. ## 3. Set up TeamCode for tests (once) Gradle is the tool that builds your code. `build.gradle` is its settings file. 1. Open `TeamCode/build.gradle` and add to `dependencies { ... }`: ```groovy testImplementation 'junit:junit:4.13.2' ``` 2. In tests, Android classes crash unless you tell them to give default values. So add this inside `android { ... }`: ```groovy testOptions { unitTests.returnDefaultValues = true } ``` 3. Make the folder `TeamCode/src/test/java/org/firstinspires/ftc/teamcode/` (next to `main`). The tests live in `test`, so they never go onto the robot. 4. Sync Gradle (the elephant button in Android Studio). ## 4. A first test ```java public class LiftHeightsTest { @Test public void upAndDownStepThroughTheHeights() { assertEquals(LiftHeights.LOW, LiftHeights.BOTTOM.up()); assertEquals(LiftHeights.MIDDLE, LiftHeights.LOW.up()); assertEquals(LiftHeights.MIDDLE, LiftHeights.HIGH.down()); } @Test public void endsDoNotWrapAround() { assertEquals(LiftHeights.HIGH, LiftHeights.HIGH.up()); assertEquals(LiftHeights.BOTTOM, LiftHeights.BOTTOM.down()); } } ``` - Each method marked `@Test` is one test. - `assertEquals(expected, actual)` fails the test when the two are different. `assertTrue(x)` fails it when `x` is false. - Name tests as sentences about what should be true. When one fails, the name tells you what broke. A test that protects a safety rule: ```java @Test public void heightsAreInOrderAndInsideTheLimit() { LiftHeights[] all = LiftHeights.values(); for (int i = 1; i < all.length; i++) assertTrue(all[i].ticks > all[i - 1].ticks); assertTrue(LiftHeights.HIGH.ticks <= Lift.MAX_TICKS); } ``` When someone later sets HIGH above the lift's limit, this test fails before the code reaches the robot. ## 5. Testing with library pieces and your numbers ```java @Test public void ourLiftPidPushesUpWhenBelowTarget() { long[] now = {0}; PidController pid = new PidController(0.004, 0, 0.0002, 0.05, () -> now[0]); assertEquals(1.0, pid.calculate(LiftHeights.HIGH.ticks, 0), 1e-9); } ``` Some library classes use time: `PidController`, `SlewRateLimiter`, `LoopTimer`, the rumble classes. They have a second constructor that takes a **clock**. In a test, you control time: `now[0] += 20_000_000L` moves it 20 ms forward. The test does not wait, and the result is the same every run. The third number in `assertEquals(a, b, 1e-9)` is the allowed difference for decimal numbers. ### A real lesson from writing this test The first version jumped from position 0 to 2400 in 20 ms, and expected only the F push. It got -1.0: the D part saw a huge, sudden "movement" and pushed back hard. The PID was right, and the test was wrong: no real lift moves that fast. Tests teach you how your code behaves. ## 6. Run the tests - **In Android Studio:** open the test file. Click the green arrow next to `class` (all tests) or next to one `@Test`. Green = pass, red = fail with the reason. - **In the Terminal tab:** **Where:** the Terminal tab, in your robot project's folder (the one with `TeamCode` in it). ```bash ./gradlew :TeamCode:testDebugUnitTest ``` Run them before every commit (a version of the code that you save in git) and before every event ([When to run them](https://crossbotics.com/ftc-helper/docs/tests/02-run-all-your-tests/#3-when-to-run-them)). ## 7. Test your robot in five files With the robot in five files (`Robot.java`, `Tunables.java`, ...), the library's **test kit** gives your robot pretend devices: motors whose encoder you set, and servos that remember where your code sent them. The test does INIT, ▶ (start on the Driver Hub) and a loop. Then it checks what each motor got: ```java import com.crossbotics.ftchelper.testkit.PretendDevices; @Test public void liftGoesUpWhenSentHigh() { PretendDevices devices = new PretendDevices(); // a fresh pretend robot Robot robot = new Robot(); robot.setup(devices); // INIT: Tunables.java is checked like on the robot robot.startForTests(); // ▶ (start) robot.lift.goTo("high"); robot.all().update(); // one loop assertTrue(devices.motor("lift").power > 0); // "lift" = the motor's configuration name } @Test public void tunablesNamesAreRight() { // The same name checks as INIT: a misspelled field, a section named after the wrong thing. assertEquals("[]", new Robot().checkTunables().toString()); } ``` **Why:** a typo in `Tunables.java` stops INIT on the robot. With a test, it fails on the laptop first. The test also checks a change to `Robot.java` (a second lift motor, a new interlock rule) in a second. The test cannot see how the real robot moves (gravity): use a [simulator test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/) for that. **Time passing:** for a test of timing ("the arm pushes 0.2 s after fire"), use a pretend clock. The test moves the time by hand. So it does not wait, and a slow laptop cannot make it fail: ```java PretendClock clock = PretendClock.use(); // and PretendClock.stopUsing() in @After robot.intake.in(); clock.addSec(0.25); // 0.25 s later, at once robot.all().update(); ``` A pretend motor does not speed up by itself. For a flywheel, set `fly.velocity = fly.velocityCommand` in each loop, or the flywheel is never ready ([PretendClock](https://crossbotics.com/ftc-helper/docs/modules/testkit/#pretendclock)). A whole robot test: `examples/src/test/.../v2bot/V2botTest.java`. ## Run it 1. Do the setup in section 3. Copy `LiftHeights` and the test (fix the package names). 2. Run the tests: 6 tests pass. 3. Break something on purpose: make `up()` return `this`. Run again: a test fails, and its name says what broke. Fix it. ## If something goes wrong | Problem | Fix | | --- | --- | | `Cannot resolve symbol 'Test'` | `testImplementation 'junit:junit:4.13.2'` is missing, or you did not sync Gradle. | | "Method ... not mocked" | `unitTests.returnDefaultValues = true` is missing. | | Test cannot find your class | The test's `package` line must match the class's package. | ## Try this 1. Test `LiftHeights.closestTo` with a position exactly halfway between two heights. Decide which one should win, write the test, and change the code when it does not match. 2. Test a `ControllerBindings` setup: make `new Gamepad()`, set `gamepad.a = true`, call `update`, and check your counter. The library's `GamepadTest` shows how. 3. Write a test for a mirror function `double side(boolean red)` from Tutorial 10. --- **Next:** [Tutorial 14: Mechanism helpers](https://crossbotics.com/ftc-helper/docs/tutorials/14-mechanisms/). **Look it up:** [Test kit](https://crossbotics.com/ftc-helper/docs/modules/testkit/) (`PretendDevices`, `PretendClock`), [Control module](https://crossbotics.com/ftc-helper/docs/modules/control/) (`PidController` with a clock). --- # Tutorial 14: Mechanism helpers URL: https://crossbotics.com/ftc-helper/docs/tutorials/14-mechanisms/ **In the five files:** one line in `Robot.java` adds a lift, an intake or a wrist. The library builds it from these helpers ([Add to your robot](https://crossbotics.com/ftc-helper/docs/add-to-robot/)). **Build it by hand** to see what the five-files parts are made of, or for a part with no module. **You will build:** one program that runs a lift, a wrist, an intake and a spinner with four helpers: a motor that goes to positions, a motor that spins, a servo with positions, and a continuous servo. A `Subsystems` group runs them all. **You need:** some of these parts: motor `lift` (+ touch `lift_bottom`), servo `wrist`, motor `intake`, continuous servo `spinner`. Delete the lines for parts you do not have. Do Tutorials 03 and 08 first. **Full program:** [`Tut14Mechanisms.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut14Mechanisms.java) --- ## 1. Why helpers? In tutorials 07, 08 and 12 you built a lift by hand: about 100 lines, and every season's robot needs it again. `PositionMotor` does that work in one tested setup chain. ## 2. A lift: `PositionMotor` ```java PositionMotor lift = PositionMotor.create(hardwareMap, "lift") .limits(0, 2600) // never below 0 or above 2600 ticks (1)! .lowerSwitch(hardwareMap, "lift_bottom") // stops at the bottom and sets 0 there (2)! .slowZone(250, 0.2) // gentle near the ends (3)! .pid(0.004, 0, 0.0002, 0.05) // from tutorial 07 (4)! .position("DOWN", 0) .position("LOW", 900) .position("HIGH", 2400); ``` 1. Positions are encoder ticks. The position at INIT counts as 0, so start with the lift DOWN. The limits stop a bug or a wrong number from driving the lift into the end of its travel. 2. When the lift presses the switch, the position resets to 0. That fixes counting errors. Until the lift presses it once, the lift only goes DOWN, slowly. When `lift_bottom` is not in your configuration, the lift runs without a switch, and telemetry shows a warning. 3. Within 250 ticks of an end, the power drops to at most 0.2, so the lift does not slam. FTC robots also need a physical hard stop: [safety.md](https://crossbotics.com/ftc-helper/docs/modules/safety/). 4. kP, kI, kD, kF. The kF of 0.05 is a small steady push up that holds the lift against gravity. The buttons: ```java .bindPress(Pad.G1, Btn.DPAD_UP, lift::stepUp) // next named height up .bindPress(Pad.G1, Btn.Y, () -> lift.goTo("HIGH")) ``` The actions only CHOOSE a target. `all.update()` does the moving, so no button ever makes the robot wait. For hand control, call `lift.manual(stick)` every loop. Push the stick: you drive the lift. Let go: the lift **holds** where you left it (PID), instead of sagging. ## 3. A wrist: `PositionServo` ```java PositionServo wrist = PositionServo.create(hardwareMap, "wrist") .position("STOW", 0.15) .position("LEVEL", 0.50) .position("DROP", 0.85) .maxSpeed(1.5); // at most 1.5 positions per second: no swinging ``` Servo positions go from 0 to 1 ([Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/) finds yours). A sudden snap could fling a game piece. With `maxSpeed(1.5)`, STOW to DROP (0.7) takes about half a second instead. `wrist::next` and `wrist::previous` on the bumpers walk through the positions in the order you added them. A servo does not move until your code tells it to. Here, `wrist.goTo("STOW")` does that right after ▶. ## 4. An intake: `SpinMotor` ```java SpinMotor intake = SpinMotor.create(hardwareMap, "intake").powers(1.0, -0.7); ... .bindHold(Pad.G1, Btn.B, intake::out) .bindRelease(Pad.G1, Btn.B, intake::stop) ``` `powers(1.0, -0.7)`: full power in, gentler out, so the intake does not fire a piece out. `in()`, `out()` and `stop()` are safe to call every loop. While the driver holds B, B's bindings are in charge, so the trigger leaves the intake alone: ```java if (!gamepad1.b) { if (gamepad1.right_trigger > 0.2) intake.in(); else intake.stop(); } ``` A jam is a stuck piece: the intake stops turning while it has power. With `.jamDetection(80, 0.3, 0.4)` (and the encoder cable), the intake backs a jam out by itself. ## 5. A spinner: `SpinServo` ```java SpinServo spinner = SpinServo.create(hardwareMap, "spinner").power(0.8); ``` A continuous-rotation servo spins like a small motor. `power(0.8)` is its speed forward. In the configuration, set the port to **Continuous Rotation Servo**. ## 6. One group for everything ```java Subsystems all = new Subsystems().add(lift, wrist, intake, spinner); ... all.update(); // every loop: PID, limits, slow moves, jam checks all.addTelemetry(t); // each part adds its own lines ... all.stop(); // in finally ``` `all.stop()` stops the lift, the intake and the spinner. A normal servo like the wrist stays where it is. ## Run it 1. Put the robot on a block, with the lift at the bottom. Press ▶. 2. When the lift says "push it DOWN to home it", do that with the stick. 3. Press Y: the lift goes to HIGH. Push the stick: you take over. Let go: the lift holds. 4. Press the bumpers: the wrist walks through its positions slowly. 5. Right trigger: the intake runs in. Hold B: it runs out. ## If something goes wrong | Problem | Fix | | --- | --- | | "No DcMotorEx named ..." | The program names a part you do not have. Delete its lines, and take it out of `all.add(...)`. | | Lift only goes down, slowly | The lift waits for homing. Push it to the switch. | | Lift goes the wrong way | Add `.reversed()` right after `create(...)`. | | Wrist swings too fast / too slow | Change `maxSpeed`. | | Spinner does not spin | The configuration says normal Servo for the port. Set it to Continuous Rotation Servo. | ## Try this 1. Add `.tunable("Lift")` at the end of the lift chain and tune it live (Tutorial 15). 2. Make the wrist go to "DROP" automatically when the lift reaches HIGH (`if (lift.isAt("HIGH"))`). 3. Use `PositionMotor` with `.units(...)` for an arm in degrees. --- **Next:** [Tutorial 15: Telemetry, profiles and tuning](https://crossbotics.com/ftc-helper/docs/tutorials/15-telemetry-profiles-tuning/). **Look it up:** [Mechanism module](https://crossbotics.com/ftc-helper/docs/modules/mechanism/) (`PositionMotor`, `SpinMotor`, `PositionServo`, `SpinServo`, `Subsystems`), [Safety module](https://crossbotics.com/ftc-helper/docs/modules/safety/). --- # Tutorial 15: Telemetry, profiles and tuning URL: https://crossbotics.com/ftc-helper/docs/tutorials/15-telemetry-profiles-tuning/ **In the five files:** the screen, the profile, the tuning menu and the match buzz are ready with no code ([What the drivers see and feel](https://crossbotics.com/ftc-helper/docs/controls/03-see-and-feel/), [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/)). **Build it by hand** to see how each one works inside, or to add them to a program without the five files. **You will build:** a lift program with a hideable debug screen, a practice/competition switch, a tuning menu and a match timer. **You need:** a motor `lift` (tutorial 08). Do Tutorial 14 first. **Full program:** [`Tut15TelemetryTuning.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut15TelemetryTuning.java) --- ## 1. Two kinds of telemetry reader In a match, the **driver** glances at the screen and needs modes, targets, "READY". The **programmer** at the bench needs powers, errors, raw sensor values. When the screen shows both, the driver's lines get lost. `RobotTelemetry` keeps them apart: ```java RobotTelemetry t = new RobotTelemetry(telemetry); t.line("Time", timer.format()); // standard: always t.debug("Loop", "%.0f Hz", loopHz); // debug: only when debug is on t.warn("Final 20 seconds!"); // always, at the TOP t.update(); // once per loop ``` Debug starts ON in the PRACTICE profile and OFF in COMPETITION. Here, BACK toggles it (`.bindPress(Pad.G1, Btn.BACK, t::toggleDebug)`). Every mechanism helper's `addTelemetry` already splits its lines the same way. ## 2. Profiles A **profile** is a setting the whole robot reads: PRACTICE (at the bench) or COMPETITION (at an event). ```java InitMenu menu = new InitMenu(gamepad1).profile(); // a "Profile" line in INIT ... lift.maxPower(Math.min(LIFT_MAX_POWER.get(), Profile.pick(0.5, 1.0))); ``` `Profile.pick(practice, competition)` gives one value or the other. `Math.min` takes the smaller of the two, so the lift's top power is never more than the profile allows, whatever the tuned value is. Use the profile for comfort (speeds, extra screens), never to turn safety off ([Profiles](https://crossbotics.com/ftc-helper/docs/guides/profiles/)). ## 3. Live tuning A `Tunable` is a number you can change from the gamepad while the program runs, without rebuilding. ```java static final Tunable LIFT_MAX_POWER = Tunable.number("Lift/maxPower", 0.8, 0.05).range(0.1, 1.0); // (1)! ... PositionMotor lift = ... .tunable("Lift"); // its PID gains and positions too TuningMenu tuning = new TuningMenu(gamepad1); // will not open in COMPETITION (2)! ControllerBindings menuKey = new ControllerBindings().bindPress(Pad.G1, Btn.GUIDE, tuning::toggle); ControllerBindings driver = new ControllerBindings().bindPress(Pad.G1, Btn.BACK, t::toggleDebug); ControllerBindings operator = new ControllerBindings() .bindPress(Pad.G2, Btn.A, () -> lift.goTo("DOWN")) .bindPress(Pad.G2, Btn.Y, () -> lift.goTo("HIGH")); ... menuKey.update(gamepad1, gamepad2); operator.update(gamepad1, gamepad2); tuning.update(); if (!tuning.isOpen()) driver.update(gamepad1, gamepad2); // gamepad 1 belongs to the menu while it is open (3)! ``` 1. "Lift/maxPower" is its name in the menu (group "Lift"). 0.8 is the code value, and 0.05 is one D-pad step. `range(0.1, 1.0)` stops anyone from tuning the lift to full reverse by mistake. 2. The menu stays closed in COMPETITION, so a driver cannot change numbers by accident at an event. 3. When the menu closes, the real program calls `driver.ignoreHeldButtons(...)`, so a button still held from the menu does not fire. **Why three button lists:** the menu uses gamepad 1's D-pad, bumpers, A, B, X and Y. If the driver's gamepad-1 buttons kept working, Y for "reset all" would also run whatever Y does for the robot. The lift buttons are on gamepad 2, so a second person can test each change while you tune. Read the value **every loop** (`LIFT_MAX_POWER.get()`), so that a change acts at once. The menu's buttons, and how to copy a number back into the code: [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/). ## 4. The match timer ```java MatchTimer timer = MatchTimer.teleOp().rumbleAt(20, gamepad1); ... timer.start(); // right after ▶ (start) timer.update(); // every loop: runs the cues t.line("Time", timer.format()); ``` Drivers often cannot look up, so a buzz at a set time helps them. In 2026-27 the field signals 1:00 (FLOWER ownership unlocks) and 0:20 (final 20 seconds). ## 5. The INIT warning ```java if (Tunable.countChanged() > 0) t.warn(Tunable.countChanged() + " tuned value(s) differ from the code"); ``` Saved tuning values come back after a restart. This warning stops the team from forgetting them at an event. `EasyAuto` shows it for you. ## Run it 1. In INIT, set Profile to PRACTICE with the D-pad. Press ▶ (start on the Driver Hub). 2. The screen shows the debug lines (Loop, Profile, lift power). BACK hides them. 3. Press GUIDE to open the tuning menu. Change `Lift/maxPower` to 0.3: gamepad 2 A/Y now move the lift slowly. Gamepad 1 A saves. 4. Stop and run again: the INIT screen warns "1 tuned value(s) differ from the code". 5. Open the menu and press Y: the values go back to the code values. The next time, the warning is gone. 6. Set Profile to COMPETITION: GUIDE does nothing, and debug starts off. ## If something goes wrong | Problem | Fix | | --- | --- | | Menu does not open | The profile is COMPETITION. That block is on purpose. | | A change has no effect | The code reads the value once in INIT. Read it every loop. | | Driving while tuning | Check `tuning.isOpen()`, and ignore gamepad1's sticks while the menu is open. | ## Try this 1. Make the D-pad slow-mode speed a `Tunable`, and find the speed drivers like best. 2. Use `setMinIntervalMs(100)`. Compare the loop speed (debug "Loop") with it and without it. 3. Add a 1:00 cue that shows a warning line for 3 seconds. --- **Next:** [Tutorial 16: Easy autonomous](https://crossbotics.com/ftc-helper/docs/tutorials/16-easy-autos/). **Look it up:** [Telemetry module](https://crossbotics.com/ftc-helper/docs/modules/telemetry/), [Core module: Profile](https://crossbotics.com/ftc-helper/docs/modules/core/#profile), [Tuning module](https://crossbotics.com/ftc-helper/docs/modules/tuning/), [Match module: MatchTimer](https://crossbotics.com/ftc-helper/docs/modules/match/#matchtimer). --- # Tutorial 16: Easy autonomous URL: https://crossbotics.com/ftc-helper/docs/tutorials/16-easy-autos/ **You will build:** an autonomous written as a list of named steps: grab, drive, lift, drop, park. **You need:** a tuned drivetrain (tutorial 09: `RobotSettings` with `calibrationConfirmed = true`), a motor `lift` and a servo `claw`. **Full program:** [`Tut16EasyAuto.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut16EasyAuto.java) --- ## 1. Compare with tutorial 10 Tutorial 10's autonomous had an INIT menu, mirroring by hand (`side`), a loop hook, waits with time limits, `finally` cleanup and a pose hand-off. Every autonomous needs them, and they are the same every time. `EasyAuto` does all of it. You write only what is special about THIS autonomous. ## 2. Tell it about the robot `extends EasyAuto` means your class starts with everything `EasyAuto` already does. `EasyAuto` is itself a `LinearOpMode`. There is no `runOpMode()` and no loop: you only fill in the parts it asks for. ```java // preselectTeleOp = the TeleOp's exact name: the Driver Station gets it ready after autonomous. @Autonomous(name = "Tutorial 16: Easy Auto", group = "Tutorials", preselectTeleOp = "Tutorial 20: Easy TeleOp") // (1)! ``` 1. When autonomous ends, the Driver Station selects this TeleOp, so the drivers only press INIT. The name must match the TeleOp's name exactly. That TeleOp must also not be `@Disabled`. ```java public class Tut16EasyAuto extends EasyAuto { private PositionMotor lift; private PositionServo claw; // drive, autonomous tuning and IMU, all from RobotSettings: the same as TeleOp (tutorial 20) @Override protected RobotConfig robotConfig() { return RobotSettings.config(); } @Override protected Subsystems createSubsystems() { lift = PositionMotor.create(hardwareMap, "lift")...; claw = PositionServo.create(hardwareMap, "claw")...; return new Subsystems().add(lift, claw); } ``` `@Override` means "I am filling in a method `EasyAuto` asks for". `RobotSettings.config()` hands over the settings from tutorial 09 as one [`RobotConfig`](https://crossbotics.com/ftc-helper/docs/modules/core/#robotconfig). Tutorial 20's TeleOp uses the same one. `EasyAuto` updates the mechanisms you return every loop, during every step. So a lift keeps holding while the robot drives. `EasyAuto` also stops them all at the end, even after an error. Start the robot with the lift DOWN: that position counts as 0. A servo cannot say where it is. So the claw's `travelTime(0.3)` tells a step how long a full move takes, and the step knows when the claw should have finished. ## 3. INIT: placement and choices ```java @Override protected String startPosition() { return "Back wall, touching the left edge of the 2nd tile, facing out"; } @Override protected void addChoices(InitMenu menu) { menu.choice("Route", "Score", "Park only"); } @Override protected double parkReserveSec() { return 4; } ``` The distances only work from one exact spot, so the INIT screen shows the placement. It also shows the menu (alliance, delay, Route) and warnings. `parkReserveSec()` keeps the last 4 seconds for parking. ## 4. The steps ```java @Override protected void buildRoutine(AutoRoutine r) { r.step("Grab", claw.goToStep("CLOSED")) .move("Off the wall", 4, 0, 0.4); if (choice("Route").equals("Score")) { r.step("Lift starts up", lift.startStep("HIGH")) .move("To the goal", 24, 0, 0.6) .turn("Face the goal", 45, 0.5) .waitUntil("Lift is up", lift::isAtTarget, 2.0) .step("Drop", claw.goToStep("OPEN")) .waitFor("Let it fall", 0.3) .step("Lift down", lift.startStep("DOWN")) .turnTo("Square up", 0, 0.5); } r.thenPark() .right("Park", 20, 0.7); } ``` Read it out loud: it IS the plan. The labels show on the Driver Station during the run and in the report. - **`startStep` vs `goToStep`:** `startStep` starts the lift and goes on at once, so the lift rises while the robot drives. `goToStep` waits until the claw should be closed. - **Directions:** `move(name, inches, direction, power)`: 0 = forward, 90 = left, -90 = right. Every angle counts counterclockwise, so positive turn degrees = left. - **`waitUntil` has a time limit** (2 s). `lift::isAtTarget` is short for `() -> lift.isAtTarget()`. When the lift never gets there, the routine goes on, and the report says "timed out". - **Mirroring:** the routine is written for BLUE. On RED, `EasyAuto` flips turns and left/right moves. - **Park:** everything before `thenPark()` stops when 4 s are left. Park always runs. How each of these works, with examples: [Put steps together](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/). Every step: [Steps](https://crossbotics.com/ftc-helper/docs/reference/steps/). ## Run it 1. In INIT, read the placement line. Choose BLUE, Route = Score. Press ▶ (start on the Driver Hub). 2. The screen shows each step and the time left. At the end, check that every step in the report says "done". 3. Run as RED: the robot turns the other way and parks to the left. Then try "Park only". The first run on the real robot: [Put steps together](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#the-first-run-on-the-robot). ## If something goes wrong | Problem | Fix | | --- | --- | | "AUTONOMOUS IS OFF: the drive is not tuned yet" in INIT | Tune with tutorial 09, then set `calibrationConfirmed` true in `RobotSettings.auto()`. | | Lift sags while driving | The lift is not in `createSubsystems()`. | | A step says STALLED | Something was in the way, or the power is too low to move the robot. | | RED does something strange | A step uses a number that must not be mirrored. Use `run(...)` or `alliance()`. | ## Try this 1. Add a choice "Pieces: 1/2" and a second scoring trip for 2. 2. Use `rememberHeading` before scoring and `returnToHeading` after. 3. Override `maxStartDelaySec()` to return 25, and set a 25 s start delay. The robot still parks. 4. Make a second autonomous class with a different route. Share the robot setup through a base class (like the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/)'s `StarterAuto`). --- **Next:** [Tutorial 17: Launcher](https://crossbotics.com/ftc-helper/docs/tutorials/17-launcher/) **Look it up:** [auto.md](https://crossbotics.com/ftc-helper/docs/modules/auto/) --- # Tutorial 17: Launcher URL: https://crossbotics.com/ftc-helper/docs/tutorials/17-launcher/ **You will build:** a shooter that spins a flywheel, sets the hood angle from the distance, and feeds a piece only when everything is ready. **You need:** motor `flywheel` (with its encoder cable), servo `hood`, motor `feeder`. Wear safety glasses: a flywheel throws things. **Full program:** [`Tut17Launcher.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut17Launcher.java) --- ## 1. How a flywheel shot works A spinning wheel grabs the game piece and throws it. Two things decide where the piece lands: the wheel's **speed** (RPM: turns per minute) and the **angle** the piece leaves at (the hood). Both depend on distance. One rule matters more than any other: **never feed a piece into a wheel that is not up to speed.** Otherwise the piece falls short. ## 2. The flywheel ```java Flywheel flywheel = Flywheel.create(hardwareMap, "flywheel") .countsPerRev(28) // encoder counts per ONE flywheel turn .maxRpm(6000) // the motor's top speed .startingGains() // the hub's speed control (a start) .tolerance(75) // "at speed" = within 75 rpm... .settleTime(0.15); // ...for 0.15 s ``` The hub holds the speed itself with four gains: P, I, D and F (like Tutorial 07). `startingGains()` calculates them from `maxRpm` and `countsPerRev` with REV's formula. The [Flywheel Finder](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/) measures better gains for `.pidf(p, i, d, f)`. "Ready" needs the speed to STAY in the band for 0.15 s. So one lucky reading during spin-up does not count. **countsPerRev:** a bare goBILDA/REV motor encoder gives 28 counts per motor turn. - **Flywheel turns at the motor's speed:** 28. - **Geared:** multiply 28 by the motor turns per flywheel turn. - **Encoder on the flywheel shaft** (plugged into this motor's encoder port): that encoder's own counts per turn. **Check the reading:** run at 3000 rpm. Compare with a tachometer (a tool that measures turning speed), or count turns in a slow-motion video. When the two do not match, countsPerRev is wrong. ## 3. The hood and the feeder ```java PositionServo hood = PositionServo.create(hardwareMap, "hood") .degrees(0.10, 0, 0.90, 25) // measured: raw 0.10 = 0 deg, raw 0.90 = 25 deg (1)! .travelTime(0.4); // (2)! MotorFeeder feeder = MotorFeeder.create(hardwareMap, "feeder").power(1.0).feedTime(0.25); // (3)! ``` 1. The hood works in degrees: two measured points and a straight line in between. 2. The servo needs about 0.4 s for a full move. A servo cannot report where it is. So the launcher uses this number to know when the hood has arrived. 3. Full power (1.0) for 0.25 seconds pushes one piece into the flywheel. Any part that goes to an angle can be the hood (an [`AngleDevice`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#angledevice)). To measure the two points: [Hood Finder](https://crossbotics.com/ftc-helper/docs/tuning/04-hood-finder/). ## 4. Fill the shot table ```java ShotTable table = new ShotTable() .add(24, 2600, 6) .add(48, 3100, 14) .add(72, 3700, 21); ``` Each row is a distance (in), an rpm and a hood angle (degrees). Between the rows, the table draws straight lines. Outside them, it uses the nearest end, so it never guesses past what you tested. To find the numbers by hand with this program: 1. Press X on gamepad 1: **manual rpm** mode. D-pad left/right = rpm -/+ 100. 2. Put the robot 24 in from the target. Measure with a tape, to the same edge of the robot every time. 3. Find the rpm and hood angle where 5 shots in a row score. Write them down. 4. Repeat at 3-5 distances, across the area you will shoot from. The **Shot Tuner** does the same and prints the `new ShotTable()` lines: [Shot Tuner](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/). Different game pieces (2026-27: POLLEN and NECTAR) may need their own tables. ## 5. The launcher ```java Launcher launcher = new Launcher(flywheel, feeder) .hood(hood) .table(table) .shotInterval(0.3) .readyTimeout(2.5); ... launcher.setDistance(distanceIn); // every loop: rpm + hood from the table launcher.update(); ``` ```java .bindPress(Pad.G2, Btn.A, launcher::spinUp) .bindPress(Pad.G2, Btn.RB, () -> launcher.shoot(1)) .bindPress(Pad.G2, Btn.LB, () -> launcher.shoot(3)) .bindPress(Pad.G2, Btn.B, launcher::idle) ``` `shoot()` does not wait, so the robot keeps driving. `launcher.update()` feeds each piece when everything is ready. `shotInterval(0.3)` gives the flywheel 0.3 s to get back to speed between pieces. `shoot(3)` does these steps: 1. Spin up, when the flywheel is not spinning yet. 2. Wait until the flywheel is ready AND the hood has arrived (AND any `requireReady` checks, like an aimed turret). 3. Feed one piece. 4. Wait `shotInterval`, then repeat. When it is not ready within `readyTimeout`, it gives up and says why: "gave up: flywheel". ## Run it 1. Put on safety glasses. Start with no game piece. Press ▶ (start on the Driver Hub). 2. Press A: telemetry shows about "2850 / 2850 rpm READY" (the program starts at 36 in). 3. Press RB without a piece: the feeder runs once. LB: three times, 0.3 s apart. 4. With pieces, D-pad up/down changes the distance, and the hood moves. Shoot. 5. Stop the OpMode and unplug the flywheel's encoder cable. Run again and `shoot(1)`. The flywheel can never read "ready", so the launcher waits, then shows "gave up: flywheel". That is the safety rule at work. Plug the cable back in. ## If something goes wrong | Problem | Fix | | --- | --- | | Never READY | countsPerRev is wrong (the speed reads wrong), or the F gain is too low (the wheel never reaches the speed). | | Speed overshoots then settles slowly | Lower P. Tune F first, so the speed gets close by itself. | | Shots fall short when shooting fast | `shotInterval` is too short: the wheel has not recovered. | | Hood never "arrives" | `travelTime` is too long. Measure it. | | "gave up: hood" | The hood's `travelTime` is longer than `readyTimeout`. | ## Try this 1. Add `.requireReady("Driver", () -> gamepad2.right_trigger > 0.5)`: then the launcher shoots only while the driver holds the trigger. 2. Add `.idleRpm(1500)`: a slow idle makes spin-up faster. Measure the difference. 3. Add a second table for another game piece, and switch tables with a button. --- **Next:** [Tutorial 18: Vision aiming](https://crossbotics.com/ftc-helper/docs/tutorials/18-vision-aim/) **Look it up:** [launcher.md](https://crossbotics.com/ftc-helper/docs/modules/launcher/) --- # Tutorial 18: Vision aiming (webcam or Limelight 3A) URL: https://crossbotics.com/ftc-helper/docs/tutorials/18-vision-aim/ **You will build:** a drive program that turns the robot toward an AprilTag (a printed square code on the field) while the driver holds a button. **You need:** the drivetrain and `RobotSettings` (tutorial 09), and a webcam named `Webcam 1` or a Limelight named `limelight`. A Limelight needs an AprilTag pipeline (a set of camera settings you save on the Limelight by number), set up on its web page. You also need an AprilTag to point at. **Full program:** [`Tut18VisionAim.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut18VisionAim.java) --- ## 1. What the camera tells you
flowchart LR
    C["camera picture"] --> O["TargetObservation"]
    O --> B["bearingDeg: how far to turn<br/>+ = target is LEFT"]
    O --> D["distanceIn: how far away<br/>NaN if unknown"]
    O --> T["timeNanos: when the picture was taken"]
`NaN` means "not a number": the camera could not tell the distance. **Bearing** is the angle between "straight ahead" and the target. Positive = the target is to the LEFT (counterclockwise, like the IMU). The Limelight reports the opposite sign. The library flips it for you, so both cameras agree. ## 2. One interface, two cameras An **interface** is a list of methods that several classes promise to have. `TargetSource` is one: both camera classes have its methods, so your code can use either. ```java TargetSource camera = menu.get("Camera").equals("Limelight") ? LimelightTags.create(hardwareMap, "limelight").pipeline(0) // (1)! : WebcamTags.create(hardwareMap, "Webcam 1").resolution(640, 480); // (2)! camera.start(); ``` 1. Pipeline 0 is a setup saved on the Limelight itself (its web page). 2. 640 x 480 pixels is a good start. A higher resolution sees tags farther away, but runs slower. The program must know WHICH camera to start. So the driver chooses the camera in an INIT menu, and the camera starts only after A. `a ? b : c` is a short if/else: when the menu says Limelight, make a Limelight, otherwise a webcam. After this line, the program works the same with either camera: `camera.update()`, `camera.target("RED SCORING")`, `camera.status()`. **A third kind: the HuskyLens.** It has the same methods, with one difference you must handle. It says the number you TAUGHT it on its screen. List each one with the tag's real number: ```java TargetSource camera = HuskyLensCamera.create(hardwareMap, "huskylens") .tag(1, 34).tag(2, 35); // (1)! ``` 1. The first tag you taught is number 1. Its AprilTag number is 34. Now `camera.target(34)` works. This tutorial's program offers only the other two cameras. The HuskyLens's limits, and how to teach it: [the HuskyLens section](https://crossbotics.com/ftc-helper/docs/modules/vision/#huskylenscamera). The webcam needs 1-2 s to start, so start it in INIT. The INIT loop shows `camera.status()` and how many tags the camera sees. Check them before ▶ (start on the Driver Hub). ## 3. Aim the drivetrain `AimController` is a small PID for aiming (Tutorial 07). kP 0.02 is the turn power per degree off. kD 0.003 eases off as the robot closes in, so it does not swing past the tag. Within the `deadband` (1.5 degrees), the power is 0, so the robot does not twitch. `maxPower(0.5)` caps the turn power. ```java AimController aim = new AimController(0.02, 0.003).deadband(1.5).maxPower(0.5).maxAgeMs(150); ... if (gamepad1.right_bumper) { turn = aim.turnPower(target); // same sign as the drive's turn (clockwise +) } else { aim.reset(); // the next aim starts fresh } drive.drive(forward, strafe, turn); ``` While the driver holds RB, the robot turns toward the tag, and the driver keeps control of driving. `aim.reset()` forgets the old aim, so the next aim does not start with a kick from an old picture. `target` is `null` when the camera sees nothing right now. Always check for `null` before you use a target. Otherwise the program crashes. **Safety built in:** `turnPower` returns **0** when there is no target, when the picture is older than 150 ms, or when there is no bearing. The robot never turns toward a tag it cannot see NOW. Without this rule, a robot keeps spinning toward where a tag WAS. `turnPower` already uses the drive's sign (clockwise +), so you need no minus sign. Bearings are counterclockwise +. `ccwPower` gives that sign when you need it. See [Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/). ## 4. Feel it ```java AimRumble feel = new AimRumble(gamepad1).setThreshold(3); feel.update(target.bearingDeg); // buzzes inside 3 degrees, stronger when closer ``` ## 5. With a turret instead ```java turret.aimAtTarget(camera.target("RED SCORING"), true); // true = the camera turns with the turret ``` `aimAtTarget` uses a picture only when it is fresh, and each picture only ONCE. A turn "by the bearing" with the same old picture again and again would push the turret further each loop. With no fresh target, the turret holds where it is. `launcher.setDistance(target.distanceIn)` picks the shot from the table (tutorial 17). Check `target.hasDistance()` first. The five-files modules add more on top: whole-robot aim mode, a turret that follows the camera, and aim from odometry when the camera loses the goal. See [Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/#when-the-camera-loses-the-goal-the-odometry) and [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/). ## 2026-27 notes - BIOBUZZ has 4 tag groups, one under each CELL: "RED SCORING", "RED AUDIENCE", "BLUE AUDIENCE", "BLUE SCORING". `camera.target("RED SCORING")` works with either camera. - A robot can score only in the CELL that is up. `TagGroup.goalTarget(camera, "RED SCORING")` gives the red HIVE's up CELL, or null when only the down CELL is in view. - The cells move, so the tags are good for aiming, but not for working out where the robot is. The aiming points, single tags with a webcam, and the rest: [vision.md](https://crossbotics.com/ftc-helper/docs/modules/vision/#taggroup). ## Run it 1. In INIT, choose the camera and the target with the D-pad, then press A. Wait for "STREAMING" (webcam) or "pipeline 0" (Limelight), and for "Targets seen: 1" or more. 2. Press ▶. Point the robot so the tag is off to the left. Hold RB: the robot turns left until it is aimed. The gamepad buzzes, and the screen says "Aimed: true". 3. Cover the camera while you hold RB: the robot stops turning (no target = 0 power). ## If something goes wrong | Problem | Fix | | --- | --- | | Webcam "OPENING..." forever | Check the USB cable and the hub port. The configuration name must match. | | Limelight "not connected" | Check the Ethernet/USB cable and its name in the configuration. Restart the robot. | | Targets seen 0 | On a Limelight, the pipeline is not AprilTag. Or check the tag family. When the tag is too far, use a higher resolution or decimation 1. | | Turns the wrong way | Someone added a minus sign in front of `aim.turnPower(...)`. Remove it. | | Shakes around the tag | Lower kP or raise the deadband. | | Distance NaN | Webcam: the tag is not in the SDK's library. Limelight: the pipeline has no 3D pose (set the tag size). | Camera light settings: [Camera lighting](https://crossbotics.com/ftc-helper/docs/tuning/11-camera-lighting/). ## Try this 1. Aim at the nearest tag: pick the observation with the smallest `distanceIn`. 2. Show "LOCKED" in big letters at the top when `aim.isAimed()`. 3. Add `offset(...)` when the camera is not centered on the shooter. The [Aim Tuner](https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/) finds the number. --- **Next:** [Check the hardware (tutorial 19)](https://crossbotics.com/ftc-helper/docs/tutorials/19-testing-procedures/) **Look it up:** [vision.md](https://crossbotics.com/ftc-helper/docs/modules/vision/) --- # Check the hardware (tutorial 19) URL: https://crossbotics.com/ftc-helper/docs/tutorials/19-testing-procedures/ **You will build:** a 3-line OpMode. With it, you test every motor, servo and sensor on the robot by hand. **You need:** any robot. **Full program:** [`Tut19HardwareCheck.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut19HardwareCheck.java) (only 3 lines) --- ## 1. The 3-line OpMode The OpMode itself is 3 lines. With the lines every Java file needs, the whole file is below. Make a new Java file `HardwareCheck.java` in your `teamcode` folder ([how to make a file](https://crossbotics.com/ftc-helper/docs/start-from-zero/#make-a-new-file-or-folder)). Replace everything in it with: ```java package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.crossbotics.ftchelper.testing.HardwareCheckOpMode; @TeleOp(name = "Hardware Check", group = "Tests") public class HardwareCheck extends HardwareCheckOpMode { } ``` - **File name:** `HardwareCheck.java`, the same as the class name after `public class`. - **The `package` line** says the file is in the `teamcode` folder. - **The two `import` lines** say where `TeleOp` (from the FTC SDK) and `HardwareCheckOpMode` (from this library) are. **Why:** without them, the build says `cannot find symbol`. - **No `@Disabled` line:** the Driver Station lists the OpMode. `extends` means "is a kind of": this OpMode is a `HardwareCheckOpMode`, so it does everything that class does. The library wrote the OpMode, and you only give it a name. The name in `@TeleOp(name = ...)` can be anything. The tutorial's own copy is "Tutorial 19: Hardware Check". ## 2. Use it Put the robot on a block, so the wheels are off the ground. Run the OpMode. It lists every device in the active configuration, and the battery voltage. - **D-pad up/down**: choose a device. When you change the device, the last motor stops. - **Motor**: right stick = power (50% max; hold RB for 100%). **Stick up = positive power.** The SDK reads a stick pushed up as a negative number. The Hardware Check flips it for you, like the library's driving. A = zero the encoder. **On a lift or an arm:** no limits apply here, and RB gives full power. Use short, gentle taps. Know where its hard stop (the end of its travel) is, and keep hands clear. - **Servo**: a servo cannot tell where it is. So first choose a **start point** near where the servo sits now: D-pad right/left = +/- 0.01, bumpers +/- 0.1, X = 0.5. Nothing moves yet. Keep hands clear, then press A: the servo moves to the start point. After that, the same buttons move it. - **Sensors**: the screen shows live values. What to check on each device, and the fix when it is wrong: [Hardware Check](https://crossbotics.com/ftc-helper/docs/tests/03-checks-before-practice-and-matches/#3-hardware-check-after-a-wiring-or-configuration-change). ## 3. The checks, in order The fixed order (laptop, Hardware Check, mechanisms, floor, autonomous, event) and the printable checklists: [Checks before practice and matches](https://crossbotics.com/ftc-helper/docs/tests/03-checks-before-practice-and-matches/). ## Try it in the simulator **Where:** the Terminal tab, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:fromRobot -PteamCode=none -ProbotClass=com.crossbotics.ftchelper.examples.lessonbot.Robot -Pout=build/lessonbot.properties ./gradlew :sim:run -PteamCode=none -Probot=build/lessonbot.properties ``` Open http://localhost:8780 and choose "Tutorial 19: Hardware Check". Pick `lift` with the D-pad, and push gamepad 1's right stick up: the lift rises and its count goes up. The simulator builds its robot from your code, so it cannot find a wrong wire: only the real robot can. More: [Simulator](https://crossbotics.com/ftc-helper/docs/simulator/). ## Try this 1. Make your own OpMode that runs each drive motor forward for 1 second in turn, and shows its encoder change. 2. Write a test (tutorial 13) for something that once went wrong on your robot. ## After this Two more tutorials build the TeleOp and the finders by hand. When you build something new for the library, read [Extending the library](https://crossbotics.com/ftc-helper/docs/guides/extending/). --- **Next:** [Tutorial 20: Easy TeleOp](https://crossbotics.com/ftc-helper/docs/tutorials/20-easy-teleop/) **Look it up:** [testing.md](https://crossbotics.com/ftc-helper/docs/modules/testing/) --- # Tutorial 20: Easy TeleOp URL: https://crossbotics.com/ftc-helper/docs/tutorials/20-easy-teleop/ **You will build:** a full TeleOp (driving, lift and claw) in a few short methods. **You need:** a drivetrain set up in `RobotSettings` (tutorial 09), a motor `lift` and a servo `claw`. **Full program:** [`Tut20EasyTeleOp.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/tutorials/Tut20EasyTeleOp.java) --- ## 1. Compare with tutorial 12 Tutorial 12's TeleOp set up the drive and IMU, read and shaped the sticks, chose field- or robot-centric, updated the lift, showed telemetry, and stopped everything in `finally`. Every robot needs all of them, and they are the same on every robot. `EasyTeleOp` does all of it. You write only what is special about YOUR robot. It is the TeleOp partner of `EasyAuto` (tutorial 16). ## 2. Tell it about the robot ```java public class Tut20EasyTeleOp extends EasyTeleOp { private PositionMotor lift; private PositionServo claw; @Override protected RobotConfig robotConfig() { return RobotSettings.config(); } @Override protected Subsystems createSubsystems() { lift = PositionMotor.create(hardwareMap, "lift")...; claw = PositionServo.create(hardwareMap, "claw")...; return new Subsystems().add(lift, claw); } ``` These are the SAME two methods as in tutorial 16's autonomous. `robotConfig()` gives the drive, the autonomous tuning and the IMU in one object (a [`RobotConfig`](https://crossbotics.com/ftc-helper/docs/modules/core/#robotconfig)). So TeleOp and autonomous can never use different motor names or directions. The tutorial `RobotSettings` keeps its settings in `static` methods, so `RobotSettings.config()` wraps them into one object. The starter kit's `RobotSettings` IS such an object, so there you write `new RobotSettings()`. `EasyTeleOp` updates the mechanisms you return every loop, shows them on the screen, and stops them at the end. ## 3. The driver's controls: already done You get the driving on gamepad 1 without writing anything: left stick drives, right stick X turns, left trigger slows. Double-tap Y for field-centric. BACK says "the robot now faces away from me". GUIDE opens the tuning menu (PRACTICE profile). Field-centric "forward" continues from where autonomous ended, so the driver does not need BACK at the start of a match. Every free control, the alliance choice and the match timer: [EasyTeleOp: what it does for you](https://crossbotics.com/ftc-helper/docs/modules/teleop/#what-it-does-for-you). In `libraryButtons(LibraryButtons lib)`, you can move each of them to another button, or free it. For example: `lib.fieldCentric(Key.g1(Btn.X));` ([the full list](https://crossbotics.com/ftc-helper/docs/modules/teleop/#moving-the-librarys-buttons)). ## 4. The operator's buttons The **operator** is the second driver, on gamepad 2. The operator runs the mechanisms while the driver drives. ```java @Override protected void bindButtons(ControllerBindings driver, ControllerBindings operator) { operator.bindPress(Pad.G2, Btn.A, () -> lift.goTo("DOWN")) .bindPress(Pad.G2, Btn.Y, () -> lift.goTo("HIGH")) .bindPress(Pad.G2, Btn.RB, () -> claw.toggle("OPEN", "CLOSED")); } ``` These are the same bindings as in tutorial 03, on the `operator` object `EasyTeleOp` hands you. Each action only sets a target and returns. The lift moves in its own `update()`. Put extra buttons for the driver on `driver`. They pause while the tuning menu is open, because the menu uses gamepad 1. ## 5. Every loop: sticks and rules ```java @Override protected void everyLoop() { lift.manual(StickShaping.shape(-gamepad2.left_stick_y, 0.1, 1)); } ``` A stick is not a button, so it goes here. `everyLoop()` runs after the buttons and the driving, before the mechanisms update. It keeps running while the tuning menu is open. The menu uses gamepad 1, so when you read gamepad 1's sticks here, check `isTuningMenuOpen()` first. Never `sleep()` or wait here: the whole robot stops while you wait ([Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/)). ## 6. Extra screen lines (optional) ```java @Override protected void addTelemetry(RobotTelemetry t) { t.line("Alliance", alliance()); } ``` The lift and claw already show their own lines. The time and drive mode are at the top. ## Run it 1. Run tutorial 16's autonomous first, then this TeleOp. INIT shows "Forward: from autonomous". 2. Press ▶ (start on the Driver Hub). Drive robot-centric. Double-tap Y (two buzzes): field-centric. Push the stick up: the robot drives away from you, whichever way it faces. 3. On gamepad 2, A / Y move the lift, the right bumper opens and closes the claw, and the left stick moves the lift by hand. 4. Wait until 1:00 is left: both gamepads buzz. ## If something goes wrong | Problem | Fix | | --- | --- | | "EasyTeleOp needs your robot settings" | Add `robotConfig()`. | | Field-centric "forward" is off | The robot did not start autonomous facing away from you. Set `startHeadingDeg()` in the autonomous, or press BACK (in a Controls.java TeleOp: hold BACK 1 s). | | Y does nothing | The drivetrain is tank, or there is no IMU. Field-centric needs mecanum wheels and the IMU. | | The robot does not drive | The tuning menu is open. GUIDE closes it. | | A warning "button job took ... ms" | A button action waits. Remove the wait ([Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/)). | ## Try this 1. Start in field-centric: `@Override protected boolean startFieldCentric() { return true; }`. 2. Make slow mode slower: `@Override protected double slowSpeed() { return 0.2; }`. 3. Add a driver button: `driver.bindPress(Pad.G1, Btn.A, ...)` in `bindButtons`. --- **Next:** [Tutorial 21: Find your numbers](https://crossbotics.com/ftc-helper/docs/tutorials/21-finders/) **Look it up:** [teleop.md](https://crossbotics.com/ftc-helper/docs/modules/teleop/) --- # Tutorial 21: Find your numbers URL: https://crossbotics.com/ftc-helper/docs/tutorials/21-finders/ **You will build:** small OpModes that start the library's ready-made finders. A **finder** is a library OpMode that measures one kind of number on your robot and prints the code lines to copy. **You need:** a robot with the parts you want to measure. **Programs:** the starter kit's [`ServoFinder.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/starter/ServoFinder.java), [`MotorFinder.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/starter/MotorFinder.java), [`FlywheelFinder.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/starter/FlywheelFinder.java), [`DriveTuner.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/starter/DriveTuner.java), and the examples [`ExampleShotTuner.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/ExampleShotTuner.java) and [`ExampleAimTuner.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/ExampleAimTuner.java). --- ## 1. Why not just guess? A guessed servo position can push the claw into the frame until the servo burns out. A guessed lift limit can pull the lift off its rails. A guessed wheel size makes every autonomous move the wrong distance. The finders measure the real numbers safely, and write the code line for you. ## 2. The smallest finder ```java @TeleOp(name = "Servo Finder", group = "Finders") public class ServoFinder extends ServoFinderOpMode { } ``` Like the Hardware Check (tutorial 19), the library wrote the whole OpMode. It reads the robot configuration, so you give it no servo name: you choose one from a list. In any finder, press **GUIDE** (the center button, or hold the gamepad's START button for 1 second). It shows a help page with every button and the steps. ## 3. Use the Servo Finder The steps, button by button: [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/). At the end, the screen shows the lines to copy: ```java PositionServo.create(hardwareMap, "claw").limits(0.180, 0.770) .position("P1", 0.210) Tunables.Claw: P1 = 0.210 // rename P1, P2... (open, closed); keep them between 0.180 and 0.770 ``` Without the five files, copy the first two lines into your code and rename P1 to "OPEN". With the five files, copy the `Tunables.Claw` line instead: `open = 0.210` in `Tunables.Claw`. When you press STOP, the finder saves the same lines in `/sdcard/FIRST/ftc-helper/finder-results.txt` on the hub. ## 4. The finders that need your code The Drive Tuner needs your `RobotSettings` (one line, like `EasyTeleOp`). The Shot Tuner needs your launcher and camera. The Aim Tuner needs your camera, and a turret or the drive to turn: ```java public class ShotTuner extends ShotTunerOpMode { @Override protected Launcher createLauncher() { return new Robot(hardwareMap).launcher; } @Override protected TargetSource createCamera() { return WebcamTags.create(hardwareMap, "Webcam 1"); } @Override protected RobotConfig robotConfig() { return new RobotSettings(); } // drive between spots } ``` This code uses the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/)'s `Robot` and `RobotSettings`. With the tutorials' `RobotSettings`, write `RobotSettings.config()`. Use the SAME launcher set-up as your TeleOp (best: from your `Robot` class). Then the numbers you find are the numbers your TeleOp uses. ## 5. The order Each finder builds on the ones before it. For example, the Shot Tuner needs a flywheel that holds its speed and a camera that aims straight. The order, and one page per finder: [Tuning](https://crossbotics.com/ftc-helper/docs/tuning/). ## If something goes wrong | Problem | Fix | | --- | --- | | The list is empty | The robot configuration has no devices of that kind. Check the Driver Station configuration. | | The servo jumps when it first moves | The start point was far from where the servo sat. Choose a start point near its real position before you press A. | | Drive Tuner: "counts went DOWN" | A wheel motor direction is wrong. Fix it in `RobotSettings` (Hardware Check). | | Shot Tuner: "no target" | The camera does not see the target. Check its status in INIT, the light, and the tag in view. | Each finder's own problems: the "Fix a mistake" table on its page in [Tuning](https://crossbotics.com/ftc-helper/docs/tuning/). ## Try this 1. Run the Motor Finder on the lift. Replace the limits in your code (five files: `Tunables.Lift`) with the measured ones. 2. Run the Flywheel Finder twice, with a full and a half-charged battery. Compare the top speeds. --- **Next:** this is the last tutorial. Back to [the tutorials](https://crossbotics.com/ftc-helper/docs/tutorials/), or put the numbers into a whole robot program with the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/). **Look it up:** [finders.md](https://crossbotics.com/ftc-helper/docs/modules/finders/) --- # How it all fits together URL: https://crossbotics.com/ftc-helper/docs/guides/architecture/ **For:** students who have written a TeleOp and want the big picture. **You need:** nothing to install. [The five files](https://crossbotics.com/ftc-helper/docs/five-files/) helps. The library has layers, and your team's code goes in the top one. TeamCode is the folder in your robot project where your team's own code lives. ## The layers
flowchart TB
    subgraph TEAM["TeamCode (your team, changes every season): the five files"]
        RB["Robot.java<br/>the parts: drive, odometry, intake, lift..."]
        TU["Tunables.java<br/>their numbers"]
        CO["Controls.java<br/>buttons -> jobs"]
        AC["Actions.java<br/>jobs made of several moves"]
        AU["One file per auto<br/>lists of steps"]
    end
    subgraph LIB["ftc-helper-lib (stays the same across seasons)"]
        direction TB
        R["robot: RobotDefinition, the modules (Drive, Odometry, Intake, Lift, Claw, Launcher, Turret...),<br/>ControlMap, Action, Auto + Steps"]
        M["the plain parts: mechanism, launcher, vision, drive, odometry<br/>PositionMotor, SpinMotor, servos, Flywheel, cameras, MecanumDrive, PinpointOdometry"]
        FI["finders + testing: Servo/Motor/Flywheel finders, Odometry Tuner, Hardware Check"]
        C["core + control + safety + hardware + util<br/>Subsystem, Profile, PidController, SafeMotor, MotorSetup, MathUtil"]
    end
    SDK["FTC SDK (FIRST, new version each season)"]
    TEAM --> LIB --> SDK
Your team writes the [five files](https://crossbotics.com/ftc-helper/docs/five-files/). They use the library's `robot` package (a package is a folder of classes that belong together). `Robot.java` extends `RobotDefinition`. Each `add(...)` line makes a module, such as `Intake` or `Lift`. A module is built on the plain parts underneath. It adds the things every team needs: its numbers in `Tunables.java`, its usual buttons, safety checks, and the simulator's picture of it. **The plain parts work alone too.** Your own `LinearOpMode` can use `PositionMotor`, `Flywheel` or `PidController` with no five files ([use only what you need](https://crossbotics.com/ftc-helper/docs/guides/use-only-what-you-need/)). A module's `part()` gives the plain part inside it. Older programs use `EasyTeleOp` and `EasyAuto` (the [earlier tutorials](https://crossbotics.com/ftc-helper/docs/tutorials/)): they still work, but new code uses the five files. **Rule of thumb:** when it is true for any game, it goes in the library. When it is about THIS game (field positions, which tag, how many pieces, scoring heights), it goes in TeamCode. ## One loop, every loop Every TeleOp has the same shape, whatever the robot:
flowchart LR
    R["read the gamepads<br/>(Controls.java's buttons)"] --> C["commands<br/>(quick: set targets and modes)"]
    C --> U["update every part<br/>(PID, limits, jam checks)"]
    U --> T["telemetry<br/>(the Driver Hub screen)"]
    T --> R
- **Commands are quick.** A button sets a target ("lift to HIGH"). It never waits. - **`update()` does the work**, once per loop: PID, limits, jam checks, timing. PID is the math that moves a motor to a target and holds it there. - **No `sleep()` in TeleOp.** While the code sleeps, the robot cannot react. Full guide: [Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/). Only autonomous moves and steps block, and they do it on purpose. The library runs this loop for you: in TeleOp, and during every step of an auto. You never write it. [What runs every loop](https://crossbotics.com/ftc-helper/docs/guides/every-loop/) gives the exact order and what each part reads and writes on the hub. It also says when the library writes files and what stays between OpMode runs. ## The interfaces (where new things plug in) An interface is a short list of methods that a class promises to have. Any class that has them can plug in. | Interface | Ready-made | Write your own when... | | --- | --- | --- | | `Module` (a class to extend) | `Intake`, `Lift`, `Claw`, `Launcher`... | a new kind of part for `Robot.java` | | `Subsystem` | every mechanism helper | you build a new kind of mechanism | | `AutoStep` | `goToStep`, `shootStep`, `runForStep`... | a step needs custom logic | | `Feeder` | `MotorFeeder`, `ServoFeeder` | a new kind of feeder feeds the launcher | | `TargetSource` | `WebcamTags`, `LimelightTags`, `HuskyLensCamera` | a new camera or a new kind of target | See [Extending the library](https://crossbotics.com/ftc-helper/docs/guides/extending/). ## Where each kind of number lives | Number | Lives in | Changed by | | --- | --- | --- | | motor and servo names, directions, gear ratios | `Robot.java` | code | | every part's numbers: positions, speeds, PID gains, the shot table | `Tunables.java`, one section per part | the finders and the tuning menu, then copied into the file (INIT lists the lines) | | which button does what | `Controls.java` | code | | start spots, routes, field points | each auto's steps | code, or the auto builder | | practice vs competition values | `Profile.pick(a, b)` | the INIT menu's profile line | | match choices (alliance, delay, which auto) | the INIT menu | the drivers, in INIT | --- # Ask an AI agent about the library URL: https://crossbotics.com/ftc-helper/docs/guides/ask-an-ai-agent/ **For:** students and mentors who use an AI coding agent (Claude Code, Codex, GitHub Copilot, Cursor or similar), or an AI chat (Claude, ChatGPT). An AI agent can answer "how do I..." questions about the library and help you write your robot code. It gives better answers when it reads these docs instead of guessing from memory. Without them, it can make up methods that do not exist. The library gives it two ways to read the docs: | You use | Use this | Why | | --- | --- | --- | | A coding agent in your robot project | The **ftc-helper skill** | It reads the docs of YOUR library version, and your TeamCode. It can change and build your code. | | An AI chat in a web browser | The **docs in one file** | No setup. The chat cannot see your code, so paste the part you ask about. | ## The ftc-helper skill (coding agents) A skill is a set of written instructions that the agent follows. This one is in `ftc-helper-lib/skills/ftc-helper/SKILL.md`. It tells the agent where each answer is in the docs. It also gives the library's rules: change TeamCode only, nothing in the loop waits, numbers come from the finders. ### Set it up Do this once per robot project. After you commit and push it, everyone on the team gets it. 1. In the top project folder (next to `TeamCode`), open `AGENTS.md`. Make the file if it is not there. Codex, Copilot, Cursor and most other agents read this file. 2. Add these lines: ```markdown ## ftc-helper-lib For questions about ftc-helper-lib, and for any change to the robot code that uses it, read and follow ftc-helper-lib/skills/ftc-helper/SKILL.md. To make or update the simulator's robot file, follow ftc-helper-lib/skills/robot-file/SKILL.md. ``` 3. **With Claude Code:** in the same folder, open `CLAUDE.md` (make it if it is not there) and add this line. Claude Code reads `CLAUDE.md`, and this line tells it to read `AGENTS.md` too. ```markdown @AGENTS.md ``` 4. Commit and push the two files ([Git and GitHub](https://crossbotics.com/ftc-helper/docs/guides/github/)). The lines point to the skill inside the library folder. **Why:** when you [update the library](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/), the skill and the docs update with it, and they always match the library version your project uses. Do not copy the skill into your project: a copy gets old. ### Ask it Open the agent in your robot project and ask in your own words. For example: - "How do I make the lift go to a height with a button?" - "INIT stops with MEASURE. What do I do?" - "Add a claw on the servo called claw to our robot." - "Make an auto that drives forward, scores, and parks." The agent reads your Robot.java, Tunables.java and Controls.java, finds the docs page, and answers with code for your files. It links the page it used, so you can read more. When it changes your code, it builds it, and it tells you what to check on the real robot. ## The docs in one file (AI chats) The website has the docs as plain text files that an AI chat can read: | File | What is in it | | --- | --- | | [crossbotics.com/llms.txt](https://crossbotics.com/llms.txt) | A list of every docs page, with one line about each | | [crossbotics.com/llms-small.txt](https://crossbotics.com/llms-small.txt) | The main pages in full: pick your start, the five files, controls, building autos, tuning, the cookbook and troubleshooting | | [crossbotics.com/llms-full.txt](https://crossbotics.com/llms-full.txt) | Every page in full. It is large: some chats cannot read all of it | 1. Download `llms-small.txt` and attach it to the chat. Some chats can also read the link directly. 2. Ask your question. Paste the part of your code that it is about. These files match the newest release on the website. When your project uses an older library version, an answer can name something your version does not have. The skill does not have this problem. ## When the answer is wrong An AI agent can be wrong. Build the code, and try it in the [simulator](https://crossbotics.com/ftc-helper/docs/simulator/) before you try it on the robot. When the agent gives an answer that does not match these docs, or the docs do not answer your question, [tell us](https://github.com/crossbotics/ftc-helper-lib/issues/new/choose). We fix the docs, and the next answer is better for every team. --- # Easy autonomous modes URL: https://crossbotics.com/ftc-helper/docs/guides/easy-autos/ **For:** teams that use `EasyAuto` and the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/). With a `Robot.java` (the robot in five files), use [building autos](https://crossbotics.com/ftc-helper/docs/building-autos/) instead. **You need:** a drive that works in TeleOp and that you have tuned ([under-the-hood tutorial 09: Autonomous by hand with AutoDrive](https://crossbotics.com/ftc-helper/docs/tutorials/09-first-auto/)). You make an autonomous with a short list, and you make MANY of them without copying code. `EasyAuto` is the layer under the robot-in-five-files autonomous. ## The idea An autonomous is a **list of named steps**. You write the list, and `EasyAuto` does the rest:
flowchart TB
    subgraph INIT
        I1["set up drive, IMU, mechanisms"] --> I2["menu: alliance, start delay, your choices, profile"]
        I2 --> I3["show where to place the robot<br/>warn: practice profile, tuned values"]
    end
    subgraph RUN["▶ start (30 s)"]
        R1["start the timer, wait the delay"] --> R2["YOUR STEPS<br/>(mirrored for RED,<br/>mechanisms always updating)"]
        R2 --> R3["park steps<br/>(always get their time)"]
    end
    subgraph END
        E1["stop everything"] --> E2["remember alliance + heading for TeleOp"] --> E3["show what each step did"]
    end
    INIT --> RUN --> END
## The smallest autonomous ```java // preselectTeleOp: after this auto, the Driver Station gets "Main TeleOp" ready @Autonomous(name = "Park Only", preselectTeleOp = "Main TeleOp") public class ParkOnly extends StarterAuto { // StarterAuto = the robot setup (starter kit) @Override // fills in the method EasyAuto asks for protected void buildRoutine(AutoRoutine r) { r.right("Park", 24, 0.6); // 24 in to the right (left on RED, unless mirrorForRed() is false) } } ``` This is a complete, safe autonomous: menu, delay, mirroring, timer, stop, TeleOp hand-off. ## Many autos, no copied code Put the robot setup in ONE base class (`StarterAuto` in the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/)). Each autonomous `extends` it. Then it gets all of that setup and only lists its steps:
flowchart TB
    E["EasyAuto (library)"] --> S["StarterAuto (TeamCode)<br/>RobotSettings + Robot"]
    S --> A1["ScoreAndPark"]
    S --> A2["ParkOnly"]
    S --> A3["TwoPieces"]
## Steps you can use | Kind | Steps | | --- | --- | | Driving | `move`, `turn`, `turnTo`, `moveWithTurn`, `rememberHeading`, `returnToHeading` | | Mechanisms | `step(label, lift.goToStep("HIGH"))`, `lift.startStep(...)`, `claw.goToStep(...)`, `intake.inStep()`, `launcher.shootStep(3)`, `turret.aimStep(...)` | | Simple code | `run(label, () -> ...)` (`() -> ...` is a lambda: a small piece of code to run later) | | Waiting | `waitFor(label, seconds)`, `waitUntil(label, condition, timeout)` | | Park | `thenPark()` and the steps after it | **Do things at the same time:** start a mechanism with a `startStep` (or `run`), then drive. The routine updates the mechanism every loop, so it keeps moving during the drive: ```java r.step("Lift starts up", lift.startStep("HIGH")) // does not wait .move("Drive to goal", 24, 0, 0.6) // lift rises meanwhile .waitUntil("Lift is up", lift::isAtTarget, 2.0); // only waits if it is not there yet ``` `lift::isAtTarget` is a method reference: it names the method itself, and the wait calls it every loop. ## Choices in INIT ```java @Override protected void addChoices(InitMenu menu) { // "Near" is the default (first); the YES/NO line starts at YES menu.choice("Route", "Near", "Far").yesNo("Score", true); } @Override protected void buildRoutine(AutoRoutine r) { // the drivers' choices are known here; equals() compares two pieces of text if (choice("Score").equals("YES")) { ... } if (choice("Route").equals("Far")) r.move("Long way", 48, 0, 0.7); } ``` One OpMode with choices is often better than many OpModes. You have fewer files, and the drive team picks at the field. For when to use which, naming, and a match-day checklist, read [Having multiple autos](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/). That page uses the five-files `Auto`, but the ideas are the same. ## Red and blue Write every route for **BLUE**. On RED, the routine mirrors `turn`, `turnTo`, sideways `move` directions and `moveWithTurn` for you. Use `alliance()` for anything else (`alliance().pick(blueTag, redTag)`). **Check the field drawing each season.** Mirroring is right for a field where one alliance's half is a MIRROR image of the other. When the field is ROTATED (turned 180 degrees) instead, the same robot-relative route works for both alliances. Then add `@Override protected boolean mirrorForRed() { return false; }`. ## Time for parking When only the reserved seconds are left, the routine stops the main steps (or skips them). The steps after `thenPark()` always run. The report says which steps it cut short or skipped. In a robot-in-five-files autonomous, the same is one call in the steps: `.parkWithSeconds(4)` ([robot module](https://crossbotics.com/ftc-helper/docs/reference/steps/#keep-time-to-park)). ```java @Override protected double parkReserveSec() { return 4; } // seconds kept for parking ... r.move(...).move(...) // main steps: cut short when 4 s are left .thenPark() .right("Park", 20, 0.8); // always runs ``` ## Where to place the robot `startPosition()` is the note the drive team reads in INIT. `startSpotIn()` (in a five-files autonomous: `s.start(note, x, y, heading)`) also gives the spot. You write it for BLUE, as seen from your drivers' wall. The x number is inches right of the field's center line. The y number is the distance from the center toward the far wall (negative = your half). RED uses it like the routes do. The routine mirrors it. On a field turned half a turn like BIOBUZZ (`mirrorForRed()` false), RED uses the same numbers from the red wall instead. The simulator puts the robot there in INIT. On a field where both alliances' drivers stand at one wall, also add `@Override protected boolean alliancesOnOneWall() { return true; }`. Without it, the simulator puts BLUE at the far wall. ## Read the report When the steps finish, autonomous ends at once, even with time left. Then the Driver Station moves to the TeleOp (`preselectTeleOp`), and the drive team can INIT it. The report gives each step's result. It shows at the end of autonomous, in the robot log, and again on TeleOp's INIT screen: ``` Grab: done Drive to goal: STALLED <- something was in the way Lift is up: timed out <- the lift was slow: tune it, or wait longer Wait for partner: cut short (time for park) <- the park time came during this step Score: skipped (time for park) <- the route is too long Park: done ``` ## Checklist for a new autonomous 1. Copy an existing one. Rename the class and the `@Autonomous(name = ...)`. 2. Write `startPosition()` exactly as the drive team should place the robot. 3. Write the steps for BLUE. Give them short labels that say what the robot does. 4. Run it at low speed first (`powerLimit` 0.4). Read the report. 5. Run it as RED once. Run it with a start delay once. 6. Time it: it must finish (park included) in under ~28 s. --- # What runs every loop URL: https://crossbotics.com/ftc-helper/docs/guides/every-loop/ **For:** programmers who want to know exactly what the library does on the hub before they trust it. **You need:** to know a `LinearOpMode` loop and what a bulk read is. We read everything here from the source (`library/src/main/java`). Each part names its file, so you can check it. **No measured loop time yet.** We have not measured how long one EasyTeleOp or ControlMap loop takes on a real Control Hub. Measure yours with [`LoopTimer`](#show-the-loop-time) and [tell us](https://github.com/crossbotics/ftc-helper-lib/issues/new/choose) the number, with the parts on your robot. ## TeleOp: EasyTeleOp and ControlMap `EasyTeleOp.runOpMode()` is `final`, so you cannot change this order. `ControlMap` (`Controls.java`) is an EasyTeleOp that fills in the hooks. ### INIT (once) 1. `BulkReads.auto(hardwareMap)`: AUTO bulk reads on every hub ([below](#bulk-reads)). 2. The IMU (`createImu()`), the driver's heading, the drive motors (`DriverControls`), `configureDriving`. 3. The alliance from `MatchMemory`, the 2:00 `MatchTimer` with its buzzes, the tuning menu. 4. `createSubsystems()`. In a ControlMap this is `robot().setup(hardwareMap)`: it builds every module from `Tunables.java`. The INIT checks (a missing Lift `max`, a misspelled field...) stop here. 5. `bindButtons(...)`, then `buttonHelp()`. Then the **INIT loop** runs until ▶ (start on the Driver Hub). It has: gamepad 1 X/B choose the alliance, the warnings (PRACTICE profile, tuned values), your `addInitTelemetry`, `t.update()`. **The INIT loop updates no part and gives no motor power.** ### ▶ start (once) First `timer.start()`. Then EasyTeleOp forgets the saved heading (the heading belongs to this run now). It ignores buttons held through ▶ until the driver lets go. Then it calls `onStart()` (ControlMap: each module's start, like an intake "on at the start", and the `atStart` actions). ### Each loop, in this order | # | What | Notes | | --- | --- | --- | | 1 | `menuKey.update(gamepad1, gamepad2)` | GUIDE: the button map / tuning menu | | 2 | `operator.update(...)` | gamepad 2 buttons (each job timed, [slow warning](#slow-code-warnings)) | | 3 | `timer.update()` | match timer: buzzes and cues | | 4 | `tuning.update()` | the tuning menu (reads gamepad 1 only while open) | | 5 | menu open: `driving.hold()`. Menu closed: `driver.update(...)`, then `drive(gamepad1)` | driver buttons and driving pause while the menu uses gamepad 1 | | 6 | `everyLoop()` | ControlMap: `plan.loop(...)` (gestures, double-taps, "buzz when" watches, each timed), then every stick job (`use(...)`) | | 7 | `robot.update()` | every part, see [below](#robotupdate) | | 8 | telemetry | the tuning menu, or the button map, or: slow-job warnings, time, drive, every part's lines, your `addTelemetry` (ControlMap: pause note, `show(...)` values); then `t.update()` | `t.update()` sends every loop (`RobotTelemetry.setMinIntervalMs` is 0 unless you change it). The library builds the lines every loop either way, so a part's telemetry reads still happen. The IMU: in field-centric driving, `DriverControls` reads the heading once per loop. A bulk read does not include the IMU. The debug line "Heading" reads it again, only while debug lines are on. ### robot.update() `Subsystems.update()` updates each part in the order you added it, and times each one. In a ControlMap (`RobotDefinition.setup`), the order is: 1. Your own `Tunables` sections (sections no part reads) get the tuning menu's values. It writes a field only when its value changed, and it writes no file. 2. Nothing else runs while the robot is paused (BACK). 3. **The odometry first of all** (with an `odometry(...)` line). It reads the device once and works out this loop's pose. Then every action, part and `driveTo` reads the same, fresh pose ([odometry](https://crossbotics.com/ftc-helper/docs/modules/odometry/#what-runs-every-loop)). 4. `ActionRunner` next: each running Action does its step for this loop. So an Action's command reaches a part before that part updates, in the same loop. 5. Cameras, then every other module, in the order `Robot.java` adds them. ### What a part does on the hub per loop | Part | Reads | Writes | | --- | --- | --- | | Lift, Arm (`PositionMotor` / `SafeMotor`) | `SafeMotor.update()` reads the encoder and each switch **fresh**, every loop. Later reads in the same loop (the PID, telemetry) within 3 ms reuse those readings, so a reading is at most 3 ms old. | the power only when it changes, and again every 25 loops. **Past a soft limit** (below min or above max): it checks and sends the power **every loop** | | Turret (`launcher.Turret`) | the encoder at most once per 3 ms | the power only when it changes | | Drive (`MecanumDrive`, `TankDrive`) | none, except the IMU in field-centric | every wheel power, every loop | | Intake in the five files (`robot.Intake`) | none | each motor's and CR servo's power only when it changes (no re-send) | | Intake building block (`mechanism.SpinMotor`) | while running in with jam detection: the speed (`getVelocity()`, part of the bulk read) every loop. When the jam check uses current, also `getCurrent()` every loop: a **separate** hub command, outside the bulk read | the power only when it changes, and again every 25 writes (one write per `update()`) | | Flywheel, launcher (`launcher.Flywheel`, used by `robot.Launcher`) | the speed (`getVelocity()`) every loop, and a follower motor's speed too | the speed (`setVelocity`) only when the target changes | | Servos (`mechanism.PositionServo`, used by the claw, wrist and other servo parts) | none (a servo cannot report where it is) | the position only when it changes; during a slow move, a small step each loop | | Odometry, Pinpoint (`odometry.PinpointOdometry`) | one I2C read per loop: the Pinpoint's position, speed and status together (the Pinpoint works out the pose itself, about 1500 times a second) | none (only when something sets the pose: at the start of autonomous, TeleOp's INIT, BACK held) | | Odometry, OTOS (`odometry.OtosOdometry`) | two I2C reads per loop: position, then speed | none (only when something sets the pose) | | Odometry, dead wheels (`odometry.DeadWheelOdometry`) | each pod's encoder (part of the bulk read). With two wheels, also the IMU's heading (a separate read) | none | | Cameras (`vision.WebcamTags`, `vision.LimelightTags`) | the newest tags, from the camera's own process (webcam) or the Limelight's last result. No hub command | none | Why the 3 ms: in a loop, `update()`, the PID and the telemetry all ask for the position. Each ask used to be a trip to the hub. Now `update()` always reads fresh at the start of the loop. Later asks within 3 ms reuse that reading, so they share one. **A reading is at most 3 ms old.** Code that never calls `update()` gets a reading at most 3 ms old every time it asks. When more than 3 ms pass between `update()` and the telemetry (slow parts in between), the telemetry reads again. Tests that move a pretend motor with no time passing turn the reuse off with `SafeMotor.freshReadingsForTests(true)`. Robot code never needs it. Why the 25 loops: a power written straight to `getMotor()` skips the limits. `SafeMotor` sends its own limited power again every 25 loops, even when it did not change. So a raw write lasts at most 25 loops (about half a second at 50 loops a second). Past a soft limit, `SafeMotor` sends every loop, so a raw write can never keep pushing past the limit. A part that rests exactly at a limit, like a lift on its bottom switch, is not "past", so it does not send every loop. `SpinMotor` sends again every 25 writes in the same way. ### Bulk reads `BulkReads.auto(hardwareMap)` (EasyTeleOp, EasyAuto and the finders call it) puts every hub in the SDK's AUTO bulk-caching mode. A bulk read gets many values from a hub in one message. In AUTO mode the first read gets all of a hub's bulk data (encoders, digital inputs, analog inputs...) in one message. **A second read of the same value starts a new bulk read.** That is why the parts read each encoder and each switch once per loop (above). **For exactly one bulk read per hub per loop:** use `BulkReads.manual(hardwareMap)`, and call `BulkReads.clear(hubs)` at the top of your own loop ([hardware](https://crossbotics.com/ftc-helper/docs/modules/hardware/#bulkreads)). EasyTeleOp does not do this for you. ### Slow-code warnings | Timed | Limit | Warning (top of the Driver Station) | | --- | --- | --- | | each part's `update()` (`Subsystems.SLOW_UPDATE_MS`) | 25 ms | ` update took 40 ms: update() must not wait or sleep` | | each button job (`ControllerBindings.SLOW_ACTION_MS`) | 20 ms | `G2:A button job took 40 ms: the whole robot stopped that long. ...` (the gamepad and button first) | | each gesture or "buzz when" job (ControlMap) | 20 ms | `a button job took 40 ms: the whole robot stopped that long. ...` | Each warning goes away 5 s after the last slow update or job. Fixes: [troubleshooting](https://crossbotics.com/ftc-helper/docs/troubleshooting/#robot-behavior). ### Show the loop time Every EasyTeleOp and `Controls.java` TeleOp shows it in the debug lines (hold the gamepad's START button, then press BACK): `Loop: 12.3 ms (81 Hz)`. Lower is better, and under 20 ms is good. To show it all the time, or in your own OpMode, use [`LoopTimer`](https://crossbotics.com/ftc-helper/docs/modules/util/#looptimer). In an EasyTeleOp: ```java private final LoopTimer loop = new LoopTimer(); @Override protected void everyLoop() { loop.update(); } @Override protected void addTelemetry(RobotTelemetry t) { t.line("Loop", "%.1f ms (%.0f Hz)", loop.getAverageMs(), loop.getHz()); } ``` In a ControlMap, `everyLoop` and `addTelemetry` belong to the ControlMap itself. Use `show(...)` there: the ControlMap reads its value once per loop, so the timer can update in it. It does not read the value while the tuning menu or the button map is open. ```java private final LoopTimer loop = new LoopTimer(); @Override protected void buttons(Robot robot, Pad g1, Pad g2) { show("Loop Hz", () -> { loop.update(); return Math.round(loop.getHz()); }); } ``` ## Autonomous: EasyAuto and Auto `EasyAuto.runOpMode()` is `final` too. - **INIT:** `BulkReads.auto`, then the IMU (with no IMU, it stops with a message). When the drive is "not tuned", it shows "AUTONOMOUS IS OFF" and never moves. Then the mechanisms (`createSubsystems()`; Auto: `robot.setup(...)`), the INIT menu, and the INIT loop (menu, warnings, lines). It updates no part. - **▶:** when the profile changed in INIT, EasyAuto makes the drive and the mechanisms again. Then the 30 s timer starts, and `AutoRoutine.runAll()` runs each step. Steps block on purpose. - **Each loop while a step drives or waits:** `AutoDrive` reads what the move needs (the four wheel encoders for a move, the IMU for a turn). It sets the wheel powers, then calls the routine's `tick()`, then `idle()`. A wait (`waitFor`, `waitUntil`) calls `tick()` and `idle()`. - **`driveTo`** (with odometry) reads the pose that the last `tick()` worked out. So the library reads the odometry once per loop, not twice. - **`tick()`:** `robot.update()` (the same as TeleOp's, odometry first), `timer.update()`, the step's line, the time left, every part's telemetry, `t.update()`. - **End:** when the steps finish, EasyAuto stops everything and the report goes to `MatchMemory`. After any end (done, STOP or an error), it stops everything again. Only when the drivers pressed ▶, the alliance and the end heading go to `MatchMemory` for TeleOp. With odometry, the whole end pose goes, and TeleOp's INIT starts the odometry there. ## When the library touches storage Storage means files on the Control Hub (`/sdcard/FIRST/ftc-helper/`). This table lists every write. | When | What | Waits? | | --- | --- | --- | | the first `Tunable` is made, or the first `Profile.current()` | reads `settings.properties` once per app run (`SettingsFile.load`) | yes, once, in INIT | | tuning menu **A** (save) and **Y** (reset all) | `Tunable.saveAllInBackground` / `resetAllInBackground` write `settings.properties` | no: a background thread | | the profile changes (`Profile.set`, the INIT menu's profile line) | writes `settings.properties` | no: a background thread | | a finder ends (`FinderOpMode`) | `finder-results.txt` | yes, after the motors stop, outside the loop | | each Characterizer test ends | a CSV in `characterizer/` | no: a background thread | | you call `Tunable.saveAll()`, `resetAll()` or `SettingsFile.save()` | `settings.properties` | **yes** (do not call them in a loop) | Nothing else writes a file. **`MatchMemory` and `PoseStore` live in memory** (see below). A settings write goes to a `.tmp` file first, and then the library renames it. So a power cut never leaves a half-written `settings.properties`. A failed write never stops the robot. ## Static state that lives across OpMode runs All OpModes run in one robot app. A `static` field keeps its value from one OpMode run to the next, until the app restarts. The library keeps these static fields: | Static | Why | What it means for you | | --- | --- | --- | | the `Tunable` registry (`Tunable.ALL`) | the tuning menu finds tunables made anywhere | a value changed in the menu stays in the next OpMode run, even unsaved, until the app restarts. `Tunable.number(name, ...)` returns the existing one, and ignores the second default (`fromCode` takes the new code value when nobody tuned the old one) | | `Profile.current` | read from the file once | when you change the file by hand, restart the app | | `SettingsFile.shared` | one settings file for the app | loaded once | | `MatchMemory` (alliance, report, placement) | autonomous hands them to TeleOp | ignored after 5 minutes (`MAX_AGE_SEC`). An autonomous writes the remembered alliance only after ▶. Every INIT loop sets the "chosen" alliance and the placement (the simulator reads them) | | `PoseStore` | autonomous hands the end heading to TeleOp | EasyTeleOp forgets it at ▶, so a later TeleOp run does not use it | | `ButtonPlan.buzzer` | a test hook: tests count buzzes instead of buzzing | package-private; robot code never changes it | | `SafeMotor.READ_KEEP_NANOS`, `Turret.READ_KEEP_NANOS` | the 3 ms reuse time | package-private. Tests change `SafeMotor`'s with the public hook `SafeMotor.freshReadingsForTests(boolean)` (true = read every time); robot code never needs it | | background threads (`SettingsFile`, finders) | one thread for file writes | made on first use | ## See also - [Your own code at INIT, ▶, every loop and STOP](https://crossbotics.com/ftc-helper/docs/guides/your-own-code/): where your code goes in each step. It also shows how to write the whole OpMode yourself with the library's robot. - [Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/): what blocks and what never does. - [Use only what you need](https://crossbotics.com/ftc-helper/docs/guides/use-only-what-you-need/): the building blocks in your own loop. - [Architecture](https://crossbotics.com/ftc-helper/docs/guides/architecture/): the big picture. --- # Example: drive, slow mode, and an intake that starts on URL: https://crossbotics.com/ftc-helper/docs/guides/example-drive-intake/ **For:** students who have driven a robot with the library and want a full TeleOp to copy. **You need:** [Robot.java](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/) (the drive) and [Controls.java](https://crossbotics.com/ftc-helper/docs/five-files/03-controls-java/) (buttons), or the same knowledge. This is a complete TeleOp for a common robot. It has a mecanum drive with a slow-mode toggle. Its intake is **ON from the start**. The driver can **stop and start** it, and **reverse it while holding a button**. **Program:** [`ExampleDriveIntake.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/ExampleDriveIntake.java) **Needs:** motors `front_left`, `front_right`, `back_left`, `back_right`, `intake`. ## The controls (gamepad 1) | Control | Does | | --- | --- | | Left stick | drive (forward/back, sideways) | | Right stick X | turn | | Y | slow mode on/off (2 buzzes = on, 1 buzz = off) | | Right bumper | intake on/off | | Left bumper (hold) | intake reverse (spit out). Let go: it goes back to what it was doing | | BACK | debug telemetry on/off | ## How the intake logic works Two switches decide what the intake does, every loop:
flowchart TB
    Q1{"left bumper held?"} -- yes --> OUT["intake.out()"]
    Q1 -- no --> Q2{"intakeOn?"}
    Q2 -- yes --> IN["intake.in()"]
    Q2 -- no --> STOP["intake.stop()"]
In the code below, `() -> ...` is a lambda: a small piece of code that you hand to a button. It runs when the driver presses the button (or, with `bindRelease`, lets it go). ```java private boolean intakeOn = true; // the intake starts ON private boolean reversing = false; // true while the left bumper is held ... // The buttons only change the two switches. "!" = not, so RB flips intakeOn. .bindPress(Pad.G1, Btn.RB, () -> intakeOn = !intakeOn) .bindPress(Pad.G1, Btn.LB, () -> reversing = true) .bindRelease(Pad.G1, Btn.LB, () -> reversing = false) ... // every loop: if (reversing) intake.out(); // reverse wins else if (intakeOn) intake.in(); else intake.stop(); intake.update(); // the motor gets its power here ``` **Switches instead of `intake.in()` in the buttons:** with switches, the rules are in ONE place that you can read top to bottom. "Reverse wins" is one line. When you let go of the reverse button, the intake goes back to on OR off, whichever it was, with no extra code. **Calling `in()` every loop is safe:** `SpinMotor.in()` does nothing when it is already running in. So it does not interrupt anything (like a jam back-out). **"Defaulted to on":** `intakeOn` starts `true`. The first loop after ▶ (start on the Driver Hub) turns the intake on. It never runs during INIT. The library moves nothing before ▶, for safety. ## How slow mode works ```java // bindToggle(pad, button, code when it turns ON, code when it turns OFF) .bindToggle(Pad.G1, Btn.Y, () -> { slowMode = true; confirm.play(true); }, () -> { slowMode = false; confirm.play(false); }) ... double speed = slowMode ? SLOW_SPEED : 1.0; // "a ? b : c" = if a then b, else c drive.drive(forward, strafe, turn, speed); // every wheel power times speed ``` The driver cannot see a toggle, so `ToggleRumble` buzzes: two = on, one = off. A toggle flips at each press. The first press runs the first action (ON), and the next press runs the second (OFF). `SLOW_SPEED` (0.35) is a constant at the top of the file, so you can find and change it there. ## The rest of the program - `"intake"` and the four drive motor names must match the names in YOUR robot configuration. For other drive names, set them on a `DriveConfig` ([tutorial 04](https://crossbotics.com/ftc-helper/docs/tutorials/04-drive-mecanum/)). - `powers(1.0, -0.7)`: in at full power, to grab pieces fast. Out at 70%, so the intake pushes pieces out and does not throw them. - The sticks: `shape(stick, 0.05, 2)` ignores tiny values, because a resting stick is often not exactly 0. It squares the rest for fine control. The stick reads negative when pushed up, so `left_stick_y` has a minus ([Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/)). - `t.warn(controls.getSlowActionWarning())`: a button action that takes too long freezes the whole robot. The screen says which one. - `finally` stops the drive and the intake, however the program ends. ## Make it yours - Two drivers: change the intake bindings to `Pad.G2`. - Jam protection: add `.jamDetection(80, 0.3, 0.4)` to the intake. It needs the intake motor's encoder cable. - To tune the slow speed live, use `static final Tunable SLOW = Tunable.number("Drive/slow", 0.35, 0.05);` and `SLOW.get()` ([tuning guide](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/)). - For slow mode on a trigger instead of a toggle, use `StickShaping.slowScale(gamepad1.left_trigger, 0.35)`. --- # Extending the library URL: https://crossbotics.com/ftc-helper/docs/guides/extending/ **For:** students and mentors who add something new to the library. **You need:** comfort with Java classes, and the library building on your laptop ([Contributing](https://crossbotics.com/ftc-helper/docs/contributing/#build-and-test)). The library grows every season. New things plug in at four places. Each has a complete example below, and the rules at the end keep the library easy for the next team. Each place is an interface: a short list of methods that a class promises to have. A class that `implements` it writes those methods (each marked `@Override`). Then it plugs in anywhere the library expects one. ## Where does my new code go?
flowchart TB
    Q{"Is it true for ANY FTC game?"} -- "no: this game only<br/>(tag ids, field spots, scoring)" --> T["TeamCode"]
    Q -- "yes" --> Q2{"Does a helper already almost do it?"}
    Q2 -- yes --> O["Add an option to that helper<br/>(a new setup method)"]
    Q2 -- no --> N["A new class in the library,<br/>implementing one of the interfaces below"]
## 1. A new mechanism: implement `Subsystem` ```java /** A two-servo gripper that closes both sides together. */ public class DualGripper implements Subsystem { private final PositionServo left, right; private boolean closed = false; // the state; the commands below only change this public DualGripper(HardwareMap hw) { left = PositionServo.create(hw, "grip_left").position("OPEN", 0.2).position("CLOSED", 0.7); // reversed(): the right servo is mounted mirrored, so the same numbers work for both right = PositionServo.create(hw, "grip_right").reversed().position("OPEN", 0.2).position("CLOSED", 0.7); } public void close() { closed = true; } public void open() { closed = false; } // update() turns the state into servo moves, every loop. "a ? b : c" = if a then b, else c. @Override public void update() { String p = closed ? "CLOSED" : "OPEN"; left.goTo(p); right.goTo(p); left.update(); right.update(); } @Override public void addTelemetry(RobotTelemetry t) { t.line("Gripper", closed ? "CLOSED" : "open"); } /** Autonomous step. */ public AutoStep closeStep() { // close, then wait until both should have arrived, at most 1.0 s return ctx -> { close(); ctx.waitUntil(() -> left.isDone() && right.isDone(), 1.0); }; } } ``` It now works in `Subsystems`, in `EasyAuto` and with buttons. It shows telemetry like every other part. ## 2. A new autonomous action: implement `AutoStep` ```java AutoStep alignWithWall = ctx -> { ElapsedTime timer = new ElapsedTime(); // a stopwatch, starts now try { // try/finally: "finally" always runs while (ctx.isActive() && !wallSensor.isPressed() && timer.seconds() < 2.0) { // a way out! drive.setPowers(new double[]{-0.2, -0.2, -0.2, -0.2}); // back up slowly ctx.loop(); // mechanisms + telemetry keep running } } finally { drive.stop(); // even if something throws } }; routine.step("Back into the wall", alignWithWall); ``` Rules: check `ctx.isActive()` in every loop. Call `ctx.loop()` (or `waitFor`/`waitUntil`) while it waits. Give it a way out (a time limit). Stop the motors that it started. ## 3. A new way to feed the launcher: implement `Feeder` ```java /** A gate servo that opens briefly to let one piece roll in. */ public class GateFeeder implements Feeder { private final Servo gate; private double closeAt = -1; // when to close the gate, seconds; -1 = not feeding public GateFeeder(HardwareMap hw) { gate = hw.get(Servo.class, "gate"); } // Never waits: feedOne() opens the gate and notes the time; update() closes it 0.2 s later. @Override public void feedOne() { if (!isBusy()) { gate.setPosition(0.8); closeAt = now() + 0.2; } } @Override public boolean isBusy() { return closeAt > 0; } @Override public void update() { if (closeAt > 0 && now() >= closeAt) { gate.setPosition(0.1); closeAt = -1; } } @Override public void stop() { gate.setPosition(0.1); closeAt = -1; } private static double now() { return System.nanoTime() / 1e9; } // nanoseconds -> seconds } ``` `new Launcher(flywheel, new GateFeeder(hardwareMap))`: everything else (ready checks, timing, steps, telemetry) stays the same. ## 4. A new camera or target type: implement `TargetSource` Return `TargetObservation`s with **bearing positive to the LEFT**, distance in inches (or NaN), and the picture time in `System.nanoTime()`. Then `AimController`, `Turret.aimBy` and `Launcher.setDistance` all work with it. Use `LimelightTags` as the model. ## The rules (so the next team can use it) 1. **One sign convention**: forward +, strafe right +, turn clockwise + for drive commands; headings, turret angles and bearings counterclockwise + ([Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/)). 2. **Nothing blocks TeleOp**: commands are quick, and the work happens in `update()`. Only autonomous steps wait. 3. **Hardware setup leaves motors at 0 power.** Nothing moves before ▶ (start on the Driver Hub). 4. **Safety stays on in every profile.** Limits, timeouts, jam checks. 5. **Testable**: tests need pretend devices and a pretend clock (see `library/src/test`). So put the logic in a part with no hardware. Or take a clock (`LongSupplier`, a method that returns the time) and devices in the constructor. The constructor is the code that makes the object. A part's default clock is `Time::nanos` (core). With it, a test's [`PretendClock`](https://crossbotics.com/ftc-helper/docs/modules/testkit/#pretendclock) moves the part's clock too, and with `System::nanoTime` it does not. 6. **The six steps**: code, Javadoc, test, module page, tutorial, CHANGELOG ([Contributing](https://crossbotics.com/ftc-helper/docs/contributing/)). 7. **Parts stay general** (any team, any season). Season knowledge goes in the season definitions (the field, the rules). A team's own numbers and spots stay in TeamCode. ## Versions Something new gets a new middle number (0.4.0 -> 0.5.0). A change to how something old works gets a new first number, and a "Changed" note in the CHANGELOG that says what teams must change. Before 1.0, a change that breaks old code also moves only the middle number (v0.11.0 renamed the package). The CHANGELOG then lists the steps for teams. --- # Git and GitHub for FTC teams URL: https://crossbotics.com/ftc-helper/docs/guides/github/ **For:** every student who changes the robot code, and the mentor. **You need:** a GitHub account (free; GitHub's rules say you must be 13 or older), and the robot project on GitHub. **Why this matters.** Git keeps every saved version of your robot code. With it you can: - **undo a mistake**, even one from last week; - **share code** between laptops, so the whole team has the same robot program; - **try an idea** without breaking the code that works; - **get back to the exact code** that ran at the last event. Without it, the code lives on one laptop. When that laptop breaks, or somebody leaves it at home on the day of an event, the code is gone. Each step has two ways. Use the one your team likes: - **The command line:** the **Terminal** tab at the bottom of Android Studio. Type a line, press Enter. - **GitHub Desktop:** a free app with buttons ([desktop.github.com](https://desktop.github.com)). The menu names below are the Mac names. On Windows they are the same words with small letters (**Merge into Current Branch…** is **Merge into current branch…**). Contents: [words](#words-in-one-line-each) · [team workflow](#the-team-workflow) · [set up once](#set-up-once) · [clone](#clone-the-robot-project-copy-it-to-a-laptop) · [every practice](#every-practice-pull-commit-push) · [branches](#try-an-idea-on-a-branch) · [merge](#merge-a-branch-into-main) · [conflicts](#a-simple-conflict) · [undo](#undo-a-bad-change) · [never commit](#what-never-to-commit) · [private or public](#private-or-public-and-student-privacy) · [before an event](#before-an-event-backups-and-a-tag) · [problems](#problems) ## Words, in one line each | Word | Means | | --- | --- | | **repository** ("repo") | a project folder whose history git keeps. Your robot project is one. | | **GitHub** | a website that keeps a copy of your repository online, so the team can share it. | | **clone** | copy a repository from GitHub to your laptop (once per laptop). | | **commit** | save a snapshot of your changes in the history, with a short message. | | **push** | send your commits from your laptop to GitHub. | | **pull** | get your teammates' commits from GitHub onto your laptop. | | **branch** | a separate line of commits, for trying something without changing `main`. | | **main** | the main branch. On our team it always builds and works. | | **merge** | bring the commits of one branch into another (for example, a tested idea into `main`). | | **conflict** | two people changed the same lines, and git asks you which version to keep. | | **submodule** | a repository inside a repository. ftc-helper-lib is one, in the `ftc-helper-lib` folder. | | **tag** | a name for one commit, like `v0.16.0` or `event-2026-11-14`. It never moves. | | **release** | a tag on GitHub with notes on what changed. The library's versions are tags. | ## The team workflow The five team rules: [Set up 8, team rules](https://crossbotics.com/ftc-helper/docs/setup/08-every-practice/#team-rules). ## Set up once Step by step, for GitHub Desktop and the command line: [Set up 3: GitHub and the robot project](https://crossbotics.com/ftc-helper/docs/setup/03-github-and-the-project/#1-tell-git-who-you-are). ## Clone the robot project (copy it to a laptop) Step by step: [Set up 3, get the robot project](https://crossbotics.com/ftc-helper/docs/setup/03-github-and-the-project/#2-get-the-robot-project). When the `ftc-helper-lib` folder is empty after a clone, run `git submodule update --init`. ## Every practice: pull, commit, push Step by step: [Set up 8: every practice](https://crossbotics.com/ftc-helper/docs/setup/08-every-practice/). ## Try an idea on a branch A branch lets you change code without touching `main`. When the idea does not work, `main` is still fine. Command line (`auto-far-start` is the branch's name: short, small letters, dashes): **Where:** Android Studio's **Terminal** tab, in your **robot project's folder** (where `TeamCode` is). ```bash git switch -c auto-far-start git push -u origin auto-far-start ``` `git switch -c` makes the branch and moves you onto it. `git push -u origin ...` puts it on GitHub. You need it only the first time. After that, `git push` is enough. Commit on the branch as usual. Switch back to `main` (commit your changes first): **Where:** Android Studio's **Terminal** tab, in your **robot project's folder** (where `TeamCode` is). ```bash git switch main ``` GitHub Desktop: **Current Branch** (top bar) > **New Branch**. Type the name, click **Create Branch**, then **Publish branch**. To switch, click **Current Branch** and choose a branch. **Note:** the robot runs the code of the branch that you built and installed. Before you install the app for a match, check which branch you are on. `git status` says `On branch ...`, and Desktop shows it under **Current Branch**. ## Merge a branch into main When the idea works on the robot, bring it into `main`. Command line: **Where:** Android Studio's **Terminal** tab, in your **robot project's folder** (where `TeamCode` is). ```bash git switch main git pull git merge --no-edit auto-far-start git push ``` These lines go to `main`, get the newest `main`, add the branch's commits to it, and send it to GitHub. `--no-edit` keeps the usual message and opens no text editor. Build and test `main` once more after a merge. GitHub Desktop: switch to **main**, click **Fetch origin** / **Pull origin**. Then **Branch > Merge into Current Branch…**, choose `auto-far-start`, and click **Create a merge commit**. Then **Push origin**. Teams that like to review code first can open a pull request on GitHub instead. It does the same merge, but a teammate reads the changes first. ## A simple conflict Two people changed the same line. Git cannot choose, so it asks you. For example, on `main` an autonomous drives `30` inches to the goal, and on your branch it drives `28`. The merge stops: ```text CONFLICT (content): Merge conflict in TeamCode/.../autos/NearCycle.java Automatic merge failed; fix conflicts and then commit the result. ``` Open the file. Git wrote both versions into it: ```text <<<<<<< HEAD .forward("To the goal", 30, 0.6) ======= .forward("To the goal", 28, 0.6) >>>>>>> auto-far-start ``` The part above `=======` is the version you are on (`main`). The part below is the branch's. Keep the right line. Delete the other line and the three marker lines (`<<<<<<<`, `=======`, `>>>>>>>`): ```java .forward("To the goal", 28, 0.6) ``` Then build. A marker line left in the file stops the build. Then finish the merge: Command line: **Where:** Android Studio's **Terminal** tab, in your **robot project's folder** (where `TeamCode` is). ```bash git add TeamCode git commit -m "Merge auto-far-start: 28 in to the goal" git push ``` **When you are not sure:** stop the merge and go back to how it was before with `git merge --abort`. GitHub Desktop: the merge window lists the conflicted files. Click **Open in** (your editor) next to a file, fix it as above, and save. When every file says it is resolved, click **Continue Merge**, then **Push origin**. **Abort Merge** goes back. ## Undo a bad change **Changes not committed yet** (you want the file back as it was at the last commit): **Where:** Android Studio's **Terminal** tab, in your **robot project's folder** (where `TeamCode` is). ```bash git restore TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Tunables.java ``` GitHub Desktop: **Changes** tab, right-click the file > **Discard Changes…**. Desktop puts the discarded changes in the computer's trash. **A commit that is already pushed.** Do not delete history. Add a new commit that undoes it. Find the commit's id (the first letters are enough): **Where:** Android Studio's **Terminal** tab, in your **robot project's folder** (where `TeamCode` is). ```bash git log --oneline git revert --no-edit 3f2c1a9 git push ``` `git log --oneline` lists the commits, newest first. Press **q** to leave the list. `git revert` makes a new commit that does the opposite of `3f2c1a9` (use your commit's id). `--no-edit` keeps git from opening a text editor for the message. GitHub Desktop: **History** tab, right-click the commit > **Revert Changes in Commit**, then **Push origin**. **Why a revert and not a delete:** your teammates already have the commit. Deleting pushed history breaks their copies. A revert is safe for everyone. ## What never to commit | Never commit | Why | | --- | --- | | `local.properties` | it holds the path to the Android tools on YOUR laptop. On another laptop it breaks the build | | `build/` folders, `.gradle/` | every build makes them. They are large, and different on every laptop | | passwords, Wi-Fi keys, API keys, tokens | anyone who can read the repository can use them, forever (they stay in the history) | | Driver Station or Control Hub passwords | the same | | photos or videos of students | privacy: ask first, and keep them out of a public repository | | very large files (CAD exports, videos) | they make every clone slow. Keep them in a shared drive | The FtcRobotController project's `.gitignore` file already keeps most of these out: git does not list the files it names. Check `git status` (or the Desktop **Changes** list) before every commit. When you see one of these, do not commit it. Ask the mentor to add it to `.gitignore`. **When someone pushes a password by mistake:** change that password at once. Removing it from the history is not enough, because someone may already have a copy. ## Private or public, and student privacy - **Private repository:** only the people you add can see it. Use it while you work on the season's secrets. GitHub gives free private repositories. - **Public repository:** anyone can read it. Use it to share with other teams, which FIRST encourages. Check the season's game manual for any rule about sharing code. - **Either way, protect students:** use usernames instead of full names, and the private noreply email. Put no school names with student names, and no photos without permission. The history keeps everything: a name in a commit message stays there. - **Use an organization** (a team account on GitHub) for the robot repository, not one student's account. Students graduate, and the team stays. Add each student as a member, and at least two mentors as owners. ## Before an event: backups and a tag 1. **Commit and push everything** you will run. Check that `git status` says `nothing to commit, working tree clean` and `Your branch is up to date with 'origin/main'`. 2. **Tag the code** you will run, so you can always get back to it: ```bash git tag event-2026-11-14 git push origin event-2026-11-14 ``` GitHub Desktop: **History** tab, right-click the newest commit > **Create Tag…**. Type the name and create it. The next **Push origin** sends it. 3. **Have a second laptop** with the same code, cloned and built, in case the first one fails. Pull on it the night before. 4. **No library update the week before the event** ([why](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/#when-not-to-update)). 5. **At the event, with no internet:** commit as usual (commits work offline). Push when you have internet again. To get the event's code back later (to look at it, or to build it again), run: **Where:** Android Studio's **Terminal** tab, in your **robot project's folder** (where `TeamCode` is). ```bash git switch --detach event-2026-11-14 ``` `git switch main` goes back to the newest code. ## Problems | What you see | Why, and what to do | | --- | --- | | `Project directory '.../ftc-helper-lib/library' does not exist` | the clone did not get the submodule: `git submodule update --init` | | `git status` says `modified: ftc-helper-lib (new commits)` and you did not mean to change it | your library folder is at another version: `git submodule update` | | `rejected ... (fetch first)` on push | a teammate pushed first. Pull, then push | | `Your local changes would be overwritten by merge` on pull | commit (or discard) your changes first, then pull | | `CONFLICT` | see [a simple conflict](#a-simple-conflict) | | `Author identity unknown` | do [set up once](#set-up-once) | | `You have divergent branches` on pull | do the `pull.rebase false` line in [set up once](#set-up-once), then pull again | | A strange text screen opens (vim) with a message to edit | git wants a commit message. Type `:wq` and press Enter to save and leave (`:q!` and Enter leaves without saving and stops) | | You committed on `main` but meant a branch | when you have not pushed yet, `git switch -c my-branch` takes the commits with you. Then ask the mentor to put `main` back | | Everything is a mess | stop, do not force anything, and ask the mentor. Nothing pushed is lost: GitHub has it. | ## Next - Keep the library up to date: [Keep it up to date](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/). - Add the library to a new robot project: [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/). - Several autos and choosing one at the field: [Having multiple autos](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/). --- # How the simulator works URL: https://crossbotics.com/ftc-helper/docs/guides/how-the-simulator-works/ ## Not simulated Phone cameras, and a webcam's colors (`PieceSensor.camera`). The simulator has color and distance sensors only as [piece sensors](#game-pieces). The Shot and Aim tuners work without a camera when `createCamera()` returns null. The physics is a model: you must still find the real numbers (gains, speeds, shot tables) on the robot. Differences to know: - The screen here updates as fast as the OpMode sends. A real Driver Station redraws about 4 times a second, so a flickering line looks steadier there. - The loop runs faster than on a robot, and hardware answers at once. So code that counts loops, instead of using time, can act differently on the robot. - The IMU never drifts, and it ignores how the hub is mounted, so the simulator does not check your `.imu(...)` line. On a robot, a wrong line can make pitch, roll and the turn speed wrong, and it can start the yaw at a wrong angle. So check it on the real robot. With the Hardware Check, turn left, and yaw goes UP. In TeleOp with field-centric, stick up goes away from you. - STOP works like on a robot: a `sleep()` ends at once. An OpMode that ignores STOP for 3 s loses the hardware: restart the simulator to run another. - Each INIT here forgets `MatchMemory.chosen()` and the start spot of the last program. So the simulator does not put the robot on an old program's spot. A real robot keeps them until a program sets them. So your own OpMode must not read them before it has set them. The library's autonomous and TeleOp do this for you. ## The page **Control Hub** (right): - the field from above, with the drivers at the bottom. To move the robot, drag it on the field, or type **x**, **y** and **heading**. Use the **Face** buttons, and tick **Snap** to go against a wall and line up with the tiles. These are the same controls as the auto builder's start spot, in the numbers that `s.start` takes. - the **Push the robot** buttons, folded. They roll the robot like a hand push, also while a program runs. So its wheels and odometry feel it: the Drive Tuner's push test uses this. - **Start over** (Back to start, Reset field). - every motor: power, count, speed, current, and "STOP" when it is at a hard stop. - every servo: where it is and where it is going. - the switches: click a switch to hold it pressed. - the cameras and the tags they see. - the battery voltage. Lower it to see a weaker robot. **Path lines** (on the field map and in the 3D view): an orange dashed line is the path that a Pedro `follow` step drives (the plan). A green line is where the robot actually went in its last 30 seconds of driving (the trail). The plan stays, faded, after its step ends, so you can compare the two. **Clear lines** clears both. Untick **Path lines** to hide them. More: [Pedro module](https://crossbotics.com/ftc-helper/docs/modules/pedro/#the-simulator). The robot is a gray box from the robot file (`robot.lengthIn` x `widthIn` x `chassisHeightIn`), with a white arrow at the front. It turns red when it bumps into something. Its shapes ([Robot shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-file/#robot-shapes)) move with their motors and servos. Rollers and wheels have dark stripes, so you see them turn, and which way. A roller glows **green** while it takes pieces in, and **orange** while it pushes them out. A flywheel or other spinner glows **yellow** while it turns. A passive part (moved by gravity or springs) **blinks yellow** while it moves. The page builds the field from the field file's shapes (tiles, walls, tape, solid and overhead parts). Each AprilTag is a square with its ID. With a 3D model of the field, the page shows that model instead, with the tag squares on top. The library has BIOBUZZ's model, made from FIRST's field CAD, and a robot file can name its own with `field.model`. "Field CAD model" in the **View** menu switches between them. Each camera shows as a cone (webcam yellow, Limelight green). "Camera view" in the View menu shows a camera's picture in the corner (pick the camera when there are two). The page redraws it 15 times a second, smaller than the screen, so it costs little. The game pieces are striped balls, so you can see them roll and spin. A tipping HIVE turns smoothly. With a rules file, the simulator turns it over its `tipSeconds`, and the page plays the same turn. Without one, the simulator tips it at once, and the page still turns it over half a second. The 3D library (three.js, MIT license) comes with the simulator, so the page works without the internet. On a slow computer, untick "Show the 3D view" in the View menu. The toolbar over the 3D view has the ways to look on the left. **View** sets where it looks from, and has the "Show", "Field CAD model" and "Camera view" boxes. **Layers** draws lines and maps over the field. The things to do are on the right: **Tests**, **Edit robot**, **Auto builder**. **Smooth motion.** The simulator moves everything 100 times a second. It sends the page where everything is 50 times a second (a stream: `GET /stream`), with its own clock. The page draws the moment about 1/20 s in the past, and glides between the two updates around it. So the robot and the balls move smoothly at any frame rate, and they do not jump 10 times a second. Across a jump (Back to start, Reset field, the robot put somewhere by hand), the page does not glide. When the stream cannot open (a very old browser, too many pages open), the page asks for `/state` 10 times a second instead. It still glides, but further behind. ### Where the robot starts **Where the robot starts.** On the page, INIT of an autonomous is a new match. Every game piece goes back where the match starts them (with the preload), and the robot goes to its start spot. A TeleOp's INIT keeps the field as it is, so the TeleOp goes on from the autonomous. Scenario files set up their own field. In INIT, the simulator puts the robot where the program says: - An autonomous that names its start spot (`s.start(note, x, y, heading)`, or `startSpotIn()` in an EasyAuto) puts the robot there, for the alliance chosen in its menu. - An autonomous with its spot only in words (`startPosition()`, or `s.start(note, heading)`) puts the robot on the chosen alliance's side (the robot file's start). The Driver Hub asks you to drag the robot to the exact spot. At ▶, the simulator remembers that spot for this autonomous (in `sim-start-spots.properties`, next to the simulator's settings). The next INIT puts the robot there. For the other alliance, it uses the same spot on that alliance's side. Or give the spot in inches in the code (`s.start(note, x, y, heading)`), so the robot goes there by itself. - A TeleOp with no autonomous before it places the robot when the drivers choose the alliance (X / B). RED gets the robot file's start. BLUE gets that spot's mirror image. Until they choose, the robot stands on BLUE's spot, and the page looks from the blue wall. The reason: the TeleOp says `Alliance : BLUE until you choose`, and aims and drives for BLUE. - After an autonomous, TeleOp leaves the robot where autonomous ended. ### The Match panel and the score bar With a rules file (BIOBUZZ has one: [Game rules and the score](#game-rules-and-the-score)), the Control Hub's **Match** button shows the game. A score bar sits over the 3D view: click it to open the panel. - **The score and the clock**: RED and BLUE, the period (AUTO, TELEOP, "AUTO done", FINAL or free play) and the time left. **The score counts like a referee** (manual 10.5). HIVE TIPs count when they happen. LEAVE and AUTO PARK count at the end of AUTO. Pieces in the CELLs, FLOWERs and GARDENs and TELEOP PARK count **only at the end of the match**. The reason: they change all match long (a TIP spills the CELL's pieces). Until then, they show **gray, as "+N"**: what they would add if the match ended now. When TeleOp ends (or you stop it), the score is **FINAL** and held. When you move the robot after that, it changes nothing. A new autonomous, or a TeleOp after a FINAL, starts a new match. BIOBUZZ starts each side at "+10": the field's own pieces in the up CELLs and GARDENs. - **Where the points come from**: click a side. The table has the same groups as FIRST's score calculator: AUTO (LEAVE, PARK, TIPs), TELEOP (TIPs, CELL, FLOWERs, the bottom NECTAR bonus, GARDEN, PARK), FOUL (the other side's fouls), the total, and the **RANKING POINTS**. These are SWARM (LEAVE + PARK points, 16 to earn it) and POLLINATOR 1 and 2 (4 and 7 TIPs). Each has a tick or a cross and the count. The end-of-match rows have a * until the end. A line says whether a NECTAR into a FLOWER is allowed now (G410). - **FLOWERs**: each FLOWER's owner, and its stack from the bottom up. Each piece is a dot in its color, and a hollow dot is outside the scoring rings. In 3D, a ring over each FLOWER shows its owner's color (gray: none) and how many pieces count. - **Shots**: the tally of verdicts (clean, rim, other HIVE, frame, miss) and the last few shots. In 3D, the page shows the verdict over the piece when the simulator judges it. The piece's trail (Layers: Ball trails) takes the verdict's color. - **Scatter**: off (every shot the same), realistic, rough, or as the robot file says (`/cmd action=scatter`). - **Hit rate**: 400 pretend shots from the robot as it is now (`GET /hit-rate`), judged like real ones. It shows how many go in cleanly, with its plus-or-minus, and the word Good (80 % or more), Risky (50-80 %) or Poor. It also says why the others did not go in. Pick the piece, or the next one in the robot. - **Fouls**: each foul charged (G407, G410), newest first. A new one shows over the 3D view for 5 s. ### Layers The **Layers** button over the 3D view turns each of these on or off. This browser remembers your choice. | Layer | What it shows | |---|---| | Camera sight lines | A line from the chosen camera to each tag in front of it. **Green**: the camera sees it (with about how many pixels across). **Pink "blocked?"**: the camera model sees it, but a field part is in the way of the line (the simulator's camera sees through field parts; a real one does not, so do not count on that tag from there). **Orange**: too slanted (the tag's face is turned more than 60 degrees from the camera). **Red**: too small (fewer pixels across than the tag finder needs: 6.5 per step of decimation, so 20 at the SDK's decimation 3). **Gray, faint**: out of the picture (left, right, above or below). **Purple**: the pretend lighting does not work with the camera's setting now (`goodPipelines`, `goodExposureMs`). Not seen: only the nearest four lines of each kind. The words at the bottom left list every tag. "Not open" means the OpMode has no camera running, so it gets nothing even where the lines are green. | | Camera view cone | The camera's view, 36 in long. | | Floor map | Where on the field the chosen camera can see tags: each 4 in square is shaded by how many tags the camera would see with the robot standing there (light: 1, darker: 2 or 3, darkest: 4 or more). The simulator works it out with the same camera rules the OpMode gets (field parts do not block in this map), with the robot facing the way it faces now, or, ticked "turned any way", the best of 24 headings. Turret and other parts stay as they are now. It updates once a second. | | Shot arc | Where each launcher would send its next piece if it fired now: a dashed yellow line from the launcher, with its peak height (check the venue's ceiling and lights). The simulator works it out from the flywheel's speed now, the shot angle (the hood's angle if it has one) and a shot table's average, with the same air drag and spin lift as a real shot, but it flies through everything (no goal, no walls, no other pieces). The words at the bottom left give the angle, speed and peak ("shoots backward, 33° up" for a launcher that throws over the robot's back); a stopped flywheel says so. | | Ball trails | The last half second of each loose ball's path, in its color: how it flew and bounced. | | Path lines | The Pedro plan and the trail (the same as **Path lines** in the Robot tab). | | Robot size box | A box around everything the robot has out now (green while it fits 18 x 24 in and 29 in tall, red when not; worked out from the shapes' boxes, not the CAD models) and the 18 in start cube, dashed. | ## Motors and the parts catalog The simulator moves each motor by the same "feedforward" model that a real motor follows. The model: power (at 12.8 V) = kS (to start moving) + speed / maxTicksPerSec + accelSec / maxTicksPerSec x speeding-up (+ gravity for a lift). Without measurements, it uses the parts catalog's top speed and typical values. To make the simulated robot move like YOURS, measure it with the Characterizer ([Real speeds](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/#6-real-speeds-optional)). The settings the Characterizer fills in (`./gradlew :sim:fit`, or the lines it shows on the Driver Hub): | Setting | Means | | --- | --- | | `drive.kS`, `drive.maxTicksPerSec`, `drive.accelSec` | the wheels: power to start moving, speed per unit of power (counts/s), seconds to reach ~63% of a new speed | | `drive.turnDegPerCount` | degrees the robot turns per wheel count of turning ((left - right) / 2): wheels slip when a robot turns | | `motor.NAME = ..., kS=, maxTicksPerSec=, accelSec=, gravity=` | a lift or arm (gravity = power that holds it) | | `motor.NAME = ..., kS=, maxTicksPerSec=, accelSec=, coastSec=` | a flywheel (coastSec: seconds to lose ~63% of its speed with power off) | `maxTicksPerSec` is the speed gained per unit of power: at full power, the speed is (1 - kS) x this. When the Characterizer runs in the simulator, it writes its logs in `sim/build/sim-data/characterizer`. `./gradlew :sim:fit` (no -Plog) reads those. A test (SimCharacterizerTest) gives the simulated robot known numbers and checks that the fit finds them again. `sim/parts/parts.json` lists the common FTC motors and servos with their real part numbers. Their numbers come from the seller's page, with the date someone checked them. The list has goBILDA Yellow Jacket (5203 and 5204, every ratio), REV HD Hex (bare, UltraPlanetary combinations, spur gearboxes) and Core Hex, AndyMark NeveRest, goBILDA 2000 series servos, REV Smart Robot Servos and Axon servos. A robot file names a part by its `id` (`part=gobilda-5203-312`). The simulator takes these numbers from it. For a motor: the top speed, encoder counts per turn and current. For a servo: the speed and range. When the seller does not publish a number, the catalog leaves it empty, with a note. The catalog uses real ratios (an UltraPlanetary "5:1" is 5.23:1). Servo speeds use the seller's row closest to 5 V. A Control Hub servo port gives about 5 V, and the headline number is often for 6 V. Motor kinds: - `free`: it only spins. - `lift`: hard stops, gravity. - `flywheel`: it coasts. While its `feeder` (a motor or a CR servo) runs, pieces go through and slow it down. One piece goes each time the feeder starts, then one every 0.3 s from 0.45 s on. `ticksPerRev=` sets a motor's encoder counts per turn (default 537.7; flywheel 28). On a robot, `setPower` in RUN_USING_ENCODER aims for the top speed of the motor TYPE chosen in the configuration. Here it aims for the robot file's `maxTicksPerSec`. The wheel motors are on the left/right sides of the robot, like on a real one, with one side's motors mounted mirrored. So motor directions in your code matter here too. That side is the left unless `drive.mirrored = right`. Write the side that your code reverses to drive straight (goBILDA's starter bot reverses the right one). If your code drives forward with negative power, write the other side. Check it: the drive stick forward must drive the robot forward. ## Physics The robot moves with a physics engine (ode4j, pure Java). The wheels say how fast the robot wants to go. The drive pushes the robot's body toward that speed as hard as the wheels' grip allows. Walls and the field's solid and overhead parts are solid shapes: each part's footprint, from its lowest to its highest point. The robot stops at them or slides along them. Its parts (the robot shapes) hit them too: a tall lift can hit the HIVE's overhead frame. When something blocks the body, the wheels keep turning (they slip). So the wheel encoders keep counting while the robot pushes, like on a real robot. An encoder-driven autonomous can "arrive" while the robot is pinned. The body follows the wheels a little behind: its grip takes about 0.02 s to catch up. So an encoder-driven autonomous ends within about half an inch of where `physics = simple` would put it. Limits: - The engine holds the robot flat, so it never tips or climbs. - The robot's parts are solid boxes on it, and they do not stop their own motors. An arm that swings into the HIVE pushes the robot, and the arm does not stall. - Field parts are simple prisms: a FLOWER is solid all the way up. Coordinates: inches from the field center, +x to the right and +y away from the drivers (drawn at the bottom), z up from the tiles. Headings and tag facing are in degrees, counterclockwise from +x for tags. ### The size check at full reach The simulator checks the size rules with the robot's shapes: the 18 in start cube, and 18 x 24 in and 29 in tall (R105). It checks them now and **at full reach**, with every moving part tried over its whole range. The Control Hub panel shows the sizes in green or red. How the simulator checks "at full reach": it tries every combination of the moving parts' important values. A slide or claw is biggest at an end of its range. It tries a hinge (arm, turret) at both ends, at each multiple of 90 degrees, and every few degrees between. That is every 5 degrees or less with a few moving parts, and coarser with many, to stay under 50,000 poses. The panel shows the worst pose. It is a careful check, not a proof: leave a little margin, and measure the real robot at its hard stops. ## Game pieces With the physics engine, the field file's game pieces are on the field. BIOBUZZ: the 4 POLLEN in each GARDEN. The sizes (POLLEN 2.8 in and NECTAR 3.6 in) come from manual 9.8. The weights (25 g and 41 g) come from AndyMark's am-5851/am-5852 pages, not the manual. The pieces roll and bounce, and the robot pushes them. The FLOWER tops are goals (the opening's center and height measured in the FLOWER CAD). The robot file says which robot shapes handle the pieces: its `collect.`, `shoot.` and `grab.` lines ([The robot file: game pieces](https://crossbotics.com/ftc-helper/docs/reference/robot-file/#game-pieces)). The match starts with every piece that the manual stages on the field (10.3.1). The simulator places them from the official field CAD: 4 POLLEN in each GARDEN (loose on the tiles), 4 POLLEN in each FLOWER and 3 NECTAR in each upward CELL. A FLOWER is solid above its bottom opening, the Retrieval Opening. That opening is 9-99 mm up, and open toward the field and both sides. So the POLLEN above the opening hold their places (the field file's `stacks`). The bottom POLLEN sits in the opening as a real piece. It stays still until the robot or another piece comes near, and a part that reaches in can knock it out. An intake running inward (or a closed claw) at the opening takes it. Either way, the next one drops into its place about 0.12 s later. The robot rolls over the FLOWER's thin floor plate (0.35 in), and pieces rest on it. The colors are the screen colors of the field file, not a real sensor's. Measure the real ones with the Piece Tuner (it also runs here). A motor or CR servo feeder sends one piece each time it turns on. If it keeps running, it sends one more every 0.3 s from 0.45 s on. So keep an indexer's `feedSec` under 0.45 s. Otherwise one feed fires two pieces here, and the count is off by one. With `stopOnShot = true`, the feed stops at the shot, so a longer `feedSec` is fine. A second webcam's colors are not simulated: it says "not found" and sees nothing. **Rollers turn the pieces they touch.** A roller or spinner (any `roller` or `flywheel` shape) drags a piece along with its surface. It moves the piece at up to its real surface speed, as far as the grip allows. So spinners can pull a piece in, or fling one away, even when the robot cannot take it (when it is full). **The HIVEs tip** (manual 9.6, 10.5.1). Each CELL is an open box from the field CAD: its floor, back, sides and roof. It is about 20 x 14 in open and 12 in deep. So a shot can go in, roll down to the back and stay. The 3 staged NECTAR rest in each up CELL. A piece counts when it has come to rest in a HIVE's up CELL (slow for 0.3 s). When those pieces weigh 187 g or more, the HIVE turns 60 degrees. The number comes from the team's field tests: no tip at about 175 g, and a tip at about 199-200 g. The 3 NECTAR are 123 g, so the 3rd POLLEN tips it. When the HIVE turns, the other CELL comes up, and the pieces in the CELL that went down fall out. The 8 AprilTags on its CELLs move with it, and cameras see them where they are now. The HIVE turns over 2 s (slow, fast, slow). That is the rules file's `tipSeconds`, an estimate until someone films a real tip: real HIVEs tip slowly. Its CELLs carry their pieces and push what they meet. The HIVE counts as TIPPED when it gets there (10.5.1). In a match, only LAUNCHED pieces may tip it (10.5.1, G417). A robot may not catch what falls out until it has touched something else (G409). The simulator does not referee either rule. The page shows the pieces in each up CELL (they score if they are still there at the end) and the tips. When a piece goes over a wall, the simulator takes it off and counts it ("left the field"). `print pieces` lists it all. Scenario checks: `expect cell "Red" >= 2`, `expect tips "Red" >= 1`, `expect left >= 1`. The 3D view shows what the robot holds, in its top-left corner. It shows a dot in each piece's color, an empty dot for each free place (its `holds=`), and the count ("In the robot: 3 / 4 · 3 POLLEN"). On the page (Control Hub, Robot tab): - **Back to start** puts the robot on its start spot, and every piece where the match starts it. - **Reset field** puts the pieces back and leaves the robot where it is. - **Preloaded** (ticked by default) gives the robot the preload now and at every reset. Untick it for an empty robot. In the robot file, `preload = off` starts the robot empty. In a scenario, use `set preload on|off` and `set field start`. Scenario lines: `set piece POLLEN X Y [Z]`, `set scatter off|realistic|rough|file`, `expect stored >= 1`, `expect launched >= 1`, `expect scored "FLOWER" >= 1` (pieces that went into goals whose name has the text; `"all"` = every goal), `expect cell "Red" >= 1`, `expect tips "Red" >= 1`, `expect left >= 1`, `expect points "red" >= 20` (the alliance's match points now), `expect clean >= 1` (shots that went cleanly into an up CELL), `print pieces` (also the points and the shot verdicts). Not in the simulator yet: - the alliance areas' NECTAR (the human player's, and the one a tip lets them enter, G426). - the HIVE's arm between its CELLs: a piece there passes through. - the tip judged at the damper (10.5.1). The simulator calls it TIPPED when the turn ends. - a held piece's weight on the arm. - robot parts that stop when they hit a piece. How far a ball rolls on the tiles is a guess (about 2 m from 1 m/s) until someone times a real one. What the rules cover and what they do not: [Game rules and the score](#game-rules-and-the-score). ## Game rules and the score A season's rules sit in a second file next to the field file: `sim/fields/biobuzz-2026.rules.json`. Someone types it by hand from the game manual, and each part says which section. (A script makes the field file itself from the CAD.) With the rules file, the simulator plays by the manual and keeps the score. Without one (an older or home-made field), the simulator counts a piece in a goal and takes it off. HIVEs tip at once, and there is no score. What it models (BIOBUZZ, Competition Manual TU01): | Rule | Manual | In the simulator | | --- | --- | --- | | Pieces stay in a FLOWER | 9.7 | A piece that falls into the top lands on the FLOWER's stack (each piece resting on the one below; the lowest in or on the lower ring). A full FLOWER (8 POLLEN) takes no more: the next one stays on top. | | FLOWER scoring volume | 10.5.2 | A piece at least partly between the middle ring's top (5.26 in, field CAD) and the top ring's top (21.4 in) counts. At the start, 3 of each FLOWER's 4 POLLEN are in it; the bottom one is not. | | FLOWER owner | 10.5.2 | The alliance with the top-most NECTAR in the volume owns the FLOWER: 2 points for every piece in it, whoever put them there. | | Bottom NECTAR bonus | 10.5.2 | 5 points to the alliance with the bottom-most NECTAR in the volume. | | NECTAR in the last minute | G410 | NECTAR into a FLOWER before the last 60 s of TELEOP (or in AUTO) is a MAJOR FOUL: 20 points to the other alliance. It still counts in the FLOWER. | | No more than 4 at a time | G407 | A MAJOR FOUL (20 points to the other alliance), once per match, when it looks STRATEGIC: 6 or more pieces in the robot at once, or 5 for more than 3 s (MOMENTARY), twice. 5 for a moment is no foul. The simulator takes as many pieces as `holds=` lets it. | | Only POLLEN from the bottom | 9.7, G418 | A NECTAR is too tall for the Retrieval Opening: once it is the lowest piece it stays in, and nothing above it can be taken out. | | HIVE TIP | 10.5.1 | 20 points to the HIVE's alliance, AUTO or TELEOP by when the turn ended. | | Pieces in the up CELL | 10.5.1 | 2 points each (the 3 staged NECTAR count too), for the HIVE's alliance. | | GARDEN | 10.5.3 | 1 point for each piece at least partly in a GARDEN (center under 6 in: the manual gives no height), for that GARDEN's alliance. | | LEAVE, PARK | 10.5.4 | At the end of AUTO: LEAVE (3) if the robot no longer touches the wall, PARK (5) if it is at least partly in its LOADING ZONE. TELEOP PARK (5): where it is now. | The robot is the alliance that its program chose in the INIT menu, or red when the program chose none. The match clock comes from the Driver Station. A running autonomous is AUTO (30 s). A running TeleOp is TELEOP (2:00). "Seconds left" counts down from the TeleOp's ▶, even with the TeleOp timer off. With no OpMode running, it is free play: no fouls, and tips count as TELEOP. The score is live ("if the match ended now"). It starts again at "Back to start", at "Reset field" and when an autonomous starts. Not modeled: - the other three robots. - the human player and the alliance areas' NECTAR (one per tip, all of them in the last 60 s). - the 8 s transition between AUTO and TELEOP. - every other foul (G408 opponent NECTAR, G409 catching what a tipped HIVE drops, G417 touching the HIVE, and so on), and G407's VERBAL WARNING and YELLOW CARD. FLOWER points scored before the last minute count, as the manual says ("still scored, but subject to penalties"). The simulator charges only the NECTAR foul (G410) and the 4-piece foul (G407). The simulator is not a referee: it counts what it can see. ## Clean shots, scatter and the hit rate **Each shot gets a verdict.** The simulator judges it the same way as the team's turret shot simulator (a line-by-line port of its `judge()`): - **clean** when the shot comes through an up CELL's opening going down at least 10 degrees, and clears the rim by its own radius. Before that, it touched neither the frame, the outside of its own CELL nor the other HIVE. - **rim** when it touched the rim going in: it may bounce out. - **other HIVE** or **frame** when it would have gone in, but hit that first. - **miss** otherwise. The simulator keeps the last 20 shots' verdicts and a count of each, for the page and `print pieces`. The judge's rule gives the verdict. The physics decides whether the piece stays in (and tips the HIVE). For the judge, the CELLs count 1 in bigger (the frame tube, as in the turret simulator). The HIVE frame is the field file's blocks. The arm between the CELLs is not there (it is not in the physics either). A test (`SimCellJudgeTest`) checks the port against the turret simulator's `judge()` on 600 shared shots, 120 of each verdict. They agree on every one. **Scatter.** Real shots differ: the ball's wear and size, the wheel speed, the hood's play. On the `shoot.` line, `scatter=realistic` makes each shot differ a little. One standard deviation is: exit speed 1.5 %, launch angle 0.35 degrees, aim 0.25 degrees left-right, spin 10 %. The first three are the turret simulator's "Realistic" for a launcher without a feed table. The spin share is a guess. `scatter=rough` gives about double, and `scatter=off` (the default) gives none. You can set each part on its own: `scatterSpeed=` (%), `scatterAngle=`, `scatterAim=` (degrees), `scatterSpin=` (%). Ball wear: `wear=red NECTAR:8+blue NECTAR:8` adds that much speed spread (%) for those pieces. In the turret's feed model, a new NECTAR leaves about 30 % slower than a medium one at the same settings. Balls a quarter of that apart give about 8 %. With a shot table, the table's spread replaces the speed, angle and spin parts, and aim and wear still apply. The page can switch every launcher at once (`/cmd` `action=scatter`: off, realistic, rough, or `file` for the robot file's). In a scenario, use `set scatter realistic`. **Hit rate.** `GET /hit-rate` (for the page) fires 400 pretend shots from where the robot is now. The shots are not on the field, so nothing moves. They use the launcher as it is now (wheel speed, hood, the robot's own speed) and the scatter (realistic if scatter is off). The simulator judges each one, for example "57 % clean (plus or minus 5), Risky". **Good** is 80 % or more, **Risky** 50 to 80 %, **Poor** under 50 % (the turret simulator's words). It assumes an empty CELL and single shots. For the page (and your own tools): - `/state` has a `game` object: the clock, the score by alliance and by kind, each FLOWER's stack and owner, each HIVE's tip progress, the last shots' verdicts, the scatter and the fouls. - `GET /hit-rate?n=400&piece=POLLEN` answers with the hit rate as JSON. - `POST /cmd` with `action=scatter&mode=realistic` sets the scatter. ## How shots fly, and shot tables A shot leaves the launcher shape at `angle=` (degrees up from its forward; default 40). Its speed is `share=` of the wheel's rim speed (default 0.5: a guess). It has `spin=`: 1 = backspin as if the ball rolled along a still hood, -1 topspin, 0 none. In flight, the air slows it. The drag uses Cd 0.5 (the drag coefficient). That is a guess: nobody measured it for POLLEN or NECTAR. A piece type can set `dragCd` in the field file. Spin lifts or drops the shot: the Magnus force, with lift coefficient = radius x spin / speed, at most 0.5. **A hood.** With `hood=SERVO, hoodAt0=80, hoodAt1=30`, the shot angle follows where that servo is, instead of `angle=`: 80 at position 0, 30 at 1, and a straight line between. With a shot table, the table's scatter goes around the hood's angle. `:sim:fromRobot` writes it for a launcher whose `Hood.servo(...)` has `shotAngles(atA, atB)` (the shot angle at the hood's two stops). A motor hood does not move the shot angle in the simulator yet. **Shot tables** replace the guesses with how the real launcher throws: `shoot.NAME = shape=flywheel, table=launcher-table.json`. For each piece and wheel speed, the table gives the likely exit speed, angle, spin and exit point, and how much they scatter. Each shot picks its numbers from that spread, so shots scatter like real ones. A share of feeds that do not become shots drop out. Make a table with the **launcher program** (`tools/launcher/`). It cuts your robot's CAD along the ball's path. It runs many shots through it, with the ball as a soft disc squeezed against the spinning wheel and the hood. The CAD cannot give some numbers. So it tries them over ranges: how soft the balls are, how much the wheel and hood grip, where the ball comes in. Then it writes the table. It is still a model: film a few real shots (a phone's slow motion, next to a tape measure) and compare. ## Cameras With a webcam in the robot file, your real camera code runs: `WebcamTags`, or the SDK's own `VisionPortal` and `AprilTagProcessor`. The simulator has pretend copies of the SDK's camera classes, made by the SDK's own builders. What it does: the camera opens about 1 s after the OpMode makes it, then sends 30 pictures a second. For each picture, it works out which of the field file's AprilTags are in view. A tag is in view when it is inside the picture and faces the camera (within 60 degrees). It must also be big enough to find at the OpMode's decimation. That is about 6.5 pixels across per step of decimation, which matches the FTC docs' ranges. The simulator then turns the tags into the SDK's own detections, the way the SDK makes them. A tag in one of the tag library's clusters gives a cluster detection. BIOBUZZ: the SDK 12 library has one cluster per CELL group of 4 tags, "RED SCORING" and so on. Any other tag gives a single-tag detection, without a pose when the library does not know the tag. `ftcPose` uses the SDK's own formulas, so range, bearing (positive = left) and elevation mean the same as on the robot. On the page, the Control Hub panel lists each camera with the tags in its picture and what it found. The 3D view draws the camera's view as a cone on the robot (webcam yellow, Limelight green). "Camera view" shows the picture from the camera, and the tags it sees turn green. A camera on a turret (`on=turret`) moves with the turret in the 3D view too. The **Layers** menu draws the camera's sight lines to the tags, with the reason it cannot see each one. It also draws a floor map of where the camera can see them ([Layers](#layers)). The hardware map gives your code a Limelight3A: the SDK's own class, with its network part replaced. So `LimelightTags` and code that calls `getLatestResult()` directly work. About 0.5 s after `start()`, it sends 50 results a second. The simulator makes them as the same JSON a real Limelight sends. The SDK's own `LLResult` reads them: `isValid()`, `tx`/`ty`/`ta` (the biggest tag), and one `FiducialResult` per tag. A Limelight does not group tags into clusters. Each result has `tx` (+ = right), `ty` (+ = up), `ta`, the pixel position and `getTargetPoseCameraSpace()` (meters; x right, y down, z out of the lens). Every pipeline finds AprilTags, and `pipelineSwitch` changes the index it reports. Not simulated: botpose / MegaTag (no field map), robot-space poses, Python, color and neural pipelines, snapshots. Limits: - The poses are exact: no noise, blur or lag beyond the Limelight's reported latency. - Field parts do not block the view. - The camera does not find tags slanted more than 60 degrees. - The webcam's `robotPose` is always null. - Only the AprilTag finder gets webcam pictures. Other VisionProcessors get `init()` and nothing more. - Phone cameras are not simulated. - The resolution comes from the robot file, not from `setCameraResolution`. --- # Two parts that must not collide (interlocks) URL: https://crossbotics.com/ftc-helper/docs/guides/interlocks/ An **interlock rule** says: *these two parts are never in their zones at the same time.* You write it once, in `Robot.java`. The library keeps to it every loop, in TeleOp and in autonomous. It does not matter what moves the part: a button, a stick, an action, a turret following the goal, an autonomous step. Reference: [Interlock in the robot module](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/). Quick recipe: [How do I stop two parts from hitting each other?](https://crossbotics.com/ftc-helper/docs/cookbook/07-turrets-and-interlocks/#how-do-i-stop-two-parts-from-hitting-each-other) ## The idea, with a turret and a lift Take a robot with a turret in the middle and a lift at the back. When the lift's slide is up, the turret must not point backward, or the shooter hits the slide. When the turret points backward, the lift must not rise. The numbers below are an example. The [V2 robot](#the-v2-robot) uses a turret and wrist rule instead. ![The turret's zone and the lift's zone, seen from above and from the side](https://crossbotics.com/ftc-helper/docs/images/interlock-zones.svg) Each part gets a **zone**: the space it must stay out of while the other part is in its own zone. - The turret's zone: from 109 to 239 degrees (straight back is 180, and counterclockwise is +). Say the lifter's parts are at 142 to 206. The turret's own parts reach 33 degrees to each side of where it points. Add 33 degrees on each side, and you get 109 to 239. - The lift's zone: above 270 encoder counts (84 mm). At this height the slide starts to be in the turret's way. ```java // Robot.java, after the parts: keepApart("TurretLift", turret.zone(), lift.zoneAbove()); ``` ```java // Tunables.java: the numbers, in each part's own units public static class TurretLift { public static double turretFrom = 109, turretTo = 239; // degrees public static double liftAbove = 270; // counts public static double liftStopSec = 0.2; // optional: see "Stop distance" } ``` The section name is the rule's name. Each field name starts with the part's Tunables name, with a small first letter: `Turret` gives `turretFrom` and `turretTo`, and `Lift` gives `liftAbove`. ## Who waits? The rule: **the part that is in its zone first keeps it. The other part waits outside its own zone.**
flowchart TD
    A{"Is one part in its zone?"} -->|"the turret is"| B["The lift waits below its line.<br/>Its target is kept: it goes on<br/>when the turret leaves."]
    A -->|"the lift is"| C["The turret waits at the edge of its zone<br/>(or goes the other way round,<br/>if its range allows)."]
    A -->|"neither"| D{"Does one want in?"}
    D -->|"yes"| E["That one goes in.<br/>(Both at once: one too fast to stop<br/>before its zone, else the first one<br/>named in the rule.)"]
    D -->|"no"| F["Nothing to do."]
    A -->|"both!"| G["Neither may go deeper.<br/>Each may only move OUT.<br/>The first one out lets the other keep its zone."]
The Driver Station shows one line per rule, only while the rule holds a part back: ``` TurretLift : Lift held at 110 counts: Turret is between 109 and 239 deg TurretLift : Turret held at 124 deg: Lift is above 270 counts TurretLift : both in their zones (...): move one out (each may only move out) ``` **How a waiting part waits.** It stops two **margins** before its zone. The margin is a safety distance in the part's units. By default it is 3 degrees for a turret, about 1/50 of a lift's range, and 0.02 for a servo. The part keeps its target, so it goes on by itself the moment the other part leaves. A part within one margin of its zone counts as "in its zone". ### Stop distance: a fast part brakes in time A motor does not stop the moment the library tells it to. Two things carry it on: 1. **The loop.** The robot looks and decides only once per loop. A loop usually takes 10 to 30 ms. A camera, a busy hub or a slow sensor can make some loops 100 ms or more. Until the next loop, the part keeps going at full speed. The position it reads is from the last loop, so count that loop too. 2. **Braking.** With its power cut (BRAKE), a motor still coasts a little while it slows down. So every loop, the rule measures each motor part's **speed** (from its encoder). From the speed it works out the part's **stop distance**: how far the part would still go if the library told it to stop now. ``` stop distance = speed x (2 x the slowest of the last 25 loops + half of StopSec) ``` A part that must wait may use only the power that lets it stop in time. It slows down as it comes near its waiting point. It brakes (power 0) as soon as its stop distance would take it past that point. The rule gets the part's top speed from its motor (`Turret.motor(..., "gobilda-5203-312")`, `Arm.motor`, `Lift.slide(...).part(...)`), or from the fastest the rule has seen it move. Example: the v2bot's turret turns about 680 degrees a second. In the simulator, push the stick fully toward the back with the wrist folded. The turret slows down and stops at its waiting point (-137), 6 degrees outside its zone. It does this even when the computer is so busy that loops get slow. A part that moves so fast that it **cannot stop before its zone** counts as already in it. The other part waits, so the two never both start into their zones. `StopSec` (optional, default 0.15 s) is how long the part takes to stop from full speed once the library cuts its power. A heavy slide or a big turret may take longer. To test it, push the stick fully toward the zone. If the part ever ends past its waiting point, raise that number. The margin is then extra safety on top (for an encoder that slips, or a part that bends). The part does not need it to coast. A servo needs no stop distance: the library never sends it past its fence. Until its `travelSec` is over, the servo counts as anywhere between where it was and where it was sent. **A part whose way crosses its zone.** Take a lift at 0 that you send to 1000, through a zone from 400 to 600. It asks for the zone, the same as for a target inside it. It goes when the other part is out, and the rule then holds the other part out. Without this, the lift would wait below the zone for ever. **A turret crossing its zone.** Take a turret at 80 degrees that you send to 250 degrees (the same direction as -110). Turning counterclockwise, it would pass through the back (109 to 239). When its range lets it reach -110 the other way round (a range like -190 to 190, or a slip ring), it turns clockwise instead and never waits. When it cannot (a range of -90 to 90 cannot reach either angle), it stops at 103 (two margins of 3 before 109). It waits there while the lift is up. **Both in their zones.** This should never happen, but it can. It can happen at ▶ (start on the Driver Hub), after another robot pushed yours, or after someone moved a part by hand. Then no part keeps a zone. Neither part may go deeper, and each may only move out. As soon as one is out, the other keeps its zone. **A part whose position is not known.** A turret that has not found its home switch yet could point anywhere. A servo cannot say where it is. Until the library knows their positions, they count as "maybe in the zone", so the other part waits. A servo counts as anywhere between where it was and where it was sent, until its `travelSec` says it has arrived. So when a wrist must be folded before the lift goes down, the lift does not move until the wrist is surely folded. The Driver Station says why the other part waits: ```text TurretLift : Lift held at 110 counts: Turret angle unknown (not homed yet) TurretLift : Lift held at 268 counts: Turret angle unknown (not sent anywhere yet: it goes to its start angle when ▶ is pressed) ``` The library sends a servo turret to its `startAngle` (or the middle of its range) at ▶. So this lasts only until the first loop after ▶. **And the other way round:** a part whose position is not known does not move at all while the other part is in its zone. That means no homing, no stick, no first servo move. From "anywhere", it could sweep through the zone. A turret waits to home while the lift is up, and it homes as soon as the lift is down. Its homing time limit waits too. A first move that cannot go into the zone from anywhere does not wait. An example is a wrist sent to "folded", below a zone at the top of its range. ```text TurretLift : Turret waits (not homed yet): Lift is above 270 counts; move Lift out of its zone first ``` **At ▶**, the rules look first, before the library sends any start command: a hood going to its `startAngle`, a turret homing, an `atStart` action. A start command into a zone the other part is in waits at the fence, like any other command. ## More examples **A wrist that must be folded before the lift goes low.** The wrist sticks out past the slide. Low down, it would hit the robot's frame. ```java keepApart("WristLift", wrist.zone(), lift.zoneBelow()); public static class WristLift { public static double wristFrom = 0.45, wristTo = 1.0; // servo positions: folded out public static double liftBelow = 300; // counts: low } ``` **An arm that must not come down while the intake is folded out.** ```java keepApart("ArmIntake", arm.zoneBelow(), intakeDeploy.zone()); public static class ArmIntake { public static double armBelow = 30; // degrees public static double intakeDeployFrom = 0.5, intakeDeployTo = 1.0; } ``` **A claw that must be closed above a height.** ```java keepApart("ClawLift", claw.zone(), lift.zoneAbove()); public static class ClawLift { public static double clawFrom = 0.0, clawTo = 0.6; // anything short of closed (closed = 0.75) public static double liftAbove = 1800; } ``` **Something the library cannot move** (your own sensor or device): use a condition. ```java keepApart("ArmBucket", arm.zoneBelow(), Zone.when("the bucket is up", () -> bucketUp.isPressed())); ``` You can write any number of rules, between any parts with a position: turret, lift, arm, claw, wrist, positioner, hood. A robot with no rules works the same as before. ## Checked at INIT The OpMode stops at INIT and gives the reason when: - a rule has no Tunables section. - a number is missing. - a zone is empty (from is not below to). - a zone is outside the part's range, or covers its whole range (the part could never be out of it). - a margin is negative. - a `StopSec` is outside 0 to 2 seconds. - a part has no position, like an intake roller. Use `Zone.when` for it. The INIT screen lists each rule: `Interlock TurretLift: Turret between 109 and 239 deg / Lift above 270 counts`. A rule with a part that is not on the robot yet is off ([`optional()`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet), its device not in the configuration). There is nothing to hit, so the rule needs no Tunables section and holds nothing back. INIT says `Interlock TurretLift: off (Lift is not on the robot)`. ## Why the numbers are not live A zone that moved while the parts were moving could suddenly put both parts in their zones. So the library reads the zones once, at INIT, and they are not in the tuning menu. Change the numbers in `Tunables.java`, then INIT again. ## What it does not do - It does not replace hard stops, and it does not see another robot pushing yours. - It does not move a part out of the way by itself, so there are no surprise moves. A waiting part waits, and the drivers move the other one. - It knows only what you tell it. Measure the zones on the real robot: move one part slowly into the other by hand, and write down where they touch. Then add the margins. ## The V2 robot The [v2bot example](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/v2bot/Robot.java) has a turret and a lift with a wrist and a claw. Its rule comes from team 8938's measured designs (turret v8.1GB and the "pincer" lifter): `keepApart("TurretClaw", turret.zone(), wrist.zone())`. Its claw reaches the turret only while the wrist is folded or at pick-up (0 to 47 degrees), at any lift height. So the rule is between the turret and the **wrist**, not the lift. The turret stays out of 147 to 217 degrees while the wrist is low. The reasons and the numbers are [below](#the-turretclaw-rule). Each number that nobody measured on a built robot says "example" in its `Tunables.java`. The robot, part by part: - A mecanum drive with a goBILDA Pinpoint (odometry). When the camera loses the goal, the turret keeps aiming from the robot's place. - An intake, a color sensor that counts the pieces (BIOBUZZ allows 4 at a time, G407), and an indexer servo that feeds the launcher. The `Pieces` line comes **above** the intake line, so the count is up to date before the intake asks "full?". - A turret on a goBILDA Gear-Driven Turret bearing, turned by a 312 RPM motor (2.75 motor turns per turret turn). It turns -190 to +190 degrees. At ▶ it finds its angle on a magnetic home switch ([Setting up a turret](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/#four-complete-examples), example A). - A flywheel launcher with a hood on a servo. It sets the speed and the hood angle from the distance to the goal. It fires only when the turret is aimed and there is a piece to fire. - A lift at the back: a goBILDA 4-stage Viper-Slide on a 435 RPM motor. On its top stage are a wrist and a two-finger claw. The wrist is a servo on an 8 mm axle across the slide. It swings the claw out the back, 0 to 145 degrees between hard stops (a stop collar and a pin). Run its TeleOp in the [simulator](https://crossbotics.com/ftc-helper/docs/simulator/). With the wrist folded, turn the turret toward the back with the stick: it stops at the edge. Then score in a FLOWER (G2 Y). While the wrist is out, the turret is free to turn to the back. At the end, the action folds the wrist again, and the rule is back on. A turret at the back then holds the wrist out: the wrist waits until the turret turns away. ### The V2 robot's buttons `Controls.java` writes out each part's usual buttons, all on gamepad 2 (the operator): - RT: intake in (held 1 s: in, even when the count says full). - LT: push out (hold). - LB: flywheel spin up/down. - RB: fire (hold: keep firing). - D-pad up/down: speed trim. - D-pad right: the next shot table. - Left stick Y: hood trim. - Right stick X: turret by hand. - Right stick click: turret following on/off (2 buzzes = on). - B: claw open/close. - D-pad left: the wrist's previous position. - Left stick button held 1 s: piece count = 0. `Controls.java` adds: A grab, Y score in a FLOWER, X stow the lifter, the lift by hand on the right stick Y, a buzz when the turret is on target, and the light's colors (orange while the rule holds a part back). Two parts' usual buttons can want the same button: the lift and the hood both use the left stick. `Controls.java` gives each one a button of its own: the hood the left stick, and the lift the right stick. ### The lifter's steps The actions in `Actions.java` keep team 8938's order: 1. Pick up with the slide down and the wrist 20 degrees out, so the ball is not under the robot. 2. Swing the wrist out to 90 degrees BEFORE lifting, then lift, then tip the wrist over the FLOWER. Drive there first: the robot's back to the FLOWER, about 28 mm away (the design's release point). 3. Coming back: wrist to 90, lift down, then fold. Each wait lets a part get there. For a servo, the wait is about its `travelSec`. For the lift, it lasts until the encoder says the lift arrived. Every wait has a time limit, so a stuck part never stops the robot for good: the action ends and says which step timed out. The rule is always on. While the turret points back, the wrist waits above 47 degrees by itself. Lower down, the claw would hit the turret, and the Driver Station says `TurretClaw : Wrist held at ...`. So `grab` first turns the turret forward. It lets the turret follow the goal again once the wrist is back out at carry. Scoring needs nothing: the wrist is out at 90 degrees and more, where the turret may point anywhere. `stow` folds the wrist last, and the wrist waits there if the turret points back. The same is true in autonomous: if a step raised the wrist into its zone while the turret pointed back, the wrist would wait. ### Where the V2 robot's numbers come from **The lift** (`Tunables.Lift`) uses encoder counts from the bottom stop. 0 is where the lift is at INIT, so start with the slide down. The top stage moves 120 mm per motor turn, and the 435 RPM motor counts 384.5 per turn. That gives 3.2 counts per mm (the lifter design log). - `pickup` 0: slide down. With the wrist at 20 degrees, the claw reaches a ball on the tiles. - `stowed` 44 (13.7 mm): the folded claw clears the tiles. - `flower` 1330 (415.1 mm): the ball over the FLOWER's top opening (wrist at 122.8 degrees). - `max` 1350: a little under the hard stop at 425.1 mm (1362). `min` 0: the bottom stop. - `kP` to `tolerance`: examples. Tune your own ([Add a lift](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/)). **The wrist** (`Tunables.Wrist`) uses servo positions. The goBILDA 2000 servo turns 0.15 degrees per microsecond of signal (300 degrees over 500-2500 us). The hub's normal signal is 600-2400 us, so 0 to 1 turns the servo 270 degrees: one degree is 1/270. The wrist needs only 145 degrees, so it keeps the normal range (no [`.fullRange()`](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/)). - Angles from straight down (the lifter design): folded 0, pickup 20, carry 90, flower 122.8. The hard stop is at 145 (0.637). - `folded = 0.10` is an example: find yours with the Servo Finder. Each other position = folded + degrees / 270 (pickup 0.174, carry 0.433, flower 0.555). - `travelSec` is for a full 0-to-1 move, which is 270 degrees on this servo. The Speed servo turns 60 degrees in 0.09 s, so 0 to 1 takes 270 / 60 x 0.09 = 0.41 s: write about 0.45. The library scales it, so the 145-degree fold waits its share (0.24 s). **The claw** (`Tunables.Claw`, the "pincer") has two fingers on one goBILDA Torque servo (2000-0025-0002), geared together. The fingers turn 1.2 times the servo's angle. Open: fingers at +17 degrees (servo +14). Closed on a POLLEN: -10 degrees (servo -8). A NECTAR stops them at 0. The positions around 0.50 are examples: find yours with the Servo Finder. **The hood** works like the turret robot's ([Add a launcher](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/#a-hood-the-shot-angle)). [Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/#when-the-camera-loses-the-goal-the-odometry) explains the aim's goal point (`goalX`, `goalY`). `shooterForwardIn = 1`: the turret's axis is 1 in forward of the robot's center (turret v8.1GB). It matters only when the robot shoots on the move, which is off until someone tests it on the real robot. ### The TurretClaw rule On 2026-10-22, team 8938 checked its pincer model against turret v8.1GB. No lifter part ever comes inside the turret's reach (201.1 mm from its axis). But with the wrist between 3 and 44.5 degrees, the claw body comes within 2 mm of that reach. This happens at +/-4 degrees of straight back, at EVERY lift height. With the wrist above 47 degrees (carry 90, flower 122.8), every lifter part is at least 206.7 mm away, so it is clear. - **The turret's zone.** The turret's parts farther than 190 mm from the axis sit from -32.3 to +28.8 degrees of where it points (the v8.1GB reach measurements). The claw is at 176 to 184 degrees. So they meet when the turret points from 176 - 28.8 = 147 to 184 + 32.3 = 217 degrees (0 forward, counterclockwise +, back = 180). In Tunables: `turretFrom = 147`, `turretTo = 217`. - **The wrist's zone.** 0 to 47 degrees (the measured 3 to 44.5, with a margin). In servo positions: `wristTo` = folded + 47 / 270 = 0.10 + 0.174 = 0.274. `wristFrom = 0`: the wrist cannot go below folded (its stop), so the zone starts at the bottom. When you change `folded`, change `wristTo` too. - **The lift needs no zone:** the wrist's rule covers every lift height. - **No `turretMargin` or `turretStopSec`:** the defaults fit. The turret is fast (a 312 RPM motor, 2.75:1: about 680 degrees a second). But the rule measures its speed every loop and slows it down near the zone ([Stop distance](#stop-distance-a-fast-part-brakes-in-time)). It waits two margins (2 x 3 degrees) from the zone: at 147 - 6 = 141 (or -143 + 6 = -137). On the built robot, push the stick fully toward the back. If the turret ever ends past its waiting point, raise `turretStopSec` (how long it takes to stop, default 0.15 s). On the field: while the wrist is folded or at pick-up, the turret aims anywhere from -137 to 141 degrees. Once the wrist swings out to carry, the turret may point anywhere again (its -190 to 190). --- # Setting up Limelight lighting pipelines URL: https://crossbotics.com/ftc-helper/docs/guides/limelight-lighting/ **For:** a team with a Limelight 3A that aims with AprilTags. **You need:** the Limelight, its USB-C cable, a laptop, and a printed AprilTag group (or the field). Every place has different light: a bright gym, a dim classroom, spotlights at an event. A camera setting that finds the tags well at school can miss them at an event. So you save three **pipelines** on the Limelight (a pipeline is one saved set of camera settings, by number). One is for your usual light, one for bright light and one for dim light. In INIT the robot tries each one, and keeps the one that sees the tags best ([the lighting test](https://crossbotics.com/ftc-helper/docs/modules/vision/#venue-lighting)). Reference: [Camera in the robot module](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/), [LimelightTags](https://crossbotics.com/ftc-helper/docs/modules/vision/). Limelight's own docs: [Limelight 3A Quick-Start](https://docs.limelightvision.io/docs/docs-limelight/getting-started/limelight-3a), [Tracking AprilTags](https://docs.limelightvision.io/docs/docs-limelight/pipeline-apriltag/apriltags). ## 1. Connect the Limelight to a laptop 1. Plug the Limelight into the laptop with its USB-C cable (the laptop powers it). 2. Wait until its status light is green (about 15-20 seconds). 3. In a browser, open **http://limelight.local:5801**. You can also open Limelight's Hardware Manager app, scan, and double-click the Limelight. You see the live camera picture and the settings. 4. First time only: in the **Settings** tab, set your team number, then click **Restart Vision Client**. The Limelight saves changes by itself. It has no "save" button. ## 2. Pipeline 0: your usual light Pick pipeline **0** in the list at the top of the page. Then: | Tab | Setting | Set it to | Why | | --- | --- | --- | --- | | Input | Pipeline Type | **Fiducial Markers** | "fiducial" = AprilTag | | Input | Resolution | the highest one | the library needs each tag's 3D position (its distance). More pixels give a steadier one | | Input | Black Level | **0** | Limelight's starting value | | Input | Sensor Gain | **15** | Limelight's starting value | | Input | Exposure | see below | | | Standard | Family | **AprilTag Classic 36h11** | the game's tags (manual 9.9) | | Standard | Marker size | **82.55 mm** | BIOBUZZ tags are 3.25 in (manual 9.9). A wrong size gives a wrong distance, and then the shot table picks the wrong speed | | Standard | ID filter | **empty** (or 30-45) | the library aims at the middle of a CELL's 4 tags and needs at least 2 of them. So do NOT filter to one tag | | Advanced | Full 3D | **on** | without it the Limelight gives no 3D position, and the distance reads NaN | **Exposure** is how long each picture collects light. Hold a tag group 4-6 ft from the camera, at the angle the robot will see it from. In BIOBUZZ the tags are under the CELLs, facing down, so the camera looks up at them. Start with Exposure low. Raise it until the 4 tags have steady boxes around them in the picture. Then move the tag a little. When the boxes drop out while it moves, the picture is blurred. Then lower Exposure a bit and raise Sensor Gain instead. **Lower exposure = less blur but a darker picture. More gain = a brighter picture, but grainier**, and too much gain makes the distance jump. ## 3. Pipeline 1 (bright) and pipeline 2 (dim) Set up pipelines **1** and **2** the same way as pipeline 0 (every row of the table). Change only: - **Pipeline 1, bright light** (sun through windows, event spotlights): **lower Exposure**, so the white parts of the tags do not wash out. When bright lights or windows still show as big white spots, raise **Black Level** a little (it darkens the picture). - **Pipeline 2, dim light** (a dark classroom, the back of a hall): **higher Exposure**, and more **Sensor Gain** when it is still dark. Test each one where you can: lights on and off, blinds open and closed. Each should keep steady boxes on the tags in its own kind of light. **Write the numbers down** (in the engineering notebook, or a text file in the robot project): each pipeline's Exposure, Sensor Gain and Black Level. A Limelight software update **erases the pipelines**. Limelight's docs say to back them up before you update. With the numbers, you can make them again fast. ## 4. Tell the robot In `Robot.java`, list the pipelines. Put your usual one first, because the first one wins a tie: ```java camera = add(Camera.limelight("limelight").autoPipelines(0, 1, 2).goal("BLUE SCORING", "RED SCORING")); ``` Put the Limelight back on the robot, in the Control Hub's blue USB 3.0 port. The first time, do this on the Driver Station: **Configure Robot**, **Scan**, and rename the new "Ethernet Device" to `limelight` (the name in `Robot.java`). ## 5. At INIT, and at an event Put a tag group in view at INIT. The spot where the robot starts the match is fine. The Driver Station shows the result, for example `limelight lighting : pipeline 2 (9 of 10 pictures saw tags)`. When the OpMode starts (▶), the test stops, and the camera keeps the best pipeline so far. **At an event:** in the queue (or on the practice field), INIT once with the robot facing a CELL's tags. Under the `limelight lighting` line, the Driver Station shows two lines. Copy them into `Tunables.Limelight`: ```java public static double pipeline = 2; public static boolean autoLighting = false; ``` Put them in with the laptop, and **install the app on the robot again**: the camera reads these numbers at INIT. Then every match at that event uses that pipeline, with no test. Back at school, set `autoLighting = true` again. **Copy tuned values back to `Tunables.java`:** a value changed live (in the tuning menu) is only on this Control Hub. The file is the record. ## If it does not work | The Driver Station says | What to do | | --- | --- | | `no pictures from pipeline 2 (missing?)` | the Limelight has no such pipeline, or its type is not Fiducial Markers. Set it up (step 3), or take it out of `autoPipelines(...)` | | the distance is NaN | **Full 3D** is off in that pipeline, or the marker size is missing | | the distance is wrong by the same share at every distance | the marker size is wrong. Set it to 82.55 mm | | no pipeline sees the tags | the camera cannot see under the CELL from where the robot is. Aim the Limelight up more, or test at the spot the robot shoots from | | `limelight` is not in the configuration | Configure Robot, Scan, rename the Ethernet Device (step 4) | **Live view on the robot:** you see the live picture above only with the Limelight plugged into the laptop. The library has no live view yet while the Limelight is on the robot. Nobody has tested the Limelight's page through the Control Hub yet. --- # A new season: what to do URL: https://crossbotics.com/ftc-helper/docs/guides/new-season/ **For:** the programming lead and mentor at the start of a season. **You need:** last season's robot project, and the new Competition Manual. FTC changes the game every September. It changes the SDK (the FTC software your code builds on) at least once a year. Most of the library carries over unchanged. Work through the checklist below in order.
flowchart TB
    K["Kickoff"] --> M["1. Read the manual:<br/>rules that touch code"]
    M --> S["2. New FTC SDK<br/>in the robot project"]
    S --> L["3. Library: test on the new SDK,<br/>update, release"]
    L --> T["4. TeamCode: this year's robot<br/>in the five files"]
    T --> V["5. This game's numbers<br/>(tags, field, autos)"]
    V --> D["6. Update docs + memory"]
## 1. Read the manual (the parts that touch code) Search the new Competition Manual for these topics. Update [README "Rules check"](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/README.md#rules-check-2026-27-biobuzz-manual-tu01) and anything below that changed: | Topic | Why it matters | 2026-27 (BIOBUZZ, TU01) | | --- | --- | --- | | Reusing software | whether teams may use the library | R304: allowed, also software made before Kickoff | | Size limits / extension | soft limits are not enough | R105 B: limits must hold WITHOUT software | | Match timing | `MatchTimer` lengths and cues | 0:30 auto, 8 s transition, 2:00 TeleOp; cues 1:00 and 0:20 | | Field symmetry | `Alliance.mirror` | check whether it is mirrored or rotated | | AprilTags | ids, sizes, and whether they move | tags on moving HIVE cells: aim yes, localize no | | Driver Station / controllers | gamepad buttons | | Also check the Team Updates during the season. ## 2. New FTC SDK In the robot project, follow FIRST's instructions. Usually you update `build.dependencies.gradle` and the `FtcRobotController` folder. Read the SDK release notes for **breaking changes** (2026-27: AprilTag detections split into single tags and clusters). Also check the SDK's normal servo pulse (`PwmControl.PwmRange.defaultRange`: 600-2400 microseconds in SDK 12.0). The library's servo degrees and `.fullRange()` assume it (`ServoSetup.SDK_PULSE_LOW_US`, `SDK_PULSE_HIGH_US`, and `SimParts.SDK_LOW_US`/`SDK_HIGH_US` in the simulator). ## 3. The library Gradle is the tool that builds the code. `./gradlew ...` runs it from the `ftc-helper-lib` folder. 1. Change `ftcSdkVersion` in `library/build.gradle`, `examples/build.gradle` and `sim/build.gradle` to the new version. 2. Build and test: run the checks in [Contributing](https://crossbotics.com/ftc-helper/docs/contributing/) (the Gradle builds and tests, and the `tools/check_*` scripts). 3. Fix what broke (often vision, sometimes hardware classes). Add a test for each fix. 4. Update `docs/02-keep-up-to-date.md` (the SDK version), `README.md` ("Works with") and the CHANGELOG. 5. Release a new version (see [Contributing](https://crossbotics.com/ftc-helper/docs/contributing/#releasing-a-version)). ## 4. TeamCode: this year's robot A robot is [five files](https://crossbotics.com/ftc-helper/docs/five-files/) in TeamCode: `Robot.java` (the parts), `Tunables.java` (their numbers), `Controls.java` (the buttons), `Actions.java` (jobs made of several moves) and one file per auto. Most of last season's files carry over. Change only what the new robot changes. 1. **A new robot, or a big change:** make the robot configuration on the Driver Hub first. Then the library writes the five files from it ([Start from a blank slate: your own robot](https://crossbotics.com/ftc-helper/docs/pick-your-start/03-blank-slate/#way-a-from-your-configuration)). A starter bot can start from its [ready files](https://crossbotics.com/ftc-helper/docs/pick-your-start/01-starter-bot/). 2. **`Robot.java`:** delete last year's parts, and add this year's: one `add(...)` line each ([the part pages](https://crossbotics.com/ftc-helper/docs/reference/)). Check the `drive(...)` and `odometry(...)` lines. 3. **`Tunables.java`:** delete the sections of the parts you removed. INIT lists every section a new part still needs. 4. **`Controls.java` and `Actions.java`:** put the new parts on buttons. Each part page has a "Buttons to add". 5. Run the Hardware Check, then the [finders](https://crossbotics.com/ftc-helper/docs/tuning/) for each new part. ## 5. This game's numbers (in TeamCode) The library knows the game (the field, the rules, the piece names, for the simulator). Your team's own choices go in TeamCode: | Thing | Where | | --- | --- | | Start spots, routes, field points | each auto's steps ([Building autos](https://crossbotics.com/ftc-helper/docs/building-autos/)) | | A field that is TURNED for red, not mirrored | `mirrorForRed()` returns `false` in each auto ([how](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/)). BIOBUZZ 2026-27 is turned: in its field CAD, each red part's twin is turned half a turn about the center. Also `Tunables.Odometry.mirrorForRed` for the reset spot | | Which AprilTag is the target, a number that differs for red | `alliance().pick(blue, red)` ([Advanced autos](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#a-different-number-for-red)) | | Scoring heights, positions, the shot table | `Tunables.java`, found with the tuning menu and the finders | | Something at a set time in TeleOp (park, a buzz) | `atSecondsLeft(seconds, job)` in `Controls.java` | **For the library (the mentor):** a new season also needs its season files in the simulator. One is `sim/fields/.json`, made from the official field CAD by a script. The other is `sim/fields/.rules.json`: the rules, typed from the manual with section numbers. When something is useful for ANY game (a new mechanism type, a sensor helper), put it in the library instead: [Extending the library](https://crossbotics.com/ftc-helper/docs/guides/extending/). ## 6. Docs and records - Library: CHANGELOG, the part pages, the walkthrough pages that changed, this page's table. - The camera fix (alpha): look again when the field has fixed tags on the walls ([Possible later work](https://crossbotics.com/ftc-helper/docs/design/possible-work/)). - The Shot Tuner's field map: change the goal and the spots in `tools/shot_spots.py`, run it, and change the season paragraph in `docs/tuning/13-shot-tuner.md`. - Robot project: its own README / design log. - AI agents: they read `AGENTS.md` every session. Update it when the rules or the layout change. --- # Non-blocking code: keep the loop running URL: https://crossbotics.com/ftc-helper/docs/guides/non-blocking/ **For:** anyone writing TeleOp or autonomous code. **You need:** a first OpMode ([Robot.java](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/) or [tutorial 01](https://crossbotics.com/ftc-helper/docs/tutorials/01-opmode-basics/)). A robot program is ONE loop that runs 50-200 times per second. Every part of the robot gets a turn in every loop. When any one piece of code **waits** (sleeps, loops until something happens, waits for a network answer), the whole robot freezes for that time. It does not drive, stop at limits, or react to STOP. The name for this is **blocking**.
flowchart LR
    subgraph GOOD["Non-blocking: every part, every loop"]
        A1["read gamepads"] --> A2["lift.update()"] --> A3["intake.update()"] --> A4["drive"] --> A1
    end
    subgraph BAD["Blocking: one part waits, everything stops"]
        B1["read gamepads"] --> B2["lift: sleep(500)<br/>robot frozen 0.5 s"] --> B3["intake..."] --> B1
    end
## The rule in this library | Kind of code | Blocks? | | --- | --- | | Everything you call in TeleOp: mechanism commands, `update()`, `ControllerBindings`, telemetry, timers, menus, cameras, the launcher | **Never.** Each call does a little work and returns. | | Slow hardware requests (Limelight pipeline switch and heading, webcam exposure, a REV 2m Distance Sensor in `PieceSensor.distance`, the battery voltage for the launcher: `Hw.batteryReader`) | Never: the library sends them on a background thread (`BackgroundWorker`). | | Setup in INIT (`create(...)`, `ImuSetup.get`, camera `start()`) | A short moment, once, in INIT. Never in the loop. | | `AutoDrive.move/turn/turnTo/moveWithTurn`, `AutoRoutine.runAll`, `AutoStep`s, `EasyAuto` | **Yes, on purpose**, and only in autonomous. While they wait, they keep updating your mechanisms and check STOP. Each has a time limit. | Each blocking method says **BLOCKS** in its Javadoc. The Javadoc is the explanation above the method in the code, and it is also in the [reference](https://crossbotics.com/ftc-helper/docs/reference/javadoc/). ## How to wait without blocking Say you want "open the claw, then close it 0.3 s later". Do not sleep. Remember WHEN, and check every loop: ```java // WRONG: freezes the robot for 0.3 s claw.goTo("OPEN"); sleep(300); claw.goTo("CLOSED"); // RIGHT: a tiny state machine (it remembers WHEN to act, and checks every loop) private double closeAt = -1; // seconds; -1 = nothing planned ... // getRuntime() = seconds since the OpMode started: close 0.3 s from now .bindPress(Pad.G2, Btn.A, () -> { claw.goTo("OPEN"); closeAt = getRuntime() + 0.3; }) ... // every loop: if (closeAt > 0 && getRuntime() >= closeAt) { claw.goTo("CLOSED"); closeAt = -1; // done: nothing planned any more } ``` The helpers already work this way inside. `PositionMotor` moves toward a target a bit each loop. `SpinServo.runFor` stops itself in `update()`. `Launcher.shoot(3)` feeds one piece per loop when ready. `SpinMotor` times its jam back-out. ## In autonomous In autonomous you want to wait, but your mechanisms must keep working while you wait. Use the library's waits, never `sleep()`: | Instead of | Use | | --- | --- | | `sleep(500)` between steps | `routine.waitFor("Settle", 0.5)` | | `while (!lift.isAtTarget()) {}` | `routine.waitUntil("Lift up", lift::isAtTarget, 2.0)` (time limit!) | | a custom waiting loop | inside an `AutoStep`: `ctx.waitFor(...)`, `ctx.waitUntil(...)`, or call `ctx.loop()` in your loop | `lift::isAtTarget` is a method reference: it hands over the method itself, so the wait can call it again every loop. ## The alarms The library watches for blocking code, and the Driver Station shows a warning: | Warning | Means | Fix | | --- | --- | --- | | `G2:A button job took 250 ms: the whole robot stopped that long. ...` | a button action waited | remove the sleep or loop, and use a state machine (above) | | `Lift update took 120 ms: update() must not wait or sleep` | a mechanism's `update()` waited | same | | Loop speed under ~30 Hz (`LoopTimer`; Hz = loops per second) | something is slow every loop | bulk reads, fewer telemetry lines, look for waits | Show the button warning in your TeleOp: ```java // "" means all good; anything else is a warning text to show if (!controls.getSlowActionWarning().isEmpty()) t.warn(controls.getSlowActionWarning()); ``` `Subsystems.addTelemetry` shows the update warning for you. ## Background jobs Some hardware requests must wait for an answer, like a network request to the Limelight. The library runs those on a `BackgroundWorker` thread: a second line of work that runs at the same time as your loop. So your loop goes on. When you add such a request, write: ```java BackgroundWorker worker = new BackgroundWorker("my-sensor"); // its own thread (a 2nd worker) worker.submitLatest("setting", () -> sensor.slowSetting(value)); // returns at once ... worker.shutdown(); // in stop() ``` Rules for background jobs: never touch motors or servos from them, because only the loop does that. Use `submitLatest` for anything you send again and again, so the worker sends only the newest value. ## Checked automatically `tools/check_blocking.py` runs on every push. It fails the build when the library has a `sleep(`, `Thread.sleep` or `.join(`. It also fails on a `while` loop outside the methods that block on purpose (the script lists them, each with the reason). Another kind of wait fails it too, such as `.await(`, `.acquire(`, `.take(`, a `Future` or `LockSupport.park`. Examples may not sleep or wait either. The script only reads the words of the code, so two things stay your job. The first is a wait for a lock (a lock lets only one thread use something at a time). Never hold a lock that the loop also needs while you write a file or talk to a device. The second is a slow request inside a call: some SDK methods wait for a device. --- # Parts catalog: motors, servos, wheels and rollers URL: https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/ The simulator knows these FTC motors and servos. A robot file names a part by its **id** (`part=gobilda-5203-312`), and the simulator takes the part's real numbers from here: how fast it turns, how many encoder counts it gives per turn, and its current (motors), or its range and speed (servos). Every number comes from the seller's page or the seller's own documents (motors and servos read on **2026-10-16**; wheels and rollers on the date in their Checked column; the link is in each row). A dash (-) means the seller does not publish that number. 39 motors and 13 servos. See also: [the simulator guide](https://crossbotics.com/ftc-helper/docs/simulator/). ## Use a part In the robot file (`simulator/robot.properties` in a robot project): ```properties drive.part = gobilda-5203-312 # all four wheel motors motor.lift = lift, part=gobilda-5203-117, min=0, max=2750 motor.flywheel = flywheel, part=gobilda-5203-6000, feeder=feeder servo.claw = 0.5, part=gobilda-2000-torque # start position, then the part ``` Numbers written in the robot file win over the part's numbers (for example `ticksPerRev=` on a motor). A typo in an id stops the simulator with a list of the ids it knows. ## Motors Free speed and current at 12 V. **Counts per turn** are encoder counts per turn of the output shaft, as the FTC SDK reports them. **Top speed** is what `getVelocity()` shows at full power with no load: free speed × counts per turn ÷ 60. On a real robot, `setVelocity()` and RUN_USING_ENCODER use the motor TYPE chosen in the robot configuration; pick the matching type there. ### goBILDA 5203 Yellow Jacket (REX shaft) | id | Part | Part number | Ratio | Free speed (RPM) | Counts per turn | Top speed (counts/s) | Stall torque (kg-cm) | Stall current (A) | |---|---|---|---|---|---|---|---|---| | `gobilda-5203-6000` | [goBILDA 5203 Yellow Jacket 6000 RPM](https://www.gobilda.com/5203-series-yellow-jacket-motor-1-1-ratio-24mm-length-8mm-rex-shaft-6000-rpm-3-3-5v-encoder/) | 5203-2402-0001 | 1:1 | 6000 | 28 | 2800 | 1.47 | 9.2 | | `gobilda-5203-1620` | [goBILDA 5203 Yellow Jacket 1620 RPM](https://www.gobilda.com/5203-series-yellow-jacket-planetary-gear-motor-3-7-1-ratio-1620-rpm-3-3-5v-encoder/) | 5203-2402-0003 | 3.71:1 | 1620 | 103.8 | 2803 | 5.4 | 9.2 | | `gobilda-5203-1150` | [goBILDA 5203 Yellow Jacket 1150 RPM](https://www.gobilda.com/5203-series-yellow-jacket-planetary-gear-motor-5-2-1-ratio-24mm-length-8mm-rex-shaft-1150-rpm-3-3-5v-encoder/) | 5203-2402-0005 | 5.18:1 | 1150 | 145.1 | 2781 | 7.9 | 9.2 | | `gobilda-5203-435` | [goBILDA 5203 Yellow Jacket 435 RPM](https://www.gobilda.com/5203-series-yellow-jacket-planetary-gear-motor-13-7-1-ratio-24mm-length-8mm-rex-shaft-435-rpm-3-3-5v-encoder/) | 5203-2402-0014 | 13.73:1 | 435 | 384.5 | 2788 | 18.7 | 9.2 | | `gobilda-5203-312` | [goBILDA 5203 Yellow Jacket 312 RPM](https://www.gobilda.com/5203-series-yellow-jacket-planetary-gear-motor-19-2-1-ratio-24mm-length-8mm-rex-shaft-312-rpm-3-3-5v-encoder/) | 5203-2402-0019 | 19.2:1 | 312 | 537.7 | 2796 | 24.3 | 9.2 | | `gobilda-5203-223` | [goBILDA 5203 Yellow Jacket 223 RPM](https://www.gobilda.com/5203-series-yellow-jacket-planetary-gear-motor-26-9-1-ratio-24mm-length-8mm-rex-shaft-223-rpm-3-3-5v-encoder/) | 5203-2402-0027 | 26.85:1 | 223 | 751.8 | 2794 | 38 | 9.2 | | `gobilda-5203-117` | [goBILDA 5203 Yellow Jacket 117 RPM](https://www.gobilda.com/5203-series-yellow-jacket-planetary-gear-motor-50-9-1-ratio-24mm-length-8mm-rex-shaft-117-rpm-3-3-5v-encoder/) | 5203-2402-0051 | 50.9:1 | 117 | 1425.1 | 2779 | 68.4 | 9.2 | | `gobilda-5203-84` | [goBILDA 5203 Yellow Jacket 84 RPM](https://www.gobilda.com/5203-series-yellow-jacket-planetary-gear-motor-71-2-1-ratio-24mm-length-8mm-rex-shaft-84-rpm-3-3-5v-encoder/) | 5203-2402-0071 | 71.16:1 | 84 | 1993.6 | 2791 | 93.6 | 9.2 | | `gobilda-5203-60` | [goBILDA 5203 Yellow Jacket 60 RPM](https://www.gobilda.com/5203-series-yellow-jacket-planetary-gear-motor-99-5-1-ratio-24mm-length-8mm-rex-shaft-60-rpm-3-3-5v-encoder/) | 5203-2402-0100 | 99.51:1 | 60 | 2786.2 | 2786 | 133.2 | 9.2 | | `gobilda-5203-43` | [goBILDA 5203 Yellow Jacket 43 RPM](https://www.gobilda.com/5203-series-yellow-jacket-planetary-gear-motor-139-1-ratio-24mm-length-8mm-rex-shaft-43-rpm-3-3-5v-encoder/) | 5203-2402-0139 | 139.14:1 | 43 | 3895.9 | 2792 | 185 | 9.2 | | `gobilda-5203-30` | [goBILDA 5203 Yellow Jacket 30 RPM](https://www.gobilda.com/5203-series-yellow-jacket-planetary-gear-motor-188-1-ratio-24mm-length-8mm-rex-shaft-30-rpm-3-3-5v-encoder/) | 5203-2402-0188 | 188.61:1 | 30 | 5281.1 | 2641 | 250 | 9.2 | ### goBILDA 5204 Yellow Jacket (D-shaft) | id | Part | Part number | Ratio | Free speed (RPM) | Counts per turn | Top speed (counts/s) | Stall torque (kg-cm) | Stall current (A) | |---|---|---|---|---|---|---|---|---| | `gobilda-5204-1620` | [goBILDA 5204 Yellow Jacket 1620 RPM (80 mm shaft)](https://www.gobilda.com/5204-series-yellow-jacket-planetary-gear-motor-3-7-1-ratio-80mm-length-8mm-rex-shaft-1620-rpm-3-3-5v-encoder/) | 5204-8002-0003 | 3.71:1 | 1620 | 103.8 | 2803 | 5.4 | 9.2 | | `gobilda-5204-1150` | [goBILDA 5204 Yellow Jacket 1150 RPM (80 mm shaft)](https://www.gobilda.com/5204-series-yellow-jacket-planetary-gear-motor-5-2-1-ratio-80mm-length-8mm-rex-shaft-1150-rpm-3-3-5v-encoder/) | 5204-8002-0005 | 5.18:1 | 1150 | 145.1 | 2781 | 7.9 | 9.2 | | `gobilda-5204-435` | [goBILDA 5204 Yellow Jacket 435 RPM (80 mm shaft)](https://www.gobilda.com/5204-series-yellow-jacket-planetary-gear-motor-13-7-1-ratio-80mm-length-8mm-rex-shaft-435-rpm-3-3-5v-encoder/) | 5204-8002-0014 | 13.73:1 | 435 | 384.5 | 2788 | 18.7 | 9.2 | | `gobilda-5204-312` | [goBILDA 5204 Yellow Jacket 312 RPM (80 mm shaft)](https://www.gobilda.com/5204-series-yellow-jacket-planetary-gear-motor-19-2-1-ratio-80mm-length-8mm-rex-shaft-312-rpm-3-3-5v-encoder/) | 5204-8002-0019 | 19.2:1 | 312 | 537.7 | 2796 | 24.3 | 9.2 | | `gobilda-5204-223` | [goBILDA 5204 Yellow Jacket 223 RPM (80 mm shaft)](https://www.gobilda.com/5204-series-yellow-jacket-planetary-gear-motor-26-9-1-ratio-80mm-length-8mm-rex-shaft-223-rpm-3-3-5v-encoder/) | 5204-8002-0027 | 26.85:1 | 223 | 751.8 | 2794 | 38 | 9.2 | | `gobilda-5204-117` | [goBILDA 5204 Yellow Jacket 117 RPM (80 mm shaft)](https://www.gobilda.com/5204-series-yellow-jacket-planetary-gear-motor-50-9-1-ratio-80mm-length-8mm-rex-shaft-117-rpm-3-3-5v-encoder/) | 5204-8002-0051 | 50.9:1 | 117 | 1425.1 | 2779 | 68.4 | 9.2 | | `gobilda-5204-84` | [goBILDA 5204 Yellow Jacket 84 RPM (80 mm shaft)](https://www.gobilda.com/5204-series-yellow-jacket-planetary-gear-motor-71-2-1-ratio-80mm-length-8mm-rex-shaft-84-rpm-3-3-5v-encoder/) | 5204-8002-0071 | 71.16:1 | 84 | 1993.6 | 2791 | 93.6 | 9.2 | | `gobilda-5204-60` | [goBILDA 5204 Yellow Jacket 60 RPM (80 mm shaft)](https://www.gobilda.com/5204-series-yellow-jacket-planetary-gear-motor-99-5-1-ratio-80mm-length-8mm-rex-shaft-60-rpm-3-3-5v-encoder/) | 5204-8002-0100 | 99.51:1 | 60 | 2786.2 | 2786 | 133.2 | 9.2 | | `gobilda-5204-43` | [goBILDA 5204 Yellow Jacket 43 RPM (80 mm shaft)](https://www.gobilda.com/5204-series-yellow-jacket-planetary-gear-motor-139-1-ratio-80mm-length-8mm-rex-shaft-43-rpm-3-3-5v-encoder/) | 5204-8002-0139 | 139.14:1 | 43 | 3895.9 | 2792 | 185 | 9.2 | | `gobilda-5204-30` | [goBILDA 5204 Yellow Jacket 30 RPM (80 mm shaft)](https://www.gobilda.com/5204-series-yellow-jacket-planetary-gear-motor-188-1-ratio-80mm-length-8mm-rex-shaft-30-rpm-3-3-5v-encoder/) | 5204-8002-0188 | 188.61:1 | 30 | 5281.1 | 2641 | 250 | 9.2 | ### REV HD Hex | id | Part | Part number | Ratio | Free speed (RPM) | Counts per turn | Top speed (counts/s) | Stall torque (kg-cm) | Stall current (A) | |---|---|---|---|---|---|---|---|---| | `rev-hd-hex` | [REV HD Hex Motor (no gearbox)](https://www.revrobotics.com/rev-41-1291/) | REV-41-1291 | 1:1 | 6000 | 28 | 2800 | 1.07 | 8.5 | | `rev-hd-hex-up3` | [REV HD Hex + UltraPlanetary 3:1 (nominal)](https://www.revrobotics.com/rev-41-1600/) | REV-41-1291 + REV-41-1601 | 2.9:1 | 2071.4 | 81.1 | 2800 | 3.1 | 8.5 | | `rev-hd-hex-up4` | [REV HD Hex + UltraPlanetary 4:1 (nominal)](https://www.revrobotics.com/rev-41-1600/) | REV-41-1291 + REV-41-1602 | 3.62:1 | 1657.9 | 101.33 | 2800 | 3.87 | 8.5 | | `rev-hd-hex-up5` | [REV HD Hex + UltraPlanetary 5:1 (nominal)](https://www.revrobotics.com/rev-41-1600/) | REV-41-1291 + REV-41-1603 | 5.23:1 | 1147 | 146.46 | 2800 | 5.61 | 8.5 | | `rev-hd-hex-up12` | [REV HD Hex + UltraPlanetary 12:1 (nominal)](https://www.revrobotics.com/rev-41-1600/) | REV-41-1291 + REV-41-1601 + REV-41-1602 | 10.48:1 | 572.4 | 293.52 | 2800 | 11.23 | 8.5 | | `rev-hd-hex-up15` | [REV HD Hex + UltraPlanetary 15:1 (nominal)](https://www.revrobotics.com/rev-41-1600/) | REV-41-1291 + REV-41-1601 + REV-41-1603 | 15.15:1 | 396 | 424.23 | 2800 | 16.22 | 8.5 | | `rev-hd-hex-up20` | [REV HD Hex + UltraPlanetary 20:1 (nominal)](https://www.revrobotics.com/rev-41-1600/) | REV-41-1291 + REV-41-1602 + REV-41-1603 | 18.93:1 | 317 | 530.05 | 2800 | 20.19 | 8.5 | | `rev-hd-hex-up60` | [REV HD Hex + UltraPlanetary 60:1 (nominal)](https://www.revrobotics.com/rev-41-1600/) | REV-41-1291 + REV-41-1601 + REV-41-1602 + REV-41-1603 | 54.83:1 | 109.5 | 1535.32 | 2802 | 58.63 | 8.5 | | `rev-hd-hex-40` | [REV HD Hex Motor 40:1 Spur Gearbox](https://www.revrobotics.com/rev-41-1301/) | REV-41-1301 | 40:1 | 150 | 1120 | 2800 | 42.83 | 8.5 | | `rev-hd-hex-20` | [REV HD Hex Motor 20:1 Spur Gearbox](https://docs.revrobotics.com/duo-build/motion/motors/hd-hex-motor) | REV-41-1298 | 20:1 | 300 | 560 | 2800 | 21.41 | 8.5 | ### REV Core Hex | id | Part | Part number | Ratio | Free speed (RPM) | Counts per turn | Top speed (counts/s) | Stall torque (kg-cm) | Stall current (A) | |---|---|---|---|---|---|---|---|---| | `rev-core-hex` | [REV Core Hex Motor](https://www.revrobotics.com/rev-41-1300/) | REV-41-1300 | 72:1 | 125 | 288 | 600 | 32.63 | 4.4 | ### AndyMark NeveRest | id | Part | Part number | Ratio | Free speed (RPM) | Counts per turn | Top speed (counts/s) | Stall torque (kg-cm) | Stall current (A) | |---|---|---|---|---|---|---|---|---| | `am-neverest-orbital-1` | [AndyMark NeveRest Orbital 1:1](https://andymark.com/products/neverest-orbital-gearmotors) | am-5185a / am-5185b | 1:1 | 6600 | 28 | 3080 | - | 11 | | `am-neverest-orbital-3-7` | [AndyMark NeveRest Orbital 3.7:1](https://andymark.com/products/neverest-orbital-gearmotors) | am-3461a / am-3461b | 3.7:1 | 1784 | 103.6 | 3080 | - | 11 | | `am-neverest-orbital-20` | [AndyMark NeveRest Orbital 19.2:1](https://andymark.com/products/neverest-orbital-gearmotors) | am-3637b | 19.2:1 | 344 | 537.6 | 3082 | - | 11 | | `am-neverest-orbital-50` | [AndyMark NeveRest Orbital 50.9:1](https://andymark.com/products/neverest-orbital-gearmotors) | am-4609a | 50.9:1 | 130 | 1425.2 | 3088 | - | 11 | | `am-neverest-orbital-264` | [AndyMark NeveRest Orbital 263.7:1](https://andymark.com/products/neverest-orbital-gearmotors) | am-4608a / am-4608b | 263.7:1 | 25 | 7383.6 | 3076 | - | 11 | | `am-neverest-classic-40` | [AndyMark NeveRest Classic 40](https://andymark.com/products/neverest-classic-40-gearmotor) | am-2964a / am-2964b | 40:1 | 160 | 1120 | 2987 | 25.21 | 11.5 | | `am-neverest-classic-60` | [AndyMark NeveRest Classic 60](https://andymark.com/products/neverest-classic-60-gearmotor) | am-3103 | 60:1 | 105 | 1680 | 2940 | 37.8 | 11.5 | ## Servos A Control Hub servo port gives about 5 V, so the simulator uses the seller's speed row closest to 5 V (**Speed used**); the headline number on the seller's page is often at 6 V. **Range** is how far positions 0 to 1 turn it. **Continuous** = it can be switched to continuous rotation (a CR servo). ### goBILDA 2000 Series servos | id | Part | Part number | Range on the hub (°) | Full range (°) | Pulse (us) | Speed used (s per 60°) | Headline speed (s per 60°) | Torque (kg-cm) | Stall current (A) | Continuous | Bigger number turns | |---|---|---|---|---|---|---|---|---|---|---|---| | `gobilda-2000-torque` | [goBILDA 2000 Series Dual Mode Servo (Torque)](https://www.gobilda.com/2000-series-dual-mode-servo-25-2-torque/) | 2000-0025-0002 | 270 | 300 | 500-2500 | 0.25 at 4.8 V | 0.2 at 6 V | 21.6 | 2.5 | yes | clockwise | | `gobilda-2000-speed` | [goBILDA 2000 Series Dual Mode Servo (Speed)](https://www.gobilda.com/2000-series-dual-mode-servo-25-3-speed/) | 2000-0025-0003 | 270 | 300 | 500-2500 | 0.11 at 4.8 V | 0.09 at 6 V | 9.3 | 2.5 | yes | clockwise | | `gobilda-2000-super-speed` | [goBILDA 2000 Series Dual Mode Servo (Super Speed)](https://www.gobilda.com/2000-series-dual-mode-servo-25-4-super-speed/) | 2000-0025-0004 | 270 | 300 | 500-2500 | 0.055 at 4.8 V | 0.043 at 6 V | 4.7 | 2.5 | yes | clockwise | | `gobilda-2000-5turn-torque` | [goBILDA 2000 Series 5-Turn Dual Mode Servo (Torque)](https://www.gobilda.com/2000-series-5-turn-dual-mode-servo-25-2-torque/) | 2000-0025-0502 | 1620 | 1800 | 500-2500 | 0.25 at 4.8 V | 0.2 at 6 V | 21.6 | 2.5 | yes | clockwise | | `gobilda-2000-5turn-speed` | [goBILDA 2000 Series 5-Turn Dual Mode Servo (Speed)](https://www.gobilda.com/2000-series-5-turn-dual-mode-servo-25-3-speed/) | 2000-0025-0503 | 1620 | 1800 | 500-2500 | 0.11 at 4.8 V | 0.09 at 6 V | 9.3 | 2.5 | yes | clockwise | | `gobilda-2000-5turn-super-speed` | [goBILDA 2000 Series 5-Turn Dual Mode Servo (Super Speed)](https://www.gobilda.com/2000-series-5-turn-dual-mode-servo-25-4-super-speed/) | 2000-0025-0504 | 1620 | 1800 | 500-2500 | 0.055 at 4.8 V | 0.043 at 6 V | 4.7 | 2.5 | yes | clockwise | ### REV Smart Robot Servos | id | Part | Part number | Range on the hub (°) | Full range (°) | Pulse (us) | Speed used (s per 60°) | Headline speed (s per 60°) | Torque (kg-cm) | Stall current (A) | Continuous | Bigger number turns | |---|---|---|---|---|---|---|---|---|---|---|---| | `rev-smart-servo` | [REV Smart Robot Servo (V1)](https://docs.revrobotics.com/rev-crossover-products/servo/srs) | REV-41-1097 | 243 | 270 | 500-2500 | 0.13 at 6 V | 0.13 at 6 V | 13.5 | 2 | yes | not given | | `rev-smart-servo-v2-balanced` | [REV Smart Robot Servo V2 - Balanced](https://www.revrobotics.com/Smart-servo-v2/) | REV-41-3334 | 243 | 270 | 500-2500 | 0.14 at 6 V | 0.14 at 6 V | 13.5 | 2.1 | yes | not given | | `rev-smart-servo-v2-ultraspeed` | [REV Smart Robot Servo V2 - UltraSpeed](https://www.revrobotics.com/Smart-servo-v2/) | REV-41-3336 | 243 | 270 | 500-2500 | 0.043 at 6 V | 0.043 at 6 V | 5.6 | 2.9 | yes | not given | ### Axon servos | id | Part | Part number | Range on the hub (°) | Full range (°) | Pulse (us) | Speed used (s per 60°) | Headline speed (s per 60°) | Torque (kg-cm) | Stall current (A) | Continuous | Bigger number turns | |---|---|---|---|---|---|---|---|---|---|---|---| | `axon-max-mk2` | [Axon MAX MK2](https://docs.axon-robotics.com/servos/max) | - | 324 | 360 | 500-2500 | 0.14 at 4.8 V | 0.115 at 6 V | 34 | 4 | yes | not given | | `axon-max-plus` | [Axon MAX+](https://docs.axon-robotics.com/archive/max) | - | - | - | - | 0.14 at 4.8 V | 0.115 at 6 V | 34 | 4 | yes | not given | | `axon-mini-mk2` | [Axon MINI MK2](https://docs.axon-robotics.com/servos/mini) | - | 324 | 360 | 500-2500 | 0.11 at 4.8 V | 0.09 at 6 V | 25 | 3.8 | yes | not given | | `axon-mini-plus` | [Axon MINI+](https://docs.axon-robotics.com/archive/mini) | - | - | - | - | 0.11 at 4.8 V | 0.09 at 6 V | 25 | 3.8 | yes | not given | **Bigger number turns** is which way a bigger position (a longer pulse) turns the servo, as its seller states it (goBILDA: clockwise; the side it is seen from is not stated). It is only a hint: the way the PART moves depends on how the servo is mounted, so check it by test (Servo Finder: D-pad up). REV and Axon do not say (an Axon servo can be switched either way with its programmer). [Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/#servos-and-motors-which-way-is-bigger). **Range on the hub** is what positions 0 to 1 turn the servo with the FTC SDK's normal pulse, 600-2400 microseconds (us). **Full range** is the seller's, over its **pulse** range; the robot uses it with `.fullRange()` on the part ([why](https://crossbotics.com/ftc-helper/docs/modules/hardware/#full-range)), and the simulator too (`pwm=500-2500` in the robot file, which `:sim:fromRobot` writes). Range on the hub = full range x 1800 / (pulse high - pulse low). A servo with no range here (-) moves at the robot file's `servo.speed` (positions per second) in the simulator; its range is set by programming it. ## Wheels and rollers For `Robot.java` (not the robot file): a `Shape` names one of these and takes its size from here, and `Drive.wheel(id)` its diameter ([robot module, Shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)). **Width** is along the axle; a dash (-) means the seller does not give it, so the shape gives its length (`lengthMm`). | id | Part | Part number | Diameter (mm) | Width (mm) | Checked | Notes | |---|---|---|---|---|---|---| | `andymark-higrip-102` | [AndyMark HiGrip Wheel 4 in (60A, black)](https://www.andymark.com/products/4-in-higrip-wheel-60a-durometer) | am-2256_blk | 101.6 | - | 2026-11-03 | Traction wheel; also 80A white (am-2256) and 50A blue (am-2256_blue). The page gives no width. Stock from the store's product data. | | `andymark-mecanum-102-bb` | [AndyMark BB Mecanum Wheels 4 in (nub bore, set of 4)](https://andymark.com/products/4-in-bb-mecanum-wheels) | am-4734 | 101.6 | 38.6 | 2026-11-03 | Slim mecanum set of 4 (2 left, 2 right) made for FTC, 12 rollers per wheel, 60A TPU on ball bearings. Also with 1/2 in hex (am-4736) and 3/8 in hex (am-4735) bores. 4 in, 1.52 in wide. Stock from the store's product data. | | `andymark-mecanum-102-hd` | [AndyMark HD Mecanum Wheels 4 in (nub bore, set of 4)](https://andymark.com/products/4-in-hd-mecanum-wheels) | am-3919 | 101.6 | 55.4 | 2026-11-03 | Mecanum set of 4 (2 left, 2 right), 9 rollers per wheel, 80A TPU. The page says 4 in (AndyMark also calls it 100 mm) and 2.18 in wide. Stock from the store's product data. | | `andymark-omni-102` | [AndyMark DuraOmni Wheel 4 in](https://andymark.com/products/duraomni-wheel) | am-3047 | 101.6 | 50.8 | 2026-11-03 | Omni wheel, 8 rollers, 80A TPU; hubs not included. The page's SKU field is blank: the part number is from its CAD file names. 4 in, 2 in wide. Stock from the store's product data. | | `gobilda-boot-72-rex` | [goBILDA Boot-Wheel 72 mm (8 mm REX bore, 30A)](https://www.gobilda.com/3615-series-boot-wheel-8mm-rex-bore-72mm-diameter-30a-durometer) | 3615-4008-0072 | 72 | - | 2026-10-20 | Silicone rubber (30A) on an acetal hex core, 14 g. Read on goBILDA's page and Core Electronics (GB-3615-4008-0072) through a web search; the page gives no width: give lengthMm. | | `gobilda-gecko-32-rex` | [goBILDA GripForce Gecko Wheel 32 mm (8 mm REX bore, 30A)](https://www.gobilda.com/gripforce-gecko-wheel-8mm-rex-bore-32mm-diameter-30a-durometer/) | 3613-4008-0032 | 32 | - | 2026-11-06 | Silicone rubber (30A) on a plastic core, 8.3 g. The diameter is in the page's name; the page gives no width: give lengthMm. | | `gobilda-gecko-32-rex-15a` | [goBILDA GripForce Gecko Wheel 32 mm (8 mm REX bore, 15A)](https://www.gobilda.com/gripforce-gecko-wheel-8mm-rex-bore-32mm-diameter-15a-durometer/) | 3632-4008-0032 | 32 | - | 2026-11-06 | The ultra-soft (15A) version of gobilda-gecko-32-rex: the same size, softer rubber, 7.9 g. The diameter is in the page's name; the page gives no width: give lengthMm. | | `gobilda-gecko-48-rex` | [goBILDA GripForce Gecko Wheel 48 mm (8 mm REX bore, 30A)](https://www.gobilda.com/gripforce-gecko-wheel-8mm-rex-bore-48mm-diameter-30a-durometer/) | 3613-4008-0048 | 48 | - | 2026-10-20 | The page gives the diameter, not the width. Not measured yet: goBILDA's STEP CAD of its BIOBUZZ starter bot (3200-2627-0003) has these wheels, so it can be measured there as for the 72 and 96 mm wheels. | | `gobilda-gecko-48-rex-15a` | [goBILDA GripForce Gecko Wheel 48 mm (8 mm REX bore, 15A)](https://www.gobilda.com/gripforce-gecko-wheel-8mm-rex-bore-48mm-diameter-15a-durometer/) | 3632-4008-0048 | 48 | - | 2026-11-06 | The ultra-soft (15A) version of gobilda-gecko-48-rex: the same size, softer rubber (better grip on a game piece it squeezes), 15 g. The diameter is in the page's name; the page gives no width: give lengthMm. | | `gobilda-gecko-72` | [goBILDA GripForce Gecko Wheel 72 mm (14 mm bore, 30A)](https://www.gobilda.com/gripforce-gecko-wheel-14mm-bore-72mm-diameter-30a-durometer/) | 3613-0014-0072 | 72 | 24 | 2026-10-20 | widthMm measured in goBILDA's STEP CAD of its BIOBUZZ starter bot (3200-2627-0003, see sim/robots/starter-bot-gobilda.properties); the page gives the diameter only. | | `gobilda-gecko-72-15a` | [goBILDA GripForce Gecko Wheel 72 mm (14 mm bore, 15A)](https://www.gobilda.com/gripforce-gecko-wheel-14mm-bore-72mm-diameter-15a-durometer/) | 3632-0014-0072 | 72 | - | 2026-11-06 | The ultra-soft (15A) version of gobilda-gecko-72, 49 g. The diameter is in the page's name; the page gives no width (the 30A one measured 24 mm in CAD; not checked for this one): give lengthMm. | | `gobilda-gecko-96` | [goBILDA GripForce Gecko Wheel 96 mm (14 mm bore, 30A)](https://www.gobilda.com/gripforce-gecko-wheel-14mm-bore-96mm-diameter-30a-durometer/) | 3613-0014-0096 | 96 | - | 2026-11-03 | Traction wheel, 30A tread, 14 mm bore (the 15A version: gobilda-gecko-96-15a). The page gives no width; stock from the page's data (InStock). | | `gobilda-gecko-96-15a` | [goBILDA GripForce Gecko Wheel 96 mm (14 mm bore, 15A)](https://www.gobilda.com/gripforce-gecko-wheel-14mm-bore-96mm-diameter-15a-durometer/) | 3632-0014-0096 | 96 | - | 2026-11-06 | The ultra-soft (15A) version of gobilda-gecko-96, 102 g. The diameter is in the page's name; the page gives no width: give lengthMm. | | `gobilda-gripforce-mecanum-104` | [goBILDA GripForce Mecanum Wheel Set 104 mm (40A rollers)](https://www.gobilda.com/gripforce-mecanum-wheel-set-o104mm-40a-durometer-rollers/) | 3625-0202-0104 | 104 | - | 2026-11-03 | A set of 4: 2 left slant, 2 right slant (the page's pictures). 40A silicone rollers, 236 g each. The wheels of goBILDA's newer Strafer chassis kits. The page gives the diameter, not the width. Use it as a drive wheel: Drive.mecanum(...).wheel("gobilda-gripforce-mecanum-104"). | | `gobilda-hogback-96` | [goBILDA Hogback Traction Wheel 96 mm (50A)](https://www.gobilda.com/hogback-traction-wheel-96mm-diameter-50a-durometer/) | 3626-0014-0096 | 96 | 24 | 2026-10-20 | widthMm measured in goBILDA's STEP CAD of its BIOBUZZ starter bot (3200-2627-0003, see sim/robots/starter-bot-gobilda.properties); the page gives the diameter only. | | `gobilda-mecanum-140` | [goBILDA Mecanum Wheel Set 140 mm (70A bearing-supported rollers)](https://www.gobilda.com/140mm-mecanum-wheel-set-70a-durometer-bearing-supported-rollers/) | 3213-3606-0003 | 140 | 37 | 2026-11-03 | Mecanum, 16 rollers per wheel, 70A bearing-supported rollers. Hub fits 8 mm and 12 mm REX shafts. The page does not say how many wheels are in the set; stock from the page's data (InStock). | | `gobilda-mecanum-96` | [goBILDA Mecanum Wheel Set 96 mm (70A bearing-supported rollers)](https://www.gobilda.com/96mm-mecanum-wheel-set-70a-durometer-bearing-supported-rollers/) | 3213-3606-0002 | 96 | - | 2026-11-03 | A set of 4: 2 left slant, 2 right slant (the page's pictures). 70A rubber rollers, 207 g each. The wheels of older Strafer chassis kits. The page gives the diameter, not the width. Use it as a drive wheel: Drive.mecanum(...).wheel("gobilda-mecanum-96"). | | `gobilda-omni-72` | [goBILDA Omni Wheel 72 mm (14 mm bore, 50A)](https://www.gobilda.com/72mm-omni-wheel-14mm-bore-50a-durometer/) | 3624-0014-0072 | 72 | - | 2026-11-03 | Omni wheel, 50A rollers, 14 mm bore, sold one at a time. The page gives no width; stock from the page's data (InStock). | | `gobilda-omni-96` | [goBILDA Omni Wheel 96 mm (14 mm bore, 50A)](https://www.gobilda.com/96mm-omni-wheel-14mm-bore-50a-durometer/) | 3624-0014-0096 | 96 | - | 2026-11-03 | Omni wheel, 50A rollers, 14 mm bore, sold one at a time. The page gives no width; stock from the page's data (InStock). | | `gobilda-rhino-96` | [goBILDA Rhino Wheel 96 mm (14 mm bore, 30A)](https://www.gobilda.com/3614-series-rhino-wheel-14mm-bore-96mm-diameter-30a-durometer/) | 3614-0014-0096 | 96 | 32 | 2026-11-03 | Traction wheel, 30A rubber, 14 mm bore. Width from the page's description; stock from the page's data (InStock). | | `offset-tubing-60` | [Offset Surgical Tubing Roller 60 mm](https://legacy.offsetrobotics.com/product/offset-surgical-tubing-rollers/) | OSTR-HEX-07-00 | 60 | - | 2026-10-20 | 55A silicone tubing pieces, 6 per size (the 'Both' pack: 6 x 60 mm, 6 x 90 mm, 1 OFFSET HEXAHUB, 6 M3 screws). SKU OSTR-HEX-07-00 is for the product (choose 60 mm, 90 mm or both). Read on the seller's legacy page, which shows the text; offsetrobotics.com/product/offset-surgical-tubing-rollers needs a browser. The page gives the diameter only; how long a roller is depends on how many hubs are on the shaft. | | `offset-tubing-90` | [Offset Surgical Tubing Roller 90 mm](https://legacy.offsetrobotics.com/product/offset-surgical-tubing-rollers/) | OSTR-HEX-07-00 | 90 | - | 2026-10-20 | 55A silicone tubing pieces, 6 per size (the 'Both' pack: 6 x 60 mm, 6 x 90 mm, 1 OFFSET HEXAHUB, 6 M3 screws). SKU OSTR-HEX-07-00 is for the product (choose 60 mm, 90 mm or both). Read on the seller's legacy page, which shows the text; offsetrobotics.com/product/offset-surgical-tubing-rollers needs a browser. The page gives the diameter only; how long a roller is depends on how many hubs are on the shaft. | | `rev-mecanum-75` | [REV DUO Mecanum Wheel Set 75 mm](https://www.revrobotics.com/rev-45-1655/) | REV-45-1655 | 75 | 40 | 2026-11-03 | Mecanum set of 4 (2 left REV-41-1656, 2 right REV-41-1657), NBR rollers, steel hubs, 5 mm hex adapters. The page says 75-78 mm: 75 here; the Drive Tuner measures the true size. | | `rev-omni-60` | [REV DUO Omni Wheel 60 mm (2-pack)](https://www.revrobotics.com/rev-41-1160/) | REV-41-1160-PK2 | 60 | 15 | 2026-11-03 | Omni wheel, TPU rollers, nylon hub, sold in 2-packs. Shares a page with the 90 mm wheel. | | `rev-omni-90` | [REV DUO Omni Wheel 90 mm (2-pack)](https://www.revrobotics.com/rev-41-1190/) | REV-41-1190-PK2 | 90 | 15 | 2026-11-03 | Omni wheel, TPU rollers, nylon hub, sold in 2-packs. Width = the page's 15 mm thickness. Shares a page with the 60 mm wheel. | | `rev-traction-90` | [REV DUO Traction Wheel 90 mm (2-pack)](https://www.revrobotics.com/rev-41-1354/) | REV-41-1354-PK2 | 90 | 15 | 2026-11-03 | Traction wheel, TPU tread, nylon hub, 5 mm hex bore, sold in 2-packs. The same page sells 60 mm (REV-41-1350-PK4) and 30 mm versions. | | `studica-mecanum-100` | [Studica Slim Mecanum Wheel Set 100 mm (bearing rollers, 2 left, 2 right)](https://www.studica.com/100mm-slim-mecanum-wheel-set-bearing-rollers-2-left-2-right) | 76246 | 100 | 38 | 2026-11-03 | Mecanum set of 4, 12 rollers per wheel on steel ball bearings, steel body; uses the 6 mm D-shaft hub. The page prints the width as 38m (read as 38 mm). Read in a browser (the site blocks scripts). | | `studica-omni-100` | [Studica Omni Wheel 100 mm](https://www.studica.com/100mm-omni-wheel) | 76272 | 100 | 16 | 2026-11-03 | Omni wheel, 18 rubber rollers, nylon body, 6 mm hub (use the Enhanced Wheel D-Shaft Hub Kit). Read in a browser. | | `studica-traction-100` | [Studica Drive Wheel 100 mm (50A, 25 mm wide, 1/2 in hex)](https://www.studica.com/100mm-drive-wheel-50a-25mm-wide-1-2-inch-inner-hex-blue) | 76262 | 100 | 25 | 2026-11-03 | Traction wheel, 50A TPU tread, 1/2 in hex bore (fits a 6 mm D-shaft with a hub). A 12.5 mm wide version is also sold. Read in a browser. | ## A part that is not in the list **In Robot.java (the robot code)**: describe it where you use it, with the seller's numbers. Its id then works wherever a catalog id goes, its numbers give the starting values (`DEFAULT`), and `:sim:fromRobot` writes them into the robot file for you: ```java launcher = add(Launcher.flywheel("launcher", Motors.custom("my-flywheel-motor", 28, 5800))); // counts per turn, free RPM claw = add(Claw.servo("claw").part(Parts.customServo("my-servo", 270, 0.16))); // turn (deg), s per 60 deg at ~5 V lift = add(Lift.slide("lift").part(Motors.unknown("old-lift-motor"))); // numbers not known yet ``` **Where the numbers are on the seller's page** (checked 2026-10-22 on goBILDA's 5203 312 RPM motor, REV's HD Hex motor REV-41-1291 and goBILDA's 2000 Series servo): | Number | goBILDA calls it | REV calls it | | --- | --- | --- | | counts per turn | "Encoder Resolution" (use the number "at the Output Shaft") | "Encoder Counts per Revolution" (with a gearbox, the number at the output) | | free RPM | "No-Load Speed" | "Free Speed" | | servo: seconds per 60 degrees | "No-Load Speed (4.8V)" | the servo's speed | A servo's speed: if the seller lists 4.8 V and 6 V, use 4.8 V (the hub gives a servo about 5 V). A number you do not know: write `Double.NaN`. It means "I don't know this one". (`Motors.unknown` / `Parts.unknownServo` = "I know none of its numbers".) The parts that need it use general defaults, and INIT says so. A launcher, an arm, a motor turret and the drive must at least have the counts per turn. More: [Parts not in the catalog](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-in-the-catalog). **In the simulator only**, three ways, from quickest to most shared: **1. Write its numbers in the robot file.** Use the seller's page. ```properties # A motor: free speed (RPM) and encoder counts per output turn; or maxTicksPerSec= directly. motor.arm = lift, rpm=90, ticksPerRev=1993.6, min=0, max=1200 # The drivetrain: counts per turn and top speed (counts per second). drive.ticksPerRev = 537.7 drive.maxTicksPerSec = 2796 # A servo: how far 0 to 1 turns it on the hub (degrees) and seconds per 60 degrees (use the 4.8-5 V number). servo.gate = 0.5, rangeDeg=180, secPer60=0.12 ``` **2. Keep the team's own parts file.** Good when several robot files use the part, or to keep its link and notes. Put a JSON file next to the robot file and name it there: ```properties parts = parts.json ``` It has the same form as the library's catalog. Only `id` and the numbers the simulator uses are needed (a motor: `freeRpm` and `countsPerRev`; a servo: `rangeDeg` and `secPer60Deg`, and `pulseMinUs`, `pulseMaxUs` when the seller gives its range over a pulse range; without them `rangeDeg` is what 0 to 1 turns it on the hub's normal 600-2400 us); the rest is for people. Give each part its own id: an id that is already in the library is refused, so a typo can't quietly replace a real part. ```json { "motors": [ { "id": "team-arm-motor", "name": "Our arm motor (bought used)", "url": "https://www.example.com/the-seller-page", "freeRpm": 90, "countsPerRev": 1993.6, "stallCurrentA": 9.2, "checked": "2026-10-16" } ], "servos": [ { "id": "team-gate-servo", "name": "Our gate servo", "rangeDeg": 180, "secPer60Deg": 0.12, "voltage": 4.8 } ] } ``` Then `motor.arm = lift, part=team-arm-motor` works like a library part. **3. Add it to the library's catalog** (for every team): add it to `sim/parts/parts.json` with the seller's link and the date you checked it, run `python3 tools/parts_page.py` to update this page, and open a pull request ([contributing](https://crossbotics.com/ftc-helper/docs/contributing/)). ## What each number is for | Field | Used for | |---|---| | `id` | the name a robot file uses (`part=...`) | | `freeRpm` | motors: top speed with no load (with `countsPerRev`, the top speed in counts per second) | | `countsPerRev` | motors: encoder counts per turn of the output shaft (`getCurrentPosition()` steps) | | `stallCurrentA`, `freeCurrentA` | motors: the current shown in the Control Hub panel | | `stallTorqueKgCm` | motors: shown here; the simple physics does not use it yet | | `rangeDeg`, `pulseMinUs`, `pulseMaxUs` | servos: the seller's full turn over its pulse range; the turn for positions 0 to 1 is worked out from the pulse the robot uses (600-2400 us, or the full range with `.fullRange()`) | | `secPer60Deg`, `byVoltage` | servos: how fast a position change takes | | `torqueKgCm`, `stallCurrentA`, `continuousCapable` | servos: shown here; not used by the physics | | `name`, `partNumber`, `seller`, `url`, `checked`, `notes` | people: what it is and where the numbers came from | ## Notes on each part From the catalog, for checking a number against the seller's page. - `gobilda-5203-6000`: Bare motor (1:1), no gearbox. 8 mm REX output shaft, 24 mm long. Weight 391g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5203-1620`: Nominal ratio 3.7:1; gearRatio is the exact value of goBILDA's listed formula (1+(46/17)). 8 mm REX output shaft, 24 mm long. Weight 396g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5203-1150`: Nominal ratio 5.2:1; gearRatio is the exact value of goBILDA's listed formula (1+(46/11)). 8 mm REX output shaft, 24 mm long. Weight 399g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5203-435`: Nominal ratio 13.7:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/17))) * (1+(46/17))). 8 mm REX output shaft, 24 mm long. Weight 438g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5203-312`: Nominal ratio 19.2:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/17))) * (1+(46/11))). 8 mm REX output shaft, 24 mm long. Weight 437g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). Shown 'Sold Out' on 2026-10-16. - `gobilda-5203-223`: Nominal ratio 26.9:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/11))) * (1+(46/11))). 8 mm REX output shaft, 24 mm long. Weight 437g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5203-117`: Nominal ratio 50.9:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/17))) * (1+(46/17))) * (1+(46/17)). 8 mm REX output shaft, 24 mm long. Weight 481g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5203-84`: Nominal ratio 71.2:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/17))) * (1+(46/17))) * (1+(46/11)). 8 mm REX output shaft, 24 mm long. Weight 486g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5203-60`: Nominal ratio 99.5:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/17))) * (1+(46/11))) * (1+(46/11)). 8 mm REX output shaft, 24 mm long. Weight 486g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5203-43`: Nominal ratio 139:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/11))) * (1+(46/11))) * (1+(46/11)). 8 mm REX output shaft, 24 mm long. Weight 485g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5203-30`: Nominal ratio 188:1; gearRatio is the exact value of goBILDA's listed formula (((((1+(46/17))) * (1+(46/17))) * (1+(46/17))) * (1+(46/17))). 8 mm REX output shaft, 24 mm long. Weight 524g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5204-1620`: Nominal ratio 3.7:1; gearRatio is the exact value of goBILDA's listed formula (1+(46/17)). 8 mm REX output shaft, 80 mm long. Weight 411g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5204-1150`: Nominal ratio 5.2:1; gearRatio is the exact value of goBILDA's listed formula (1+(46/11)). 8 mm REX output shaft, 80 mm long. Weight 412g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5204-435`: Nominal ratio 13.7:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/17))) * (1+(46/17))). 8 mm REX output shaft, 80 mm long. Weight 435g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5204-312`: Nominal ratio 19.2:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/17))) * (1+(46/11))). 8 mm REX output shaft, 80 mm long. Weight 458g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5204-223`: Nominal ratio 26.9:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/11))) * (1+(46/11))). 8 mm REX output shaft, 80 mm long. Weight 458g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5204-117`: Nominal ratio 50.9:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/17))) * (1+(46/17))) * (1+(46/17)). 8 mm REX output shaft, 80 mm long. Weight 465g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5204-84`: Nominal ratio 71.2:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/17))) * (1+(46/17))) * (1+(46/11)). 8 mm REX output shaft, 80 mm long. Weight 501g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5204-60`: Nominal ratio 99.5:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/17))) * (1+(46/11))) * (1+(46/11)). 8 mm REX output shaft, 80 mm long. Weight 501 (page omits unit). countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5204-43`: Nominal ratio 139:1; gearRatio is the exact value of goBILDA's listed formula (((1+(46/11))) * (1+(46/11))) * (1+(46/11)). 8 mm REX output shaft, 80 mm long. Weight 501g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `gobilda-5204-30`: Nominal ratio 188:1; gearRatio is the exact value of goBILDA's listed formula (((((1+(46/17))) * (1+(46/17))) * (1+(46/17))) * (1+(46/17))). 8 mm REX output shaft, 80 mm long. Weight 543g. countsPerRev is goBILDA's 'Encoder Resolution ... PPR at the Output Shaft' (= 28 x ratio; these are the counts the FTC SDK reports). - `rev-hd-hex`: Page: 6000 rpm, 0.105 Nm stall, 8.5 A stall, 400 mA no-load, 28 counts/rev at the motor, 15 W max. Out of stock on 2026-10-16. Note: REV-41-1301 is the 40:1 spur version, not the bare motor. Since 1 Jan 2025 the bare motor ships with the UltraPlanetary pinion, which does NOT fit the 20:1/40:1 spur gearboxes (REV-41-1064/-1065). - `rev-hd-hex-up3`: Actual ratio from REV cartridge pages / https://docs.revrobotics.com/rev-crossover-products/ultraplanetary/cartridge-details: 3:1=84:29 (2.89), 4:1=76:21 (3.61), 5:1=68:13 (5.23). countsPerRev COMPUTED = 28 x actual ratio. freeRpm (6000/ratio) and stall torque (0.105 Nm x ratio, no gearbox loss, the same method REV's own table uses) are COMPUTED, not listed by REV. Currents are the bare HD Hex motor's. Sold as kit REV-41-1600 (motor + 3:1, 4:1, 5:1 cartridges) or cartridges separately. - `rev-hd-hex-up4`: Actual ratio from REV cartridge pages / https://docs.revrobotics.com/rev-crossover-products/ultraplanetary/cartridge-details: 3:1=84:29 (2.89), 4:1=76:21 (3.61), 5:1=68:13 (5.23). countsPerRev COMPUTED = 28 x actual ratio. freeRpm (6000/ratio) and stall torque (0.105 Nm x ratio, no gearbox loss, the same method REV's own table uses) are COMPUTED, not listed by REV. Currents are the bare HD Hex motor's. Sold as kit REV-41-1600 (motor + 3:1, 4:1, 5:1 cartridges) or cartridges separately. - `rev-hd-hex-up5`: Actual ratio from REV cartridge pages / https://docs.revrobotics.com/rev-crossover-products/ultraplanetary/cartridge-details: 3:1=84:29 (2.89), 4:1=76:21 (3.61), 5:1=68:13 (5.23). countsPerRev COMPUTED = 28 x actual ratio. freeRpm and stall torque (0.55 Nm) from REV's UltraPlanetary table (https://docs.revrobotics.com/duo-build/motion/motors/hd-hex-motor). Currents are the bare HD Hex motor's. Sold as kit REV-41-1600 (motor + 3:1, 4:1, 5:1 cartridges) or cartridges separately. - `rev-hd-hex-up12`: Actual ratio from REV cartridge pages / https://docs.revrobotics.com/rev-crossover-products/ultraplanetary/cartridge-details: 3:1=84:29 (2.89), 4:1=76:21 (3.61), 5:1=68:13 (5.23). countsPerRev COMPUTED = 28 x actual ratio. freeRpm (6000/ratio) and stall torque (0.105 Nm x ratio, no gearbox loss, the same method REV's own table uses) are COMPUTED, not listed by REV. Currents are the bare HD Hex motor's. Sold as kit REV-41-1600 (motor + 3:1, 4:1, 5:1 cartridges) or cartridges separately. - `rev-hd-hex-up15`: Actual ratio from REV cartridge pages / https://docs.revrobotics.com/rev-crossover-products/ultraplanetary/cartridge-details: 3:1=84:29 (2.89), 4:1=76:21 (3.61), 5:1=68:13 (5.23). countsPerRev COMPUTED = 28 x actual ratio. freeRpm (6000/ratio) and stall torque (0.105 Nm x ratio, no gearbox loss, the same method REV's own table uses) are COMPUTED, not listed by REV. Currents are the bare HD Hex motor's. Sold as kit REV-41-1600 (motor + 3:1, 4:1, 5:1 cartridges) or cartridges separately. - `rev-hd-hex-up20`: Actual ratio from REV cartridge pages / https://docs.revrobotics.com/rev-crossover-products/ultraplanetary/cartridge-details: 3:1=84:29 (2.89), 4:1=76:21 (3.61), 5:1=68:13 (5.23). countsPerRev COMPUTED = 28 x actual ratio. freeRpm and stall torque (1.98 Nm) from REV's UltraPlanetary table (https://docs.revrobotics.com/duo-build/motion/motors/hd-hex-motor). Currents are the bare HD Hex motor's. Sold as kit REV-41-1600 (motor + 3:1, 4:1, 5:1 cartridges) or cartridges separately. - `rev-hd-hex-up60`: Actual ratio from REV cartridge pages / https://docs.revrobotics.com/rev-crossover-products/ultraplanetary/cartridge-details: 3:1=84:29 (2.89), 4:1=76:21 (3.61), 5:1=68:13 (5.23). countsPerRev COMPUTED = 28 x actual ratio. freeRpm and stall torque (5.75 Nm) from REV's UltraPlanetary table (https://docs.revrobotics.com/duo-build/motion/motors/hd-hex-motor). Currents are the bare HD Hex motor's. Sold as kit REV-41-1600 (motor + 3:1, 4:1, 5:1 cartridges) or cartridges separately. - `rev-hd-hex-40`: Page marks it Discontinued but in stock on 2026-10-16: 150 rpm, 594.7 oz-in (4.2 Nm). countsPerRev 1120 from https://docs.revrobotics.com/duo-control/sensors/encoders/motor-based-encoders. Actual (vs nominal 40:1) ratio not published. Currents from the bare motor page (REV-41-1291). - `rev-hd-hex-20`: Product page www.revrobotics.com/rev-41-1298/ returns Not Found on 2026-10-16; values from REV docs (https://docs.revrobotics.com/duo-build/motion/motors/hd-hex-motor: 300 rpm, 297.4 oz-in / 2.1 Nm) and https://docs.revrobotics.com/duo-control/sensors/encoders/motor-based-encoders (560 counts). The 20:1 gearbox alone (REV-41-1064) is listed Discontinued, and the current bare HD Hex pinion does not fit it. Kept for older robots only. - `rev-core-hex`: Page: 125 RPM, 3.2 N-m stall, 4.4 A stall, 72:1, 4 counts/rev at the motor, 288 at the output. Free (no-load) current NOT given on the page -> null. 5 mm female hex output, 90-degree layout. - `am-neverest-orbital-1`: Page gives ratio 1:1 and speed only as '~6600 RPM' (approximate). Stall current 11 A and 14 W max power are listed for the family. Stall torque and free current NOT on the page -> null. countsPerRev DERIVED: page says 7 pulses/rev at the motor, 'multiply the ratio by 7'; x4 quadrature = 28 x ratio (same convention as AndyMark's Classic 40 page: 7 ppr <-> 1120 ticks). Exact ratio not published. Part numbers: variants by power connector (a = Anderson Powerpole, b = JST-VH-2). 6 mm D shaft. - `am-neverest-orbital-3-7`: Page gives ratio 3.7:1 and speed only as '~1784 RPM' (approximate). Stall current 11 A and 14 W max power are listed for the family. Stall torque and free current NOT on the page -> null. countsPerRev DERIVED: page says 7 pulses/rev at the motor, 'multiply the ratio by 7'; x4 quadrature = 28 x ratio (same convention as AndyMark's Classic 40 page: 7 ppr <-> 1120 ticks). Exact ratio not published. Part numbers: variants by power connector (a = Anderson Powerpole, b = JST-VH-2). 6 mm D shaft. - `am-neverest-orbital-20`: Page gives ratio 19.2:1 and speed only as '~344 RPM' (approximate). Stall current 11 A and 14 W max power are listed for the family. Stall torque and free current NOT on the page -> null. countsPerRev DERIVED: page says 7 pulses/rev at the motor, 'multiply the ratio by 7'; x4 quadrature = 28 x ratio (same convention as AndyMark's Classic 40 page: 7 ppr <-> 1120 ticks). Exact ratio not published. Part numbers: variants by power connector (a = Anderson Powerpole, b = JST-VH-2). 6 mm D shaft. - `am-neverest-orbital-50`: Page gives ratio 50.9:1 and speed only as '~130 RPM' (approximate). Stall current 11 A and 14 W max power are listed for the family. Stall torque and free current NOT on the page -> null. countsPerRev DERIVED: page says 7 pulses/rev at the motor, 'multiply the ratio by 7'; x4 quadrature = 28 x ratio (same convention as AndyMark's Classic 40 page: 7 ppr <-> 1120 ticks). Exact ratio not published. Part numbers: variants by power connector (a = Anderson Powerpole, b = JST-VH-2). 6 mm D shaft. - `am-neverest-orbital-264`: Page gives ratio 263.7:1 and speed only as '~25 RPM' (approximate). Stall current 11 A and 14 W max power are listed for the family. Stall torque and free current NOT on the page -> null. countsPerRev DERIVED: page says 7 pulses/rev at the motor, 'multiply the ratio by 7'; x4 quadrature = 28 x ratio (same convention as AndyMark's Classic 40 page: 7 ppr <-> 1120 ticks). Exact ratio not published. Part numbers: variants by power connector (a = Anderson Powerpole, b = JST-VH-2). 6 mm D shaft. - `am-neverest-classic-40`: Tagged Discontinued but purchasable on 2026-10-16. Page: 160 RPM no-load, stall 1.823 ft-lb (2.472 N-m), stall 11.5 A, ticks/rev 1120. The page lists BOTH 'Free Current 0.5 A' and 'No Load Current 0.4 A' (conflict); 0.4 A used. 'Ratio' printed as '40:01:00' (spreadsheet typo). - `am-neverest-classic-60`: Tagged Discontinued but purchasable on 2026-10-16. Page: 105 RPM no-load, stall 2.734 ft-lb (3.707 N-m), stall 11.5 A, free current 0.5 A, ticks/rev 1680. - `gobilda-2000-torque`: Headline values at 6.0 V; byVoltage has goBILDA's 4.8/6.0/7.4 V numbers. Gear ratio 300:1, weight 60 g, PWM 500-2500 us (0.150 deg/us); continuous mode PWM 900-2100 us. Continuous rotation is switched on with the 3102 Series Dual Mode Servo Programmer (sold separately). - `gobilda-2000-speed`: Headline values at 6.0 V; byVoltage has goBILDA's 4.8/6.0/7.4 V numbers. Gear ratio 135:1, weight 58 g, PWM 500-2500 us (0.15 deg/us); continuous mode PWM 1000-2000 us. Continuous rotation is switched on with the 3102 Series Dual Mode Servo Programmer (sold separately). - `gobilda-2000-super-speed`: Headline values at 6.0 V; byVoltage has goBILDA's 4.8/6.0/7.4 V numbers. Gear ratio 67:1, weight 58 g, PWM 500-2500 us (0.15 deg/us); continuous mode PWM 1000-2000 us. Continuous rotation is switched on with the 3102 Series Dual Mode Servo Programmer (sold separately). - `gobilda-2000-5turn-torque`: Headline values at 6.0 V; byVoltage has goBILDA's 4.8/6.0/7.4 V numbers. Gear ratio 300:1, weight 64 g, PWM 500-2500 us (0.90 deg/us); continuous mode PWM 900-2100 us. Continuous rotation is switched on with the 3102 Series Dual Mode Servo Programmer (sold separately). - `gobilda-2000-5turn-speed`: Headline values at 6.0 V; byVoltage has goBILDA's 4.8/6.0/7.4 V numbers. Gear ratio 135:1, weight 60 g, PWM 500-2500 us (0.90 deg/us); continuous mode PWM 900-2100 us. Continuous rotation is switched on with the 3102 Series Dual Mode Servo Programmer (sold separately). - `gobilda-2000-5turn-super-speed`: Headline values at 6.0 V; byVoltage has goBILDA's 4.8/6.0/7.4 V numbers. Gear ratio 67:1, weight 58 g, PWM 500-2500 us (0.90 deg/us); continuous mode PWM 1000-2000 us. Continuous rotation is switched on with the 3102 Series Dual Mode Servo Programmer (sold separately). - `rev-smart-servo`: Product page www.revrobotics.com/rev-41-1097/ returns Not Found on 2026-10-16 (replaced by Smart Robot Servo V2); values from REV's SRS docs page. Default 270 deg over the full pulse range; modes: Servo Limit Mode (custom angular limits) and Continuous Mode, set with the SRS Programmer (sold separately). Voltage 4.8-7.4 V (6 V typical); only 6 V performance given. Docs list gears as brass in the table but 'metal gears' in the features; a search summary of the old product page said 0.14 s/60 deg - NOT verified (page gone). - `rev-smart-servo-v2-balanced`: Steel gears, 62 g, 4.8-7.4 V (6 V nominal), 500-2500 us. Default 270 deg; up to 280 deg programmable in angular mode; continuous mode. Modes set with the SRS Programmer (sold separately). No 4.8 V figures and no free current on the page. - `rev-smart-servo-v2-ultraspeed`: Steel gears, 60 g, 4.8-7.4 V (6 V nominal), 500-2500 us. Default 270 deg; up to 280 deg programmable in angular mode; continuous mode. Modes set with the SRS Programmer (sold separately). No 4.8 V figures and no free current on the page. - `axon-max-mk2`: Specs from Axon's docs (https://docs.axon-robotics.com/servos/max; product page https://axon-robotics.com/products/max has no spec table). 85 g, H25T spline, 4.8-8.4 V, 500-2500 us, 360 deg max range; modes: servo, continuous rotation (swerve 'coming soon'), set with Programmer MK2. Axon lists 4.8 V as the REV Control/Expansion Hub servo voltage and 6.0 V as the REV Servo Power Module/Servo Hub. No part number published (sold only through distributors) -> null. 'Idle' current is in freeCurrentA. goBILDA's resale page (gobilda.com/axon-max-servo-mk2, checked 2026-10-22) lists 350 deg max rotation and 0.175 deg/us over 500-2500 us; rangeDeg keeps Axon's own 360. - `axon-max-plus`: Axon's archive page says the MAX+ is discontinued and replaced by the MAX MK2; its spec table is identical to the MK2's. Dual mode (servo/continuous) if bought after 25 Sep 2022. Range of motion NOT given on the archive page -> null. No part number published -> null. - `axon-mini-mk2`: Specs from Axon's docs (https://docs.axon-robotics.com/servos/mini; product page https://axon-robotics.com/products/mini has no spec table). 65 g, H25T spline, 4.8-8.4 V, 500-2500 us, 360 deg max range; modes: servo, continuous rotation (swerve 'coming soon'), set with Programmer MK2. Axon lists 4.8 V as the REV Control/Expansion Hub servo voltage and 6.0 V as the REV Servo Power Module/Servo Hub. No part number published (sold only through distributors) -> null. 'Idle' current is in freeCurrentA. goBILDA's resale page (gobilda.com/axon-mini-servo-mk2, checked 2026-10-22) lists 350 deg max rotation and 0.175 deg/us over 500-2500 us; rangeDeg keeps Axon's own 360. - `axon-mini-plus`: Axon's archive page says the MINI+ is discontinued and replaced by the MINI MK2; its spec table is identical to the MK2's. Dual mode (servo/continuous). Range of motion NOT given on the archive page -> null. No part number published -> null. Catalog notes: Every number was read from the seller's product page or the seller's own documentation on the 'checked' date (URL per part). Values marked COMPUTED/DERIVED in a part's notes are worked out from the seller's numbers. null = the seller does not publish it. Motor values at 12 V; servo headline values at 6.0 V with the full table in byVoltage. countsPerRev = encoder counts per output-shaft revolution as the FTC SDK reports them (x4 quadrature). Torque converted to kg-cm with 1 N-m = 10.197 kg-cm where the seller gives N-m. A part added here is also added to library/.../robot/Parts.java (wheels, servos) or Motors.java (motors); PartsCatalogTest and MotorsCatalogTest check they match. Servos: rangeDeg is the seller's full turn over pulseMinUs-pulseMaxUs (the pulse range the seller gives; null = not given). The FTC SDK sends 600-2400 us for positions 0-1 unless the code widens it (.fullRange()), so on a normal hub a servo turns rangeDeg x 1800 / (pulseMaxUs - pulseMinUs): a goBILDA 2000 servo 270 deg, not 300 (SDK 12.0 PwmControl.PwmRange.defaultRange, checked 2026-10-22). Servos: biggerTurns = which way a bigger position (a longer pulse) turns it, as the seller states it (goBILDA's spec tables: 'Clockwise w/ Increasing PWM Signal', checked 2026-11-05; the side it is seen from is not stated); null = the seller does not say (REV, Axon: an Axon servo's direction can also be switched with its programmer). A hint only: check by test. --- # Profiles: practice vs competition URL: https://crossbotics.com/ftc-helper/docs/guides/profiles/ **For:** teams getting ready for practice and events. **You need:** a TeleOp or autonomous that runs (any robot in five files: [The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). The same robot code should be **helpful in the shop**: debug numbers, live tuning. It should also be **safe at an event**: no tuning menu, no surprise values, nothing extra on the screen. A profile switches between the two, and you do not change the code. ## The two profiles | | PRACTICE | COMPETITION | | --- | --- | --- | | Drive power | the same: `maxPower` (unless you set `practiceMaxPower`) | `maxPower` | | Debug telemetry | starts ON | starts OFF | | Tuning menu | can open | stays closed | | INIT screen | warns "PRACTICE profile" | normal | | A part that is off ([`optional()`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet), device not in the configuration) | a quiet note | a loud `!!` warning at the top, and `!! OFF` on the button map | | Your `Profile.pick(a, b)` values | `a` | `b` | **The drive power is the same in both,** so the drivers practice at match speed. `practiceMaxPower` in `Tunables.Drive` can set a lower top power for PRACTICE only, for example for a brand-new driver's first day. **COMPETITION is the default**, so a robot that nobody set up is in the safe mode. ## Choosing the profile The Control Hub saves the profile, and it stays until you change it. You can change it in two ways: 1. **INIT menu** (the easier way): every autonomous (`EasyAuto`, `Auto`) has a "Profile" line. Press the D-pad to reach it, and left/right to change it. A TeleOp has no such line (it only warns when PRACTICE is on). A TeleOp you write yourself can add `.profile()` to an `InitMenu`. 2. **Code**: `Profile.set(Profile.PRACTICE)`. To see which one is on, any OpMode can show `Profile.current()`. ## Using it in your code ```java // Numbers: Profile.pick(value in PRACTICE, value in COMPETITION) int logEvery = Profile.pick(1, 10); // log every loop in the shop, every 10th at events // Features boolean liveView = Profile.pick(true, false); // camera preview only in practice // or ask directly which profile is on: if (Profile.current().isPractice()) { ...extra checks, logging... } ```
flowchart LR
    P{Profile.current} -- PRACTICE --> A["practice value<br/>debug on, tuning allowed"]
    P -- COMPETITION --> B["competition value<br/>debug off, tuning blocked"]
## Event checklist At the event, before the first match: 1. INIT any autonomous and set **Profile: COMPETITION** in its menu. 2. Check that the INIT screen has **no** "PRACTICE profile" warning. 3. Check that there is no "tuned value(s) differ from the code" warning, or that you meant it. 4. Check that there is no `!! COMPETITION: "..." not in the configuration: ... is OFF` warning for a part that IS on the robot. That warning means a misspelled or lost configuration name. At the shop (PRACTICE), a part that you have not built yet gives only a note. At an event the warning is loud on purpose. After the event, set PRACTICE again for the shop. ## What should NOT differ between profiles Safety stays the same: limits, hard stops, jam handling, timeouts. Never make a profile turn off a safety feature. Profiles change only comfort and convenience. --- # Your robot in the simulator: the robot-file skill URL: https://crossbotics.com/ftc-helper/docs/guides/robot-file-skill/ **For:** teams that want the [simulator](https://crossbotics.com/ftc-helper/docs/simulator/) to act like their own robot. **You need:** an AI coding agent (Claude Code, Codex or similar), your robot project with ftc-helper-lib in it, and a tape measure. The simulator moves like YOUR robot only when its robot file (`simulator/robot.properties` in your robot project) describes your robot. The file lists every device name, the motors and servos, the size, the mechanisms and cameras. You can write it by hand ([simulator guide](https://crossbotics.com/ftc-helper/docs/simulator/)). An AI coding agent can do most of it for you with the **robot-file skill**. A skill is a set of written instructions that the agent follows. This one is in `ftc-helper-lib/skills/robot-file/`.
flowchart LR
    C["Robot configuration<br/>(Control Hub XML)"] --> D["fromConfig<br/>draft robot file"]
    D --> Q["Agent asks the team<br/>(measurements, parts, photos)"]
    Q --> R["robot.properties<br/>+ shapes, cameras, pieces"]
    R --> K["Checks: loads, size rules,<br/>your OpModes INIT"]
    K --> F["Characterizer + fit<br/>real speeds"]
## Set it up Do this once, in your robot project. To turn on this skill and the ftc-helper skill (answers to "how do I" questions) together, follow [Ask an AI agent](https://crossbotics.com/ftc-helper/docs/guides/ask-an-ai-agent/#set-it-up) instead. - **Claude Code**: copy (or link) the skill into your robot project: ```bash mkdir -p .claude/skills && cp -r ftc-helper-lib/skills/robot-file .claude/skills/ ``` Then ask: "Make our simulator robot file" (or "our robot has a new arm: update the robot file"). - **Other agents (Codex and others)**: add one line to your robot project's `AGENTS.md`: "To make or update the simulator robot file, follow ftc-helper-lib/skills/robot-file/SKILL.md." ## What it does 1. Reads your **robot configuration** and makes a draft with the tool below. The configuration is `/sdcard/FIRST/.xml` on the Control Hub. Get it with the REV Hardware Client or Android Studio's Device Explorer. 2. Reads your **TeamCode** (motor names, directions, limits, finder results). 3. **Asks you** the rest, a few questions at a time. It asks about sizes (bring a tape measure), which motors and servos, the lift's and arm's hard stops (from the Motor Finder), where the cameras are, how the robot picks up and scores pieces. **With photos and a tape measure (no CAD):** give it photos of the robot from the side, the top and the front. Add photos of each moving part at both ends of its travel. Keep a field tile or a tape measure in view. It reads where each part sits from the photos. Then it asks you for the few numbers that decide a rule (measured from the robot's edges and the floor). It checks its 3D robot against your photos with you. Photos stay on your computer (`skills/robot-file/photos.md`). **With CAD of the whole robot:** give it the STEP file. It reads the exact sizes, places, spin axes and seller part numbers from it. It guesses which motor drives which part, and asks you only when it is not sure. It draws your real parts in the 3D view (`skills/robot-file/cad.md`, tools in `tools/cad/`). **With Robot.java in five files:** the sizes and shapes it learns go into Robot.java (`part(...)`, `looks(...)`, `chassisMm`). Then `./gradlew :sim:fromRobot` writes the robot file from it, so the code and the simulator stay one description. To fix a shape by eye afterwards, use the simulator's **Edit robot** mode, and copy the `.looks(...)` lines it shows into Robot.java. 4. **Checks** the result in the simulator (it loads, the size rules, your OpModes start). It writes a small scenario, so the check runs again later. 5. Tells you what is still unknown, and how to get real speeds (the Characterizer). It never makes up a number without saying so. Each number in the file has a note that says where it came from (measured, the configuration, a seller page, a photo estimate, a default). ## The draft tool on its own **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:fromConfig -Pconfig=path/to/config.xml -Pout=../simulator/robot.properties ``` Run it from the `ftc-helper-lib` folder. `-Pconfig=` is the configuration file to read, and `-Pout=` is the robot file to write. The tool: - lists every device of the configuration, and writes a robot file with each one under its exact name; - matches the motor types that pin down a part (REV HD Hex 20:1 and 40:1, Core Hex, NeveRest) to the parts catalog; - marks everything else `TODO`, checks that the draft loads, and prints the questions still open. It finds the drivetrain from the motor names (front/back and left/right in any form: `front_left`, `leftFront`, `fl`...). A goBILDA Pinpoint or SparkFun OTOS becomes the `odometry = ...` line, with a `TODO` for its offsets or mounting. Color and distance sensors and lights get their lines too. The tool lists devices that the simulator does not have yet as notes. When the robot file exists, the draft goes next to it (`robot.properties.draft`). An example configuration is `sim/configs/example-config.xml`. | Configuration type | Becomes | | --- | --- | | a motor type (goBILDA 5202/3/4, REV HD Hex, Core Hex, NeveRest, unspecified...) | `motor.NAME` (or the drivetrain), and the part when the type tells it | | `Servo`, `ServoFullRange` | `servo.NAME` | | `ContinuousRotationServo`, `RevSPARKMini` | `crservo.NAME` | | any type with "imu" in its name (`ControlHubImuBHI260AP`, `LynxEmbeddedIMU`, `RevExternalImu`...) | `imu` | | `RevTouchSensor`, `DigitalDevice`, `ModernRoboticsAnalogTouchSensor` | `touch.NAME` | | `Webcam` | `camera.KEY = name=...` | | `EthernetDevice` (a Limelight) | `limelight.KEY = name=...` | | `HuskyLens` | `huskylens.KEY = name=...` (then add `hfov=` and `taught=`) | | anything else | a note: not simulated yet | --- # The BIOBUZZ starter bots: robot files and code URL: https://crossbotics.com/ftc-helper/docs/guides/starter-bots/ **For:** a team with one of these starter bots ([A starter bot](https://crossbotics.com/ftc-helper/docs/pick-your-start/01-starter-bot/) in Pick your start), or anyone who wants a ready robot to try in the [simulator](https://crossbotics.com/ftc-helper/docs/simulator/). For each starter bot, you find its [configuration names](#the-configuration-names) and what its code does differently. At the end: [what to change when you changed the robot](#you-changed-your-starter-bot). Each seller in FTC (REV, goBILDA, AndyMark, Studica) gives away the design of a simple "starter bot" for the season. For 2026-27 (BIOBUZZ), we wrote one robot file for each, so the simulator has real, different robots to test with. goBILDA has two: the standard StarterBot (6-wheel tank drive) and the StarterBot with mecanum wheels, built on a Strafer chassis. That makes five. They are also worked examples for the robot-file skill ([robot-file-skill.md](https://crossbotics.com/ftc-helper/docs/guides/robot-file-skill/)): every number has a note that says where it came from. | Robot file | Drive | Intake | Scores with | Size in the simulator | | --- | --- | --- | --- | --- | | [starter-bot-rev.properties](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/sim/robots/starter-bot-rev.properties) | 6 wheels, 2 motors | flap wheels (Core Hex) | flywheel + CR-servo feeder | 17.5 x 17.2 in, 15.0 in tall (20.0 in wide with the poker out) | | [starter-bot-gobilda.properties](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/sim/robots/starter-bot-gobilda.properties) | 6 wheels, drop center, 2 motors | Gecko wheels (motor + 2 CR servos) | flywheel + CR-servo "windmill" | 17.8 x 16.8 in, 12.0 in tall | | [starter-bot-gobilda-strafer.properties](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/sim/robots/starter-bot-gobilda-strafer.properties) | 4 mecanum wheels (Strafer), 4 motors | Gecko wheels (motor + 2 CR servos) | flywheel + CR-servo "windmill" | 17.8 x 17.8 in, 12.2 in tall | | [starter-bot-andymark.properties](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/sim/robots/starter-bot-andymark.properties) | 4 wheels, belts, 2 motors | rubber-band rollers (CR servo) | rubber-band catapult | 17.2 x 17.7 in, 17.5 in tall | | [starter-bot-studica.properties](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/sim/robots/starter-bot-studica.properties) | 2 driven wheels + 2 omni | 4 wheels (motor) | flywheel + servo flap | 14.0 x 15.0 in, 13.0 in tall | **Code for each one:** every kit bot is also a robot in five files with the seller's configuration names: [`gobildabot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/gobildabot), [`gobildastraferbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/gobildastraferbot), [`revbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/revbot), [`andymarkbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/andymarkbot) and [`studicabot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/studicabot). To copy one into your TeamCode, read [Start from a starter bot](https://crossbotics.com/ftc-helper/docs/pick-your-start/01-starter-bot/). The library has no catapult part (AndyMark), and it cannot put a gear between a flywheel motor and its wheel (Studica). Those two files use the closest part and say so. Each file names each part's motor or servo (`.part(...)`, or the motor's id in a launcher's brackets). So the starting values are those parts' real numbers. Some parts are not in the parts catalog: Studica's Maverick motors and Multi-Mode Smart Servo, and AndyMark's High Speed programmable servo. The files describe them with `Motors.custom(...)` and `Parts.customServo(...)` and the seller's numbers. **The autonomous programs** (`autos/`) are the same for all five. Each starts at the simulator robot file's start spot: back against your wall, 56 in left of the center. `mirrorForRed()` returns false. BIOBUZZ's field is turned half a turn between the alliances (not mirrored). So the same route works for both alliances, when each one drives it from its own wall. **Shooting in the simulator:** only the two goBILDA bots shoot. The REV, AndyMark and Studica files have no `shoot.` line, because their sellers do not publish the launch direction and angle. So their launchers spin, but no piece flies. Their flywheels may also not reach "ready" in the simulator: the stand-in motor numbers are guesses (see each robot below). All five fit the 18 in start cube, and 18 x 24 x 29 in at full reach. Each has a scenario in `sim/scenarios/starter-bot-*.sim`, so they run in the automatic tests. The scenario loads the robot with a `robot ../robots/...` line, checks the size rules, rolls the robot forward by hand and checks for no error. To drive one in the simulator (`-Probot=` picks the robot file): **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:run -Probot=sim/robots/starter-bot-gobilda.properties ``` To run its scenario (`-Pfile=` picks the scenario file): **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:scenario -Pfile=sim/scenarios/starter-bot-gobilda.sim ``` **How sure the numbers are:** goBILDA and AndyMark publish STEP CAD files. We measured them on a laptop (the bounding box of each part: the smallest box around it) and wrote down only the numbers. So their sizes and part positions are measured. REV's CAD is on Onshape, which needs a sign-in. Studica's STEP download sits behind a browser check. So we worked out their sizes from the part lengths in the build guides and the photos, and marked them "est." in the file. No seller's CAD is in this repository: nobody checked the licenses, and the robot files hold only our own numbers. **Same for all five:** - The start pose is x = -56, with the back against the red wall (field file: inside face at y = -70.585). - No seller states the game-piece capacity, so `holds=4` is the game's limit. - The motor directions come from the sellers' code, where it has them. ## The configuration names Make the robot configuration on the Driver Station with these names ([how](https://crossbotics.com/ftc-helper/docs/setup/07-robot-configuration/)). They are the names in each seller's own code, so the template runs on the starter bot as it is. Use the port that each wire is in on your robot. Leave the `imu` line as it is (the Control Hub's own IMU). When a motor type is not in the Driver Station's list, pick the closest one: the library takes the motor's numbers from `Robot.java`. **goBILDA:** | Name | Kind | What it is | | --- | --- | --- | | `left_drive`, `right_drive` | Motor (goBILDA 5202/3/4 series) | the drive motors (312 RPM) | | `intake` | Motor (goBILDA 5202/3/4 series) | the intake roller (117 RPM) | | `launcher` | Motor (goBILDA 5202/3/4 series) | the flywheel (a 312 RPM motor with its gearbox taken off) | | `left_intake_servo`, `right_intake_servo` | Continuous Rotation Servo | the two corner wheels | | `windmill` | Continuous Rotation Servo | the feeder | **goBILDA with mecanum wheels (Strafer):** the same mechanisms, four drive motors, and one other name: the feeder is `windmillServo`. | Name | Kind | What it is | | --- | --- | --- | | `left_front_drive`, `right_front_drive`, `left_back_drive`, `right_back_drive` | Motor (goBILDA 5202/3/4 series) | the drive motors (312 RPM) | | `intake` | Motor (goBILDA 5202/3/4 series) | the intake roller (117 RPM) | | `launcher` | Motor (goBILDA 5202/3/4 series) | the flywheel (a 312 RPM motor with its gearbox taken off) | | `left_intake_servo`, `right_intake_servo` | Continuous Rotation Servo | the two corner wheels | | `windmillServo` | Continuous Rotation Servo | the feeder | **REV:** | Name | Kind | What it is | | --- | --- | --- | | `leftDrive`, `rightDrive` | Motor (REV UltraPlanetary HD Hex) | the drive motors (20:1) | | `intakeMotor` | Motor (REV Core Hex) | the intake | | `flywheel` | Motor (REV HD Hex) | the flywheel (no gearbox) | | `crServo` | Continuous Rotation Servo | the feeder roller | | `pollenServo` | Servo | the pollen pusher ("poker") | **AndyMark:** | Name | Kind | What it is | | --- | --- | --- | | `left_drive`, `right_drive` | Motor (the closest NeveRest type) | the drive motors (NeveRest Hex 19.2:1) | | `rollerI` | Continuous Rotation Servo | the intake rollers | | `rollerF` | Continuous Rotation Servo | the flower roller (the "stick" version has a `stick` Servo instead) | | `catapult` | Motor (the closest NeveRest type) | the catapult (NeveRest Hex 50.9:1) | **Studica:** | Name | Kind | What it is | | --- | --- | --- | | `leftDrive`, `rightDrive` | Motor (the closest type to a Maverick 50.9:1) | the drive motors | | `Intake` | Motor | the intake (Maverick 3.7:1) | | `FlyWheel` | Motor | the flywheel (Maverick 1:1) | | `fwActuator` | Servo | the flap that pushes each piece into the wheels | Capitals count: Studica's `Intake` and `FlyWheel` start with a capital letter. ## REV DUO FTC Starter Bot Sources, read 2026-10-16: [the starter bot page](https://www.revrobotics.com/duo/ftc-starter-bot/), its [build guide (PDF, 126 pages)](https://www.revrobotics.com/content/technical-resources/DUO/FTC-Kickoff-Concepts/2026-27/2026-27_REV_DUO_FTC_Starter_Bot-Build_Guide_1567.pdf), and the [TeleOp code and configuration page](https://docs.revrobotics.com/ftc-kickoff-concepts/home/programming-teleop-and-auto). CAD (not used, it needs a sign-in): [Onshape](https://cad.onshape.com/documents/9cb9eb90e973fd37d10ee178/w/b9c02b0f4e09998f08becbd2/e/a55c018c62564f3ea8812a47). Modeled: - the tank drive (`leftDrive`, `rightDrive`: 20:1 UltraPlanetary HD Hex, 90 mm wheels, 1:1 chain). - the intake roller (`intakeMotor`, Core Hex). - the flywheel (`flywheel`, HD Hex at 1:1, two 90 mm grip wheels) on its frame. - the feeder roller (`crServo`, Smart Robot Servo in CR mode). - the pollen pusher ("poker", `pollenServo`), as an arm on the left side. It collects POLLEN. Not modeled or not published: - The shot: its CR-servo feeder could be the launcher's `feeder=`. But REV's pages do not give the flywheel's target speed or the launch angle, so there is no `shoot.` line. - Sizes: all estimated (nobody measured CAD). The page does not give the pollen pusher's preset positions. The model swings it 0 to 90 degrees out to the side, a guess. - The real pusher swings up and down, out to the side. The simulator's arm always points forward from its hinge, so the simulator draws it turning about "up" instead. ### REV bot code [`revbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/revbot) is this robot in five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/) walks through them). The configuration names are the ones in REV's own code, so it runs on that robot as it is. These facts are not in the code's comments: - **Drive:** REV's code does not reverse a drive motor, so the library's default (the left side reversed) is a guess. If the robot spins when you push the stick forward, change it ([Robot.java](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#a-wheel-turns-the-wrong-way)). REV does not say which way each motor turns: check them all on your robot. - **Intake:** REV's code takes POLLEN in with the right bumper and pushes it out with the right trigger. REV's page does not say which power sign is "in". If the intake pushes out when it should take in, add `.reversed()` to its line. - **Launcher:** the HD Hex motor runs at 1:1 (its gearbox is off), so `"rev-hd-hex"` gives it the 6000 RPM motor's numbers. The feeder roller is a Smart Robot Servo V2 (Balanced) in continuous (CR) mode. REV's code spins the flywheel "to the target velocity", but the page does not give the number. `speedRpm = 3000` is a guess, and so is the feeder's 0.4 s per piece. Find kF and kP with the [Flywheel Finder](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/). Then find the speed by watching shots. - **Fire all (Y):** the launcher spins up. As soon as the wheel is at speed, it feeds the pieces one by one. It uses only the launcher, so the driver can still run the intake. With fewer than 4 pieces, the feeder only turns a few more times. - **Poker:** a Smart Robot Servo V2 (Balanced) with two spots, as in REV's code. A = `down`: out over a FLOWER, to comb POLLEN out of it. B = `up`: folded along the side, the start. REV's page has no numbers for them, so both are `MEASURE`. INIT stops until you measure them with the [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/) and write them in `Tunables.java`. **Why:** a guess could swing the poker into the frame. The simulator's REV robot file has stand-ins for them, so it runs before you measure. Nothing moves at INIT, so the code does not fold the poker. Fold it by hand before INIT, so the robot fits the 18 in start cube. The poker first moves when A, B or an action sends it. - **Buttons:** one driver on gamepad 1, with each part's usual buttons written out (LB flywheel on/off, RB fire one, D-pad up/down speed +/- 100 RPM). So this robot drives like the other examples. REV's code puts the intake on RB and RT, and runs the feeder by hand on the D-pad. If your drivers want REV's layout, change the buttons in `Controls.java`. - **Autonomous** (`autos/`): REV's own autonomous is not on its page, so this is a simple first one. It fires the preloaded pieces, then drives off the start line in the last 3 s. ## goBILDA FTC StarterBot Sources, read 2026-10-16: [the resource guide page](https://www.gobilda.com/ftc-starter-bot-resource-guide-2026-2027-season/), its [assembly instructions (PDF, 37 pages)](https://www.gobilda.com/content/user_manuals/3200-2627-0003_assembly-instructions.min.pdf), [example code (ZIP)](https://www.gobilda.com/content/downloads/3200-2627-0003_example-code.zip) and [STEP CAD (ZIP)](https://www.gobilda.com/content/step_files/3200-2627-0003.zip), measured. Modeled: - the drop-center 6-wheel tank drive (`left_drive`, `right_drive`: 19.2:1 Yellow Jacket, 96 mm wheels, 30T to 30T gears). - the intake (`intake`, 50.9:1, seven 48 mm Gecko wheels), and the two flat 72 mm Gecko wheels at the front corners (`left_intake_servo`, `right_intake_servo`, CR servos). - the launcher (`launcher`, a 19.2:1 converted to 1:1, one 96 mm Hogback wheel) under the hood gridplate. - the `windmill` feeder CR servo. It collects POLLEN and **shoots**. The launcher's `feeder=windmill` is the CR servo. The shot leaves up and backward at 147 degrees from forward, because the hood rises 33 degrees toward the back in the CAD. So the simulator's shot arc says "shoots backward, 33° up" for it. Its autonomous, **goBILDA Bot Launch and Back Up**, starts with the robot's back against your wall, left of center (x -56, y -62.95, facing the field). The simulator puts it there at INIT. It fires the preload up and back over the robot, then drives `Away from the wall` (forward 4.7 in, at power 0.4). Its frame is 15.1 in long (17.8 in with the intake wheels), so at y -62.95 its center is 7.6 in from the wall's inside face (y -70.585). goBILDA's code launches for 10 s. Here the launch ends as soon as the feeder sends the last piece. ### goBILDA bot code [`gobildabot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/gobildabot) is this robot in five files. Part by part: - Drive: one motor per side. The right one runs reversed, as in goBILDA's code. - Intake: the roller's motor is the 117 RPM Yellow Jacket (50.9:1, 5203-2402-0051). The two corner wheels are goBILDA Speed servos in CR mode. They run with the roller, as in goBILDA's code. The intake carries 4 POLLEN and no NECTAR (a NECTAR is too big for it): `.holds(4).holds(0, "NECTAR")`. So the simulator's intake does not take a NECTAR. Count yours by hand ([Tuning](https://crossbotics.com/ftc-helper/docs/tuning/)). - Launcher: a 312 RPM motor with its gearbox taken off (1:1, 28 counts per turn). Those are the 6000 RPM motor's numbers, so its id is `gobilda-5203-6000`. - Windmill: a 2000 Series Torque servo (2000-0025-0002) in CR mode. It runs reversed, as in goBILDA's code (`Direction.REVERSE`). - Each part names its motor or servo from goBILDA's build guide, so the starting values and the simulator use that part's real numbers. **The TeleOp buttons** (`oneDriver = true`: one driver does everything on gamepad 1, like goBILDA's TeleOp): - Left stick forward/back drives, and right stick X turns. Left stick click: slow on/off. - RT runs the intake in, and LT runs it out, while you hold the trigger. - LB spins the flywheel up and down. RB fires one piece when the wheel is at speed. Hold RB to keep firing. - Y fires all four preloads (`Actions.fireAll`). Hold RT at the same time to help push them in. The action uses only the launcher, so the intake stays free for the driver. - D-pad up/down: flywheel speed +/- 50 RPM. One difference from goBILDA's code: there, RB also spins the wheel up. Here LB spins it up too, so the driver can spin up early and fire the moment the shot lines up. RB alone also works: it spins up first, then fires. Not modeled or not published: - goBILDA does not publish the exit angle and speed of a shot. We estimated them from the hood, and `share=0.5` is the default. - The 100T/20T gear pair on the intake: the guide does not make clear which gear is on the motor. The simulator does not use it anyway, because a roller only needs to turn. - The simulator does not draw the lower 264 mm roller of small "Intake Roller" parts at the front. - No source states which side `left_intake_servo` is on. ## goBILDA FTC StarterBot with Mecanum Wheels Sources, read 2026-11-09: [the resource guide page](https://www.gobilda.com/ftc-starterbot-with-mecanum-wheels-resource-guide-2026-2027/), the [Strafer Chassis Kit page](https://www.gobilda.com/strafer-chassis-kit-104mm-gripforce-mecanum-wheels/), [example code (ZIP)](https://www.gobilda.com/content/downloads/3200-2627-0004_example-code.zip) and [STEP CAD (ZIP)](https://www.gobilda.com/content/step_files/3200-2627-0004.zip), measured with `tools/cad/robot_cad.py`. This is the same robot as the goBILDA StarterBot above, on a different chassis. It uses the 2026-2027 FTC Starter Kit, a Strafer Chassis Kit and two Flat Pattern Mounts. Modeled: a mecanum drive (`left_front_drive`, `right_front_drive`, `left_back_drive`, `right_back_drive`: 312 RPM Yellow Jackets through 1:1 miter gears, 104 mm GripForce mecanum wheels). The intake, corner wheels, launcher and windmill are the same as on the 6WD bot, measured again in this robot's CAD. Here the hood sits at a 37-degree tilt, so the shot leaves up and backward at 143 degrees from forward. goBILDA's mecanum code is a TeleOp only. Its autonomous here, **goBILDA Strafer Bot Launch and Leave**, is ours. It starts with the back against your wall, like the 6WD bot's, and fires the preload. Then it drives `Leave` forward (20 in, a starting guess: the number is in the step). ### goBILDA Strafer bot code [`gobildastraferbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/gobildastraferbot) is this robot in five files. It is the [goBILDA bot's code](#gobilda-bot-code) with three changes: - Drive: `Drive.mecanum(...)` with goBILDA's four names. The two left motors run reversed, as in goBILDA's code. - The feeder's name is `windmillServo`, so its numbers are in `Tunables.WindmillServo`. - The left stick also slides the robot sideways (left stick X), as in goBILDA's code. **The TeleOp buttons** are the 6WD bot's, plus the sideways slide. Not modeled or not published: - goBILDA does not publish the exit angle and speed of a shot. We estimated them from the hood, and `share=0.5` is the default. - In the CAD, the drive wheels sit 24 mm behind the frame's center. The simulator turns the robot about the frame's center. - No source states which side `left_intake_servo` is on. ## AndyMark Robits BIOBUZZ StarterBot Sources, read 2026-10-16: [the kit page](https://andymark.com/products/robits-biobuzz-starterbot) (parts list), [the StarterBot page](https://andymark.com/pages/2026-2027-robits-starterbot-base) with the [assembly guide](https://cdn.shopify.com/s/files/1/0644/2303/5052/files/BIOBUZZ_StarterBot_Guide_REV1.pdf?v=1790188781), [user manual](https://cdn.shopify.com/s/files/1/0644/2303/5052/files/FTC_BIOBUZZ_Robits_StarterBot_User_Manual.pdf?v=1789231495), [TeleOp code](https://cdn.shopify.com/s/files/1/0644/2303/5052/files/RobitsStarterBotTeleop_051df575-88c0-401f-9b66-629c8754c6b8.java?v=1789231494) and [STEP CAD](https://s3.amazonaws.com/andymark-files/CAD%20Files/Robits%20BIOBUZZ%20Robot.STEP) (roller flower version), measured by subassembly. Modeled: - the skid-steer tank drive (`left_drive`, `right_drive`: NeveRest 19.2:1, 3 in Stealth and omni wheels, 40T to 40T, belts). - the intake rollers (`rollerI`, CR servo) and the intake frame. - the hopper. - the electronics and Control Hub. - the launcher frame on the left side (`catapult` motor, NeveRest 50.9:1, as a free-spinning motor). - the flower roller on the right side (`rollerF`, CR servo). - the `stick` servo of the other flower version (not drawn). It collects POLLEN. Not modeled or not published: - The shot: the simulator has no part for a catapult that a motor winds and rubber bands throw. AndyMark does not publish its release angle, which the hood sets. - The NeveRest Hex gearmotors (the drive's am-5442, am-5550-0100-019 in the CAD, and the catapult's am-5443) are not in the parts catalog. The files use the NeveRest Orbital 20 and 50 (the same motor and ratio). AndyMark's page gives only "~344 RPM" and "~130 RPM". - The drivetrain has its own guide (ROBITS Starter Chassis), which we did not read. The 1:1 gears and the wheel base come from the CAD. We estimated the track width, because each side is in its own CAD frame. - We estimated the intake rollers' exact place inside the intake subassembly. ### AndyMark bot code [`andymarkbot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/andymarkbot) is this robot in five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/) walks through them). The configuration names are the ones in AndyMark's own code (RobitsStarterBotTeleop), so it runs on that robot as it is. These facts are not in the code's comments: - **Drive:** the kit's NeveRest Hex 19.2:1 is the same motor and ratio as the NeveRest Orbital 20, so the code uses `"am-neverest-orbital-20"`. The right motor runs reversed, as AndyMark's code sets it. - **Intake:** `rollerI` runs reversed (REVERSE in AndyMark's code), and the flower roller `rollerF` runs with it. Their servo is the kit's 4-wire Programmable Servo, High Speed (am-4955a), in continuous mode. It is not in the parts catalog. So `Parts.customServo("am-4955a", 300, 0.05)` describes it with AndyMark's numbers: 300 degrees, 0.05 s per 60 degrees at 6 V (the only speed listed; [am-4955](https://andymark.com/am-4955), read 2026-10-23). AndyMark's code runs the rollers at full power both ways. - **The catapult** (a NeveRest Hex 50.9:1, am-5443, the same as the NeveRest Orbital 50; REVERSE in AndyMark's code) winds rubber bands and lets go once per turn. The library has no catapult part. The closest real part is an `Indexer` on a motor. It runs the motor at a set power (`power`, 0.65 from AndyMark's code) for a set time (`feedSec`) per press. Tune `feedSec` so that one press is one turn of the catapult. That is one throw, and the arm stops ready for the next. With no load, the motor turns at about 130 RPM, so one turn at 0.65 power takes about 0.7 s. The rubber bands make it take longer, so 0.8 s is a starting guess. The catapult has no sensor, so the library does not know when it is wound or lets go. So the library cannot wait for "ready" the way it does for a flywheel launcher. AndyMark's own code runs the motor for as long as the driver holds the trigger. - **Throw all (Y):** throws up to 4 pieces (the game's limit), one turn each. The hopper feeds the next piece by gravity, so there is a short wait between throws (0.5 s, in `Actions.java`). - **The flower "stick" version:** the flower mechanism has a second version, with a `stick` servo instead of the roller. For that version, take `"rollerF"` out of the intake line, and add the commented `stick` line in `Robot.java` (`Tunables.Stick`: in = 0.46, out = 0.65). AndyMark does not say which of the kit's servos the stick has. Use the one on yours (`"am-4955a"` if it is a High Speed servo too). - **Buttons:** one driver on gamepad 1, with each part's usual buttons written out (RT intake in, LT out, RB throws one piece). So this robot drives like the other examples. AndyMark's code puts the intake on the bumpers (LB in, RB out), and runs the catapult while the driver holds RT. If your drivers want AndyMark's layout, change the buttons in `Controls.java`. - **Autonomous** (`autos/`): AndyMark's own autonomous is not on its page, so this is a simple first one. It throws the preloaded pieces, then drives off the start line in the last 3 s. AndyMark's manual says to shoot from against the field wall, with the launcher in line with the goal. ## Studica FTC Starter Bot Sources, read 2026-10-16: [the resource guide page](https://www.studica.com/ftc-starter-bot-resource-guide-2026-2027), its [build guide (PDF, 64 pages, version 1.0 of 12 Sept 2026)](https://www.studica.com/images/uploaded/Resources/SR/2026-2027%20Starter%20Kit%20Build%20Guide.pdf), the Blocks code picture on that page, and the [Maverick motor page](https://www.studica.com/maverick-planetary-dc-gear-motor-wencoder-5091-ratio-gearbox) (speed and encoder counts for every ratio). The pages are behind a browser check, so we read them in a browser. STEP CAD: [ZIP](https://www.studica.com/images/uploaded/StepFiles/Starter%20Bot%202026-2027.zip), not downloaded. Modeled: - the tank drive (`leftDrive`, `rightDrive`: Maverick 50.9:1 through 36T bevel gears to 100 mm wheels, omni wheels behind). - the intake (`Intake`, Maverick 3.7:1, four 50 mm wheels). - the flywheel (`FlyWheel`, Maverick 1:1, three 100 mm wheels). - the hood. - the `fwActuator` servo (positions 0 and 0.2 in the code). The Maverick motors are not in the parts catalog, so `rpm=` and `ticksPerRev=` come from Studica's table. It collects POLLEN. Not modeled or not published: - The shot: the servo flap could be the feeder (with `feeder=`, a servo feeds while it is more than 0.15 from where it starts). But Studica does not publish the launch direction and angle, so there is no `shoot.` line. - The flywheel turns at half the motor's speed (13T to 26T bevel gears). The simulator takes the rim speed straight from the motor, so a `shoot.` line would need `share=` halved. - Sizes: all estimated (nobody measured CAD). The Multi-Mode Smart Servo is not in the parts catalog, and the kit page does not give its speed. So this file moves it at `servo.speed`. Studica's [servo page](https://docs.wsr.studica.com/en/latest/docs/Motors/servo-motors.html), read 2026-10-23, gives 300 degrees, 0.25 s per 60 degrees at 4.8 V. `studicabot/Robot.java` uses these. ### Studica bot code [`studicabot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/studicabot) is this robot in five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/) walks through them). The configuration names are the ones in Studica's own Blocks code, so it runs on that robot as it is. These facts are not in the code's comments: - **The Maverick motors and the Multi-Mode Smart Servo** are not in the parts catalog. So `Motors.custom(...)` and `Parts.customServo(...)` describe them with Studica's own numbers. The speed at 12 V and encoder counts per output turn come from the [Maverick page](https://www.studica.com/maverick-planetary-dc-gear-motor-wencoder-5091-ratio-gearbox). The servo's numbers come from the [servo page](https://docs.wsr.studica.com/en/latest/docs/Motors/servo-motors.html). We read both on 2026-10-23. The starting values and the simulator then use the real parts. - **Drive:** two driven 100 mm wheels at the front (Maverick 50.9:1, bevel gears 1:1) and two free omni wheels at the back. The library reverses the left side by default, as Studica's code does. - **Intake:** Studica's code runs it at power 1 (in) on the right bumper and -1 (out) on the left bumper. - **Launcher:** three 100 mm wheels on a Maverick 1:1, through 13T to 26T bevel gears, so the wheels turn at half the motor's speed. The library's launcher cannot take a gear between the motor and the wheel. So its speed numbers (`speedRpm`, the D-pad's +/- 100) are the MOTOR's, not the wheel's. Studica's code runs the flywheel at the right trigger's power, with no set speed. The motor's top speed is 6100 RPM, so 4000 is a starting guess with room to speed up. Tune it by watching shots. - **The flap** (`fwActuator`) pushes each piece into the wheels: rest = 0 and push = 0.2, from Studica's code (X and A). The flap goes to rest when the OpMode starts (▶). Your servo's horn may sit differently from Studica's, so measure both with the [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/) BEFORE the first TeleOp. The push and return times are guesses. - **Fire all (Y):** the launcher spins up. As soon as the wheel is at speed, the flap pushes the pieces in one by one. It uses only the launcher, so the driver can still run the intake. - **Buttons:** one driver on gamepad 1, one stick to drive, and each part's usual buttons written out. So this robot drives like the other examples. Studica's code drives "tank style" (each stick runs one side). It puts the intake on the bumpers, the flywheel on RT and the flap on X and A. If your drivers want Studica's layout, change the buttons in `Controls.java`. - **Autonomous** (`autos/`): Studica's own autonomous is not on its page, so this is a simple first one. It fires the preloaded pieces, then drives off the start line in the last 3 s. ## You changed your starter bot Start from your starter bot's code ([Start from a starter bot](https://crossbotics.com/ftc-helper/docs/pick-your-start/01-starter-bot/)). Then make your changes **one at a time**: change, build, check. **Why:** when something breaks, you know which change did it. **Keep the seller's names** for every part you did not change. **Why:** the template, the starter bot's robot file and the notes on this page all use them. ### A part added 1. **The configuration:** a name for its port (small letters, `_` between words: `intake_deploy`). 2. **`Robot.java`:** a field at the top of the class, and an `add(...)` line in `define()`, with `.part(...)` for its motor or servo ([the parts](https://crossbotics.com/ftc-helper/docs/reference/robot-java/), [the parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/), short recipes in the [cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/)). When the part is not built yet, add `.optional()`, and the code runs without it ([parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)). 3. **`Tunables.java`:** its section, named after the device in CamelCase (`intake_deploy` reads `Tunables.IntakeDeploy`). Write `MEASURE` for each position and limit, and `DEFAULT` for the rest ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)). **Why:** INIT then stops until a finder gives the real number, so a guess never pushes the part into the frame. 4. **Buttons:** `Controls.java` writes out each part's buttons. So a part you add has **no buttons** until you write its lines there (each part's "buttons to add" in the [reference](https://crossbotics.com/ftc-helper/docs/reference/robot-java/)). To move a button, or add a job, edit `Controls.java` ([Controls.java](https://crossbotics.com/ftc-helper/docs/five-files/03-controls-java/)). For several parts together, write an action in `Actions.java` ([Actions.java](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/)). 5. **When you changed the intake, or where the pieces ride:** count again how many pieces fit (POLLEN, NECTAR, a mix). Then change `.holds(...)` on the intake's line ([Tuning](https://crossbotics.com/ftc-helper/docs/tuning/)). ### A part taken off 1. Delete its `add(...)` line and its field in `Robot.java`, and its section in `Tunables.java`. 2. Build. Android Studio marks in red every line that still uses the part (in `Controls.java`, `Actions.java` and `autos/`). Delete or change each one. 3. Take its name out of the configuration. ### A motor, servo or wheel changed 1. Change its `.part(...)` (for a drive: `.motor(...)` and `.wheelMm(...)`). The `DEFAULT` numbers follow the new part. Numbers that you wrote in `Tunables.java` (a flywheel's `kF`, a speed) may now be wrong: measure them again with the finder. 2. When a drive motor changed, do the Hardware Check and the motor directions again. Later, run the Drive Tuner again. 3. In the configuration, change that port's motor type. ### A part moved, or a new shape The robot code does not change, unless a servo's positions changed. Then run the Servo Finder again. Only the simulator's robot file changes: the part's place and size ([Edit robot](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/#3-shape-the-parts-with-edit-robot) in the simulator page, or `looks(...)` in `Robot.java`: [shapes](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)). ### The simulator's robot file Start from your starter bot's measured file: copy `sim/robots/starter-bot-.properties` to `simulator/robot.properties` in your robot project. After each change, run `./gradlew :sim:fromRobot` from the `ftc-helper-lib` folder. It adds a line for each new part, marked `TODO measure` ([a robot file from Robot.java](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#2-the-simulator-makes-it-from-robotjava)). The lines of the copied file are yours, so it does not delete them. For a part you took off, delete its lines (and its `shape.` lines) by hand. When a line in the file and your code disagree, the tool stops and says why: fix that line by hand. Then measure the robot and write the real sizes on the `TODO` lines. ### Your names on the Driver Station Change the names in `@TeleOp(name = ...)` and `@Autonomous(name = ..., preselectTeleOp = ...)`, and `group = "Examples"`, to your own. `preselectTeleOp` must be the TeleOp's name exactly. ### A worked example: team 8938's robot 1 Team 8938 started from goBILDA's starter bot ([its pages](https://crossbotics.com/teams/8938-octobots/)). The table shows what they changed, and what each change needed: | Change | Configuration | Code | | --- | --- | --- | | an intake that folds up at the start, pushed over by a servo at ▶ | `intake_deploy` (Servo) added | a `Positioner` with `.optional()`; `Tunables.IntakeDeploy`: `stowed` and `deployed` are `MEASURE` (Servo Finder); an action that pushes it over at ▶, and X to push it again | | corner wheels driven from the intake through gears, not by servos | `left_intake_servo`, `right_intake_servo` taken out | the `.withCrServos(...)` part of the intake line deleted; the new wheels are only shapes for the simulator | | a flywheel on a sliding mount and a ramp that sends shots out of the back | none | only shapes and the shot angle (`.shotAngle(147)`) for the simulator | | new buttons (B: intake on/off) | none | `Controls.java` | They worked on the robot in the tuning order. First came the Hardware Check, the Servo Finder and the Flywheel Finder. Then, on a block at 0.4 power, came the motor directions and the first drive, and each mechanism. Last came the Drive Tuner and the autonomous. ## What the simulator could not express (input for its next stages) 1. **A gear between a flywheel motor and its wheel.** Studica has 2:1 bevel gears. The simulator takes the rim speed straight from the motor, so the stand-in is `share=` halved on the `shoot.` line. `gear=` on a flywheel shape does not change the shot. 2. **A catapult.** AndyMark's rubber-band catapult: a motor winds it, and it lets go at the top of each turn. A stand-in is possible: the motor as a `flywheel` with `feeder=` itself, and a fixed `speed=` (in/s) on the `shoot.` line. It needs someone to film a real shot first. The AndyMark file does not do this yet. 3. **An arm that reaches sideways and swings up/down** (REV's poker). `axis=up` only swings an arm flat. To swing it up and down while it reaches sideways, the simulator needs a second hinge. 4. **Shot direction and angle:** no seller publishes them, and a shot needs them. 5. **Motors not in the catalog:** Studica Maverick (every ratio) and the AndyMark NeveRest Hex gearmotors. Studica's Multi-Mode Smart Servo and AndyMark's programmable servos are not in it either. --- # Setting up a turret URL: https://crossbotics.com/ftc-helper/docs/guides/turret-setup/ Reference: [Turret in the robot module](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/). The lesson that builds a shooter with a turret: [Add a launcher](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/). Signs: angles are in degrees, **0 = straight forward, counterclockwise (to the left, seen from above) is +** ([conventions](https://crossbotics.com/ftc-helper/docs/conventions/)).
flowchart TD
    Q1["1. What turns it?<br/>motor / servo / CR servo + encoder"] --> Q2["2. How does it know its angle?<br/>start position / home switch / absolute encoder / servo"]
    Q2 --> Q3["3. How far can it turn?<br/>+/-90, +/-180, +/-190, round and round"]
    Q3 --> Q4["4. Where is the camera?<br/>on the turret / on the body / none"]
    Q4 --> Q5["5. A hood?<br/>none / servo / motor"]
    Q5 --> Q6["6. Can it hit another part?<br/>interlock rules"]
    Q6 --> Q7["7. Is it off the robot's center?<br/>shooting on the move"]
## 1. What turns it? | What turns it | `Robot.java` | Notes | | --- | --- | --- | | A motor (its own encoder counts the angle) | `Turret.motor("turret", "gobilda-5203-117").gearRatio(5)` | `gearRatio` = motor turns per turret turn (gears or belt). The motor id is from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). | | A standard servo (goes to an angle by itself) | `Turret.servo("turret")` | No encoder, no PID, no homing. A goBILDA 2000 servo turns 270 degrees on the hub's normal signal, and 300 with `.fullRange()`. For a smaller turret range, gear it. | | A continuous-rotation (CR) servo + an encoder on a motor port (for example REV Through Bore) | `Turret.crServo("turret").encoder("turret_enc", 8192)` | 8192 = the Through Bore's counts per turn. The port may also run another part's motor: the turret only reads its count, and never resets it. `gearRatio` = ENCODER turns per turret turn (1 = on the turret's axis). | | A CR servo + an absolute encoder on an analog port (for example an Axon's feedback wire) | `Turret.crServo("turret").analogEncoder("turret_pos")` | It knows its angle at once, at INIT. | Options for every kind: `.reversed()` flips it when positive power turns it clockwise. For a CR servo, `.encoderReversed()` flips the encoder when it counts down while the turret turns counterclockwise. **Tunables for a motor or CR servo turret** (the PID that turns it to an angle): ```java public static class Turret { public static double kP = 0.02, kI = 0, kD = 0.001; // the turning (tutorial 07 explains PID) public static double maxPower = 0.8, tolerance = 1.0; // tolerance: "aimed" within this many degrees public static double slowZone = 10, slowZonePower = 0.25; // slow down within 10 deg of a limit } ``` **Tunables for a servo turret** (two measured points and the travel time): ```java public static class Turret { public static double posA = 0.10, angleA = -90; // servo position 0.10 points the turret at -90 public static double posB = 0.90, angleB = 90; // servo position 0.90 points it at +90 public static double travelSec = 0.6; // seconds from posA to posB (time it) public static double tolerance = 1.0; } ``` ## 2. How does it know its angle? A motor's encoder counts from where it was at INIT, so the turret must learn where "0" is. Pick one way: | How | `Robot.java` | `Tunables.Turret` | Homing at ▶ (start)? | | --- | --- | --- | --- | | **Start position** (no switch): you put it there by hand before INIT | nothing extra | `startAngle = 0` (the default: straight forward) | no | | **Home switch**: a touch sensor or a magnetic switch | `.homeSwitch("turret_home")` | `homeAngle = 45` (needed), optional `homeDirection = 1`, `homingPower = 0.2`, `homingTimeout = 5` | yes, slowly | | **Absolute encoder** (CR servo turret) | `.analogEncoder("turret_pos")` | `encoderOffset = 117` (its reading, 0 to 360, with the turret at 0) | no | | **Servo** | `Turret.servo(...)` | `posA`, `angleA`, `posB`, `angleB`; optional `startAngle`. A servo cannot say where it is, so at ▶ the library sends it to `startAngle` (default: the middle of its range) | no | **Start position.** Make a mark (or a small printed jig) that holds the turret at `startAngle`. Put it there before every INIT. When it is somewhere else, every angle is off by the difference, and the turret aims 20 degrees wide with no warning. The INIT screen says `Turret : startAngle 0 deg: put the turret there by hand before INIT, or every angle is off`. **Home switch.** Either kind works, and the library finds which one you have: - a touch sensor (for example REV Touch Sensor) configured as **REV Touch Sensor**; - a magnetic switch (for example REV Magnetic Limit Switch, with a magnet on the turret) configured as a **Digital Device**. It reads LOW near the magnet, and the library knows this. Homing happens at **▶** (start on the Driver Hub), never in INIT. The library never moves anything before ▶, for safety. The game rules also want the robot to stand still once INIT ends (G304.H). At ▶, when the switch is not closed already, the turret turns slowly (`homingPower`) toward it, and the Driver Station says `homing: looking for the switch`. A turret that starts ON the switch homes at once, with no turning and no "looking" line. It turns from `startAngle` toward `homeAngle`, or the way `homeDirection` says (+1 = counterclockwise, -1 = clockwise). When the switch closes, the turret is at `homeAngle`. Following the goal and "aimed" wait until then. A broken switch must not wind up the wires. So when the turret does not find the switch within `homingTimeout` seconds, it stops. The Driver Station then says `homing failed: switch not found`. After homing, the library sets the angle right again **every time the turret passes the switch**. This fixes encoder drift (a slipping belt) during the match. When the configuration has no such switch, the INIT screen says `NO home switch`, and the turret uses the start angle. **How to find `homeAngle`:** without the `homeSwitch` line, put the turret at `startAngle` (straight forward). INIT, press ▶, and turn it with the stick until the switch clicks (or the magnetic switch's light comes on). Read the angle on the Driver Station (`Turret : 43 deg`). That is `homeAngle`. Then add the line. **Absolute encoder.** To find `encoderOffset`, put the turret straight forward, INIT, and read the encoder's degrees. You can also set `encoderOffset = 0` and read the turret's angle: that number is the offset. A geared encoder (`gearRatio` more than 1) repeats every `360 / gearRatio` turret degrees. So the turret must start within half of that of `startAngle`. ### From autonomous to TeleOp TeleOp's INIT starts the encoder again, but the turret is wherever autonomous left it. So the library remembers each turret's angle at the end of every program, until the robot app restarts and for at most 5 minutes. **TeleOp starts from that angle**, and does not home again. The INIT screen says `Turret : -37 deg, carried from the last program (12 s ago ...)`. Autonomous never uses it, because the drive team placed the robot by hand. This works for a TeleOp started again too (stopped and INIT again, no autonomous between). **When someone turned the turret by hand between programs:** restart the robot app, or set `public static boolean keepAngle = false;` in `Tunables.Turret`. **Nothing carried over** (the robot app restarted, more than 5 minutes passed, or a program's turret never finished homing): with no switch, the turret starts from `startAngle`. TeleOp's INIT says so: `no angle from a program before: turn it to startAngle 0 deg by hand and INIT again`. Do it. If you do not, the angle on the Driver Station is off by however far someone turned the turret. In a test, it said 4 degrees while the turret pointed at -12. A home switch avoids this, because it finds the real angle at ▶. ## 3. How far can it turn? **Any range works.** Write your own `min` and `max` in degrees. The only rule is that `max` is more than `min`. They do not have to match: `min = -30, max = 250` is fine, and so is a range of more than one turn. The rows below are only examples. | Example range | `Robot.java` | `Tunables.Turret` | What it does | | --- | --- | --- | --- | | A quarter turn each way | nothing extra | `min = -90, max = 90` | for a goal past a limit, it waits at the limit, and the Driver Station says `goal out of turret range` | | Half a turn each way | nothing extra | `min = -180, max = 180` | every direction once. It never turns through the back to get there | | A bit more than a turn | nothing extra | `min = -190, max = 190` | **the safe way round**: it has two ways to point at 175 (175 or -185). It picks the one closest to where it points that does not pass a limit | | Round and round (a slip ring carries the wires) | `.continuous()` | no `min`/`max` | no limits, always the shortest way, never "out of range". The Driver Station shows -180 to 180 | `min` and `max` are your wires' limits: never more than the turret can turn without pulling a cable. Put a hard stop there too, because software is not a hard stop. A servo turret's range is between `angleA` and `angleB` (or `min`/`max`, when they are narrower). ## 4. Where is the camera? | Camera | `Robot.java` | | --- | --- | | On the turret (turns with it) | `.follows(camera)` | | On the robot's body | `.follows(camera).cameraOnBody()` | | None: aim from where the robot is ([odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/)) | `.followsOdometry()` with `Tunables.Aim.goalX, goalY` | `follows` turns follow mode on at ▶ (operator BACK switches it). With odometry and the goal point, the odometry takes over while the camera does not see the goal ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). A camera beside the launcher needs `cameraOffset` (Tunables.Turret): the goal's bearing in the camera's picture when the launcher points straight at the goal. Find it with the Aim Tuner ([finders](https://crossbotics.com/ftc-helper/docs/tuning/)). ## 5. A hood? | Hood | `Robot.java` (in the launcher line) | Tunables | | --- | --- | --- | | None | nothing | - | | A servo | `.hood(Hood.servo("hood"))` | `Tunables.Hood`: `posA`, `posB` (hard stops), optional `angleA`, `angleB`, `travelSec` | | A motor | `.hood(Hood.motor("hood", "gobilda-5203-117"))` | `posA`, `posB` in ticks, ... | The shot table's third column is the hood angle ([Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/)). The Hood Finder finds its stops. The hood belongs to the launcher, so it works the same with or without a turret. ## 6. Can it hit another part? When a lift, an arm or a climber is in the turret's path, write an **interlock rule** in `Robot.java`, with the zones in `Tunables.java`. While the lift is up, the turret stays out of the back, and the other way round. See [Two parts that must not collide](https://crossbotics.com/ftc-helper/docs/guides/interlocks/). The rule pairs the turret with the part that reaches it. The [v2bot example](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/v2bot/Robot.java) uses `keepApart("TurretClaw", turret.zone(), wrist.zone())`, because its claw is in the turret's way only while the wrist is low, at any lift height. ```java keepApart("TurretLift", turret.zone(), lift.zoneAbove()); // Robot.java public static class TurretLift { // Tunables.java public static double turretFrom = 109, turretTo = 239; // degrees: the turret's zone public static double liftAbove = 270; // counts: the lift's zone } ``` ## 7. Is it off the robot's center? Shooting while driving leads the shot for the robot's speed. When the turret (or the camera) is not on the robot's center, give the offsets in `Tunables.Aim` ([Aim: shooting on the move](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). A turret that follows the odometry assumes that it turns about the robot's center. ## Summary **Required** means INIT stops without it. Every other number has a default. In PRACTICE, INIT's `Library starting values` line names a number written `DEFAULT`. The robot log has every value, and the tuning menu shows each one. The defaults are safe for a first test, but they do not fit your robot. Write `min` and `max` for your wires and hard stops (default -90 to 90). Write `encoderOffset` for an absolute encoder (default 0, so the turret would think it starts straight forward). | You have | `Robot.java` | `Tunables.Turret`: required | Write too (defaults) | Homing | | --- | --- | --- | --- | --- | | Motor, no switch | `Turret.motor(name, motorId).gearRatio(r)` | nothing | `min`, `max` (-90, 90), `startAngle` (0, or the middle when 0 is outside `min` to `max`) | none: start it at `startAngle` | | Motor + touch or magnetic switch | `... .homeSwitch("turret_home")` | `homeAngle` | `min`, `max` (-90, 90) | at ▶ | | Motor, slip ring | `... .continuous()` | nothing | `startAngle` (0) | none, or a switch | | Servo | `Turret.servo(name)` | `posA`, `angleA`, `posB`, `angleB` | `travelSec` (0.6), `startAngle` (the middle of its range) | none: sent to `startAngle` (or its middle) at ▶ | | CR servo + Through Bore | `Turret.crServo(name).encoder(port, 8192)` | nothing | `min`, `max` (-90, 90), `startAngle` (0) | none, or a switch | | CR servo + absolute encoder | `Turret.crServo(name).analogEncoder(port)` | nothing | `min`, `max` (-90, 90), `encoderOffset` (0) | none | ## Four complete examples **A. Team 8938's turret (motor, magnetic home switch, servo hood).** A 312 RPM goBILDA motor turns a goBILDA Gear-Driven Turret bearing (2.75 motor turns per turret turn). A REV Magnetic Limit Switch marks one angle. The hood is a servo. The [v2bot example](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/v2bot/Robot.java) has the whole robot. ```java // Robot.java turret = add(Turret.motor("turret", "gobilda-5203-312").gearRatio(2.75).homeSwitch("turret_home").follows(camera)); launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000").feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .hood(Hood.servo("hood").part("gobilda-2000-torque")).speedFromDistance(camera).requireReady("turret aimed", () -> turret.isAimed())); // Tunables.java public static class Turret { public static double min = -190, max = 190, homeAngle = 0; // switch closes facing forward: measure your own public static double kP = 0.02, kI = 0, kD = 0.001, maxPower = 0.8, tolerance = 1.5; } public static class Hood { public static double posA = 0.20, posB = 0.65, angleA = 0, angleB = 25, travelSec = 0.45; } ``` Where the turret's numbers come from (turret v8.1GB): its range is -190 to +190, a bit more than one turn. So it can point anywhere, and it picks the way round that stays inside the range. The design's checks turn it +/-190 without pulling the wires. The switch (REV-31-1462) sits at -45 degrees on the bearing housing, and its magnet at -45 degrees on the turret. So they line up when the turret points straight forward: `homeAngle = 0`. Measure your own ([How to find `homeAngle`](#2-how-does-it-know-its-angle)). **B. A servo turret, +/-90, no hood.** It is light and simple, with no encoder and no homing. ```java // Robot.java turret = add(Turret.servo("turret").follows(camera)); launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000").feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .speedFromDistance(camera).requireReady("turret aimed", () -> turret.isAimed())); // Tunables.java public static class Turret { public static double posA = 0.17, angleA = -90, posB = 0.83, angleB = 90, travelSec = 0.5; } ``` **C. A slip-ring turret with an absolute encoder.** A CR servo turns it round and round. An encoder on its axis says where it is at once. ```java // Robot.java turret = add(Turret.crServo("turret").analogEncoder("turret_pos").continuous().follows(camera)); // Tunables.java public static class Turret { public static double encoderOffset = 117; // the reading with the turret forward public static double kP = 0.015, kI = 0, kD = 0, maxPower = 1.0, tolerance = 2; } ``` **D. No turret: the whole robot turns.** The shooter is fixed. While the driver holds a button, the drive turns the robot toward the goal ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). ```java // Robot.java: no turret line launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000").feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .speedFromDistance(camera).requireReady("aimed", () -> aimMode().isOn() && aim().isAimed())); // Controls.java g1.rb.toggle(robot.aimMode()).says("aim at the goal"); ``` ## How to find each number | Number | How | | --- | --- | | `gearRatio` | count the teeth: turret gear / motor gear (a 20T pinion on a 100T ring = 5) | | `min`, `max` | turn the turret by hand to where the wires are tight, both ways. Take a few degrees less | | `startAngle` | where your mark or jig holds it (0 = straight forward is the easiest) | | `homeAngle` | turn it to the switch and read the angle ([above](#2-how-does-it-know-its-angle)) | | `posA`, `posB`, `angleA`, `angleB` (servo) | the [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/): two positions, and the angle at each (a phone angle app) | | `travelSec` (servo) | time a move from posA to posB | | `kP`, `kD`, `tolerance` | the tuning menu ([tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/)). Copy the values back into `Tunables.java` | | `cameraOffset` | the Aim Tuner ([finders](https://crossbotics.com/ftc-helper/docs/tuning/)) | | `encoderOffset` | the reading with the turret straight forward | ## What the INIT screen shows - `Turret : startAngle 0 deg: put the turret there by hand before INIT, or every angle is off` (autonomous) - `Turret : no angle from a program before: turn it to startAngle 0 deg by hand and INIT again, or every angle is off` (a TeleOp with nothing carried over: the robot app restarted, more than 5 minutes, or `keepAngle = false`) - `Turret : home switch at 0 deg: found when ▶ is pressed` and `Turret homing : when ▶ is pressed it turns clockwise slowly to find the switch` - `Turret : -37 deg, carried from the last program (12 s ago; keepAngle = false to turn this off)` - `Turret : absolute encoder: 31 deg (encoderOffset 117)` - After ▶, while homing: `Turret : homing: looking for the switch`; then `Turret : 12 deg following: camera`. - With interlock rules: `Interlock TurretLift: Turret between 109 and 239 deg / Lift above 270 counts`. ## Common mistakes - **The turret turns the wrong way** (+ power turns it clockwise): add `.reversed()`. When a CR servo's encoder counts the wrong way, add `.encoderReversed()`. Check with the stick: right = clockwise. - **Every angle is off by the same amount**: it was not at `startAngle` at INIT. Use a mark or a jig, or add a home switch. - **Homing turns the wrong way and stops with "switch not found"**: set `homeDirection` (+1 or -1). - **`homeAngle` outside `min`..`max`**: the switch must be inside the range that the turret may turn. - **The angle drifts during a match**: a belt slips. A home switch fixes it at every pass. - **A slip-ring turret with `min`/`max`**: `continuous()` ignores them. Remove them, so they confuse nobody. - **The turret is aimed, but the shots go wide by the same angle**: a camera beside the launcher needs `cameraOffset`. - **TeleOp starts with the wrong angle after someone turned the turret by hand**: restart the robot app, or set `keepAngle = false`. ## In the simulator `./gradlew :sim:fromRobot` writes every kind into the simulator robot file: - a motor turret, with its home switch as `touch.turret_home = turret, at=..., width=...`; - a slip-ring turret (`motor ... = free`); - a servo turret (a `turret` shape on the servo); - a CR servo turret. Its encoder is a `motor.... drivenBy=turret` line that the CR servo turns. An absolute encoder is `analog.turret_pos = ...`. See the [simulator guide](https://crossbotics.com/ftc-helper/docs/simulator/). --- # Use only what you need URL: https://crossbotics.com/ftc-helper/docs/guides/use-only-what-you-need/ **For:** teams with their own code who do not want a framework. **You need:** your own `LinearOpMode` and the library [added to the project](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/). You do not have to use `EasyTeleOp`, `ControlMap` or the robot in five files. Every building block below works on its own, next to plain SDK code, in your own loop. Each one has the import, a short example, what it depends on, and how to get around it. **Mixing with the five files:** two pieces of code that send power to one motor fight each other. The library has no per-part switch yet to take one part out of `robot.update()`. `robot.update()` updates every part added in `Robot.java` (`add(...)`) every loop. Each part sends its own power to its motor. A Lift or Arm sends it again at least every 25 loops, so your power does not last. So when you want to drive a motor yourself, **do not** add it as a part in `Robot.java`. Use its building block (`PositionMotor` or `SafeMotor`, below) in your own OpMode instead. We checked "Depends on" in the source. **None of these blocks reads or writes a file, and none keeps static state, unless the table says so.** | Block | Depends on | Files or statics | | --- | --- | --- | | [`ControllerBindings`](#controllerbindings) | the SDK `Gamepad` | none | | [`SafeMotor`](#safemotor) | `PidController`, `SoftLimits`, `MathUtil` | one static: the 3 ms reading reuse, changed only by the test hook `SafeMotor.freshReadingsForTests(boolean)` (tests only) | | [`PositionMotor`](#positionmotor) | `SafeMotor`, `PidController`, `MotorSetup`, `Hw` | none, **unless** you call `.tunable(...)` (see there) | | [`PidController`](#pidcontroller) | `MathUtil`, `Angles` | none | | [`MotorSetup`, `Hw`](#motorsetup-and-hw) | the SDK `HardwareMap` | none | | [`BulkReads`](#bulkreads) | the SDK `LynxModule` | none (it sets the hubs' mode) | | [`LoopTimer`](#looptimer) | nothing | none | | [`MatchTimer`](#matchtimer) | the SDK `Gamepad` (for buzzes) | none | | [The finders and the Hardware Check](#the-finders-and-the-hardware-check) | their own OpModes | the finders write a results file when they end | ## ControllerBindings ```java import com.crossbotics.ftchelper.gamepad.ControllerBindings; import com.crossbotics.ftchelper.gamepad.ControllerBindings.Btn; import com.crossbotics.ftchelper.gamepad.ControllerBindings.Pad; ControllerBindings buttons = new ControllerBindings() .bindPress(Pad.G2, Btn.A, () -> claw.setPosition(0.2)) // once per press .bindHold(Pad.G2, Btn.DPAD_UP, () -> winch.setPower(0.5)) // every loop while held .bindRelease(Pad.G2, Btn.DPAD_UP, () -> winch.setPower(0)); waitForStart(); buttons.ignoreHeldButtons(gamepad1, gamepad2); // a button held through ▶ (start) does not fire while (opModeIsActive()) { buttons.update(gamepad1, gamepad2); // ... your own code } ``` `ControllerBindings` times each job. A job over 20 ms sets `getSlowActionWarning()`, and you can show it. For example: `G2:A button job took 40 ms: the whole robot stopped that long. ...`. Escape hatch: `isDown(pad, btn)` reads a button yourself. You can always read `gamepad1` directly next to it. Full list: [gamepad](https://crossbotics.com/ftc-helper/docs/modules/gamepad/#controllerbindings). ## SafeMotor ```java import com.crossbotics.ftchelper.safety.SafeMotor; SafeMotor lift = new SafeMotor(liftMotor) // your own DcMotorEx, set up your way .setLimits(0, 2900) // encoder ticks .setLowerSwitch(bottom::isPressed) .setSlowZone(200, 0.25); while (opModeIsActive()) { lift.update(); // first: reads the encoder and switches lift.setPower(-gamepad2.left_stick_y); // limits applied } lift.stop(); ``` `update()` reads the encoder and the switches fresh each loop. Later reads within 3 ms reuse them, so a reading is at most 3 ms old. It sends a power only when the power changes, and also every 25 loops (every loop while it is past a soft limit). Escape hatch: `getMotor()` gives the `DcMotorEx`. Power written straight to it skips the limits. While `update()` runs every loop, that power lasts at most 25 loops, and then `SafeMotor` sends its own limited power again. For a different power on purpose, stop calling `update()` for that motor. Details: [safety](https://crossbotics.com/ftc-helper/docs/modules/safety/#safemotor). ## PositionMotor ```java import com.crossbotics.ftchelper.mechanism.PositionMotor; PositionMotor lift = new PositionMotor("lift", liftMotor) // your own DcMotorEx (brake, encoder reset) .limits(0, 2600) .pid(0.004, 0, 0.0002, 0.05) .position("LOW", 900) .position("HIGH", 2400); buttons.bindPress(Pad.G2, Btn.Y, () -> lift.goTo("HIGH")); // once per press, not every loop // in the loop: lift.manual(-gamepad2.left_stick_y); // non-zero takes over; 0 holds where let go lift.update(); ``` Call `goTo` once per press, because each call starts the target fresh (it resets the PID). `PositionMotor.create(hardwareMap, name)` gets the motor for you (brake, encoder reset, plain power). The constructor above takes the motor that you set up yourself. Depends on: without `.tunable(...)`, nothing outside the table. **With `.tunable(prefix)`**, the gains and positions become `Tunable`s. They live in a static registry that the whole app shares. The library reads them from `/sdcard/FIRST/ftc-helper/settings.properties` the first time (see [what runs every loop](https://crossbotics.com/ftc-helper/docs/guides/every-loop/#static-state-that-lives-across-opmode-runs)). Leave it out to keep it plain. Escape hatches: `getSafeMotor()` (the limits layer) and `getPid()` (the `PidController`; change gains with `setGains`). Details: [mechanism](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#positionmotor). ## PidController ```java import com.crossbotics.ftchelper.control.PidController; PidController pid = new PidController(0.004, 0, 0.0002); // kP, kI, kD (kF is a 4th argument) pid.setTolerance(20); // in the loop: double power = pid.calculate(target, motor.getCurrentPosition()); motor.setPower(power); if (pid.atTarget()) { /* there */ } ``` It is pure math, with no hardware. Call `reset()` when the target jumps, and `setAngleMode(true)` for headings. Details: [control](https://crossbotics.com/ftc-helper/docs/modules/control/#pidcontroller). ## MotorSetup and Hw ```java import com.crossbotics.ftchelper.hardware.Hw; import com.crossbotics.ftchelper.hardware.MotorSetup; DcMotorEx arm = MotorSetup.get(hardwareMap, "arm") .reversed().brake().resetEncoder().runWithoutEncoder().done(); TouchSensor bottom = Hw.get(hardwareMap, TouchSensor.class, "arm_bottom"); // wrong name: lists the real ones DistanceSensor extra = Hw.tryGet(hardwareMap, DistanceSensor.class, "test"); // null if missing ``` `MotorSetup.of(motor)` sets up a motor you already have. `done()` gives the plain `DcMotorEx`. Details: [hardware](https://crossbotics.com/ftc-helper/docs/modules/hardware/#motorsetup). ## BulkReads ```java import com.crossbotics.ftchelper.hardware.BulkReads; List hubs = BulkReads.manual(hardwareMap); // or BulkReads.auto(hardwareMap) waitForStart(); while (opModeIsActive()) { BulkReads.clear(hubs); // first line, every loop // ... reads } ``` It only sets the SDK's bulk-caching mode on every hub. A bulk read gets many values from a hub in one message. Details: [hardware](https://crossbotics.com/ftc-helper/docs/modules/hardware/#bulkreads). ## LoopTimer ```java import com.crossbotics.ftchelper.util.LoopTimer; LoopTimer loop = new LoopTimer(); while (opModeIsActive()) { loop.update(); telemetry.addData("Loop", "%.1f ms (%.0f Hz)", loop.getAverageMs(), loop.getHz()); // ... telemetry.update(); } ``` Please [send us](https://github.com/crossbotics/ftc-helper-lib/issues/new/choose) your numbers. Nobody has measured the library's loop time on a Control Hub yet. ## MatchTimer ```java import com.crossbotics.ftchelper.match.MatchTimer; MatchTimer timer = MatchTimer.teleOp() // 2:00 .rumbleAt(20, gamepad1, gamepad2) // both gamepads buzz at 0:20 .cueAt(30, () -> endgame = true); // your own job at 0:30 waitForStart(); timer.start(); while (opModeIsActive()) { timer.update(); // runs the buzzes and cues telemetry.addData("Time", timer.format()); } ``` Details: [match](https://crossbotics.com/ftc-helper/docs/modules/match/#matchtimer). ## The finders and the Hardware Check Each is a ready-made OpMode. You add a one-line file, and it needs nothing else from your code. ```java import com.crossbotics.ftchelper.finders.MotorFinderOpMode; @TeleOp(name = "Motor Finder", group = "Finders") public class MotorFinder extends MotorFinderOpMode { } ``` The same for `ServoFinderOpMode`, `FlywheelFinderOpMode` and the [Hardware Check](https://crossbotics.com/ftc-helper/docs/modules/testing/#hardwarecheckopmode) (`HardwareCheckOpMode`). They show the numbers as plain code too (`PositionMotor.create(...).limits(...)`), as well as `Tunables.` lines. When a finder ends, it writes its lines to `/sdcard/FIRST/ftc-helper/finder-results.txt`. The Drive Tuner and Shot Tuner need more: see [finders](https://crossbotics.com/ftc-helper/docs/modules/finders/). ## Mixing with the bigger pieces You can also start big and step down: - **EasyTeleOp, your own driving:** override `drive(Gamepad gamepad)`. EasyTeleOp calls it every loop while the tuning menu is closed. For example: `driving().tank(-gamepad.left_stick_y, -gamepad.right_stick_y, 1);`. - **The robot in five files, your own code for one part:** a module's `part()` gives the plain part inside. `lift.part()` is its `PositionMotor`, and `part().getSafeMotor()` and `part().getPid()` go one layer deeper. - **Your own code every loop with the five files:** use `robot.addOwn(part)` or `robot.everyLoop(() -> ...)`. `addOwn` takes a class that `implements Subsystem`. The robot updates it every loop after the library's parts, and calls its `stop()` at STOP and at pause. `everyLoop` takes a small piece of code, with no `stop()`. Call them in `define()` or in `Controls.java`'s `buttons(...)` ([Your own code every loop](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#your-own-code-every-loop)). A ControlMap's own `everyLoop()` belongs to the library (it runs the buttons), so you cannot override it there. - **`EasyTeleOp.everyLoop()`:** with a plain [EasyTeleOp](https://crossbotics.com/ftc-helper/docs/modules/teleop/) (not the five files), it runs your own code every loop, before the parts update. - **A second motor on a lift or arm:** you need no code of your own: `Lift.slide("lift_left").alsoMotorReversed("lift_right")` ([two motors](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm)). ## When not to use it - **Path following** (splines, following a curved path): the core library has none. Add the optional [pedro module](https://crossbotics.com/ftc-helper/docs/modules/pedro/). It plugs [Pedro Pathing](https://pedropathing.com/) into your `odometry(...)` and `drive(...)` lines, and adds a `follow(...)` step. For [Road Runner](https://rr.brott.dev/), use it directly with the library's odometry ([`PoseTracker`](https://crossbotics.com/ftc-helper/docs/modules/odometry/)). We plan a Road Runner module. - **You already have a working command framework** (your own, FTCLib, NextFTC): use the small blocks above (`SafeMotor`, `PidController`, `BulkReads`) inside it, not `EasyTeleOp`. - **You need a value the library does not show:** read the SDK device yourself. Every block hands over its raw device. ## How to pin a version Use one tagged version for a whole event, and update between events. The steps are in [Keep it up to date: use a specific version](https://crossbotics.com/ftc-helper/docs/02-keep-up-to-date/#use-a-specific-version). --- # Your own code at INIT, ▶, every loop and STOP URL: https://crossbotics.com/ftc-helper/docs/guides/your-own-code/ **For:** students who want to write their own code in the steps of an FTC OpMode, and students who want to write a whole OpMode themselves. **You need:** the five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)) and a first look at [non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/). ## The five steps of every FTC OpMode Every FTC program (an **OpMode**) goes through the same five steps. The library runs them for you, and you can add your own code to each one: | FTC step | When | What the library does | Your code | | --- | --- | --- | --- | | `init` | once, when the driver presses INIT | makes every part, checks the robot configuration and `Tunables.java` | `atInit(...)` | | `init_loop` | again and again, until ▶ (start on the Driver Hub) | the alliance choice, the INIT checks, the Driver Hub screen | `duringInit(...)` | | `start` | once, when the driver presses ▶ | each part's start (an intake "on at the start") | `atStart(...)` | | `loop` | again and again, until STOP | the buttons, driving, every part and action moves a little | `everyLoop(...)` | | `stop` | once, at STOP, at the end of an autonomous, or after an error | stops the wheels and every part | `atStop(...)` | Two rules for all of them: - **Nothing moves before ▶.** The game rules say the robot stays still until the match starts. A robot that moves in INIT can also hurt someone who is setting it up. So code in `atInit` and `duringInit` may read sensors and show things, but it must not give a motor power or move a servo. - **Never wait.** While your code waits, the whole robot freezes, STOP included ([Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/)). So each piece of code must be quick: no `sleep()`, no `while` that waits for something. To do things one after another, use an [action](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/). ## Road 1: your code in the five files This is the usual road. You keep everything the library does (the buttons, the menus, the safety stops), and you add your own code where you need it. **For every OpMode** (TeleOp and every autonomous): put it in `Robot.java`'s `define()`. ```java title="Robot.java" public int piecesScored = 0; // a number of your own (your actions add to it) @Override protected void define() { drive(Drive.mecanum("front_left", "front_right", "back_left", "back_right").motor("gobilda-5203-312").wheelMm(96)); lift = add(Lift.slide("lift").part("gobilda-5203-435").bottomSwitch("lift_bottom")); claw = add(Claw.servo("claw")); atInit(() -> piecesScored = 0); // INIT, once duringInit(() -> show("Lift (counts)", lift.position())); // INIT loop: check it before the match everyLoop(() -> show("Pieces scored", piecesScored)); // every loop after ▶ atStop(() -> RobotLog.ii("team", "scored " + piecesScored)); // the end, after the motors stop } ``` **For one TeleOp only:** put it in `Controls.java`'s `buttons(...)`. It runs once, in INIT. ```java title="Controls.java" @Override protected void buttons(Robot robot, Pad g1, Pad g2) { g2.rb.press(Actions.scoreHigh(robot)).says("score high"); robot.everyLoop(() -> robot.show("Lift (counts)", robot.lift.position())); } ``` **For one autonomous only:** put it in its `atInit(robot)`. Do not put it in `steps(...)`: the library reads the steps several times in INIT, so it would add the code several times. ```java title="autos/ScoreAndPark.java" @Override protected void atInit(Robot robot) { robot.duringInit(() -> robot.show("Claw", "closed on the preload?")); robot.atStop(() -> RobotLog.ii("team", "auto ended")); } ``` - `atStart(...)` takes an [action](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/), for example `atStart(() -> Actions.deployIntake(this))`. - `show("label", value)` puts one line on the Driver Hub, under the library's warnings. The screen starts empty each loop, so call it in every loop. - Put code that moves a motor every loop in a part of your own: `addOwn(...)` ([the robot module](https://crossbotics.com/ftc-helper/docs/reference/robot-java/)). Then STOP and the pause button stop its motor too. - When one `atStop` fails, the others still run, and the Driver Station shows the first error. - `atStop` runs at every end, also when the driver presses STOP in INIT. `wasStarted()` tells them apart: `atStop(() -> { if (wasStarted()) savedCount = piecesScored; })`. - In `Controls.java`, write `robot.show(...)`. There, plain `show(...)` is the TeleOp's own `show`. It takes a value to read again every loop (`show("Lift", robot.lift::position)`). ## Road 2: your own OpMode, with the library's robot Some students want to write the whole OpMode themselves, the way FTC teaches it: their own `INIT`, their own loop, their own buttons. You can do that and still use your `Robot.java`, `Tunables.java` and `Actions.java`. Five lines connect them: | In your OpMode | What it does | | --- | --- | | `robot.init(this)` | INIT: makes every part, turns on bulk reads (faster loops), runs the INIT checks. Moves nothing. | | `robot.initLoop()` | one pass of the INIT loop: the parts' INIT work, your `duringInit`, then it sends the screen | | `robot.start()` | ▶: each part's start and your `atStart` actions (nothing when the driver pressed STOP in INIT) | | `robot.update()` | one loop: every part and action moves a little, your `everyLoop`, then it sends the screen | | `robot.stop()` | STOP: stops the wheels and every part, then your `atStop`. Put it in a `finally`. | Two more lines help you drive. `robot.driveWith(gamepad1)` drives with the sticks (the left trigger drives slowly). `robot.driveWith(forward, strafeRight, turnRight)` drives with numbers from -1 to 1. ```java title="OwnTeleOp.java" @TeleOp(name = "Own TeleOp") public class OwnTeleOp extends LinearOpMode { @Override public void runOpMode() { Robot robot = new Robot(); robot.init(this); // INIT: makes the parts, checks the numbers; moves nothing int scored = 0; boolean aBefore = false; while (opModeInInit()) { robot.show("Press ▶", "A scores high"); robot.initLoop(); // sends the screen } try { robot.start(); // (does nothing if STOP was pressed in INIT) while (opModeIsActive()) { robot.driveWith(gamepad1); // A: only when it goes down, not every loop while it is held if (gamepad1.a && !aBefore) { robot.run(Actions.scoreHigh(robot)); // runs a little each loop: never waits scored++; } aBefore = gamepad1.a; if (gamepad1.right_trigger > 0.5) robot.intake.in(); else robot.intake.stop(); robot.show("Scored", scored); robot.update(); // every part moves a little, then the screen is sent } } finally { robot.stop(); // always: stops the wheels and every part } } } ``` The whole file is in the example robot `lessonbot`: [OwnTeleOp.java](https://github.com/crossbotics/ftc-helper-lib/blob/main/examples/src/main/java/com/crossbotics/ftchelper/examples/lessonbot/OwnTeleOp.java). Try it in the simulator: **Lesson Bot: own OpMode**. - **Call `robot.update()` once in every loop.** Without it, no part moves and no action runs. - **Do not call `telemetry.update()` yourself.** `robot.update()` and `robot.initLoop()` send the screen, with your own `telemetry.addData(...)` lines and your `robot.show(...)` lines. - **Keep `robot.stop()` in a `finally`.** Then it runs even after an error, so no motor keeps its power. **What you keep:** every part's safety (lift and arm limits, soft stops, jam back-out), the actions, the interlock rules, the INIT checks of `Tunables.java`, bulk reads, and the simulator. **The same as the library's OpModes:** in a TeleOp, the alliance and (with odometry) the pose come from the autonomous that ran before it. An OpMode marked `@Autonomous` starts every part from its start position. INIT shows the PRACTICE and "tuned values differ" warnings. **What you do yourself now:** the buttons, the alliance choice, the pause button, field-centric driving, the tuning menu, the button list on the Driver Hub, and the match timer's buzzes. The library's taps, double-taps and holds are in [Use only what you need](https://crossbotics.com/ftc-helper/docs/guides/use-only-what-you-need/#controllerbindings). In an autonomous, you also do the steps one after another, the alliance choice, the RED/BLUE mirroring, the start spot, and handing the alliance and the end pose to the TeleOp. The library's `Auto` does all of these for you. ## Which road? | You want | Road | | --- | --- | | Show a sensor in INIT, count something, save a number at the end | Road 1 | | Your own button logic, but the library's buttons, menus and safety for the rest | Road 1 (`buttons(...)`, actions) | | To learn how an FTC OpMode works from the inside | Road 2 | | A TeleOp written the way your old code was, with the library's parts | Road 2 | You can mix them, for example one team TeleOp on road 1 and a practice OpMode on road 2, both with the same `Robot.java`. ## See also - [What runs every loop](https://crossbotics.com/ftc-helper/docs/guides/every-loop/): the library's own steps, in order. - [Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/): why nothing may wait. - [Use only what you need](https://crossbotics.com/ftc-helper/docs/guides/use-only-what-you-need/): single pieces of the library in your own code, without `Robot.java`. --- # Auto module URL: https://crossbotics.com/ftc-helper/docs/modules/auto/ Learn it hands-on: [16 Easy autonomous](https://crossbotics.com/ftc-helper/docs/tutorials/16-easy-autos/). Full guide: [Easy autonomous modes](https://crossbotics.com/ftc-helper/docs/guides/easy-autos/). With this module you write an autonomous (the 30 seconds when the robot drives itself) as a list of named steps. The library runs the steps in order, keeps your mechanisms working, flips the route for the RED alliance, and keeps time to park. The [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto) has an `Auto` class built on this one. With five files, start there. Use this page when you write an autonomous without five files. | Class | Use it to | | --- | --- | | [`EasyAuto`](#easyauto) | write a whole autonomous OpMode: fill in a few methods, list the steps | | [`AutoRoutine`](#autoroutine) | hold the list of steps and run them | | [`AutoStep`](#autostep) | write one step of your own (mechanisms give you ready-made ones) | | [`AutoContext`](#autocontext) | wait inside a step while mechanisms keep working |
sequenceDiagram
    participant DS as Driver Station
    participant E as EasyAuto
    participant R as AutoRoutine
    participant M as Mechanisms
    DS->>E: INIT
    E->>E: set up drive, IMU, mechanisms
    E->>DS: menu: alliance, delay, choices, profile, "place robot"
    DS->>E: ▶ (start)
    E->>R: build steps (mirrored for RED), run
    loop every step
        R->>M: update() every loop, during moves and waits
        R->>DS: "Step 3/8: Drive to basket", time left
    end
    R-->>E: report (DONE / STALLED / timed out / skipped)
    E->>M: stop everything (even after an error)
    E->>E: remember alliance and heading for TeleOp
--- ## EasyAuto Extend it and fill in these methods: | Method | Required? | What you return / do | | --- | --- | --- | | `robotConfig()` | yes* | `new RobotSettings()`: the [`RobotConfig`](https://crossbotics.com/ftc-helper/docs/modules/core/#robotconfig) shared with TeleOp | | `buildRoutine(r)` | yes | add the steps. It runs AFTER INIT, so the choices are known | | `createSubsystems()` | no | your mechanisms. The routine keeps them working during every step. Make new objects here: it runs again when the drivers change the profile in INIT. | | `addChoices(menu)` | no | extra INIT choices: `menu.choice("Route", "Near", "Far")` | | `addInitTelemetry(t)` | no | extra screen lines during INIT | | `startPosition()` | no | where to place the robot. INIT shows it | | `startHeadingDeg()` | no | which way the robot faces at the start, in degrees from "facing away from your driver" (default 0). Write it for BLUE. EasyAuto mirrors it for RED, unless `mirrorForRed()` gives false. TeleOp's field-centric "forward" uses it. | | `parkReserveSec()` | no | the seconds the routine keeps for the steps after `thenPark()` | | `maxStartDelaySec()` | no | the longest start delay in the menu (default 10) | | `mirrorForRed()` | no | true (default): EasyAuto mirrors routes written for BLUE for RED. Return false on a ROTATED field | | `alliancesOnOneWall()` | no | false (default): each alliance's drivers stand at their own wall (BIOBUZZ, DECODE). Return true when both alliances' drivers stand at one wall. The simulator's start spot uses it | \* Without a `RobotConfig`, override `driveConfig()`, `autoDriveConfig()` and `createImu()` instead. Inside your steps you can use `alliance()`, `choice(label)` and `autoDrive()`. To have the Driver Station pick your TeleOp after autonomous, add `preselectTeleOp = "Main TeleOp"` to the `@Autonomous` line. ## AutoRoutine | Step | What it does | | --- | --- | | `forward`, `back`, `left`, `right` `(label, inches, power)` | drive that way (no angle). `left`/`right` work on mecanum only | | `move(label, inches, direction, power)` | drive at an angle (counterclockwise: 0 forward, 90 left, 180 back, -90 right) | | `turnLeft`, `turnRight` `(label, degrees, power)` | turn that way (no sign) | | `turn(label, degrees, power)` | turn by this many degrees (positive = left) | | `turnTo(label, heading, power)` | turn to a heading (0 = start direction) | | `turnToward(label, bearingDeg, toleranceDeg, maxPower, timeoutSec)` | turn toward something the robot measures (`bearingDeg` gives the degrees to turn, + left, NaN = not seen). It makes up to 4 turns, with a fresh reading after each, all inside `timeoutSec`. The routine does not mirror it. `Steps.aimAtGoal` uses it | | `moveWithTurn(label, inches, fieldDir, heading, power, turnPower)` | drive and turn together (mecanum) | | `driveTo(label, pose, ready, x, y, heading, power, tolerance)` | drive to a field point with odometry (mecanum). The five-files `Steps.driveTo` fills in the pose for you ([odometry](https://crossbotics.com/ftc-helper/docs/modules/odometry/#driveto)) | | `followPath(label, pathJob, timeoutSec[, events])` | follow a path that another library drives, for example Pedro. `PathJob` is the small plug (an interface) that connects it: start, busy, ready, distance left, cancel; optional: `totalIn()`, `partNow()`. `events` is a list of `PathEvent`s. Each one fires once, when the robot gets to its place. The report lists the ones that did not fire (`STALLED, not fired: Spin up`). The five-files `Steps.follow` makes both for you ([pedro](https://crossbotics.com/ftc-helper/docs/modules/pedro/#do-things-along-the-path)) | | `driveTo(label, pose, ready, x, y, heading, power, tolerance, events)` | `driveTo` with `PathEvent`s on the way. The "path" is the straight line from where the step starts | | `driveRoute(label, pose, ready, poseKnown, map, x, y, heading, power, tolerance)` | drive to a field point around the boxes of a [`FieldMap`](https://crossbotics.com/ftc-helper/docs/modules/drive/#fieldmap). The five-files `Steps.routeTo` fills in the rest. The route starts from where the robot is when the step starts | | `rememberHeading(label)` / `returnToHeading(label, power)` | come back to a saved heading | | `turnTowardWithSweep(label, bearingDeg, toleranceDeg, maxPower, timeoutSec, sweepDeg, stepDeg, sweepPower)` | `turnToward` with a sweep. When the robot sees nothing at the start, it turns in `stepDeg` steps up to `sweepDeg` left, then right, and looks after each step. When it never sees the target, it turns back to the start (that turn gets up to `timeoutSec` again), and the report says "not seen (swept)". `Steps.aimAtGoal(label, sec, sweepDeg)` uses it | | `run(label, code)` | run code at once, then go on (for example `claw::open`) | | `waitFor(label, seconds)` | wait; mechanisms keep working | | `waitUntil(label, condition, timeout)` | wait for something, with a time limit | | `step(label, autoStep)` | run a mechanism's step (`lift.goToStep("HIGH")`) or your own | | `thenPark()` | the steps after this one always get their time | | Setup / running | What it does | | --- | --- | | `new AutoRoutine(this)` | for your OpMode (or `new AutoRoutine(isActive, idle, telemetry)` in tests) | | `.drive(autoDrive)`, `.subsystems(group)`, `.telemetry(t)`, `.timer(timer)` | what the routine uses | | `.mirrorFor(alliance)` | flip turns, headings and sideways moves for RED (null = no mirroring, for example on a rotated field) | | `.reserveForPark(seconds)` | the main steps stop when this much time is left | | `.beforeDriving(code)` | code to run when a driving step starts. Each call adds one. The robot layer uses it to end a path's hold | | `runAll()` | run every step (after `waitForStart()`) | | `getReport()` | what happened to each step | | `size()` | the number of steps | On `AutoRoutine`, `waitFor("label", s)` only ADDS a wait step to the list. A wait that happens right now (`ctx.waitFor(s)`) exists only inside a step, on the `ctx` the step gets. So you cannot mix the two up. When a step throws an error, the routine stops the drive before the error goes on. The report gives the result of every move: `"Drive to basket: STALLED"`, `"Lift up: timed out"`, `"Wait for lift: cut short (time for park)"`, `"Score: skipped (time for park)"`. Read it after every practice run. ## AutoStep `AutoStep` is an **interface** (a promise that a class has certain methods) with one method, `run(AutoContext ctx)`. Write your own as a lambda: ```java // "ctx -> { ... }" is a lambda: code handed to the routine, run when this step's turn comes. AutoStep shake = ctx -> { // 3 times, but quit at once if STOP is pressed or time is up (ctx.isActive() is false) for (int i = 0; i < 3 && ctx.isActive(); i++) { claw.goTo("OPEN"); ctx.waitFor(0.15); // wait 0.15 s; mechanisms keep working (never use sleep()) claw.goTo("CLOSED"); ctx.waitFor(0.15); } }; routine.step("Shake loose", shake); ``` Three rules for your own step: - Return when the step is done. - In any loop that waits, call `ctx.loop()` (or use `ctx.waitFor` / `ctx.waitUntil`). - Stop as soon as `ctx.isActive()` is false. ## AutoContext | Method | What it does | | --- | --- | | `isActive()` | whether the step may go on: false when the OpMode stops or the main time is up | | `loop()` | one loop: update mechanisms, telemetry, idle | | `waitUntil(condition, timeout)` | waits, and gives true when the condition came true | | `waitFor(seconds)` | waits while the mechanisms keep working | | `secondsLeft()` | seconds left in autonomous | | `telemetry()` | the telemetry, to add your own lines | | `note(text)` | puts a note on this step's report line instead of "done" (for example "timed out") | --- # Control module URL: https://crossbotics.com/ftc-helper/docs/modules/control/ Learn it hands-on: [07 PID lift](https://crossbotics.com/ftc-helper/docs/tutorials/07-pid-lift/), [11 Driver assists](https://crossbotics.com/ftc-helper/docs/tutorials/11-driver-assists/). These classes do the math that turns "where I want to be" into a motor power. Use them when you build a mechanism by hand: a lift that holds a height, a turn to a heading, a smooth start. The ready-made mechanisms ([`PositionMotor`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#positionmotor), the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/robot-java/)) already use them, so you only set their numbers. To learn what PID means, start with tutorial 07. | Class | Use it to | | --- | --- | | [`PidController`](#pidcontroller) | move a mechanism to a target and hold it there | | [`SlewRateLimiter`](#slewratelimiter) | stop a value from changing too fast (a ramp) | | [`Feedforward`](#feedforward) | work out the power a motor needs for a speed, from measured numbers | --- ## PidController ### What a PID controller does You have a **target** (lift at 1500 ticks) and a **measurement** (lift is at 900 now). Ticks are counts from the motor's **encoder**, a sensor that counts how far the motor has turned. The difference is the **error** (600). Each loop, the controller turns the error into a power. The power is the sum of up to four parts. Each part has a number you tune, called a **gain** (kP, kI, kD, kF): - **P (proportional):** power = kP x error. Far away = push hard. Close = push gently. - **I (integral):** adds up the error over time. It fixes a small error that P alone never closes (for example gravity pulling a lift down). Start with 0. - **D (derivative):** looks at how fast the error shrinks and pushes back. This keeps the mechanism from going past the target (overshooting). - **F (feedforward):** a fixed extra push every loop, for example 0.1 to hold an arm up against gravity. ### Example: a lift ```java PidController liftPid = new PidController(0.005, 0, 0.0002) // kP, kI, kD .setOutputLimits(-0.5, 1.0) // go down at half power at most .setTolerance(15); // within 15 ticks counts as "there" // every loop: (where we want to be, where the encoder says we are) -> a power double power = liftPid.calculate(liftTarget, lift.getCurrentPosition()); lift.setPower(power); // send it every loop: that is what holds the lift up ``` The controller remembers past errors. So make it once, in INIT, and not in the loop. With a [`SafeMotor`](https://crossbotics.com/ftc-helper/docs/modules/safety/), use `safeLift.moveTo(target, liftPid)` instead. It does the same, and it also keeps the limits. ### Methods | Method | What it does | | --- | --- | | `new PidController(kP, kI, kD)` | make one, no feedforward | | `new PidController(kP, kI, kD, kF)` | make one, with a fixed feedforward push | | `calculate(target, measured)` | **call every loop.** It gives the power, inside the output limits. | | `setGains(kP, kI, kD, kF)` | change the gains (for live tuning) | | `setOutputLimits(min, max)` | limit the output. Default -1 to 1. | | `setIntegralLimit(max)` | the most power the I part may add. This stops "windup" (see below) | | `setTolerance(value)` | how close counts as "at target" | | `setAngleMode(true)` | for headings in degrees: the error takes the short way around (170 to -170 = +20) | | `atTarget()` | whether the last error was within the tolerance | | `getLastError()` | the last error (target minus measured) | | `reset()` | clears the memory. **Call it when you set a new target.** | | `getKP()`, `getKI()`, `getKD()`, `getKF()` | read the gains | Each `set...` method gives back the controller. So you can chain them: write one after the other, as in the example. ### How to tune (do it in this order) 1. Set kI = 0 and kD = 0. Start with a small kP: `1 / (a big error)`. For a lift with 2000 ticks of travel, try 0.002. 2. Raise kP until the mechanism gets close to the target fast. When it shakes back and forth around the target ("oscillates"), kP is too big: go back a step. 3. When it goes past the target (overshoots), add a little kD. Start at kP / 20 and raise it slowly. 4. When it stops a bit short and stays there (often on a lift), add a small kF (lift). Or add a small kI with `setIntegralLimit(0.2)`. 5. Write the final numbers in your design log. **Integral windup:** when something blocks the mechanism (a game piece, for example), the I part keeps growing. When the mechanism comes free, this big build-up throws it past the target. `setIntegralLimit` caps it. ### Turning with PID ```java PidController headingPid = new PidController(0.012, 0, 0.003).setAngleMode(true); // IMU headings are counterclockwise-positive, so this power is too (positive = turn left) double turnCcw = headingPid.calculate(targetHeading, ImuSetup.headingDeg(imu)); drive.drive(0, 0, -turnCcw); // the drive's turn is clockwise-positive, so flip the sign ``` --- ## SlewRateLimiter A slew rate limiter stops a value from changing too fast. When the driver slams a stick, it keeps a tall robot from tipping and a heavy mechanism from jerking. ```java SlewRateLimiter forwardRamp = new SlewRateLimiter(2.0, 4.0); // speed up 2/s, slow down 4/s // every loop (minus: the SDK gives stick UP as negative, and up should mean forward): double forward = forwardRamp.calculate(-gamepad1.left_stick_y); ``` With rate 2.0, going from 0 to full power takes 0.5 seconds. | Method | What it does | | --- | --- | | `new SlewRateLimiter(rate)` | same limit both ways, per second | | `new SlewRateLimiter(rise, fall)` | `rise` = away from zero (speeding up), `fall` = toward zero (slowing down) | | `calculate(input)` | **call every loop.** It moves toward the input, no faster than the limit. The first call gives the current value (0 unless you used `reset`). | | `reset(value)` | jumps straight to a value (for example 0 when you stop) | | `getValue()` | the last output | Tip: let it slow down faster than it speeds up (`fall` > `rise`), so the robot still stops fast. ## Feedforward A PID reacts only after an error builds up. **Feedforward** works out the power a motor needs for a speed before there is an error. It uses numbers that describe how the motor behaves. The two work well together. The [Characterizer](https://crossbotics.com/ftc-helper/docs/modules/finders/#characterizeropmode) measures these numbers on your robot. ``` power = kS x sign(speed) + kV x speed + kA x speeding-up + kG ``` - **kS:** the power to start moving (to beat friction). - **kV:** the extra power for each count per second of speed. - **kA:** the extra power for speeding up (per count per second, per second). - **kG:** the power that holds a lift up against gravity. Speeds are in encoder counts per second, like `DcMotorEx.getVelocity()`. Powers are for a 12.8 V battery. ```java Feedforward ff = new Feedforward(0.06, 0.00037, 0.00004); // from the Characterizer motor.setPower(ff.power(1500, 0, battery.getVoltage())); // 1500 counts/s, scaled for the battery // a lift: feedforward for the move plus a PID for what is left over lift.setPower(liftFf.power(targetSpeed, 0) + pid.calculate(target, lift.getCurrentPosition())); ``` | Method | What it does | | --- | --- | | `new Feedforward(kS, kV, kA)` / `(kS, kV, kA, kG)` | the numbers (kG for a lift) | | `power(speed, accel)` | the power at 12.8 V | | `power(speed, accel, batteryVolts)` | the same, scaled for the battery now (not limited to -1..1) | | `topSpeed()` | the speed at full power | --- # Core module URL: https://crossbotics.com/ftc-helper/docs/modules/core/ Learn it hands-on: [12 Organize a whole robot](https://crossbotics.com/ftc-helper/docs/tutorials/12-robot-structure/), [14 Mechanisms](https://crossbotics.com/ftc-helper/docs/tutorials/14-mechanisms/), [15 Telemetry, profiles and tuning](https://crossbotics.com/ftc-helper/docs/tutorials/15-telemetry-profiles-tuning/). The small pieces that every other part of the library uses. You meet them when you write your own mechanism class (`Subsystem`), or switch between practice and competition settings (`Profile`). You also meet them when you describe your drivetrain once for every program (`RobotConfig`). With the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/robot-java/), you use them by name only for a special case. To see how they fit together, start with tutorial 12. | Class | Use it to | | --- | --- | | [`Subsystem`](#subsystem) | give any mechanism the same shape: update it every loop, stop it, show it on the screen | | [`Subsystems`](#subsystems) | update, stop and show a group of mechanisms together | | [`Profile`](#profile) | behave differently in PRACTICE and COMPETITION | | [`SettingsFile`](#settingsfile) | keep small settings on the Control Hub between restarts | | [`RobotConfig`](#robotconfig) | describe the drivetrain once, for TeleOp and every autonomous | | [`InitStop`](#initstop) | show a mistake found at INIT as plain lines on the Driver Station | | [`Time`](#time) | the library's clock (a test can swap in a pretend one) | --- ## Subsystem An **interface**: a promise that a class has these methods. Every mechanism helper in the library (`PositionMotor`, `SpinMotor`, `Flywheel`, `Launcher`, `Turret`, cameras...) is a `Subsystem`. | Method | Required? | What it is for | | --- | --- | --- | | `update()` | yes | the loop calls it once every loop. It is the one place that talks to the hardware | | `stop()` | no (default: nothing) | stop all motion. The OpMode calls it at the end | | `addTelemetry(RobotTelemetry t)` | no | add this part's lines (standard and debug) | | `name()` | no (default: class name) | shown in telemetry | **Why one shape for everything:** ONE line updates the whole robot. Autonomous can keep every mechanism working during a drive move. And next season's new mechanism plugs in without changes anywhere else. Your own mechanism: ```java // "implements Subsystem": Bucket promises to have update() (and may add stop(), addTelemetry()) public class Bucket implements Subsystem { private final PositionServo servo; private boolean dumping = false; // the state: what the bucket should be doing // Runs once, when the robot code makes the Bucket (in INIT). "bucket" = configuration name. public Bucket(HardwareMap hw) { servo = PositionServo.create(hw, "bucket").position("CARRY", 0.3).position("DUMP", 0.9); } public void dump() { dumping = true; } // commands only change state: quick, safe from a button public void carry() { dumping = false; } // @Override: fills in a method Subsystem asks for. "a ? b : c" = if a then b, else c. @Override public void update() { servo.goTo(dumping ? "DUMP" : "CARRY"); servo.update(); } @Override public void addTelemetry(RobotTelemetry t) { t.line("Bucket", dumping ? "DUMP" : "carry"); } } ``` The pattern: **commands** change a little state and are quick, so a button can call them safely. **`update()`** turns that state into hardware actions. A servo command may move the servo at once. So command a part in INIT only when a move then is safe. ## Subsystems A group of subsystems that acts like one. ```java Subsystems robot = new Subsystems().add(lift, claw, intake); // null parts are skipped robot.update(); // each, in order robot.addTelemetry(t); robot.stop(); // stops each, even if one throws an error ``` | Method | What it does | | --- | --- | | `add(parts...)` | adds parts. It skips null, for optional hardware | | `update()`, `stop()`, `addTelemetry(t)` | does it for every part, in order. `update()` times each part. When a part takes more than 25 ms (it waits or sleeps), the group shows a warning | | `getSlowUpdateWarning()` | "" or the last slow part. It stays for 5 s after the last slow update | | `all()` | the list of parts | `Subsystems` is itself a `Subsystem`, so a group can contain groups. ## Profile `PRACTICE` or `COMPETITION`. The Control Hub saves it, so it stays until someone changes it. **Default: COMPETITION** (the safe one). | | PRACTICE | COMPETITION | | --- | --- | --- | | `RobotTelemetry` debug lines | start ON | start OFF | | `TuningMenu` | can open | stays closed | | `EasyAuto` INIT screen | warns "PRACTICE profile" | - | | Method | What it does | | --- | --- | | `Profile.current()` | the active profile | | `Profile.set(p)` | changes and saves it (or use `InitMenu.profile()`) | | `Profile.pick(practiceValue, competitionValue)` | one value or the other. It works with numbers, true/false, anything | | `profile.isPractice()` | whether the profile is PRACTICE | ```java // Profile.pick(value in PRACTICE, value in COMPETITION) c.powerLimit = Profile.pick(0.6, 1.0); // gentle in the shop boolean showCamera = Profile.pick(true, false); // live view only in practice ``` Full guide: [Profiles](https://crossbotics.com/ftc-helper/docs/guides/profiles/). ## SettingsFile A tiny file on the Control Hub that keeps settings as name = value pairs: `/sdcard/FIRST/ftc-helper/settings.properties`. `Profile` and `Tunable` use it. You need it yourself only for a special case. | Method | What it does | | --- | --- | | `SettingsFile.shared()` | the robot's settings file | | `SettingsFile.folder()` | the helper's folder: `/sdcard/FIRST/ftc-helper` on the robot, the simulator's data folder on a laptop (the `ftchelper.dataDir` setting) | | `get(key, fallback)`, `getDouble(key, fallback)`, `has(key)` | read | | `put(key, value)`, `remove(key)` | change in memory | | `save()` | write the file. It gives false when it could not, and the robot keeps working. It waits until the file is written, so use it in INIT or tests | | `saveInBackground()`, `saveInBackground(ok -> ...)` | write the file on a background thread, and return at once. Use this while the robot runs | | `SettingsFile.useForTests(file)` | tests only: use another file | A damaged or missing file means "nothing saved". Then the library uses the values in the code. ## RobotConfig The drivetrain, described ONCE: motor names and directions, autonomous tuning, and how the Control Hub is mounted. [`EasyTeleOp`](https://crossbotics.com/ftc-helper/docs/modules/teleop/) and [`EasyAuto`](https://crossbotics.com/ftc-helper/docs/modules/auto/) both read it from their `robotConfig()`. So TeleOp and every autonomous always match. When you change a motor name here, every program gets it. ```java public class RobotSettings extends RobotConfig { @Override public DriveConfig drive() { DriveConfig c = DriveConfig.mecanum(); c.frontLeft = "front_left"; // ... the other three names c.powerLimit = Profile.pick(0.6, 1.0); return c; } @Override public AutoDriveConfig auto() { ... } // optional: only autonomous uses it @Override public IMU imu(HardwareMap hardwareMap) { return ImuSetup.get(hardwareMap, "imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD); } } // in every TeleOp and autonomous: @Override protected RobotConfig robotConfig() { return new RobotSettings(); } // (the tutorials' RobotSettings uses static methods instead: return RobotSettings.config();) ``` | Method | Required? | What you return | | --- | --- | --- | | `drive()` | yes | the [`DriveConfig`](https://crossbotics.com/ftc-helper/docs/modules/drive/#driveconfig). The library may call it more than once, so make a fresh one each time | | `auto()` | no | the [`AutoDriveConfig`](https://crossbotics.com/ftc-helper/docs/modules/drive/#autodriveconfig). Default: untuned, and autonomous refuses to run until you tune it | | `imu(hardwareMap)` | yes | the IMU, usually one [`ImuSetup.get`](https://crossbotics.com/ftc-helper/docs/modules/hardware/) line. Every Control Hub has one. Null = no IMU: TeleOp is robot-centric only, and autonomous refuses to start | The mechanisms go in your own `Robot` class, not here. Then your programs can reach them by name (`robot.lift`). See the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/). ## InitStop It shows a mistake found at INIT as plain lines on the Driver Station, in place of the FTC app's red line. A mistake can be a wrong name in Robot.java or a missing number in Tunables.java. For a missing number, you see: INIT STOPPED: the robot did not start.
Tunables.Lift has no max: write max (...)
Fix it, then press INIT again. Press STOP now. Then it waits for STOP, and nothing moves. The library's OpModes (EasyTeleOp, EasyAuto, the finders, the Hardware Check, Tune and check) and `robot.init(this)` use it already. InitStop does not catch a mistake after ▶ (start on the Driver Hub): the FTC app shows it as before. The robot log keeps the full error. | Method | What it does | | --- | --- | | `InitStop.run(this, () -> { ... })` | in your own `LinearOpMode`: runs the code. It shows a mistake before ▶ and waits for STOP | | `InitStop.showAndWait(this, e)` | show one error now and wait for STOP (false in the simulator) | | `InitStop.words(e)` | the plain words for an error. It gives a library message as it is, and another error with where it happened, for example "NullPointerException in Robot.java line 42" | **Why:** the red line starts with Java words, and you can miss the real message after them. In the simulator, INIT errors still show in its own error panel. ## Time The library's clock. A JUnit test can swap in a pretend clock and move the time forward by hand. Then a test of timing is quick, and it gives the same result on a slow computer. Use the testkit's [`PretendClock`](https://crossbotics.com/ftc-helper/docs/modules/testkit/#pretendclock). `Time.nanos()` is the time now, in nanoseconds. Only the difference between two times means anything. On the robot it is the real clock, `System.nanoTime()`. Most of the robot's parts read it each time they need the time. These parts include the five-files modules, the launcher, the mechanisms, the match timer, and the PID and slew controllers. | Method | What it does | | --- | --- | | `Time.nanos()` | the time now, in nanoseconds. It never waits | | `Time.useForTests(clock)` | JUnit tests only: use this clock (nanoseconds). Null = the real clock again | A new part that needs the time reads `Time::nanos`, not `System::nanoTime`, so tests can move it. Two parts keep the real clock. The slow-loop warning measures how long the loop itself takes. The camera aim uses the real clock because the camera stamps its pictures with it, so the aim measures a picture's age on it too. --- # Drive module URL: https://crossbotics.com/ftc-helper/docs/modules/drive/ Learn it hands-on: [04 Mecanum](https://crossbotics.com/ftc-helper/docs/tutorials/04-drive-mecanum/), [05 Tank](https://crossbotics.com/ftc-helper/docs/tutorials/05-drive-tank/), [09 Autonomous by hand](https://crossbotics.com/ftc-helper/docs/tutorials/09-first-auto/), [10 Autonomous with mechanisms](https://crossbotics.com/ftc-helper/docs/tutorials/10-auto-with-mechanisms/). Drives a **mecanum** chassis or a **standard** chassis, in TeleOp and in autonomous. A mecanum chassis has 4 mecanum wheels, so it can also slide sideways. A standard chassis (also called tank or differential drive) has normal wheels, a left side and a right side, and 2 or 4 motors. With the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/), you describe the drive in one line, and these classes work underneath. Use this page to drive by hand in your own OpMode, or to look up a setting. First read [Signs and units](https://crossbotics.com/ftc-helper/docs/conventions/): it says which way is plus and which is minus. | Your robot | TeleOp class | Autonomous class | Config | | --- | --- | --- | --- | | Mecanum, 4 motors | `MecanumDrive` | `AutoDrive` | `DriveConfig.mecanum()` | | Standard, 4 motors | `TankDrive` | `AutoDrive` | `DriveConfig.tank()` | | Standard, 2 motors | `TankDrive` | `AutoDrive` | `DriveConfig.tankTwoMotor()` | | Class | Use it to | | --- | --- | | [`DriveConfig`](#driveconfig) | choose the drive type, name the motors, set their directions and a power limit | | [`MecanumDrive`](#mecanumdrive) | drive a mecanum robot in TeleOp (robot-centric or field-centric) | | [`TankDrive`](#tankdrive) | drive a standard (tank) robot in TeleOp (arcade or tank style) | | [`DriverControls`](#drivercontrols) | standard TeleOp driving from one gamepad (mecanum or tank, slow trigger, field-centric switch) | | [`DriverHeading`](#driverheading) | know which way the robot faces compared with the driver. It continues from autonomous | | [`ReverseDrive`](#reversedrive) | switch to a mode where the back of the robot acts as the front | | [`AutoDriveConfig`](#autodriveconfig) | hold the tuning numbers for autonomous moves | | [`AutoDrive`](#autodrive) | autonomous: drive a distance, turn an angle, turn to a heading | | [`MecanumMixer`](#mecanummixer) | do the mecanum wheel-power math (no hardware) | | [`DifferentialMixer`](#differentialmixer) | do the standard-drive left/right math (no hardware) | | [`MotionMath`](#motionmath) | do the math that slows a move down near its end (the "taper") | | [`StallDetector`](#stalldetector) | tell when a move is stuck | | [`FieldMap`](#fieldmap) | hold your keep-out boxes, and find the route around them | | [`RouteDriver`](#routedriver) | drive a route in TeleOp, one loop at a time | The steps to [check motor directions](#check-motor-directions) and [tune AutoDrive](#tune-autodrive) are at the end of the page. --- ## DriveConfig A small settings object. Start from the factory method for your drivetrain (a method that makes one with the usual settings). Then change what is different on your robot. ```java DriveConfig driveConfig = DriveConfig.mecanum(); // or DriveConfig.tank(), DriveConfig.tankTwoMotor() driveConfig.frontLeft = "fl"; // only if your names are different driveConfig.powerLimit = 0.6; // no wheel ever gets more than 0.6 power ``` | Factory | Type | Motor names | | --- | --- | --- | | `DriveConfig.mecanum()` (same as `new DriveConfig()`) | `MECANUM` | `front_left`, `front_right`, `back_left`, `back_right` | | `DriveConfig.tank()` | `TANK` | `front_left`, `front_right`, `back_left`, `back_right` | | `DriveConfig.tankTwoMotor()` | `TANK` | `left_drive`, `right_drive` (the FTC sample names). The back names are `null` | | Field | Default | Meaning | | --- | --- | --- | | `type` | `MECANUM` | `DriveType.MECANUM` or `DriveType.TANK` | | `frontLeft`, `frontRight`, `backLeft`, `backRight` | `"front_left"` ... `"back_right"` | the motors' names in the configuration. For a 2-motor tank, use `frontLeft`/`frontRight` and set both back names to `null`. | | `frontLeftReversed` ... `backRightReversed` | left = `true`, right = `false` | which motors run reversed | | `powerLimit` | `1.0` | the most power any wheel ever gets. Use 0.4 on a new robot. | | `brake` | `true` | the wheels hold still at power 0 (false = coast: they roll freely) | | Method | What it does | | --- | --- | | `hasBackMotors()` | true when both back motor names are set | | `validate()` | checks that the settings make sense (the drive classes call it for you). A mecanum drive needs 4 names. The back names must be both set or both `null`. | Use the SAME `DriveConfig` in TeleOp and autonomous. One way: write one class in TeamCode with a `static DriveConfig make()` method, and call it from both. --- ## MecanumDrive ```java MecanumDrive drive = new MecanumDrive(hardwareMap, driveConfig); waitForStart(); while (opModeIsActive()) { // forward, strafe right, turn clockwise. Minus: the SDK gives stick UP as negative. drive.drive(-gamepad1.left_stick_y, gamepad1.left_stick_x, gamepad1.right_stick_x); } drive.stop(); // wheels off when the OpMode ends ``` The constructor gets the four motors and sets their direction and brake. It uses plain power (RUN_WITHOUT_ENCODER) and sets the power to 0. A wrong motor name gives a clear error. | Method | What it does | | --- | --- | | `drive(forward, strafeRight, turnClockwise)` | robot-centric drive. Each value is -1 to 1. | | `drive(forward, strafeRight, turnClockwise, speedScale)` | the same, times a speed multiplier from 0 to 1 (for a slow mode) | | `driveFieldCentric(fieldForward, fieldRight, turnClockwise, headingCcwDeg)` | field-centric drive (see below) | | `driveFieldCentric(..., headingCcwDeg, speedScale)` | the same, with a speed multiplier | | `stop()` | sets all wheels to 0 | | `setPowers(double[4])` | sets each wheel yourself (order FL, FR, BL, BR), for testing. The power limit still applies. | | `setBrake(boolean)` | `true` = hold at 0 power, `false` = coast | | `getMotors()` | the four `DcMotorEx` motors (FL, FR, BL, BR) | | `getConfig()` | the `DriveConfig` | The numbers can add up to more than 1 on a wheel, for example full forward and full strafe. Then the drive scales all four wheels down together, and the robot keeps the direction you asked for. ### Robot-centric or field-centric? - **Robot-centric:** stick up drives the robot the way IT faces. It is simple. When the robot faces you, stick up drives it toward you. - **Field-centric:** stick up drives the robot AWAY FROM YOU, whichever way it faces. New drivers find it easier. It needs the IMU (the turn sensor inside the Control Hub, see [ImuSetup](https://crossbotics.com/ftc-helper/docs/modules/hardware/#imusetup)). ```java double heading = ImuSetup.headingDeg(imu); // read every loop: which way the robot faces now drive.driveFieldCentric(-gamepad1.left_stick_y, gamepad1.left_stick_x, gamepad1.right_stick_x, heading); ``` The heading must be 0 when the robot faces away from the driver. In a match, use [`DriverHeading`](#driverheading) instead of the plain IMU heading. It continues from where autonomous ended, so "forward" is right from the first second of TeleOp. ## DriverControls Standard TeleOp driving from one gamepad, for mecanum AND tank robots, in one line per loop. [`EasyTeleOp`](https://crossbotics.com/ftc-helper/docs/modules/teleop/) uses it for you. ```java DriverHeading heading = new DriverHeading(imu); // or null: no field-centric DriverControls driving = DriverControls.create(hardwareMap, new RobotSettings().drive(), heading); // every loop: driving.update(gamepad1); // at the end (in finally): driving.stop(); ``` | Control | What it does | | --- | --- | | left stick | drives (mecanum: any direction, tank: forward and back) | | right stick X | turns | | left trigger | slows the robot, down to `slowSpeed` at a full squeeze | | Method | What it does | | --- | --- | | `DriverControls.create(hardwareMap, config, heading)` | makes a `MecanumDrive` or a `TankDrive`, from `config.type` | | `update(gamepad)` | drives from the sticks. Call it every loop. | | `update(gamepad, slow)` | the same, but your own code turns slow mode on, in place of the left trigger | | `update(gamepad, speed)` | the same, at a speed your own code works out (0 to 1, for example from a slow trigger that is not LT) | | `drive(forward, strafeRight, turnClockwise, speed)` | drives with your own numbers (robot-centric), for custom controls | | `tank(left, right, speed)` | two-stick tank style: one value per side. It works on tank and mecanum robots. | | `turnAssist(turn -> ...)` | a helper that may change the turn every loop. It gets the driver's shaped turn (clockwise +) and gives back the turn to use. Forward and sideways stay the driver's. Null = none. The five-files TeleOp uses it for [whole-robot aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/). | | `moveScale(() -> ...)` | multiplies forward and strafe every loop, 0 to 1 (1 = unchanged, the default). The turn is not changed. The five-files TeleOp uses it to drive slower while [whole-robot aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#whole-robot-aim) is on (`Tunables.Aim.aimDriveSpeed`). Null = always 1. | | `hold()` | keeps the wheels still this loop (for example while a menu uses the gamepad) | | `stop()` | sets all wheels to 0 | | `slowSpeed(s)` | the speed at a full slow trigger, default 0.3 | | `sticks(deadband, exponent)` | the stick feel, default 0.05 and 2 ([StickShaping](https://crossbotics.com/ftc-helper/docs/modules/gamepad/)) | | `reverseWhen(() -> on)` | reverses the drive while the test gives true. Forward and strafe flip (the back is the front), and the turn does not. Field-centric ignores it. The five-files TeleOp uses it for `robot.reverseDriveMode()` | | `swapSticks(true)`, `sticksSwapped()` | the right stick drives (and strafes), and the left stick X turns. Default false | | `setFieldCentric(on)`, `toggleFieldCentric()`, `isFieldCentric()` | the field-centric switch. It starts off. It stays off on a tank robot or without a heading. | | `canFieldCentric()` | true with mecanum wheels and a heading | | `isSlow()`, `status()` | for telemetry. `status()` gives text like "field SLOW" | ## DriverHeading Which way the robot faces compared with the driver: 0 = straight away from the driver, left = +. **Why:** In INIT, TeleOp sets up the IMU again. That makes "0" the way the robot faces at that moment, which is wherever autonomous left it. Drivers may not touch the robot between autonomous and TeleOp. Without help, field-centric "forward" stays wrong until the driver turns the robot and presses a reset button. ```java // TeleOp INIT, after the IMU is set up: DriverHeading heading = new DriverHeading(imu); // reads autonomous's saved heading controls.bindPress(Pad.G1, Btn.BACK, heading::reset); // manual reset: face away first waitForStart(); heading.forgetSaved(); // this run uses it now // every loop: drive.driveFieldCentric(forward, strafe, turn, heading.degrees(), speed); ``` | Method | What it does | | --- | --- | | `new DriverHeading(imu)` | call it in TeleOp INIT, after the IMU is set up. It reads the heading autonomous saved, when that is less than 5 minutes old. Otherwise 0 = the way the robot faces now. | | `forgetSaved()` | call it right after ▶ (start on the Driver Hub). It clears the saved heading, so a later TeleOp run does not use it. Do not call it in INIT: then INIT, STOP, INIT again still works. EasyTeleOp does this for you. | | `degrees()` | the heading compared with the driver, -180 to 180. Call it every loop. | | `reset()` | means "the robot now faces away from me": the heading now = 0. For a button. | | `isFromAuto()` | true while it still counts from autonomous (no reset since) | Where the saved heading comes from: - **EasyAuto** saves it for you at the end. When the robot does not start facing straight away from its driver, override `startHeadingDeg()` with the start angle (left = +). Write it for BLUE. EasyAuto mirrors it for RED, like the turns (unless `mirrorForRed()` returns false). - **Your own autonomous:** at the end, call `PoseStore.save(new FieldPose(0, 0, heading))`. Measure the heading from "away from the driver" (use `auto.headingDeg()` when the robot started facing away). --- ## TankDrive For a standard (tank / differential) drive with 2 or 4 motors. It cannot move sideways. ```java TankDrive drive = new TankDrive(hardwareMap, DriveConfig.tankTwoMotor()); waitForStart(); while (opModeIsActive()) { // left stick = forward/back (minus: stick UP is negative), right stick = turn drive.arcade(-gamepad1.left_stick_y, gamepad1.right_stick_x); } drive.stop(); // wheels off when the OpMode ends ``` The constructor gets the motors and sets their direction and brake. It uses plain power and sets the power to 0. It refuses a `MECANUM` config (and `MecanumDrive` refuses a `TANK` one), so you cannot mix them up. | Method | What it does | | --- | --- | | `arcade(forward, turnClockwise)` | **arcade style:** one stick for forward, one for turning. Each is -1 to 1. | | `arcade(forward, turnClockwise, speedScale)` | the same, with a speed multiplier from 0 to 1 | | `tank(left, right)` | **tank style:** one stick for each side, for example `tank(-gamepad1.left_stick_y, -gamepad1.right_stick_y)` | | `tank(left, right, speedScale)` | the same, with a speed multiplier | | `stop()` | sets both sides to 0 | | `setPowers({left, right})` | sets each side yourself. The power limit still applies. | | `setBrake(boolean)` | `true` = hold at 0 power, `false` = coast | | `getMotors()` | `{left, right}` for 2 motors, `{FL, FR, BL, BR}` for 4 | | `getConfig()` | the `DriveConfig` | **Arcade or tank style:** most new drivers find arcade easier. Tank style gives direct control of each side. `ExampleTankTeleOp` lets the driver switch with X. --- ## ReverseDrive When the mode is ON, forward and strafe flip, so the back of the robot acts as the front. The turn does not flip. ```java ReverseDrive reverse = new ReverseDrive(); // toggle() flips the mode and returns it; confirm (a ToggleRumble) buzzes 2x = ON, 1x = OFF controls.bindPress(Pad.G1, Btn.L_STICK_BTN, () -> confirm.play(reverse.toggle())); // every loop: drive.drive(reverse.apply(forward), reverse.apply(strafe), turn); ``` | Method | What it does | | --- | --- | | `toggle()` | flips the mode. It gives the new state (true = reversed). | | `set(boolean)` | sets the mode | | `isReversed()` | true when reversed | | `apply(value)` | use it on forward and strafe only. It gives the value, flipped when reversed. | --- ## AutoDriveConfig Tuning numbers for `AutoDrive`. The defaults come from last season's robot. **Tune them on this robot** (see [Tune AutoDrive](#tune-autodrive)). | Field | Default | Meaning | | --- | --- | --- | | `calibrationConfirmed` | `false` | `AutoDrive` refuses to run until you set this to `true`. It reminds you to tune first. | | `ticksPerRev` | 537.7 | encoder counts per motor turn. goBILDA 312 RPM = 537.7, 435 RPM = 384.5. Check your motor's page. | | `wheelDiameterIn` | 4.098 | the wheel size, in inches. The default is last season's wheel (about 104 mm). Start with your wheel's real size (for example, 96 mm = 3.78 in), then tune. | | `gearRatio` | 1.0 | motor turns per wheel turn | | `strafeCorrection` | 1.15 | mecanum wheels slip sideways. `AutoDrive` divides the sideways wheel travel by this to get the real distance. It also multiplies the sideways power by it, so diagonals stay straight. | | `turnKp` | 0.012 | turn power per degree of error | | `turnKd` | 0.003 | slows the turn near the end to stop overshoot | | `turnToleranceDeg` | 1.0 | a turn is done when the error stays inside this... | | `turnSettleSec` | 0.15 | ...for this long | | `turnMinPower` | 0.0 | the smallest turn power outside the tolerance. Try 0.05-0.1 when turns stop short. | | `moveMinPower` | 0.30 | the slowest speed at the end of a move | | `taperStartFraction` | 0.10 | the move starts slowing for its last 10% | | `slowDownIn` | 0 | ...and for at least this many inches at the end (0 = only the 10%). `taperFraction(distanceIn)` gives the larger of the two | | `moveTurnScale` | 0.60 | `moveWithTurn` multiplies the heading correction by this | | `moveMaxTurnPower` | 0.35 | `moveWithTurn` and routes: the most turn power while moving | | `driveToNearIn` | 8 | `driveTo` and routes: in the last this-many inches, the speed follows the distance left... | | `driveToKp` | 0.04 | ...this much power per inch left... | | `driveToMinPower` | 0.12 | ...but at least this power, so it does not stall short | | `driveToMinTurn` | 0.08 | `driveTo` and routes: the least turn power while the heading is off, when `turnMinPower` is 0 | | `actionTimeoutSec` | 10.0 | any move or turn gives up after this long | | `stallExitEnabled` | `true` | stops a move early when the robot is stuck | | `stallProgressIn` | 0.25 | stuck = less than this many inches of progress... | | `stallTimeSec` | 0.4 | ...within this many seconds | `ticksPerInch()` gives the encoder counts per inch. It works them out from the first four numbers. --- ## AutoDrive Autonomous moves for mecanum and standard (tank) robots. It measures distance with the wheel **encoders** (sensors that count how far each motor turned), and it turns with the IMU. The `DriveConfig` type tells it which drive you have. Each method **waits until the move ends**, so use them only in a `LinearOpMode` autonomous. No wheel ever gets more power than `DriveConfig.powerLimit`, whatever `maxPower` you pass. ```java AutoDrive auto = new AutoDrive(this, driveConfig, autoConfig, imu); // this = your OpMode waitForStart(); // Each line waits until that move is done, then the next one starts. 0.6 = top power. auto.move(24, 0, 0.6); // 24 in forward auto.move(12, -90, 0.5); // 12 in right (90 = left) auto.turn(90, 0.5); // turn 90 degrees left auto.turnTo(0, 0.5); // face the start direction ``` ### The constructor `new AutoDrive(opMode, driveConfig, autoConfig, imu)` - `opMode`: your `LinearOpMode`, usually `this`. - `driveConfig`: the same `DriveConfig` TeleOp uses. - `autoConfig`: the tuning. The constructor throws an error when `calibrationConfirmed` is false. - `imu`: from `ImuSetup.get(...)`. `new AutoDrive(opMode, driveConfig, autoConfig, imu, isActive)` is the same, with your own "keep going" check (`isActive`, true while the moves may run). Use it for an OpMode that runs inside another one, such as a finder inside "Tune and check". There, the finder's own `opModeIsActive()` is always false, so every move would end at once with `STOPPED`. The constructor resets the drive encoders, uses RUN_USING_ENCODER and brake, and sets the power to 0. ### Methods | Method | What it does | | --- | --- | | `move(distanceIn, directionDeg, maxPower)` | drives straight, with no turning. `directionDeg` is robot-relative and counterclockwise, like a heading: 0 forward, 90 left, 180 back, -90 right. A negative distance goes the other way. | | `moveWithTurn(distanceIn, fieldDirectionDeg, targetHeadingDeg, maxPower, maxTurnPower)` | drives in a FIELD direction and turns to a heading at the same time. The field direction stays fixed while the robot turns (counterclockwise, 90 = left). When the move ends before the heading is reached, it finishes the turn inside the same time limit. After a stall, it does not turn. | | `turn(degrees, maxPower)` | turns in place by an amount. Positive = left. | | `turnTo(headingDeg, maxPower)` | turns in place to face a heading (IMU degrees, 0 = start direction) | | `turn(degrees, maxPower, timeoutSec)`, `turnTo(headingDeg, maxPower, timeoutSec)` | the same with a shorter time limit, for a step that has its own (never more than `actionTimeoutSec`) | | `headingDeg()` | the IMU heading | | `resetHeading()` | makes the current heading 0 | | `getWheelTicks()` | the encoder counts (FL, FR, BL, BR) | | `stop()` | stops all wheels | | `setLoopHook(code)` | runs your code once per loop during every move, for example `auto.setLoopHook(() -> lift.moveTo(target, pid));` Keep it fast. | | `setStopCondition(condition)` | ends a move early (result `STOPPED`) when this becomes true. `AutoRoutine` uses it for park time. | A third constructor is for simulations and tests, with no robot. You give it pretend motors, a heading, "is the OpMode running" and "idle". The library's own tests drive a pretend robot this way. ### On a standard (tank) drive A standard drive cannot move sideways. So: - `move` works only with direction `0` (forward) or `180` (back). Any other direction throws an error that says "turn first, then move". - `moveWithTurn` throws an error. Use `turnTo(...)` and then `move(...)`. - `turn` and `turnTo` work the same as on mecanum. - `AutoDrive` does not use `strafeCorrection`. ```java auto.move(24, 0, 0.6); // forward auto.turnTo(90, 0.5); // face left auto.move(12, 0, 0.6); // forward again (in the new direction) ``` ### Results Every move returns how it ended, an `AutoDrive.Result`: | Result | Meaning | | --- | --- | | `DONE` | the robot reached the target | | `STALLED` | the move stopped early: the robot was stuck (pushing a wall or a robot) | | `TIMED_OUT` | the move took longer than `actionTimeoutSec` | | `STOPPED` | the OpMode stopped | You can ignore it, or react to it: ```java // STALLED = stuck: pushing on would waste time and strain the motors if (auto.move(30, 0, 0.7) == AutoDrive.Result.STALLED) { auto.move(4, 180, 0.4); // back off a little } ``` ### How a move works (cruise and taper) `AutoDrive` measures the distance with the four wheel encoders: forward travel plus sideways travel (divided by `strafeCorrection`). So straight, sideways and diagonal moves all go the real distance. A robot that stops from full speed slides past its target. So the robot drives at `maxPower` until the last 10% (`taperStartFraction`) of the distance. Then it slows in a straight line down to `moveMinPower`. On a short move, 10% is too little road to slow down on, and the robot reaches the end fast and slides past it. With `slowDownIn` (for example 6), the robot also slows over at least the last 6 in. At the distance, the wheels brake. The move waits until the robot stops rolling (at most 0.3 s, with the mechanisms still updating). So the next move starts from a robot that stands still. The motors always stop at the end, whatever happens (even when your code throws an error). --- ## Check motor directions A motor that runs the wrong way makes the robot drive in circles. Do this check first on every new drivetrain. **Put the robot on a block, with the wheels off the ground.** **With the robot in five files:** you copy nothing. Use **Tune and check > Motor Direction Check**. It reads the directions from Robot.java ([steps](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#motor-direction-check-each-wheel-rolls-forward)). **With your own `DriveConfig`** (no Robot.java): 1. Copy `examples/.../MotorDirectionCheck.java` into TeamCode. Set its `config()` to your `DriveConfig`, and remove `@Disabled`. 2. Run it. Hold X, Y, A or B: each spins one wheel (front-left, front-right, back-left, back-right). On a 2-motor tank, only X (left) and Y (right) work. 3. Every wheel must roll so the robot would go FORWARD. 4. When one rolls backward, flip its `...Reversed` value in your `DriveConfig`. With the robot in five files, add the motor's name to `.reversed(...)` in `Robot.java` (or take it out). A held button spins its wheel at 30%: slow enough to be safe, and fast enough to see the direction. Run the check again after anyone changes a motor or a wire. 5. Then put the robot on the floor, with `powerLimit = 0.4`. Stick up must drive forward, and right stick right must turn clockwise. On mecanum only, left stick right must strafe right. When strafing goes diagonal, a motor name is on the wrong wheel. ## Tune AutoDrive Do these steps in order. Write each result in your team's log. 1. **IMU:** check the heading sign (see [hardware.md](https://crossbotics.com/ftc-helper/docs/modules/hardware/#imusetup)). 2. **Ticks per inch:** set `ticksPerRev` from the motor's product page, and set `wheelDiameterIn` to the real wheel size. Run `auto.move(48, 0, 0.5)`. Measure the real distance. New diameter = old diameter x (real distance / 48). Repeat until the move is within half an inch. 3. **Strafe (mecanum only):** run `auto.move(48, -90, 0.5)` (to the right). New `strafeCorrection` = old x (48 / real distance). 4. **Turns:** run `auto.turn(90, 0.5)` and `auto.turn(-90, 0.5)`. When it overshoots, raise `turnKd` or lower `turnKp`. When it stops short, raise `turnKp` (in small steps, like 0.002) or set `turnMinPower`. 5. Set `calibrationConfirmed = true`. --- ## MecanumMixer The math under `MecanumDrive`. It uses no hardware, so you can test it on a laptop. You need it only to build your own drive. | Method | What it does | | --- | --- | | `mix(forward, strafeRight, turnClockwise, limit)` | four wheel powers (FL, FR, BL, BR), scaled together so none is over `limit`. All are zero when an input is NaN. | | `fieldToRobot(fieldForward, fieldRight, headingCcwDeg)` | changes a field-relative command into `{forward, strafeRight}` for the robot | | `fieldDirection(fieldCcwDeg, headingCcwDeg)` | a field direction as `{forward, strafeRight}` for the robot, with a length of 1 | | `FRONT_LEFT`, `FRONT_RIGHT`, `BACK_LEFT`, `BACK_RIGHT` | the index of each wheel (0-3) | ## DifferentialMixer The math under `TankDrive`. It uses no hardware. | Method | What it does | | --- | --- | | `arcade(forward, turnClockwise, limit)` | `{left, right}` = `{forward + turn, forward - turn}`, scaled together so neither is over `limit`. Both are zero when an input is NaN. | | `tank(left, right, limit)` | `{left, right}`, each cut to -1..1 and multiplied by `limit` | | `LEFT`, `RIGHT` | the index of each side (0, 1) | ## MotionMath | Method | What it does | | --- | --- | | `taperSpeed(remainingFraction, minSpeed, maxSpeed, taperStart)` | the speed for this part of a move: `maxSpeed` until `taperStart` is left, then a straight line down to `minSpeed`. For example, (0.05, 0.3, 0.8, 0.1) gives 0.55. | ## StallDetector Tells when something with a target is stuck. `AutoDrive` uses it, and you can use it for a lift too. ```java StallDetector stall = new StallDetector(0.25, 0.4); // stuck: not 0.25 in closer within 0.4 s (same unit as distanceLeft) // every loop: how far is still left, and the time now (getRuntime() = seconds since INIT) if (stall.update(distanceLeft, getRuntime())) { ... stuck ... } ``` | Method | What it does | | --- | --- | | `new StallDetector(minProgress, windowSec)` | stuck = less than `minProgress` closer within `windowSec` | | `update(remaining, timeSec)` | true when stuck. Never true when `remaining` is already below `minProgress`. | | `reset()` | starts over (before a new move) | It checks the progress over the whole time window, so it works the same at any loop speed. ## FieldMap The places on the field the robot must not drive through, and the way around them. On a five-file robot, it is one line in `Robot.java`: `fieldMap(...)`. [Keep-out boxes and routes](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes) says what the numbers mean and what a route cannot do. It uses no hardware, so you can use it alone. ```java FieldMap map = FieldMap.margin(13).keepOut("Post", -5, -5, 5, 5); List points = map.route(pose.x, pose.y, 0, 40); // each point is {x, y}; empty = no route ``` | Method | What it does | | --- | --- | | `FieldMap.margin(inches)` | a new map: how far the robot's center stays from every box | | `keepOut(name, x1, y1, x2, y2)` | adds a box: two opposite corners, in inches | | `safePoint(x, y)` | adds a place a route may pass through. INIT stops when the point is within a margin (or less than 0.5 in outside it), or closer to a wall than the margin | | `fieldSize(inches)` | the side of the square field. Default 144 | | `route(fromX, fromY, toX, toY)` | the points to drive to, in order, ending at the spot. Empty when there is no route: then the robot must not set off | | `lineIsClear(x1, y1, x2, y2)` | true when the robot's center may drive straight there: the line misses every margin. For a box whose margin holds the end, the line only has to miss the box itself | | `whyBadSpot(x, y)` | why a route cannot end there (off the field, on a box, or boxed in), or `""`. A spot inside a margin is fine: the last line goes straight in | | `marginIn()`, `boxCount()` | what the map holds | ## RouteDriver Drives a route without waiting. `route(...)` in `Controls.java` uses it for you. In autonomous, `AutoDrive.followRoute(pose, ready, points, clear, headingDeg, power, toleranceIn)` runs it in a blocking loop (`Steps.routeTo` uses that). Each loop, call `update()` and send what it gives to the wheels. [`AutoDrive.driveTo`](#autodrive) does the same work in autonomous, and blocks. ```java RouteDriver route = new RouteDriver(autoConfig, 1.0, robot::pose, odometry::isReady, System::nanoTime) .checkLines(map::lineIsClear); // leave a point early only if the line on is clear route.start(map.route(pose.x, pose.y, 0, 40), 0, 0.7, 1.0); // every loop: if (route.isRunning()) { double[] p = route.update(); // {forward, strafe right, turn clockwise} driving.drive(p[0], p[1], p[2], 1); } ``` | Method | What it does | | --- | --- | | `new RouteDriver(cfg, powerLimit, pose, ready, clockNanos)` | while `ready` is false, it holds still, and after 0.2 s it ends | | `checkLines(check)` | the map's line check (`map::lineIsClear`). A point on the way counts as reached early (within 2 in, or slid past it) only when the line from the robot to the next point is clear. Otherwise the robot drives to the point (within 0.5 in). Give it one for every route from `FieldMap.route` | | `start(points, headingDeg, maxPower, toleranceIn)` | starts a route. False when it has no points | | `update()` | one loop. It never waits. It gives all 0 once the route has ended | | `isRunning()` | true while it drives | | `result()` | `DONE`, `STALLED`, `TIMED_OUT`, `NO_ODOMETRY` or `CANCELLED`. Null while it runs | | `cancel()` | ends it now. Then your code sends the wheels what comes next | | `PASS_POINT_IN` | a point on the way counts as reached within this many inches (2) | --- # Finders module URL: https://crossbotics.com/ftc-helper/docs/modules/finders/ Learn it hands-on: [21 Find your numbers](https://crossbotics.com/ftc-helper/docs/tutorials/21-finders/). Step by step on the robot: [Finders guide](https://crossbotics.com/ftc-helper/docs/tuning/). Quick answers: [cookbook: tuning and finders](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/). Finders are ready-made programs. Each one **measures** numbers your code needs (servo ends, lift limits, flywheel gains, wheel size, odometry offsets, shot speeds, camera offset). It shows them as **lines of code to copy**. Use a finder whenever a part is new or was rebuilt, before you tune by hand. When you press STOP, the finder also saves those lines on the Control Hub in `/sdcard/FIRST/ftc-helper/finder-results.txt`. So nobody copies numbers from the screen by hand. Start with tutorial 21, or with [Add a lift](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/) for the robot in five files. Each finder shows its numbers in two forms. The first form is code for the older helpers (`PositionServo.create(...)`, `PositionMotor.create(...)`, `c.wheelDiameterIn = ...`). The second form is lines for the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/robot-java/). For example, `Tunables.Lift: min = 0, max = 2580, P1 = 1200` means "in `Tunables.java`, section `Lift`, set `min = 0`, `max = 2580`, `P1 = 1200`". The section is the device's name in CamelCase (`lift` -> `Lift`, `intake_deploy` -> `IntakeDeploy`, [`RobotDefinition.sectionName`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/)). When you gave the part its own section with `.tunables("Name")` in Robot.java, copy the numbers into that section instead. Copy the lines that fit your code. | Class | Use it to | Needs code from you? | | --- | --- | --- | | [`TuneAndCheckOpMode`](#tuneandcheckopmode) | every check and finder that fits Robot.java, in one menu (the library adds it) | no | | [`MotorDirectionCheckOpMode`](#motordirectioncheckopmode) | spin one drive motor at a time, with Robot.java's directions: each wheel must roll forward | `robot()` (five files) | | [`EncoderCheckOpMode`](#encodercheckopmode) | push each motor a little and find an encoder cable that is missing, in another motor's port, or counting backward | `robot()` (five files) | | [`ServoFinderOpMode`](#servofinderopmode) | find a servo's safe ends and positions | no | | [`HoodFinderOpMode`](#hoodfinderopmode) | find a launcher hood's two stops (`posA`, `posB`) and, if you measure them, its angles (a linkage's calibration table) | `robot()` (five files) or `hoodName()` | | [`MotorFinderOpMode`](#motorfinderopmode) | find a lift's, arm's or turret's limits, positions and top speed | no | | [`FlywheelFinderOpMode`](#flywheelfinderopmode) | find a flywheel's top speed, speed-control gains (the tuning numbers) and recovery time | no | | [`FeedStopFinderOpMode`](#feedstopfinderopmode) | find a feed stop's hold and release positions | `robot()` (five files, with `.feedStop(...)`) | | [`DriveTunerOpMode`](#drivetuneropmode) | find the wheel size and strafe correction for autonomous | `robot()` (five files) or `robotConfig()` | | [`OdometryTunerOpMode`](#odometrytuneropmode) | check which way each odometry pod counts and measure where it sits (the offsets); a loop check sets `checked` | `robot()` (five files, with an `odometry(...)` line) | | [`MoveTunerOpMode`](#movetuneropmode) | measure how exactly autonomous moves stop and turns end, and find `moveMinPower`, `slowDownIn`, the turn numbers and `moveWithTurn`'s numbers | `robot()` (five files) or `robotConfig()` | | [`AimTunerOpMode`](#aimtuneropmode) | find the camera offset so shots go in the middle | your camera (+ turret or drive) | | [`ShotTunerOpMode`](#shottuneropmode) | build the shot table: distance -> speed (and hood angle) | `robot()` (five files), or your launcher (+ camera) | | [`CameraFixCheckOpMode`](#camerafixcheckopmode) | ALPHA: find the camera fix's turn for each alliance | `robot()` (five files, with `cameraFix(camera)`) | | [`PieceTunerOpMode`](#piecetuneropmode) | see what each game-piece sensor reads, and measure each kind's color (or size) and the "empty" line | `robot()` (five files, with a `Pieces` or `PieceSensor` line) | | [`CharacterizerOpMode`](#characterizeropmode) | measure how the drive, lifts and flywheels move on your robot (feedforward numbers, and the simulator's robot file) | `robotConfig()`, `mechanisms()` | | [`FinderOpMode`](#finderopmode) | the shared frame of every finder (for writing your own) | - | | [`FinderResults`](#finderresults) | the code lines a finder shows and saves | - | | [`FinderMath`](#findermath) | the arithmetic behind the finders | - | | [`Chooser`](#chooser) | a list to choose from with the D-pad | - | | [`NudgeStep`](#nudgestep) | the step size for nudging a servo (D-pad left/right changes it) | - | | [`ShotPoints`](#shotpoints) | the saved good shots of the shot tuner | - | | [`CharacterizeMath`](#characterizemath) | the math behind the Characterizer (it fits numbers to the measurements) | - | Each finder is a TeleOp. To use one, make a tiny file in TeamCode. The [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/) has them ready: ```java @TeleOp(name = "Servo Finder", group = "Finders") public class ServoFinder extends ServoFinderOpMode { } ``` **GUIDE = help** in every finder, in INIT or while it runs. It opens a page with every button and the steps. GUIDE is the center button (the Logitech or Xbox logo, the PS button on a PlayStation controller). Some controllers have no GUIDE button, or the Driver Hub keeps it for itself. Then **hold the gamepad's START button for 1 second** (OPTIONS on a PS controller). While help is open, the finder's buttons pause and its motors stop. Servos stay where they were sent, and a camera keeps running. After ▶ (start on the Driver Hub), and after help closes, **let go of every stick, trigger and button on gamepad 1** once. Until then the finder ignores them, so a finger that was already down cannot start anything. Every finder keeps these safety rules: - Nothing moves in INIT. - The loop never waits (except the drive tuner's test moves, like autonomous). - At the end, the finder stops everything it moved, even after an error. --- ## TuneAndCheckOpMode `TuneAndCheckOpMode` is the library's own OpMode, **"Tune and check"** (group "Finders"). In INIT it shows a menu with the Hardware Check and the finders that fit Robot.java. A opens a tool (its INIT screen), ▶ runs it, and BACK in the tool's INIT goes back to the menu. It looks for the robot classes in `org.firstinspires.ftc.teamcode`. On the robot, it searches the app's classes, the same way the SDK finds OpModes. In the simulator, it searches the class path. The menu does not have the Aim Tuner or the Characterizer. Steps: [the finders guide](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/#the-tune-and-check-menu). | Member | What it does | | --- | --- | | `NAME` | `"Tune and check"`, the Driver Station name | | `useRobots(list)` | uses these robot classes instead of searching (for the simulator's tests). `null` = search again | `Hosting` runs a finder inside the menu. For a hosted finder, `inInit()` means the host's INIT, and `running()` means the time after ▶. In a finder of your own that loops by itself, use `running()`, not `opModeIsActive()`. ## MotorDirectionCheckOpMode Use it to check that each drive wheel rolls forward. Hold **X**, **Y**, **A** or **B** for front-left, front-right, back-left or back-right (a tank drive: X left, Y right). That drive motor runs at 30% while you hold the button. The check sets it up as Robot.java says (`reversed(...)` on the drive line). Each wheel must roll forward. Tune and check has it for every robot in five files. To use it on its own: ```java @TeleOp(name = "Motor Direction Check", group = "Finders") public class MotorDirectionCheck extends MotorDirectionCheckOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` Steps: [Motor Direction Check](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#motor-direction-check-each-wheel-rolls-forward). For a robot without five files (it has its own `DriveConfig`), copy `examples/.../MotorDirectionCheck.java` instead. ## EncoderCheckOpMode Use it to find an encoder cable that is missing, in another motor's port, or counting backward. Hold **A**. Once every port is still, each motor in Robot.java gets a short push (30% for 0.3 s), one at a time. The check sets each motor up as Robot.java says, and reads every motor port's encoder. Each motor shows OK, NO COUNTS, `counts on "X" instead` or `counts BACKWARD`. The check pushes a lift, arm, turret or hood toward the side of its range with more room. It finds that side from the limits in Tunables.java (`min` and `max`). A lift goes up from its bottom stop, so watch that a lift moves up. Let go of **A**, and everything stops. **Y** = check again. Tune and check has it for every robot in five files. To use it on its own: ```java @TeleOp(name = "Encoder Check", group = "Finders") public class EncoderCheck extends EncoderCheckOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` | Method | Does | | --- | --- | | `robot()` | your robot (`return new Robot();`): its motors and their directions ([`encoderMotors()`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition)) | Steps and what each result means: [Encoder Check](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#encoder-check-each-encoder-cable-in-its-own-port). ## ServoFinderOpMode Use it to find a servo's safe ends and positions. It lists every servo in the configuration. Nudge the one you choose, and mark what you find. | Button | Does | | --- | --- | | D-pad up/down (list) | choose a servo; **A** = use it | | **Y** (list) | full range on or off: 500-2500 us (microseconds) instead of the SDK's normal 600-2400. A goBILDA 2000 servo turns 300 degrees, not 270. Turn it on when the part has [`.fullRange()`](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/) in Robot.java, so the numbers fit. Then the lines say `.fullRange()` | | D-pad, then **A** (first) | choose a START POINT near where the servo sits now (it does not move). Then **A** moves it there | | D-pad up/down | move by the step (before the first move, it moves the start point) | | D-pad left/right | a smaller / bigger step: 0.1, 0.05, 0.01, 0.005, 0.001 ([`NudgeStep`](#nudgestep)). It starts at 0.05, and the screen shows it | | **X** / **B** | mark one END / the other END (the point where it stops pushing on the frame). After that, it stays between them. Hold **LB** to go past, for example to mark again | | **A** | save this as a position (P1, P2...; rename them in your code) | | **Y** | undo the last position | | **BACK** | choose another servo (its lines stay) | A servo cannot report where it is, so nothing moves until you press A at the start point. When you save a position outside the marked ends, its line gets a note. The output: ```java PositionServo.create(hardwareMap, "claw").limits(0.180, 0.770) .position("P1", 0.210) .position("P2", 0.740) Tunables.Claw: P1 = 0.210, P2 = 0.740 // rename P1, P2... (open, closed); keep them between 0.180 and 0.770 ``` In five files, the positions become `public static double open = 0.210, closed = 0.740;` in `Tunables.Claw`. A servo module has no ends of its own, so the ends become a reminder. ## HoodFinderOpMode Use it to find the numbers in `Tunables.Hood` for a launcher's [hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/). With the robot in five files, it reads the hood from Robot.java (its name, servo or motor, `reversed()`, `fullRange()`). So it works before `Tunables.Hood` has any numbers. An example is the turret robot's [HoodFinder.java](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/turretbot/HoodFinder.java): ```java @TeleOp(name = "Hood Finder", group = "Finders") public class HoodFinder extends HoodFinderOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` Without five files, it uses the servo (or motor) called `hoodName()` ("hood"). | Button | Does | | --- | --- | | D-pad (servo) | before the first move, it sets a start point (nothing moves), and **A** moves there. After that, up/down moves it by the step, and left/right makes the step smaller / bigger ([`NudgeStep`](#nudgestep)) | | (motor) | the finder powers nothing: move the hood by hand and watch the encoder (0 = where it was at INIT, as in a match) | | **X** / **B** | mark stop A / stop B. Mark it a hair off the stop, because a servo that strains against it hums | | hold **LB** + D-pad | set the angle you measured here (up/down +/- 1, right/left +/- 0.1). Do it before X, B or A | | **A** | save a calibration point here {position, angle} | | **Y** | undo the last point | The output is `Tunables.Hood: posA = 0.205, posB = 0.648`. When you gave the angle at both stops, it adds `angleA = 0, angleB = 25`. With 3 or more points, it gives `public static double[][] calibration = {{0.205, 0}, {0.33, 9}, ...};` for a linkage, and this replaces posA/posB. Copy them into `Tunables.java`, because the robot reads the file, not this screen. A number you change in the tuning menu (`Hood/posA`) is lost at the next restart, unless you save it with **A**. A saved number stays on this hub and wins over `Tunables.java`. So copy it into `Tunables.java`, then put the menu back to the code values (**Y**). ## MotorFinderOpMode Use it to find a lift's, arm's or turret's limits, positions and top speed. It lists every motor. **The count starts at 0 when you choose the motor, so put the mechanism at its bottom first.** | Button | Does | | --- | --- | | D-pad up/down (list) | choose a motor; **A** = use it (brake, count from 0) | | right stick Y | move it, at most at "max power" | | D-pad up/down | max power +/- 0.05 (0.1 to 0.6; starts at 0.3) | | **X** / **B** | mark the LOW end / the HIGH end. After that, it stops at them (hold **LB** to go past) | | **A** / **Y** | save a position / undo the last one | | hold **RT** | speed test: full power toward the HIGH end. It stops 15% of the range before that end | | **BACK** | choose another motor | The screen shows the count, the speed (counts/s) and the current (amps). A stalled motor draws a lot of current. When the HIGH end has a smaller count than the LOW end, the motor counts down as it goes up. Then the output adds `.reversed()` and flips the signs. The output: ```java PositionMotor.create(hardwareMap, "lift").limits(0, 2580) .position("P1", 1200) // top speed up: 2650 counts/s Tunables.Lift: min = 0, max = 2580, P1 = 1200 // encoder counts: right for a Lift; an Arm's numbers are degrees ``` In five files, put `min = 0, max = 2580` and a named height such as `low = 1200` in `Tunables.Lift`. For a reversed motor, the output also says `Robot.java: add .reversed() to the "lift" part`. An `Arm` reads degrees from `Tunables.java`. So divide its counts by the counts per degree (motor counts per turn x gear ratio / 360). ## FlywheelFinderOpMode Use it to find a flywheel's top speed, speed-control gains and recovery time. It lists every motor. Keep your hands away, and wear eye protection. | Step | Button | Does | | --- | --- | --- | | 1 | hold **A** | runs full power (at most 5 s), measures the top speed and works out starting gains. The A press that chose the motor does not count: let go and press again | | 2 | **B** | turns speed holding on or off (the library's `Flywheel`, with those gains, or the gains in Tunables.java) | | 2 | **Y** | the gains step 2 uses: Tunables.java's, or this finder's own (after step 1) | | 2 | D-pad up/down, right/left | target +/- 100 / 25 RPM (starts at 60% of top speed) | | 2 | **RB** / **LB** | F gain +2% / -2%. F does most of the work: when the wheel is too slow at every speed, add F | | 1, 2 | **X** | reverses the wheel when it spins the wrong way (adds `.reversed()`) | Each motor starts in the direction from `motorDirections()` (motor name to `true` for reversed). Tune and check fills it from Robot.java: a launcher with `.reversed()` starts reversed, so the wheel spins the way it does in TeleOp. A motor not in the map starts forward. Your own finder can override `motorDirections()`. When **X** makes the direction differ from Robot.java, the results say to add or remove `.reversed()` there. The list starts on the flywheel: the first motor in `motorDirections()` or `robotGains()`, else a name with "fly", "launch" or "shoot". `robotGains()` (motor name to {kP, kI, kD, kF, nominalVolts or NaN}) holds the wheel in step 2 with the robot's own gains, so step 1 is not needed and **RB** / **LB** fine-tune the kF the robot uses; the Tunables line keeps their kP, kI and kD. Tune and check fills it from `Tunables.java` (a launcher with kP, kI and kF). When the speed still rose in the last second before step 1's 5 s limit (a heavy wheel), the finder warns `Still speeding up at 5 s` and adds "may be higher" to the top-speed line. F is then a little high: fine-tune it in step 2. When the encoder counts BACKWARD at forward power, the finder warns you to check the encoder cable and port. It also blocks step 2, because speed control with a backward encoder would run away. In step 2, feed a piece with the robot's feeder or a push stick, never with fingers near the wheel. The finder then shows the **recovery time** (from the shot until the wheel is ready again), "Shots seen" (the drops of more than 150 RPM) and "Shot drop": every drop out of "Ready", counted or not, with the last drop, the smallest drop and how many (for `shotDropRpm`). The screen shows the drop; the results file does not. It works out the gains as F = 32767 / top speed (counts/s), P = F / 10, I = P / 10, D = 0. This is a common starting point for REV hubs. `countsPerRev()` is 28 (the motor's own encoder, wheel on the motor shaft). Override it for a geared wheel. The output: ```java Flywheel.create(hardwareMap, "flywheel").countsPerRev(28.0).pidf(1.17, 0.117, 0, 11.70).maxRpm(5400) // top speed 6000 RPM; maxRpm = 90% of it // recovery after a shot at 3600 RPM: 0.38 s // tuned at 12.6 V: add .batteryCompensation(Hw.batteryReader(hardwareMap), 12.6) Tunables.Flywheel: kP = 1.17, kI = 0.117, kD = 0, kF = 11.70, nominalVolts = 12.6, shotIntervalSec = 0.45 ``` The `Tunables` line is for a [`Launcher`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/) module on that motor. Here the motor is named `flywheel`. The docs pages call it `launcher`, so their section is `Tunables.Launcher`. The line has `shotIntervalSec` only when the recovery is longer than the default 0.25 s. `nominalVolts` is the battery voltage during the top-speed test (the screen shows `Battery: 12.61 V (gains for 12.6 V)`). The gains are right for that voltage. The launcher's [battery compensation](https://crossbotics.com/ftc-helper/docs/modules/launcher/#battery-compensation) (off until you turn it on) scales F from it. Step 2 runs with that compensation, so an F you fine-tune there fits the same voltage. Under 11.5 V, the finder warns you to charge the battery first. ## FeedStopFinderOpMode `FeedStopFinderOpMode` finds a launcher's feed stop positions: `Tunables.Launcher: feedStopHold = ..., feedStopRelease = ...`. It needs `robot()` (the robot in five files, with a launcher that has `.feedStop(...)`). Tune and check adds it by itself. Steps: [Feed Stop Finder](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-stop-finder/). With both positions saved, it also finds the two times: `Tunables.Launcher: feedStopMoveSec = ..., feedStopOpenSec = ...`. - `feedStopMoveSec`: from the servo's catalog speed and the angle between hold and release, plus 25%, rounded up to 0.05 s. The 25% is there because the seller's speed is with no load. Only with the part in Robot.java: `.feedStop("feed_stop", "gobilda-2000-speed")`. - `feedStopOpenSec`: LB spins the wheel up to `speedRpm`, RB fires a test shot. The longest test shot plus 0.2 s, rounded up to 0.05 s. ### FeedTest `FeedTest` is the test shot (`robot.launcher.feedTest(hold, release, moveSec, backupSec)`). It uses the launcher's own feed: the stop opens, the indexer and the pushing parts run like a real shot. It is for the finder, not for TeleOp or autonomous code. | Method | What it does | | --- | --- | | `spin(on)` | spins the wheel up to `speedRpm`, or stops it (a shot on its way is canceled, the stop holds) | | `isSpinning()`, `isReady()` | the wheel is on; it is on and at speed | | `rpmNow()`, `targetRpm()` | the wheel's speed now; the speed it spins to (RPM) | | `fire()` | one test shot (only when ready and not busy) | | `update()` | runs the wheel, the stop, the indexer and the pushers: call it every loop | | `isBusy()` | a test shot is on its way, or it still watches for a second piece | | `lastSec()` | the last shot's time to the shot, seconds, counted like `feedStopOpenSec` (NaN: no shot seen) | | `lastEnd()` | `shot seen` or `backup time` | | `lastPieces()` | the speed drops in the last test shot: 1 is right, 2 or more = pieces slipped through | ```java FeedTest test = robot.launcher.feedTest(0.150, 0.550, 0.20, 3.0); test.spin(true); // every loop: test.update(); if (test.isReady() && !test.isBusy() && gamepad1.right_bumper) test.fire(); ``` ## FeedTimeFinderOpMode `FeedTimeFinderOpMode` finds how long a launcher's feeder must run per shot: `Tunables.Feeder: feedSec = ...`. It is for a feeder that runs for a time (`Indexer.crServo(...)` or `Indexer.motor(...)`) with no feed stop, pushing parts or feed wheel (`Launcher.hasTimedFeeder()`). It needs `robot()` (the robot in five files). Tune and check adds it by itself. Steps: [Feed Time Finder](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-time-finder/). LB spins the wheel up to `speedRpm`. RB fires a test shot: the feeder runs at its `power` until the wheel sees the shot (at most 3 s). X clears the times. It shows the shortest, average and longest time, and `feedSec` = the longest plus 0.1 s, rounded up to 0.05 s. Without `stopOnShot`, it warns when the times differ by more than 0.15 s. ```java @TeleOp(name = "Feed Time Finder", group = "Finders") public class FeedTimeFinder extends FeedTimeFinderOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` ### FeedTimeTest `FeedTimeTest` is the test shot (`robot.launcher.feedTimeTest(limitSec)`). It runs the launcher's own feeder. It is for the finder, not for TeleOp or autonomous code. | Method | What it does | | --- | --- | | `works()` | true for a launcher with a timed feeder that is on the robot | | `spin(on)` | spins the wheel up to `speedRpm`, or stops it (a test feed going on stops too) | | `isSpinning()`, `isReady()` | the wheel is on; it is on and at speed | | `rpmNow()`, `targetRpm()` | the wheel's speed now; the speed it spins to (RPM) | | `fire()` | one test shot (only when ready and not busy) | | `update()` | runs the wheel, and ends a test feed at the shot or the time limit: call it every loop | | `isBusy()` | a test feed runs | | `lastSec()` | the last test shot's time from the start of the feed to the shot, seconds (NaN: no shot seen) | | `lastEnd()` | `shot seen` or `time limit` | | `limitSec()` | the time limit of one test feed, seconds | | `feederSection()`, `feedSecNow()`, `stopsOnShot()` | the feeder's Tunables section, its `feedSec` now, its `stopOnShot` | ## DriveTunerOpMode Use it to find the wheel size and strafe correction for autonomous. It needs your robot. For the robot in five files, put this file next to `Robot.java`. An example is `lessonbot`'s [DriveTuner.java](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/lessonbot/DriveTuner.java): ```java @TeleOp(name = "Drive Tuner", group = "Finders") public class DriveTuner extends DriveTunerOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` For a robot with a `RobotSettings` class instead, write `@Override protected RobotConfig robotConfig() { return new RobotSettings(); }`. D-pad up/down chooses a test, and **A** starts it. D-pad left/right sets the power for the Drive and Strafe tests (0.3 to 1.0, starts at 0.5). A faster robot slides farther when it stops, so use the power of your autonomous moves. After you change the power, the tests must measure right again before the tuner shows `Tunables.Drive: calibrated = true`. The results file says which power the numbers fit. | Test | You do | It finds | | --- | --- | --- | | Push | roll the robot BY HAND exactly 48 in along a tape, then press **B** | the wheel size, from the counts. Every wheel must count up about the same. If not, it says so (a wrong motor direction or encoder cable) | | Drive | it drives 48 in. Measure, set the real distance (D-pad +/- 1 / 0.25 in), and press **A** | a corrected wheel size | | Strafe (mecanum) | it drives 48 in right. Measure, set it, and press **A** | a corrected strafe correction | | Strafe left (mecanum, if needed) | it drives 48 in left. Measure, set it, and press **A** | `strafeCorrectionLeft`, for a robot that slips differently to the left | | Turn | it turns 90 degrees left. Check it with a square | (the IMU's heading, to compare) | The Drive, Strafe and Turn tests WAIT while the robot moves, like autonomous. STOP still works. The tuner does not measure a move that ends STALLED or TIMED_OUT: clear the path and run it again. GUIDE (or the gamepad's START button) stops a moving test at once and opens help. The tuner does not measure that test either. The tuner uses each new number at once, with no rebuild. Run Drive and Strafe again until they measure 48, then copy the lines into your code. `testDistanceIn()` changes the 48. The output: ```java c.wheelDiameterIn = 3.812; // RobotSettings.auto() Robot.java: .wheelMm(96.8) // in the drive(...) line c.strafeCorrection = 1.180; // RobotSettings.auto() Tunables.Drive: strafeCorrection = 1.180 // measured at power 0.6: these numbers fit autonomous moves at that power ``` In five files, the wheel size goes in the drive line of `Robot.java` (`.wheelMm(96.8)`, in millimeters). The strafe correction goes in `Tunables.Drive`. When the Drive test (and on a mecanum the Strafe test) measures 48 within 0.5 in, the tuner shows `Tunables.Drive: calibrated = true`. You copy that line into `Tunables.java` yourself. Autonomous does not run until it is true. ## OdometryTunerOpMode Use it to check which way each odometry pod counts and to measure where each pod sits (the offsets). A pod is a dead wheel: an unpowered wheel with an encoder. The tuner needs your robot in five files, with an `odometry(...)` line ([odometry](https://crossbotics.com/ftc-helper/docs/modules/odometry/)). Put this file next to `Robot.java`. An example is the odometry robot's [OdometryTuner.java](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/odometrybot/OdometryTuner.java): ```java @TeleOp(name = "Odometry Tuner", group = "Finders") public class OdometryTuner extends OdometryTunerOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` In every test, the sticks drive slowly (30%). D-pad up/down chooses a test. **A** starts it and sets the pose (the robot's x, y and heading) to 0, 0, 0. **B** ends it and shows the result. | Test | You do | It finds | | --- | --- | --- | | 1 Forward 48 in | push or drive 48 in straight forward along a tape | the forward pod's direction, and how far off the distance is. For an OTOS: `linearScalar` | | 2 Left 24 in | push or drive 24 in to the left | the sideways pod's direction | | 3 Spin 3+ turns | turn in place at least 3 times | the offsets (Pinpoint), `trackWidthIn` + `perpForwardIn` (three wheels), `parallelLeftIn` + `perpForwardIn` (two). Not for an OTOS | | 4 Loop and back | from a tape mark, drive anywhere and back onto it | `checked = true` when it ends within 1 in and 2 degrees | The Spin test divides each pod's roll by the turn. It measures the turn with the Pinpoint's own heading, or with the Control Hub's IMU for dead wheels. The Pinpoint's heading is not wrapped: it keeps counting past 360 degrees. The test prints only the numbers to change (for dead wheels: `.trackWidthIn(..).perpForwardIn(..)` or `.parallelLeftIn(..).perpForwardIn(..)`). So `.reversed(...)` and the pod type stay as you wrote them. The output: ```java Robot.java: in the odometry(...) line, .offsetsMm(-84.2, -167.5) Tunables.Odometry: linearScalar = 1.012 // times the one in use now (OTOS only) Tunables.Odometry: checked = true ``` For a reversed pod, the result says which name to add to (or take out of) `.reversed(...)`. While a test runs, the screen shows the pose and the raw pod counts since the test began. Walk-through: [finders guide](https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/). ## MoveTunerOpMode Use it after the Drive Tuner, to see how exactly autonomous moves stop and turns end. It suggests the numbers in `Tunables.Drive` and uses each new number at once. It needs your robot and `Tunables.Drive.calibrated = true`. The **Tune and check** menu has it. For your own file, put this next to `Robot.java`: ```java @TeleOp(name = "Move Tuner", group = "Finders") public class MoveTuner extends MoveTunerOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` For a robot with a `RobotSettings` class instead, write `@Override protected RobotConfig robotConfig() { return new RobotSettings(); }`. D-pad up/down chooses a test, and **A** starts it. D-pad left/right sets the power of the moves and turns (0.3 to 1.0, starts at 0.5). Use the power of your autonomous moves: a faster robot slides farther. With an `odometry(...)` line, the tuner measures with the odometry. The odometry sees a wheel that skids. Without it, the tuner measures with the wheel counts. | Test | It does | It finds | | --- | --- | --- | | 1 Creep | raises the power slowly until the robot rolls (forward, then right on a mecanum) | `moveMinPower`: that power x 1.3, at least 0.10 | | 2 Stops | moves of 6, 12 and 24 in, out and back, with `slowDownIn` 0, 3, 6, 9 and 12, until every move slides 0.5 in or less past its end | `slowDownIn`: the smallest that is good (or the best one) | | 3 Turns | turns 90, 135 and 45 degrees left and back | one change per round: `turnMinPower` (0.05, 0.08, 0.11), then `turnKp`, when it stops off target; `turnToleranceDeg` + 0.5 when it rocks a little outside it; `turnKd` or less `turnKp` when it swings past; `turnKp` when it is slow | | 4 Drift | 48 in forward and back (and right and left) | how much the heading changes on a straight move. A report, nothing to copy | | 5 Move and turn (mecanum) | 24 in sideways while it turns 90 degrees (`moveWithTurn`), four times | `moveTurnScale` or `moveMaxTurnPower` | Each move and turn WAITS while the robot moves, like autonomous. STOP still works. GUIDE (or the gamepad's START button) stops a test at once and opens help. The tuner does not use that test's numbers. Between the moves, nothing waits: the tuner waits for the robot to stand still loop by loop, then measures. Run a test again until it says OK, then copy the lines. The output: ```java c.slowDownIn = 6; // RobotSettings.auto() Tunables.Drive: slowDownIn = 6 c.turnKd = 0.0039; // RobotSettings.auto() Tunables.Drive: turnKd = 0.0039 // measured at power 0.6: these numbers fit autonomous moves at that power ``` ## AimTunerOpMode Use it to find the camera offset, so shots go in the middle. The offset is where the target sits in the camera's view when the LAUNCHER points straight at it (degrees, left = +). Fill in these methods: | Method | Required? | What it gives | | --- | --- | --- | | `createCamera()` | yes | your camera | | `createTurret()` / `cameraOnTurret()` | no | aim with a turret (default: turn the robot) | | `robotConfig()` | without a turret | to turn the robot, and to drive | | `createAimController()` | no | the aiming gains (use your TeleOp's) | | `createLauncher()`, `shotRpm()` | no | for test shots (with a table, it uses the camera's distance) | | `startOffsetDeg()` | no | the offset in your code now | | Button | Does | | --- | --- | | hold **A** | aim at the target | | D-pad right/left, up/down | aim 0.5 / 2 degrees more right / left. **When shots go left of the middle, press RIGHT.** | | **RB** / **LB** | shoot one / flywheel off | | **X** | home the turret. A turret with a home switch does not aim before it is homed (`homeDirection()`, default -1) | | sticks | drive when not aiming | A camera to the SIDE of the launcher sees the target from a different angle at each distance. So it needs a different offset at each distance. When the offset that works changes with distance, move the camera onto the launcher's line. Or tune at the distance you shoot from most. The output is `new AimController(...).offset(-1.5)` or `turret.cameraOffset(-1.5)`. With a turret, it also gives `Tunables.Turret: cameraOffset = -1.5` (the section is the turret motor's name). --- ## ShotTunerOpMode Use it to build the shot table: the speed (and hood angle) for each distance. For the robot in five files, it needs one method. An example is the turret robot's [ShotTuner.java](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/turretbot/ShotTuner.java): ```java @TeleOp(name = "Shot Tuner", group = "Finders") public class ShotTuner extends ShotTunerOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` At INIT, it sets the robot up. It uses the robot's first `Launcher` (with its numbers from `Tunables.java`), its first `Camera`, its odometry and its drive. Every button is on gamepad 1. **The way it tunes:** at each distance, shoot 3-5 pieces at one speed, and mark each shot HIT (A) or MISS (B). Then try another speed. X saves the speed with the best hit ratio (hits out of shots) at that distance. **The distance** is an average over the last half second of fresh readings. It comes from the camera. When the camera does not see the goal, it comes from the odometry (with an `odometry(...)` line and `Tunables.Aim.goalX, goalY`). For the odometry, the robot starts at `startSpotIn()`, by default the middle of the field facing away from you (see [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). With neither, you set the distance by hand. The screen says which one it uses. When it has both, it shows both. When they are far apart, move the goal point. **Several tables** (`speedByDistancePollen`, `speedByDistanceNectar`): press Y until `> Table`, then D-pad left/right picks the one you tune. It starts on the launcher's start table. Each table keeps its own points and gets its own line. The tuner sets up the robot's other parts but does not move them. A turret stays still. The launcher's `requireReady(...)` checks (like "turret aimed") are off. A robot with whole-robot aim (a camera with `goal(...)`, no following turret) aims like TeleOp instead: the alliance chosen in INIT (X / B), the camera's lighting test in INIT (hold Y 0.5 s for it again), and RB turns to the goal with `robot.aim()` and shoots once aimed and Ready (`AIM_TIMEOUT_SEC` not aimed, or no goal: no shot). Without five files, fill in these methods: | Method | Required? | What it gives | | --- | --- | --- | | `robot()` | no | the robot in five files: gives the three below | | `createLauncher()` | without `robot()` | your [`Launcher`](https://crossbotics.com/ftc-helper/docs/modules/launcher/), as in TeleOp (with a hood, it tunes the hood too) | | `createCamera()` | no | the camera gives the distance; null = set the distance by hand | | `findTarget(camera)` | no | which target to use. Default: the robot's goal (`robot.aim().goal()`, this alliance's) with a goal camera, else the first one with a distance | | `robotConfig()` | no | lets you drive with the sticks between distances | | `createSubsystems()` | no | other mechanisms to keep updated (an intake that loads it) | | `startRpm()` | no | the starting speed; default (NaN) = the table's speed at the distance seen, else `Tunables.Launcher.speedRpm`, else 3000 | | `startHoodDeg()` | no | the starting hood angle; default (NaN) = the table's hood at the distance seen (until you change it), else the robot hood's `startAngle`, else 0 | | `startSpotIn()` | no | where the robot is at INIT, for the odometry: {x, y, heading} from your drivers' wall; default {0, 0, 0} | | `tableNames()` | no | the tables to tune; default the launcher's (`pollen`, `nectar`...), or one table `main` | | Button | Does | | --- | --- | | **Y** | what the D-pad changes: SPEED, HOOD (with a hood), DISTANCE (no camera, no odometry), TABLE (two or more tables) | | D-pad up/down, right/left | big / small step (100 / 10 RPM; the hood: a fifth / a fiftieth of its range, 5 / 0.5 deg for 0-25 deg; 6 / 1 in) | | **LB** | flywheel on/off (it is OFF at ▶) | | **RB** / hold **RT** | shoot one / keep shooting (let go to stop). Keep shooting also stops after a jam or a "gave up": press RT again to go on | | **A** / **B** | the oldest shot not marked yet was a HIT / a MISS (at the speed, hood angle and distance it was fired with) | | left stick click | undo the last HIT / MISS: that shot waits to be marked again | | right stick click | drop the last shot not marked yet (a "shot" with no piece: the wheel dipped by itself) | | **X** | save the speed with the best hit ratio at this distance. It replaces a saved point within 1 in. With no shots marked, it saves the speed now | | hold **BACK** 1 s | delete the saved point here. It needs a hold, so nobody deletes it by mistake | | sticks, left trigger | drive, slow (with `robotConfig()`) | The speed stays at or below the flywheel's `maxRpm`, and the hood stays inside its limits. A warning shows when the D-pad reaches one. So a saved point is what the robot tested. The screen shows: - the target and measured speed, and whether it is ready (or why not) - the shots fired, and how many are still to mark - `Hits at 2550: 3/4`, and every speed tried at this spot - every table's point count (`Points: POLLEN 3, NECTAR 0 (4-6 per table)`) - the recovery time, the distance and bearing, and the saved points. The tuner never uses the launcher's speed trim, because the table holds the real speeds. The launcher's battery compensation stays on. Each shot keeps the flywheel speed **measured** when the piece was fed. When that speed is more than `sagLimitRpm` under the speed asked for, the tuner flags the shot "sagged". `sagLimitRpm` is 60 RPM or 3% of the speed asked for, whichever is larger. A sagged shot means that the wheel had not got back to speed after the last shot, or that the battery is low. With a hood, each speed and hood angle is its own try. X saves the winner with the hood angle it was fired with. The hit counts start again after a save, on another table, and when the distance moves more than `SPOT_MOVE_IN` (4 in). The tuner drops shots fired at the old spot that are not marked. The output: ```java new ShotTable() .add(24.0, 2600, 6.0) // 4/5 in, measured 2588 RPM .add(48.5, 3100, 14.0) // 3/4 in, measured 3079 RPM .add(72.0, 3700, 21.0) // 4/4 in, measured 3672 RPM ``` It also shows the line for five files, one per table, in the launcher's section. With a hood, each row has the hood as its third number, in the hood's scale (degrees, or a servo position): ```java public static double[][] speedByDistance = {{24, 2600}, {48.5, 3100}, {72, 3700}}; // in Tunables.Launcher public static double[][] speedByDistanceNectar = {{24, 2800, 4}, {48.5, 3300, 12.5}}; // a named table, with a hood ``` Copy each line into `Tunables.java`, in place of the line with the same name. The robot reads the file, not this screen. At STOP, the tuner also saves the lines on the Control Hub. The screen says what to do next (`Next: LB to spin up the flywheel.`). ## CameraFixCheckOpMode `CameraFixCheckOpMode` (**alpha**) is the standing test for the [camera fix](https://crossbotics.com/ftc-helper/docs/modules/odometry/#camera-fix-alpha). It finds `Tunables.CameraFix` `turnDegBlue` / `turnDegRed`. It also shows where the camera puts the robot, so you can check it with a tape. It needs `robot()`. Tune and check has it for a robot with `cameraFix(camera)`. ## PieceTunerOpMode Use it to see what each game-piece sensor reads, and to measure each kind's color (or size) and the "empty" line. It needs your robot in five files, with a [`Pieces` or `PieceSensor`](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/) line. Put this file next to `Robot.java`: ```java @TeleOp(name = "Piece Tuner", group = "Finders") public class PieceTuner extends PieceTunerOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` Nothing moves. - **D-pad up/down** chooses the sensor. - **D-pad left/right** chooses what is in front of it: each kind, then EMPTY. - **A** measures it: 20 readings, about half a second. Hold the piece still, where it sits on the robot. - **B** forgets that sensor's measurements. The screen shows the live reading and the kind the sensor sees now. The reading is the hue (the color, as an angle in degrees), the saturation (how strong the color is) and the distance. Until a kind's line is in `Tunables.java`, the sensor reads that kind as `UNKNOWN`. Measure every kind and EMPTY. The lines to copy: ```java Tunables.IntakeColor: POLLEN = 74 // its color (hue, degrees) Tunables.IntakeColor: RED_NECTAR = 6 // its color (hue, degrees) Tunables.IntakeColor: hueTolerance = 34 Tunables.IntakeColor: nearMm = 52 // a piece is there below this ``` The tuner warns when two kinds read too close together (under 15 degrees, or 10 mm for a distance sensor). It also warns when EMPTY looks like a piece. Then aim a distance sensor at a far wall, or put a gray background behind a camera's spot. Copy the lines into `Tunables.java` and rebuild. A value changed only in the tuning menu and saved there (**A**) stays on this hub, and it wins over a later edit in `Tunables.java`. After you copy it into `Tunables.java`, put the menu back to the code values (**Y**). ## CharacterizerOpMode Use it to measure how the real robot moves. This is called **characterizing** the robot. The numbers have two uses. In your code, they give **feedforward** (the power a motor needs for a speed, see [Feedforward](https://crossbotics.com/ftc-helper/docs/modules/control/#feedforward)). In the simulator, they are the **real numbers** in its robot file. It needs `robotConfig()`, and `mechanisms()` for lifts, arms and flywheels: ```java @TeleOp(name = "Characterizer", group = "Finders") public class Characterizer extends CharacterizerOpMode { protected RobotConfig robotConfig() { return new RobotSettings(); } protected List mechanisms() { return Arrays.asList(Mechanism.lift("lift", 0, 2600), // soft limits: counts from the bottom Mechanism.lift("arm", 0, 1100), Mechanism.flywheel("flywheel")); } } ``` The D-pad chooses a test, **A** runs it, and **B** stops it at once. | Test | It does | Space and safety | | --- | --- | --- | | Drive | power ramps up slowly forward (to 0.4) and back, then quick steps (0.5, 0.6 s) | about 5 ft clear in front and behind. Each roll ends at `maxDriveCounts()` (default 2500 counts: about 5 ft with 312 rpm motors and 104 mm wheels, 4.6 ft with 96 mm wheels). `driveRampMax()` (at most 0.5) lowers the speed | | Turn (needs the IMU) | the same, turning in place | room to turn | | Lift/arm | slowly up to 60% of its range, slowly down, quick steps up and down, then back to the bottom | start it at the BOTTOM, because the soft limits (the limits in your code) count from there. It stops and says why when it goes past them. Add `.reversed()` when positive power moves it down | | Flywheel | ramps up to full power, coasts, full power, coasts | keep hands and pieces away | The Characterizer stops itself and says why when: - a wheel or motor turns the wrong way for its power (a direction setting is wrong; it checks each wheel) - a lift goes past a soft limit, or counts down while it goes up - something pushes but does not move for 0.7 s (jammed, against a hard stop, or an encoder cable in another motor's port) - someone presses GUIDE or the gamepad's START. A drive roll that reaches `maxDriveCounts()` ends early, and the test goes on with the next part. What each part of a test measures: - A slow ramp: the power needed to start moving (kS) and the power per speed (kV). - A quick step: the power for speeding up (kA). Spinning wheels spoil this number, so run the drive test on tiles, not on a smooth floor. - A lift: also the power that holds it against gravity (kG). - A flywheel's coasting: how long it takes to slow down. The results (the Characterizer saves them with the other finders' results): ```text # simulator robot file: drive.kS = 0.052 drive.maxTicksPerSec = 2776 drive.accelSec = 0.176 Feedforward driveFf = new Feedforward(0.05230, 0.0003602, 6.329e-05); // wheels, counts per second drive.turnDegPerCount = 0.08012 # add to motor.lift in the robot file: kS=0.041, maxTicksPerSec=2792, accelSec=0.087, gravity=0.060 ``` The Characterizer saves each test's log in the results folder as `characterizer/[-]-.csv` (for example `lift-lift-20261021-101500.csv`). A test stopped early saves its log too, marked "(stopped early)". The simulator's fit tool reads the logs and writes the robot file for you (`./gradlew :sim:fit -Plog=... -Pwrite`, see the [simulator guide](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/#6-real-speeds-optional)). Run each test 2-3 times on a charged battery. The fit tool fits the logs of the same test together. It also gives r2, a score from 0 to 1 for how well the numbers match the measurements. Below 0.9 it says "poor: run it again"; below 0.5 it says "Could not fit". The Characterizer measures arms like lifts: it takes the pull of gravity as the same at every angle. So the numbers are a middle value for an arm. **For an arm, set the high limit below straight up**, so gravity always pulls it back down. Past straight up, gravity pulls it on to the far side, and a motor's brake does not hold a heavy arm. ## CharacterizeMath The fitting math, with no hardware. `fit(t, volts, power, speed, gravity)` gives kS, kV, kA (and kG) and r2. It uses least squares (it finds the numbers with the smallest total error) over the moments when the motor was moving and powered. It smooths the speeds over 30 ms on each side, or over 2.5 loops on a slower loop. It leaves out the moments within that window plus 20 ms of a jump in power. The other methods: `coastSec(...)`, `turnDegPerCount(...)`, `yawRates(...)`, `accelerations(...)`, `smoothed(...)`, `leastSquares(...)`. It scales the powers to 12.8 V with the logged battery voltage. ## FinderOpMode To write your own finder, extend `FinderOpMode`. It is the shared frame of every finder. INIT: `setup()`, `showInit()`. The loop: `bind()` once, then `step()` and `show()` every loop, plus the results. The end: `stopAll()`, always. When the finder stops, it saves the results to the file, and the screen says whether that worked. `runOpMode()` is `final`. | Field / method | What it is | | --- | --- | | `t` | the [RobotTelemetry](https://crossbotics.com/ftc-helper/docs/modules/telemetry/) | | `results` | the [FinderResults](#finderresults) | | `finderName()`, `setup()`, `bind(controls)`, `step()`, `show(t)`, `stopAll()` | fill these in | | `helpLines()` | optional, but please write it: the help page, at most 13 lines of about 50 characters. Default: "No help page for this finder yet." | | `showInit(t)` | optional: what INIT shows | | `pause()` | optional: what stops while help is open (default `stopAll()`). Override it when `stopAll()` also closes a camera | | `inputsReady()` | false after ▶ and after help, until gamepad 1 was let go. Check it before you act on a stick, trigger or held button that you read directly | | `openHelp()` | opens the help page (for example, when a help key stopped a test) | | `helpKeyDown()` | whether the gamepad's GUIDE or START is down (for example, as a stop condition for a moving test) | The gamepad's GUIDE and START are the help keys in every finder, so a finder must not bind them itself. ## FinderResults | Method | What it does | | --- | --- | | `set(key, line)` | sets or replaces the line with this key | | `remove(key)`, `removeStartingWith(start)` | removes lines | | `lines()`, `isEmpty()` | read the lines | | `addTelemetry(t)` | shows them under "Copy into your code" | | `saveNow()` | adds them to `/sdcard/FIRST/ftc-helper/finder-results.txt` now (FinderOpMode does this at STOP and shows the result) | | `saveInBackground(ok -> ...)` | the same on a background thread | | `FinderResults.num(value, decimals)` | a number as text, always with "." | | `FinderResults.tunablesLine(deviceName, fields)` | a line for five files: `tunablesLine("lift", Arrays.asList("min = 0", "max = 2580"))` gives `Tunables.Lift: min = 0, max = 2580` | ## FinderMath `flywheelPidf(topTicksPerSec)`, `ticksPerSecToRpm(ticksPerSec, countsPerRev)`, `wheelDiameterFromPush(ticks, inches, ticksPerRev, gearRatio)`, `correctedDiameter(old, asked, measured)`, `correctedStrafe(old, asked, measured)`, `limits(lowEndTicks, highEndTicks)` (-> min, max, reversed), `pushTicks(deltas)` (the push test's count, NaN when the wheels disagree), `servoPosition(p)` (kept in 0..1). ## Chooser A D-pad list: `new Chooser(names)` (sorted A to Z), `next()`, `previous()`, `current()`, `select(name)` (choose that name; false when it is not in the list), `isEmpty()`, `addTelemetry(t, emptyText)`. ## NudgeStep The step size that the servo finders (Servo, Feed Stop, Hood) nudge by. D-pad up/down moves the servo by the step, and D-pad left/right makes the step smaller / bigger. The sizes (`NudgeStep.SIZES`) are 0.1, 0.05, 0.01, 0.005 and 0.001. It starts at 0.05. A big step gets close fast. The smallest step finds an exact spot: 0.001 is about a quarter of a degree on a 270 degree servo. | Method | Does | | --- | --- | | `size()` | the step now | | `smaller()` / `bigger()` | the next step size (stops at the ends of the list) | | `reset()` | back to 0.05 | | `move(position, direction)` | the position one step up (`+1`) or down (`-1`), rounded to 0.001, kept in 0..1 | | `label()` | the step as text, for example `"0.005"` | ```java NudgeStep step = new NudgeStep(); // 0.05 step.smaller(); // 0.01 double p = step.move(0.500, +1); // 0.510 ``` ## ShotPoints The shot tuner's saved points. Make it with `new ShotPoints(hasHood)`, or with `new ShotPoints(hasHood, hoodDecimals)`: 1 for degrees, 3 for servo positions, 0 for ticks. `save(distance, rpm, hoodDeg)` replaces a point within `SAME_DISTANCE` = 1. The other methods: `removeNear(distance)`, `points()` (sorted by distance, shortest first), `codeLines()` (the `ShotTable` code), and `tunablesLine(section)`. That gives the five-files line, `public static double[][] speedByDistance = {{48, 2550}, ...}; // in Tunables.Launcher`, or with a hood `{{48, 2550, 12.5}, ...}`. It is empty when nothing is saved. `tunablesLine(section, field)` does the same for a named table, for example `speedByDistanceNectar`. `save(distance, rpm, hoodDeg, measuredRpm, hits, shots)` also keeps how many went in and the measured speed (`saved()`, `size()`, `note(saved)`; `codeLines()` writes them as a comment). `ShotPoints.Tally` counts hits and shots per try at one spot. A try is a speed (and a hood angle, with a hood). Its methods: `mark(rpm, hit, measuredRpm)`, `mark(rpm, hoodDeg, hit, measuredRpm)`, `unmark(...)` (an undo), `hits(rpm)` / `hits(rpm, hoodDeg)`, `shots(...)`, `totalShots()`, `measuredRpm(...)`, `best()` ({rpm, hood}, null with no hit), `bestRpm()` (the best hit ratio; on a tie, more shots wins, then the lower speed; NaN with no hit), `tries()`, `summary()` (`2450: 1/3, 2550: 3/4 (best)`; with a hood `2550 @ hood 10: 3/4`), `spotIn()`, `setSpot(in)`, `isEmpty()`, `clear()`. `ShotPoints.Trials` holds the shots at one spot that wait to be marked. Each shot keeps the speed, hood and distance it was fired with. Its methods: `fired(rpm, hoodDeg, measuredRpm, distanceIn)`, `mark(hit)` (the oldest waiting shot), `undo()` (the last mark; that shot waits again), `dropLast()` (the newest waiting shot), `check(distanceIn)` (when the distance moved more than `SPOT_MOVE_IN`, marks start again and old shots are dropped), `unmarkedCount()`, `tally()`, `clear()`. Each one returns the words the tuner shows. `ShotPoints.DistanceAverage` averages the distance over the last `WINDOW_SEC` (0.5 s) of fresh readings. Its methods: `add(nowSec, distance, from)` (a different `from` starts the average again), `average(nowSec)` (NaN with no readings), `count(nowSec)`, `source()`. --- # Gamepad module URL: https://crossbotics.com/ftc-helper/docs/modules/gamepad/ Learn it hands-on: [03 Buttons](https://crossbotics.com/ftc-helper/docs/tutorials/03-buttons/), [11 Driver assists](https://crossbotics.com/ftc-helper/docs/tutorials/11-driver-assists/). Turns gamepad buttons, sticks and triggers into robot actions, and gives the driver feedback by rumble (vibration). Use it in a TeleOp you write yourself, or in [`EasyTeleOp`](https://crossbotics.com/ftc-helper/docs/modules/teleop/)'s `bindButtons`. With the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/controls/#controlmap), `Controls.java` does this job in a shorter way. If you are new to buttons, start with tutorial 03. | Class | Use it to | | --- | --- | | [`ControllerBindings`](#controllerbindings) | say what each button does, in one place | | [`StickShaping`](#stickshaping) | make sticks feel smooth: ignore tiny stick moves, add a curve, slow down with a trigger | | [`ToggleRumble`](#togglerumble) | buzz to confirm a toggle (2 buzzes = ON, 1 = OFF). In `Controls.java`: `.rumble()` ([Controls](https://crossbotics.com/ftc-helper/docs/controls/)) | | [`AimRumble`](#aimrumble) | buzz when an error is small, for example "aimed at the target" | | [`ButtonNames`](#buttonnames) | write the button names printed on each driver's controller (A or ×) on the screen | --- ## ControllerBindings ### Why A button action must run once per press, not 50 times per second. Without `ControllerBindings`, every button needs code like this: ```java boolean aWasDown = false; // was A down last loop? ... if (gamepad2.a && !aWasDown) claw.setPosition(OPEN); // down now, up before = a new press aWasDown = gamepad2.a; // remember for the next loop ``` With `ControllerBindings`, you write each button's job once, at the top, and the class does the rest: ```java // in INIT, once: gamepad 2's A opens the claw, once per press ControllerBindings controls = new ControllerBindings() .bindPress(Pad.G2, Btn.A, () -> claw.setPosition(OPEN)); ... controls.update(gamepad1, gamepad2); // every loop ``` All of a robot's buttons are in one list. So you can see what each button does, and you can spot two jobs on one button. ### Names - `Pad.G1` = `gamepad1` (usually the driver). `Pad.G2` = `gamepad2` (usually the operator). - `Btn`: `A`, `B`, `X`, `Y`, `LB`, `RB` (bumpers), `BACK`, `START`, `GUIDE`, `L_STICK_BTN`, `R_STICK_BTN` (stick clicks), `DPAD_UP`, `DPAD_DOWN`, `DPAD_LEFT`, `DPAD_RIGHT`, `TOUCHPAD`, `M1`, `M2` (extra paddles, see below). - `Trigger.LT`, `Trigger.RT` = left and right trigger. Add these imports to use the short names: ```java import com.crossbotics.ftchelper.gamepad.ControllerBindings; import com.crossbotics.ftchelper.gamepad.ControllerBindings.Btn; import com.crossbotics.ftchelper.gamepad.ControllerBindings.Pad; import com.crossbotics.ftchelper.gamepad.ControllerBindings.Trigger; ``` ### The `() -> ...` part `() -> claw.setPosition(OPEN)` is a **lambda**: a small piece of code that you hand over to run later. For more than one line, use braces: ```java .bindPress(Pad.G2, Btn.B, () -> { claw.setPosition(OPEN); liftTarget = 0; // only sets the target: the loop moves the lift, the button never waits }) ``` To change a variable inside a lambda, make it a field of your OpMode class. A local variable inside `runOpMode` does not work. ### Methods Every `bind...` method gives back the same `ControllerBindings`, so you can chain them. | Method | Runs the action... | | --- | --- | | `bindPress(pad, btn, action)` | once, when the button goes down | | `bindRelease(pad, btn, action)` | once, when the button comes up | | `bindHold(pad, btn, action)` | every loop while the button is down | | `bindToggle(pad, btn, onAction, offAction)` | each press flips ON/OFF. It starts OFF. Either action may be `null`. | | `bindTriggerPress(pad, trigger, action)` | once, when the trigger goes past the threshold (how far you must pull it, default halfway) | | `bindTriggerHold(pad, trigger, action)` | every loop while the trigger is past the threshold | | `bindTriggerRelease(pad, trigger, action)` | once, when the trigger comes back under the threshold | | `bindTriggerToggle(pad, trigger, onEnable, onDisable)` | each pull flips on / off | | `bindTriggerAxis(pad, trigger, use)` | every loop, with the trigger's value 0 to 1. For example: `v -> intake.setPower(v)` | | `setTriggerThreshold(value)` | how far you must pull a trigger for it to count as pressed. Default 0.5. | | `registerExtraButton(pad, btn, reader)` | for controllers with extra paddles. `btn` must be `M1` or `M2`. `reader` tells the class how to read the paddle. | | Method | What it does | | --- | --- | | `update(gamepad1, gamepad2)` | **Call once every loop.** Reads the gamepads and runs the actions. | | `ignoreHeldButtons(gamepad1, gamepad2)` | Call it once, right after `waitForStart()`. It stops surprises at the start: a button or trigger held down through ▶ (start on the Driver Hub) does NOTHING (press, release, hold or toggle) until the driver lets go of it once. `bindTriggerAxis` still works. | | `releaseAll()` | Acts as if the driver let go of every button and trigger. "Release" actions run for held buttons, and `bindTriggerAxis` code gets 0. Call it before you stop calling `update()` for a while (for example, while a menu uses the gamepad). Call `ignoreHeldButtons` when you start again. | | `isDown(pad, btn)` | Whether the button was down at the last `update`. | | `getSlowActionWarning()` | "", or a note that a button job took more than 20 ms because it waited or slept, like `G2:A button job took 40 ms: the whole robot stopped that long. ...`. It goes away 5 s after the last slow action. Show it with `t.warn(...)`. See [Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/). | | `clear()` | Removes all bindings. | ### Rules - **Several actions can share a button.** They run in the order you added them. Example: `bindPress` and `bindHold` on the same button both work. - **Actions must be quick.** The whole robot freezes while an action waits. So never use `sleep()` or a waiting loop inside an action. Set a variable or a target instead, and let your loop do the work. - A trigger and the bumper above it are separate. `bindTriggerPress(G1, RT, ...)` does not fire on `RB`. ### Tip: the SDK also has edge checks FTC SDK 11 added `gamepad1.aWasPressed()`, `aWasReleased()` and so on. They work well for one or two buttons. `ControllerBindings` is better when you have many buttons, toggles, or two actions on one button. It also keeps the whole button map in one place. --- ## StickShaping ### `StickShaping.shape(value, deadband, exponent)` The usual one-line stick setup. First it applies a **deadband**: a stick that is only a tiny bit off the middle counts as 0, and power starts smoothly from there. Then it applies a curve, for fine control at low speed. ```java double forward = StickShaping.shape(-gamepad1.left_stick_y, 0.05, 2); // minus: stick UP is negative ``` | Parameter | Meaning | | --- | --- | | `value` | the stick, -1 to 1 | | `deadband` | values smaller than this become 0, so the robot does not creep when a stick rests at 0.02. 0.05 is usual. | | `exponent` | 1 = straight (no curve). 2 = "squared": half stick gives quarter power, for fine control. 3 = softer still. | ### `StickShaping.curve(value, exponent)` Only the curve part. It keeps the sign: -0.5 squared gives -0.25. ### `StickShaping.slowScale(trigger, slowest)` Turns a trigger into a speed multiplier. This is last season's "trigger brake". ```java double speed = StickShaping.slowScale(gamepad1.left_trigger, 0.25); // 1.0 down to 0.25 drive.drive(forward, strafe, turn, speed); // every wheel power is multiplied by speed ``` A trigger not pressed gives 1.0 (full speed). Fully pressed, it gives `slowest` (0.25 = quarter speed). Half pressed, it gives a number in between (0.625). --- ## ToggleRumble Two quick buzzes mean ON, and one means OFF. So the driver knows a mode changed without looking. ```java ToggleRumble confirm = new ToggleRumble(gamepad1); // bindToggle(pad, button, code run when it turns ON, code run when it turns OFF) controls.bindToggle(Pad.G1, Btn.Y, () -> { slowMode = true; confirm.play(true); }, () -> { slowMode = false; confirm.play(false); }); ``` | Method | What it does | | --- | --- | | `new ToggleRumble(gamepad)` | the gamepad to buzz | | `setPattern(strength, stepMs, gapMs)` | the feel. Defaults: 0.8, 120 ms buzz, 80 ms gap. | | `play(on)` | `true` = two buzzes, `false` = one buzz. A new buzz replaces one that is still playing. | | `isPlaying()` | whether it still buzzes. Use it to hold back other rumble (see below). | --- ## AimRumble Buzzes when an error is inside a threshold. The closer the error is to zero, the stronger and longer the buzzes. Last season it told the driver "you are aimed at the goal". Its old name was `RumbleNotifier`. ```java AimRumble aimFeel = new AimRumble(gamepad1).setThreshold(2.5); ... // every loop (but not while the toggle buzz plays, so the driver can tell them apart): if (!confirm.isPlaying()) aimFeel.update(headingErrorDeg); ``` | Method | What it does | | --- | --- | | `new AimRumble(gamepad)` | the gamepad to buzz | | `setThreshold(value)` | buzzing starts when the error is this small. Default 2.5. | | `setFeel(minStrength, maxStrength, minPulseMs, maxPulseMs, minCooldownMs, maxCooldownMs)` | It uses the "min" values at the edge of the threshold, and the "max" values at zero error. Defaults: 0.10, 0.65, 120, 200, 120, 350. The cooldown is the time from the start of one buzz to the start of the next. So at the edge (120 ms buzz, 120 ms cooldown), the buzzes run together. | | `setEnabled(on)` / `isEnabled()` | turn buzzing on or off (for a driver who does not want it) | | `update(error)` | call it every loop. It gives true when it started a buzz. `NaN` (no target) does nothing. | In the robot in five files, it is one line in `Controls.java`: `g2.rumbleWhenAimed();`. The error is the turret's aim or the whole robot's aim. On a robot with no turret and the aim off, it is the camera's bearing to the goal while the driver turns by hand. See [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/). --- ## ButtonNames A student with a PlayStation controller has no button called "A". And "START" on a screen could mean the Driver Hub's ▶ or the small START button on the gamepad. So the library's screens write each button as a short mark. These screens are the finders, Tune and check, the Hardware Check, the TeleOp button map and the tuning menu. Right before the library sends the screen, `ButtonNames` turns each mark into the name printed on the controller in use. Once a controller is linked, the FTC SDK says which kind it is (`gamepad.type`). | Mark | Logitech / Xbox (and before a controller is linked) | PlayStation (PS4, PS5, Etpark) | | --- | --- | --- | | `{A}` `{B}` `{X}` `{Y}` | A B X Y | × ○ □ △ | | `{LB}` `{RB}` `{LT}` `{RT}` | LB RB LT RT | L1 R1 L2 R2 | | `{BACK}` `{START}` `{GUIDE}` | BACK START GUIDE | SHARE OPTIONS PS | | `{2:A}` (any button) | gamepad 2's button, by gamepad 2's own kind | - | | `{PLAY}` | ▶, the Driver Hub's start button (never a gamepad button) | ▶ | A generated line such as `G2 RT: intake in` needs no marks. `ButtonNames` also changes a button name after "G1 " or "G2 " (`G2 R2: intake in`). ```java // In your own OpMode (the library's OpModes do this by themselves): ButtonNames.watch(gamepad1, gamepad2); RobotTelemetry t = new RobotTelemetry(telemetry); t.text("{A} = score high, {B} = stop"); // "× = score high, ○ = stop" on a PS controller t.update(); // RobotTelemetry turns the marks into names ``` | Method | What it does | | --- | --- | | `watch(gamepad1, gamepad2)` | uses these gamepads' kinds from now on. Every library OpMode calls it at INIT | | `say(text)` | the text with its marks (and "G1 A" names) turned into the controllers' names. `RobotTelemetry` calls it on every line | | `name(pad, button)` | one name: `name(1, "A")` is "A" or "×" | | `mark(pad, button)` | one mark for a line built in code: `mark(2, "RT")` is `"{2:RT}"`; a D-pad or stick name comes back as it is | | `style(pad)`, `styleOf(gamepad)` | `LETTERS` or `PLAYSTATION` | | `force(pad, style)` | for tests: gives names as if that gamepad were this kind (`null` = ask the gamepad) | Plain `telemetry.addLine(...)` does not change marks. Write your own lines with real names, or send them through `RobotTelemetry` (or `ButtonNames.say`). In the simulator, a scenario line `set gamepad 1 ps` makes gamepad 1 a PS controller. On the simulator page, the library sees a Sony PS controller plugged into the laptop by itself. It does not see an Etpark that way, so use the scenario line. The test recorder does not write `set gamepad` lines. Add one by hand to a recorded test that checks PS names. --- # Hardware module URL: https://crossbotics.com/ftc-helper/docs/modules/hardware/ Learn it hands-on: [02 Motors and servos](https://crossbotics.com/ftc-helper/docs/tutorials/02-motors-and-servos/), [06 A fast, clear loop](https://crossbotics.com/ftc-helper/docs/tutorials/06-fast-clear-loop/). Gets motors, servos, sensors and the IMU (the turn sensor in the Control Hub) from the robot configuration. It sets each one up in one readable chain. When a name is wrong, the error says which names do exist. Use it whenever your own code needs a device. The [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/robot-java/) does this for its parts, so there you only type the names. Start with tutorial 02. | Class | Use it to | | --- | --- | | [`Hw`](#hw) | get any device, with a helpful error if the name is wrong | | [`MotorSetup`](#motorsetup) | get and set up a motor | | [`ServoSetup`](#servosetup) | get and set up a servo | | [`ImuSetup`](#imusetup) | start the IMU and read the heading | | [`BulkReads`](#bulkreads) | make your loop faster by reading a hub's encoders and simple sensors at once | --- ## Hw Gets devices by their configuration name (the names you typed in the Driver Station's **Configure Robot** screen). ### `Hw.get(hardwareMap, type, name)` Gets a device. When the name is wrong, it stops the OpMode with a message that lists the names that DO exist. ```java // (where to look, what kind of device, its name in the robot configuration) DcMotorEx intake = Hw.get(hardwareMap, DcMotorEx.class, "intake"); TouchSensor bottom = Hw.get(hardwareMap, TouchSensor.class, "lift_bottom"); ``` | Parameter | Meaning | | --- | --- | | `hardwareMap` | the OpMode's `hardwareMap` | | `type` | the kind of device, for example `DcMotorEx.class`, `Servo.class`, `TouchSensor.class` | | `name` | the configuration name. Type it exactly: capitals and spaces matter. | **Returns** the device. **If the name is wrong**, the Driver Station shows something like: ``` No DcMotorEx named "intak" in the active robot configuration. Names of this type that do exist: [front_left, front_right, intake, lift]. Check the spelling and the active configuration on the Driver Station. ``` The SDK's own `hardwareMap.get` only says that it could not find "intak". ### `Hw.tryGet(hardwareMap, type, name)` The same as `get`, but it returns `null` instead of stopping when the device is not there. Use it for optional parts, like a sensor that is only on the practice robot. **Always check for null.** ```java TouchSensor bottom = Hw.tryGet(hardwareMap, TouchSensor.class, "lift_bottom"); // null = not on this robot. bottom::isPressed hands over "how to read it" (a method reference). if (bottom != null) lift.setLowerSwitch(bottom::isPressed); ``` ### `Hw.missingMessage(hardwareMap, type, name)` Gives the error text that `get` uses. You need it only when your own code writes that message. ### `Hw.batteryVolts(hardwareMap)` The battery's voltage now: the lowest hub reading, or NaN with no voltage sensor. Each call asks the hubs and **waits** for them for a few milliseconds. That is fine in INIT, but not in the loop. In the loop, use `Hw.batteryReader` (below). ### `Hw.batteryReader(hardwareMap)` The battery voltage for code that runs every loop. It gives a `DoubleSupplier` (an object that hands back a number when you ask). It answers at once with the latest reading. Then it asks the hubs again on the library's helper thread, at most every `BATTERY_READ_SEC` (0.25 s) ([non-blocking](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/)). It gives NaN before the first answer, with no voltage sensor, or when the last answer is older than `BATTERY_STALE_SEC` (2 s). The flywheel's [battery compensation](https://crossbotics.com/ftc-helper/docs/modules/launcher/#battery-compensation) uses it. ```java DoubleSupplier battery = Hw.batteryReader(hardwareMap); // once, in INIT double volts = battery.getAsDouble(); // every loop: never waits ``` --- ## MotorSetup Gets a motor and sets it up in one chain. The chain applies the settings in the order you write them. The **encoder** is the motor's sensor that counts how far the motor has turned. Its cable goes to the hub's encoder port. ```java DcMotorEx lift = MotorSetup.get(hardwareMap, "lift") .reversed() // mounted mirrored: positive power should still mean "up" .brake() // at power 0, hold still instead of letting the lift drop .resetEncoder() // here counts as 0 (reset BEFORE the run mode) .runUsingEncoder() .done(); // finish: power 0, and hand back the motor ``` | Method | What it does | | --- | --- | | `MotorSetup.get(hardwareMap, name)` | Starts the chain. A wrong name gives a clear error (like `Hw.get`). | | `MotorSetup.of(motor)` | Starts the chain for a motor you already have. | | `.forward()` | Positive power turns the normal way (the default). | | `.reversed()` | Positive power turns the other way. Use it for a mirrored motor. | | `.reversed(boolean)` | `true` = reversed, `false` = forward. Use it with a setting variable. | | `.brake()` | At power 0 the motor holds still. Use it for drive wheels, lifts, arms. | | `.coast()` | At power 0 the motor spins freely. Use it for flywheels. | | `.resetEncoder()` | The encoder count becomes 0. **Put it before a run mode** (see below). | | `.runUsingEncoder()` | Power sets a speed. The hub uses the encoder to keep that speed. It needs the encoder cable. | | `.runWithoutEncoder()` | Power goes straight to the motor. You can still read the encoder. | | `.done()` | Sets power to 0 and returns the `DcMotorEx`. Always end with this. | **Common mistakes** - `.runUsingEncoder().resetEncoder()` in that order: the reset puts the motor in STOP_AND_RESET_ENCODER mode. The motor does not move until your code sets a new run mode. Always reset first, then choose the run mode. - `runUsingEncoder()` without an encoder cable: the motor jumps to full speed or does not move. Use `runWithoutEncoder()` when there is no cable. --- ## ServoSetup ```java Servo claw = ServoSetup.get(hardwareMap, "claw") .reversed() .range(0.20, 0.75) // only this part of the travel: it can never hit the frame .done(); ``` | Method | What it does | | --- | --- | | `ServoSetup.get(hardwareMap, name)` | Starts the chain. A wrong name gives a clear error. | | `ServoSetup.of(servo)` | Starts the chain for a servo you already have. | | `.reversed()` | Positions 0 and 1 swap ends. | | `.range(min, max)` | Uses only part of the travel. After this, 0 means `min` and 1 means `max`. | | `.fullRange()` | Uses the servo's whole turn: 0 to 1 sends a 500 to 2500 microsecond pulse instead of 600 to 2400 ([below](#full-range)). | | `.pulseRange(lowUs, highUs)` | The same with your own pulse numbers (100 to 3000 us, low first). | | `.done()` | Returns the `Servo`. | | `ServoSetup.setPulseRange(servo, lowUs, highUs)` | The same for any servo. It gives false when it cannot change the pulse (not a REV hub servo). | | `ServoSetup.checkPulse(lowUs, highUs)` | Stops with a clear message when a number is outside 100 to 3000 us, or when low is not below high. | | `SDK_PULSE_LOW_US`, `SDK_PULSE_HIGH_US`, `FULL_PULSE_LOW_US`, `FULL_PULSE_HIGH_US` | 600, 2400 (the SDK's normal pulse) and 500, 2500 (full range), microseconds. | **Why use `range`:** it keeps the servo away from the frame. Find the positions where the claw is fully open and fully closed (for example 0.20 and 0.75), and put them in `range`. Now `setPosition(0)` is "open", `setPosition(1)` is "closed", and no code can push the servo into the frame. **Note:** setup does not move the servo. The servo moves the first time you call `setPosition`. ### Full range A servo goes where the hub's **pulse** tells it. A signal that lasts 600 microseconds (us) means position 0, and 2400 us means position 1. That is the FTC SDK's normal range (`PwmControl.PwmRange.defaultRange`). Most FTC servos take a wider pulse, 500 to 2500 us. So with the normal range, the servo never uses part of its turn: | Servo | Seller's range | 0 to 1 on the normal 600-2400 us | with `.fullRange()` | | --- | --- | --- | --- | | goBILDA 2000 Series (Torque, Speed, Super Speed) | 300 deg over 500-2500 us | 270 deg | 300 deg | | goBILDA 2000 Series 5-Turn | 1800 deg over 500-2500 us | 1620 deg | 1800 deg | | REV Smart Robot Servo (V1, V2) | 270 deg over 500-2500 us | 243 deg | 270 deg | | Axon MAX MK2, MINI MK2 | 360 deg max over 500-2500 us | 324 deg | 360 deg | ```java Servo wrist = ServoSetup.get(hardwareMap, "wrist").fullRange().done(); // 0 to 1 = 300 degrees ``` - **Nothing changes unless you ask.** Without `.fullRange()` the library never touches the pulse range. - **Measure positions again after you switch.** Position 0.5 is still the middle, but every other number points somewhere else. A measured number (positions, `posA`/`posB`, `angleA`/`angleB`, a calibration table) is right only for the range you measured it with. The Servo Finder has the same switch (Y while you choose a servo). The Hood Finder uses the hood's own setting. - **Only REV hub servos** (Control Hub, Expansion Hub, Servo Hub: the SDK's `ServoImplEx`) can change the range. On another servo, `setPulseRange` gives false and nothing changes. - **It lasts until the next INIT:** the hub goes back to its normal range when an OpMode starts. - **Check your servo's own numbers:** a servo programmed to a smaller range turns less. Two examples: an Axon's left and right limits, a REV servo in its Servo Limit Mode. Past 500 or 2500 us, most servos stop short or buzz. Stay inside the range the seller gives. The [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/) lists each servo's pulse range and both degrees. --- ## ImuSetup The IMU is a sensor inside the Control Hub that measures turning. The library uses it for field-centric driving and autonomous turns. ### `ImuSetup.get(hardwareMap, name, logo, usb)` Gets the IMU, tells it how the hub is mounted, and sets the heading to 0. If the IMU does not start, it stops the OpMode with a clear message. So you never get a broken IMU. ```java // How the hub sits on the robot: logo pointing UP, USB ports toward the robot's FRONT. IMU imu = ImuSetup.get(hardwareMap, "imu", RevHubOrientationOnRobot.LogoFacingDirection.UP, RevHubOrientationOnRobot.UsbFacingDirection.FORWARD); ``` | Parameter | Meaning | | --- | --- | | `name` | the IMU's configuration name. It is `"imu"` unless you changed it. | | `logo` | which way the REV logo printed on the hub points: `UP`, `DOWN`, `FORWARD`, `BACKWARD`, `LEFT`, `RIGHT` | | `usb` | which way the hub's USB ports point (same choices) | "Forward" means the front of the robot. **If these are wrong, the heading is wrong** and field-centric driving goes the wrong way. **To check:** run an OpMode that shows `ImuSetup.headingDeg(imu)`. Turn the robot left by hand. The number must go UP. Turn it right: the number must go DOWN. ### `ImuSetup.headingDeg(imu)` The robot's heading in degrees, from -180 to 180. Turning left makes it bigger. It is 0 in the direction the robot pointed at setup, or at the last `imu.resetYaw()`. --- ## BulkReads Each time your code reads an encoder or sensor, it sends a message to the hub and waits for the answer (about 2 milliseconds). With 6 encoders, that is 12 ms each loop. A **bulk read** gets everything from a hub in one message, so the loop runs faster. ### `BulkReads.auto(hardwareMap)` One line in INIT. It is safe for every robot. Start with this. ```java BulkReads.auto(hardwareMap); ``` In AUTO mode, the hub does a new bulk read when you read any value a second time. So your loop is fastest when it reads each value once. That is why `SafeMotor` (and so every Lift, Arm and `PositionMotor`) and the launcher's `Turret` read each encoder about once per loop. They use a reading again for 3 ms, so it is at most 3 ms old. `EasyTeleOp`, `EasyAuto` and the finders call `BulkReads.auto` for you. To see what each part reads every loop, read [what runs every loop](https://crossbotics.com/ftc-helper/docs/guides/every-loop/#bulk-reads). ### `BulkReads.manual(hardwareMap)` and `BulkReads.clear(hubs)` The fastest way. You clear the saved readings yourself at the top of every loop. **If you forget `clear`, the readings never change,** and the robot does strange things. ```java // List = a list of the hubs (a LynxModule is one Control or Expansion Hub) List hubs = BulkReads.manual(hardwareMap); waitForStart(); while (opModeIsActive()) { BulkReads.clear(hubs); // first line of the loop, every time ... } ``` Use `LoopTimer` ([util](https://crossbotics.com/ftc-helper/docs/modules/util/)) to see how much faster your loop gets. --- # Launcher module URL: https://crossbotics.com/ftc-helper/docs/modules/launcher/ Learn it hands-on: [17 Launcher](https://crossbotics.com/ftc-helper/docs/tutorials/17-launcher/), [18 Vision aiming](https://crossbotics.com/ftc-helper/docs/tutorials/18-vision-aim/). Parts for a robot that shoots game pieces. A **flywheel** is a fast-spinning wheel that throws the piece. A **hood** is a curved plate that a servo tilts to set the shot angle. A **feeder** pushes one piece into the flywheel. A **turret** turns the shooter to aim. Each part works alone. The `Launcher` joins them. The [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/) builds its `Launcher` on these parts, so start there ([Add a launcher](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/)). Use this page to build a shooter by hand (tutorial 17). Speeds are in **RPM** (turns per minute). | Class | Use it to | | --- | --- | | [`Flywheel`](#flywheel) | hold a speed in RPM, say "ready", notice shots | | [`ShotTable`](#shottable) | look up the RPM and hood angle for a distance, from a few measured shots | | [`Feeder`](#feeder) | push ONE piece into the flywheel (an interface) | | [`MotorFeeder`](#motorfeeder) | run a roller or belt feeder | | [`ServoFeeder`](#servofeeder) | run a kicker-arm feeder | | [`Turret`](#turret) | aim in degrees, never past its limits, hold a field direction | | [`Launcher`](#launcher) | spin up, wait until EVERYTHING is ready, feed, repeat | A hood is any [`AngleDevice`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#angledevice): a [`PositionServo`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#positionservo) with `degrees(...)`, the five-files [`Hood`](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/) (servo or motor, a linkage table), or your own.
flowchart LR
    T["ShotTable<br/>distance -> rpm, hood"] --> L
    L["Launcher"] --> F["Flywheel<br/>(speed)"]
    L --> H["Hood<br/>(PositionServo)"]
    L --> FD["Feeder<br/>(one piece)"]
    C["Ready checks<br/>turret aimed? target seen?"] --> L
## How a shot happens
stateDiagram-v2
    [*] --> OFF
    OFF --> SPINNING: spinUp() / shoot(n)
    OFF --> IDLE: idle()
    IDLE --> SPINNING: spinUp() / shoot(n)
    SPINNING --> WAITING_READY: shots left > 0
    WAITING_READY --> FEEDING: flywheel ready AND hood arrived AND every check true
    FEEDING --> WAITING_READY: piece through, wait shotInterval, shots left > 0
    FEEDING --> SPINNING: no shots left
    WAITING_READY --> SPINNING: not ready within readyTimeout (gives up, says why)
    WAITING_READY --> SPINNING: stopShooting()
    FEEDING --> SPINNING: feeder jammed (shots dropped, says why) / stopShooting()
    WAITING_READY --> IDLE: idle()
    SPINNING --> IDLE: idle()
    SPINNING --> OFF: stop()
    IDLE --> OFF: stop()
The two safety rules: **never feed into a slow flywheel**, and **never wait forever**. --- ## Flywheel ```java Flywheel flywheel = Flywheel.create(hardwareMap, "flywheel") .countsPerRev(28) // encoder counts per ONE flywheel turn .maxRpm(6000) // the motor's top speed .startingGains() // the hub's speed control (a start) .tolerance(75) // ready within 75 rpm... .settleTime(0.15); // ...for 0.15 s ``` | Method | What it does | | --- | --- | | `create(hardwareMap, name)` | coast (a flywheel must spin down freely), speed control on | | `.reversed()` | spin the other way | | `.follower(hardwareMap, name, reversed)` | a second motor on the same wheel (same speed command). **It needs its own encoder cable.** If its encoder reads nothing while the wheel spins, the flywheel switches it off and shows a warning. It gets the `pidf` gains whether you call `pidf` before or after it | | `.countsPerRev(c)` | counts per FLYWHEEL turn. A bare motor at 1:1 = 28. With gears, multiply by the motor turns per wheel turn. A shaft encoder on this motor's port = its counts (REV Through Bore 8192) | | `.pidf(p, i, d, f)` | the hub's speed gains (PID plus F, a push that grows with the speed; see [PID](https://crossbotics.com/ftc-helper/docs/modules/control/#pidcontroller)). No tuned gains yet? Use `startingGains()` (next row). Tune F first, with a charged battery | | `.startingGains()` | for a wheel with no tuned gains yet. It sets `pidf` from this wheel's `maxRpm` and `countsPerRev` (set them first) with REV's formula: F = 32767 / top counts per second, P = F / 10, I = P / 10, D = 0 (a goBILDA 6000 RPM motor, 28 counts: 1.17, 0.117, 0, 11.70). Then the Flywheel Finder finds your gains | | `Flywheel.startingPidf(topTicksPerSec)` | that formula: `{P, I, D, F}` (the Flywheel Finder and the robot `Launcher` use it too) | | `.batteryCompensation(volts, nominalVolts)`, `.noBatteryCompensation()` | F follows the battery ([below](#battery-compensation)); off (the default) | | `getBatteryVolts()`, `getFScale()`, `hasBatteryCompensation()` | the battery voltage F is scaled for (the highest reading of the last second; NaN if none); what F is multiplied by now (1 = as tuned) | | `.tolerance(rpm)`, `.settleTime(s)` | when the wheel counts as "ready" | | `.maxRpm(r)` | the highest speed allowed | | `.shotDrop(rpm)` | a drop this big after "ready" counts as a shot | | `setRpm(r)`, `stop()`, `update()` | use. `stop()` and speed 0 COAST, so a fast wheel never brakes hard | | `isReady()`, `getRpm()`, `getTargetRpm()`, `getMaxRpm()`, `getShotCount()`, `getFault()` | read | | `spinUpStep(rpm, timeout)` | autonomous step | **Check your speed reading** before you trust it. The RPM on telemetry must match a tachometer (a tool that measures spin speed) or a slow-motion video. Very high count rates (a fine encoder at high speed) can read wrong. ### Battery compensation > **Battery compensation: OFF by default. Nobody has proven it on a real robot yet.** Testing teams: please > try it and tell us what you see. > The RPM control already makes up for a low battery by itself, but slowly (the I gain is small). > Compensation makes that faster. It helps the first shot after spin-up and quick shots in a row. It cannot > help when the battery is too low for the speed you ask: then the motor is already at full power. > - **Turn it on:** in the robot in five files, write `public static boolean batteryCompensation = true;` in > `Tunables.Launcher` (with `kF` set). With the parts on this page, add `.batteryCompensation(...)` as below. > - **Test it on your robot:** with a battery at about 11.5 V, fire 4 shots in a row. On the Driver Station, > compare the launcher's measured RPM with its target. Do it with compensation off, then on. If you see no > difference, leave it off. If the wheel overshoots after a battery swap, turn it off and tell us. ```java Flywheel flywheel = Flywheel.create(hardwareMap, "flywheel").pidf(1.17, 0.117, 0, 11.70) .batteryCompensation(Hw.batteryReader(hardwareMap), 12.6); // 12.6 V: from the Flywheel Finder ``` **Why.** The hub's speed control works in power. F means "this much power for each count per second of speed". The Flywheel Finder sets F = 32767 / the top speed in counts per second (32767 = full power). FIRST's motor PIDF tuning guide does the same. Power is a share of the battery's voltage. So the same power on a weaker battery pushes less, and the wheel runs slower. The P and I gains notice the missing speed and add power, but I builds up slowly. So with a low battery, the wheel spins up slowly and recovers slowly after each shot. Shots fired before it recovers go short. **What it does.** Every 0.25 s the flywheel reads the battery and sends F x (`nominalVolts` / volts). For example, with gains tuned at 12.6 V, at 11.5 V F is x 1.10 (12.6 / 11.5). Then the wheel gets the same push as when you tuned it. "volts" is the **highest reading of the last second** (`BATTERY_FILTER_SEC`). The reason: while the drive or the flywheel pulls hard, the battery dips for a moment and comes back. A dip is not a weaker battery. A higher F for a dip would push the wheel past its speed when the load ends. A battery that is truly weaker reads low the whole second, and then the flywheel scales F. Some limits keep it safe: - The scale stays between 0.8 and 1.3, so a bad reading cannot run the wheel away. - The flywheel skips a reading outside 7 to 16 V, or NaN (no reading yet, or too old). - It sends a new F only when F changes by more than 2%, because each send costs loop time. P and I stay as tuned. `nominalVolts` is the battery voltage when you found the gains. The Flywheel Finder shows it. Without it, the flywheel uses 12.8 V (`Flywheel.DEFAULT_NOMINAL_VOLTS`, a charged battery under load). Below 11.5 V the Driver Station warns: `battery 11.2 V: low`. Debug mode shows `flywheel battery: 11.50 V (tuned at 12.6 V), F x1.10`. **Where the volts come from.** `Hw.batteryReader(hardwareMap)` never waits. It answers with the latest reading, and it asks the hubs again (at most every 0.25 s) on the library's helper thread. So the loop never waits for the hubs ([non-blocking](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/)). `() -> Hw.batteryVolts(hardwareMap)` works too, but then each reading holds up the loop for a few milliseconds. The robot in five files turns it on when `Tunables.Launcher` has `batteryCompensation = true` and a `kF` ([robot.md](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#speed-trim-and-battery-compensation)). ## ShotTable ```java ShotTable pollen = new ShotTable() .add(24, 2600, 6) // distance in, rpm, hood degrees .add(48, 3100, 14) .add(72, 3700, 21); ShotTable.Shot s = pollen.lookup(36); // 2850 rpm, 10 deg (halfway between 24 and 48) ``` The table draws straight lines between your points, for the speed AND the hood. Outside your points, it uses the nearest end, so it never guesses beyond what you tested. `add(distance, rpm)` (no hood angle) makes a table that never moves the hood: `hasHood()` is true only once a point has a hood angle. The hood number is in the hood's own scale: degrees, or a servo position if your hood works in positions. `covers(distance)` says whether a distance is inside your points. When game pieces fly differently, make one table per piece (BIOBUZZ: POLLEN is a 2.8 in ball, NECTAR a 3.6 in ball). Swap tables with `launcher.table(other)`. To fill a table, follow [tutorial 17](https://crossbotics.com/ftc-helper/docs/tutorials/17-launcher/#4-fill-the-shot-table). In the robot in five files, each `speedByDistance...` line in `Tunables.Launcher` is one table. Your code picks one by name with `robot.launcher.useTable("nectar")` ([robot.md: Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/)). The [Shot Tuner](https://crossbotics.com/ftc-helper/docs/modules/finders/) tunes one table at a time. ## Feeder An interface (a list of methods a class promises to have): `feedOne()`, `isBusy()`, `update()`, `stop()`, and optional `isJammed()` and `clearJam()`. The launcher decides WHEN to feed. The feeder only knows HOW. For a new feeding mechanism next season, write a class with these methods, and the launcher works with it. See [Extending](https://crossbotics.com/ftc-helper/docs/guides/extending/). ## MotorFeeder ```java MotorFeeder feeder = MotorFeeder.create(hardwareMap, "feeder") .power(1.0).feedTime(0.25) // run 0.25 s per piece // optional: stop when a sensor sees the piece leave. beam = a beam-break sensor // (a DigitalChannel); "!" = not: it reads false while something blocks the beam .stopWhen(() -> !beam.getState()) .jamDetection(60, 0.2); // optional (encoder cable) ``` A jam stops the launcher's remaining shots. The next `shoot(...)` clears the jam and tries again. The feeder still detects a new jam. So the driver clears the piece, then presses shoot again. ## ServoFeeder ```java ServoFeeder kicker = ServoFeeder.create(hardwareMap, "kicker") .positions(0.15, 0.60) // rest, push .times(0.15, 0.15); // push time, return time ``` `goToRest()` moves the arm to rest. Call it in INIT only if that is safe. `withServo(other, trim)` adds a second servo that moves with the first, for two arms, one on each side. It goes to the same positions plus `trim` (a raw servo position; `() -> 0` for none). Set its direction yourself: REVERSE when it faces the first. ## Turret ```java Turret turret = Turret.create(hardwareMap, "turret") .countsPerDegree(1479 / 360.0) // encoder counts per turret turn / 360. ".0": a // decimal result (1479 / 360 alone would drop it) .limits(-190, 190) // degrees; it never turns past these (cables!) .homeSwitch(hardwareMap, "turret_home", 45) // the switch closes at 45 degrees .pid(0.02, 0, 0.001, 0) // kP, kI, kD, kF on the angle in degrees .tolerance(1.0); // within 1 degree = aimed ``` ![Turret angles and limits](https://crossbotics.com/ftc-helper/docs/images/turret-limits.svg) Angles: 0 = robot forward, **counterclockwise positive** (like the IMU). Positive power must turn the turret counterclockwise. If it turns the other way, add `.reversed()`. | Method | What it does | | --- | --- | | `.countsPerDegree(c)` | encoder counts per turret degree (motor counts x gear ratio / 360) | | `.limits(min, max)` | the allowed range. It may be more than 360 in total (for example -190..190) | | `.startAngle(deg)` | the angle at power-on, for a turret with no switch. It reads the encoder when you call it, so call it after `countsPerDegree` and `reversed`. A servo turret cannot say where it is, so this is where it counts from before its first command. Send it there when the OpMode starts (▶) with `aimAt(servoStartAngle())` | | `servoStartAngle()` | a servo turret: `startAngle`, or the middle of its range when you gave none (0 with no limits). Other turrets: `getAngle()`. The stick and `aimBy` start from it before the first command | | `.homeSwitch(hardwareMap, name, angle)` / `.homeSwitch(reader, angle)` | a switch that closes at a known angle | | `.homingPower(p)`, `.pid(...)`, `.tolerance(deg)`, `.maxPower(p)`, `.slowZone(deg, power)` | tuning. Before homing, the turret limits manual power to the homing power | | `.homingTimeout(s)` | homing stops with a fault when it does not find the switch in time (default 5 s) | | `.maxTargetAgeMs(ms)` | the oldest camera picture `aimAtTarget` uses (default 150) | | `.cameraOffset(deg)` | for a camera not centered on the launcher: where the target sits in the camera's view when the launcher points at it (left = +). The [Aim Tuner](https://crossbotics.com/ftc-helper/docs/modules/finders/#aimtuneropmode) finds it. | | `aimAt(robotDeg)` | turn to a robot-relative angle, **the safe way round** | | `aimField(fieldDeg, headingDeg)` | point at a field direction. Call it every loop while the robot turns | | `aimBy(delta)` | turn by an amount | | `aimAtTarget(target, cameraOnTurret)` | aim at a camera target. It uses fresh pictures only, each picture once, and holds when there is none | | `manual(power)` | a stick; 0 holds where it is | | `home(direction)` | turn slowly toward the switch until it closes. It ends at once when the switch is already closed, and gives a fault after the timeout | | `addWarnings(t)` | only the warnings of `addTelemetry` (a fault, not homed, out of range), for code that writes its own line (the five files' [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/) does) | | `getAngle()`, `getTargetAngle()`, `isAimed()`, `isOutOfRange()`, `isHomed()`, `isHoming()`, `getFault()` | read. `isAimed()` is false for an out-of-range target. It only says whether the turret reached its LAST target. When the goal can get lost (a camera), also check that the camera sees the goal now. The robot in five files' [`Turret.isAimed()`](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/) does | | `getTolerance()`, `degreesOutOfRange(deg)` | the aimed tolerance; how far past the limits a direction is (0 = it can point there) | | `aimStep(deg, timeout)` | autonomous step | | `fence(lo, hi)`, `fence(lo, hi, upPower, downPower)`, `clearFence()`, `isHeld()` | an [interlock rule](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) sets these every loop. A target past `lo`..`hi` goes the other way round, or waits at the edge. The caps (0 to 1) limit the power toward each side, so the turret brakes in time | **The safe way round:** with limits -190..190, 170 and -190 are the same direction. The turret picks the one inside the limits that is closest to where it is. It turns there without passing a limit, so cables never wind up. For a direction outside the limits, the turret goes to the nearest limit, and `isOutOfRange()` is true. **Homing** means finding a known angle: the turret turns until a switch closes. With a switch, aiming waits until the turret has seen the switch once (`home(direction)`). When homing does not find the switch within `homingTimeout`, it stops, and `getFault()` says so. So a broken wire never spins the turret forever. Without a switch, the turret trusts `startAngle` (default 0): turn the robot on with the turret facing forward. ## Launcher The five-files launcher (`robot.Launcher`) adds the speed from the distance and its Tunables (`distanceSmoothSec`, `lockSpeedWhileFiring`, `ejectFeedSec`, `ejectRpm`): see [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava). ```java Launcher launcher = new Launcher(flywheel, feeder) .hood(hood) .table(pollen) .requireReady("Turret", turret::isAimed) // never feed before the turret is aimed .shotInterval(0.25) // at least 0.25 s between pieces .readyTimeout(3); // not ready in 3 s: give up, say why ``` | Method | What it does | | --- | --- | | `.hood(device)`, `.table(t)` | optional parts: a hood is any [`AngleDevice`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#angledevice) | | `.hoodDeadband(a)` | the launcher sends the hood a new angle only when the table's angle changes by more than this (default 0.25). So a jittery distance does not keep the hood "moving" | | `hoodOffset(a)`, `getHoodOffset()` | a hood trim: `setDistance` adds it to the table's hood angle | | `.requireReady(name, check)` | another condition before each piece (aim, sensor, anything) | | `.clearReadyChecks()` | removes every `requireReady` check. The Shot Tuner does this, because you aim by hand there | | `.shotInterval(s)` | the least time between pieces | | `.readyTimeout(s)` | gives up the remaining shots when the launcher is not ready for this long | | `.idleRpm(r)` | the speed when not shooting. A low idle speed makes spin-up faster | | `setRpm(r)` / `setDistance(d)` | sets the shot by hand / from the table. `setDistance` sets the hood too, when the table has hood angles | | `speedScale(s)`, `getSpeedScale()` | the shot speed x `s` (1.03 = +3%), a live trim for a match. It does not change the idle speed. 1 = as set | | `getShotRpm()` | the shot speed before `speedScale` (from `setRpm` or the table) | | `getHood()`, `getTable()`, `hasTable()` | the hood (or null); the table (or null); whether you gave a table | | `spinUp()`, `shoot(n)`, `stopShooting()` | commands | | `idle()` | back to the idle speed | | `stop()` | fully OFF, even the idle speed, until `spinUp()`, `shoot()` or `idle()` | | `update()` | call it every loop. It updates the flywheel, feeder and hood for you | | `isReady()`, `whyNotReady()` | for example "flywheel, Turret": your first debug clue | | `getState()` (OFF, IDLE, SPINNING, WAITING_READY, FEEDING), `isShooting()`, `getShotsLeft()`, `getShotsFired()`, `getLastProblem()` | read. The last problem shows as a warning for `PROBLEM_SHOW_SEC` (5 s). A jam shows for as long as the feeder is jammed | | `spinUpStep()`, `shootStep(n)` | autonomous steps | | `.shotMode(mode)`, `getShotMode()` | how strict the launcher is before each piece. `ShotMode.CAREFUL` (default): every piece at speed. `QUICK`: the volley's first piece at speed, the next ones in a looser band or after a short wait. `SPRAY`: no wait for the speed band or the checks, but the wheel must turn at `SPRAY_MIN_SHARE` (half its speed) or more | | `.quickBand(rpm)`, `getQuickBand()` | QUICK: the looser band (default 3 x the flywheel's tolerance) | | `.quickMaxWait(s)`, `getQuickMaxWait()` | QUICK: the longest wait for the band (default 0.3 s) | | `getShotInterval()` | the least time between pieces | | `getShotStats()` | the [firing stats](#shotstats) | A volley is a group of shots in a row. A piece asked for within `shotInterval` + 1 s of the last feed belongs to the same volley. The robot in five files chooses the mode itself ([Firing](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#firing-shot-modes-feed-stop-piece-path)). ### ShotStats `launcher.getShotStats()` tells you what each fed piece did to the wheel, for tuning. It has `count()`, `last()`, `volley()` (the pieces of this volley), `lastVolley()` and `ShotStats.summary(list)` ("drop avg 290 worst 340, recovery avg 0.20 worst 0.26 s"). Each `ShotStats.Shot` has `mode`, `rpmAtFeed`, `targetRpm`, `dropRpm`, `recoverySec` (NaN while the wheel recovers, or when the next piece came first) and `gapSec` (the time since the last piece of the volley; NaN for the first). The launcher's debug lines show them, in the PRACTICE profile only: ``` Shot 3 QUICK fed at 2410/2450 rpm, drop 310, back in 0.21 s, 0.30 s after the last Volley (4) drop avg 290 worst 340, recovery avg 0.20 worst 0.26 s ``` --- # Match module URL: https://crossbotics.com/ftc-helper/docs/modules/match/ Learn it hands-on: [15 Telemetry, profiles and tuning](https://crossbotics.com/ftc-helper/docs/tutorials/15-telemetry-profiles-tuning/), [16 Easy autonomous](https://crossbotics.com/ftc-helper/docs/tutorials/16-easy-autos/). These classes know about the MATCH, not the robot: red or blue, the clock, the choices made in INIT, and what autonomous tells TeleOp. [`EasyAuto`](https://crossbotics.com/ftc-helper/docs/modules/auto/), [`EasyTeleOp`](https://crossbotics.com/ftc-helper/docs/modules/teleop/) and the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/robot-java/) use them for you. Use this page when you write your own OpMode, or to add a timer cue or an INIT choice. | Class | Use it to | | --- | --- | | [`Alliance`](#alliance) | red/blue, and mirror a route written for blue | | [`MatchTimer`](#matchtimer) | count down a period and buzz the gamepads at set times | | [`InitMenu`](#initmenu) | choose alliance, delay, route... with the gamepad in INIT | | [`MatchMemory`](#matchmemory) | pass the alliance (and pose: where the robot is and which way it faces) from autonomous to TeleOp | --- ## Alliance `Alliance.BLUE` or `Alliance.RED`. | Method | What it does | Example | | --- | --- | --- | | `mirror(blueValue)` | gives the value as it is for blue, and with the sign flipped for red | `RED.mirror(90)` = -90 | | `pick(blue, red)` | gives the value for this alliance | `alliance.pick(20, 24)` (tag ids) | | `other()` | gives the other alliance | - | | `sign()` | gives +1 for blue, -1 for red | - | **Write routes for BLUE.** `AutoRoutine.mirrorFor(alliance)` flips every turn, heading and sideways direction for RED. Check each season's field. On some fields the red half is ROTATED (turned around) instead of mirrored. Then forward and back flip as well, and you need your own rule for that ([New season](https://crossbotics.com/ftc-helper/docs/guides/new-season/)).
flowchart LR
    B["Route written for BLUE<br/>turn(45), move(20, 90)"] --> M{alliance}
    M -- BLUE --> B2["turn(45), move(20, 90)"]
    M -- RED --> R2["turn(-45), move(20, -90)"]
## MatchTimer ```java MatchTimer timer = MatchTimer.teleOp() // 2:00 (autonomous(): 0:30) .rumbleAt(60, gamepad1, gamepad2) // buzz both gamepads at 1:00 left... .rumbleAt(20, gamepad1, gamepad2); // ...and at 0:20 left waitForStart(); timer.start(); // counts from ▶ (start), not from INIT while (opModeIsActive()) { timer.update(); // checks the clock, buzzes when due t.line("Time", timer.format()); // "1:23" } ``` | Method | What it does | | --- | --- | | `MatchTimer.autonomous()`, `MatchTimer.teleOp()`, `new MatchTimer(seconds)` | makes a timer | | `cueAt(secondsLeft, action)` | runs code once at that time | | `rumbleAt(secondsLeft, gamepads...)` | buzzes the gamepads 3 times at that time | | `start()` | starts counting. Call it right after `waitForStart()` | | `update()` | runs the cues. Call it every loop | | `secondsLeft()`, `elapsedSec()`, `isOver()`, `isRunning()` | read the timer | | `format()` | gives the time left as "m:ss", like the field clock | Good cues to add for 2026-27 BIOBUZZ: **1:00** (FLOWER ownership unlocks) and **0:20** (final 20 seconds). The field clock is the official one. This timer starts with your OpMode, so it can be a second off. ## InitMenu ```java InitMenu menu = new InitMenu(gamepad1) .alliance() // X = blue, B = red .delay(10) // start delay 0..10 s .choice("Route", "Near", "Far") .yesNo("Park", true) .profile(); // practice / competition while (opModeInInit()) { // repeats until ▶ is pressed (instead of waitForStart()) menu.update(); // reads the D-pad and changes the choices menu.addTelemetry(t); t.update(); } ``` | Method | What it does | | --- | --- | | `alliance()` | adds the alliance line. It starts at the alliance remembered from earlier, or BLUE when there is none | | `delay(maxSeconds)` | adds a start delay, in 1 s steps | | `choice(label, options...)` | adds a list. The first option is the default | | `yesNo(label, startYes)` | adds a YES/NO line | | `profile()` | adds PRACTICE/COMPETITION. The menu saves it when the drivers change it | | `update()`, `addTelemetry(t)` | call them every INIT loop | | `getAlliance()`, `getDelaySec()`, `get(label)`, `isYes(label)` | read the choices | The buttons: D-pad up/down chooses a line, and left/right changes it. X and B are alliance shortcuts. `EasyAuto` builds this menu for you. ## MatchMemory ```java MatchMemory.remember(Alliance.RED, pose); // end of autonomous (EasyAuto does it) // TeleOp INIT: the alliance autonomous saved, or BLUE if nothing (recent) was saved Alliance a = MatchMemory.allianceOr(Alliance.BLUE); // TeleOp INIT boolean fromAuto = MatchMemory.hasAlliance(); // false: let the drivers choose (EasyTeleOp does) MatchMemory.rememberReport(lines); // end of autonomous: its report (EasyAuto does it) List report = MatchMemory.lastReport(); // TeleOp INIT shows it MatchMemory.setPlacement(pose, "Against our wall"); // autonomous's start spot (EasyAuto does it); the FieldPose spot = MatchMemory.placement(); // simulator puts the robot there in INIT MatchMemory.setPlacement(pose, "Against our wall", "x -36, y -63 in, heading 0 (as written)"); String written = MatchMemory.placementAsWritten(); // the team's own numbers, for messages (the // simulator's "Start spot ... overlaps the field wall") FieldPose p = MatchMemory.fieldPose(Alliance.BLUE, 56, -61.55, 0); // a spot seen from that alliance's wall MatchMemory.setChosen(Alliance.RED); // the alliance in use now (EasyAuto/EasyTeleOp do it); Alliance now = MatchMemory.chosen(); // the simulator turns its drivers' view to it MatchMemory.changeAlliance(Alliance.RED); // TeleOp's "switch alliance" (opt-in: lib.switchAlliance(...)): // chosen() and autonomous's remembered one (if from this match) become RED ``` `MatchMemory` lets ONE TeleOp serve both alliances. The memory lasts until the app restarts. After 5 minutes (`MAX_AGE_SEC`) the library ignores it, so an old match never leaks into a new one. The pose goes to `PoseStore` ([util](https://crossbotics.com/ftc-helper/docs/modules/util/#posestore)). --- # Mechanism module URL: https://crossbotics.com/ftc-helper/docs/modules/mechanism/ Learn it hands-on: [14 Mechanisms](https://crossbotics.com/ftc-helper/docs/tutorials/14-mechanisms/). Example: [Drive + intake](https://crossbotics.com/ftc-helper/docs/guides/example-drive-intake/). Ready-made helpers for the mechanisms that most robots have: four classes and one interface. Each one is a [`Subsystem`](https://crossbotics.com/ftc-helper/docs/modules/core/#subsystem). One line connects it to a button, and one call gives an autonomous step. The Lift, Arm, Claw and other parts of the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/robot-java/) use them inside. So with five files, you make them yourself only for a special case. Use them in your own mechanism class, or for a part that five files has no module for. Start with tutorial 14. | Class | For | Hardware | | --- | --- | --- | | [`PositionMotor`](#positionmotor) | lifts, arms, slides, motor claws: go to named positions and hold | motor + encoder | | [`SpinMotor`](#spinmotor) | intakes, rollers, conveyors: in / out / stop, jam back-out | motor | | [`PositionServo`](#positionservo) | claws, wrists, hoods, gates: named positions or degrees | servo | | [`SpinServo`](#spinservo) | small rollers and spinners | continuous-rotation servo | | [`AngleDevice`](#angledevice) | anything that goes to an angle and says when it is there (a launcher's hood) | an interface |
flowchart LR
    BTN["Button<br/>bindPress(..., () -> lift.goTo(&quot;HIGH&quot;))"] --> CMD["Command<br/>(quick: sets the target)"]
    STEP["Autonomous step<br/>lift.goToStep(&quot;HIGH&quot;)"] --> CMD
    CMD --> UPD["update() every loop<br/>PID + limits + switch"] --> HW["Motor"]
**Two rules for all of them:** 1. Commands (`goTo`, `in`, `toggle`...) are quick, and you can safely call them from a button. Motor helpers act in `update()`, once per loop. So call `update()` every loop, or put them in a `Subsystems` group. 2. **Servo commands move the servo AT ONCE.** That is how servos work. With `.maxSpeed()`, the first move happens at once, and `update()` does the rest in small steps. Nothing may move before ▶ (start on the Driver Hub). So call a command in INIT only when that movement is allowed and safe. **A typo in a position name** (`goTo("HGIH")`) does nothing and shows a warning on the Driver Station. So a typo can never stop the OpMode in a match. `getWarning()` gives the warning. --- ## PositionMotor Everything from tutorials 07, 08 and 12 in one helper: - **PID** to reach a position and hold it ([PidController](https://crossbotics.com/ftc-helper/docs/modules/control/#pidcontroller)). - **Soft limits:** the code never pushes past the safe range. - A bottom switch with **homing**: when the switch is pressed, the helper sets the position to 0. This keeps the count right. - A **slow zone** near the ends, so the mechanism does not slam. - Named positions, steps between them, control by hand that holds where you let go, live tuning, and autonomous steps. ```java PositionMotor lift = PositionMotor.create(hardwareMap, "lift") .limits(0, 2600) // safe range, encoder ticks .lowerSwitch(hardwareMap, "lift_bottom") // touch sensor at the bottom: resets to 0 .slowZone(250, 0.2) // last 250 ticks: power down to 0.2, no slamming .pid(0.004, 0, 0.0002, 0.05) // kP, kI, kD, kF (0.05 holds it up) .position("DOWN", 0) // named heights, ticks: measure yours .position("LOW", 900) .position("HIGH", 2400) .tunable("Lift"); // put the numbers in the tuning menu ``` Setup (chain them). **Positive power must move toward bigger positions:** | Method | What it does | | --- | --- | | `PositionMotor.create(hardwareMap, name)` | gets the motor: brake, encoder zeroed, plain power | | `new PositionMotor(name, motor)` | wraps a motor you already have | | `.reversed()` | positive power the other way (call first) | | `.units(ticksPerUnit, "deg")` | work in degrees or inches instead of ticks. Call it FIRST: after limits, positions, slowZone or tolerance, it stops with a clear error | | `.limits(min, max)` | the safe range | | `.lowerSwitch(hardwareMap, name)` / `.lowerSwitch(reader)` | bottom switch: it stops downward power and homes (sets position 0). Until it homes, only slow downward power works. When the name is not in the configuration, it shows a warning and runs without a switch | | `.upperSwitch(reader)` | top switch | | `.slowZone(distance, powerAtLimit)` | slow near the ends | | `.maxPower(p)` | the most power it ever uses | | `.pid(kP, kI, kD, kF)` | gains (on the error in UNITS) | | `.tolerance(units)` | "there" when this close (default: about 20 ticks) | | `.position(name, value)` | a named position | | `.holdWhenReleased(bool)` | after control by hand, hold where the driver let go (default true) | | `.stepTimeout(seconds)` | how long autonomous steps wait (default 3) | | `.tunable(prefix)` | gains and positions in the [tuning menu](https://crossbotics.com/ftc-helper/docs/modules/tuning/); call LAST | Commands and reading: | Method | What it does | | --- | --- | | `goTo(name)` / `goTo(value)` | go there and hold | | `stepUp()` / `stepDown()` | next named position up / down (by value) | | `manual(power)` | call it every loop with a stick. A power other than 0 takes over; 0 = hold where it is | | `hold()`, `stop()`, `zeroHere()` | hold here / no power / make here zero | | `update()` | every loop | | `isAtTarget()`, `isAt(name)`, `getPosition()`, `getTargetName()` | read (`getTargetName()` gives "hand", "hold", "none" or the name) | | `isWaitingForHoming()` | whether the bottom switch has not been pressed yet | | `goToStep(name)` | autonomous: go, and wait until it is there. When it is not there in time (for example, a jam), it holds where it is and stops pushing. The end report says "timed out" | | `startStep(name)` | autonomous: start going, and go on to the next step at once (it moves during the next steps) | | `getSafeMotor()`, `getPid()` | the layers inside | | `fence(lo, hi)`, `fence(lo, hi, upPower, downPower)`, `isHeld()` | an [interlock rule](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) sets these every loop. A target past `lo`..`hi` waits at its edge. The caps (0 to 1) limit the power toward each side, so the part brakes in time | Telemetry: standard = target and position; debug = target value, power asked and sent, limits, homed. **Per loop on the hub** (from its `SafeMotor`): - One encoder read. `update()` reads it fresh, and the PID and telemetry reuse it for 3 ms. So a reading is at most 3 ms old. - It sends a power only when the power changes, and again every 25 loops (every loop while past a soft limit). So a power you write straight to `getSafeMotor().getMotor()` lasts at most 25 loops. The launcher's [`Turret`](https://crossbotics.com/ftc-helper/docs/modules/launcher/#turret) reads its encoder the same way (at most once per 3 ms). All the details: [what runs every loop](https://crossbotics.com/ftc-helper/docs/guides/every-loop/#what-a-part-does-on-the-hub-per-loop). ## SpinMotor ```java SpinMotor intake = SpinMotor.create(hardwareMap, "intake") .powers(1.0, -0.7) // in, out .jamDetection(80, 0.3, 0.4); // < 80 ticks/s for 0.3 s = jam; back out 0.4 s ``` | Method | What it does | | --- | --- | | `create(hardwareMap, name)` | gets the motor: coast, plain power | | `.reversed()`, `.powers(in, out)` | direction and powers | | `.jamDetection(minSpeed, jamSec, unjamSec)` | while IN: on a jam (motor powered but barely turning), it backs out, then runs IN again. It needs the encoder cable | | `.jamCurrent(amps)` | it also counts a jam when the motor draws too much current | | `in()`, `out()`, `stop()` | **safe to call every loop** (in() does not interrupt a jam back-out) | | `toggleIn()`, `toggleOut()` | for one button | | `setPower(p)` | any power, for example from a trigger | | `getState()` | STOPPED, IN, OUT, UNJAMMING, MANUAL | | `getJamCount()`, `isRunning()` | read | | `inStep()`, `outStep()`, `stopStep()`, `outForStep(seconds)` | autonomous steps | A common pattern is "reverse wins, then on/off": ```java // every loop; reverseHeld and intakeOn are your own true/false values (e.g. from buttons) if (reverseHeld) intake.out(); else if (intakeOn) intake.in(); else intake.stop(); intake.update(); // only here does the motor actually get its power ``` **Per loop on the hub:** `update()` sends the power only when it changes, and again every 25 writes (one write per `update()`). So a power you write straight to `getMotor()` lasts at most 25 loops. While it runs IN with jam detection, it reads the speed every loop, as part of a bulk read. With `.jamCurrent(...)`, it also reads the current. `getCurrent()` is a separate hub command each loop, outside the bulk read. So add it only when the speed check is not enough. ## PositionServo ```java PositionServo claw = PositionServo.create(hardwareMap, "claw") .position("OPEN", 0.20) // raw servo positions, 0 to 1: find yours by testing .position("CLOSED", 0.75) .travelTime(0.3); // seconds for a full 0..1 move (measure it) PositionServo hood = PositionServo.create(hardwareMap, "hood") .degrees(0.10, 0, 0.90, 25); // two measured points: raw 0.10 = 0 deg, raw 0.90 = 25 deg hood.setDegrees(18); // moves the servo at once (servos do) ``` ![How a servo's raw position maps to named positions and degrees](https://crossbotics.com/ftc-helper/docs/images/servo-range.svg) | Method | What it does | | --- | --- | | `create(hardwareMap, name)` | gets the servo. It does NOT move it | | `.reversed()` | 0 and 1 swap ends | | `.fullRange()`, `.pulseRange(lowUs, highUs)` | the servo's whole turn: 0 to 1 sends 500-2500 us instead of the SDK's 600-2400 (a goBILDA 2000 servo turns 300 degrees, not 270). Set it before you measure positions and degrees ([full range](https://crossbotics.com/ftc-helper/docs/modules/hardware/#full-range)). When a servo cannot change its pulse, the Driver Station shows a warning | | `isFullRange()` | whether `fullRange()`/`pulseRange` changed the pulse | | `.limits(min, max)` | never past these raw positions (keeps it off the frame) | | `.position(name, raw)` | a named raw position (0..1) | | `.degrees(posA, degA, posB, degB)` | use degrees, from two measured points | | `.travelTime(seconds)` | time for a full 0..1 move. A servo cannot report its position, so the helper uses this to guess "arrived". A shorter move waits its share. When you time a move between two positions: seconds / distance | | `.maxSpeed(perSecond)` | move slowly (raw positions per second). After a pause in `update()` calls, it goes on slowly. It never jumps the rest of the way | | `.withServo(other, trim)` | a second servo that moves with this one (the other side of a two-servo part). It goes to the same positions plus `trim` (a `DoubleSupplier`, raw position, read at each move). Set its direction yourself | | `.tunable(prefix)` | positions in the tuning menu; call LAST | | `goTo(name)`, `set(raw)`, `setDegrees(deg)` | move | | `toggle(a, b)`, `next()`, `previous()` | for buttons | | `isDone()` | whether it should have arrived (an estimate) | | `getPosition()`, `getDegrees()`, `getTargetName()` | read | | `getTargetDegrees()` | the angle it is going to (after its limits). It differs from `getDegrees()` only during a slow move | | `goToStep(name)` | autonomous: move, and wait until it should have arrived | | `update()` | every loop (needed for slow moves and "done") | `PositionServo` is an [`AngleDevice`](#angledevice), so it can be a launcher's hood. ## AngleDevice An interface for any part that goes to an angle. Its methods: `setDegrees(angle)` (start moving, never wait), `getTargetDegrees()` (NaN before the first command), `isDone()`, and `update()`, `stop()`, `addTelemetry(t)` like any [`Subsystem`](https://crossbotics.com/ftc-helper/docs/modules/core/#subsystem). A [launcher](https://crossbotics.com/ftc-helper/docs/modules/launcher/#launcher)'s hood is an `AngleDevice`, so the launcher does not care what moves it. It can be a `PositionServo` with `degrees(...)`, or the five-files [`Hood`](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/) (a servo or a motor with an encoder, a linkage table). It can also be your own class (a CR servo with an absolute encoder). "Angle" is the part's own scale: degrees, or plain servo positions when you never measured angles. ```java public class MyHood implements AngleDevice { public void setDegrees(double deg) { target = deg; } // never wait here public double getTargetDegrees() { return target; } public boolean isDone() { return Math.abs(encoderDeg() - target) < 0.5; } public void update() { crServo.setPower(0.02 * (target - encoderDeg())); } } launcher.hood(new MyHood(...)); ``` ## SpinServo For a servo in **continuous rotation** mode (set the port as "Continuous Rotation Servo" in the configuration). ```java SpinServo roller = SpinServo.create(hardwareMap, "roller").power(0.8); // hold X = spin forward at 0.8; let go = stop. roller::forward = "() -> roller.forward()" controls.bindHold(Pad.G2, Btn.X, roller::forward).bindRelease(Pad.G2, Btn.X, roller::stop); ``` | Method | What it does | | --- | --- | | `.reversed()`, `.power(p)` | direction and power for forward/backward | | `.angleSensor(hardwareMap, name, maxVolts)` | read the angle from an analog wire (for example, Axon servos) | | `forward()`, `backward()`, `stop()`, `setPower(p)` | spin | | `runFor(seconds, power)` | spin, then stop on its own | | `isRunning()`, `getPower()`, `getAngleDeg()` | read | | `runForStep(seconds, power)` | autonomous step | | `update()` | every loop (needed for `runFor`) | --- # Odometry module URL: https://crossbotics.com/ftc-helper/docs/modules/odometry/ Learn it hands-on: [Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/). Worked example: [`examples/.../odometrybot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/odometrybot). Quick answers with code to copy: [cookbook: odometry and driveTo](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/). **Odometry** tells the robot where it is on the field. Small unpowered wheels, called **pods**, roll on the tiles. They count how far the robot moved forward and sideways. An **optical sensor** under the robot does the same job: it watches the floor go by, like a computer mouse. The library adds up every small move. The result is where the robot is and which way it faces: its **pose** (x, y and heading). **Drive wheels are not enough:** they slip. They spin when another robot pushes yours, and they skid when the robot speeds up. Pods carry no load and do not slip, so they measure what happened. **AprilTags are not enough in BIOBUZZ:** the tags are on the HIVE cells, and the cells move. A tag gives your place compared with the tag, and the tag is not at a fixed place on the field. So this season, odometry tells you where you are ([vision](https://crossbotics.com/ftc-helper/docs/modules/vision/)). | Class | Use it to | | --- | --- | | [`Odometry`](#robotjava-the-odometry-line) | the one line in `Robot.java`: which device, and where it sits | | [`PoseTracker`](#posetracker) | read the pose every loop, set it, check the device (every kind is one) | | [`PinpointOdometry`](#pinpointodometry) | a goBILDA Pinpoint odometry computer with two pods | | [`OtosOdometry`](#otosodometry) | a SparkFun OTOS optical sensor | | [`DeadWheelOdometry`](#deadwheelodometry) | three dead-wheel pods, or two and the IMU, on motor encoder ports | | [`OdometryTunerOpMode`](#the-odometry-tuner) | checks and measures the odometry and shows the lines to copy |
flowchart LR
    D["Pinpoint, OTOS<br/>or dead wheels"] --> T["PoseTracker<br/>(updated first, every loop)"]
    T --> P["robot.pose()<br/>x, y, heading"]
    P --> A["autonomous: driveTo(...)"]
    P --> E["end of autonomous:<br/>the pose goes to TeleOp"]
    P --> F["TeleOp: field-centric<br/>forward"]
--- ## The frame The **frame** is the set of directions that the pose numbers use. The autonomous start spot uses the same frame (`s.start(note, x, y, heading)`, see [Auto](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto)). Stand at your drivers' wall and look at the field: ```text far wall +-----------------------------------+ | y + | | ^ | | | | | x - <--------+--------> x + | (0, 0) = the middle of the field | | | | v | | y - | +-----------------------------------+ your drivers' wall (you) ``` - **x**: inches to the RIGHT of the field's center line. - **y**: inches AWAY from you (negative = your half). - **heading**: degrees. 0 = facing away from you. **Counterclockwise is +**: 90 = facing left, -90 = facing right, 180 = facing you. - The pose is the pose of the robot's **center**: the point it turns around (on a mecanum robot, the middle of the four wheels). The map shows the BIOBUZZ field in this frame, with the example's start, goal and park points. It shows the field from the RED wall. From the BLUE wall the numbers are the same: the field is turned half a turn between the alliances, and `mirrorForRed()` is false. ![The BIOBUZZ field from above in the library's frame: tiles every 24 in from -72 to 72, the HIVEs, FLOWERs, the red loading zone and the example's three points with heading arrows](https://crossbotics.com/ftc-helper/docs/images/biobuzz-field-map.svg) `tools/field_map.py` makes the map from the simulator's field file (`sim/fields/biobuzz-2026.json`). **Where (0, 0) is:** wherever the pose was last set. An `Auto` sets the pose from its start spot after ▶ (start on the Driver Hub). So with `s.start(note, x, y, heading)`, (0, 0) is the middle of the field. With `s.start(note, heading)` (no spot), the robot starts at (0, 0), and x and y count from where it started. **The reason for this frame:** the drivers see the field this way. "Go to x -30, y -30" means the same spot in every autonomous, from every start. --- ## Robot.java: the odometry line One line in `define()`, next to the drive: ```java odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); // goBILDA Pinpoint, 4-bar pods odometry(Odometry.otos("otos").mountIn(0, -3, 0)); // SparkFun OTOS odometry(Odometry.threeWheels("par_left", "par_right", "perp") .trackWidthIn(13.2).perpForwardIn(-6)); // three dead wheels odometry(Odometry.twoWheels("par", "perp").parallelLeftIn(5).perpForwardIn(-6)); // two + the IMU ``` Put `import com.crossbotics.ftchelper.robot.Odometry;` at the top of `Robot.java`. The names are the names in the robot configuration on the Driver Station. Use only one `odometry(...)` line. The line gives you: - `robot.pose()`: where the robot is, every loop ([below](#robotpose)). - `s.driveTo(...)` in autonomous: drive to a field point ([below](#driveto)). - TeleOp starts where autonomous ended, and field-centric "forward" comes from the odometry ([below](#teleop-starts-where-autonomous-ended)). - The simulator gets pretend odometry (`:sim:fromRobot` writes its lines, [below](#the-simulator)). The **offsets** say where the pods (or the sensor) sit, measured from the robot's center. When the robot turns in place, a pod that is not at the center rolls too. The library takes that roll away, but only when it knows how far the pod is from the center. The [Odometry Tuner](#the-odometry-tuner) measures the offsets for you. ### Pinpoint ```java odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); ``` A **goBILDA Pinpoint** is a small computer on an I2C port. Two pods plug into it. The **X pod** measures forward and back, and the **Y pod** measures sideways. The Pinpoint also has its own IMU (a turn sensor). It works out the pose itself, about 1500 times a second. The library reads the answer once per loop. | Setting | Means | Default | | --- | --- | --- | | `pinpoint(name)` | the Pinpoint's configuration name | - | | `offsetsMm(xPodLeftMm, yPodForwardMm)` | where the pods sit, mm (see the sketch) | 0, 0 | | `robotSizeMm(lengthMm, widthMm)` | the frame's size, front to back and side to side (bumpers off). The middle of it is the robot's center. Needed by `podsFromEdgesMm` | - | | `podsFromEdgesMm(forwardPodFromLeftMm, sidewaysPodFromFrontMm)` | the same as `offsetsMm`, measured from the edges: the X pod's wheel from the LEFT edge, the Y pod's wheel from the FRONT edge. The last of the two you write wins | - | | `podsSwingarm()` | goBILDA swingarm pods instead of 4-bar pods | 4-bar pods | | `ticksPerMm(counts)` | other pods: encoder counts per mm of wheel travel | - | | `reversed("x")`, `reversed("y")`, `reversed("x", "y")` | a pod that counts the wrong way (the tuner says which). Names add up over several calls. `"X"` and `"x"` both work. A name that is not a pod stops INIT (`a Pinpoint's pods are "x" and "y"`) | none | The two offsets (goBILDA's own meaning, from the SDK): - **First number:** how far **LEFT** of the center the **X pod** (the forward-measuring one) is. Right of the center = negative. - **Second number:** how far **FORWARD** of the center the **Y pod** (the sideways-measuring one) is. Behind the center = negative. Seen from above, the example robot's `offsetsMm(-84, -168)`: ```text FRONT +-----------------------+ | | | ^ | | C | C = the robot's center | |<-84 mm->[X] X pod (rolls forward/back): 84 mm RIGHT of C -> -84 | 168 mm | | | | | [Y] | Y pod (rolls sideways): 168 mm BEHIND C -> -168 +-----------------------+ BACK ``` **Measure from the edges, not the center.** The center is hard to find on a real robot. Measure from the frame's edges with a tape, and let the library do the math: ```java odometry(Odometry.pinpoint("pinpoint").robotSizeMm(430, 400).podsFromEdgesMm(284, 383)); ``` The robot is 430 mm long and 400 mm wide. So the center is 200 mm from the left edge and 215 mm from the front. The X pod's wheel is 284 mm from the left edge: 84 mm right of the center (-84). The Y pod's wheel is 383 mm from the front edge: 168 mm behind the center (-168). The result is `offsetsMm(-84, -168)`. The [Odometry Tuner](#the-odometry-tuner) then measures the exact offsets. It tells you to write `.offsetsMm(...)` in place of `.podsFromEdgesMm(...)`. Only the X pod's left/right distance matters, and only the Y pod's forward/back distance. A pod on the center line gives 0. For swingarm pods, add `.podsSwingarm()`. For any other pod, add `.ticksPerMm(...)`. ### OTOS ```java odometry(Odometry.otos("otos").mountIn(0, -3, 0)); ``` A **SparkFun OTOS** (Optical Tracking Odometry Sensor) is a small sensor on an I2C port. It looks at the floor like a computer mouse, and it has its own IMU. It needs no pods. It must sit 10 to 12 mm above the tiles. | Setting | Means | Default | | --- | --- | --- | | `otos(name)` | the OTOS's configuration name | - | | `robotSizeMm(lengthMm, widthMm)` | the frame's size (bumpers off). Needed by `mountFromEdgesMm` | - | | `mountFromEdgesMm(fromFrontMm, fromLeftMm, headingDeg)` | the same as `mountIn`, measured from the edges: the sensor's middle from the FRONT edge and from the LEFT edge, mm, and the heading | - | | `mountIn(forwardIn, leftIn, headingDeg)` | where it sits: inches FORWARD of the center (back = negative), inches LEFT (right = negative), and which way the sensor's **Y arrow** points, degrees counterclockwise from the robot's front | 0, 0, 0 | **The heading in `mountIn`:** the OTOS's own axes are x = right and y = forward (as in the SDK's sample). So its **Y arrow** is its forward axis. Heading 0 means the Y arrow points to the robot's front. Turn the sensor so its **X arrow** points forward, and its Y arrow points left: that is **90** (counterclockwise). A Y arrow that points right is -90. `OtosOdometry` sends the offset to the OTOS as `(-leftIn, forwardIn, headingDeg)`. Nobody has checked this on a robot yet. If a push forward shows up as sideways in the `Pose` line, try the other sign. The tuner does not measure where an OTOS sits. Measure it from the robot's edges with a tape, and write `robotSizeMm(...).mountFromEdgesMm(...)`: for example `robotSizeMm(430, 400).mountFromEdgesMm(126, 200, 0)` is `mountIn(3.5, 0, 0)`. The OTOS's two scale numbers are in [`Tunables.Odometry`](#tunablesodometry). ### Three dead wheels ```java odometry(Odometry.threeWheels("par_left", "par_right", "perp").trackWidthIn(13.2).perpForwardIn(-6)); ``` **Dead wheels** are pods with no computer: each pod's encoder plugs into a motor port's encoder connector. Two pods measure forward (one left of the center, one right), and one measures sideways. The library works out the pose from their counts every loop. The names are the motor ports' configuration names, in this order: left forward pod, right forward pod, sideways pod. | Setting | Means | Default | | --- | --- | --- | | `trackWidthIn(inches)` | the distance between the left and right forward pods (required) | - | | `perpForwardIn(inches)` | how far FORWARD of the center the sideways pod is (back = negative) | 0 | | `podsSwingarm()`, `ticksPerMm(counts)` | the pods' encoder counts per mm | goBILDA 4-bar pods | | `reversed(names...)` | the pods that count the wrong way, by port name | none | The library takes the two forward pods' average as the forward move. So put them the same distance from the center, one on each side. ```text FRONT +-----------------------+ | | | [L] C [R] | L and R roll forward/back; trackWidthIn = L to R | | | [P] | P rolls sideways: perpForwardIn = -(C to P), behind = negative +-----------------------+ ``` A pod's port can still drive a motor. The pod's encoder cable takes the place of that motor's encoder, and the library only reads the count. So a motor on that port loses its own encoder. ### Two dead wheels and the IMU ```java odometry(Odometry.twoWheels("par", "perp").parallelLeftIn(5).perpForwardIn(-6)); ``` This kind uses one forward pod, one sideways pod, and the Control Hub's IMU for the heading. It needs the IMU in the drive line (`drive(...).imu(...)`). The odometry sets the IMU up and zeroes it at INIT. | Setting | Means | Default | | --- | --- | --- | | `parallelLeftIn(inches)` | how far LEFT of the center the forward pod is (right = negative) | 0 | | `perpForwardIn(inches)` | how far FORWARD of the center the sideways pod is (back = negative) | 0 | | `podsSwingarm()`, `ticksPerMm(counts)`, `reversed(names...)` | as for three wheels | - | **To choose a kind:** a Pinpoint is the easiest. The device works out the pose 1500 times a second, and the library reads it once per loop over I2C. Three dead wheels need no extra computer, but they use three encoder ports. Two wheels save a port, but they trust the IMU for turning. An OTOS has no wheels to mount. But its height above the tiles matters, and you must measure its scale numbers. ### Your own pose source: Odometry.custom ```java odometry(Odometry.custom(devices -> new MyPoseTracker(devices.get(MyDevice.class, "my_device")))); ``` Use this for a pose from somewhere else, like odometry fused with AprilTags, or another library's localizer (the code that works out the pose). Your class extends [`PoseTracker`](#posetracker) (`read()`, `write()`, `isReady()`, `status()`, `kind()`). The library makes it at INIT from the robot's devices. `robot.pose()`, `driveTo` and the hand-off to TeleOp use it like the built-in kinds. **It must use the library's frame** ([above](#the-frame)). `PoseTracker`'s `read()` and `write()` work in the device frame (X forward, Y left), and the library turns them for you. The simulator has no pretend device for it (`:sim:fromRobot` writes only a comment), and the Odometry Tuner does not measure it. These mistakes stop INIT with a message: a setting for another kind (`mountIn` on a Pinpoint), three wheels with no `trackWidthIn`, two wheels with no IMU, a device name used twice, an empty name, a `reversed(...)` name that is not a pod (`the pods are [par_left, par_right, perp]`), and a `custom(...)` that makes nothing (null). --- ## Tunables.Odometry ```java public static class Odometry { public static boolean checked = false; public static double linearScalar = 1.0, angularScalar = 1.0; // OTOS only } ``` | Field | Means | Default | | --- | --- | --- | | `checked` | set it `true` by hand after the Odometry Tuner's Loop test passes. Until then, a real robot skips `driveTo` steps | false | | `linearScalar` | OTOS only: distance scale (the tuner's Forward test measures it; allowed 0.872 to 1.127) | 1.0 | | `angularScalar` | OTOS only: turning scale ([measure it by hand](#otos-turn-scale-by-hand); 0.872 to 1.127) | 1.0 | The odometry reads them once, at INIT. They are not in the tuning menu: change them in `Tunables.java` and rebuild. **The reason for a switch you set by hand** is the same as for `Tunables.Drive.calibrated`. A pod that counts the wrong way makes `driveTo` drive the wrong way, at speed. So the library does not drive to points until a person has seen the Loop test pass. The simulator is the exception: there `driveTo` runs anyway. --- ## robot.pose() ```java FieldPose p = robot.pose(); // x, y in inches; headingDeg ``` `robot.pose()` gives where the robot is now, in [the frame](#the-frame): `p.x`, `p.y` and `p.headingDeg`. It is a copy ([`FieldPose`](https://crossbotics.com/ftc-helper/docs/modules/util/#fieldpose)): a change to it does not move the robot. It is `null` when `Robot.java` has no `odometry(...)` line. Every loop, the odometry adds a line labeled `Pose` to the Driver Station by itself: `x -30.0, y -30.0 in, heading 45.0`. When the device is not ready, a warning goes above it. To show the pose your own way, add a line to `Controls.java`: ```java show("Where", robot::pose); // "(-30.0 in, -30.0 in, 45.0 deg)" ``` `robot.odometry()` gives the running [`PoseTracker`](#posetracker) (null before INIT, or with no odometry line). `robot.odometrySpec()` gives the line as written. `robot.odometryChecked()` reads `Tunables.Odometry.checked`. --- ## Camera fix (alpha) > **ALPHA. NOT TESTED ON A ROBOT. OFF BY DEFAULT. NOT FOR BIOBUZZ.** > BIOBUZZ's only field tags are under the CELLs, facing down, and each HIVE tips 30 degrees as it fills. > The tags move during the match. So a position worked out from them is wrong whenever a HIVE tips. > Aiming with those tags works: aiming needs the direction, and not the robot's place. The camera fix is > for a season with fixed wall tags. Try it only to help test it, and tell us what you see. `cameraFix(camera)` in `Robot.java` (`CameraPoseFix`, `CameraFixCheckOpMode`) corrects the odometry's x and y. It uses the field position that a Limelight 3A works out from the AprilTags (MegaTag2). It uses last season's lessons. Last season's version never worked, for three reasons. The odometry itself lost distance, the heading never reached the camera, and the field directions were guesses ([From last season](https://crossbotics.com/ftc-helper/docs/from-last-season/)). - **The odometry must be right on its own first:** a 48 in move reads 48 in (the Drive Tuner, the Odometry Tuner). The camera only corrects small drift. - **The fix smooths only the camera's correction** (`blend`, a fifth of the difference per picture). It never smooths the wheel moves. - **The fix compares each picture with where the robot was when the camera took it**, and not with where the robot is now. - **The fix refuses:** an old picture (`maxAgeMs`), a repeated one, fewer than `minTags` tags, the robot moving or turning fast, a jump bigger than `maxJumpIn`, a pose that was never set, and a mirrored RED field. - **The heading goes to the Limelight** every loop (`updateRobotOrientation`, in the background), turned into its field frame. - **A debug line says what happened** to each picture: `Camera fix (ALPHA): used +1.2, -0.4 in (4 tags, 1.3 in off)` or `refused: moving`. INIT says `Camera fix: ALPHA, NOT TESTED ON A ROBOT, off (Tunables.CameraFix.enabled = false). Not for BIOBUZZ: its tags move with the HIVE`. ```java camera = add(Camera.limelight("limelight").goal("BLUE SCORING", "RED SCORING")); odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); cameraFix(camera); // Robot.java (alpha) public static class CameraFix { // Tunables.java public static boolean enabled = false; // true to try it public static double turnDegBlue = 0, turnDegRed = 0; // the Camera Fix Check finds them } ``` **The field directions** are the turn from the Limelight's field frame to ours, a multiple of 90 degrees. A test finds them: the **Camera Fix Check**. It is not in Tune and check (the camera fix is alpha, and not for BIOBUZZ), so run it from a file of your own. **Where:** a new file in TeamCode, next to Robot.java. ```java title="CameraFixCheck.java" @TeleOp(name = "Camera Fix Check", group = "Finders") public class CameraFixCheck extends CameraFixCheckOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` Put the robot on the field facing away from your drivers' wall, with tags in view. The test shows the Limelight's own pose, the turn that fits, and the robot's place with that turn. Check the place with a tape measure. X saves the turn for BLUE, and B saves it for RED. The Limelight's pipeline (a set of camera settings saved on the Limelight) needs Full 3D and the right tag size ([Limelight lighting pipelines](https://crossbotics.com/ftc-helper/docs/guides/limelight-lighting/)). | `Tunables.CameraFix` | What it does | Default | | --- | --- | --- | | `enabled` | on or off | false | | `turnDegBlue`, `turnDegRed` | the turn from the Limelight's field frame to ours (Camera Fix Check) | 0 | | `maxAgeMs` | the fix skips a picture older than this | 100 | | `maxSpeedInPerSec`, `maxTurnDegPerSec` | the fix skips pictures while the robot moves or turns faster | 20, 30 | | `maxJumpIn` | the fix refuses a bigger difference | 12 | | `blend` | how much of the difference the fix applies, per picture | 0.2 | | `minTags` | the fix skips a picture with fewer tags | 2 | ## PoseTracker Every kind of odometry is a `PoseTracker`, so your code reads them all the same way. | Method | What it does | | --- | --- | | `update()` | reads the device once and works out the new pose. The robot calls it for you, first, once per loop | | `pose()` | this loop's pose (a copy) | | `setPose(FieldPose)` | says "the robot is here now". Autonomous does this from its start spot, and TeleOp from where autonomous ended. When the device is not ready yet (a Pinpoint still calibrating in TeleOp's INIT), the tracker keeps the pose and writes it to the device as soon as the device is ready | | `isPoseSet()` | whether `setPose` was called. Until then the pose is only "(0, 0) where it was turned on", and not a place on the field. So [aiming by odometry](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/) stays off | | `unsetPose()` | says "the pose is not known any more". `isPoseSet()` becomes false (the numbers stay), so aiming by odometry stays off until the pose is set again. TeleOp does this when the driver switches the alliance on a field that is not mirrored ([buttons guide](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/#switching-the-alliance-in-teleop)) | | `setHeading(deg)` | the way the robot faces now becomes this heading, and x and y stay (TeleOp's "forward = away from you now"). It does not count as setting the pose | | `speedInPerSec()`, `turnDegPerSec()` | how fast it moves (in/s) and turns (deg/s, counterclockwise +). A Pinpoint or OTOS gives it. For dead wheels, the library works it out from how far the robot moved between loops. It smooths it over about 0.06 s, so it is a little behind | | `velocityX()`, `velocityY()` | which way it moves over the field, in/s: toward +x (right, seen from your drivers' wall) and +y (away), whichever way the robot faces. A Pinpoint and an OTOS give it over the field directly. Dead wheels work as above. [Shooting on the move](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/) uses it | | `useClock(nanos)` | tests: a pretend clock for the dead-wheel speed | | `isReady()` | whether the device works and gives a pose | | `status()` | words for the Driver Station (table below) | | `kind()` | "Pinpoint", "OTOS", "three dead wheels" or "two dead wheels + IMU" | | `name()`, `addTelemetry(t)` | the [Subsystem](https://crossbotics.com/ftc-helper/docs/modules/core/#subsystem) parts: the `Pose` line, and a warning when the device is not ready | `status()` and the warning: | Kind | Status | Means | | --- | --- | --- | | Pinpoint | `ready` | working | | Pinpoint | `calibrating (keep the robot still)` | its IMU is starting: do not move the robot | | Pinpoint | `starting up` | it has only now powered on | | Pinpoint | `X pod not found: check its cable`, `Y pod not found: check its cable`, `no pods found: check both cables` | a pod is unplugged | | Pinpoint | `IMU fault: power the robot off and on` | its IMU stopped working | | Pinpoint | `bad reading (I2C cable?)` | a garbled answer: check the I2C cable | | Pinpoint | `no answer` | no status at all | | OTOS | `ready` / `not answering: check the I2C cable and the configuration` | checked at INIT, then again once a second | | Dead wheels | `ready` | always. An encoder cannot say that it is unplugged: the Odometry Tuner's counts show it | A device that is not ready does not stop the program: the warning tells the drive team. An autonomous also reads the odometry in INIT. It shows `Odometry: Pinpoint ready`, or a warning such as `Odometry (Pinpoint): X pod not found: check its cable`. So the drive team sees a missing pod before ▶. **How the frames fit (for veterans).** Inside, `PoseTracker` works in one shared device frame: X forward and Y left at heading 0. The goBILDA Pinpoint and the dead-wheel math use this frame. The library's frame is a quarter turn from it: our x (right) = -Y, our y (away) = X, and the heading is the same. `PoseTracker` turns one into the other in `update()` and `setPose()`. The SparkFun OTOS's own axes are different again: x = right, y = forward (as in the SDK's sample). `OtosOdometry` converts its position, speed and mounting offset to the shared frame. So `mountIn(forward, left, heading)` stays forward and left. Your code only sees the drivers' frame. ### PinpointOdometry The robot layer makes it for you. To make it without the five files: ```java GoBildaPinpointDriver pp = hardwareMap.get(GoBildaPinpointDriver.class, "pinpoint"); PoseTracker odo = new PinpointOdometry("pinpoint", pp, -84, -168, GoBildaPinpointDriver.GoBildaOdometryPods.goBILDA_4_BAR_POD, 0, false, false); // every loop: odo.update(); FieldPose p = odo.pose(); ``` The arguments: name, device, X pod mm left, Y pod mm forward, pod type (or `null` to use the next number), counts per mm (only when the pod type is `null`), X reversed, Y reversed. The constructor zeroes the Pinpoint and its IMU (`resetPosAndIMU()`). So the robot must stay still for about a quarter second, as it does in INIT. For anything else, `device()` gives the SDK's `GoBildaPinpointDriver`. ### OtosOdometry ```java SparkFunOTOS sensor = hardwareMap.get(SparkFunOTOS.class, "otos"); PoseTracker odo = new OtosOdometry("otos", sensor, 0, -3, 0, 1.0, 1.0); ``` The arguments: name, device, inches forward, inches left, its heading, linear scale, angular scale. The constructor sets inches and degrees, the mounting offset and the scales. It also calibrates the OTOS's IMU and zeroes it, so the robot must stay still. `device()` gives the SDK's `SparkFunOTOS`. ### DeadWheelOdometry ```java PoseTracker odo = DeadWheelOdometry.threeWheels("odometry", left, right, perp, 505.3, 13.2, -6, false, false, false); // counts per inch, track width, perp forward, reversed x3 PoseTracker odo2 = DeadWheelOdometry.twoWheels("odometry", par, perp, () -> imuHeadingDeg(), 505.3, 5, -6, false, false); // + the heading, counter-clockwise + ``` The pods are `DcMotorEx` ports, and the library reads only `getCurrentPosition()`. 505.3 counts per inch is a goBILDA 4-bar pod (19.894 counts per mm). The math each loop: - With three wheels, the turn is (right - left) / track width, and the forward move is their average. - With two wheels, the turn comes from the IMU, and the library takes away the forward pod's roll during the turn. - The library also takes away the sideways pod's roll during the turn. - Then it turns the move into the field frame, with the heading halfway through the turn. ### Escape hatches (for veterans) When the five files do not cover what you need: | Use | What you get | | --- | --- | | `robot.odometry()` | the running `PoseTracker` (null before INIT, or with no odometry line) | | `((PinpointOdometry) robot.odometry()).device()` | the SDK's `GoBildaPinpointDriver` (raw encoder counts, its own status, its loop rate) | | `((OtosOdometry) robot.odometry()).device()` | the SDK's `SparkFunOTOS` | | `Odometry.custom(devices -> ...)` | your own pose source in place of the built-in kinds ([above](#your-own-pose-source-odometrycustom)) | | `AutoRoutine.driveTo(label, poseSupplier, readySupplier, x, y, heading, maxPower, toleranceIn)` | `driveTo` on any pose you supply, outside the five files. It stops with `NO_ODOMETRY` when `readySupplier` stays false for 0.2 s. Leave `readySupplier` out, and it always trusts the pose | --- ## What runs every loop - **The odometry updates first,** before every other part and before the actions (`RobotDefinition.setup` adds it first). So every part, every action and every `driveTo` reads this loop's pose. - **Pinpoint:** one I2C read per loop. `update()` on the driver reads position, speed and status in one go. The Pinpoint does its own math 1500 times a second, so the loop's speed does not change its accuracy. - **OTOS:** two I2C reads per loop (position, then speed). - **Dead wheels:** one encoder read per pod (part of the hub's bulk read), and the library's math. - **Two dead wheels:** one IMU read per loop on top of that. The IMU is not part of a bulk read. - **In INIT** the odometry does not update (the same as every part). **While paused** (BACK), the library does not read it either. A Pinpoint or OTOS keeps counting on its own, and dead wheels catch up on the next loop. More: [What runs every loop](https://crossbotics.com/ftc-helper/docs/guides/every-loop/). --- ## driveTo ```java s.start("Against our wall, in the left corner tile, facing the field", -56, -61, 0) .driveTo("To the goal", -30, -30, 45, 0.6) // x, y, heading, max power .driveTo("Park", -56, -36, 0, 0.7, 2.0); // last number: "close enough", inches (default 1) ``` `driveTo(label, xIn, yIn, headingDeg, maxPower)` drives to a point on the field and turns to a heading at the same time. It is a [Steps](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto) step (and an `AutoRoutine` and `AutoDrive` method underneath). It works only on mecanum, because it drives sideways. On a tank drive, INIT stops with `Steps: driveTo("...") needs a mecanum drive (it drives sideways)...`. So you find out before the match, and not in the middle of it. On a tank drive, use `turnTo` and then `move`. How it drives, every loop: 1. It reads the pose. It works out how far the point is, and turns that into "forward" and "right" for the robot. 2. **Far away:** it sets the speed like a `move`: up to `maxPower`, slower as it gets close, but never less than `Tunables.Drive.moveMinPower`. 3. **In the last 8 inches:** it sets the speed in proportion to the distance left. That is 0.04 power per inch, at least 0.12 (`AutoDriveConfig.driveToNearIn`, `driveToKp` and `driveToMinPower`). So it settles on the point and does not circle it. 4. **The heading:** it corrects the heading all the way with the drive's turn numbers (`turnKp`, `turnKd` in `Tunables.Drive`). While the heading is off, the turn power is at least `AutoDriveConfig.turnMinPower` when that is set (more than 0), or else 0.08. So a weak turn cannot stop a bit short (`Tunables.Drive.turnMinPower`; the Move Tuner finds it). 5. **Done:** it is within the **tolerance** ("close enough": 1 inch unless you give one). It is also within 2 degrees of the heading (or the drive's `turnToleranceDeg`, if that is bigger). Both must be true for 3 loops in a row, so passing by does not count. **If the odometry stops working** during a `driveTo`, `isReady()` becomes false. A Pinpoint fault (like an unplugged pod) or an OTOS that stops answering does this. A short glitch does no harm: the robot holds still and waits up to 0.2 s. If the odometry is still not ready, the step ends with the report word `NO_ODOMETRY`. On a frozen pose, the robot would never arrive, and it would push on until the time ran out. The library checks the OTOS's connection again once a second. It also ends early: - `STALLED` when it is stuck. Farther than 8 inches from the point, the rule is the same as a `move`: less than 0.25 in closer in 0.4 s. In the last 8 inches, where it is slow on purpose, the rule is less than 0.1 in closer in 2 s. - `TIMED_OUT` after 10 s. - `STOPPED` on STOP or park time. The report shows the word. **After any of these, the autonomous goes on with its next steps**, from wherever the robot is. So put a mechanism action that needs the right place right after the `driveTo` that gets it there. Check the report after practice runs. A `driveTo` that did not say `done` means the next steps started from the wrong place. In your own `step(...)`, you can check `robot.pose()` before an action. **`driveTo` is better than `move` with odometry.** A `move` counts the drive wheels. After a bump, a slip or a push, every later step is off. `driveTo` checks the real pose every loop and keeps correcting. So it ends at the field point, wherever the bump left the robot. And each point is a place on the field, so a change to one step does not shift the steps after it. **Its rules:** - It needs an `odometry(...)` line in `Robot.java`. Without one, INIT stops: `Steps: driveTo("To the goal") needs odometry: add an odometry(...) line to Robot.java (docs/modules/odometry.md)`. - On a real robot it needs `Tunables.Odometry.checked = true`. Until then the step does nothing, and the report says `To the goal: skipped: Tunables.Odometry.checked is false (run the Odometry Tuner first)`. In the simulator it runs anyway. - Like every step, it needs a tuned drive (`Tunables.Drive.calibrated = true`). - **RED:** you write the numbers for BLUE, like the start spot. With `mirrorForRed()` true (the default), RED flips x and the heading (x -30 becomes x 30, heading 45 becomes -45), and y stays. With `mirrorForRed()` false (BIOBUZZ: the field is turned half a turn), RED uses the same numbers, seen from the red wall. - Use the start spot (`s.start(note, x, y, heading)`) with it: the pose starts there. Without a spot, the pose starts at (0, 0) where the robot stands, and the points count from there. **`turnTo` and `driveTo` use different headings.** `turn` and `turnTo` use the Control Hub's IMU, with 0 = the way the robot faced at the start. `driveTo` uses the field heading from the odometry, with 0 = facing away from your wall. They agree only when the start heading is 0. Take `s.start(note, x, y, 90)`: `turnTo(..., 0, ...)` turns back to the start direction, which is field heading 90. But `driveTo(..., 0, ...)` faces away from your wall. **With odometry, give headings in `driveTo`** (field numbers, like the points). If you also use `turnTo`, remember that its 0 is the start. Every step: [driveTo](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/#drive-to-a-point-driveto). --- ## Keep-out boxes and routes `driveTo` drives one straight line. That works when you know where the line starts. But `parkWithSeconds` can stop the robot at any place in the middle of a step. Then you do not know where the line starts, and the line can go through a field element. A **route** goes around such places. The robot works out the route when it sets off, from where it is at that moment. **1. List the boxes in `Robot.java`.** Each box is two opposite corners, in `driveTo`'s numbers, written for BLUE. The library knows no game, so you choose the numbers. ```java odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); fieldMap(FieldMap.margin(13) .keepOut("HIVE frame, near", -19.5, -24.8, 19.5, -15.4) .keepOut("HIVE frame, far", -19.5, 15.4, 19.5, 24.8)); ``` **The margin** is how far the robot's center stays from every box. Make it half the robot's corner to corner size, plus some for odometry drift (the error that grows as the robot drives). For an 18 x 18 in robot, that is 13 in. A bigger margin is safer, but it closes small gaps between boxes. With a margin of 13, the 30.8 in gap between these two frames leaves a path 4.8 in wide for the robot's center. A route's corners also stay inside the walls by the margin. A path less than 2.5 in wide needs a `.safePoint(x, y)` at each end. The boxes' corners do not fit in it, so without the safe points the route says `no route`. **2. Use it in an autonomous.** `routeTo` takes the same numbers as `driveTo`. ```java s.start("Against our wall, in the left corner tile, facing the field", -56, -61, 0) .driveTo("To the goal", -30, -30, 45, 0.6) .parkWithSeconds(6) .routeTo("Park", -56, -36, 0, 0.8); ``` **3. Or use it in TeleOp.** In `Controls.java`, `route(...)` makes a job. A button or a time starts it. ```java Runnable park = route("Park", -56, -36, 0, 0.8); g1.dpadLeft.tap(park).says("drive to the park spot (a drive stick stops it)"); atSecondsLeft(10, park); ``` **How the robot finds the route.** It tries the straight line first. If the line crosses a box (with the margin added), the robot goes around the boxes' corners by the shortest way of straight lines. It slows down at each corner, but it does not stop there. It goes on up to 2 in early, or after it slid past the corner by up to 8 in. (In the simulator, at power 0.7, the robot slid about 6 in past a corner.) It does this only if the line from where it is to the next point misses every margin. If not, it drives back to the point first. So list what stands near the corners too. To make routes go your way, add `.safePoint(x, y)`: a place a route may pass through, at least 0.5 in outside every margin. A robot that stands inside a margin first goes out by the nearest side. **A spot right next to a box** (a place to score, inside the margin) is allowed. The robot first goes to a point outside the margin, then straight in. Only that last line is inside the margin, so check it on the robot. A spot on the box itself stops INIT. So does a spot with no way in from outside. **A spot near a wall:** the library does not know your robot's size. When a spot is closer to a wall than half your robot, the robot presses against the wall, and the route ends `STALLED`. **In TeleOp, the driver always wins:** - **Any drive stick stops the route at once**, and the sticks drive from that loop on. The Driver Station says `Park: stopped: a drive stick moved`. - **A route that `atSecondsLeft(...)` starts does not take the robot from a driver who is driving.** If the driver pushes a stick at that time, the gamepad buzzes, and the Driver Station says `Park: waiting: let go of the drive sticks to start it`. The route starts on the first loop after the driver lets go of the sticks. After 5 s it gives up: `Park: not started: the driver kept driving`. It waits no longer because a driver who parked by hand and lets go at the last moment must not see the robot drive off. Pause and the tuning menu make it wait the same way. If the match ends first, it does not start: `Park: not started: the match is over`. - Pause and the tuning menu stop it too. It does not set off again by itself. - It never waits: the rest of the robot keeps running. The robot refuses "Set pose here" while a route drives. - `Park: there` says it arrived. It also ends on `STALLED`, `TIMED_OUT` (10 s on one line of the route) or `NO_ODOMETRY`, the same words as `driveTo`. - The sticks' slow button and reverse drive do nothing to a route. Whole-robot aim does not turn the robot during a route. **When it does not set off:** | Where | The words | Why | | --- | --- | --- | | INIT stops | `needs a map`, `needs odometry`, `needs a mecanum drive` | a line is missing in `Robot.java` | | INIT stops | `... is on "HIVE frame, near"` | the spot you gave is on a box: move it | | INIT stops | `... and a robot cannot drive in from outside` | other boxes close every way to that spot: move it, or use a smaller margin | | Report, or Driver Station | `no route` | boxes close every way. The robot stays where it is | | Report, or Driver Station | `no pose` / `the pose is not set` | nothing set the pose ([set pose here](#tunablesodometry), or a start spot with x and y) | | Report, or Driver Station | `Tunables.Odometry.checked is false` | run the [Odometry Tuner](#the-odometry-tuner) first (in the simulator it runs anyway) | | Driver Station | `Tunables.Drive.calibrated is false` | run the Drive Tuner first (in the simulator it runs anyway) | | Driver Station | `the driver kept driving` | a time started it, and a drive stick stayed pushed for 5 s | When `Controls.java` has a `route(...)`, the INIT screen warns about the two tuners' words. So you find out before the match. These two switches are true/false lines in `Tunables.java`. The tuning menu does not show them: change them in the file. **Its limits.** It uses only the odometry's numbers, and it cannot see. **Another robot is not on the map**, and a wrong pose gives a wrong route. If the robot hits something, the stuck check ends the route (`STALLED`), and the robot does not reach the spot. Make the first test slow, and stand by to stop it. **RED:** you write the numbers for BLUE, like `driveTo`. With `mirrorForRed` true, RED drives the mirror image of the route (x and the heading flip). With it false (BIOBUZZ), RED uses the same numbers from the red wall. More: [`FieldMap` and `RouteDriver`](https://crossbotics.com/ftc-helper/docs/modules/drive/#fieldmap), the [cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-get-around-field-elements-on-the-way-to-a-spot). --- ## TeleOp starts where autonomous ended 1. **Autonomous, at ▶:** the first step ("Start") sets the pose from the start spot (mirrored for RED like the routes). 2. **Autonomous end** (done, STOP or an error, after ▶): the library saves the whole pose (`robot.pose()`) in [`MatchMemory`](https://crossbotics.com/ftc-helper/docs/modules/match/#matchmemory) / [`PoseStore`](https://crossbotics.com/ftc-helper/docs/modules/util/#posestore). 3. **TeleOp INIT** (`Controls.java`): if autonomous left a pose in the last 5 minutes, the odometry starts there. Otherwise it starts at (0, 0, 0) where the robot stands. 4. **Field-centric "forward"** comes from the odometry's heading. The odometry's heading carries on from autonomous with nothing added, and the Pinpoint's and OTOS's IMUs are made for this job. With field-centric on, holding BACK for 1 s makes "forward" the way the robot faces now. The press of BACK also pauses the robot at once, and the robot stays paused after the reset: tap BACK to go on. The reset changes only the driver's "forward". The pose does not change, so aiming at a field point stays right. --- ## The simulator The simulator has a pretend Pinpoint, OTOS and dead wheels. They measure the robot's true motion, so `robot.pose()`, `driveTo` and the Odometry Tuner work there. `./gradlew :sim:fromRobot` writes the lines from `Robot.java` (they end with `# from Robot.java`). You add the noise lines yourself. They show why `driveTo` keeps correcting. | Robot-file line | Default | Means | | --- | --- | --- | | `odometry = pinpoint NAME` (or `otos NAME`, `threeWheels L, R, P`, `twoWheels PAR, PERP`) | none | the kind and the configuration name(s) | | `odometry.offsetsMm = X, Y` | 0, 0 | Pinpoint: where the pods sit (as `offsetsMm`). They set the pretend pods' raw counts, which the tuner's Spin test reads | | `odometry.mountIn = F, L, H` | - | OTOS: as `mountIn`. The pretend OTOS already reports the center's pose, so it does not change the simulation | | `odometry.trackWidthIn` | 12 | three wheels: left to right pod | | `odometry.parallelLeftIn` | 0 | two wheels: the forward pod, inches left | | `odometry.perpForwardIn` | 0 | dead wheels: the sideways pod, inches forward | | `odometry.ticksPerIn` | 505.3 (4-bar pods) | dead wheels: pod counts per inch | | `odometry.reversed = names` | none | these pods count backward, as wired (the code's `reversed(...)` turns them back): dead-wheel port names, or `x`/`y` for a Pinpoint's pods | | `odometry.scaleError = 0.01` | 0 | noise: it measures 1% too far (wheel slip, a wrong pod size) | | `odometry.driftDegPerMin = 0.5` | 0 | noise: the heading creeps this much per minute | The tools also turn a Pinpoint or OTOS in the robot configuration XML into an odometry line. `./gradlew :sim:fromConfig` writes `odometry = pinpoint NAME` (and `odometry.offsetsMm = 0, 0` with a TODO). `./gradlew :sim:newRobot` writes the `odometry(...)` line in `Robot.java` and a `Tunables.Odometry` section with `checked = false`. They use only the first one they find. An `Odometry.custom(...)` line has no pretend device: `:sim:fromRobot` writes only a comment for it. Details: [simulator guide](https://crossbotics.com/ftc-helper/docs/reference/robot-file/#every-setting). --- ## The Odometry Tuner `OdometryTunerOpMode` (package `com.crossbotics.ftchelper.finders`) checks and measures the odometry of the robot in five files. Give it your robot in a small file next to `Robot.java`: ```java package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.crossbotics.ftchelper.finders.OdometryTunerOpMode; import com.crossbotics.ftchelper.robot.RobotDefinition; @TeleOp(name = "Odometry Tuner", group = "Finders") public class OdometryTuner extends OdometryTunerOpMode { @Override protected RobotDefinition robot() { return new Robot(); // your Robot.java, with its odometry(...) line } } ``` The sticks drive slowly (30%) in every test. D-pad up/down chooses a test, **A** starts it, and **B** ends it. GUIDE shows help (or hold the gamepad's START button for 1 s). Each test starts the pose at (0, 0, 0). | Test | You do | It finds | | --- | --- | --- | | 1 Forward 48 in | push or drive the robot 48 in straight forward along a tape, B | the forward pod's direction, and how far off the distance is (sideways drift too). OTOS: `Tunables.Odometry: linearScalar = ...` (multiply it with the one in use). Pods more than 2% off: check the pod type (Pinpoint) or `ticksPerMm(...)` (dead wheels), and the tape. More than 10% off: "was it really 48 in?" The mistake is in the test, and not in the pods, so there is nothing to copy | | 2 Left 24 in | push or drive it 24 in straight to its LEFT, B | the sideways pod's direction (a tank robot: push it) | | 3 Spin 3+ turns | turn it in place at least 3 times (right stick), B | only the numbers to change: `Robot.java: in the odometry(...) line, .offsetsMm(-84.2, -167.5)`, or `.trackWidthIn(..).perpForwardIn(..)` (three wheels), or `.parallelLeftIn(..).perpForwardIn(..)` (two). `.reversed(...)` and the pod type stay as written. OTOS: no offsets ([turn scale by hand](#otos-turn-scale-by-hand)) | | 4 Loop and back | start on a tape mark, drive anywhere, come back onto the mark facing the same way, B | within 1 in and 2 degrees: `Tunables.Odometry: checked = true` | When a pod counts the wrong way, the Forward or Left test says so. It also says which name to put in (or take out of) `.reversed(...)`. On a Pinpoint, the Spin test measures the turn from the odometry's own heading. For dead wheels and the OTOS, it uses the Control Hub's IMU. So dead wheels and the OTOS need the IMU in the drive line (`drive(...).imu(...)`). Without it, the tuner stops at INIT with `the Odometry Tuner's Spin test needs the IMU: add .imu(...) to drive(...)`. Copy the lines (the tuner also saves them in `finder-results.txt` at STOP), rebuild, and run Loop. The full walk-through: [Odometry Tuner](https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/). ### OTOS turn scale by hand The tuner does not measure an OTOS's `angularScalar`, so measure it by hand: 1. Put the robot on a tape mark, square to a tile seam. Run the tuner (or any TeleOp that shows the pose). 2. Start the Spin test (it zeroes the pose). Turn the robot LEFT (counterclockwise) exactly 10 whole turns, slowly, and stop square to the seam again. 3. Read the heading `h` (it should be 0). 4. New `angularScalar` = old × 3600 / (3600 + h). For example, `h` = 18 means it counted 3618 degrees, so 1.0 × 3600 / 3618 = 0.995. Use 10 turns because a 1% error is only 3.6 degrees after one turn: too small to read. After 10 turns it is 36 degrees. --- ## Questions for veterans What the code shows, and what is **not yet checked on a robot**: - **Whether `getEncoderX()`/`getEncoderY()` include the Pinpoint's direction setting:** the tuner's Spin test assumes they do **not**. It reads the raw counts and flips a pod in `.reversed(...)` itself. Nobody has checked this on a robot yet. If the raw counts are already flipped, the Spin test gives a reversed pod's offset the wrong sign, and the Loop test then fails. - **Whether `setPosition` sticks while the Pinpoint is calibrating:** the library does not depend on it. The tracker keeps a pose set while the device is not ready, and writes it once `isReady()` is true ([`setPose`](#posetracker)). Nobody has checked on a robot whether the device would have kept it. - **Whether a pod unplugged in the middle of a match shows up:** the Pinpoint has fault statuses (`X pod not found`, `Y pod not found`, `no pods found`, `IMU fault`, `bad reading`). The library shows them as a warning, and ends a `driveTo` with `NO_ODOMETRY` after 0.2 s of not ready. Nobody has checked on a robot whether the Pinpoint reports a pod pulled out while it runs (and not only at power-up). Dead wheels cannot tell at all: an unplugged encoder stops counting. - **The field heading for TeleOp's field-centric, and not the IMU:** the field heading carries on from autonomous with nothing added ([above](#teleop-starts-where-autonomous-ended)). --- ## If something goes wrong | What you see | Why, and what to do | | --- | --- | | `Pinpoint: X pod not found` (or Y, or both) | the pod's cable is out of the Pinpoint, or in the other port | | `Pinpoint: calibrating (keep the robot still)` stays | the robot moved during INIT: hold it still, or INIT again | | `OTOS: not answering` | the I2C cable, or the configuration name or type | | The pose goes up when it should go down | a pod counts the wrong way: run the tuner's Forward and Left tests | | The pose drifts when the robot only turns in place | the offsets are wrong: run the Spin test | | x and y look swapped | the pods are in the wrong ports (Pinpoint: X = forward pod), or the OTOS's `mountIn` heading is wrong | | `skipped: Tunables.Odometry.checked is false` | run the tuner's Loop test, then set `checked = true` | | `driveTo` goes to the mirror spot on RED | `mirrorForRed()`: false on a turned field (BIOBUZZ) | | `driveTo` ends with `NO_ODOMETRY` | the odometry was not ready for more than 0.2 s during the drive: read its warning (a pod cable, the I2C cable). The next steps still ran | | INIT stops: `odometry .reversed("...")` | a name that is not a pod: a Pinpoint's are `"x"` and `"y"`, dead wheels' are their port names | | The tuner stops at INIT: `needs the IMU` | dead wheels or an OTOS: add `.imu(...)` to `drive(...)` | | `turnTo(0)` and `driveTo(..., 0, ...)` face different ways | `turnTo` uses the IMU with 0 = the start direction; `driveTo` uses the field heading ([driveTo](#driveto)) | | `driveTo` circles the point, or stops short | `Tunables.Drive.turnKp`/`turnKd` (the heading), `moveMinPower`; or a tolerance under 1 in that it cannot reach | | TeleOp's field-centric is wrong after autonomous | the start spot's heading in `s.start(...)` is wrong | | `robot.pose()` is null | `Robot.java` has no `odometry(...)` line | --- # Pedro module (Pedro Pathing) URL: https://crossbotics.com/ftc-helper/docs/modules/pedro/ New to path following: start with [Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/). Quick answers with code to copy: [cookbook: Pedro paths](https://crossbotics.com/ftc-helper/docs/cookbook/12-pedro-paths/). Worked example: [`examples/.../pedrobot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/pedrobot). Pedro needs a working, checked odometry, so read [the odometry module](https://crossbotics.com/ftc-helper/docs/modules/odometry/) first. **Pedro Pathing** ([pedropathing.com](https://pedropathing.com)) is a path follower. You give it a path (a line or a smooth curve). Pedro drives the robot along it fast, corrects all the way, and brakes at the end. `driveTo` goes to one point. Pedro follows a whole path, curves included. > **You need odometry and a mecanum drive.** > > **Odometry:** Pedro steers by the robot's real place on the field, every loop. Only the > `odometry(...)` line gives that: a Pinpoint, an OTOS or dead wheels, set up and checked > ([odometry](https://crossbotics.com/ftc-helper/docs/modules/odometry/), [Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/)). Drive-wheel encoders slip, > so they are not enough. With no odometry line, INIT stops. Until you check the odometry, the robot > skips the `follow` steps. > **Mecanum:** Pedro corrects the robot's position by sliding it sideways, so it needs > wheels that can strafe. Pedro 3.0.2 has two drivetrains, Mecanum and Swerve. It has no tank (two-side) > drive. With a tank `drive(...)` line, `Pedro.follower(...)` stops INIT with a clear message. A tank > robot uses odometry with `turnTo` and `move` instead ([building autos](https://crossbotics.com/ftc-helper/docs/building-autos/)). > Swerve: build Pedro's `Swerve` drivetrain yourself through the > [escape hatch](#escape-hatches). Nobody has tested this, and the library has no swerve `drive(...)` line. **When to use which:** | You want | Use | | --- | --- | | go to a point, with code that is short and clear | `driveTo` (no add-on, no extra tuning) | | a curved path, or more speed with smooth braking | Pedro (`follow`), after Pedro's own tuning | Both use the same field numbers and the same odometry, so you can mix them in one autonomous. | Class | Use it to | | --- | --- | | [`Pedro`](#robotjava-the-follower-line) | the one line in `Robot.java`: `follower(Pedro.follower(...))` | | [`PedroPath`](#pedropath-paths-in-our-field-numbers) | make a line or a curve in our field numbers | | [`PathAt`](#do-things-along-the-path) | start things along a path (in the core library: `com.crossbotics.ftchelper.robot`) | | [`PedroTuning`](#tuning-pedro) | run Pedro's own tuners on your robot's drive and odometry lines | | [`PedroFollower`](#what-runs-every-loop) | Pedro's Follower as a part of the robot (made for you) | | [`PedroLocalizer`](#what-runs-every-loop) | gives Pedro the pose from your `odometry(...)` line (made for you) | | [`PedroFrame`](#the-frame) | turns poses between our numbers and Pedro's |
flowchart LR
    O["odometry(...) line<br/>(read first, every loop)"] --> L["PedroLocalizer"]
    L --> F["Pedro's Follower<br/>(Foresight)"]
    P["follow(&quot;To the goal&quot;, path)"] --> F
    F --> M["the drive motors<br/>(only while a path runs)"]
--- ## Add it to your robot project Pedro is a separate library (from Maven Central). The `pedro` folder brings Pedro in and connects it to your robot files. Do this once, after the library itself works ([Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/)). **1. `settings.gradle`**, in the project folder (not in TeamCode). Under the library's two lines, add: ```groovy include ':ftc-helper-lib-pedro' project(':ftc-helper-lib-pedro').projectDir = new File(rootDir, 'ftc-helper-lib/pedro') ``` **2. `TeamCode/build.gradle`**, in `dependencies { ... }`, under the library's line: ```groovy implementation project(':ftc-helper-lib-pedro') ``` **3. Sync** (**File > Sync Project with Gradle Files**). **Why:** the `pedro` folder brings in Pedro version 3.0.2, the version we test this module with. Teams that do not add these lines do not get Pedro. --- ## Robot.java: the follower line One line, after the `odometry(...)` line: ```java odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); follower(Pedro.follower(PedroConstants.foresight)); ``` - The **drive motors** come from your `drive(...)` line: the names, and which ones are reversed. Pedro needs a **mecanum** drive. - The **pose** (the robot's place and heading) comes from your `odometry(...)` line. Pedro does not read the Pinpoint itself. So you set up and tune the odometry once, with the library's Odometry Tuner. - **`PedroConstants.foresight`** holds Pedro's own numbers: how fast the robot goes, how it brakes, how hard it corrects. They come from [Pedro's Foresight tuner](#tuning-pedro). To start, copy [`PedroConstants.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/pedrobot/PedroConstants.java) from the example into your TeamCode. We measured its numbers on the simulated example robot ([The simulator](#the-simulator)). They are **not yours**: run the tuner before you trust a path. Pedro reads `PedroConstants` at INIT. These numbers are not in the library's tuning menu. Change them in the file and send the code again. --- ## follow: the autonomous step ```java s.start("Against our wall, left corner tile, facing the field", -56, -61, 0) .follow("To the goal", PedroPath.line(-56, -61, -30, -30).turnTo(0, 45)) .follow("Park", PedroPath.curve(-30, -30, -50, -24, -56, -36).keepHeading(0)); ``` `follow(label, path)` starts the path and waits until Pedro is at the end. Then the next step runs. `follow(label, path, seconds)` sets your own time limit (the default is 10 s). **What the report says:** | Report | Meaning | What to do | | --- | --- | --- | | `To the goal: done` | Pedro reached the end | nothing | | `timed out` | the robot was still going after the time limit | give a longer limit, or check the path for walls | | `STALLED` | the distance left did not go down for 1.5 s (the robot is stuck on something) | check the path. The robot stops and the next step runs | | `NO_ODOMETRY` | the odometry did not answer (at the start, or for 0.2 s on the way) | check the Pinpoint cable. The robot stops | | `skipped: Tunables.Odometry.checked is false` | nobody checked the odometry | run the Odometry Tuner, then set `checked = true` | | `cut short` | park time or STOP came first | nothing: this is normal at the end of the match | | `..., not fired: Spin up` | the path ended early, so these [`PathAt`](#do-things-along-the-path) things never started | fix the early end. If they matter, start them in a later step | **After a problem the next steps still run**, as with `driveTo`. When the next step needs the robot at the end of the path, guard it with a `waitUntil`, or plan a safe next step. **Skipped until checked:** an odometry with a wrong offset or a reversed pod can send the robot the wrong way at full speed. So, like `driveTo`, `follow` does nothing on a real robot until `Tunables.Odometry.checked = true`. The simulator does not need it. --- ## Do things along the path Pedro has no "do this at this point" of its own. `PathAt` adds it: put things after the path in the `follow` step. Each one **starts** something once, at its place along the path. The robot keeps driving, as with a `run` step in the middle of the path: ```java s.follow("To the goal", TO_GOAL, 15, // 15 s at most, then the things to do PathAt.fraction(0.5, "Intake on", robot.intake::in), // halfway along the whole path PathAt.part(2, "Intake off", robot.intake::stop), // where part 2 starts PathAt.inchesLeft(12, "Spin up", robot.launcher::spinUp)); // 12 in before the end ``` `robot.intake` and `robot.launcher` are the parts in your `Robot.java`: use your own part names. | Write | It starts | | --- | --- | | `PathAt.inchesDone(10, ...)` | after 10 in of the path | | `PathAt.inchesLeft(12, ...)` | when 12 in of the path are left (the whole path, all its parts) | | `PathAt.fraction(0.5, ...)` | when that much of the WHOLE path is done (0.5 = halfway, all parts counted; 0.25 = a quarter) | | `PathAt.part(2, ...)` | where part 2 of a `then` path starts (`part(1)` = at once) | | `PathAt.near(-40, -40, 6, ...)` | when the robot's center is within 6 in of the field point (-40, -40) | **What to do:** a name and a command (`"Intake on", robot.intake::in`), or an action from your `Actions.java` (`PathAt.inchesLeft(12, Actions.scoreHigh(robot))`). Any action you wrote works too, and the step uses its name. An action keeps running after the step, like `alongside`. A command must not wait: it starts things (`spinUp`, `goTo`), as in a `run` step. **The rules:** - **Once each.** Every loop the step checks them **in the order you wrote them**. So when the robot reaches two in the same loop, they start in that order. Write them in the order they come along the path. - **At the end of the path**, the ones reached there start. This holds even when Pedro called the path done a little short of the end (it is done within 2.5 in). It also holds when Pedro called it done in its very first loop. - **A path that comes back the same way** (out 24 in, then back along the same line) keeps counting. Halfway back is 36 in done, never back to 12. The robot's place on the path only moves forward. It may slip back a few inches, no more. `near` starts only when the robot truly came that close. - **If the path ends early** (`timed out`, `STALLED`, `NO_ODOMETRY`, `cut short`), the rest do not start, and the report names them: `To the goal: STALLED, not fired: Spin up`. When a path got to its end but missed a `near` point, the report says `To the goal: done, not fired: ...`. - **Mirrored like the path:** distances along the path are the same on both sides. You write `near`'s point for BLUE, and the step mirrors it for RED, like `driveTo`'s. - **Mistakes stop INIT** with a message: a fraction that is not 0 to 1, a part 0, or `part(3)` on a path with 2 parts. **How far along the robot is:** the step measures it along the path. It finds the robot's closest point on the path, and the distance along the path from there to the end (`PedroFollower.remainingIn()`). The "part" is the part that closest point is on, so `part(2)` starts where the robot passes the join. The step does not use Pedro's own distance left. That distance counts only the part Pedro steers along now, and Pedro looks ahead: it may start steering along part 2 well before the join. **With `driveTo` too:** `driveTo("To the goal", -30, -30, 45, 0.7, PathAt.inchesLeft(12, "Spin up", robot.launcher::spinUp))`. Its "path" is the straight line from the robot's place at the start of the step to the point. So it has one part. **`alongside` or `PathAt`:** `.alongside(action)` before the `follow` starts the action when the path starts. `PathAt` starts it later, at a place along the path. **Another path follower** (an add-on that fills in `PathFollower`) works with `PathAt` too. When it does not give its path's length, the step uses the distance left at the start. When it does not say which part it drives, `part(n)` starts at the end of the path ([PathFollower](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/)). --- ## PedroPath: paths in our field numbers The numbers are the same as for `driveTo` and the start spot. Seen from your drivers' wall, **x** is inches right of the center line, and **y** is inches away from the center toward the far wall. The **heading** is in degrees: 0 = facing away, counterclockwise + ([the frame](https://crossbotics.com/ftc-helper/docs/modules/odometry/#the-frame)). > **Draw it first:** the [Pedro Path Builder](https://crossbotics.com/ftc-helper/path-builder/) is a web > page with the BIOBUZZ field. Draw lines and curves, and set the heading and speed of each part. The > page shows the robot's footprint along the path, in red where it hits a field element. It writes the > `PedroPath` code (or `driveTo` steps), and it reads your code back so you can change it. **Make a path:** | Code | The path | | --- | --- | | `PedroPath.line(x1, y1, x2, y2)` | a straight line | | `PedroPath.line(fromPose, toPose)` | a straight line, turning from the first heading to the second | | `PedroPath.curve(x1, y1, cx, cy, x2, y2)` | a smooth curve from (x1, y1) to (x2, y2). The control point (cx, cy) pulls the curve toward it. The robot does not drive through it. For more control points, put more pairs in the middle | **Then choose the heading** with one of these. The default is `facePath()`. | Code | The robot | | --- | --- | | `.turnTo(startDeg, endDeg)` | turns evenly from one heading to the other on the way | | `.turnTo(startDeg, endDeg, from, until)` | turns only on one stretch of the part (0 = its start, 1 = its end). `0, 0.3` turns first, then drives. `0.7, 1` drives first, then turns. On the last part, add `.holdEnd()` so the turn can finish | | `.keepHeading(deg)` | keeps one heading the whole way (it slides sideways as needed) | | `.facePath()` | faces along the path, front first | | `.facePathBackwards()` | faces along the path, back first | | `.facePoint(x, y)` | keeps facing a field point, for example the goal | **More options:** add them after the heading. | Code | What it does | | --- | --- | | `.then(otherPath)` | adds another part. The robot drives on with **no stop** between the parts. Start the next part where this one ends, at the same heading, or the robot turns fast at the join. If `otherPath` has `.holdEnd()`, the whole path holds | | `.maxSpeed(0.5)` | at most half of the robot's top speed on this part (Pedro's `maxPathSpeed`), for example near a field element. The limit starts where the part starts, so the robot brakes inside the part: give it room | | `.holdEnd()`, `.holdEnd(seconds)` | keeps holding the end point after the robot gets there, for at most 5 s or your time ([hold](#hold-the-end-point)) | The heading and `maxSpeed` settings work on the **last part added so far**. `holdEnd()` works on the whole path. So write each part's settings right after that part: ```java static final PedroPath TO_GOAL = PedroPath.line(-56, -61, -48, -50).keepHeading(0) // part 1 .then(PedroPath.curve(-48, -50, -44, -36, -30, -30)).turnTo(0, 45) // part 2 .maxSpeed(0.6) // part 2 only .holdEnd(); // the whole path ``` **A path that comes straight back along itself:** in the pretend-robot tests, Pedro's own steering took a shortcut onto the way back at once. Our progress measure handles such a path, but Pedro's steering does not. Use two `follow` steps, out and back, or a curve that turns around. Nobody has checked this on a robot yet. Without `then`, each `follow` brakes to a stop at its end. So two `follow` steps in a row stop between them. ### Hold the end point With `.holdEnd()`, the `follow` step still ends when the robot gets to the end, so the next steps run. But Pedro keeps the robot on that point: when another robot bumps it, Pedro pushes back. The hold ends at: - the next `follow` (the new path takes over), - the next driving step (`driveTo`, `move`, `turn`, `turnTo`). That step ends the hold first, so the two never drive the wheels at once, - the end of the autonomous, - its time limit: 5 s, or your own with `.holdEnd(seconds)`. **Why:** a robot wedged against something must not push for the rest of autonomous. When the limit ends the hold, the Driver Station shows `Path: the hold ended after 5 s (its limit)`. `run`, `waitSeconds`, `waitUntil` and `alongside` do **not** end the hold, because they do not drive the wheels. Your own `step(...)` or an action that drives the wheels does not end it either. Call `robot.follower().cancel()` first. **A PedroPath never changes.** Every method (`then`, `turnTo`, `holdEnd`...) gives back a new path. So `TO_GOAL.then(...)` makes a longer path and leaves `TO_GOAL` as it was. `then` also checks that the next part starts where the path ends (within 0.5 in). If it does not, INIT stops. Use the hold for a step that needs the robot still, for example `waitSeconds` while it scores. The Driver Station shows `Path: holding the end (0.4 in off)`: how far the robot is from the point. **Mirroring:** with `mirrorForRed()` on, the step mirrors the path for RED (x and headings flip), like every other step. Write the path once. **Tip:** make each path once, as a `static final` field (see the example). It is the same every match. **Pedro's own paths:** `follow` also takes a Pedro `Path` (for example with Pedro's other path modifiers). Pedro's paths use **Pedro's** numbers, not ours ([the frame](#the-frame)). The step **never mirrors** them. --- ## The frame Pedro uses the same x and y as we do. Only the heading is different. Pedro measures it in radians from the +x direction (right). We measure it in degrees from "away". So: **Pedro heading = our heading + 90 degrees.** `PedroFrame.toPedro(...)` and `PedroFrame.fromPedro(...)` do it for you. `PedroPath` uses them, so you only need them for Pedro's own paths. --- ## Tuning Pedro Tune in this order. Each step needs the one before it. 1. **The drive:** motor directions and the drive check ([Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/)). 2. **The odometry:** the library's Odometry Tuner, then `Tunables.Odometry.checked = true` ([odometry](https://crossbotics.com/ftc-helper/docs/modules/odometry/#the-odometry-tuner)). 3. **Pedro's Foresight tuner**, which fills `PedroConstants`. Set it up once: - In `build.dependencies.gradle`, add Pedro's tuning library and the place it comes from: ```groovy repositories { maven { url 'https://repo.dairy.foundation/releases/' } } dependencies { implementation 'com.pedropathing:tuning:1.0.1' } ``` - Copy the `pedro/procedures` folder and `pedro/Tuning.java` from [Pedro's Quickstart](https://github.com/Pedro-Pathing/Quickstart) into your TeamCode. Its `Tuning.java` is empty (`// Tuners go here`). Add this method to it, with the imports at the top: ```java import com.crossbotics.ftchelper.pedro.PedroTuning; import com.pedropathing.tuning.autotune.Procedure; import com.pedropathing.tuning.autotune.Tuner; import org.firstinspires.ftc.teamcode.Robot; import org.firstinspires.ftc.teamcode.pedro.procedures.ForesightTuner; public class Tuning { @Tuner public static Procedure foresightTuner() { return new ForesightTuner(PedroTuning.localizer(Robot::new), PedroTuning.drivetrain(Robot::new)); } } ``` (If your files are in other packages, change the `Robot` and `ForesightTuner` imports.) - Run it as [Pedro's tuning page](https://pedropathing.com/docs/pathing/tuning/foresight) says (the robot's web page, "Foresight Procedure"). Copy the "Java" output into `PedroConstants`. The tuner does not change your code, so **copy the numbers back into `PedroConstants.java` every time**. 4. **Test before you trust it.** This step is optional, but a good idea. Run Pedro's "Tests" procedure (Line and Curve tests). Add it to `Tuning.java` the same way, from Pedro's [testing page](https://pedropathing.com/docs/pathing/tuning/test). Then run one `follow` step at low power (the PRACTICE profile). **Versions:** use `tuning:1.0.1`, the version Pedro's Quickstart uses. Its `procedures` files match it. The tuning library asks for an older Pedro (3.0.x), and this module asks for 3.0.2. Gradle uses the newer one, 3.0.2. That is correct: do not change it back. You need the `repo.dairy.foundation` line, because the tuning library gets one of its parts (Sloth) from there. (Checked 2026-10-21.) **Take the tuner out before an event.** Pedro's tuning library runs a web page on the robot (the "192.168.43.1:10158" page). This season's rule R704.D bans "additional logging/streaming services" like FTC Dashboard and FTControl Panels at events. Before an event, remove or comment out the `tuning` line in `build.dependencies.gradle`. Also remove the `pedro/Tuning.java` and `procedures` files, or move them out of TeamCode. Then build and install again. Your `PedroConstants` numbers stay, because the follower does not need the tuner. **The tuner drives at full power.** It uses Pedro's own drivetrain, without the library's power limit (`maxPower`). Give it room, and keep a hand on STOP. **Skip Pedro's localization tuners.** Step 2 already tuned your `odometry(...)` line, and `PedroTuning.localizer` uses it. --- ## When is a path "done"? Pedro decides. By default a path is done within **2.5 in** of the end (`translationalDeviationTolerance`) and **11.25 degrees** of heading (`headingDeviationTolerance`). That is looser than `driveTo` (1 in, 2 degrees). To make it tighter, set them in `PedroConstants`. **The heading is in radians**, like everything in Pedro: ```java c.translationalDeviationTolerance.set(1.0); // inches c.headingDeviationTolerance.set(Math.toRadians(5)); // 5 degrees ``` --- ## What runs every loop 1. The odometry reads the device (first of all parts). 2. `PedroLocalizer` copies that pose for Pedro and works out the speed from the change since the last loop (Pedro brakes using the speed). 3. **Only while a path runs or holds its end:** Pedro's Follower works out the wheel powers and sets them. When no path runs or holds, Pedro sets nothing. So it never fights TeleOp driving or a `driveTo` step. **The power limit:** no wheel gets more than the drive's limit (`Tunables.Drive.maxPower`, or `practiceMaxPower` in the PRACTICE profile). Every other drive in the library works the same way. **Brake or coast:** Pedro brakes with power, on purpose, so it lets the wheels coast while it drives a path. After the path, the robot's own setting (brake) comes back. **The drive motors' run mode:** autonomous runs the drive motors at a set speed (`RUN_USING_ENCODER`). Pedro expects plain power. So during a path the library switches the motors to `RUN_WITHOUT_ENCODER`, and puts them back after it. **At the end of a path** the wheels stop, unless the path asks to [hold the end](#hold-the-end-point). **Telemetry:** `Path: 18 in to go` while a path runs; `Path: holding the end (0.4 in off)` while it holds. --- ## Escape hatches | You want | Use | | --- | --- | | Pedro's own Follower (its debug data, its settings) | `Pedro.of(robot)` | | another drivetrain (for example Pedro's `Swerve`) or algorithm | `follower(Pedro.follower((hardwareMap, localizer) -> new Follower(localizer, yourDrivetrain, yourAlgorithm)))`. Make the Follower with the `localizer` you are given. Not for tank: Pedro has no tank drivetrain | | Pedro's Mecanum settings from your drive line | `Pedro.mecanumConfig(robot.drive())` | | the pose for Pedro in a tool with no robot loop | `PedroTuning.localizer(Robot::new)` | **Pedro commands you start yourself** (`Pedro.of(robot).hold(...)`, `manual(...)`) do not run. The library updates Pedro's Follower only during a `follow` step and its hold. For a hold, use `.holdEnd()`. --- ## The simulator Pedro runs in the simulator like the rest of the robot: `follow` steps drive the simulated robot. **See the path.** The field map (Control Hub, Robot tab) and the 3D view draw two lines: | Line | What it is | | --- | --- | | orange, dashed | the plan: the path the running `follow` step drives, with a ring at its end. It fades after the step ends | | green | the trail: where the robot truly went, in its last 30 seconds of driving | **To check whether a curve hits a field element:** look at the orange line first. If it crosses a field element, change the path: move the control point, or add a part with `then`. Then run it and look at the green line. Where the green line leaves the orange one, the robot did not drive the plan. Either it bumped something (the robot turns red), or it was too fast to turn or brake in time (try `maxSpeed(...)` on that part). The robot is wider than the line. So leave half the robot's width (9 in for an 18 in robot), plus a little, between the line and any field element. **Clear lines** clears both. When you put the robot somewhere by hand, a new piece of trail starts. The plan comes from `PedroFollower.plannedPoints()`: the running path as points about 1 in apart (at most 200), in our field numbers, mirrored as driven. It only reads, and changes nothing. **The numbers.** The simulator uses the numbers in `PedroConstants`. The Pedro example robot (`examples/.../pedrobot`) has numbers measured on the simulated robot itself: we ran the measuring steps of Pedro's Foresight tuner in the simulator. So its paths brake the way the simulated robot brakes. (Pedro's Quickstart of 2026-10-15, on the example's simulator robot file, with the tuner's default distances: 48 in, 30 in/s, 36 in. Measured 2026-10-21.) Your robot needs its own numbers: tune on the real robot ([Tuning Pedro](#tuning-pedro)). **Pedro's Foresight tuner in the simulator:** it runs in part. Pedro's tuner menu (the robot's web page) needs the real Robot Controller app, so it does not start in the simulator. Its measuring steps are plain OpModes, and those do run there. They need the robot's speed. When we worked out the speed from the simulated odometry, it was too uneven: the tuner gave different brake numbers every run. With the physics engine's own speed, it gave the same numbers every run (within a few percent). The example's numbers come from that. They are not a real robot's numbers. For example, the simulated robot coasts to a stop more slowly than a real one. --- ## If something goes wrong | Problem | Cause | Fix | | --- | --- | --- | | INIT stops: "follower(...) needs an odometry(...) line too" | no odometry line | add `odometry(...)` | | INIT stops: "Pedro.follower needs a mecanum drive(...) line" | a tank drive | Pedro needs mecanum. Use `turnTo` and `move` | | INIT stops: "follow(...) needs a path follower" | a `follow` step but no follower line | add `follower(Pedro.follower(...))` | | the report says `skipped` for every `follow` | `Tunables.Odometry.checked` is false | run the Odometry Tuner, then set it true | | the robot drives the wrong way | a reversed drive motor, or the odometry's x/y swapped | run the drive check and the Odometry Tuner again | | it overshoots and comes back | `PedroConstants` not tuned (the example robot's numbers) | run Pedro's Foresight tuner | | it stops a little short | Pedro's "done" distance is 2.5 in | [tighten it](#when-is-a-path-done) | | it is slow | `Tunables.Drive.maxPower` is low (or `practiceMaxPower`, in PRACTICE) | raise it | | Pedro's tuner does not compile | the tuning library or its repository is missing | step 3 of [Tuning Pedro](#tuning-pedro) | **Known Pedro bug (fixed in 3.0.2, checked 2026-10-21 with the issue's own test):** in Pedro 3.0.1, a path with "hold the end" off stayed "busy" forever ([Pedro issue #191](https://github.com/Pedro-Pathing/PedroPathing/issues/191)). This module checks Pedro's mode instead of its busy flag, so it works with both versions. --- # Robot module URL: https://crossbotics.com/ftc-helper/docs/modules/robot/ The classes of the five-files layer. How to use each part is in the [Reference](https://crossbotics.com/ftc-helper/docs/reference/): one page per part, and pages for [Robot.java](https://crossbotics.com/ftc-helper/docs/reference/robot-java/), [Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/tunables/), [Controls.java](https://crossbotics.com/ftc-helper/docs/reference/controls/) and [steps for autos](https://crossbotics.com/ftc-helper/docs/reference/steps/). Package: `com.crossbotics.ftchelper.robot` | Class | Use it to | | --- | --- | | [`RobotDefinition`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition) | describe the robot in `Robot.java`: `drive(...)` and one `add(...)` per mechanism | | [`Drive`](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/) | the drivetrain: mecanum or tank, motor names, motor, wheel, IMU | | [`Odometry`](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/) | where the robot is on the field: a goBILDA Pinpoint, a SparkFun OTOS, or dead wheels | | [`Intake`](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/) | a roller on a motor and/or CR servos: in, out, on at the start | | [`Lift`](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/) | a slide on a motor with named heights and a bottom switch | | [`Arm`](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/) | an arm on a motor with named angles in degrees | | [`Claw`](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/) | a claw servo: open, closed | | [`Wrist`](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/) | a wrist servo with named positions | | [`Positioner`](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/) | any servo with named positions (deploy, fold, gate) | | [`Turret`](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/) | a turret inside its limits, by hand or following the camera's goal | | [`Launcher`](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/) | a flywheel and its [`Indexer`](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/): spin up, fire, speed from distance | | [`Indexer`](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/) | feeds one piece at a time (servo, CR servo or motor) | | [`Hood`](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/) | a launcher's hood (servo or motor): its angle from the shot table, by hand, a trim | | [`Camera`](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/) | a Limelight or webcam; the alliance's goal | | [`Pieces`](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/), [`PieceSensor`](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/) | which game piece is at a spot (color sensor, distance sensor, second webcam); how many the robot holds and which fires next | | [`Lights`](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/), [`LightColor`](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/) | a colored light for the drivers (goBILDA RGB Indicator Light or REV Blinkin): which color when | | [`Action`](https://crossbotics.com/ftc-helper/docs/reference/steps/#action) | steps across several parts that never block (never make the loop wait) | | [`Mode`](https://crossbotics.com/ftc-helper/docs/reference/steps/#modes) | a rule a module follows every loop while the mode is on | | [`ControlMap`](https://crossbotics.com/ftc-helper/docs/reference/controls/#controlmap), [`Pad`](https://crossbotics.com/ftc-helper/docs/reference/controls/#controlmap) | `Controls.java`: the TeleOp and the button map | | [`Auto`](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto), [`Steps`](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto) | one autonomous as a list of steps | | [`Feature`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#what-your-robot-can-do) | what the library does by itself for your robot, ready or not (`robot.features()`) | | [`EncoderMotor`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition) | one motor for the [Encoder Check](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#encoder-check-each-encoder-cable-in-its-own-port) (`robot.encoderMotors()`) | | [`Toggleable`](https://crossbotics.com/ftc-helper/docs/reference/controls/#controlmap) | anything one button switches on and off | | [`Motors`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#motors) | look up the encoder counts and speed of common motors, by catalog id (a part's name in the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/), e.g. `"gobilda-5203-312"`) | | [`Shape`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts), [`Parts`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts) | how each part looks and where it sits, for the simulator; wheels, rollers and servos by catalog id | | [`Starting`](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure) | `DEFAULT` and `MEASURE`, the two special values in `Tunables.java` | | [`Zone`](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) | a part's zone for an interlock rule: `lift.zoneAbove()`, `turret.zone()` | | [`Module`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#module), [`MotorPositions`](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/), [`ServoPositions`](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/), [`Devices`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#module) | what the modules share (you rarely use these by name) | ## Where each section went | Old section | New page | | --- | --- | | Drive | [Drive](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/) | | Odometry | [Odometry](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/) | | PathFollower | [PathFollower and PathAt](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/) | | PathAt | [PathFollower and PathAt: PathAt](https://crossbotics.com/ftc-helper/docs/reference/parts/path-follower/#pathat) | | Camera | [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/) | | Aim | [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/) | | Intake | [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/) | | Intake: buttons to add | [Intake: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/#buttons-to-add) | | Lift | [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/) | | Two motors on one lift or arm | [Lift: Two motors on one lift or arm](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm) | | Lift: buttons to add | [Lift: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#buttons-to-add) | | Arm | [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/) | | Arm: buttons to add | [Arm: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/#buttons-to-add) | | Claw | [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/) | | Claw: buttons to add | [Claw: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#buttons-to-add) | | Wrist | [Wrist](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/) | | Wrist: buttons to add | [Wrist: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/#buttons-to-add) | | Positioner | [Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/) | | Positioner: buttons to add | [Positioner: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/#buttons-to-add) | | Turret | [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/) | | Turret: buttons to add | [Turret: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/#buttons-to-add) | | Interlock | [Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) | | Launcher | [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/) | | Firing: shot modes, feed stop, piece path | [Launcher: Firing: shot modes, feed stop, piece path](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#firing-shot-modes-feed-stop-piece-path) | | Speed trim and battery compensation | [Launcher: Speed trim and battery compensation](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#speed-trim-and-battery-compensation) | | Launcher: buttons to add | [Launcher: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#buttons-to-add) | | Indexer | [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/) | | Indexer: buttons to add | [Indexer: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/#buttons-to-add) | | Hood | [Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/) | | Hood: buttons to add | [Hood: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/#buttons-to-add) | | Pieces and PieceSensor | [Pieces and PieceSensor](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/) | | Pieces: buttons to add | [Pieces and PieceSensor: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/#buttons-to-add) | | Lights | [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/) | | The alliance at INIT | [Lights: The alliance at INIT](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/#the-alliance-at-init) | | RobotDefinition | [Robot.java: RobotDefinition](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition) | | Tunables.java | [Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/tunables/) | | DEFAULT and MEASURE | [Tunables.java: DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure) | | Your own code every loop | [Robot.java: Your own code every loop](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#your-own-code-every-loop) | | What your robot can do | [Robot.java: What your robot can do](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#what-your-robot-can-do) | | Parts not in the catalog | [Robot.java: Parts not in the catalog](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-in-the-catalog) | | Parts not on the robot yet | [Robot.java: Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet) | | Shapes and parts | [Robot.java: Shapes and parts](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts) | | Motors | [Robot.java: Motors](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#motors) | | Module | [Robot.java: Module](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#module) | | Making the files | [Robot.java: Making the files](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#making-the-files) | | Action | [Steps for autos: Action](https://crossbotics.com/ftc-helper/docs/reference/steps/#action) | | Modes | [Steps for autos: Modes](https://crossbotics.com/ftc-helper/docs/reference/steps/#modes) | | ControlMap | [Controls.java: ControlMap](https://crossbotics.com/ftc-helper/docs/reference/controls/#controlmap) | | Reading a button line | [Controls.java: Reading a button line](https://crossbotics.com/ftc-helper/docs/reference/controls/#reading-a-button-line) | | Drive to a spot by itself | [Controls.java: Drive to a spot by itself](https://crossbotics.com/ftc-helper/docs/reference/controls/#drive-to-a-spot-by-itself) | | Auto | [Steps for autos: Auto](https://crossbotics.com/ftc-helper/docs/reference/steps/#auto) | | Keep time to park | [Steps for autos: Keep time to park](https://crossbotics.com/ftc-helper/docs/reference/steps/#keep-time-to-park) | --- # Safety module URL: https://crossbotics.com/ftc-helper/docs/modules/safety/ Learn it hands-on: [08 A lift that cannot hurt itself](https://crossbotics.com/ftc-helper/docs/tutorials/08-safe-lift/). Keeps lifts, slides, arms and turrets inside their safe range. Then code can never drive them into the frame, snap a string, or stall a motor at the end of travel. (A stalled motor pushes but cannot turn, and it gets hot.) [`PositionMotor`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#positionmotor) and the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/) use it for you. Use it directly when you control a motor by hand. Start with tutorial 08. | Class | Use it to | | --- | --- | | [`SafeMotor`](#safemotor) | run a motor with soft limits, limit switches, homing and a slow zone (each explained [below](#what-it-does-each-loop)) | | [`SoftLimits`](#softlimits) | use the limit rule by itself (no hardware) | | [`JamDetector`](#jamdetector) | tell when a motor is jammed (too slow or too much current, for a set time) | For an easier start, use [`PositionMotor`](https://crossbotics.com/ftc-helper/docs/modules/mechanism/#positionmotor). It wraps `SafeMotor` with PID, named positions and steps. **Software limits are not enough on their own.** Rule R105 B (2026-27 manual) says the robot must stay inside its size limits *without the use of software*. Inspectors check the maximum mechanical extension. So every moving part needs a **hard stop** (a physical block). Use `SafeMotor` AND a hard stop. The software stops the motor before it hits the block, and the block holds when the software is wrong. --- ## SafeMotor ```java DcMotorEx liftMotor = MotorSetup.get(hardwareMap, "lift") .brake().resetEncoder().runWithoutEncoder().done(); // hold at 0 power, start at 0 TouchSensor bottom = hardwareMap.get(TouchSensor.class, "lift_bottom"); SafeMotor lift = new SafeMotor(liftMotor) .setLimits(0, 2900) // encoder ticks .setLowerSwitch(bottom::isPressed) // "how to read the switch", asked every loop .setSlowZone(200, 0.25); // last 200 ticks: power down to 0.25 at the end waitForStart(); while (opModeIsActive()) { lift.update(); // FIRST: read switches, re-zero at bottom lift.setPower(-gamepad2.left_stick_y); // limits are applied for you } lift.stop(); // no power once the OpMode ends ``` ### What it does each loop 1. **Soft limits** (limits in software, from the encoder count): power that would push past `min` or `max` becomes 0. Power that moves away from the limit always works, so the part can never get "stuck at the top". 2. **Limit switches:** a pressed switch stops power toward it, whatever the encoder says. 3. **Homing:** the moment the lower switch closes, the position becomes 0. This fixes encoder drift (a slipping belt, or a robot turned on with the lift half up). Until the first homing, the part only goes down, slowly ([Homing](#homing-with-a-lower-switch)). 4. **Slow zone:** close to a limit, `SafeMotor` reduces the power toward it, so the mechanism does not slam. **Hub traffic:** `update()` reads the encoder and each switch **fresh**, every loop. Later reads in the same loop (`getPosition()`, the PID, the limits and the telemetry) within 3 ms reuse those readings. So a reading is at most 3 ms old, and one loop usually makes one read of each. Code that never calls `update()` gets a reading at most 3 ms old every time it asks. `SafeMotor` sends a power only when the power changes, and again every 25 loops. **Past a soft limit** (below `min` or above `max`), it checks and sends the power every loop (see [Rules for use](#rules-for-use)). **For tests only:** a test can move a pretend motor with no time passing. Without help, it then sees the old reading. `SafeMotor.freshReadingsForTests(true)` reads the encoder and the switches every time a test asks (no 3 ms reuse). `false` puts the normal reuse back. Robot code never needs it. **Set the motor direction first:** positive power must move toward `max` (up or out). Check it with a low power before you add limits. ### Methods Setup (each one gives back the `SafeMotor`, so you can chain them): | Method | What it does | | --- | --- | | `new SafeMotor(motor)` | wrap a motor | | `setLimits(min, max)` | the safe range in ticks, measured from home (0) | | `setSlowZone(distance, powerAtLimit)` | within `distance` ticks of a limit, power toward it goes down to `powerAtLimit` at the limit | | `setMaxPower(max)` | the most power ever sent, 0 to 1 | | `setLowerSwitch(reader)` | a lower limit switch. Homing uses it too | | `setUpperSwitch(reader)` | an upper limit switch | | `setRequireHoming(boolean)` | with a lower switch: `true` (default) = only slow downward power until homed | | `setHomingPower(power)` | the most downward power before homing, default 0.3 | | `alsoPowers(otherMotor)` | a second motor on the same mechanism (a lift with a motor on each side). It gets exactly the same power as this one, every time (limits and `stop()` too). `SafeMotor` reads only this motor's encoder. First set the second motor's direction, so + power moves the mechanism the same way on both. Check it with the chain off. `getPartners()` lists them. In the five files: [`alsoMotor`](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm) | Every loop: | Method | What it does | | --- | --- | | `update()` | **call it first in every loop.** It reads the encoder and the switches, and homes when the lower switch closes. It sends your last power again with the limits applied, so the limits act with no new `setPower` call. Every 25 loops it sends the limited power even when it did not change. While the position is past a soft limit, it sends it every loop | | `setPower(power)` | set power, -1 to 1, with the limits applied. It gives the power it sent | | `moveTo(target, pid)` | move toward a target with a [`PidController`](https://crossbotics.com/ftc-helper/docs/modules/control/#pidcontroller). It keeps the target inside the limits, and gives the power sent | | `stop()` | power 0 | Read: | Method | What it gives | | --- | --- | | `getPosition()` | position in ticks, from home | | `isAtLower()` / `isAtUpper()` | whether it is at or past a limit, or its switch is pressed | | `isHomed()` | whether the lower switch or `zeroHere()` has set the zero | | `isWaitingForHoming()` | whether it has a lower switch, needs homing, and is not homed yet | | `getRequestedPower()` | the last power you asked for | | `getAppliedPower()` | the last power it sent to the motor. When it is 0 while you asked for power, a limit stopped it | | `getMotor()` | the `DcMotorEx` inside. Power you send to it skips the limits: see [Rules for use](#rules-for-use) | | `zeroHere()` | make the current position 0 (home by hand) | ### Reading switches `setLowerSwitch` takes "a way to read the switch". For example: ```java lift.setLowerSwitch(touchSensor::isPressed); // REV Touch Sensor lift.setLowerSwitch(() -> !magnetSwitch.getState()); // REV Magnetic Limit Switch (DigitalChannel): // it reads false when the magnet is near ``` ### Homing (with a lower switch) When the robot turns on, the encoder does not know where the mechanism is. So with a lower switch, `SafeMotor` does not trust the position until it is **homed** (the switch was pressed once): - Until then, only DOWNWARD power works, at most 0.3 (`setHomingPower`). `SafeMotor` does not use the soft limits yet. - Drive it down until the switch is pressed. The position becomes 0, and everything works normally. - When it is already on the switch at the first `update()`, it homes at once. In TeleOp, the driver pushes the lift down once at the start. In autonomous, drive it down with `setPower(-0.3)` each loop until `isHomed()` is true, with a timeout. `setRequireHoming(false)` turns this off and trusts the start position as 0. We do not recommend it. ### No lower switch Position 0 is wherever the motor was when you turned the robot on. So **turn the robot on with the mechanism all the way down**. ### Rules for use - Send ALL power for this motor through the `SafeMotor` (`setPower` or `moveTo`). A call to `getMotor().setPower(...)` skips the limits, but that power cannot stick. While `update()` runs every loop, `SafeMotor` sends its own limited power again within 25 loops (about half a second at 50 loops a second). It does this even when that power did not change, and every loop while it is past a soft limit. - Call `update()` once per loop, before `setPower` or `moveTo`. --- ## SoftLimits The limit rule by itself. `SafeMotor` uses it. Use it when you control a motor some other way. ```java // (power you want, position now, min, max, slow zone, power at the limit, bottom switch, top switch) double safe = SoftLimits.limit(power, position, 0, 2900, 200, 0.25, atBottom, atTop); ``` | Parameter | Meaning | | --- | --- | | `power` | the power you want, -1 to 1 (positive = toward max) | | `position` | where it is now | | `min`, `max` | the safe range | | `slowZone` | the distance from a limit where the rule reduces power toward it (0 = none) | | `slowZonePower` | the power allowed right at the limit, 0 to 1 | | `atLowerSwitch`, `atUpperSwitch` | switch states (`false` when there is no switch) | It gives the safe power. --- ## JamDetector ```java JamDetector jam = new JamDetector(50, 0.3); // slower than 50 ticks/s for 0.3 s = jammed jam.setMaxCurrent(6); // optional: or above 6 A for 0.3 s // every loop: (power sent, speed in ticks/s, current in amps, time now in seconds) if (jam.update(power, motor.getVelocity(), amps, getRuntime())) { ...back it out... } ``` | Method | What it does | | --- | --- | | `new JamDetector(minSpeed, seconds)` | too slow for this long while powered = jammed | | `setMinPower(p)` | below this power, the motor is not "trying" (default 0.15) | | `setMaxCurrent(amps)` | it also counts a jam when the current is above this | | `update(power, speed, nowSec)` / `update(power, speed, amps, nowSec)` | whether the motor is jammed now | | `reset()` | start over after you clear a jam | `SpinMotor` and `MotorFeeder` use it for you. --- # Telemetry module URL: https://crossbotics.com/ftc-helper/docs/modules/telemetry/ Learn it hands-on: [06 A fast, clear loop](https://crossbotics.com/ftc-helper/docs/tutorials/06-fast-clear-loop/). **Telemetry** is the text your program shows on the Driver Station screen. This module makes that text clear during a match and useful when you hunt for a bug. [`EasyTeleOp`](https://crossbotics.com/ftc-helper/docs/modules/teleop/) and the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/robot-java/) set it up for you, and every mechanism adds its own lines. Use this page to add your own lines, or in an OpMode you write yourself. Start with tutorial 06. | Class | Use it to | | --- | --- | | [`RobotTelemetry`](#robottelemetry) | show lines at two levels (standard for drivers, debug for programmers), warnings on top, and send less often for a faster loop | | [`TelemetryHelper`](#telemetryhelper) | add common lines (a motor, a yes/no) to the SDK's plain `telemetry` in one call | ## RobotTelemetry ```java RobotTelemetry t = new RobotTelemetry(telemetry); // debug ON in PRACTICE, OFF in COMPETITION controls.bindPress(Pad.G1, Btn.BACK, t::toggleDebug); // let the driver switch it // every loop: t.section("Lift"); t.line("Height", lift.getTargetName()); // standard: always shown t.debug("Power", "%.2f", power); // debug: only when debug is on if (battery < 11.5) t.warn("Battery low!"); // warnings: always, at the top robot.addTelemetry(t); // every mechanism adds its own lines t.update(); // ONCE, at the end of the loop ``` | Method | What it does | | --- | --- | | `section(title)` | a `--- title ---` heading (standard) | | `debugSection(title)` | a heading that shows only in debug | | `line(label, value)` / `line(label, format, args...)` | a driver line | | `text(text)` | a plain driver line | | `debug(label, value)` / `debug(label, format, args...)` | a programmer line (only in debug) | | `warn(text)` | `!! text` at the top, always. The same warning shows once per loop | | `warnFirst(text)` | a warning above every other one, even the ones added before it. The library uses it for a part that is OFF in COMPETITION. Several `warnFirst` warnings keep their order | | `setDebug(on)`, `toggleDebug()`, `isDebug()` | set, switch or read the debug level | | `setMinIntervalMs(ms)` | for a faster loop: send at most every N ms (100 = 10 per second is enough). The next send keeps the warnings from the loops it skipped | | `update()` | sends the screen (warnings first) and starts a fresh one. It turns button marks such as `{A}` into the names on the driver's controller ([ButtonNames](https://crossbotics.com/ftc-helper/docs/modules/gamepad/#buttonnames)) | | `pending()`, `raw()` | the lines that wait to be sent (for tests); the SDK telemetry | **To choose standard or debug:** ask whether the DRIVER needs this during a match. Yes = `line`. No = `debug`. The mechanism helpers already split their lines this way.
flowchart TB
    W["!! warnings (always, top)"] --> S["standard lines<br/>drivers: modes, targets, OK/READY"] --> D["debug lines (PRACTICE or toggled)<br/>powers, errors, raw sensor values, loop speed"]
## TelemetryHelper ```java // Each line only ADDS text; nothing is shown until telemetry.update(). TelemetryHelper.section(telemetry, "Lift"); TelemetryHelper.motor(telemetry, "Lift", liftMotor); // power, position, speed TelemetryHelper.value(telemetry, "Target", liftTarget, "ticks"); TelemetryHelper.flag(telemetry, "At bottom", lift.isAtLower()); // true/false shown as yes/no telemetry.update(); // send: once per loop ``` The Driver Station shows: ``` --- Lift --- Lift : pwr 0.45 | pos 1203 | vel 812/s Target : 1500.00 ticks At bottom : no ``` | Method | Adds | | --- | --- | | `section(telemetry, title)` | a heading line: `--- title ---` | | `value(telemetry, label, number, unit)` | `label : number unit`, 2 decimals | | `value(telemetry, label, number, decimals)` | `label : number`, with the decimals you choose | | `flag(telemetry, label, boolean)` | `label : yes` or `label : no` | | `motor(telemetry, label, motor)` | power, encoder position and speed (counts per second) on one line | | `servo(telemetry, label, servo)` | the last position the code sent to the servo. A normal servo cannot report where it is. | | `num(number, decimals)` | the number as text, for example `num(0.4567, 2)` = `"0.46"`. NaN shows as `--`. | These methods only ADD lines. You still call `telemetry.update()` once, at the end of the loop. ## Tips - One `telemetry.update()` per loop. More than one makes the screen flicker and slows the loop. - Put what the driver needs during a match at the top. Put the debug numbers lower. - Show the loop speed while you test: `TelemetryHelper.value(telemetry, "Loop", loopTimer.getHz(), "Hz")` (`LoopTimer` is in [util](https://crossbotics.com/ftc-helper/docs/modules/util/)). --- # TeleOp module URL: https://crossbotics.com/ftc-helper/docs/modules/teleop/ Learn it hands-on: [20 Easy TeleOp](https://crossbotics.com/ftc-helper/docs/tutorials/20-easy-teleop/). Ready to copy: the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/)'s `MainTeleOp`. A whole TeleOp (the driver-controlled part of the match). You write only what is special about your robot. Driving, the match timer, safety at ▶ (start on the Driver Hub) and STOP, and the tuning menu come ready-made. The `Controls.java` of the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/controls/#controlmap) uses it inside, so with five files, start there. Use `EasyTeleOp` directly with the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/) or your own classes. | Class | Use it to | | --- | --- | | [`EasyTeleOp`](#easyteleop) | a whole TeleOp OpMode: give it your robot settings and mechanisms, add the operator's buttons | | [`LibraryButtons`](#moving-the-librarys-buttons), [`Key`](#moving-the-librarys-buttons) | move or free the library's own buttons (pause, slow, field-centric, menus, switch alliance) |
flowchart LR
    I["INIT<br/>drive, IMU, 'forward' from auto,<br/>your mechanisms + buttons,<br/>warnings, alliance"] --> S["▶ start<br/>match timer starts"]
    S --> L["every loop:<br/>buttons -> driving -> everyLoop() -><br/>mechanisms update() -> telemetry"]
    L --> L
    L --> E["STOP (or an error)<br/>wheels and every mechanism stopped"]
--- ## EasyTeleOp ```java @TeleOp(name = "Main TeleOp") public class MainTeleOp extends EasyTeleOp { private Robot robot; // the robot's settings, shared with every autonomous @Override protected RobotConfig robotConfig() { return new RobotSettings(); } // the mechanisms: updated every loop, shown, stopped at the end @Override protected Subsystems createSubsystems() { robot = new Robot(hardwareMap); return robot.all; } // the operator's buttons (gamepad 2) @Override protected void bindButtons(ControllerBindings driver, ControllerBindings operator) { operator.bindPress(Pad.G2, Btn.RB, () -> robot.claw.toggle("OPEN", "CLOSED")); } // anything else, every loop (here: the lift by hand) @Override protected void everyLoop() { robot.lift.manual(StickShaping.shape(-gamepad2.left_stick_y, 0.1, 1)); } } ``` ### What it does for you | | | | --- | --- | | Driving (gamepad 1) | left stick drives, right stick X turns, left trigger slows. Mecanum and tank: your `DriveConfig` picks one. See [`DriverControls`](https://crossbotics.com/ftc-helper/docs/modules/drive/#drivercontrols). | | Field-centric | It starts robot-centric (stick up = the way the robot faces). **Y** turns field-centric (stick up = away from the driver) on and off. Two buzzes = on, one = off. Mecanum with an IMU only. | | "Forward" | It carries on from where autonomous ended ([`DriverHeading`](https://crossbotics.com/ftc-helper/docs/modules/drive/#driverheading)), even after INIT, STOP, INIT again. Press and let go of **BACK** alone (one buzz) to say "the robot now faces away from me". With odometry, that lasts for this run. After INIT again, "forward" comes from the pose. With `backTap()`, a tap of BACK does your job instead, and a 1 s hold of BACK sets "forward". Either way, BACK resets "forward" only while field-centric is on. In robot-centric driving, BACK does not reset it, and the Driver Station says why for 3 s: `BACK: "forward" is only reset in field-centric driving (turn it on first).` | | Alliance | the one autonomous chose, from [`MatchMemory`](https://crossbotics.com/ftc-helper/docs/modules/match/). When none came (no autonomous ran, or the robot app restarted), INIT says "Choose the alliance": gamepad 1 **X** = BLUE, **B** = RED. The same buttons change it. INIT also shows autonomous's report. A switch during the match is optional (off by default). `lib.switchAlliance(Key.g1(Btn.BACK), Key.g1(Btn.START))` turns it on. Then hold **START, then BACK** (START first), both for 1.5 s, to switch. Both gamepads buzz twice, and the screen says `Alliance now RED (was BLUE)`. `alliance()` and `MatchMemory` give the new one. INIT's `Switch alliance` line says whether the switch is on. | | Match timer | 2:00. Both gamepads buzz at 1:00 and 0:20. The screen shows the time. | | Tuning menu | **GUIDE** opens it (PRACTICE profile only). Gamepad 1 runs the menu, and the wheels hold still. With a button map (`buttonHelp()`, as `ControlMap` has), a tap of GUIDE shows the map during the match, and the robot still drives. A 1 s hold of GUIDE opens the tuning menu. | | Telemetry | your mechanisms' lines, drive mode, time. **START + BACK together** turns the debug lines on or off when you let go. With the alliance switch on, a 1.5 s hold of the pair switches the alliance instead. With a pause on BACK (`backTap()` and `pauseState()`, a Controls.java TeleOp), hold START first, then press BACK: BACK first only pauses. Without a pause job, either order works. | | Moving the buttons | You can move every one of the buttons above to another button, or free it: [`libraryButtons(lib)`](#moving-the-librarys-buttons). | | Warnings | PRACTICE profile, tuned values that differ from the code, slow button actions or `update()`s. At INIT: a freed pause button ("No pause button": nothing pauses the robot) or a freed field-centric button. | | Safety | The library ignores buttons held through ▶. The wheels and every mechanism stop at the end, even after an error. | ### Fill in | Method | Required? | What you return / do | | --- | --- | --- | | `robotConfig()` | yes* | `new RobotSettings()`: the [`RobotConfig`](https://crossbotics.com/ftc-helper/docs/modules/core/#robotconfig) shared with autonomous | | `createSubsystems()` | no | your mechanisms. Default: none | | `bindButtons(driver, operator)` | no | your buttons. Put gamepad 2 on `operator`, and extra gamepad 1 buttons on `driver` (they pause while the tuning menu is open). The library takes these on gamepad 1, unless you move them: LT, Y (field-centric, when the drive has it), BACK, START (with BACK: debug lines; START first when BACK pauses), GUIDE. | | `libraryButtons(lib)` | no | move or free the library's buttons ([below](#moving-the-librarys-buttons)) | | `setPoseJob()` | no | the "set pose here" job (it gives the words to show), or null (default). `Controls.java` gives one on a robot with odometry. Its button works in INIT too (held 1 s before ▶) | | `allianceChanged(now)` | no | update what uses the alliance when the driver switches it during the match (`Controls.java`: `robot.setAlliance(now)`) | | `everyLoop()` | no | your code for every loop (sticks for mechanisms, simple rules). It must not wait. | | `addTelemetry(t)` | no | extra screen lines | | `backTap()` | no | a job for a tap of BACK (a Controls.java TeleOp: pause everything). Then a 1 s hold of BACK resets "forward" | | `pauseState()` | no | how to read "paused now" (a `BooleanSupplier`), or null (default). With one, the pause button pauses at the PRESS, and a tap still goes on. This works even though BACK also has a held job. `Controls.java` gives one | | `buttonHelp()` | no | the button map's lines. Then a tap of GUIDE shows them, and a 1 s hold of GUIDE opens the tuning menu | | `addInitTelemetry(t)` | no | extra screen lines during INIT | | `onStart()` | no | runs once right after ▶, before the first loop. It is the first moment anything may move | \* Starter kit: `return new RobotSettings();`. Tutorials (09-20): `return RobotSettings.config();`. The tutorial `RobotSettings` keeps its settings in `static` methods, so `config()` wraps them. Without a `RobotConfig`, override `driveConfig()` and `createImu()`. Note: the bindings name the gamepad themselves (`Pad.G1`, `Pad.G2`). A `Pad.G1` button on `operator` works, but it does not pause while the tuning menu is open. So put gamepad 1 buttons on `driver`. ### Optional settings | Method | Default | | | --- | --- | --- | | `startFieldCentric()` | false | true = start in field-centric | | `slowSpeed()` | 0.3 | speed at a full squeeze of the slow trigger | | `fieldCentricButton()` | `Btn.Y` | the gamepad 1 button for field-centric on/off. It takes a double tap: one tap does nothing. Null = none. This is a shortcut: `libraryButtons` can put it anywhere | | `standardLibraryButtons()` | `LibraryButtons.twoDrivers()` | the defaults before `libraryButtons(lib)` (`Controls.java` uses the one-driver ones with `oneDriver`) | | `buzzAtSecondsLeft()` | {60, 20} | when both gamepads buzz | | `drive(gamepad)` | the standard controls | replace it to drive your own way, for example two-stick tank style: `driving().tank(-gamepad.left_stick_y, -gamepad.right_stick_y, 1)` | ### For your code | Method | Gives | | --- | --- | | `alliance()` | RED or BLUE | | `robotTelemetry()` | the screen helper ([RobotTelemetry](https://crossbotics.com/ftc-helper/docs/modules/telemetry/)) | | `driving()` | the [`DriverControls`](https://crossbotics.com/ftc-helper/docs/modules/drive/#drivercontrols) (field-centric, slow) | | `heading()` | the [`DriverHeading`](https://crossbotics.com/ftc-helper/docs/modules/drive/#driverheading), or null without an IMU | | `matchTimer()` | the [`MatchTimer`](https://crossbotics.com/ftc-helper/docs/modules/match/) | | `isTuningMenuOpen()` | whether the menu has gamepad 1. While it does, do not read gamepad 1's sticks | | `switchAlliance()` | switches BLUE / RED now. The START + BACK hold does this once `lib.switchAlliance(...)` turns it on | | `driveSpeed()` | the speed the library's slow buttons ask for now, 0 to 1 (for your own `drive(gamepad)`) | | `showNote(text)` | a warning at the top of the screen for 3 s (for example, to confirm a job) | | `libraryKeys()`, `libraryJobs(withMap)`, `keyWords(job)` | where the library's buttons are, which of its jobs this TeleOp has, and a job's button in words ("BACK") | ### Moving the library's buttons Every button above is the library's own job. You can move or free (`null`) each one in `libraryButtons(lib)`. A [`Key`](#moving-the-librarys-buttons) names one button on one gamepad: `Key.g1(Btn.X)`, `Key.g2(Btn.BACK)`, `Key.g1(Trigger.RT)`. In `Controls.java`, write `g1.x`: each button there is a Key. ```java @Override protected void libraryButtons(LibraryButtons lib) { lib.fieldCentric(Key.g1(Btn.X)) // field-centric on/off: X instead of Y .slow(Key.g1(Trigger.RT)) // slow on the right trigger .switchAlliance(Key.g1(Btn.BACK), Key.g1(Btn.START)); // optional: turn on the alliance switch } ``` | `LibraryButtons` | Default (`twoDrivers()`; `oneDriver()` in brackets) | How it works | | --- | --- | --- | | `pause(key)` | G1 BACK | runs `backTap()` (Controls.java: pause everything). With `pauseState()`, a press pauses at once, and a tap goes on. A 1 s hold runs the hold job too, still paused. A pair with this button forms only when its other button went down first, so a pair never takes a pause back. Without `pauseState()`, a tap. Without `backTap()`, nothing. Null: INIT warns "No pause button" | | `resetForward(key)` | G1 BACK | a 1 s hold when its button has a quick job (pause), or else a tap. Field-centric only (in robot-centric, a note) | | `debug(key, with)` | G1 START + BACK | both together; it runs when you let go. When one is the pause button, the other goes first (hold START, then press BACK; BACK first only pauses). `with` null = one button | | `switchAlliance(key, with)` | none (off) | turns it on: hold both for 1.5 s (`SWITCH_ALLIANCE_SEC`). With the pause button in the pair, the other goes first. `with` null = hold one button | | `setPose(key)` | G1 START | a 1 s hold (`HOLD_SEC`), in INIT too. Only with a `setPoseJob()`. START + A/B (pairing a gamepad) cancels it | | `slow(key)` | G1 LT (none) | a trigger: the further you squeeze, the slower. A button: slow while held | | `slowToggle(key)` | none (G1 left stick click) | each press turns slow on or off | | `fieldCentric(key)` | G1 Y (G1 right stick click) | a press. Only where field-centric works | | `buttonMap(key)` | G1 GUIDE | a tap. Only with `buttonHelp()` | | `tuningMenu(key)` | G1 GUIDE | a 1 s hold when its button shows the map, or else a tap | | `allianceInInit(blue, red)` | G1 X, G1 B | INIT only, and not while START is held (START + A/B pairs a gamepad) | | `swapSticks(boolean)` | false | true: the right stick drives, and the left stick X turns ([`DriverControls.swapSticks`](https://crossbotics.com/ftc-helper/docs/modules/drive/#drivercontrols)) | | `moveAllToGamepad1()` | - | one driver: every gamepad 2 button of these jobs goes to gamepad 1 (Controls.java does it) | | `key(job)`, `with(job)`, `initBlue()`, `initRed()`, `sticksSwapped()`, `words(jobs)` | - | read them back. `words` checks them and gives each button's words for the map | **Checked at INIT** (the message names the button): - a button with two quick library jobs, or two held ones - the slow key with another job - a pair on two gamepads, or with one button twice - the tuning menu on a button the menu itself uses (gamepad 1 D-pad, A, B, X, Y, LB, RB) While a pair is down, its buttons' own jobs wait until you let go. While the tuning menu is open, only its button works. `runOpMode()` is `final`: your class cannot replace it, so the safety steps always run. For a completely different loop, write a plain `LinearOpMode` (tutorials 04 and 12) with the same parts. --- # Testing module URL: https://crossbotics.com/ftc-helper/docs/modules/testing/ Learn it hands-on: [Check the hardware (tutorial 19)](https://crossbotics.com/ftc-helper/docs/tutorials/19-testing-procedures/). Full guide: [Checks before practice and matches](https://crossbotics.com/ftc-helper/docs/tests/03-checks-before-practice-and-matches/). The hardware check tests that every motor, servo and sensor is wired and named right, before you write robot code. Run it on a new robot, after you rewire, and whenever a part acts strangely. It needs no code from you, only the tiny file below. ## HardwareCheckOpMode `HardwareCheckOpMode` is a ready-made OpMode. It lists every device in the active robot configuration, and you test each one. Make this tiny file in TeamCode: ```java @TeleOp(name = "Hardware Check", group = "Test") // "extends": it IS the library's hardware check; the empty { } adds nothing of our own public class HardwareCheck extends HardwareCheckOpMode { } ``` It finds these devices: motors, continuous-rotation (CR) servos that spin like a motor, servos, the IMU and touch sensors. It also finds digital channels (magnetic switches, beam breaks), color and distance sensors, analog inputs, webcams, Limelights and HuskyLens cameras. For a HuskyLens, it shows each box the camera sees, with the taught number. It also shows the battery voltage, and it warns below 12.0 V. Slow reads (a HuskyLens, a distance sensor) run on a helper thread, so the buttons never wait. Because of this, a distance can show one read late. **With your robot in five files**, give the check your robot. Then INIT also checks Robot.java against the configuration. It shows one line for each device that Robot.java names and the configuration does NOT have, and what that means. ```java public class HardwareCheck extends HardwareCheckOpMode { @Override protected RobotDefinition robot() { return new Robot(); } } ``` ``` Robot.java devices not in this configuration: "lift" (Lift): NOT in the configuration: INIT will stop. Add it, or add .optional() to Lift in Robot.java "intake_deploy" (IntakeDeploy): not in the configuration: optional, so the part is off (fine) ``` The check lists a part marked `optional()` ([parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)), but it is not an error. When every device is there, it shows `Robot.java: every device is in the configuration`. | Gamepad 1 | What it does | | --- | --- | | D-pad up / down | choose a device. The device you leave stops | | Motor or CR servo: right stick Y | power, at most 50% (hold the right bumper for 100%) | | Motor: A | zero the encoder | | Servo, before its first move: D-pad right / left, bumpers, X | choose the START POINT: +/- 0.01, +/- 0.1, 0.5 (nothing moves) | | Servo, before its first move: A | move the servo to the start point | | Servo: D-pad right / left | +/- 0.01 | | Servo: bumpers | +/- 0.1 | | Servo: X | go to 0.5 | | GUIDE (or hold the gamepad's START button 1 s) | the help page with every button, like the finders. The motors stop while it is open. `helpLines()` gives its lines: override it to add your own | **A servo does not move until you press A at its start point.** A servo cannot tell where it is, so the code does not know where it sits. Before the first move, the servo buttons only change the start point on the screen (it starts at 0.5). Set the start point near where the servo sits now, keep hands clear, then press A: the servo moves there. After that, the buttons move it. The [Servo Finder](https://crossbotics.com/ftc-helper/docs/modules/finders/#servofinderopmode) works the same way, and it also finds the safe ends and positions. For each device, the hardware check shows what to check, for example "positive power turns the way you expect, and the encoder counts UP". **Put the robot on a block** before you test the drive motors. --- # Test kit module URL: https://crossbotics.com/ftc-helper/docs/modules/testkit/ Learn it hands-on: [13 Testing](https://crossbotics.com/ftc-helper/docs/tutorials/13-testing/#7-test-your-robot-in-five-files). Guide: [Run all your tests: laptop tests](https://crossbotics.com/ftc-helper/docs/tests/02-run-all-your-tests/#4-for-programmers-laptop-tests-in-java-optional). The test kit gives you pretend motors, servos and switches for **JUnit tests on a laptop**. Your `Robot.java` (the robot in five files) runs on them instead of the real hardware. A test sets the robot up (INIT) and presses ▶ (start on the Driver Hub). Then it runs a loop and checks what the robot sent to each motor and servo. A test needs no robot and no Control Hub, and it takes a second. So you can run the tests after every change. | Class | Use it to | | --- | --- | | [`PretendDevices`](#pretenddevices) | give your robot pretend devices instead of the hardwareMap | | [`PretendMotor`](#pretendmotor-pretendservo-pretendcrservo) | read the power sent, set the encoder | | [`PretendServo`](#pretendmotor-pretendservo-pretendcrservo) | read the position sent | | [`PretendCRServo`](#pretendmotor-pretendservo-pretendcrservo) | read the power sent to a CR servo | | [`PretendPinpoint`](#pretendpinpoint) | a goBILDA Pinpoint that says the robot is where the test puts it | | [`PretendTelemetry`](#pretendtelemetry) | read what the Driver Station would show | | [`PretendClock`](#pretendclock) | move the time forward by hand: a timing test does not wait | **Why it is in the library:** a team's tests (in `TeamCode/src/test`) can use it with no extra Gradle lines (only JUnit, [tutorial 13](https://crossbotics.com/ftc-helper/docs/tutorials/13-testing/#3-set-up-teamcode-for-tests-once)). It is a few small classes. Nothing in it runs on the robot unless a test makes it. ## PretendDevices ```java PretendDevices devices = new PretendDevices(); // a fresh pretend robot Robot robot = new Robot(); robot.setup(devices); // INIT (Tunables.java as written; INIT's checks run) robot.startForTests(); // ▶ (start) robot.lift.goTo("high"); robot.all().update(); // one loop assertTrue(devices.motor("lift").power > 0); // the lift motor got power up devices.motor("lift").position = 2400; // the pretend encoder: at the top devices.press("lift_bottom", true); // a pretend switch pressed ``` | Method | What it does | | --- | --- | | `new PretendDevices()` | a pretend configuration where every name the robot asks for exists. Each test starts like a robot that you turned on a moment ago. For that, it forgets what the library keeps between programs (tuned numbers in memory, a turret's last angle, a launcher's last trim, autonomous's alliance: `RobotDefinition.freshRobotApp()`). It uses an empty temporary settings file. Its motors read their pretend encoder every time (no 3 ms reuse) | | `motor(name)`, `servo(name)`, `crServo(name)`, `pinpoint(name)` | the pretend device with that name. It makes the device now when there is none yet | | `press(name, pressed)` | press or let go of a pretend switch (a touch sensor, or a magnetic switch on a digital port) | | `analog(name, volts, maxVolts)` | a pretend analog input (an absolute encoder) | | `notConfigured(names...)` | takes these names out of the configuration. Use it to test an `optional()` part, or `checkConfiguration` | | `battery(volts)` | the battery the hubs read | | `get`, `tryGet`, `has` | what the robot asks ([`Devices`](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition)). The kit has no pretend camera or color sensor. Such a device counts as not plugged in: a part that can do without it warns and goes on | With the robot: `robot.setup(devices)` (INIT), `robot.startForTests()` (what ▶ does), `robot.all().update()` (one loop), `robot.pauseAll()` / `robot.resume()` (BACK), `robot.all().stop()` (STOP), `robot.checkTunables()` (the Tunables name checks, with no devices). More: [RobotDefinition](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition). **What it cannot do:** move anything. A pretend motor's encoder stays where your test puts it. Time does not pass by itself, so an action's `waitSeconds` never ends in a test. There is no camera picture. For these, use the [simulator](https://crossbotics.com/ftc-helper/docs/simulator/). A scenario file is a test too. ## PretendMotor, PretendServo, PretendCRServo Each pretend device has plain fields. Your test reads and sets them: | Class | Fields | | --- | --- | | `PretendMotor` | `power` (last sent), `position` (the encoder: set it), `velocity`, `currentAmps`, `direction`, `zeroPower`, `mode`, `powerWrites`, `maxAbsPower`, `failSetPower` (true: `setPower` throws an error, like an unplugged motor), `motor` (the SDK `DcMotorEx`) | | `PretendServo` | `position` (last sent; NaN = never), `writes`, `direction`, `pulseUs` (set by `.fullRange()`), `servo` (the SDK `Servo`) | | `PretendCRServo` | `power`, `writes`, `direction`, `servo` (the SDK `CRServo`) | ## PretendPinpoint A robot with `odometry(Odometry.pinpoint("pinpoint"))` gets one at INIT. It moves only when your test moves it: ```java devices.pinpoint("pinpoint").moveTo(10, 0, 90); // the device's own frame: x forward, y left (inches), degrees robot.all().update(); // robot.pose() now has it (from the start spot) ``` | Member | What it is | | --- | --- | | `x`, `y`, `headingDeg` | where the device says it is (its own frame, inches and degrees) | | `moveTo(x, y, headingDeg)` | sets all three | ## PretendTelemetry ```java PretendTelemetry screen = new PretendTelemetry(); RobotTelemetry t = new RobotTelemetry(screen.telemetry); robot.all().addTelemetry(t); t.update(); assertTrue(screen.has("Lift : high")); ``` | Member | What it is | | --- | --- | | `telemetry` | the SDK `Telemetry` to hand over | | `lastScreen` | the last screen sent, one line per entry (`"Lift : high 900 ticks"`, `"!! warning"`) | | `has(words)` | whether a line of the last screen contains them | | `updates` | how many screens the robot sent | ## PretendClock With the real clock, a timing test must wait, and a slow computer can make it fail when the code is fine. The pretend clock moves only when your test moves it. The robot's parts read the library's clock ([`Time`](https://crossbotics.com/ftc-helper/docs/modules/core/#time)). So with a pretend clock, a timing test ("the arm pushes 0.2 s after fire") runs at once. It gives the same result on every computer. ```java @After public void realClock() { PretendClock.stopUsing(); // (1)! } @Test public void theArmPushesAfterStaging() { PretendClock clock = PretendClock.use(); PretendDevices devices = new PretendDevices(); Robot robot = new Robot(); robot.setup(devices); robot.startForTests(); PretendMotor fly = devices.motor("launcher"); robot.launcher.spinUp(); for (int i = 0; i < 100; i++) { // 0.5 s, 5 ms a loop clock.addSec(0.005); // (2)! fly.velocity = fly.velocityCommand; // (3)! robot.all().update(); if (i == 60) robot.launcher.fire(); // at 0.3 s } assertEquals(0.7, devices.servo("feeder_arm").position, 1e-9); } ``` 1. The next test gets the real clock again. 2. The clock is 5 ms later at once, and nothing waits. The whole loop takes far less than a second. 3. A pretend motor does not speed up by itself. This line says that the wheel reached the speed the robot asked for. Without it, the flywheel is never ready, and nothing fires. | Member | What it does | | --- | --- | | `PretendClock.use()` | makes a pretend clock and has the robot's parts use it (the only way to make one) | | `PretendClock.stopUsing()` | goes back to the real clock (in `@After`) | | `addSec(sec)` | moves the time forward (seconds, 0 or more) | | `sec()` | the time now, seconds (it starts at 1) | A part that waits for a helper thread still needs real time, because the thread runs on its own. Two examples: a camera, a distance sensor on the library's helper thread. The camera aim also keeps the real clock, because the camera stamps its pictures with it. **Always** call `PretendClock.stopUsing()` in `@After`. A pretend clock that stays in use stops time for every later test. Their flywheels are never ready, and their time limits never end. --- # Tuning module URL: https://crossbotics.com/ftc-helper/docs/modules/tuning/ Learn it hands-on: [15 Telemetry, profiles and tuning](https://crossbotics.com/ftc-helper/docs/tutorials/15-telemetry-profiles-tuning/). Full guide: [Tuning while the robot runs](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/). With this module you change numbers from the gamepad while the robot runs, with no rebuild. Use it to tune PID gains, positions and speeds fast in the shop. A **tunable** is one number the menu can change. `PositionMotor.tunable(...)` and the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/tunables/) make their numbers tunable for you. This page is for your own numbers, and for how the menu works. | Class | Use it to | | --- | --- | | [`Tunable`](#tunable) | make one number changeable from the menu | | [`PidTunables`](#pidtunables) | make the four PID gains of a controller tunable | | [`TuningMenu`](#tuningmenu) | show the on-screen menu that changes them (PRACTICE profile only) | --- ## Tunable ```java // static final: one shared Tunable, made once (the number inside can still change) static final Tunable LIFT_KP = Tunable.number("Lift/kP", 0.004, 0.0005); // name, code value, step ... pid.setGains(LIFT_KP.get(), 0, 0, 0); // read it every loop ``` | Method | What it does | | --- | --- | | `Tunable.number(name, value, step)` | makes one ("Group/Name"), or gives the one that already has that name (the first code value stays) | | `Tunable.fromCode(name, value, step)` | the same, but an existing one that nobody tuned takes this code value. `PositionMotor.tunable`, `PositionServo.tunable`, `PidTunables.of` and the robot in five files use it. So two programs that use one name each use their own numbers | | `.range(min, max)` | the menu cannot go outside this range | | `get()` | the value now (read it every loop) | | `set(v)`, `increase()`, `decrease()`, `reset()` | change it in memory | | `isChanged()` | whether it differs from the code value | | `name()`, `group()`, `defaultValue()`, `step()`, `display()` | read its name, group, code value, step and display text | | `Tunable.all()` | every tunable the code made | | `Tunable.shown()` | the ones the tuning menu shows: all except those of a part that is not on the robot | | `Tunable.hideGroup(group, hidden)`, `Tunable.hiddenGroups()`, `isHidden()` | leaves a group ("IntakeDeploy") out of the menu, or shows it again. The robot in five files does this at every INIT for a part marked `optional()` whose device is missing ([parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)). The saved values stay | | `Tunable.saveAll()` | saves the changed ones on the hub. It waits until the storage is done | | `Tunable.saveAllInBackground(ok -> ...)`, `Tunable.resetAllInBackground(ok -> ...)` | the same, without waiting. The tuning menu uses these | | `Tunable.resetAll()` | puts all back to the code values, and deletes the saved values | | `Tunable.countChanged()` | how many differ from the code. EasyAuto warns about them in INIT | | `Tunable.forgetAllForTests()` | for JUnit tests only: forgets every tunable in memory, so one test's robot does not see another's numbers ([`PretendDevices`](https://crossbotics.com/ftc-helper/docs/modules/testkit/) does it). Never use it in robot code | | `Tunable.changedAsCode()` | the ones that differ, as lines to copy into the code: `"Lift: kP = 0.005"` (in `Tunables.java`, class `Lift`) | **Saved values come back after a restart.** That makes tuning fast. It is also a risk: the robot uses a value tuned in the shop at the event, even when the code says something else. So when a number is good, **copy it into the code** and press "reset all". The code is the record. ## PidTunables ```java // name prefix, then the code values of kP, kI, kD, kF static final PidTunables LIFT = PidTunables.of("Lift", 0.004, 0, 0.0002, 0.05); LIFT.applyTo(liftPid); // every loop: copies the menu's values into the controller ``` `PidTunables.of` makes "Lift/kP", "Lift/kI", "Lift/kD" and "Lift/kF". Each step is 1/8 of the value. `PositionMotor.tunable("Lift")` does this for you, and also makes every named position tunable. ## TuningMenu ```java TuningMenu menu = new TuningMenu(gamepad1); controls.bindPress(Pad.G1, Btn.GUIDE, menu::toggle); // center button opens/closes it // every loop: menu.update(); if (menu.isOpen()) menu.addTelemetry(t); // the menu shows only while it is open ``` | While open | What it does | | --- | --- | | D-pad up / down | choose a number | | D-pad right / left | change by one step (hold a bumper for x10) | | A | save all on the hub | | X | put the chosen one back to its code value | | Y | put ALL back to the code values, and delete the saved values | | B | show the changed values as lines to copy into the code. They also go in the robot log, tag `ftc-helper`. Press B again for the list | The menu opens only in the PRACTICE profile. **Do not drive with the same gamepad while it is open.** Check `menu.isOpen()`, and stop reading the sticks while it is true. The starter kit's TeleOp shows how. --- # Util module URL: https://crossbotics.com/ftc-helper/docs/modules/util/ Learn it hands-on: [06 A fast, clear loop](https://crossbotics.com/ftc-helper/docs/tutorials/06-fast-clear-loop/), [10 Autonomous with mechanisms](https://crossbotics.com/ftc-helper/docs/tutorials/10-auto-with-mechanisms/), [13 Testing](https://crossbotics.com/ftc-helper/docs/tutorials/13-testing/). Small helpers for number math, angle math, a loop timer, and passing the robot's position from autonomous to TeleOp. The rest of the library uses them, and you can use them in any code you write. They need no setup. | Class | Use it to | | --- | --- | | [`MathUtil`](#mathutil) | keep a number in a range, ignore tiny values, blend two numbers, compare, scale down together | | [`Angles`](#angles) | do math with headings (the -180/180 seam) | | [`LoopTimer`](#looptimer) | see how fast your loop runs | | [`FieldPose`](#fieldpose) | hold a pose: x, y and heading | | [`PoseStore`](#posestore) | pass the robot's pose from Autonomous to TeleOp | | [`BackgroundWorker`](#backgroundworker) | run slow jobs (network, camera settings) without stopping the loop | | [`Spelling`](#spelling) | "did you mean ...?" for a name typed by hand | --- ## MathUtil | Method | What it does | Example | | --- | --- | --- | | `clamp(value, min, max)` | keeps a number inside a range. NaN ("not a number", for example 0 / 0) gives 0, a safe value for a motor. It also works with `int`. | `clamp(1.3, -1, 1)` = 1.0 | | `deadband(value, band)` | turns values smaller than `band` into 0 | `deadband(0.03, 0.05)` = 0 | | `deadbandScaled(value, band)` | the same, but it starts again from 0 at the band edge, so there is no jump | `deadbandScaled(0.55, 0.1)` = 0.5 | | `lerp(a, b, t)` | the number `t` of the way from a to b (0 = a, 1 = b, 0.25 = a quarter of the way) | `lerp(0, 10, 0.25)` = 2.5 | | `isNear(a, b, tolerance)` | true when a and b are within tolerance of each other | `isNear(100, 103, 5)` = true | | `normalize(values, limit)` | scales an array down together so none is over `limit` | `[2, 1, -1, 0]`, 1 gives `[1, 0.5, -0.5, 0]` | ## Angles Headings go around a circle, so plain subtraction gives a wrong answer near the -180/180 seam. From 170 to -170 is a 20 degree turn, but -170 - 170 = -340. | Method | What it does | Example | | --- | --- | --- | | `wrapDegrees(deg)` | writes any angle as an angle between -180 and 180 | `wrapDegrees(190)` = -170 | | `shortestDiff(target, current)` | the shortest turn from current to target. Positive = turn left (counterclockwise). | `shortestDiff(-170, 170)` = 20 | ## LoopTimer ```java LoopTimer loopTimer = new LoopTimer(); while (opModeIsActive()) { loopTimer.update(); // top of every loop telemetry.addData("Loop", "%.0f Hz", loopTimer.getHz()); // loops per second, no decimals ... } ``` | Method | What it does | | --- | --- | | `update()` | call it once at the top of each loop. It gives the seconds since the last call. | | `getHz()` | loops per second, smoothed. 50-200 is usual. Below 30, the robot feels laggy. | | `getAverageMs()` | the average loop time in milliseconds | | `getLastSeconds()` | how long the last loop took | | `reset()` | starts over | A slow loop makes the robot lag. To speed it up, turn on [bulk reads](https://crossbotics.com/ftc-helper/docs/modules/hardware/#bulkreads), send fewer telemetry lines, and check that nothing in the loop calls `sleep()`. ## FieldPose An x and y in inches, and a heading in degrees (counterclockwise is positive). The library does not decide where (0, 0) is on the field. Your team decides that each season and writes it down. | Member | Meaning | | --- | --- | | `new FieldPose(x, y, headingDeg)` | makes one (`new FieldPose()` = 0, 0, 0) | | `x`, `y`, `headingDeg` | the values. You can read and change them | | `copy()` | a separate copy | | `toString()` | text like `(12.0 in, -3.5 in, 90.0 deg)` | ## PoseStore Passes the robot's last pose from Autonomous to TeleOp. Both run in the same app, so a saved value stays between them. It is lost when the app restarts or the robot loses power. ```java // End of Autonomous: PoseStore.save(new FieldPose(x, y, auto.headingDeg())); // inches, inches, degrees (left = +) // TeleOp INIT: FieldPose start = PoseStore.consume(); // null if autonomous did not save one if (start != null) { ... use it ... } // always check for null first // For the heading alone, use DriverHeading (docs/modules/drive.md): it does this for you. ``` | Method | What it does | | --- | --- | | `save(pose)` | saves a copy. It ignores `null`. | | `consume()` | gives the saved pose and forgets it, so your code uses it once. `null` when there is none. | | `peek()` | gives a copy and keeps it saved | | `has()` | true when a pose is saved | | `clear()` | forgets it | | `ageSec()` | seconds since the save (very large when there is none). Over a few minutes means it is from an earlier match. | ## BackgroundWorker Runs slow jobs on its own **thread** (a second line of work that runs at the same time as your loop). So the robot's loop never waits. The library uses it for the Limelight's network requests and the webcam settings. Guide: [Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/). ```java // "() -> ..." is a lambda: the slow job, handed over to run on the worker's own thread BackgroundWorker worker = new BackgroundWorker("my-sensor"); worker.submitLatest("setting", () -> sensor.slowSetting(value)); // returns at once worker.shutdown(); // in stop() ``` | Method | What it does | | --- | --- | | `new BackgroundWorker(name)` | starts the thread (a daemon: it never keeps the app from closing) | | `submit(job)` | puts a job in the queue | | `submitLatest(key, job)` | puts a job in the queue in place of a waiting job with the same key (only the newest runs) | | `queued()`, `getLastError()`, `isRunning()` | read the worker's state. A job that throws an error never crashes the robot | | `shutdown()` | stops the worker. It drops the waiting jobs | Never move motors or servos from a background job. Only the loop does that. ## Spelling "Did you mean ...?" for names typed by hand. The library's messages use it for a position name with a typo (`no position called "lvel" (did you mean level?)`), a claw's `closd`, or a misnamed Tunables section. ```java String like = Spelling.closest("closd", Arrays.asList("open", "closed")); // "closed" (null if none is close) int d = Spelling.distance("closd", "closed"); // 1 letter off ``` | Method | What it does | | --- | --- | | `closest(name, known)` | the known name that `name` is most likely a typo of, or null. Capitals and `_` never matter. A name of 5 letters or more may be 2 letters off. A shorter one (3 or 4 letters) may be 1 letter off | | `distance(a, b)` | how many letters must be added, removed or changed to turn `a` into `b` | --- # Vision module URL: https://crossbotics.com/ftc-helper/docs/modules/vision/ Learn it hands-on: [18 Vision aiming](https://crossbotics.com/ftc-helper/docs/tutorials/18-vision-aim/). Find **AprilTags** (square black-and-white field markers, each with an id number) and aim at them. Use a USB webcam, a Limelight 3A or a HuskyLens camera. Your code talks to ONE interface (a set of methods every camera has), so you switch cameras by changing one line. With the [robot in five files](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/), its `Camera` part sets this up: start with [Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/). Use this page to aim in your own code (tutorial 18). The **bearing** is how far the robot must turn to face a target, in degrees (+ = the target is to the left). | Class | Use it to | | --- | --- | | [`TargetSource`](#targetsource) | talk to any camera the same way (the interface) | | [`WebcamTags`](#webcamtags) | find AprilTags with a USB webcam (the SDK's tag finder; SDK 12 clusters too) | | [`HuskyLensCamera`](#huskylenscamera) | find taught AprilTags, colors or an object with a HuskyLens | | [`LimelightTags`](#limelighttags) | find AprilTags with a Limelight 3A | | [`TagGroup`](#taggroup) | report a row of tags as one target with a Limelight or a HuskyLens | | [`TargetObservation`](#targetobservation) | read one target: id, name, bearing, distance, picture time | | [`AimController`](#aimcontroller) | turn the bearing into a turn power, safely | | [`MovingShot`](#movingshot) | the math of shooting while moving: an old picture brought to now, the lead for the flight time | | [`DistanceFilter`](#distancefilter) | keep camera glitches out of a distance (the middle of the last pictures, and a jump check) |
flowchart LR
    W["WebcamTags"] --> S(["TargetSource"])
    L["LimelightTags"] --> S
    N["next year's camera"] -.-> S
    S --> O["TargetObservation<br/>bearing (+ = left), distance, time"]
    O --> A["AimController -> drive turn"]
    O --> T["turret.aimAtTarget(target, onTurret)"]
    O --> D["launcher.setDistance(distance)"]
**2026-27 note:** BIOBUZZ tags are on the HIVE cells, and the cells MOVE. So the tags are good for aiming, but not for finding the robot's position on the field. SDK 12 also adds tag **clusters** (groups of tags with one aiming point). `WebcamTags` reports a cluster as a target with id `TargetObservation.CLUSTER` and its name. `LimelightTags` reports the same groups by the same names ([TagGroup](#taggroup)), so `camera.target("RED SCORING")` works with either camera. **Aim at the up CELL only.** Each HIVE has two CELLs. A robot can score only in the up one, and a tip swaps them. A CELL's tags read **right side up** only while that CELL is up. The down CELL's tags read upside down. `TagGroup.goalTarget(camera, "RED SCORING")` gives the red HIVE's group that reads right side up now ("RED SCORING" or "RED AUDIENCE"). It gives null when only an upside-down CELL is in view, for example from under the HIVE. The robot must never aim at the underside of a down CELL. The five-files [`Camera`](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/) module's `goal()` uses it. `camera.target(name)` still gives the named group, upside down or not. --- ## TargetSource | Method | What it does | | --- | --- | | `start()` | starts the camera (in INIT; a webcam needs 1-2 s) | | `update()` | every loop: gets the newest picture's targets | | `targets()` | everything in the newest picture. It drops targets older than 500 ms, so a camera that stops sending never leaves old targets | | `target(id)` / `target(name)` | one target, or null when the camera does not see it | | `isWorking()`, `status()` | whether it is streaming, and its state, for example "STREAMING 28 fps", "not connected" | | `close()` / `stop()` | frees the camera | | `addTelemetry(t)` | a warning when it is not working. In debug: the status and every target | ## WebcamTags ```java WebcamTags camera = WebcamTags.create(hardwareMap, "Webcam 1") .resolution(640, 480) // pixels: a good start .decimation(2) // 2 = default balance of speed and range .exposure(6, 85); // optional: short exposure = sharp tags while driving camera.start(); // in INIT: a webcam needs 1-2 s to start ``` | Method | What it does | | --- | --- | | `.resolution(w, h)` | 640x480 to start. A higher one sees farther but is slower | | `.decimation(d)` | how much the camera shrinks the picture before the tag search: 1 = slow/far, 2 = default, 3 = fast/near | | `.liveView(on)` | the picture on the Robot Controller screen (it costs speed) | | `.library(lib)` | another tag library (default: this season's, from the SDK) | | `.exposure(ms, gain)` | manual exposure. `status()` says when the camera refused it | | `.autoExposure()` / `.autoExposure(6, 3, 12, 0)` | [venue lighting](#venue-lighting): tries exposures in INIT (ms; 0 = the camera's own automatic) and keeps the best | | `.gain(g)` | the gain for `autoExposure`'s manual exposures (default: the camera's highest) | | `lighting()` / `matchStarted()` | the lighting test (null without `autoExposure`); tells it that the driver pressed ▶ (start on the Driver Hub) | | `.keepTargetsMs(ms)` | how long targets stay in `targets()` without a new picture (default 500) | | `.pitchDeg(degrees)` | the camera's tilt up (0 = level, the default), so bearings and distances are along the floor ([CameraTilt](#cameratilt)) | | `.upsideDown(on)` / `isUpsideDown()` | the webcam is mounted upside down: each target's bearing and roll are turned back (left is left, a right-side-up tag reads right side up). The live view stays upside down | | `WebcamTags.convert(detection)` / `convert(detection, pitchDeg)` / `convert(detection, pitchDeg, upsideDown)` | turns an SDK detection into a TargetObservation (level, tilted, or upside down) | | `WebcamTags.facingDeg(detection, pitchDeg, upsideDown, bearingDeg)` | which way the tag's face points along the floor (the observation's `facingDeg`), from the SDK's raw pose; NaN with no raw pose or a face pointing almost straight up or down | For better distances, calibrate the camera (the FTC docs explain "camera calibration"). Or use a camera the SDK already knows (Logitech C270/C920 at common resolutions). ## CameraTilt A camera tilted up (to see a high goal) measures in its own tilted view. So a goal off to the side reads too few degrees. For example, with the camera 35 degrees up, 27.5 degrees left reads about 22 (goal 48 inches away along the floor, 35 inches above the lens). Its distance is the slanted line from the lens up to the goal. The aim and the odometry need the bearing and the distance **along the floor**. `CameraTilt` turns the camera's numbers flat again to give them. ```java WebcamTags camera = WebcamTags.create(hardwareMap, "Webcam 1").pitchDeg(35); // tilted 35 degrees up // In the robot in five files: Tunables.Webcam1.pitchDeg = 35 ``` | Method | What it does | | --- | --- | | `CameraTilt.bearingDeg(right, forward, up, pitchDeg)` | the floor's bearing (+ = left) of a point in the camera's view (right, along the lens, up in the picture) | | `CameraTilt.floorDistance(right, forward, up, pitchDeg)` | its distance along the floor (same length unit) | `pitchDeg`: + = tilted up, 0 = level (nothing changes). Measure it on the robot: put a phone's level app on the camera's face. A webcam and a Limelight use it. A HuskyLens does not use it yet. ## LimelightTags ```java LimelightTags camera = LimelightTags.create(hardwareMap, "limelight") .pipeline(0) // pipeline 0, set up on the Limelight's web page .pollRate(100); // results per second camera.start(); ``` A **pipeline** is a saved set of Limelight settings for one kind of target. First set up an AprilTag (fiducial) pipeline in the Limelight's web page (http://limelight.local:5801 on the robot network). For distances, set the correct tag size there. | Method | What it does | | --- | --- | | `.pipeline(n)` | which pipeline. If the camera has already started, it also switches at once | | `.autoPipelines(0, 1, 2)` | [venue lighting](#venue-lighting): tries these pipelines in INIT and keeps the best (replaces `.pipeline`) | | `.pitchDeg(degrees)` | the Limelight's tilt up (0 = level, the default), so bearings and distances are along the floor ([CameraTilt](#cameratilt)) | | `lighting()` / `matchStarted()` | the lighting test (null without `autoPipelines`); tells it that the driver pressed ▶ | | `.pollRate(hz)` | results per second | | `setRobotHeading(deg)` | for the Limelight's MegaTag2 position feature (aiming does not need it). Safe every loop: the library sends it in the background | | `fieldSighting()` | **alpha**: the robot's field position from the newest picture (`FieldSighting`: `mt2XIn`, `mt2YIn`, `mt1XIn`, `mt1YIn`, `mt1YawDeg`, `tags`, `timeNanos`, `number`), in the Limelight's field frame; NaN when there is none. The [camera fix](https://crossbotics.com/ftc-helper/docs/modules/odometry/#camera-fix-alpha) uses it | | `.keepTargetsMs(ms)` | how long targets stay without a new picture (default 500) | | `.groups(list)` | tag groups to report as one target each (default `TagGroup.currentSeason()`; empty list = off) | | `getLimelight()` | the SDK object, for color pipelines and more | | `LimelightTags.distanceInches(pose)` | the distance from a 3D pose | The Limelight's pipeline switch and heading updates are network requests that wait for an answer. The library sends them on a background thread, so they never slow the loop. The library flips the sign of the Limelight's `tx`, so the bearing is **positive to the LEFT**, like everywhere else. The picture time includes the Limelight's own capture and processing time, so the picture's age is honest. The library never reports the same picture twice. ## HuskyLensCamera A [DFRobot HuskyLens](https://wiki.dfrobot.com/sen0305/) is a small camera with a screen and two buttons. It finds AprilTags, colors or one object by itself. It plugs into an I2C sensor port of a hub, not USB. The FTC docs suggest bus 1, 2 or 3, because bus 0 has the hub's IMU. It does not use the SDK's VisionPortal. The SDK has the driver, and the [FTC docs](https://ftc-docs.firstinspires.org/en/latest/devices/huskylens/huskylens.html) show the wiring. goBILDA sells one with a cable that fits a REV hub. Configure it as `HuskyLens`. ```java HuskyLensCamera camera = HuskyLensCamera.create(hardwareMap, "huskylens") .tag(1, 34).tag(2, 35) // taught number 1 is AprilTag 34, taught number 2 is AprilTag 35 // (1)! .hfovDeg(60) // its view angle: measure yours // (2)! .sizeIn(3.25); // for a rough distance: the tag's black square, in inches // (3)! camera.start(); // every loop: camera.update(); TargetObservation tag = camera.target(34); ``` 1. **It never says a tag's real number.** It says the number you taught it. Without `tag(...)`, `target(34)` finds nothing. 2. The seller gives no view angle, so the library uses a guess of 60 until you measure it. See below. 3. Without `sizeIn`, `distanceIn` is `NaN` (no distance). **Teach it, on the camera.** Turn the dial to Tag Recognition. Long press the dial, turn on **Learn Multiple**, and save. Point the `+` at a tag and press the learning button: that tag is ID1. For ID2, press the learning button again before the countdown ends, and so on. An untaught tag has the number 0. This comes from the camera's protocol, and test AIM-06 checks it. Write the list down: the numbers in `tag(...)` must match the order you taught. | Method | What it does | | --- | --- | | `create(hardwareMap, name)` | finds it in the robot configuration | | `mode(Mode.TAGS / COLORS / OBJECTS)` | what to look for (default `TAGS`). `OBJECTS` follows ONE taught object. You can change it in a running OpMode | | `tag(taughtNumber, tagNumber)` | which real AprilTag a taught number is | | `label(taughtNumber, name)` | a name for `target(name)`, for example a taught color: `label(1, "POLLEN")` | | `hfovDeg(degrees)` | the view angle, from the left edge to the right edge of the picture | | `sizeIn(inches)` | the real size of what it looks at (its longest side as the camera sees it), for a rough distance | | `groups(list)`, `keepTargetsMs(ms)` | the same as on the Limelight | | `mode()`, `latestBlocks()`, `getHuskyLens()` | the mode now, the SDK's boxes, the SDK's object (for example for line tracking's arrows) | | `HuskyLensCamera.answers(device)` | asks "are you there?" and checks the answer. It is slow, so never call it in the robot's loop | | `start()`, `update()`, `targets()`, `target(...)`, `isWorking()`, `status()`, `close()` | see [`TargetSource`](#targetsource) | **Measure the view angle.** Stand a thin stick 24 in straight in front of the lens. Move it sideways until it touches the edge of the screen. Measure how far it moved, in inches (`s`). The angle is `2 * atan(s / 24)`: 14 in sideways gives about 60 degrees. A wrong angle makes bearings too big or too small. But 0 is still straight ahead, so aiming still ends in the right place. **What it cannot do as well as the other cameras:** - **Distance is rough.** It comes only from the size of a box (a thing twice as far looks half as big). A slanted tag has a smaller box. Make your shot table with this camera, and check it. For long or exact shots, use a Limelight or a webcam. - **A single tag has no "right side up".** A tag group has one: the order of its tags in the picture gives it, as with the Limelight ([`TagGroup`](#taggroup)). So a goal needs 2 taught tags of the group in view. - **At most 6 boxes in one reading.** That is the SDK driver's limit. With more in view, it leaves some out. - **Colors change with the light.** The seller says so too. If you can, teach them at the venue. - **A cable that comes off takes about a second to show.** The SDK cannot tell an unplugged HuskyLens from one that sees nothing. On a REV hub, an empty port reads as zeros, and its `knock()` still says true. So while the camera sees nothing, this class asks "are you there?" about once a second and checks the answer itself. Reading the camera is a slow I2C request, so `update()` hands it to a helper thread and never waits. !!! warning "Not yet tried on a real robot" We tested this class with the SDK's own HuskyLens class and pretend I2C answers, not with a real camera. Test it first ([test AIM-06](https://github.com/crossbotics/ftc-helper-lib/blob/main/testing/tests/AIM-06.md)), and please tell us what you find. ## Venue lighting Every venue has different light: a bright gym, a dim practice room, spotlights at an event. A camera setting that finds tags well in one place can miss them in another. During INIT, the lighting test picks the setting for the place you are in, by itself: 1. It asks the camera to switch to the first setting. Once the camera has truly switched, the test waits 300 ms for the picture to settle. Then it counts the next 10 pictures that see at least one AprilTag. Pictures from before that do not count. 2. It does the same with each setting in the list. 3. The setting with the most pictures with tags wins. A tie goes to the one earlier in the list, so **put your usual setting first**. 4. When no setting saw at least 3 pictures with tags (the robot is not facing a tag yet), the test starts over. It keeps trying all through INIT. 5. **At ▶ it stops at once** and keeps the best setting so far (the first one when none saw a tag). So the robot never aims with a setting the test is only trying. **Have a tag in view at INIT** (the robot's start spot for the match is fine), or the test cannot help. You can also put the test on a button. The driver aims at a tag and presses, and the test runs again (up to 5 s, or `lightingAfterStartMs`; see `relight()` on the [Camera page](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/)). Some settings get no score. One is a setting the camera refuses (a webcam without manual exposure). Another is a Limelight pipeline that sends no pictures (not set up). The test skips such a setting from then on, and the Driver Station shows it (`no pictures from pipeline 2 (missing?)`). When a camera is not in the robot configuration, or not working after 3 s, INIT shows a warning. The OpMode still runs. The test never waits: each switch goes to a background helper, and the test is one quick step per loop. **At an event:** in the queue, INIT once with the robot facing a tag. The Driver Station shows the result and two lines for `Tunables.java`, for example `public static double pipeline = 2;` and `public static boolean autoLighting = false;`. With them, every match there uses that setting with no test. Set `autoLighting = true` again at home. A webcam shows `exposureMs` (a new line to add). **Limelight:** on the Limelight's web page, set up one AprilTag pipeline per kind of light. For example: 0 = normal, 1 = bright (lower exposure), 2 = dim (higher exposure and gain). The Exposure slider is in the pipeline's Input tab at http://limelight.local:5801. Every step: [Setting up Limelight lighting pipelines](https://crossbotics.com/ftc-helper/docs/guides/limelight-lighting/). Then: ```java LimelightTags camera = LimelightTags.create(hardwareMap, "limelight").autoPipelines(0, 1, 2); ``` Only pictures taken with the pipeline under test count. The Limelight says which pipeline made each picture. **Webcam:** the test tries manual exposures. The exposure is how long each picture collects light. ```java WebcamTags camera = WebcamTags.create(hardwareMap, "Webcam 1").autoExposure(); // auto, 3, 6, 12 ms WebcamTags camera = WebcamTags.create(hardwareMap, "Webcam 1").autoExposure(6, 3, 12, 0); // your own list ``` `0` is the camera's own automatic exposure. A short exposure gives sharp tags while the robot moves, but a dark picture. The gain (a brightness boost) makes up for it. Manual exposures use the gain from `.gain(g)` or `.exposure(ms, gain)`, or else the camera's highest. "auto" gets the camera's own gain back (the test reads it before the first manual setting). It is the same idea as the FTC SDK's sample `ConceptAprilTagOptimizeExposure`, done for you. Not every webcam allows manual exposure. When it does not, `status()` says "exposure not supported". In the five-files robot it is one word on the camera's line: `Camera.limelight("limelight").autoPipelines(0, 1, 2)` or `Camera.webcam("Webcam 1").autoExposure()` (see the [Camera page](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/)). The Driver Station shows the result at INIT. It also shows the lines to copy into `Tunables.java` to skip the test at this venue next time. ## LightingSweep The helper behind the lighting test. It tries settings one after the other and keeps the one whose pictures see the most tags. `LimelightTags` and `WebcamTags` make one for you. Get it with `lighting()` to read its result or to change its numbers. | Method | What it does | | --- | --- | | `new LightingSweep(labels, apply, clock)` | one label per setting (usual first); `apply` switches to setting i and must not wait; the clock is `System::nanoTime` | | `update(tags)` | every loop: the tags in a new picture from the setting under test, `LightingSweep.NO_PICTURE`, or `LightingSweep.OTHER_SETTING` (a picture from the setting before) | | `switched()` | tells it the camera has the setting under test (settling starts now) | | `switchFailed()` | tells it the camera refused the setting: no score, and the test skips it from now on | | `waitingForCamera()` | call it instead of `update` while the camera is not ready (it checks only the time limits) | | `.settleMs(ms)` | the wait after the switch lands, before counting (default 300; Tunables `lightingSettleMs`) | | `.pictures(n)` | pictures counted per setting (default 10; `lightingPictures`) | | `.trialMs(ms)` | the most time per setting, once switched (default 2000) | | `.switchTimeoutMs(ms)` | the most time for the camera to switch (default 1500). If only pictures from another setting come in that time, the setting is "missing" | | `.minPictures(n)` | pictures with tags a setting needs to count as good (default 3; `lightingMinPictures`) | | `.giveUpAfterStartMs(ms)` | after ▶, how long to keep trying (default 0 = stop at ▶ with the best so far; Tunables `lightingAfterStartMs`). The cameras report no targets while it tries after ▶ | | `matchStarted()`, `matchHasStarted()` | tells it that the driver pressed ▶; whether the driver pressed ▶ | | `restart()` | tries every setting again during the match. It gets `giveUpAfterStartMs` from now, or `RESTART_IN_MATCH_MS` (5 s) when that is 0. When it sees no tag, it goes back to the setting it had. The five-files `Camera.relight()` calls it | | `newSession()` | tells it the camera was closed and started again, so it does INIT again (the cameras call it in `close()`) | | `isDone()`, `gaveUp()`, `chosen()`, `chosenLabel()`, `current()`, `noTagsYet()`, `skipped(i)` | the result | | `status()`, `scores()`, `problems()` | "dim (9 of 10 pictures saw tags)"; "normal 2/10, bright 0/10, dim 9/10"; "no pictures from pipeline 2 (missing?)" | ## TagGroup A Limelight reports each tag on its own. `LimelightTags` also reports each **group** of tags in a row as one target, with the same name as the webcam's SDK cluster. In BIOBUZZ, a group is the 4 tags under each CELL (`TagGroup.biobuzz()`). **Right side up or not:** the tag numbers in a row rise to the right when the tags are right side up (as printed). So the order of the tags in the picture says how the row is turned. That is the group's `rollDeg` (0 = right side up, 180 = upside down). This needs only the tags' places. The Limelight also sends each tag's turn in its pose. But the Limelight's docs and the FTC SDK do not agree on which number in that list is the roll. So a single tag's `rollDeg` is the SDK's reading. **Where it aims:** at the middle of the tag row, worked out from the tags in view. The two seen tags farthest apart give the row's direction. Then the library steps back from each seen tag along the row, by that tag's place in the group. It needs at least 2 of the group's tags and their 3D poses (set the tag size in the pipeline). **The webcam aims somewhere else.** Its cluster target is the SDK's own aiming point, not the tag row. The SDK puts it 7.2 in toward the tags' printed top and 5.6 in behind them. In BIOBUZZ the printed bottom faces the field center. So for a robot in front of the CELL, the point is about 9 in farther away and 1 in higher than the row. It is not at the CELL opening. The two cameras give about the same bearing but a different distance. Make the shot table with the camera the robot uses. ```java // Next season, or your own targets: a name, the tag ids, each tag's place along the row (inches // from the middle, + = right as printed). TagGroup goal = new TagGroup("GOAL", new int[] {1, 2, 3}, new double[] {-5, 0, 5}); camera.groups(java.util.Arrays.asList(goal)); ``` | Method | What it does | | --- | --- | | `TagGroup.biobuzz()` / `TagGroup.currentSeason()` | this season's groups | | `contains(id)`, `alongRowIn(id)`, `ids()` | what is in a group | | `element` | the field element the group is on, for example "RED HIVE" (BIOBUZZ: each HIVE has two groups, one per CELL). Null when you did not give one (`new TagGroup(name, ids, places, element)` gives one) | | `TagGroup.goalTarget(camera, name)` | the target to aim at for a goal named `name`. For a group on a HIVE: that HIVE's group that reads right side up now (the up CELL), or null when only an upside-down one is in view. For any other name: `camera.target(name)` | | `TagGroup.whyNoGoal(camera, name)` | why there is no goal while the camera sees part of it, for example "RED SCORING is upside down (a down CELL)". Otherwise "" | | `LimelightTags.groupTarget(group, places, time)` | the group's target from tag places in camera space (public for tests) | ## TargetObservation | Field / method | Meaning | | --- | --- | | `id`, `name` | the tag id and name. `CLUSTER` = -1 for clusters. `ODOMETRY` = -2 for a goal worked out from the odometry instead of seen | | `fromOdometry()` | whether it is a goal from the odometry ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). Its bearing is from the robot's front, and its distance from the robot's center | | `bearingDeg` | how far to turn to face it; **+ = it is to the left** | | `distanceIn` | inches from the camera, flat in the camera's own view (its up/down left out), or NaN when unknown. It is the floor distance only for a level camera. A camera tilted up reads more. It means the same for both cameras, but make the shot table with the camera mounted as on the robot | | `timeNanos` | when the camera took the picture | | `rollDeg`, `isUpright()` | how far it is turned in the picture: 0 = right side up, 180 (or -180) = upside down, NaN when the camera cannot tell. `isUpright()`: whether it is turned less than 90 degrees either way (false for NaN). Webcam: the SDK's `ftcPose.roll` (for a cluster, the turn of its row). Limelight: a group's, from the order of its tags ([TagGroup](#taggroup)) | | `facingDeg` | which way its face points along the floor, in the camera's frame like `bearingDeg` (degrees, counterclockwise +, turned to the camera's side; straight on = the bearing + 180), NaN when the camera cannot tell. Webcam: from the SDK's raw pose (`WebcamTags.facingDeg`). Limelight and HuskyLens: NaN. [Aim into the opening](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#aim-into-the-opening) uses it | | `withBearing(deg)` | the same observation with another bearing (for code that moves the aim point) | | `ageMs(now)`, `isFresh(now, maxAgeMs)` | how old it is, and whether it is newer than `maxAgeMs`. Never aim with an old picture | | `hasBearing()`, `hasDistance()` | whether the camera worked out a bearing, and a distance | ## AimController ```java AimController aim = new AimController(0.02, 0.003) // kP and kD, on the bearing in degrees .deadband(1.5) // close enough .maxPower(0.5) // never turn harder than this while aiming .maxAgeMs(150) // ignore pictures older than 150 ms (they point the wrong way) .offset(0); // where the target sits in view when the launcher is aimed (left = +); Aim Tuner finds it // camera.target("RED SCORING") = that tag group, or null if not seen now; turnPower(null) gives 0 drive.drive(forward, strafe, aim.turnPower(camera.target("RED SCORING"))); // ready for any drive's turn ``` `turnPower` is **clockwise positive**, the same as every drive's `turn` argument, so it plugs straight in. `ccwPower` gives the same power counterclockwise positive, for your own heading math. `turnPower` gives **0** when there is no target, the picture is old, or there is no bearing. So the robot never turns toward something it cannot see now. The D part changes only on a NEW picture, so a repeated picture never fakes motion. Also: `isAimed()`, and `reset()` (call it when the driver lets go of the aim button). The robot in five files has this built in. `g1.rb.toggle(robot.aimMode())` turns the whole robot to the goal while the driver drives, with the odometry as a backup ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). It is for a robot with no turret. A turret that follows the goal is a separate mode: use one, not both. For a turret, use `turret.aimAtTarget(target, cameraOnTurret)`. It uses only fresh pictures, and each picture once: an old bearing used again would push the turret further and further. It holds still when there is no target. See [launcher.md: Turret](https://crossbotics.com/ftc-helper/docs/modules/launcher/#turret). ## MovingShot The math behind `Tunables.Aim.shootOnMove` ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)), for your own code and tests. A piece keeps the shooter's speed. So aim at the **virtual goal** = the goal - the shooter's speed x the flight time. Also, a camera picture is old. So the math first turns the goal back by the robot's turn since the picture, and moves it by the robot's motion since then. Everything is in one frame, the robot's: x forward, y left, from the robot's center, angles counterclockwise +. ```java MovingShot shot = new MovingShot() .shooterAt(-4, 0) // the shooter (a turret's pivot) 4 in behind the robot's center .onTurret() // a turret aims (leave out: the whole robot turns, a fixed shooter) .flightSec(0.8, 0) // seconds in the air (+ seconds per inch) .maxLeadIn(24); // never lead more than this double[] goal = MovingShot.seenFrom(bearing, distance, 7, 0, 0); // a camera 7 in in front, facing forward double[] v = MovingShot.toRobotFrame(odo.velocityX(), odo.velocityY(), odo.pose().headingDeg); MovingShot.Result r = shot.solve(goal[0], goal[1], v[0], v[1], odo.turnDegPerSec(), pictureAgeSec); // r.aimDeg: the turret angle (or how far to turn the robot); r.distanceIn: for the launcher's speed ``` | Method / field | | | --- | --- | | `shooterAt(forwardIn, leftIn)` | where the shooter is from the robot's center (default 0, 0). A turning robot swings an off-center shooter sideways, and the lead includes that speed too | | `onTurret()` | makes `aimDeg` a turret angle from the turret's pivot. Without it, `aimDeg` is how far to turn the whole robot so a fixed shooter's line (parallel to the robot's front, `leftIn` to the side) passes through the goal | | `flightSec(sec, perIn)`, `maxLeadIn(in)` | the flight time (`sec + perIn x distance`; the distance is the virtual goal's, worked out a few times), and the largest lead (0 = no cap) | | `solve(goalForward, goalLeft, vForward, vLeft, turnDegPerSec, latencySec)` | where to aim now: a `Result` | | `Result`: `aimDeg`, `distanceIn`, `leadDeg`, `leadIn`, `flightSec` | the aim; inches from the shooter to the virtual goal; how much the motion moved the aim (deg) and the aim point (in); the flight time used | | `seenFrom(bearing, distance, camForward, camLeft, camYaw)` | a camera's target as {forward, left} from the robot's center (camYaw: a turret's angle for a camera on it) | | `toRobotFrame(fieldVx, fieldVy, headingDeg)` | the robot's field speed as {forward, left} | It leaves out three things. First, the turret's own turn during the picture's age. Second, air drag: it slows the piece's sideways speed a little. In the simulator, a 30 in/s strafe missed by 21 in without the lead, and by 3.5 in with it. Third, a change of speed during the flight. ## DistanceFilter Keeps camera glitches out of a distance. A camera sometimes gives one picture with a wrong distance (a tag half hidden, a blur, a reflection). If the robot uses that picture as it comes, the flywheel speed changes for a moment, and a shot fired then goes long or short. The five-files launcher's `speedFromDistance(camera)` uses a filter for you. Its numbers are in `Tunables.Launcher`: `distanceMedianOf`, `distanceJumpIn`, `distanceJumpAgreeIn`. After the filter, the launcher can also ease its speed into each new distance (`distanceSmoothSec`, off by default): see the [launcher's page](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava). The filter does two checks, one after the other: 1. **The middle of the last 5 pictures** (the median): sort them and take the one in the middle. One or two bad pictures end up at the ends of the list, so the filter never uses them. It costs about 2 pictures of delay (0.07 s at 30 pictures a second). 2. **The jump check:** when a new distance is more than 12 in from the one in use, the filter waits. It uses the new distance only after 3 pictures in a row, each within 4 in of the one before. A camera never gives the exact same number twice, so the check needs that tolerance. A real move gets through in about 0.1 s. A glitch of a few pictures does not. **After a gap it starts over.** After 0.5 s with no new picture (the goal out of view), a big change is normal. For example, the HIVE tipped, or the robot drove away for pieces. So the first distance after the gap skips the jump check. It still waits for 3 pictures, so one glitch as the goal comes into view stays out. Only NEW pictures count (each picture's own time, `timeNanos`). So a loop faster than the camera does not count one picture many times. | Method | What it does | | --- | --- | | `new DistanceFilter()` | the defaults: the middle of 5, and jumps over 12 in need 3 pictures within 4 in | | `new DistanceFilter(medianOf, jumpIn, agreeIn)` | your own numbers: `medianOf` 1 to 15 (1 = off), `jumpIn` in inches (0 = no jump check), `agreeIn` in inches | | `add(goal, nowNanos)` | every loop: give it the goal now (or null). It gives the distance to use (inches), or NaN when there is none yet (then keep what you had) | | `distance()` | the distance in use, or NaN when there is none | | `jumpWaiting()` | whether a jump is waiting to be sure | | `reset()` | forgets everything. The next distance skips the jump check | ```java DistanceFilter filter = new DistanceFilter(); // every loop: double d = filter.add(camera.target("RED SCORING"), System.nanoTime()); if (!Double.isNaN(d)) launcher.setDistance(d); // else keep the speed you have ``` --- # Possible later work URL: https://crossbotics.com/ftc-helper/docs/design/possible-work/ | Idea | Why it waits | Notes | | --- | --- | --- | | **Swerve drive support** (deferred 2026-10-21) | No seller makes FTC swerve pods. A team must build them first, and nobody can test the work on a robot before that. | Plan, options and effort: [swerve.md](https://crossbotics.com/ftc-helper/docs/design/swerve/). Start with option 2 when a team has a working prototype pod. | | **Road Runner add-on** (built 2026-10-21, kept out on purpose) | Pedro covers the need. A second path system means two lessons and two tunings for students. This version also differs from the Road Runner that teams know: it uses only Road Runner's core math, with our follower and our Characterizer tuning. Road Runner's own drive code and tuners need FTC Dashboard. No team has asked for it. | It is finished on the local branch `roadrunner` (commit de59b46). That branch is only on the mentor's computer, not on GitHub. It has the `roadrunner/` add-on, the `rrbot` example, 22 tests and a simulator test. Still open before merging: what counts as "done" when the plan's time runs out; the gains default to 0; there are no Road Runner Actions and no turn-in-place; `tools/check_blocking.py` does not scan the add-on folders. Review it, update it to the newest main, and run the full review before merging. | | **`alongside` that ends at a path distance** | The FTC-veteran review ("Alex") asked for it, for cycle autonomous. | For example, start the shooter 12 in before a path ends, or at the join between two parts. | | **Live tuning of `PedroConstants`** | Pedro reads its numbers at INIT. Today you must build again to change them. | It needs Pedro's config values in the tuning menu, and a copy back to the file, as for every tuned value. | | **Pose and path drawing: FTC Dashboard add-on + record-and-replay** (set aside 2026-10-21) | The mentor wants it, but has set it aside for now. | (1) An optional `dashboard` add-on (like `pedro/`). It shows the pose, the planned path, the trail and tuning graphs on Dashboard's field view. The robot sends them only in the PRACTICE profile. In COMPETITION it sends nothing, and INIT warns if Dashboard is still on ("run Enable/Disable Dashboard"). FTC Dashboard 0.6.0 (maven.brott.dev, 2026-05-16) has a saved on/off switch in the Robot Controller menu and an "Enable/Disable Dashboard" OpMode. It has no public method to switch it from code (`isEnabled()` only). It is built against SDK 10, so try a real SDK 12 build first. Rule R704.D bans such services at events: turn it off (or remove it), and ask the FIRST Q&A whether "off" is enough. (2) Record-and-replay: the robot writes the pose, the planned path and the step report to a file. Nothing streams, so events allow it. The simulator or the path builder replays the file. About 1-2 days for (1), 2-3 for (2). They share the drawing data. | | **Camera positions mixed into odometry: the camera fix** (Camera Fix Check taken out of Tune and check 2026-11-12) | BIOBUZZ's AprilTags are on moving HIVE cells, so it does not fit this season. The camera fix (`cameraFix(camera)`, `CameraFixCheckOpMode`) stays in the code, alpha and off. | Look again at each new season: does the field have fixed tags on the walls, and does Limelight publish a field map for it? If yes, test it on a robot, put the Camera Fix Check back in Tune and check (`TuneAndCheckOpMode`) with a page in `docs/tuning/`, and settle the RED-wall steps: which way the robot faces, and whether to restart so the heading starts at 0 (the check works out the turn from the odometry heading). `Odometry.custom(...)` is the other hook. | | **Battery compensation for lifts, arms and the drive** (logged 2026-10-24) | The mentor chose the small step first: every tuner shows the battery, and each copied number notes the voltage at which you tuned it. Scaling needs a test on a real robot. | Scale the power-based numbers by (tuned volts / battery now), as the launcher's flywheel F already does (`nominalVolts`). These are the lift and arm hold power (`kF`), the drive's `moveMinPower` and turn gains, and the Drive Tuner's results. Each number needs its own "tuned at" voltage in Tunables.java. Read the battery off the loop (on the library's helper thread) and smooth it. Then a voltage dip under load does not make the power jump. | | **Drives that correct on the way with odometry** (logged 2026-11-11) | The mentor asked for it while reviewing Building autos. | Today `forward`, `back`, `left`, `right`, `move` and `moveWithTurn` count only wheel turns. They do not fix a bump or a wheel slip. Only `driveTo`, `routeTo` and `follow` use the odometry. With odometry on the robot, a drive could hold its heading and its line from the odometry, and end where the wheel count says it should. Keep the step words the same. The report should say when the drive corrected. | | **Auto builder: the steps it cannot make yet** (logged 2026-11-11) | The mentor asked for it while reviewing Building autos. | The builder cannot make these today (docs/building-autos/06-auto-builder-steps.md, "What it cannot do"): INIT menus (`menuChoice`, `menuYesNo`, `onlyIf`/`end`, `choice`), `alliance().pick`, `waitUntil`, your own `step`, `routeTo`, and autos built from `Routes.java` pieces (Load cannot read them). Load lists each one it drops. When you paste back over `steps(...)`, you lose them. | --- # Design study: swerve drives URL: https://crossbotics.com/ftc-helper/docs/design/swerve/ ## The short answer - The library does not support swerve today. `DriveConfig.DriveType` is `MECANUM` or `TANK`. - Pedro Pathing 3.0.2 has a swerve drivetrain (`Swerve` + `CoaxialPod`). Today a team can use it only through Pedro's escape hatch (`Pedro.follower((hw, localizer) -> ...)`). Then it has no TeleOp, no `move`/`turn`/`driveTo`, no simulator and no help to line up the wheels. - None of goBILDA, REV or AndyMark sells an FTC swerve module (checked 2026-10-21). A team builds its own pods. goBILDA does sell the usual steering servo (Axon MAX MK2, with a position wire). - Full support is about **3 weeks** of work. A smaller first step (TeleOp + Pedro + alignment finder + simulator) is about **2 weeks**. ## What a swerve drive is (for the docs later) Each wheel sits in a **pod** that can turn. One motor drives the wheel. A second actuator points the pod. On FTC it is usually a continuous-rotation servo. An **absolute encoder** (a sensor that knows the pod angle the moment the robot turns on) tells the code which way the pod points. On FTC this is an analog input (0–3.3 V for one turn). Why teams want it: full speed in every direction (mecanum loses about 30 % sideways), and more push, because the wheels are plain traction wheels. Why it is hard: it has 8 actuators for 4 wheels. The team must build the pods and line them up. The steering needs a small control loop of its own. ## How Pedro 3.0.2 does it (read from the jars with `javap`) - `Swerve implements Drivetrain`: `new Swerve(hardwareMap, SwerveConfig, SwervePod...)`. It does the math from (forward, strafe, turn) to one (angle, speed) per pod (`computePodPowers`), with voltage compensation. `SwerveConfig.zeroPowerBehavior` is `X_LOCK` or `IGNORE_ANGLE_CHANGES`. - `SwervePod` is an **interface**: `getOffset()`, `getAngle()`, `adjustThetaForEncoder(..)`, `move(angle, power, ..)`, `setToFloat()`, `setToBreak()`, `debug()`. So we can plug in our own pod. - `CoaxialPod` is Pedro's pod: a `DcMotorEx` drive motor, a `CRServo` steering servo and an `AnalogInput` encoder. `CoaxialPodConfig` holds `motorName`, `servoName`, `servoEncoderName`, `driveDirection`, `servoDirection`, `angleOffsetRad` (the alignment), `podOffset` (where the pod sits), `analogMinVoltage` 0 / `analogMaxVoltage` 3.3, `encoderReversed`, and `turnController`. - `turnController` defaults to `Controller.zero`: **the pods do not steer at all until you set it.** - `move(..)` turns the pod the short way, and flips the wheel direction when the target is more than 90° away. It stops steering inside 2° (0.0349 rad). ## The plan, part by part ### 1. The Robot.java line ```java drive(Drive.swerve( Drive.pod("fl_drive", "fl_steer", "fl_angle").atMm(-140, 140), // x right, y forward Drive.pod("fr_drive", "fr_steer", "fr_angle").atMm(140, 140), Drive.pod("bl_drive", "bl_steer", "bl_angle").atMm(-140, -140), Drive.pod("br_drive", "br_steer", "br_angle").atMm(140, -140)) .motor("gobilda-5203-312").wheelMm(72) .imu("imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD)); ``` - One `Drive.pod(drive motor, steering servo, angle input)` per pod, with two to four pods. `atMm(x, y)` is the pod center from the robot center (the same signs as `docs/conventions.md`). - New numbers in `Tunables.Drive`: one alignment offset per pod (`flOffsetDeg` …, which the finder writes), the steering `steerKp` / `steerKd`, and `steerToleranceDeg`. - `DriveType` gets `SWERVE`. `isMecanum()` stays as it is. Add `canStrafe()` (mecanum or swerve), and move the callers that mean "can strafe" to it (`DriveTunerOpMode`, `Pedro`, `DriverControls`). - `reversed(...)` works for drive motors and steering servos by name, like today. ### 2. TeleOp driving New plain classes in `drive/`, the same shape as mecanum: - `SwerveMixer`: (forward, right, turn clockwise) → one (angle, speed) per pod. It scales the speeds so none goes past the power limit (like `MecanumMixer`). It is pure math, so tests are simple. - `SwervePodControl`: one pod. A PD loop from angle error to servo power, the 90° flip, and **cosine scaling**: drive power × cos(angle error). With it, a pod that still points the wrong way does not push the robot sideways. At zero stick the pod keeps its last angle (no snap back to 0°). - `SwerveDrive`: `drive(f, s, t, speed)`, `driveFieldCentric(...)`, `stop()`. The steering loop needs a call every loop. TeleOp already calls `drive` every loop, so it fits the non-blocking rule. - `DriverControls.create` gets a third `Wheels` case. `EasyTeleOp` needs no change: strafe and field-centric work because `canStrafe()` is true. - Loop time matters, because each loop has 4 analog reads. Check that bulk reads cover them (the hub's bulk data includes the analog inputs), and add a loop-time check to the finder. ### 3. Autonomous `move` / `turn` / `driveTo` `AutoDrive` is built on four motors and `MecanumMixer` (wheel ticks → distance). The plan: - Pull a small internal interface out of `AutoDrive`. It has two halves: "drive with (forward, right, turn)", and "the distance the robot went (forward, right inches), from the wheels". Mecanum and tank keep their exact math behind it. Swerve averages each pod's tick change × (cos angle, sin angle). - `driveTo` with odometry needs only the first half, so it is the easy part. `move`/`turn` without odometry need the second half. - `strafeCorrection` is 1 for swerve. The Drive Tuner skips its strafe test and shows the pods instead. - This touches tested mecanum code. Every existing `AutoDrive` test must pass unchanged. ### 4. Pedro - `Pedro.follower(foresight)` accepts a swerve `drive(...)` line and builds Pedro's `Swerve`. - **Use our own pod inside Pedro:** the pedro module wraps `SwervePodControl` as Pedro's `SwervePod` interface. Then TeleOp, `AutoDrive` and Pedro steer with the same code and the same tuned numbers. There is no second steering loop to tune, and no `Controller.zero` trap. - `LimitedSwerve extends Swerve`: the power limit, like `LimitedMecanum` (`computePodPowers` is public). - Pod positions go through `PedroFrame` (Pedro's axes and inches). - Risk: teams use Pedro's swerve less than any other part of Pedro. Test on a real robot before a release says "supported". ### 5. The simulator robot - Robot file: `drive.type = swerve`, `drive.pods = fl_drive fl_steer fl_angle -5.5 5.5, ...` (inches). It also has a hidden `drive.podMountDeg = 37, -112, ...` (the true mount angle of each encoder). Then the alignment finder has something real to find. - Steering model: a CR servo turns the pod at up to its no-load speed (Axon MAX MK2: 83 rpm at 6 V, goBILDA page), with a little lag. A pretend `AnalogInput` gives (angle + mount) / 360 × 3.3 V. The simulator has `CRServo` today but **no `AnalogInput`**, so add it. - Chassis motion: fit (forward, right, turn) to the four pod velocity vectors (least squares). Then call the existing `world.step(dt, forward, right, cw)`. Nothing changes in the physics engine. - `Drive.simLines`, `SimNewRobot` (guess swerve from names like `*_steer` + `*_angle`), `:sim:fromConfig` and the robot-file skill (`skills/robot-file/`) learn the new lines. ### 6. Pod-alignment finder (`SwerveFinderOpMode`) Steps, each with a plain on-screen prompt: 1. **Steering off.** All servos float. The student lines up every wheel straight forward with a straight edge (two goBILDA channels across the pods work). The student presses A, and each pod's voltage becomes its offset. 2. **Encoder range and direction.** Each pod turns slowly once, alone. The finder records the lowest and highest voltage. It checks that positive servo power makes the angle go up. If not, it says "add fl_steer to reversed(...)". 3. **Drive motor direction.** Each wheel rolls forward slowly. The student says yes or no. 4. **Check.** All pods point to 0°, 45°, 90°, then back. The student checks by eye. 5. **Steering tune.** The finder gives each pod a 90° step, and reports the time to settle and any overshoot. Then it nudges `steerKp`/`steerKd`. 6. It prints the lines for `Tunables.java`, and says to copy them there. Without the copy, live-tuned values stay only on that hub. A scenario test (`FinderSafetyTest`) also runs it in the simulator with the hidden mount angles. ### 7. Real parts (checked on the seller pages 2026-10-21) | Seller | What they sell for swerve | Usable on FTC? | |---|---|---| | goBILDA | Site search "swerve": 0 results. No module or kit. | Build your own pod | | goBILDA | Axon MAX Servo MK2, `2004-0025-0002`, $99.99, in stock. 4th wire = analog position. 28 kg·cm / 71 rpm at 4.8 V, 34 kg·cm / 83 rpm at 6 V. H25T spline. | Yes: the steering servo | | goBILDA | Axon MINI Servo MK2, `2004-0025-0001`, $99.99, in stock. Same 4th wire, smaller. | Yes, for light robots | | goBILDA | Axon Servo Programmer MK2, `3102-0002-0001`, $59.99. Loads the continuous-rotation firmware ("CR Mode" `.sfm` file). | Needed once per servo | | REV | 3in MAXSwerve `REV-21-3005` ($275), 4in EasySwerve `REV-21-3006` ($223), drivetrain kits $2,000+. NEO motors, SPARK controllers. | No: FRC only | | REV | Through Bore Encoder V2 `REV-11-3174`. Its absolute output is a pulse (duty cycle); REV says the FTC hubs cannot read it. Quadrature works on a motor encoder port. | Only as a relative encoder: needs lining up at every power-on | | AndyMark | SDS MK4 / MK4i / MK4n / MK4c ($283.90–$345.10), MK5i/MK5n ($395, sold out). Their own Swerve & Steer is discontinued. | No: FRC only | Not checked: the Axon feedback wire's voltage range (the goBILDA pages do not say, and the finder measures it), and community FTC pod designs (they are not sold products). Game rules (BIOBUZZ manual TU01): R502 allows "4th Wire Position Feedback". It caps a servo at 8 W at 6 V (the Axon MAX MK2 is listed at 7.5 W). R504 C allows continuous-rotation mode "as specified by the manufacturer". R503: at most 8 motors and 8 servos. **A 4-pod swerve uses 4 of the 8 motors, 4 of the 8 servos and 4 analog ports** (all four on one hub). The Axon servos need 6 V, and the hubs give 5 V. So the robot needs a servo power module or the REV Servo Hub. ## Effort estimate (agent work plus mentor review; robot testing on top) | Part | Days | |---|---| | `SwerveMixer`, `SwervePodControl`, `SwerveDrive`, `Drive.swerve` line, `DriveType`, `DriverControls`, tests | 3–4 | | `AutoDrive` refactor (move/turn/driveTo), Drive Tuner changes, tests | 2–3 | | Pedro: pod wrapper, `LimitedSwerve`, frame, tests | 1–2 | | Simulator: `AnalogInput`, pod model, robot file, `SimNewRobot`, robot-file skill, scenarios | 3 | | Alignment finder + steering tune + scenario test | 2 | | Docs: `modules/drive.md`, `robot.md`, `pedro.md`, a tutorial section, troubleshooting, CHANGELOG | 2–3 | | **Total** | **13–17 (about 3 weeks)** | On a real robot, after the team builds the pods, it needs one or two practice nights to line up and tune them. ## Options for the mentor 1. **Not now (0.5 day).** Keep the Pedro escape hatch. Add one tested example of Pedro's own `Swerve` in `docs/modules/pedro.md`, with the `turnController` warning. This fits when no team plans swerve this season. 2. **Swerve "first step" (about 2 weeks).** The `Drive.swerve` line, TeleOp, Pedro (with our pod inside), `driveTo` with odometry, the alignment finder and the simulator. Leave out `move`/`turn` without odometry, and refuse them with a clear message. This fits when a team builds pods this season: Pedro or `driveTo` covers autonomous. 3. **Full support (about 3 weeks).** Everything above, plus the `AutoDrive` refactor, so `move`/`turn` work without odometry, the same as mecanum. **Recommendation: option 1 now, option 2 when a team has a working prototype pod.** No seller has an FTC swerve pod. So every team must design, cut and build four pods first. Until then, nobody can test the library work on hardware. Swerve also takes half the motor and servo budget, which is tight for a robot with a turret, lifter and intake. Option 2 gets a team driving and running Pedro paths. Option 3's extra week mostly serves teams without odometry, and a swerve team will have odometry. ## Sources - Pedro Pathing 3.0.2 `revhub` and `core` jars, read with `javap`. - goBILDA: [search "swerve"](https://www.gobilda.com/search.php?search_query=swerve), [Axon MAX MK2](https://www.gobilda.com/axon-max-servo-mk2/), [Axon MINI MK2](https://www.gobilda.com/axon-mini-servo-mk2/), [Axon Servo Programmer MK2](https://www.gobilda.com/axon-servo-programmer-mk2/) (all 2026-10-21). - REV: [search "swerve"](https://www.revrobotics.com/search.php?search_query=swerve), [Through Bore Encoder V2 docs](https://docs.revrobotics.com/rev-crossover-products/sensors/tbe) (2026-10-21). - AndyMark: [search "swerve"](https://www.andymark.com/search?q=swerve) (2026-10-21, first 24 of 58 results). - BIOBUZZ Competition Manual TU01: R502, R503, R504. --- # Add a lift URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/ **You need:** - A robot that drives, with its five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). - On the robot: a lift motor with an encoder, and hard stops at the top and the bottom. We recommend a touch switch at the bottom. In the robot configuration, call them `lift` and `lift_bottom`. ## 1. What it is A **lift** holds named heights. You send it to a height by its name, and it goes there and holds still. - **Heights are encoder counts.** An encoder is a sensor on the motor that counts how far the shaft has turned. 0 is the bottom, and bigger numbers are higher. - **It never goes past its safe range** (`min` to `max`). The library slows it down near both ends. - **It needs a known 0** (homing). An encoder counts only changes, so it does not know where the bottom is. - **With a switch at the bottom:** a press of the switch sets 0. Until the first press, the lift goes only down, at most 0.3 power, and the screen says `Lift: push it DOWN to the switch to home it`. Each later press fixes drift from a slipped belt or a skipped tooth. - **Without a switch:** 0 is where the lift is at INIT. Press INIT with the lift all the way down, every time, also in TeleOp after an autonomous that left it up ([Where 0 is](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#where-0-is)). **Hard stops and software limits:** `min` and `max` are software limits. The program stops the motor there. Software can be wrong (a bad number, a slipped encoder). So the lift also needs physical blocks at both ends. Set `min` and `max` just inside them. The rules also require this: the robot must stay inside its size limits without software (rule R105). ## 2. Add it to the five files ### Robot.java: one line **Where:** `Robot.java`. The field goes at the top of the class. The line goes in `define()`, after the drive. ```java title="Robot.java" // At the top of the class: public Lift lift; Here in define(): // "lift", "lift_bottom" = the motor's and the bottom switch's names in the robot configuration. // .part(...): which motor it is (optional, recommended). lift = add(Lift.slide("lift").part("gobilda-5203-435").bottomSwitch("lift_bottom")); ``` - `.part(...)` names the motor from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). The number is on its label. **Why:** the library then starts the lift's numbers from that motor, and the simulator moves it like the real one. - `.bottomSwitch(...)` is the switch at the bottom. Until the lift has pressed it once, the lift goes only down, slowly. Leave it out when your lift has no switch. - When a name is red, click it and press Alt+Enter (Option+Enter on a Mac) to add the import. ### Tunables.java: its numbers **Where:** `Tunables.java`, a new section. The section's name is the device's name in CamelCase: `"lift"` reads `Tunables.Lift`. ```java title="Tunables.java" public static class Lift { // "lift" in the configuration public static double min = MEASURE; // lowest safe point, counts (Motor Finder) public static double max = MEASURE; // highest safe point, counts (Motor Finder) public static double kP = DEFAULT; // push toward the target (from the motor) public static double kI = DEFAULT; // fix a small steady miss (0) public static double kD = DEFAULT; // brake near the target (from the motor) public static double kF = DEFAULT; // hold up against gravity (0.05) public static double down = MEASURE; // a named height, counts: any name you like public static double low = MEASURE; // a named height (Motor Finder) public static double high = MEASURE; // a named height (Motor Finder) } ``` - `MEASURE` means "find this on the robot". INIT stops until you write a number. **Why:** a guessed `max` can pull the lift off its rails. - `DEFAULT` means "use the library's starting value". The PID numbers (`kP` to `kF`) start from the motor in `.part(...)`. You tune them later (step 4). - `down`, `low` and `high` are **named heights**. Use any names you like. Every number in the section that is not a setting is a height. ### Controls.java: its buttons **Where:** `Controls.java`, inside `buttons(...)`. A part has no buttons until you add them. ```java title="Controls.java" g2.a.press(() -> robot.lift.goTo("down")).says("down"); g2.x.press(() -> robot.lift.goTo("low")).says("low"); g2.y.press(() -> robot.lift.goTo("high")).says("high"); g2.dpadUp.press(robot.lift::stepUp).says("next height up"); g2.dpadDown.press(robot.lift::stepDown).says("next height down"); g2.leftStickY.use(robot.lift::manual).says("by hand"); ``` With one gamepad (`oneDriver = true`), these `g2` lines work on gamepad 1 ([One gamepad, and a second one when you want it](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/#one-gamepad-and-a-second-one-when-you-want-it)). The left stick moves the lift by hand. When you let go, it holds there. ### Actions.java and autos: use it in steps You need no line here for the lift alone. When the lift works with another part, an action puts them in order. For example, with a claw ([Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/)): **Where:** `Actions.java`, one method per action. ```java title="Actions.java" /** Lift up, open the claw, lift down: one step after the other. */ public static Action scoreHigh(Robot r) { return Action.named("Score high") .then(() -> r.lift.goTo("high")) .waitUntil("lift at the top", r.lift::isAtTarget, 2.0) // at most 2 s .then(r.claw::open) .waitSeconds(0.3) // let the piece drop .then(() -> r.lift.goTo("down")); } ``` An autonomous uses the same action as one step ([Actions.java](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/)). ## 3. Find its numbers INIT stops on `MEASURE`. The finders still run, because they do not read `Tunables.java`. 1. **Motor Finder** ([how](https://crossbotics.com/ftc-helper/docs/tuning/05-motor-finder/)): put the lift at the bottom. Press **X** just above the bottom block (`min`) and **B** just below the top block (`max`). Press **A** at each height you want. 2. Put the numbers in `Tunables.Lift`. Give each P a real name (`P1` -> `low`, `P2` -> `high`). 3. When the Motor Finder says `Robot.java: add .reversed() to the "lift" part`, do that. It means the motor counts down as the lift goes up. ## 4. Check it, then tune it **Check it:** 1. Lift the wheels off the floor, and keep a hand near STOP. Put the lift at the bottom, on its switch. 2. Press INIT. Check that no warning names the lift. Press ▶. 3. Push gamepad 2's left stick up a little. The lift must go **up**. If it goes down, add `.reversed()`. 4. Press X, then Y, then A. The lift must reach and hold each height. **Tune it** with [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/), while the robot runs. Change one number, then send the lift between its heights: 1. **kP:** raise it until the lift moves fast to each height. If it shakes, go back a step. 2. **kD:** if it goes past the height and comes back, raise it a little at a time. 3. **kF:** if it stops a little low and sags, raise it until it holds still. 4. **kI:** only if a small error stays, a very small number. Then put the tuned numbers in `Tunables.Lift`, in place of `DEFAULT`. ## Fix a problem | Problem | Why, and the fix | | --- | --- | | INIT stops: `Tunables.Lift.max = MEASURE` | Not measured yet. Do step 3 | | The lift goes only down, slowly | Not homed yet. Push it down to the switch once | | Every height is too high (no switch) | It was not at the bottom at INIT. Lower it, and INIT again | | The lift goes down when it should go up | Add `.reversed()` to the lift in `Robot.java` | | It sags below a height | `kF` is too small | | It shakes at a height | `kP` or `kD` is too big | **Two motors on one lift:** name the second motor on the same line, `.alsoMotorReversed("lift_right")` ([Two motors](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm)). ## Done when - INIT shows no warning for the lift. - Each button sends the lift to its height, and it holds still there. - `min`, `max` and every height in `Tunables.Lift` are numbers, not `MEASURE`. --- **Next:** [Add an arm](https://crossbotics.com/ftc-helper/docs/add-to-robot/02-arm/), or the part you need next ([Add to your robot](https://crossbotics.com/ftc-helper/docs/add-to-robot/)). **Look it up:** [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/): every setting, number and command. --- # Add an arm URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/02-arm/ **You need:** - A robot that drives, with its five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). - On the robot: an arm motor with an encoder, and hard stops at both ends of the swing. In the robot configuration, call the motor `arm`. ## 1. What it is An **arm** works like a [lift](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/), but in **degrees**, not encoder counts. You send it to an angle by its name, and it goes there and holds still. - **0 degrees is where the arm is at INIT.** So put the arm on its bottom stop before you press INIT. Then 0 is the same place each time ([Where 0 is](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/#in-robotjava)). - **It never goes past its safe range** (`min` to `max`). Set them just inside the hard stops. The hard stops are still necessary: software can be wrong, and the robot must stay inside its size limits without software (rule R105). - **It needs its gear ratio.** The library changes motor turns to arm degrees with the motor from the catalog and `gearRatio`. **A servo at the end of the arm** that tilts a claw is a **wrist**. Add it after the arm: [Add a claw and other servo parts](https://crossbotics.com/ftc-helper/docs/add-to-robot/03-claw/). ## 2. Add it to the five files ### Robot.java: one line **Where:** `Robot.java`. The field (`public Arm arm;`) goes at the top of the class. The line goes in `define()`, after the drive. ```java title="Robot.java" // "arm" = the motor's name in the robot configuration. Its numbers: Tunables.Arm. // "gobilda-5203-117" = the motor's catalog id (needed: it works in degrees). // gearRatio: motor turns per arm turn. 0 degrees = where it is at INIT. arm = add(Arm.motor("arm", "gobilda-5203-117").gearRatio(2)); ``` - `"gobilda-5203-117"` names the motor from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). The number is on its label. **Why:** the library needs the motor's counts per turn to work in degrees. - `.gearRatio(2)` means the motor turns 2 times for 1 turn of the arm. Count the teeth: the gear on the arm divided by the gear on the motor. With no gears between them, leave it out (1). - When a name is red, click it and press Alt+Enter (Option+Enter on a Mac) to add the import. ### Tunables.java: its numbers **Where:** `Tunables.java`, a new section. The device `"arm"` reads `Tunables.Arm`. ```java title="Tunables.java" public static class Arm { // "arm" in the configuration public static double min = MEASURE; // lowest safe angle, degrees, 0 = at INIT public static double max = MEASURE; // highest safe angle, degrees (Motor Finder) public static double kP = DEFAULT; // push toward the target (0.02) public static double kI = DEFAULT; // fix a small steady miss (0) public static double kD = DEFAULT; // brake near the target (0.001) public static double kF = 0.1; // hold up against gravity (0) public static double stowed = MEASURE; // a named angle, degrees: any name you like public static double pickup = MEASURE; // a named angle (Motor Finder) public static double score = MEASURE; // a named angle (Motor Finder) } ``` - `MEASURE` means "find this on the robot". INIT stops until you write a number. - `DEFAULT` means "use the library's starting value" (the number in brackets). - `kF = 0.1` starts the arm with some push against gravity. An arm sags more than a lift. - `stowed`, `pickup` and `score` are **named angles**. Use any names you like. ### Controls.java: its buttons **Where:** `Controls.java`, inside `buttons(...)`. A part has no buttons until you add them. ```java title="Controls.java" g2.rightStickY.use(robot.arm::manual).says("by hand"); ``` The operator's right stick moves the arm by hand. When you let go, it holds there. For each named angle, add a line on a free button, like the lift's: `g2.y.press(() -> robot.arm.goTo("score")).says("score");`. ### Actions.java and autos: use it in steps You need no line here for the arm alone. When the arm works with another part, an action puts them in order. It is the same as the lift's action: `goTo(...)`, then `waitUntil(..., r.arm::isAtTarget, ...)` ([the lift's example](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/#actionsjava-and-autos-use-it-in-steps)). ## 3. Find its numbers INIT stops on `MEASURE`. The finders still run, because they do not read `Tunables.java`. 1. **Motor Finder** ([how](https://crossbotics.com/ftc-helper/docs/tuning/05-motor-finder/)): put the arm on its bottom stop, then choose `arm`. Press **X** just above the bottom stop (`min`) and **B** just before the top stop (`max`). Press **A** at each angle you want. 2. **Change counts to degrees.** The Motor Finder shows encoder counts. `Tunables.Arm` takes degrees. Divide each count by the counts per degree: - counts per degree = the motor's counts per turn x `gearRatio` / 360. The counts per turn are in the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). - Example: `gobilda-5203-117` (1425.1 counts per turn) with `gearRatio(2)`: 1425.1 x 2 / 360 = 7.92. So 712 counts is 712 / 7.92 = 90 degrees. 3. Put the degrees in `Tunables.Arm`. Give each P a real name (`P1` -> `pickup`, `P2` -> `score`). 4. When the Motor Finder says to add `.reversed()` to the part, add it to the arm's line in `Robot.java`. It means the motor counts down as the arm goes up. ## 4. Check it, then tune it **Check it:** 1. Keep hands away from the arm's swing, and keep a hand near STOP. Put the arm on its bottom stop. 2. Press INIT. Check that no warning names the arm. Press ▶. 3. Push gamepad 2's right stick up a little. The arm must go **up**. If it goes down, add `.reversed()`. 4. Press each button for a named angle. The arm must reach and hold each angle. **Tune it** with [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/), while the robot runs. Change one number, then send the arm between its angles: 1. **kF:** raise it until the arm holds still at a level angle, with no sag. Do this first: gravity pulls an arm hardest when it is level. 2. **kP:** raise it until the arm moves fast to each angle. If it shakes, go back a step. 3. **kD:** if it goes past the angle and comes back, raise it a little at a time. 4. **kI:** only if a small error stays, a very small number. Then put the tuned numbers in `Tunables.Arm`, in place of `DEFAULT`. ## Fix a problem | Problem | Why, and the fix | | --- | --- | | INIT stops: `Tunables.Arm.max = MEASURE` | Not measured yet. Do step 3 | | Every angle is wrong by the same amount | The arm was not on its bottom stop at INIT. Put it there, and INIT again | | Every angle is too big or too small | A count was not changed to degrees, or `gearRatio` is wrong. Do step 3 again | | The arm goes down when it should go up | Add `.reversed()` to the arm in `Robot.java` | | It sags below an angle | `kF` is too small | | It shakes at an angle | `kP` or `kD` is too big | **Two motors on one arm:** name the second motor on the same line, `.alsoMotorReversed("arm_right")` ([Two motors](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm)). ## Done when - INIT shows no warning for the arm. - Each button sends the arm to its angle, and it holds still there. - `min`, `max` and every angle in `Tunables.Arm` are numbers in degrees, not `MEASURE`. --- **Next:** [Add a claw and other servo parts](https://crossbotics.com/ftc-helper/docs/add-to-robot/03-claw/). **Look it up:** [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/): every setting, number and command. --- # Add a claw and other servo parts URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/03-claw/ **You need:** - A robot that drives, with its five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). - On the robot: the servo, plugged into a servo port. In the robot configuration, call it `claw` (or `wrist`). ## 1. What it is A servo part holds **named positions**. A position is a number from 0 to 1. You send the servo to a position by its name. | Part | What it does | Its positions | | --- | --- | --- | | **Claw** | opens and closes | `open` and `closed` (both needed) | | **Wrist** | tilts a claw, for example at the end of an [arm](https://crossbotics.com/ftc-helper/docs/add-to-robot/02-arm/) | any names, for example `down`, `level`, `up` | | **Positioner** | any other servo with named positions: a gate, a kicker, a fold-out intake | any names, for example `stowed`, `deployed` ([a fold-out intake](https://crossbotics.com/ftc-helper/docs/add-to-robot/04-intake/#a-fold-out-intake)) | - **A servo cannot say where it is.** The library guesses when it has arrived, from `travelSec` (the time for a full move). - **A servo does not move until the first command after ▶.** - **Never let a servo push on something.** At a hard stop it gets hot and can strip its gears. The finder helps you find the positions just before the stops. ## 2. Add it to the five files ### Robot.java: one line **Where:** `Robot.java`. The field goes at the top of the class. The line goes in `define()`, after the drive. ```java title="Robot.java" // At the top of the class: public Claw claw; Here in define(): // "claw" = the servo's name in the robot configuration. Its numbers: Tunables.Claw. // .part(...): which servo it is (optional, recommended). claw = add(Claw.servo("claw").part("gobilda-2000-torque")); ``` - `.part(...)` names the servo from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). **Why:** the library then takes `travelSec` from the servo's speed. - When a name is red, click it and press Alt+Enter (Option+Enter on a Mac) to add the import. **A wrist** is the same line with `Wrist`: ```java title="Robot.java" // At the top of the class: public Wrist wrist; Here in define(): // "wrist" = the servo's name in the robot configuration. Its numbers: Tunables.Wrist. // .part(...): which servo it is (optional, recommended). wrist = add(Wrist.servo("wrist").part("gobilda-2000-speed")); ``` **A claw on two servos**, one for each finger: name the second servo on the same line. ```java title="Robot.java" // "claw_left", "claw_right" = the servos' names in the robot configuration. Numbers: Tunables.ClawLeft. // Find open and closed in Tune and check > Servo Finder on the FIRST servo: the second moves with it. // The servos face each other, so the second turns the other way: alsoServoReversed. claw = add(Claw.servo("claw_left").part("gobilda-2000-torque").alsoServoReversed("claw_right")); ``` Two servos that turn the same way use `.alsoServo(...)` ([Two servos on one part](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#two-servos-on-one-part)). **The servo's whole turn:** a servo turns a little less than its seller says, on the FTC normal range. `.fullRange()` gives it its whole turn. Add it **before** you find the positions: the same number points somewhere else after the range changes. ```java title="Robot.java" // fullRange(): positions 0 to 1 = the servo's whole turn (300 degrees on a goBILDA 2000). // Turn it on FIRST, then find the positions (Servo Finder: press Y while choosing the servo). wrist = add(Wrist.servo("wrist").part("gobilda-2000-speed").fullRange()); ``` ### Tunables.java: its numbers **Where:** `Tunables.java`, a new section. The section's name is the device's name in CamelCase: `"claw"` reads `Tunables.Claw`. ```java title="Tunables.java" public static class Claw { // "claw" in the configuration // The Servo Finder shows "Tunables.Claw: P1 = 0.210, P2 = 0.770": write P1 as open, P2 as closed. public static double open = MEASURE; // servo position, open (Servo Finder) public static double closed = MEASURE; // servo position, closed (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) } ``` The wrist's section has its own names. Every number except `travelSec` is a position: ```java title="Tunables.java" public static class Wrist { // "wrist" in the configuration public static double down = MEASURE; // servo position: any name you like public static double level = MEASURE; // servo position (Servo Finder) public static double up = MEASURE; // servo position (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) } ``` A claw on two servos takes the **first** servo's name, and has one more number, `alsoTrim`: ```java title="Tunables.java" // A claw on two servos, Claw.servo("claw_left").alsoServoReversed("claw_right"): its section is the // FIRST servo's name in CamelCase. public static class ClawLeft { // "claw_left" in the configuration public static double open = MEASURE; // servo position, open (Servo Finder on claw_left) public static double closed = MEASURE; // servo position, closed (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) public static double alsoTrim = DEFAULT; // the second servo: raw position added so the two meet (0; used at the next move) } ``` - `MEASURE` means "find this on the robot". INIT stops until you write a number. - `DEFAULT` means "use the library's starting value" (the number in brackets). ### Controls.java: its buttons **Where:** `Controls.java`, inside `buttons(...)`. A part has no buttons until you add them. ```java title="Controls.java" g2.b.toggle(robot.claw).says("open / close"); ``` ```java title="Controls.java" g2.dpadLeft.press(robot.wrist::previous).says("previous position"); g2.dpadRight.press(robot.wrist::next).says("next position"); ``` - The operator's B opens and closes the claw. - D-pad left and right move the wrist to the next position, in order of value. To send it to one position, use `goTo`: `g2.x.press(() -> robot.wrist.goTo("level")).says("level");`. With one gamepad (`oneDriver = true`), these `g2` lines work on gamepad 1 ([One gamepad, and a second one when you want it](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/#one-gamepad-and-a-second-one-when-you-want-it)). ### Actions.java and autos: use it in steps You need no line here for the claw alone. When the claw works with another part, an action puts them in order. For example, lift up, open the claw, lift down ([the lift's example](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/#actionsjava-and-autos-use-it-in-steps)). A servo cannot say when it has arrived. So wait for it with `.waitUntil("claw done", r.claw::isDone, 1.0)`, or a short `.waitSeconds(...)`. ## 3. Find its numbers INIT stops on `MEASURE`. The finders still run, because they do not read `Tunables.java`. 1. **Servo Finder** ([how](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/)): choose the servo. Find the two ends: press **X** just before one hard stop, and **B** just before the other. 2. Move to each position you need (open, closed) and press **A**. 3. Put the numbers in the servo's section. Give each P a real name: `P1` -> `open`, `P2` -> `closed`. **Two servos:** choose the **first** servo. The second moves with it. When the two sides do not meet, change `alsoTrim` in TeleOp, a little at a time. ## 4. Check it, then tune it **Check it:** 1. Keep fingers out of the claw. Press INIT. Check that no warning names the part. Press ▶. 2. Press B. The claw must open. Press B again. It must close. 3. Listen at each position. **A servo that hums or gets hot is pushing on something.** Move that position 0.01 away from the stop. 4. For a wrist: press D-pad right and left. It must go to each position in turn. **Tune it** with [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/), while the robot runs. The positions change at once: 1. **`closed`:** close the claw on a game piece. It must hold the piece without humming. 2. **`open`:** wide enough to let the piece go, and no wider. A smaller move is a faster move. 3. **`travelSec`:** when an action goes on before the servo arrives, make it longer ([Timing travelSec](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#timing-travelsec)). Then put the tuned numbers in the servo's section, in place of the old ones. ## Fix a problem | Problem | Why, and the fix | | --- | --- | | INIT stops: `Tunables.Claw.open = MEASURE` | Not measured yet. Do step 3 | | The servo does not move at all | No command after ▶ yet. Press its button. Still nothing? Check the port and the name in the robot configuration | | The servo hums or gets hot at a position | It pushes on a stop. Move that position 0.01 away | | The two fingers do not meet | Change `alsoTrim` in Live tuning | | The second servo fights the first | Change `.alsoServoReversed(...)` to `.alsoServo(...)`, or the other way | | Every position is a little off after a repair | The arm on the servo went on one tooth off ([Put an arm back on](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/#put-an-arm-back-on)) | | Every position is off after you added `.fullRange()` | The range changed. Find the positions again | | An action goes on before the claw has closed | `travelSec` is too short | ## Done when - INIT shows no warning for the part. - Each button sends the servo to its position. No servo hums at a position. - Every position in its section is a number, not `MEASURE`. --- **Next:** [Add an intake](https://crossbotics.com/ftc-helper/docs/add-to-robot/04-intake/). **Look it up:** [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/) (every setting, number and command for all servo parts), [Wrist](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/), [Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/). --- # Add an intake URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/04-intake/ **You need:** - A robot that drives, with its five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). - On the robot: the intake motor (call it `intake` in the robot configuration), or two continuous-rotation servos (call them `left_intake` and `right_intake`). An intake needs no encoder. ## 1. What it is An **intake** has two jobs: **in** (take pieces) and **out** (push them back out). - **It runs on power, not to a position.** So it has no limits and no positions to measure. - **A continuous-rotation (CR) servo** spins all the way round, like a small motor. Set the servo to CR mode before you put it on (for a goBILDA servo, with its programmer). - **It can stop by itself when the robot is full.** That needs a count of the pieces ([Stop when full](#stop-when-the-robot-is-full)). ## 2. Add it to the five files ### Robot.java: one line **Where:** `Robot.java`. The field goes at the top of the class. The line goes in `define()`, after the drive. **On a motor:** ```java title="Robot.java" // At the top of the class: public Intake intake; Here in define(): // "intake" = the motor's name in the robot configuration. Its numbers: Tunables.Intake. // .part(...): which motor it is (optional, recommended). intake = add(Intake.motor("intake").part("gobilda-5203-1150")); ``` **Or on CR servos (one, two or more):** ```java title="Robot.java" // Two continuous-rotation (CR) servos. The one that spins the wrong way is reversed. // "intake", "intake_right" = the servos' names in the robot configuration. Numbers: Tunables.Intake (the 1st name). // .part(...): which servo it is (optional, recommended). intake = add(Intake.crServos("intake", "intake_right").part("gobilda-2000-speed") .reversed("intake_right")); ``` - `.part(...)` names the motor or servo from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). **Why:** the simulator then spins it like the real one. - **One CR servo:** `intake = add(Intake.crServos("intake").part("gobilda-2000-speed"));`. Leave out `.reversed(...)`, or reverse that one servo when it spins out. - `.reversed("intake_right")`: two servos that face each other must spin opposite ways. Reverse the one that spins the wrong way. - **Add `.holds(n)`**, the number of pieces it carries: `.holds(3)`. Count them by hand: load pieces until no more fit. The simulator and the piece count use it. INIT warns when it is above the game's limit. - When a name is red, click it and press Alt+Enter (Option+Enter on a Mac) to add the import. **Run from ▶:** some teams keep the intake on all match. Add `.onAtStart()`: ```java title="Robot.java" // Runs in from ▶ until stopped. Its button (operator RT) then switches it on/off. // .part(...): which motor it is (optional, recommended). add(Intake.motor("intake").part("gobilda-5203-1150").onAtStart()); ``` ### Tunables.java: its numbers **Where:** `Tunables.java`, a new section. The device `"intake"` reads `Tunables.Intake`. With CR servos, the section comes from the **first** name: `crServos("intake", "intake_right")` reads `Tunables.Intake`. ```java title="Tunables.java" public static class Intake { // "intake" in the configuration public static double inPower = DEFAULT; // power taking pieces in, 0 to 1 (1.0) public static double outPower = DEFAULT; // power pushing pieces out (0.7) } ``` Both numbers start at `DEFAULT`, so the intake works at once. Change them only when a test shows a problem (step 4). ### Controls.java: its buttons **Where:** `Controls.java`, inside `buttons(...)`. A part has no buttons until you add them. ```java title="Controls.java" robot.intake.inOn(g2.rt); robot.intake.outOn(g2.lt); ``` `inOn` and `outOn` put "in" and "out" on a button the right way for your intake: | Your Robot.java | `inOn(g2.rt)` does | `outOn(g2.lt)` does | | --- | --- | --- | | plain | in while held | out while held | | `.onAtStart()` | a press switches it on and off | out while held | | `.stopsWhen(...)` | in while held; held 1 s = in anyway | out while held | With one gamepad (`oneDriver = true`), these `g2` lines work on gamepad 1 ([One gamepad, and a second one when you want it](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/#one-gamepad-and-a-second-one-when-you-want-it)). ### Actions.java and autos: use it in steps You need no line in `Actions.java` for the intake alone. In an auto, a step turns it on or off: `.run("Intake in", robot.intake::in)`, and later `.run("Intake off", robot.intake::stop)` ([what an auto can do](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/)). ### A fold-out intake Some intakes fold out after ▶, on a servo. That servo is a **Positioner**, a servo with named positions ([servo parts](https://crossbotics.com/ftc-helper/docs/add-to-robot/03-claw/)). **Where:** `Robot.java`. The field (`public Positioner intakeDeploy;`) goes at the top of the class. The lines go in `define()`, after the intake line. ```java title="Robot.java" // Any servo with named positions: a gate, a kicker, a fold-out intake. // "intake_deploy" = the servo's name in the robot configuration. Numbers: Tunables.IntakeDeploy. // .part(...): which servo it is (optional, recommended). intakeDeploy = add(Positioner.servo("intake_deploy").part("gobilda-2000-torque")); // Right after ▶ (autonomous and TeleOp): fold the intake out. atStart(() -> Action.named("Deploy").then(() -> intakeDeploy.goTo("deployed"))); ``` **Where:** `Tunables.java`, a new section. Find both positions with the [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/). ```java title="Tunables.java" public static class IntakeDeploy { // "intake_deploy" in the configuration public static double stowed = MEASURE; // servo position, folded (Servo Finder) public static double deployed = MEASURE; // servo position, folded out (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) } ``` The robot must fit its size limit at the start. So the fold-out waits for ▶. ### Stop when the robot is full The game limits how many pieces a robot holds (BIOBUZZ: 4, rule G407). The intake can stop by itself at that count. It needs `Pieces`, which counts the pieces with color sensors ([Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/)). Then add `.stopsWhen(...)` to your intake line: ```java title="Robot.java" // ADD .stopsWhen(...) to your intake line (no second intake line); the Pieces line goes above it. // .part(...): which motor it is (optional, recommended). intake = add(Intake.motor("intake").part("gobilda-5203-1150").stopsWhen(() -> pieces.isFull())); ``` - Pushing out still works when it is full. - When the count is wrong, the operator holds the in button for 1 s. Then it runs in anyway. - The Driver Station warns when `stopsWhen` has kept the intake from running in for more than 2 s. ## 3. Find its numbers An intake has no finder. Its two powers start at good values. Only `.holds(n)` needs a count: load pieces by hand until no more fit. ## 4. Check it, then tune it **Check it:** 1. Keep hands away from the rollers. Press INIT. Check that no warning names the intake. Press ▶. 2. Hold gamepad 2's RT. The rollers must pull a piece **in**. If they push it out, add `.reversed()` to the intake line in `Robot.java`. 3. Hold LT. The rollers must push the piece **out**. 4. Two CR servos: both must spin toward the inside. If one fights the other, reverse that one with `.reversed("its name")`. **Tune it** with [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/), while the robot runs. Feed it pieces, and change one number at a time: 1. **`inPower`:** lower it when pieces jam or bounce out. Keep it as high as you can for fast pickup. 2. **`outPower`:** raise it when pieces do not come out. Then put the tuned numbers in `Tunables.Intake`, in place of `DEFAULT`. ## Fix a problem | Problem | Why, and the fix | | --- | --- | | It pushes out when it should take in | Add `.reversed()` to the intake in `Robot.java` | | One CR servo fights the other | Reverse that servo: `.reversed("intake_right")` | | A CR servo goes to one place and stops | It is not in CR mode. Set it with the servo's programmer | | Pieces jam or bounce out | `inPower` is too big | | Pieces do not come out | `outPower` is too small | | It does not run in, and the screen says it is full | `stopsWhen` says full. Hold the in button 1 s to run in anyway. Then check the piece count | | INIT warns about `holds` | `.holds(n)` is above the game's limit | ## Done when - INIT shows no warning for the intake. - RT takes a piece in, and LT pushes it out. - `.holds(n)` is on the intake line, with the number you counted. --- **Next:** [Add a launcher](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/). **Look it up:** [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/): every setting, number and command. --- # Add a launcher URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/ **You need:** - A robot that drives, with its five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). - On the robot: a flywheel motor with an encoder, and a feeder (a servo arm, a CR servo wheel or a motor). In the robot configuration, call them `launcher` and `indexer`. - Safety glasses, and nobody in front of the launcher when the wheel spins. ## 1. What it is A **launcher** spins a wheel to a speed, and feeds a piece only when the wheel is at that speed. - **The speed is in RPM** (turns a minute). The library needs the motor's catalog id to know its top speed. - **The feeder pushes one piece at a time** into the wheel. The launcher tells it when. - **It never feeds into a slow wheel.** It waits until the speed is within `readyBandRpm`. When the wheel is not ready within 3 s, it gives up the shot and says why: `Launcher gave up: flywheel`. - **It spins up at ▶** when it has a feeder of its own, so the first shot does not wait. ## 2. Add it to the five files ### Robot.java: one line **Where:** `Robot.java`. The field goes at the top of the class (`public Launcher launcher;`). The line goes in `define()`, after the drive. ```java title="Robot.java" // A flywheel (in RPM) and the indexer that feeds it one piece at a time. // "launcher", "indexer" = names in the robot configuration. Numbers: Tunables.Launcher, .Indexer. // The motor's catalog id is in the brackets (needed). The indexer's .part(...) is optional, recommended. launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed"))); ``` - The motor's catalog id (`"gobilda-5203-6000"`) is needed. The number is on the motor's label ([parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/)). - `.feeder(...)` is the part that pushes the pieces in. `Indexer.servo` is a servo arm. Use `Indexer.crServo(name)` for a CR servo wheel, or `Indexer.motor(name)` for a motor ([Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/)). - **Two arms** that pinch the piece from both sides: `Indexer.servo("feeder_left").alsoServoReversed("feeder_right")`. Both arms use the same `rest` and `push`. - **Two wheels** that squeeze the piece from both sides: `Indexer.crServo("feeder_left").alsoServoReversed("feeder_right")`. Both CR servos get the same `power`, and the second spins the other way. Add `.feedWheelOutWith(intake)` to run them backward while the intake pushes out. - **A wheel and an arm:** a CR servo wheel brings each piece up, and the arm pushes it in. Write the arm as the feeder, and add `.feedWheel(Indexer.crServo("feeder_wheel"))` ([Feed wheel](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#feed-wheel)). - **A motor that is not in the catalog:** write `Motors.custom("my-motor", 28, 5800)` in place of the id (counts per turn, then top RPM). - When a name is red, click it and press Alt+Enter (Option+Enter on a Mac) to add the import. **A feed stop, and an intake that pushes the pieces in.** Add these only when your robot has them: **Where:** `Robot.java`, in `define()`. The intake line goes **before** the launcher line ([Add an intake](https://crossbotics.com/ftc-helper/docs/add-to-robot/04-intake/)). ```java title="Robot.java" intake = add(Intake.motor("intake")); // first: the launcher's pushedBy(...) needs it launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feedStop("feed_stop", "gobilda-2000-speed") // a servo that holds the pieces back .pushedBy(intake)); // the intake pushes each piece into the wheel ``` - `.feedStop(servo, part)`: a servo that holds the pieces back until a shot is allowed. The servo's catalog id is optional. With it, the Feed Stop Finder works out how long the stop takes to open. - `.pushedBy(intake)`: for each piece, the intake runs in for a short time (`assistSec`, 0.25 s), even when the driver has it off. - **A hood** changes the shot angle. Add `.hood(Hood.servo("hood"))` to the launcher line ([Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/)). ### Tunables.java: its numbers **Where:** `Tunables.java`, two new sections. A section's name is the device's name in CamelCase: `"launcher"` reads `Tunables.Launcher`, and `"indexer"` reads `Tunables.Indexer`. ```java title="Tunables.java" public static class Launcher { // "launcher" in the configuration public static double speedRpm = DEFAULT; // shot speed without the table (60% of top) public static double stepRpm = DEFAULT; // speed change per D-pad press (100) public static double readyBandRpm = DEFAULT; // "at speed" = this close to the target (60) public static double idleRpm = 1500; // spins between shots: quicker first shot (0) public static double shotIntervalSec = DEFAULT; // least time between two pieces (0.25) // The hub's speed control: the defaults for the motor until the Flywheel Finder (INIT shows them). // Then write the Finder's numbers in their place. public static double kP = DEFAULT; // push per speed error (kF / 10) public static double kI = DEFAULT; // fix a steady error (kP / 10) public static double kD = DEFAULT; // brake changes (0) public static double kF = DEFAULT; // steady power for a speed (from the motor) // {inches to the goal, RPM}, blended between rows. Example rows: write the Shot Tuner's instead. public static double[][] speedByDistance = {{24, 2200}, {48, 2550}, {72, 2900}, {96, 3250}}; } ``` ```java title="Tunables.java" public static class Indexer { // "indexer" in the configuration public static double rest = MEASURE; // servo position, out of the way (Servo Finder) public static double push = MEASURE; // servo position, piece pushed (Servo Finder) public static double pushSec = DEFAULT; // time to push (0.25, or the servo's speed) public static double returnSec = DEFAULT; // time to come back (the same as pushSec) } ``` - `DEFAULT` means "use the library's starting value". The speed gains (`kP` to `kF`) start from the motor in `Launcher.flywheel(...)`. INIT says `Starting gains (worked out, not tuned)` until you write your own. - `speedRpm` is the shot speed. Its starting value is 60% of the motor's top speed. - `speedByDistance` is the **shot table**: a speed for each distance to the goal. The launcher uses it only with a camera or odometry (`.speedFromDistance(camera)`, [Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/)). Until then, it uses `speedRpm`. - `rest` and `push` are `MEASURE`: INIT stops until you write them (step 3). - **With a feed stop:** add `feedStopHold`, `feedStopRelease`, `feedStopMoveSec` and `feedStopOpenSec` to `Tunables.Launcher`. The Feed Stop Finder gives all four. ### Controls.java: its buttons **Where:** `Controls.java`, inside `buttons(...)`. A part has no buttons until you add them. ```java title="Controls.java" robot.launcher.spinOn(g2.lb); robot.launcher.fireOn(g2.rb); robot.launcher.speedOn(g2.dpadUp, g2.dpadDown); robot.launcher.tableOn(g2.dpadRight); ``` | Button | What it does | | --- | --- | | LB | spins up, or spins down | | RB | a tap fires one piece. More taps fire more pieces. Held, it keeps firing | | D-pad up / down | the speed + / - `stepRpm`. With a shot table, the speed trim + / - 1% | | D-pad right | the next shot table (only with two tables or more) | With one gamepad (`oneDriver = true`), these `g2` lines work on gamepad 1 ([One gamepad, and a second one when you want it](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/#one-gamepad-and-a-second-one-when-you-want-it)). **How it fires:** - **A tap of RB is CAREFUL:** each piece waits until the wheel is at speed, and `shotIntervalSec` after the last piece. - **RB held is QUICK:** the first piece waits the same way. The next ones go a little sooner. Let go, and no more pieces go. - **Many quick taps** line up shots, at most `maxFiringQueue` (4). More taps do nothing. A nervous driver who taps 10 times does not get 10 shots. - **SPRAY** does not wait for the speed. It is off until you set `sprayEnabled = true`. Then tap RB, press it again and hold it: the launcher empties the robot fast. In the last seconds of a period, the launcher picks SPRAY by itself. - **It spins up at ▶** when it has a feeder or a feed stop. A launcher that only the intake feeds (`pushedBy` only) waits for LB. Change it with `spinAtStart = true` or `false` in `Tunables.Launcher`. - **Other buttons:** `robot.launcher.fireOn(g2.y);` puts the fire job on Y. Do not give the fire button a double tap or a long press of your own. With one, a quick press waits to see the gesture, and does not fire at once. Every setting: [Firing: shot modes](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#firing-shot-modes-feed-stop-piece-path). ### Actions.java and autos: use it in steps When the intake must run while the launcher fires, an action puts them together. **Where:** `Actions.java`, one method per action. ```java title="Actions.java" /** Fires 3 pieces with the intake running, to push each one in. Then the intake stops. */ public static Action fireWithIntake(Robot r) { return Action.named("Fire with intake") .then(r.intake::in, () -> r.launcher.fire(3)) .waitUntil("the shots", () -> !r.launcher.isShooting(), 9.0) .then(r.intake::stop); } ``` **Where:** `Controls.java`, inside `buttons(...)`. A button runs the action. The second line is a ready-made action: it needs nothing in `Actions.java`. ```java title="Controls.java" g2.y.press(Actions.fireWithIntake(robot)).says("fire 3 with the intake"); g2.x.press(robot.launcher.fireAllAction()).says("fire all"); // a ready-made action ``` **Where:** an autonomous in `autos/`. The wheel spins up while the robot drives to the shooting spot. ```java title="autos/YourAuto.java" s.start("Against our wall, facing the field", 0) .alongside(robot.launcher.readyAction(3)) // spin up while it drives .forward("To the shooting spot", 24, 0.5) .action(Actions.fireWithIntake(robot), 9) // waits until it is done (at most 9 s) .right("Park", 12, 0.5); ``` **With no camera:** the launcher has no distance, and shoots at `speedRpm`. An auto that shoots from two spots gives each spot its own speed: `.action(robot.launcher.fireAllAction(2250))` fires every piece at 2250 RPM, then goes back to `speedRpm`. ## 3. Find its numbers INIT stops on `MEASURE`. The finders still run, because they do not read `Tunables.java`. 1. **Servo Finder** ([how](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/)): find the indexer's two positions. `rest` is out of the way. `push` has pushed a piece into the wheel. Put them in `Tunables.Indexer`. 2. **Flywheel Finder** ([how](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/)): it finds the speed gains and the recovery time after a shot. Until then, the wheel runs on starting gains from the motor, and INIT says so: `Launcher: defaults from the catalog (gobilda-5203-6000): kF 11.7, ...`. Put the gains line in `Tunables.Launcher`. Make `shotIntervalSec` a little longer than the recovery time. Feed 10 pieces and read "Shots seen": it must show 10. Fewer: see `shotDropRpm` in [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#in-tunablesjava). 3. **Feed Stop Finder** ([how](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-stop-finder/)), only with a feed stop: the hold and release positions, and the firing times. With a CR servo or motor feeder and no feed stop, pushing parts or feed wheel: the **Feed Time Finder** ([how](https://crossbotics.com/ftc-helper/docs/tuning/07-feed-time-finder/)) instead. Its test shots give `feedSec`. 4. **Hood Finder** ([how](https://crossbotics.com/ftc-helper/docs/tuning/04-hood-finder/)), only with a hood: the hood's two stops. 5. **Shot Tuner** ([how](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/)), after the camera or the odometry: the shot table. ## 4. Check it, then tune it **Check it:** 1. Put on safety glasses. Keep everybody out of the front of the launcher. 2. Press INIT. Check that no warning names the launcher or the indexer. Press ▶. 3. Press LB to spin up. Read the speed on the Driver Station. It must reach the speed and stay there. 4. Press LB to stop the wheel. Load the pieces by hand. Keep your hands away from the wheel once it spins. 5. Spin up, then tap RB. The feeder must push **one** piece for each tap. **Tune it** with [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/), while the robot runs: 1. **speedRpm:** change it until the shots land where you want, from your usual shooting spot. 2. **The feeder:** when it pushes two pieces at once, make `pushSec` shorter. When the piece does not reach the wheel, move `push` further. Then put the tuned numbers in `Tunables.java`, in place of `DEFAULT`. ## More for your launcher Add these when your robot needs them. ### Two kinds of pieces: two shot tables Two pieces that fly differently need two speeds for the same distance. BIOBUZZ has POLLEN (a 2.8 in ball) and NECTAR (a 3.6 in ball). Each `speedByDistance...` line in `Tunables.Launcher` is a table, and the part after `speedByDistance` is its name: **Where:** `Tunables.java`, in `Tunables.Launcher`, in place of the `speedByDistance` line. ```java title="Tunables.java" public static double[][] speedByDistancePollen = {{36, 1970}, {48, 2250}, {60, 2520}, {72, 2790}}; public static double[][] speedByDistanceNectar = {{24, 2400}, {48, 2800}, {72, 3200}, {96, 3600}}; ``` - `.startTable("pollen")` on the launcher's line in `Robot.java` picks the table at ▶. - **Change the table:** D-pad right picks the next table (`tableOn`, above). Or one button for each piece: `g2.x.press(() -> robot.launcher.useTable("pollen"));`. In an action: `.then(() -> r.launcher.useTable("nectar"))`. - The Driver Station shows the table: `Shot table : POLLEN, 48 in (camera)`. - The [Shot Tuner](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/) fills each table: press Y until `> Table`, and pick it with the D-pad. ### Speed trim and a low battery In some matches every shot lands a little short or long (a worn wheel, soft balls). With a shot table, D-pad up and down make every shot 1% faster or slower. Hold it for more. Double-tap D-pad down to go back to 0. The Driver Station shows `Speed trim : +3% READY`. - The trim starts at 0 at every INIT. At INIT, the Driver Station offers the last trim: double-tap D-pad up after ▶ to use it. - **The same trim match after match:** the table is off. Multiply each speed in the table by the trim (+3%: x 1.03), put the new line in `Tunables.java`, and go back to no trim. - **A low battery** makes the wheel slow to get back to speed after a shot. Under 11.5 V the Driver Station warns. Swap the battery. Battery compensation is off, and not yet tested on a robot ([Speed trim and battery compensation](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#speed-trim-and-battery-compensation)). ### A hood: the shot angle A **hood** is the curved plate over the flywheel. It sets how steep the piece leaves. Near the goal, a steep shot drops in. Far away, a flatter shot goes further. With a hood, each row of a shot table has a third number: `{48, 2550, 11}` (inches, RPM, hood angle). **Where:** `Robot.java`, the launcher's line. The `.hood(...)` line is new. Add `import com.crossbotics.ftchelper.robot.Hood;`. ```java title="Robot.java" // The hood goes on the launcher; its numbers are in Tunables.Hood. // .part(...): which servos they are (optional, recommended). launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .hood(Hood.servo("hood").part("gobilda-2000-torque")) .speedFromDistance(camera)); ``` **Where:** `Tunables.java`, a new section, `Tunables.Hood`. ```java title="Tunables.java" public static class Hood { // "hood" in the configuration // posA and posB: the servo positions a hair off the hood's two hard stops. Never past them. public static double posA = MEASURE; // servo position at stop A (Hood Finder) public static double posB = MEASURE; // servo position at stop B (Hood Finder) // Optional: the hood's angle at each stop (any scale, e.g. 0 = steep end, 30 = flat end). public static double angleA = MEASURE; // the angle at stop A (an angle app) public static double angleB = MEASURE; // the angle at stop B (an angle app) public static double travelSec = DEFAULT; // stop to stop, seconds (0.5, or the servo's) public static double startAngle = DEFAULT; // where it goes at ▶ (angle A) } ``` - **`posA` and `posB` are the hood's two hard stops.** The hood never goes past them, because a servo that pushes on a stop gets hot and breaks. The [Hood Finder](https://crossbotics.com/ftc-helper/docs/tuning/04-hood-finder/) finds them. - **The launcher waits for the hood.** A servo cannot say where it is, so the launcher waits `travelSec` for a stop-to-stop move (`Launcher waits for: hood`). A piece fired while the hood moves flies wrong. - **By hand:** gamepad 2's left stick moves the hood. With a shot table, it trims the hood angle. Use the speed trim for shots that are short or long. Use the hood trim for shots that arrive at the wrong slope. - The [Shot Tuner](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/) finds the speed and the hood angle together: press Y until `> Hood`. Every setting, a linkage and a motor hood: [Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/). ### Know which piece fires next Two color sensors let the robot count what it holds and know the next piece: one where the pieces come in, and one at the "ready to fire" place. Then the next piece picks the shot table, and the drivers do not switch tables by hand. **Where:** `Robot.java`, in `define()`, **before** the launcher line (the launcher uses `pieces`). The field goes at the top of the class (`public Pieces pieces;`). ```java title="Robot.java" pieces = add(Pieces.kinds("POLLEN", "RED_NECTAR", "BLUE_NECTAR") .comingIn(PieceSensor.color("intake_color")) .readyToFire(PieceSensor.color("ready_color")) .max(4)); ``` Then add these two lines to the launcher's line: ```java title="Robot.java" .tableFrom(pieces.nextKind()) // the next piece picks the table .tableFor("nectar", "RED_NECTAR", "BLUE_NECTAR") // both NECTAR colors use "nectar" ``` - The [Piece Tuner](https://crossbotics.com/ftc-helper/docs/tuning/14-piece-tuner/) measures each kind's color. Until then, a piece reads `UNKNOWN`, and an `UNKNOWN` piece keeps the table in use. - The count can be wrong (two pieces that touch, a piece that bounces out). The drivers, not the count, keep the robot to its piece limit. Every sensor and command: [Pieces](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/). ### Try it in the simulator The goBILDA starter bot has a measured simulator robot. **Where:** the Terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:run -PteamCode=none -Probot=sim/robots/starter-bot-gobilda.properties ``` Open http://localhost:8780, choose "goBILDA Bot TeleOp", press INIT, then ▶. Tap LB and watch the speed go up, then tap RB. Tap RB before the wheel is at speed, and the piece waits. The turret and camera robots: [Add a camera: Try it in the simulator](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/#try-it-in-the-simulator). ## Fix a problem | Problem | Why, and the fix | | --- | --- | | INIT stops: `Tunables.Indexer.rest = MEASURE` | Not measured yet. Do step 3 | | INIT stops: `speedRpm` is above the motor's top speed | The number is too high for that motor, or the catalog id is wrong | | `Launcher gave up: flywheel` | The wheel never got to its speed. Check the encoder cable, run the Flywheel Finder, or lower `speedRpm` | | INIT: `Launcher fire one; hold: keep firing: no button (G2 RB is your "..." in Controls.java)` | One of your own jobs is on the launcher's button. Move your job to a free button | | Two pieces go in at once | The feeder runs too long. Lower `pushSec` | | The wheel spins the wrong way | Add `.reversed()` to the launcher in `Robot.java` | | `Launcher gave up: turret aimed` | The goal is not in view, or out of the turret's range, or `tolerance` is too small | | `Launcher: no shot table "nectr"` | No `speedByDistance...` line has that name. The warning lists the names there | | Shots short (or long) in every match | Trim with the D-pad. If you need the same trim again and again, tune the table again | | INIT stops: `Tunables.Hood has no posA` | Run the Hood Finder, and put its line in `Tunables.Hood` | | `Launcher waits for: hood`, and it never fires | `travelSec` is very long, or a motor hood cannot reach the angle | | INIT stops: `the row at 48 in has hood 30, outside the hood's range` | A table row asks past a stop. Fix the row, or the stops | | `battery 11.2 V: low` | Swap the battery. A low battery makes the wheel slow to get back to speed | ## Done when - INIT shows no warning for the launcher or the indexer. - LB spins the wheel up, and the speed holds. - Each tap of RB fires one piece. - The gains line from the Flywheel Finder is in `Tunables.Launcher`. --- **Next:** [Add a turret](https://crossbotics.com/ftc-helper/docs/add-to-robot/06-turret/), or [Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/) when your robot has no turret. **Look it up:** [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/): every setting, number and command. --- # Add a turret URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/06-turret/ **You need:** - A robot that drives, with its five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). - On the robot: a turret turned by a motor with an encoder, and hard stops at both ends. In the robot configuration, call the motor `turret`. - To follow the goal: a camera ([Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/)). ## 1. What it is A **turret** turns to an angle and holds it. With a camera, it follows the goal by itself. - **Angles are in degrees.** 0 is straight forward. Counterclockwise (to the left, seen from above) is +. - **It never turns past its range** (`min` to `max`). When the goal is outside, it waits at the limit, and the Driver Station says `goal out of turret range`. - **It needs a known 0.** Without a switch, 0 is where the turret points at INIT. Put it straight forward by hand before every INIT. A home switch finds 0 by itself at ▶. **Hard stops and software limits:** `min` and `max` are software limits. They are your wires' limits too. Software can be wrong, so the turret also needs physical blocks at both ends. Teams build turrets in many ways. This page adds a motor turret. For a servo, a CR servo, a slip ring or a home switch, see [Your turret is different](#your-turret-is-different) below. ## 2. Add it to the five files ### Robot.java: one line **Where:** `Robot.java`. The field goes at the top of the class (`public Turret turret;`). The line goes in `define()`, after the camera line. ```java title="Robot.java" // The camera knows the goal of each alliance (BLUE first, then RED). camera = add(Camera.limelight("limelight").goal("BLUE SCORING", "RED SCORING")); // "turret" = the motor's name in the robot configuration. 5 motor turns per turret turn. // follows(camera): it follows the goal from ▶, but never past Tunables.Turret min and max. turret = add(Turret.motor("turret", "gobilda-5203-117").gearRatio(5).follows(camera)); ``` - `.gearRatio(5)`: how many turns the motor makes for one turn of the turret. Count the teeth: turret gear / motor gear. A 20-tooth gear on a 100-tooth ring is 5. - `.follows(camera)`: the turret follows the goal from ▶. **With no camera yet:** leave out the camera line and `.follows(camera)`. Add them on [Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/). - When a name is red, click it and press Alt+Enter (Option+Enter on a Mac) to add the import. ### Tunables.java: its numbers **Where:** `Tunables.java`, a new section. The section's name is the device's name in CamelCase: `"turret"` reads `Tunables.Turret`. ```java title="Tunables.java" public static class Turret { // "turret" in the configuration public static double min = MEASURE; // furthest right, degrees (Motor Finder) public static double max = MEASURE; // furthest left, degrees: 0 = forward, + = left public static double startAngle = DEFAULT; // where you set it by hand before INIT (0) public static double kP = DEFAULT; // push per degree off (0.02) public static double kD = DEFAULT; // brake near the target (0.001) public static double maxPower = DEFAULT; // the most power (0.8) public static double tolerance = DEFAULT; // "aimed" within this, degrees (1.0) public static double cameraOffset = DEFAULT; // aims a little to one side: Aim Tuner (0) } ``` - `MEASURE` means "find this on the robot". INIT stops until you write a number. **Why:** a guessed range can pull the wires off. - `DEFAULT` means "use the library's starting value". You tune `kP` and `kD` later (step 4). - `cameraOffset` comes from the Aim Tuner, after the camera. ### Controls.java: its buttons **Where:** `Controls.java`, inside `buttons(...)`. A part has no buttons until you add them. ```java title="Controls.java" g2.rightStickX.use(v -> robot.turret.manual(-v)).says("by hand (right = clockwise)"); g2.rightStickButton.toggle(robot.turret.followMode()).rumble().says("follow the goal on/off"); // only with follows(...) ``` The operator's right stick turns the turret by hand. A click of the same stick switches following on and off: 2 buzzes = on, 1 buzz = off. **With one gamepad** (`oneDriver = true`): the stick click is also the library's field-centric button. Move field-centric first ([Turret: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/#buttons-to-add)). ### Actions.java and autos: use it in steps You need no line here for a turret that follows the goal. The launcher can wait until the turret is aimed. Add this to the launcher's line in `Robot.java`: **Where:** `Robot.java`, at the end of the launcher's line, before the `);`. ```java title="Robot.java" .requireReady("turret aimed", () -> turret.isAimed()) ``` For a turret that follows the goal, "aimed" means **at the goal now**. The robot sees the goal (camera or odometry), and the turret is in range and on it. When the robot loses the goal, the turret is not aimed. So the launcher never fires blind. To point it at an angle in an action, use `r.turret.aimAt(45)`. It stops following. ### Your turret is different **A home switch** (a touch sensor or a magnetic switch). At ▶ the turret turns slowly until it finds the switch. Then its angle is right, even when someone turned it by hand. ```java title="Robot.java" // "turret", "turret_home" = the motor's and the home switch's names in the robot configuration. // At ▶ the turret turns slowly until it finds the switch. turret = add(Turret.motor("turret", "gobilda-5203-312").gearRatio(2.75) .homeSwitch("turret_home") .follows(camera)); ``` ```java title="Tunables.java" public static class Turret { // "turret" in the configuration public static double min = MEASURE; // furthest right, degrees (Motor Finder) public static double max = MEASURE; // furthest left, degrees: 0 = forward, + = left public static double homeAngle = MEASURE; // where the switch closes (turret-setup.md) public static double homingPower = DEFAULT; // how slowly it looks for the switch (0.2) public static double homingTimeout = DEFAULT; // the most seconds it looks (5) } ``` **A servo turret.** A servo goes to a position by itself. It uses two servo positions and the turret's angle at each. It has no PID numbers and no homing. ```java title="Robot.java" // "turret" = the servo's name in the robot configuration. Numbers: Tunables.Turret. // fullRange(): the servo's whole turn. Turn it on BEFORE you measure posA and posB. turret = add(Turret.servo("turret").part("gobilda-2000-speed").fullRange().follows(camera)); ``` ```java title="Tunables.java" public static class Turret { // "turret" in the configuration // Two servo positions and the turret's angle at each: 0 = straight forward, counterclockwise // (left) +. Its range is between the two angles. public static double posA = MEASURE; // servo position at one end (Servo Finder) public static double angleA = MEASURE; // the turret's angle there (an angle app) public static double posB = MEASURE; // servo position, other end (Servo Finder) public static double angleB = MEASURE; // the turret's angle there (an angle app) public static double travelSec = DEFAULT; // posA to posB, seconds (0.6, or the servo's) public static double startAngle = DEFAULT; // sent here at ▶ (0) } ``` **A slip ring** (the turret turns round and round). A CR servo turns it, and an absolute encoder says where it points. ```java title="Robot.java" // A CR servo turns it, an absolute encoder says where it points, continuous(): no limits. // "turret", "turret_pos" = the servo's and the encoder's names in the robot configuration. // .part(...): which servo it is (optional, recommended). turret = add(Turret.crServo("turret").part("axon-max-mk2").analogEncoder("turret_pos").continuous() .follows(camera)); ``` ```java title="Tunables.java" public static class Turret { // "turret" in the configuration // No min and max: it turns round and round. public static double kP = 0.015; // push per degree off, CR servo (0.02) public static double kD = DEFAULT; // brake near the target (0.001) public static double maxPower = 1.0; // a CR servo's full speed (0.8) public static double tolerance = DEFAULT; // "aimed" within this, degrees (1.0) public static double encoderOffset = MEASURE; // encoder reading, pointing forward } ``` [Setting up a turret](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/) has every way to build a turret, with the lines for each. **It can hit another part** (a lift, an arm): write an interlock rule. While the lift is up, the turret stays out of its way ([Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/)). ## 3. Find its numbers INIT stops on `MEASURE`. 1. **`min` and `max`:** turn the turret by hand to where the wires are tight, both ways. Take a few degrees less. Measure the angle from straight forward with a phone angle app. 2. **`homeAngle`** (a home switch): remove the `.homeSwitch(...)` line. Put the turret straight forward, press INIT, then ▶. Turn it with the stick until the switch clicks. Read the angle on the Driver Station (`Turret : 43 deg`). That is `homeAngle`. Then add the line again. 3. **`posA`, `posB`, `angleA`, `angleB`** (a servo turret): the [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/) gives the two positions. Measure the turret's angle at each with a phone angle app. 4. **`encoderOffset`** (an absolute encoder): put the turret straight forward, press INIT, and read the encoder's degrees. 5. **`cameraOffset`:** the [Aim Tuner](https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/), after the camera. ## 4. Check it, then tune it **Check it:** 1. Put the turret straight forward by hand. Press INIT. Check that no warning names the turret. Press ▶. 2. Push gamepad 2's right stick to the right. The turret must turn **clockwise**. If it turns the other way, add `.reversed()`. 3. Turn it to each end with the stick. It must stop before the hard stops. 4. With a camera: click the right stick to turn following on. Point the robot at the goal. The Driver Station must say `following: camera`, then `AIMED`. **Tune it** with [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/), while the robot runs. Change one number, then let the turret follow the goal: 1. **kP:** raise it until the turret aims fast. If it shakes, go back a step. 2. **kD:** if it goes past the goal and comes back, raise it a little at a time. 3. **kI:** only if it stops a degree short, a very small number. Then put the tuned numbers in `Tunables.Turret`, in place of `DEFAULT`. ## Fix a problem | Problem | Why, and the fix | | --- | --- | | INIT stops: `Tunables.Turret.min = MEASURE` | Not measured yet. Do step 3 | | The turret turns away from the goal | Add `.reversed()` to the turret in `Robot.java` | | Every angle is off by the same amount | It did not point at `startAngle` at INIT. Use a mark, or add a home switch | | The angles are wrong | `.gearRatio(...)` is wrong (count the teeth again), or it did not point forward at INIT | | `goal out of turret range` | The goal is past `min` or `max`. Turn the robot | | `goal out of turret range (behind the robot: holding)` | The odometry says the goal is far behind. The turret holds where it points. Turn the robot toward the goal | | `homing failed: switch not found` | Homing turns the wrong way: set `homeDirection` (+1 or -1) | | INIT: `Turret : no angle from a program before: ...` | Turn it to `startAngle` by hand, then INIT again | | It is aimed, but the shots go wide by the same angle | The camera is beside the launcher. Run the Aim Tuner (`cameraOffset`) | ## Done when - INIT shows no warning for the turret. - The stick turns the turret, and it stops before both hard stops. - `min`, `max` and every other `MEASURE` in `Tunables.Turret` are numbers. - With a camera: the turret follows the goal and shows `AIMED`. --- **Next:** [Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/). **Look it up:** [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/): every setting, number and command. --- # Add a camera URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/ **You need:** - A robot that drives, with its five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). - On the robot: a Limelight 3A or a webcam. In the robot configuration, call it `limelight` (or `Webcam 1` for a webcam). - AprilTags to look at: the field's goal, or printed tags. - For a Limelight: a laptop and the Limelight's USB-C cable. ## 1. What it is A **camera** finds the goal and says how far away it is and in which direction. AprilTags are the square black-and-white codes on the field. - **It knows each alliance's goal.** `.goal("BLUE SCORING", "RED SCORING")` names each alliance's HIVE. The camera gives this match's goal only, never the other alliance's. - **It aims only at the up CELL.** In BIOBUZZ, teams can score only in the CELL whose tags read right side up. The camera never aims at a down CELL. - **Everything that aims uses it:** a turret that follows the goal, the launcher's speed from the distance, whole-robot aim and the aim buzz. - **It tests the light at INIT.** Each place has different light. The camera tries a few settings and keeps the one that sees the most tags. ## 2. Add it to the five files ### Robot.java: one line **Where:** `Robot.java`. The field goes at the top of the class (`public Camera camera;`). The line goes in `define()`, after the drive and **before** the parts that use it (a turret, a launcher). ```java title="Robot.java" // In INIT the Limelight tries these pipelines (your usual one FIRST) and keeps the best one. camera = add(Camera.limelight("limelight").autoPipelines(0, 1, 2).goal("BLUE SCORING", "RED SCORING")); // A webcam: Camera.webcam("Webcam 1").autoExposure().goal(...) tries the camera's own // exposure, then 3, 6 and 12 ms. ``` - `.autoPipelines(0, 1, 2)`: the lighting test at INIT. A **pipeline** is a set of camera settings that you save on the Limelight by number. Put your usual one first, because it wins a tie. - A webcam: `Camera.webcam("Webcam 1").autoExposure()`. It tries exposures in place of pipelines. - A webcam mounted upside down: add `.upsideDown()`, like `Camera.webcam("Webcam 1").upsideDown().autoExposure()`. Without it, the robot aims the wrong way ([A webcam upside down](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/#a-webcam-upside-down)). - A HuskyLens works too, with fewer features: no lighting test, and a rough distance ([Camera: A HuskyLens](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/#a-huskylens)). - When a name is red, click it and press Alt+Enter (Option+Enter on a Mac) to add the import. **Use it in the other parts.** Add `.follows(camera)` to the turret ([Add a turret](https://crossbotics.com/ftc-helper/docs/add-to-robot/06-turret/)). Add `.speedFromDistance(camera)` to the launcher, so its speed comes from the shot table: **Where:** `Robot.java`, at the end of the launcher's line, before the `);`. ```java title="Robot.java" .speedFromDistance(camera) ``` **Fire only when aimed** (no turret): add this check to the launcher's line too. It feeds a piece only when the camera sees the goal now and the robot points at it. So the robot never fires blind. It needs `import com.crossbotics.ftchelper.robot.Aim;`. ```java title="Robot.java" .requireReady("aimed", () -> aim().stage() == Aim.Stage.LOCKED) ``` With a turret, use the turret's check in place of this one ([Add a turret](https://crossbotics.com/ftc-helper/docs/add-to-robot/06-turret/#actionsjava-and-autos-use-it-in-steps)). ### Tunables.java: its numbers **Where:** `Tunables.java`, a new section. The section's name is the camera's name in CamelCase: `"limelight"` reads `Tunables.Limelight`, and `"Webcam 1"` reads `Tunables.Webcam1`. ```java title="Tunables.java" public static class Limelight { // "limelight" in the configuration public static double pipeline = 0; // a Limelight: the pipeline to use (0) public static boolean autoLighting = true; // try a few settings at INIT, keep the best (true) public static double pitchDeg = DEFAULT; // its tilt up, degrees (0 = level) } ``` - `pipeline`: the pipeline to use when the lighting test is off. - `autoLighting`: `true` runs the lighting test at each INIT. At an event, you can set it to `false` ([Camera lighting: At an event](https://crossbotics.com/ftc-helper/docs/tuning/11-camera-lighting/#at-an-event)). - `pitchDeg`: the camera's tilt up, in degrees. Then the camera gives the direction and the distance along the floor. - The camera reads these numbers once, at INIT. They are not in the tuning menu. Change them in `Tunables.java` and install again. **Aiming numbers** are in a section with a fixed name, `Tunables.Aim`. They set how whole-robot aim turns, and the goal's place on the field for the odometry backup. Every line is optional ([Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/)). ### Controls.java: its buttons **Where:** `Controls.java`, inside `buttons(...)`. The camera itself needs no button. These lines use what it sees. The aim buzz: gamepad 2 buzzes while the aim is close. ```java title="Controls.java" // Gamepad 2 buzzes while the aim is close: the closer, the stronger (Tunables.Aim.rumbleDeg). // It works for a turret that follows the goal and for whole-robot aim. g2.rumbleWhenAimed(); ``` **With no turret:** the whole robot turns to face the goal while the driver holds RB. Do not use it with a turret that follows the goal: INIT stops. ```java title="Controls.java" // Hold RB: the robot turns to face the goal by itself; the driver keeps forward and sideways. g1.rb.hold(robot.aimMode()::on, robot.aimMode()::off).says("hold: aim the robot at the goal"); // Or a toggle. Careful: while it is on, the robot turns by itself, even after you let go. // g1.rb.toggle(robot.aimMode()).says("aim the robot at the goal on/off").rumble(); ``` **The driver still wins:** while aim mode is on, a push of the turn stick turns the robot as the stick says. Let go, and the aim takes over again. **Aim only when you shoot:** add `public static boolean aimOnFire = true;` to `Tunables.Aim`. Then, with aim mode off, RB with the goal in view turns the robot to the goal, fires, and gives the turn stick back. It waits at most `aimOnFireSec` (0.5 s), so a press always fires. Tune whole-robot aim first: it uses the same numbers ([Quick turn on fire](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#quick-turn-on-fire)). To run the lighting test again in a match, put `relight()` on a button ([Camera: Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/#buttons-to-add)). ### Actions.java and autos: use it in steps **Where:** an autonomous in `autos/`, at the shooting spot. Three ready-made steps aim, get ready and fire, with nothing in `Actions.java`: ```java title="autos/YourAuto.java" .aimAtGoal("Aim", 4, 45) // turns the robot; goal not seen: looks 45 degrees each way .readyToLaunch("Ready", 3) // spins up, waits until at speed and aimed .action(robot.launcher.fireAllAction()) // fires every piece it holds, only when aimed ``` - `aimAtGoal` turns the whole robot to the goal (at most 4 s). When the camera does not see the goal, the robot turns slowly up to 45 degrees each way to find it. With a turret that follows the goal, it waits for the turret instead. - `readyToLaunch` waits until the wheel is at speed and every launcher check is true (at most 3 s). - With the "aimed" check, a robot that never found the goal fires nothing. - **Start where the camera sees the goal.** In BIOBUZZ, at the start, our HIVE's up CELL is on the HIVE's right side, seen from our wall ([Aim in an auto](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#aim-in-an-auto)). ## 3. Find its numbers 1. **Camera lighting** ([how](https://crossbotics.com/ftc-helper/docs/tuning/11-camera-lighting/)): for a Limelight, save 3 pipelines on a laptop (usual, bright and dim light). 2. **`pitchDeg`:** put a phone level app on the camera's face. Read the tilt up, in degrees. 3. **Aim Tuner** ([how](https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/)): it finds `cameraOffset`, when the camera is beside the launcher. Do not measure it: the tuner finds it from test shots. 4. **Shot Tuner** ([how](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/)): the shot table, a speed for each distance. Do it again when you change `pitchDeg`. ## 4. Check it, then tune it **Check it:** 1. Turn the robot so that the camera sees a tag. Press INIT. 2. Read the lighting line, for example `limelight lighting : pipeline 2 (9 of 10 pictures saw tags)`. When the camera sees no tag, this line is a warning. 3. Look at the camera's picture ([See what the camera sees](https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/#see-what-the-camera-sees)). The tags must be sharp, and not too dark or too bright. 4. Press ▶. Point the robot at your goal. The Goal line must say **seen**, then `Goal : LOCKED (camera, 52 in, 0.8 deg off)` when the robot (or the turret) points at it. **Tune it:** the aim numbers in `Tunables.Aim` (`turnKp`, `turnKd`) only change whole-robot aim. Change them with [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/). Then put the tuned numbers in `Tunables.java`. ## More for your camera ### When the camera loses the goal: the odometry An arm, another robot or a bad angle can hide the tags. A robot with odometry ([Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/)) knows where it is, so it can work out where the goal is too. Tell it where the goal is: **Where:** `Tunables.java`, in the `Tunables.Aim` section. ```java title="Tunables.java" public static class Aim { public static double goalX = 13; // the goal: inches right of the center line public static double goalY = -13; // the goal: inches from the center, - = our half public static boolean mirrorForRed = false; // BIOBUZZ: false } ``` - `goalX`, `goalY` are field numbers, seen from your own drivers' wall, as in `driveTo` ([Field numbers](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/#field-numbers)). BIOBUZZ: the up CELL at the start is 13 in right of the center line and 13 in toward your wall. Put the point where the camera measures to (the tags), so the camera's distance and the odometry's agree. - `mirrorForRed`: BIOBUZZ is `false`, because the field looks the same from each wall. On a mirror-image field, write `true`. INIT shows the choice on its `Aim :` line. Check it before the match. - You need nothing more. The turret and the shot table use the camera while it sees the goal, and the odometry while it does not: `Turret : 12 deg AIMED following: odometry`. A robot with no camera uses `.followsOdometry()` on the turret and `.speedFromOdometry()` on the launcher. **The camera comes first,** because the odometry drifts a little in a match. The odometry needs a good start, so the backup stays off until the robot has its pose. It gets the pose when an autonomous ran first, or when the drivers parked on the reset spot and held gamepad 1 START for 1 s ([Add odometry: TeleOp starts where autonomous ended](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/#teleop-starts-where-autonomous-ended)). The backup also stays off while it says the goal is farther than the field allows. Every setting: [Aim: The goal point](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#the-goal-point). ### Shooting while moving A piece shot from a moving robot keeps the robot's speed. At 30 in/s sideways, a piece in the air for 0.8 s lands 24 in to the side. So the robot aims that far the other way, at a "virtual goal". It needs odometry, for the robot's speed. **Where:** `Tunables.java`, in the `Tunables.Aim` section. ```java title="Tunables.java" public static boolean shootOnMove = false; // true only after testing it on the real robot public static double flightSec = 0.8; // seconds in the air: measure it public static double shooterForwardIn = -4; // the turret's pivot: inches ahead of the odometry's center public static double shooterLeftIn = 0; // the turret's pivot: inches left of the odometry's center ``` - **Measure `flightSec`** with a phone's slow-motion video (240 pictures a second). Film a shot from the side, count the pictures from the launcher to the goal, and divide by 240 (192 pictures = 0.8 s). - **The shooter's place:** do not measure from the robot's middle. Measure from the edges, in inches: `shooterForwardIn` = (half the robot's length) - (the pivot's distance from the FRONT edge). `shooterLeftIn` = (half the robot's width) - (the pivot's distance from the LEFT edge). Example: a robot 17 in long with the pivot 12.5 in from the front: 8.5 - 12.5 = -4 (4 in behind the middle). - **Test it:** first shoot standing still: the shots must land as before. Then drive slowly sideways past the goal and shoot. Misses toward the way the robot drives: `flightSec` is too short. Misses the other way: it is too long. - A button can switch it off in a match: `g2.a.toggle(robot.aim().movingShotMode()).says("shoot on the move on/off");`. Every setting, a camera on the body, longer flights: [Shooting on the move](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#shooting-on-the-move). ### Aim into the opening Some goals have their opening in front of their tags (BIOBUZZ: about 3 in in front of the tags under the CELL). From an angle, a shot aimed at the tags goes toward the back edge of the opening, and up close it can miss. Turn on the angle aim, and the robot aims at the opening instead: ```java title="Tunables.java" public static class Aim { public static boolean angleAim = true; // aim into the opening, not at the tags public static double goalFrontIn = 3; // the opening is 3 in in front of the tags (BIOBUZZ) } ``` Straight on, nothing changes. From an angle, the aim turns a few degrees toward the front of the goal. Put it on a button to compare shots with it on and off: `g1.a.toggle(robot.aim().angleAimMode());`. It needs a webcam ([Aim into the opening](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/#aim-into-the-opening)). ### Try it in the simulator The turret robot has a camera on a turret, and a shot table for each piece. Make its simulator file from its `Robot.java`, then run it. **Where:** the Terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:fromRobot -PteamCode=none -ProbotClass=com.crossbotics.ftchelper.examples.turretbot.Robot -Pout=build/turretbot.properties ./gradlew :sim:run -PteamCode=none -Probot=build/turretbot.properties ``` Open http://localhost:8780. Choose "TurretBot TeleOp", pick the alliance in INIT (gamepad 1 X = BLUE, B = RED), and press ▶. Drive until the goal is in view. The turret follows it, and the speed changes with the distance. - **Where to stand:** the tags are under the up CELL, so the camera must be below and in front of them. RED: about x 57, y -13, facing the HIVE (heading 90). BLUE: about x -57, y 13 (heading -90). Drag the robot there on the map. - Spin up (LB) and fire (RB). The POLLEN table comes from tuning in the simulator, so POLLEN shots go in. The NECTAR table is example numbers, so expect misses. - **Whole-robot aim:** do the same with `flywheelbot` (`-ProbotClass=com.crossbotics.ftchelper.examples.flywheelbot.Robot -Pout=build/flywheelbot.properties`). Choose "FlywheelBot TeleOp", drive until the goal is in view, and press RB on gamepad 1. - Your own robot: [Simulator](https://crossbotics.com/ftc-helper/docs/simulator/). ## Fix a problem | Problem | Why, and the fix | | --- | --- | | `limelight: not found: no Limelight called "limelight"` | The name in the robot configuration is different (case counts), or the Limelight is not in it. The OpMode still runs, without the camera | | `limelight lighting: NO TAGS SEEN` (after ▶) | No pipeline saw a tag at INIT. Have a tag in view at INIT. Check each pipeline on the Limelight's page | | `limelight lighting: no pictures from pipeline 2 (missing?)` | That pipeline is not set up on the Limelight. Make it, or take it out of `autoPipelines(...)` | | `Goal : not seen (RED SCORING is upside down (a down CELL))` | The camera sees only a down CELL. Drive to see the up CELL | | Aim turns away from the goal, or aims at the down CELL (webcam) | The webcam is mounted upside down. Add `.upsideDown()` to its line in Robot.java | | The speed never changes with distance | No goal in view. Check `pipeline` and the `goal(...)` names | | INIT stops: `robot.aimMode() ... separate modes` | The turret follows the goal. Remove the `aimMode()` line, or `.follows(...)` on the turret | | Whole-robot aim stops a few degrees off | Raise `turnKp`, or set `minTurnPower` in `Tunables.Aim` | | It is aimed, but the shots go wide by the same angle | The camera is beside the launcher. Run the Aim Tuner | | `limelight lighting: trying 1 of 3: pipeline 0 (no tags yet: face a tag)` (INIT) | No pipeline saw a tag yet. Turn the robot toward a tag. The test goes on until ▶ | | `Aim: no goal` | Whole-robot aim is on, but the camera does not see the goal, and there is no odometry backup | | `following: odometry` points the wrong way | Check `goalX`, `goalY` (seen from your own wall), `mirrorForRed`, and that the pose started right | | `Aim odometry: the pose was never set` | TeleOp ran with no autonomous before it. Run the autonomous first, or park on the reset spot and hold gamepad 1 START 1 s | | `Aim odometry: ... more than the field allows` | The pose is wrong. The backup stays off until it is right | | `Aim: camera says 60 in, odometry 48 in` | The pose drifted, or `goalX`, `goalY` are not where the camera measures to | ## Done when - At INIT, facing a tag, the lighting line shows a setting and no warning. - Pointed at your goal, the Driver Station shows `Goal : LOCKED`. - A Limelight has its 3 pipelines saved. --- **Next:** [Add lights](https://crossbotics.com/ftc-helper/docs/add-to-robot/08-lights/). **Look it up:** [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/) and [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/): every setting, number and command. --- # Add lights URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/08-lights/ **You need:** - A robot that drives, with its five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). - On the robot, one of these two: - a goBILDA RGB Indicator Light on a servo port. In the robot configuration it is a "Servo". Call it `light`. - a REV Blinkin LED Driver with an LED strip. In the robot configuration it is a "REV Blinkin LED Driver". Call it `blinkin`. ## 1. What it is A **light** shows one color at a time. You write **rules** in `Controls.java`: "show this color when this is true". - **The drivers watch the robot, not the Driver Station.** A light tells them "ready" without a look at the screen. - **The first true rule wins.** Put the most important rule first. - **A flash beats every rule** while it lasts: one short flash for each piece fired, or from a button or an action. - **The alliance shows at INIT, with no code.** Before the drivers pick the alliance, the light blinks white once a second. After the pick, it is solid RED or BLUE. At ▶ it flashes the alliance for 1 s, then your rules start. **Keep your rules away from red and blue.** Then nobody reads "intake on" as "BLUE alliance". The examples use purple, orange, green, yellow and white. **Game rules:** the referees can switch off a light that flashes faster than about 5 times a second (R202 J). So the library never changes the light faster than every 0.1 s, and blinks at most 5 times a second. Do not shine a light onto the field (G302). ## 2. Add it to the five files ### Robot.java: one line **Where:** `Robot.java`. The field `public Lights lights;` goes at the top of the class. The line goes in `define()`, after the drive. ```java title="Robot.java" // At the top of Robot.java: import com.crossbotics.ftchelper.robot.Lights; // A goBILDA RGB Indicator Light on a servo port ("Servo" in the robot configuration): lights = add(Lights.gobilda("light")); // Or a REV Blinkin LED Driver with an LED strip ("REV Blinkin LED Driver" in the configuration): // lights = add(Lights.blinkin("blinkin")); ``` - Use one of the two lines. The name in quotes is the name in the robot configuration. - When a name is red, click it and press Alt+Enter (Option+Enter on a Mac) to add the import. **When a Blinkin color looks wrong on your strip:** give that color another Blinkin pattern. Your rules still say `LightColor.BLUE`. A goBILDA light ignores this line. **Where:** `Robot.java`, in `define()`, below the lights line. ```java title="Robot.java" // At the top of Robot.java: import com.qualcomm.hardware.rev.RevBlinkinLedDriver; // A REV Blinkin LED Driver ("REV Blinkin LED Driver" in the robot configuration): lights = add(Lights.blinkin("blinkin")); // Plain blue too dark on your strip? Show another Blinkin pattern for BLUE. lights.blinkinPattern(LightColor.BLUE, RevBlinkinLedDriver.BlinkinPattern.BLUE_VIOLET); ``` The pattern names are on REV's Blinkin page. ### Two lights A robot can have two lights (or more). Pick one of these ways: | You want | Do this | | --- | --- | | Both lights show the same thing | One part that drives both: `.alsoLight(...)` | | Two goBILDA lights show the same thing, with no code | Plug both into one servo port with a servo Y-cable. Robot.java stays one light | | Each light shows something different | Two parts, each with its own rules | **Both lights show the same:** **Where:** `Robot.java`, in `define()`, in place of the lights line. ```java title="Robot.java" // "light" and "light_right" = the two lights' names in the robot configuration (the same kind). // Both show the same color, blinking and flashes. Write the rules once, for robot.lights. lights = add(Lights.gobilda("light").alsoLight("light_right")); ``` - Both lights must be the same kind: two goBILDA lights, or two Blinkins. - Write the rules once, for `robot.lights`. Both lights show the same color, blinking and flashes. **Each light shows something different:** **Where:** `Robot.java`. The two fields go at the top of the class. The lines go in `define()`, in place of the lights line. ```java title="Robot.java" // At the top of the class: public Lights leftLight, rightLight; Here in define(): leftLight = add(Lights.gobilda("light_left")); rightLight = add(Lights.gobilda("light_right")); ``` **Where:** `Controls.java`, inside `buttons(...)`. Each light has its own rules and its own `otherwise`. ```java title="Controls.java" // The left light: the launcher. The right light: the intake. robot.leftLight.show(LightColor.GREEN).when(robot.launcher::isReady); robot.leftLight.otherwise(LightColor.OFF); robot.rightLight.show(LightColor.YELLOW).when(robot.intake::isRunning); robot.rightLight.otherwise(LightColor.OFF); ``` **Why each light needs its own rules:** a rule, a flash and `otherwise` belong to one part. A flash on `robot.leftLight` does not show on `robot.rightLight`. ### Tunables.java: one switch **Where:** `Tunables.java`, a new section. You need it only to turn off the alliance at INIT. The section's name is the device's name in CamelCase: `"light"` reads `Tunables.Light`. ```java title="Tunables.java" public static class Light { // "light" in the configuration public static boolean allianceAtInit = true; // show the alliance in INIT, flash it at ▶ (true) } ``` `false`: no alliance color at INIT, and your rules show from INIT on. ### Controls.java: the rules **Where:** `Controls.java`, inside `buttons(...)`. Every file that names a color needs `import com.crossbotics.ftchelper.robot.LightColor;` at the top. Press Alt+Enter on a red `LightColor` to add it. Write the lines in this order: the flashes, then the endgame, then your rules. **1. A flash for each piece fired, and one from a button:** ```java title="Controls.java" // A flash beats every rule while it lasts (write it first: it reads that way). // A short white flash for each piece fired, and one from a button. robot.lights.show(LightColor.WHITE).forSeconds(0.2) .whenCountGoesUp(() -> robot.launcher.part().getShotsFired()); g2.a.press(() -> robot.lights.flash(LightColor.YELLOW)).says("flash the light (signal the partner)"); ``` The flash is 0.2 s, so two quick shots are two flashes, not one long one. **2. Yellow in the last 20 seconds:** ```java title="Controls.java" // Yellow, blinking, in the last 20 seconds of TeleOp: time to park (above the other rules: it wins). robot.lights.show(LightColor.YELLOW).blinking().inLastSeconds(20); ``` The time counts from ▶, like the gamepad buzzes. It is about 1 s off from the field clock. **3. Your rules, one per line:** ```java title="Controls.java" // One rule per line. The first true rule wins: put the most important first. // Red and blue are left for the alliance (shown at INIT), so no rule looks like one. robot.lights.show(LightColor.ORANGE).blinking().when(robot.intake::isPushingOut); // pushing out robot.lights.show(LightColor.GREEN).when(robot.launcher::isReady); // at speed: fire robot.lights.show(LightColor.PURPLE).when(robot.intake::isRunning); // intake on robot.lights.otherwise(LightColor.OFF); // none true ``` - Use the parts your robot has. Any true/false works as a rule: a part's method (`robot.intake::isRunning`), a mode (`() -> robot.turret.followMode().isOn()`), or your own test (`() -> robot.lift.position() > 1000`). - `otherwise(...)` is the color when no rule is true. **The alliance colors:** you add nothing, because it is on by default. When your light shows red badly, pick other colors for it: ```java title="Controls.java" // On by default: the alliance at INIT (solid RED or BLUE), flashed for 1 s at ▶. // Your light shows red badly? Other colors for the alliance at INIT (BLUE, and PURPLE for RED): robot.lights.allianceColors(LightColor.BLUE, LightColor.PURPLE); // No alliance color at INIT at all? Delete the line above and write: // robot.lights.allianceAtInit(false); ``` A line in `Controls.java` wins over `Tunables.Light.allianceAtInit`. ### Actions.java and autos: a flash when an action is done You need no line here for the light alone. An action can flash the light as its last step. No action "claims" the light, so any action may flash it. **Where:** `Actions.java`, one method per action. ```java title="Actions.java" // In Actions.java (it needs import com.crossbotics.ftchelper.robot.LightColor; at the top). // The last step: a 1 s white flash says "done" to the drivers. Pick a color your rules do not use. public static Action shootTwo(Robot r) { return Action.named("Shoot two") .then(r.launcher::spinUp) .waitUntil("at speed", r.launcher::isReady, 3.0) .then(() -> r.launcher.fire(2)) .waitUntil("both gone", () -> !r.launcher.isShooting(), 3.0) .then(() -> r.lights.flash(LightColor.WHITE, 1.0)); } ``` A GREEN flash over the GREEN "ready" rule cannot be seen. Pick another color, or a longer time. ## 3. Find its numbers A light has no numbers to find. The colors come from your rules. ## 4. Check it, then tune it **Check it:** 1. Press INIT. Before you pick the alliance, the light must blink white once a second. 2. Pick the alliance. The light must be solid RED or BLUE. 3. Press ▶. The light must flash the alliance for 1 s, then show your rules. 4. Make each rule true, one at a time (for example, turn on the intake). The light must show that rule's color. 5. Press the flash button (gamepad 2 A). The light must flash yellow. **Tune it:** nothing to tune. To change a color, change the rule and send the code again. ## Fix a problem | Problem | Why, and the fix | | --- | --- | | INIT stops: no device with that name | The name in `Robot.java` must match the robot configuration exactly | | The light shows the wrong rule | The first true rule wins. Move the most important rule up | | A flash does not show | It is the same color as the rule under it. Pick another color | | Two quick shots give one long flash | Put `.forSeconds(0.2)` before `whenCountGoesUp(...)` | | Your light shows red or blue badly | Pick other alliance colors: `robot.lights.allianceColors(LightColor.BLUE, LightColor.PURPLE);` | | A Blinkin color looks wrong | `lights.blinkinPattern(...)` in `Robot.java` | | The light blinks white in INIT | No alliance is picked yet. TeleOp: press gamepad 1 X or B. Autonomous: pick it in the INIT menu | | INIT stops: no device named the second light's name | That name is in `.alsoLight(...)` or a second `add(...)` line. Add it to the robot configuration, or remove it | | One of two lights shows nothing | With a Y-cable: check the cable. With `.alsoLight(...)`: both must be the same kind | | INIT stops on `blinking(...)` | More than 5 times a second is not allowed (R202 J) | ## Done when - INIT shows the alliance color on the light. - Each rule shows its color when it is true. - No rule uses red or blue. --- **Next:** [Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/). **Look it up:** [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/): every rule, color and command. --- # Add odometry URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/ **You need:** - A robot that drives, with its five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). The drive is calibrated (`Tunables.Drive.calibrated = true`, [Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/)). - For `driveTo`: a mecanum drive. A tank robot can still use odometry for `robot.pose()`. - On the robot, one of these three: - **a goBILDA Pinpoint and two pods** (recommended). The Pinpoint goes on an I2C port. In the robot configuration it is a "goBILDA® Pinpoint Odometry Computer". Call it `pinpoint`. - **a SparkFun OTOS** on an I2C port, 10 to 12 mm above the tiles. In the robot configuration it is a "SparkFun OTOS". Call it `otos`. - **dead wheels:** three pods (or two and the Control Hub's IMU), each in a motor port's encoder connector. Which one to get, and how to mount and wire it: step 1. ## 1. What it is **Odometry** tells the robot its **pose** every loop: where it is (x, y) and which way it faces (heading). - **Pods** are small free-turning wheels with encoders. Springs press them onto the tiles. One rolls forward and back (the **X pod**), one rolls sideways (the **Y pod**). - **Field numbers are inches, seen from your own drivers' wall**, whatever your alliance. x = inches right of the center line. y = inches away from your wall (negative = your half). Heading 0 = facing away from you, and a turn to the left is +. See the [field numbers](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/#field-numbers). - **It must know where its pods sit.** When the robot turns in place, a pod away from the turn point rolls too. The library takes that roll away. - **You must check it before it drives.** `driveTo` steps do nothing on the robot until `Tunables.Odometry.checked = true`. **Why:** a pod that counts the wrong way would send the robot the wrong way at speed. With odometry, `driveTo` goes to a field point and ends on it, even after a bump or a wheel slip. TeleOp starts where autonomous ended. ### Why odometry The drive wheels slip: they spin when another robot pushes yours, and they skid when the robot speeds up. After a bump, a drive by distance (`forward(...)`) is off, and every later step is off too. The robot does not know it. The pods carry no weight and drive nothing, so they do not slip. They only roll and count. The robot adds up every small move, many times a second. So it knows its real pose. **Why not AprilTags in BIOBUZZ:** the tags are on the HIVE cells, and the cells move. A tag tells you where you are compared with the tag, not with the field. So in BIOBUZZ, odometry says where the robot is, and the camera is for aiming. ### Which one to get | Choice | What it is | Parts and price (checked 2026-10-21) | | --- | --- | --- | | **goBILDA Pinpoint + 2 pods** (recommended) | a small odometry computer with its own IMU. Two pods plug into it, and it plugs into an I2C port | Pinpoint Odometry Computer V2, goBILDA 3110-0002-0002, $79.99. Two 4-bar odometry pods, goBILDA 3110-0001-0002, about $99.99 each (not checked on goBILDA's page: check it before you order) | | **SparkFun OTOS** | an optical sensor under the robot that watches the floor, like a computer mouse. No pods | SparkFun SEN-24904, $84.95 | | **Dead wheels** | three pods (or two and the Control Hub's IMU), each plugged into a motor port's encoder connector. No extra computer | the pods only. They use three (or two) encoder ports | - **I2C port:** the small 4-pin ports on the Control Hub (I2C 0 to 3). Sensors that send numbers, like the Pinpoint and the OTOS, plug in there. - **4-bar and swingarm pods:** goBILDA's two pod designs. They give a different number of encoder counts per mm. The library expects 4-bar pods. Swingarm pods need `.podsSwingarm()` in the odometry line. - **Why we recommend the Pinpoint:** it does the math itself about 1500 times a second, and the robot reads the answer once per loop. So the loop speed does not change how good the pose is. It also uses no encoder ports. ### Mount it, wire it, name it 1. **Mount the two pods** under the robot, with the springs pressing the wheels onto the tiles. One rolls **forward and back** (the X pod). One rolls **sideways** (the Y pod). They can sit anywhere: step 2 says how to give their places, and the tuner measures them. 2. **Mount the Pinpoint** flat, anywhere on the robot. 3. **Plug the X pod into the Pinpoint's X port, and the Y pod into its Y port.** **Why:** the Pinpoint takes X as forward. With the pods swapped, the robot takes forward as sideways. 4. **Plug the Pinpoint into an I2C port** on the Control Hub. Port 0 has the hub's own IMU, so use port 1. 5. **Add it to the robot configuration** on the Driver Hub: Configure Robot, edit your configuration, Control Hub, the I2C bus you used (for example I2C Bus 1), Add. Choose the type **goBILDA® Pinpoint Odometry Computer** and name it `pinpoint`. Save, and restart the robot. An OTOS goes on an I2C port the same way: type **SparkFun OTOS**, name `otos`. Mount it 10 to 12 mm above the tiles. For dead wheels, plug each pod's encoder cable into a motor port's encoder connector. The pod's name is that motor port's configuration name. ## 2. Add it to the five files ### Robot.java: one line **Where:** `Robot.java`, in `define()`, right after the `drive(...)` line. Add `import com.crossbotics.ftchelper.robot.Odometry;` at the top (Alt+Enter on the red name). Use the line for your kind. Measure with a tape from the robot's **edges**, with the bumpers off. The library works out the robot's center from the size. The Odometry Tuner then measures the exact numbers. **A Pinpoint:** ```java title="Robot.java" // After drive(...). The robot's length and width, then where each pod's wheel is, mm: // the forward pod from the LEFT edge, the sideways pod from the FRONT edge. odometry(Odometry.pinpoint("pinpoint").robotSizeMm(430, 400).podsFromEdgesMm(284, 383)); ``` ![A robot seen from above: the X pod 284 mm from the left edge, the Y pod 383 mm from the front edge](https://crossbotics.com/ftc-helper/docs/images/odometry-pods-from-edges.svg) | Number | What it is | Measure | | --- | --- | --- | | `robotSizeMm(430, …)` | the robot's length | front edge to back edge | | `robotSizeMm(…, 400)` | the robot's width | left edge to right edge | | `podsFromEdgesMm(284, …)` | the **X pod**: the pod that rolls when the robot drives **forward** | LEFT edge to the middle of its wheel | | `podsFromEdgesMm(…, 383)` | the **Y pod**: the pod that rolls when the robot drives **sideways** | FRONT edge to the middle of its wheel | - Plug the X pod (forward) into the Pinpoint's X port, and the Y pod (sideways) into its Y port. - goBILDA swingarm pods need `.podsSwingarm()` at the end of the line. The default is 4-bar pods. **An OTOS:** ```java title="Robot.java" // The robot's length and width, then the OTOS's middle from the FRONT and LEFT edges (mm), and its turn. odometry(Odometry.otos("otos").robotSizeMm(430, 400).mountFromEdgesMm(126, 200, 0)); ``` | Number | What it is | Measure | | --- | --- | --- | | `robotSizeMm(430, 400)` | length, then width | as for the Pinpoint | | `mountFromEdgesMm(126, …, …)` | where the OTOS is, front to back | FRONT edge to the middle of the OTOS | | `mountFromEdgesMm(…, 200, …)` | where the OTOS is, side to side | LEFT edge to the middle of the OTOS | | `mountFromEdgesMm(…, …, 0)` | the way its arrow points | degrees, see below | **Careful:** the OTOS line gives FRONT first, then LEFT. The Pinpoint line is the other way around. The last number is the way the OTOS's arrow points, in degrees (0 = forward, a turn to the left is +). The tuner cannot measure where an OTOS sits, so these tape numbers stay. **Dead wheels:** ```java title="Robot.java" // The configuration names of the motor ports the pods plug into: left, right, sideways pod. // trackWidthIn: left pod to right pod. perpForwardIn: the sideways pod, 6 in BEHIND the center. odometry(Odometry.threeWheels("par_left", "par_right", "perp") .trackWidthIn(13.2).perpForwardIn(-6)); ``` | Number or name | What it is | Measure | | --- | --- | --- | | `"par_left"` | the LEFT pod that rolls when the robot drives forward | its motor port's configuration name | | `"par_right"` | the RIGHT pod that rolls when the robot drives forward | its motor port's configuration name | | `"perp"` | the pod that rolls when the robot drives sideways | its motor port's configuration name | | `trackWidthIn(13.2)` | the distance between the two forward pods | the left pod's wheel to the right pod's wheel, inches | | `perpForwardIn(-6)` | how far the sideways pod is ahead of the robot's middle: **+** = ahead, **−** = behind | do not measure it from the middle (see below) | **A first `perpForwardIn` from the edges:** (half the robot's length) − (the sideways pod's wheel from the FRONT edge), in inches. Example: a robot 17 in long with the pod 14.5 in from the front: 8.5 − 14.5 = −6. The Odometry Tuner then measures the exact number. - Two pods and the IMU: `Odometry.twoWheels(parallel, perp)` with `.parallelLeftIn(...)` and `.perpForwardIn(...)` ([Odometry](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/#in-robotjava)). **Dead wheels and the OTOS need the IMU in the drive line** (`.imu(...)` in `drive(...)`). The tuner's Spin test uses it. The Pinpoint has its own. ### Tunables.java: the check and the reset spot **Where:** `Tunables.java`, a new section. Its name is always `Odometry`. ```java title="Tunables.java" public static class Odometry { // a fixed name: always Odometry public static boolean checked = false; // true after the Odometry Tuner's Loop test // "Set pose here" (TeleOp: hold gamepad 1 START 1 s on this spot), written for BLUE. public static double resetX = -56; // inches right of center, - = left public static double resetY = -61; // inches from center, - = our half public static double resetHeading = 0; // degrees, 0 = facing the field // RED: false = the same numbers from the red wall; true (or left out) = mirrored left-right. public static boolean mirrorForRed = false; // BIOBUZZ: false } ``` - `checked`: you set it to `true` by hand, after the tuner's Loop test passes (step 3). - `resetX`, `resetY`, `resetHeading`: the **reset spot**. When autonomous did not run, TeleOp does not know where the robot is. Put the robot on this spot, let go of the sticks, and hold gamepad 1 **START** for 1 s. Here the spot is your left corner tile, facing the field. - `mirrorForRed = false` is for BIOBUZZ: its field is turned half a turn, so RED uses the same numbers from its own wall. ### TeleOp starts where autonomous ended You write nothing for this: - When autonomous ends, its pose goes to TeleOp. TeleOp's INIT starts the odometry there, if autonomous ran in the last 5 minutes. A Pinpoint still calibrates right after INIT: the library keeps the pose and gives it to the Pinpoint when it is ready. - Field-centric "forward" comes from the odometry's heading. Hold BACK to make "forward" the way the robot faces now. This is for the driver only: the pose does not change, so aiming at a field point stays right. **With no autonomous, or one stopped early,** set the pose with the reset spot. Put the robot on it, let go of the sticks, and hold gamepad 1 **START** (OPTIONS on a PlayStation gamepad) for 1 s. Do it in INIT if you can. Gamepad 1 buzzes twice, and the Driver Station says `Pose set: x -56, y -61 in, heading 0 (BLUE)`. While the robot drives, it says `Pose NOT set: stop first`. START held with A or B pairs a gamepad, so it never sets the pose. From code or an action: `robot.resetPose()` (the reset spot) or `robot.resetPose(x, y, heading)`. To move the button: `lib.setPose(...)` ([Move the library's buttons](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/)). **One mirror setting for the whole robot.** The autos' start spots, the reset spot and the aim's goal point all use one answer to "is RED a mirror image of BLUE?". The robot takes the first one it finds: `Tunables.Aim.mirrorForRed`, then `Tunables.Odometry.mirrorForRed`, then the autonomous's `mirrorForRed()`, else `true`. Write it in `Tunables.Odometry`, so a TeleOp with no autonomous before it gets it right too. INIT shows the one it uses: `Reset spot for RED: ...`. **The autonomous ran with the wrong alliance:** with the alliance switch in `Controls.java` (`lib.switchAlliance(g1.start, g1.back)`), hold START, then BACK, for 1.5 s. On a mirrored field, the library mirrors the pose too. On BIOBUZZ's turned field it cannot: set the pose here again ([Switching the alliance in TeleOp](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/#switching-the-alliance-in-teleop)). ### Controls.java: show the pose **Where:** `Controls.java`, inside `buttons(...)`. The reset spot on START works with no line. To check the odometry, show the pose on the Driver Station: ```java title="Controls.java" show("Where", () -> String.format(Locale.US, "x %.0f, y %.0f in, heading %.0f", robot.pose().x, robot.pose().y, robot.pose().headingDeg)); ``` For a second reset spot, or a reset from an action: [How do I set the pose when autonomous did not run?](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-set-the-pose-when-autonomous-did-not-run). #### A button that drives to a spot in TeleOp With odometry, a button can drive the robot to a field spot by itself, for example to park at the end. **Any drive stick stops it at once**, and the driver has the robot again. It needs a mecanum drive and a field map, so that it goes around the field parts. **Where:** `Robot.java`, in `define()`, after the `odometry(...)` line: the field map. ```java title="Robot.java" // After odometry(...). The margin: half the robot's corner to corner size, plus some for drift. // Each box: two opposite corners, like driveTo's numbers. These are BIOBUZZ's two HIVE frames. fieldMap(FieldMap.margin(13) .keepOut("HIVE frame, near", -19.5, -24.8, 19.5, -15.4) .keepOut("HIVE frame, far", -19.5, 15.4, 19.5, 24.8)); ``` **Where:** `Controls.java`, inside `buttons(...)`: the button, and a time when it starts by itself. ```java title="Controls.java" // route(...) makes the job. It starts when the button or the time says so. Runnable park = route("Park", -56, -36, 0, 0.8); g1.dpadLeft.tap(park).says("drive to the park spot (a drive stick stops it)"); atSecondsLeft(10, park); ``` - `route("Park", -56, -36, 0, 0.8)`: the spot's x, y and heading (field numbers, as in `driveTo`), then the top power. - `atSecondsLeft(10, park)`: it starts with 10 s left. When a driver pushes a stick at that time, it waits until the sticks are let go (at most 5 s). - It drives only after the Drive Tuner and the Odometry Tuner (`calibrated` and `checked` are `true`). More: [Keep-out boxes and routes](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes). ### Actions.java and autos: drive to field points **Where:** a file in `autos/`, inside `steps(...)`. It needs a mecanum drive. ```java title="autos/YourAuto.java" // The start spot (x, y, heading) must be where the robot really stands: the pose starts there. s.start("Against our wall, in the left corner tile, facing the field", -56, -61, 0) .driveTo("To the goal", -30, -30, 45, 0.6) .parkWithSeconds(4) // The last number: "close enough", in inches (default 1). .driveTo("Park", -56, -36, 0, 0.7, 2.0); ``` - `driveTo(label, x, y, heading, power)`: a place on the field, not a distance. - The numbers in `start(...)` must be where the robot stands. The pose starts there. An action can also use the pose. **Where:** `Actions.java`, one method per action. ```java title="Actions.java" /** Runs the intake while the robot is on our half of the field (y below 0). */ public static Action intakeOnOurHalf(Robot r) { return Action.named("Intake on our half") .then(r.intake::in) .waitUntil("past the center line", () -> r.pose().y > 0, 10.0) .then(r.intake::stop); } ``` To drive around field elements (`routeTo`), see [keep-out boxes and routes](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes). ## 3. Find its numbers The **Odometry Tuner** is in the **Tune and check** OpMode ([how](https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/)). You need a 48 in strip of tape on the floor, with a mark at its start. 1. **Forward 48 in:** it says which way the X pod counts. For "counted BACKWARD", add `.reversed("x")` to the odometry line (dead wheels: that pod's port name). 2. **Left 24 in:** it says which way the Y pod counts. For "counted RIGHT", add `.reversed("y")`. 3. **Spin 3+ turns:** it measures where the pods sit, and shows the line to change, for example `.offsetsMm(-84.2, -167.5)`. The 1st number is the X pod: mm LEFT of the robot's middle (− = right). The 2nd is the Y pod: mm AHEAD of the middle (− = behind). With a Pinpoint, write `.offsetsMm(...)` in place of `.robotSizeMm(...).podsFromEdgesMm(...)`. Dead wheels get `.trackWidthIn(..).perpForwardIn(..)`. 4. Send the code again. 5. **Loop and back:** drive away at least 24 in and come back onto the mark. Within 1 in and 2 degrees, the screen says `Tunables.Odometry: checked = true`. Write it in `Tunables.java`. An OTOS gets `Tunables.Odometry: linearScalar = ...` from the Forward test. ## 4. Check it, then tune it **Check it:** 1. Run your TeleOp. Push the robot by hand and watch the `Where` line. 2. Forward must make y go up. Left must make x go down. A turn to the left must make the heading go up. 3. In an autonomous with a `driveTo`, set `Tunables.Drive.maxPower` low (0.4) for the first runs. Put the robot exactly on the start spot, and keep a hand on STOP. 4. In INIT, check for `Odometry: Pinpoint ready` (or your kind). Run it. The robot must end within about 1 in of the point. 5. Run it again, and push the robot gently sideways while it drives. It must come back on course. 6. Set `maxPower` back to `DEFAULT`. **Tune it** with the [Move Tuner](https://crossbotics.com/ftc-helper/docs/tuning/10-move-tuner/). It makes moves stop where they should and turns end on their heading. `driveTo` and routes use the same numbers (`moveMinPower`, `slowDownIn`, `turnMinPower`). With an odometry line, the Move Tuner measures with the odometry, so it sees a skid. Run its tests in order: Creep, Stops, Turns, Drift, then Move and turn on a mecanum. Put the `Tunables.Drive:` lines it shows in `Tunables.Drive`. To try a turn number without a new build, use [Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/). The drive's turn numbers change at the next INIT. Then write the number in `Tunables.Drive`. ## Fix a problem | Problem | Why, and the fix | | --- | --- | | `skipped: Tunables.Odometry.checked is false` in the report | Run the tuner's Loop test, then `checked = true` | | INIT stops: no `GoBildaPinpointDriver` named `"pinpoint"` | The configuration name and type must match `Robot.java` | | `Pinpoint: X pod not found: check its cable` | A pod cable is out of the Pinpoint | | `Pinpoint: calibrating (keep the robot still)` stays | The robot moved in INIT. Keep it still, and INIT again | | The pose goes the wrong way | A pod is reversed. Forward and Left tests, then `.reversed("x")` or `("y")` | | x and y look swapped | The X and Y pods are in each other's ports | | The pose drifts when the robot only turns | The offsets. Run the Spin test | | INIT stops: `driveTo(...) needs a mecanum drive` | `driveTo` drives sideways. A tank robot uses `turnTo` and `move` | | It drives to the mirror spot on RED | BIOBUZZ: `mirrorForRed = false` | | It circles the point or stops just short | Run the [Move Tuner](https://crossbotics.com/ftc-helper/docs/tuning/10-move-tuner/) | | The report says `NO_ODOMETRY` | The odometry stopped during a `driveTo`. Check the pod and I2C cables | | `OTOS: not answering` | The I2C cable, or the configuration name or type | | INIT stops: `odometry .reversed("...")` | A name in `.reversed(...)` that is not a pod. A Pinpoint's pods are `"x"` and `"y"` | | The tuner stops at INIT: `needs the IMU` | Dead wheels or an OTOS: add `.imu(...)` to `drive(...)` | | TeleOp's field-centric is wrong after autonomous | The heading in `s.start(...)` is wrong | | `No reset spot: add resetX, resetY, resetHeading to Tunables.Odometry` | The reset spot is missing in `Tunables.Odometry` | | After "set pose here", the pose is mirrored the wrong way on RED | BIOBUZZ: add `mirrorForRed = false` to `Tunables.Odometry`. INIT's `Reset spot for RED` line shows which is used | | `Pose NOT set: stop first` | The robot was driving (or aiming by itself). Stop, then hold START 1 s again | More, for `driveTo` reports (`STALLED`, `TIMED_OUT`): [Drive to points: problems](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/#problems). ## Done when - Pushed by hand, the `Where` line goes the right way. - The Loop test passed, and `Tunables.Odometry.checked = true`. - A `driveTo` ends within about 1 in of its point. --- **Next:** [Make parts work together](https://crossbotics.com/ftc-helper/docs/add-to-robot/10-parts-together/). For curved paths in autos: [Add Pedro paths](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/). **Look it up:** [Odometry](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/): every setting, number and command. --- # Make parts work together URL: https://crossbotics.com/ftc-helper/docs/add-to-robot/10-parts-together/ **You need:** - A lift, an arm and a claw, each added and checked on its own: [Add a lift](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/), [Add an arm](https://crossbotics.com/ftc-helper/docs/add-to-robot/02-arm/), [Add a claw](https://crossbotics.com/ftc-helper/docs/add-to-robot/03-claw/). - Their named positions measured: lift `down` and `high`, arm `stowed` and `score`, claw `open` and `closed`. Use your own names in place of these. ## 1. What it is Two things join the parts: - **An action** puts the moves in order: lift up, arm out, claw open, arm in, lift down. Each move waits until the part before it is there. One button starts it, and the same button cancels it. - **A safety rule** (an **interlock**: a rule that keeps two parts apart) stops the arm from swinging out while the lift is low. The action has the right order. The rule also covers a driver who moves one part by hand, and an action that you cancel half way. **Why both:** the action makes the score fast and the same each time. The rule makes a crash impossible, whoever moves the parts. ## 2. Add it to the five files ### Robot.java: the safety rule **Where:** `Robot.java`, in `define()`, after the lift's, the arm's and the claw's lines. ```java title="Robot.java" // The arm stays below its line while the lift is low, and the lift stays up while the arm is out. keepApart("ArmLift", arm.zoneAbove(), lift.zoneBelow()); ``` - `arm.zoneAbove()` is the arm's zone: from an angle up to the top of its swing (the arm is out). - `lift.zoneBelow()` is the lift's zone: from a height down to the bottom (the lift is low). - The two parts are never in their zones at the same time. **The part that is in its zone first keeps it. The other part waits outside its own zone**, with its target kept. It goes on when the first part leaves. For comparison, the cookbook's rule for a turret and a lift has the same shape: ```java title="Robot.java" // AFTER the parts' add lines: the turret stays out of its zone while the lift is in its // zone, and the other way round. Whoever is in its zone first keeps it. keepApart("TurretLift", turret.zone(), lift.zoneAbove()); ``` ### Tunables.java: where each zone starts **Where:** `Tunables.java`, a new section. Its name is the rule's name, `"ArmLift"`. ```java title="Tunables.java" public static class ArmLift { // keepApart("ArmLift", ...) in Robot.java public static double armAbove = MEASURE; // degrees: the arm is out from here up public static double liftBelow = MEASURE; // counts: the lift is low from here down public static double armStopSec = 0.15; // how long the arm takes to stop public static double liftStopSec = 0.2; // a heavy slide takes longer to stop } ``` - The field names come from the part's section name with a small first letter: `Arm` -> `armAbove`, `Lift` -> `liftBelow`. A lift called `lift_left` gives `liftLeftBelow`. INIT stops on a wrong name. - Each zone is in its part's own units: degrees for the arm, counts for the lift. - The rule reads these numbers once, at INIT. They are never in the tuning menu. **Why:** a zone that changes while the parts move could let them hit. The cookbook's section for the turret and lift rule: ```java title="Tunables.java" // The rule's own section, named like the rule in Robot.java. Each zone in its part's units. public static class TurretLift { // keepApart("TurretLift", ...) in Robot.java public static double turretFrom = MEASURE; // degrees: where the turret's zone starts public static double turretTo = MEASURE; // degrees: where it ends (robot's back) public static double liftAbove = MEASURE; // counts: the slide is up from here public static double liftStopSec = 0.2; // a heavy slide takes longer to stop (0.15) } ``` **Find the two numbers with the Motor Finder** ([Motor Finder](https://crossbotics.com/ftc-helper/docs/tuning/05-motor-finder/)). Keep a hand near STOP: 1. Choose `lift`. Raise the slide slowly until the arm can swing out with room to spare. Press **A** there. That count is `liftBelow`. 2. Put the lift at the bottom. Choose `arm`. Swing the arm out slowly until it almost touches the slide or the frame. Press **A** there. Change that count to degrees, as in [Add an arm, step 3](https://crossbotics.com/ftc-helper/docs/add-to-robot/02-arm/#3-find-its-numbers). A number a little below it is `armAbove`. ### Actions.java: the score action **Where:** `Actions.java`, one method per action. ```java title="Actions.java" /** Lift up, arm out, claw open, arm in, lift down: each move waits for the one before it. */ public static Action scoreHigh(Robot r) { return Action.named("Score high") .then(() -> r.lift.goTo("high")) .waitUntil("lift at the top", r.lift::isAtTarget, 2.0) // at most 2 s .then(() -> r.arm.goTo("score")) .waitUntil("arm out", r.arm::isAtTarget, 1.5) .then(r.claw::open) .waitUntil("claw open", r.claw::isDone, 1.0) .waitSeconds(0.3) // let the piece drop .then(() -> r.arm.goTo("stowed")) .waitUntil("arm in", r.arm::isAtTarget, 1.5) .then(() -> r.lift.goTo("down")); } ``` - `waitUntil(words, check, seconds)` waits until the check is true, at most that many seconds. When the time runs out, the action stops, and the Driver Station says `timed out waiting for` and the words. **Why:** a lift that never reached the top must not open the claw. - `isAtTarget` is true when a motor part (lift, arm) is at its named position. `isDone` is true when a servo part (claw) has had the time to get there. - The safety rule still works inside the action. If the arm is sent out too early, it waits at its line. ### Controls.java: the buttons **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Press Y: the action starts. Press Y again while it runs: it is canceled, safely. g2.y.press(Actions.scoreHigh(robot)).says("score high"); ``` Add a button that stops every action at once: ```java title="Controls.java" // Stop every running action at once (each stops what it started, safely). g2.back.press(robot::cancelAll).says("stop all actions"); ``` A canceled action stops what it started, safely: the lift holds its height and the arm holds its angle. The safety rule still holds. Move the parts back with their own buttons. **Use free buttons.** The part pages put the lift's heights on A, X and Y. Move one of them, or use another button for the action. INIT lists the free buttons (`G2 free: ...`). ### Autos: the same action as one step **Where:** your autonomous file in `autos/`, in its steps. ```java title="autos/YourAuto.java" s.start("Against our wall, facing the field", 0) .forward("To the goal", 24, 0.5) .action(Actions.scoreHigh(robot), 5) // waits until it is done (at most 5 s) .back("Back up", 12, 0.5); ``` `.action(action, seconds)` starts the action and waits until it is done. When it takes too long, the autonomous cancels it, and goes on with the next step. ## 3. Check it 1. Lift the wheels off the floor, and keep a hand near STOP. Put the lift at the bottom and the arm in. 2. Press INIT. Check that no warning names `ArmLift`. Press ▶. 3. **Check the rule first, by hand:** with the lift at the bottom, send the arm out with its own button. The arm must stop below its line and wait. The Driver Station says which part waits, and why. 4. Raise the lift. The arm must go on to its position by itself. 5. With the arm out, send the lift down. The lift must wait until the arm comes back in. 6. **Then the action:** put the parts back. Press Y once and watch each move. Press Y again during a move: everything must stop where it is. 7. Press Y and let it run to the end. Each move must start only when the one before it is done. **Slow first:** for the first runs, lower `maxPower` in `Tunables.Lift` and `Tunables.Arm`. Put it back when the order is right. ## 4. Tune it - **Wait times:** each `waitUntil` has a time limit. Set it a little longer than the move takes on the robot. A limit that runs out stops the action. Watch the Driver Station for the wait's name. - **The drop time:** `waitSeconds(0.3)` gives the piece time to leave the claw. Make it longer if the arm pulls the piece back in. - **Order:** some moves can start before the one before them ends. For example, the arm can start out when the lift is above `liftBelow`. Change one wait at a time, and check again. - **The rule's stop time:** if a part still goes past its waiting point, raise its `StopSec` ([Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/)). If it waits too far out, lower it. ## Fix a problem | Problem | Why, and the fix | | --- | --- | | INIT stops: `Tunables.ArmLift.armAbove = MEASURE` | Not measured yet. Find the two numbers (step 2) | | INIT stops on a field name | The name does not match the part. INIT says "did you mean ...?". Use that name | | The arm never swings out | The lift never leaves its zone: `liftBelow` is above the `high` height. Lower `liftBelow` | | The lift never goes down after a score | The arm is still in its zone: `armAbove` is below the `stowed` angle. Raise `armAbove` | | The action stops half way | A `waitUntil` ran out of time: `timed out waiting for ...`. Give it more time, or tune that part | | The claw opens before the arm is out | The arm's wait is missing or too short. Wait on `r.arm::isAtTarget` | | The parts still touch | The zones are too small. Move `armAbove` down or `liftBelow` up, or add a margin ([Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/)) | ## Done when - With the lift low, the arm will not swing out, from any button. - With the arm out, the lift will not go down. - One press of the button scores, in order, and a second press stops it. - The autonomous runs the same action as one step. --- **Next:** [Controls](https://crossbotics.com/ftc-helper/docs/controls/): more ways to use the buttons. **Look it up:** [Actions.java](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/) for every action step, and [Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/) for every rule setting. Examples: [Two parts that must not collide](https://crossbotics.com/ftc-helper/docs/guides/interlocks/). --- # The basics URL: https://crossbotics.com/ftc-helper/docs/cookbook/01-the-basics/ **The questions on this page:** - [Coming from Blocks: where did my blocks go?](#coming-from-blocks-where-did-my-blocks-go) - [Where does each line go? The files, whole](#where-does-each-line-go-the-files-whole) - [Words you will meet](#words-you-will-meet) ## Coming from Blocks: where did my blocks go? | In Blocks you used | Here you write | In which file | | --- | --- | --- | | a `repeat while opModeIsActive` loop | nothing: the library runs the loop for you, many times a second | - | | drive forward, turn (in autonomous) | `.move("Forward", 24, 0, 0.5)`, `.turn("Left", 90, 0.4)` ([moves](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-drive-forward-sideways-and-turn)) | a file in `autos/` | | `if` a sensor or part says something, then ... | `.waitUntil(...)`: wait until it is true, then go on ([wait until](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-wait-until-something-is-true)) | `Actions.java` or an autonomous | | `if` the drivers chose something before the match | `onlyIf(...)` with a menu choice ([choices](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-let-the-drivers-choose-before-the-match)) | an autonomous | | `repeat 3 times` | a `for` loop that adds the steps 3 times to an action ([repeat](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-repeat-steps-several-times)) | `Actions.java` | | set servo position | a named position: `robot.claw.open()`, `robot.intakeDeploy.goTo("deployed")` ([servo positions](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-any-servo-with-named-positions-a-gate-a-fold-out)) | `Controls.java`, `Actions.java` | | `waitForStart` | nothing: the library waits for ▶ (start on the Driver Hub). For something right after ▶: `atStart(...)` ([at ▶](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-run-an-action-when-the-opmode-starts)) | `Robot.java` | | blocks before `waitForStart`, or after the loop | `atInit(...)`, `duringInit(...)`, `atStop(...)` ([your own code](https://crossbotics.com/ftc-helper/docs/guides/your-own-code/)) | `Robot.java` | | `if gamepad2.y then ...` inside the loop | one line, once: `g2.y.press(...)` ([buttons](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-make-a-button-do-something-once)) | `Controls.java` | | `if` the button is held | `g1.a.hold(...)` ([hold](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-run-something-only-while-a-button-is-held)) | `Controls.java` | | `sleep 500` | `.waitSeconds(0.5)` ([wait](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-wait-half-a-second-like-sleep-in-blocks)) | `Actions.java` or an autonomous | | a loop that waits until something is true | `.waitUntil(...)` ([wait until](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-wait-until-something-is-true)) | `Actions.java` or an autonomous | | set motor direction REVERSE | drive motors: `.reversed("front_right", ...)` ([drive](https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/#a-wheel-turns-the-wrong-way-how-do-i-fix-it)); a lift: `.reversed()` ([lift](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#my-lift-goes-down-when-it-should-go-up-how-do-i-fix-it)) | `Robot.java` | | set motor power | a command of the part: `robot.intake.in()`, `robot.lift.goTo("high")` ([parts](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-send-a-part-to-a-position-from-a-button)) | `Controls.java`, `Actions.java` | | a variable for a number (a speed, a position) | a number in `Tunables.java` ([numbers](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#where-do-the-numbers-go)) | `Tunables.java` | | `telemetry.addData` | `show("Label", ...)` ([show](https://crossbotics.com/ftc-helper/docs/cookbook/13-telemetry/#how-do-i-show-a-value-on-the-driver-station-screen)) | `Controls.java` | | drive blocks (sticks to motor powers) | nothing: driving is built in ([driving](https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/#driving-that-is-already-built-in)) | - | **Why there is no loop:** in Blocks, your code ran again and again in the loop. Here `buttons(...)` runs **once**, at INIT, and each line plugs a job into a button. Then the library's loop runs the job each time the driver presses the button. So you never write `if`, `while` or `sleep` for buttons. More: [From Blocks to Java](https://crossbotics.com/ftc-helper/docs/blocks-to-java/). ## Where does each line go? The files, whole Each recipe gives a few lines. Put them INSIDE one of these files, at the spot the comment shows. Keep every other line of the file. Your files also start with a `package` line and some `import` lines. The recipes leave them out. They stay at the very top, above `public class`. An import tells Java where a word like `Lift` comes from. When Android Studio shows a word in red, click it and press **Alt+Enter** (Mac: **Option+Enter**) to add its import. **`Robot.java`**: the parts. Fields at the top, one line per part inside `define()`: ```java title="Robot.java" public class Robot extends RobotDefinition { public Intake intake; // one field per part: "public", the kind of part, a name public Lift lift; public Claw claw; public Camera camera; public Launcher launcher; @Override protected void define() { // the drive line, then one line per part drive(Drive.mecanum("front_left", "front_right", "back_left", "back_right") .motor("gobilda-5203-312").wheelMm(96) .imu("imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD)); odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); // .part(...) = which motor or servo it is: the id on its label (optional, recommended). (1)! intake = add(Intake.motor("intake").part("gobilda-5203-1150")); lift = add(Lift.slide("lift").part("gobilda-5203-435").bottomSwitch("lift_bottom")); claw = add(Claw.servo("claw").part("gobilda-2000-torque")); camera = add(Camera.limelight("limelight").goal("BLUE SCORING", "RED SCORING")); launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .speedFromDistance(camera)); } } ``` 1. `.part(...)` says which motor or servo it is. It is optional, but we recommend it: with it, the library takes better starting values from the part's numbers, and the simulator moves like the real part. The ids here are examples. Write the ids of your parts, from the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). An arm, a turret and a launcher need the motor's id, and take it in their brackets instead. Every recipe below has the same `.part(...)` comment, with this meaning. **`Controls.java`**: the buttons, and your TeleOp. Button lines go inside `buttons(...)`: ```java title="Controls.java" @TeleOp(name = "Cookbook TeleOp", group = "Cookbook") // the name on the Driver Station @Disabled // delete this line in your copy public class Controls extends ControlMap { public static boolean oneDriver = false; @Override protected void buttons(Robot robot, Pad g1, Pad g2) { // robot = your Robot.java, g1 = gamepad 1, g2 = gamepad 2. Button lines go here: g2.y.press(Actions.scoreHigh(robot)).says("score high"); show("Lift ticks", robot.lift::position); } } ``` **`Actions.java`**: one method per action: ```java title="Actions.java" public class Actions { // One method per action. r = your robot. Use it in Controls.java and in autos. public static Action scoreHigh(Robot r) { return Action.named("Score high") .then(() -> r.lift.goTo("high")) .waitUntil("lift at the top", r.lift::isAtTarget, 2.0) .then(r.claw::open) .waitSeconds(0.5) // wait half a second (this is "sleep", done safely) .then(() -> r.lift.goTo("down")); } } ``` An autonomous file: see [your first autonomous](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-make-my-first-autonomous-drive-2-feet). The numbers file: see [Tunables.java](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#where-do-the-numbers-go). **`Tunables.java`**: one section per part, inside `public class Tunables { ... }`. When a recipe adds a new part, it shows the part's whole section (`public static class Lift { ... }`). Put it inside `Tunables`, next to the other sections. If your file **already has** a section with that name, do not add a second one. Two sections with one name do not compile. Copy only the lines inside it into yours, and change the lines you already have. A recipe that adds to a section you already have says so ("In your `Tunables.Launcher` section") and shows only the lines. **How a recipe's section reads:** one number per line, with a short comment. - `MEASURE`: a number that only your robot can give (a lift's top, a servo's positions). INIT stops and names the tool that finds it. Write the number in its place. - `DEFAULT`: the library's starting value, shown in brackets in the comment. Change it only when you see the problem it fixes ([Find a setting by what you want](https://crossbotics.com/ftc-helper/docs/reference/tunables/#find-a-setting-by-what-you-want)). - A real number: the point of the recipe (a slower robot, a spot on the field). - These words need one line at the top of `Tunables.java`: `import static com.crossbotics.ftchelper.robot.Starting.*;` **Names:** the name in quotes in `Robot.java` (`Lift.slide("lift")`) is exactly the device's name in the robot configuration on the Driver Station. The section's name is that name in CamelCase (each word starts with a capital letter, no spaces or `_`): `"lift"` reads `Lift`, `"intake_deploy"` reads `IntakeDeploy`. ## Words you will meet | Word | Means | | --- | --- | | `Robot.java` | the file that says WHAT is on the robot: the drive and one line per part, inside `define()` | | `Tunables.java` | the file with every number (speeds, positions), one section per part | | `Controls.java` | the file that says which button does what, inside `buttons(...)`. It is also your TeleOp | | `Actions.java` | moves that use several steps or parts (score, grab) | | `autos/` | the folder with your autonomous programs, one file each | | configuration name | the name of a motor or servo you typed on the Driver Station (`"lift"`). The code must use the same name | | `robot.lift::position` | `::` hands over a method without running it. The library runs it later (when the driver presses the button) | | `() -> robot.lift.goTo("high")` | a **lambda**: a small piece of code the library runs later. Use `::` when the job is one method with nothing in its brackets (`robot.claw::open`); use `() ->` when the brackets hold something (`goTo("high")`) or for several commands | | `g1`, `g2` | gamepad 1 (the driver) and gamepad 2 (the operator) | | operator | the second driver, on gamepad 2: runs the mechanisms while the driver drives | | GUIDE | the center button of the gamepad. **Tap:** the button map (what each button does). **Hold 1 s** (PRACTICE profile): the tuning menu (change numbers while the robot runs) | | "every loop" | the library's loop runs many times a second: it reads the gamepads, runs the jobs and updates every part. You never write it | | power | from 0 (stopped) to 1 (full). A negative power runs the other way | | `robot`, `g1`, `g2`, `s` | names the library hands you: `buttons(Robot robot, Pad g1, Pad g2)` and `steps(Steps s, Robot robot)` (see [the files, whole](#where-does-each-line-go-the-files-whole)) | | `;` | ends a line of Java. A chain of steps (`.move(...)` then `.turn(...)`) is ONE line split over several lines: only its last line has `;` | | `"lift"` (in quotes) | a name. Capitals and spelling must match exactly | | class | one Java file's main block: `public class Robot ... { ... }`. "Inside the class" = between its `{` and `}` | | method | a named piece of code, like `define()` or `scoreHigh(...)`. Its lines go between its `{` and `}` | | `@TeleOp(...)`, `@Autonomous(...)` | puts the program in the Driver Station's list, with this name | | `@Disabled` | hides the program from the list. The cookbook's programs have it. Delete it in your copy | | `@Override`, `public`, `static`, `protected` | Java words the file needs. Copy them as they are | | INIT, ▶ | the Driver Station's two buttons: INIT gets ready (the library moves nothing then), and ▶ (start) runs the program | | PRACTICE, COMPETITION | the two profiles (ways to run): PRACTICE is slower and has the tuning menu | | ticks (counts) | how far a motor has turned, from its encoder (a sensor in the motor) | | `kP`, `kI`, `kD`, `kF` | the PID numbers: how hard a lift pushes toward its target. Start with the defaults | | catalog id (`"gobilda-5203-312"`) | a motor's or servo's name in the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/): 5203 is goBILDA's motor series, 312 its RPM (on the motor's label) | | `.part("gobilda-5203-435")` | which motor or servo a part uses. Optional, but recommended: with it, the library takes better starting values from the part's numbers, and the simulator moves like the real part. An arm, a turret and a launcher need the id, and take it in their brackets instead | | tuning menu | a menu where you change numbers while the robot runs. The INIT choice menu of an autonomous is a different menu | | terminal | a window where you type commands. In Android Studio: the **Terminal** tab at the bottom ([how](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/)) | **One rule for every recipe:** a job never waits. A `sleep(...)` or a `while` loop in a button job or an action freezes the whole robot, so never write one there. To wait, see [how do I wait half a second (like sleep)?](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-wait-half-a-second-like-sleep-in-blocks). --- # Driving URL: https://crossbotics.com/ftc-helper/docs/cookbook/02-driving/ **The questions on this page:** - [How do I set up a mecanum drive?](#how-do-i-set-up-a-mecanum-drive) - [How do I set up a tank (standard) drive?](#how-do-i-set-up-a-tank-standard-drive) - [A wheel turns the wrong way. How do I fix it?](#a-wheel-turns-the-wrong-way-how-do-i-fix-it) - [How do I tell the robot how the Control Hub is mounted?](#how-do-i-tell-the-robot-how-the-control-hub-is-mounted) - [How do I make the robot slower (or faster)?](#how-do-i-make-the-robot-slower-or-faster) - [How do I let one driver do everything?](#how-do-i-let-one-driver-do-everything) - [How do I put slow mode on a trigger?](#how-do-i-put-slow-mode-on-a-trigger) - [Driving that is already built in](#driving-that-is-already-built-in) ## How do I set up a mecanum drive? **Where:** `Robot.java`, inside `define()`. ```java title="Robot.java" // The four motor names, in this order: front left, front right, back left, back right. drive(Drive.mecanum("front_left", "front_right", "back_left", "back_right") .motor("gobilda-5203-312").wheelMm(96) // the motor (catalog id) and wheel size .imu("imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD)); ``` **Why:** the names must match the configuration, and the wheel size makes autonomous distances right. **More:** [Robot.java](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/), [Drive](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/). ## How do I set up a tank (standard) drive? **Where:** `Robot.java`, inside `define()` (in place of the mecanum line). ```java title="Robot.java" drive(Drive.tank("left_drive", "right_drive") .motor("gobilda-5203-312").wheelMm(96) .reversed("right_drive") // only the motors that run backward .imu("imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD)); ``` **Why:** the motors on the two sides face opposite ways, so one side runs backward. List that side's motors in `.reversed(...)`. With two motors per side, name all four: `Drive.tank("front_left", "front_right", "back_left", "back_right")`. **More:** [Robot.java](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#your-motor-names), [Drive](https://crossbotics.com/ftc-helper/docs/reference/parts/drive/). ## A wheel turns the wrong way. How do I fix it? **Where:** `Robot.java`, in the drive line, before `.imu(...)`. ```java title="Robot.java" drive(Drive.mecanum("front_left", "front_right", "back_left", "back_right") .motor("gobilda-5203-312").wheelMm(96) // List EVERY reversed drive motor. Without this line the left side is reversed. .reversed("front_right", "back_right") .imu("imu", LogoFacingDirection.UP, UsbFacingDirection.FORWARD)); ``` **Why:** the motors on the two sides face opposite ways. So one side must run reversed, or the robot does not go straight. **More:** [Wiring checks: check the motor directions](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#motor-direction-check-each-wheel-rolls-forward), [Troubleshooting](https://crossbotics.com/ftc-helper/docs/troubleshooting/#robot-behavior). ## How do I tell the robot how the Control Hub is mounted? **Where:** `Robot.java`, the `.imu(...)` part of the drive line. ```java title="Robot.java" drive(Drive.mecanum("front_left", "front_right", "back_left", "back_right") .motor("gobilda-5203-312").wheelMm(96) // Which way the hub's LOGO faces, then which way its USB PORTS face, on the robot. .imu("imu", LogoFacingDirection.LEFT, UsbFacingDirection.UP)); ``` **Why:** the IMU (the hub's turn sensor) must know which way is up. If it does not, turns and field-centric driving go wrong. **More:** [Robot.java: the IMU](https://crossbotics.com/ftc-helper/docs/five-files/01-robot-java/#how-your-control-hub-is-mounted). ## How do I make the robot slower (or faster)? **Where:** `Tunables.java`, section `Drive`. ```java title="Tunables.java" public static class Drive { // a fixed name: always Drive public static double maxPower = 0.6; // top wheel power: slow for first drives (1.0) public static double practiceMaxPower = DEFAULT; // top wheel power in PRACTICE (same as maxPower) public static double slowSpeed = DEFAULT; // top power with the slow trigger held (0.3) public static double strafeCorrection = DEFAULT; // sideways moves: Drive Tuner (1.15) public static double turnKp = DEFAULT; // auto turns: push per degree off (0.012) public static double turnKd = DEFAULT; // auto turns: brake near the end (0.003) public static double moveMinPower = DEFAULT; // auto: least power that moves it (0.30) public static boolean calibrated = false; // true after the Drive Tuner: auto runs then } ``` **Why:** `maxPower` is the top power in both profiles, so the drivers practice at match speed. Lower it for the first drives, then set it back. To set a lower top power for PRACTICE only, use `practiceMaxPower`, for example on a new driver's first day. **More:** [Tunables.java: the numbers](https://crossbotics.com/ftc-helper/docs/five-files/02-tunables-java/#the-drives-numbers), [Profiles](https://crossbotics.com/ftc-helper/docs/guides/profiles/). ## How do I let one driver do everything? **Where:** `Controls.java`, at the top of the class. ```java title="Controls.java" // true: every button is on gamepad 1 (the operator's buttons move there). public static boolean oneDriver = true; ``` **Why:** with one driver, the operator's buttons move to gamepad 1, and the stick clicks switch slow mode and field-centric. **More:** [How buttons work: one driver or two](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/#one-gamepad-and-a-second-one-when-you-want-it). ## How do I put slow mode on a trigger? **Where:** `Controls.java`, inside `buttons(...)`. This is for one driver. With two drivers, LT on gamepad 1 is already slow mode. ```java title="Controls.java" // One driver: slow on LT. The further it is pulled, the slower (down to slowSpeed). g1.lt.slow().says("slow"); ``` **Why:** a trigger gives fine control: a small squeeze makes the robot a little slower. **More:** [ControlMap: one driver](https://crossbotics.com/ftc-helper/docs/reference/controls/#controlmap). ## Driving that is already built in You write no code for these. With `Controls.java` (two drivers): - **Drive:** the gamepad 1 left stick drives (and strafes), and right stick X turns. LT gives slow mode: the further you pull it, the slower the robot. - **Field-centric** (mecanum): double-tap gamepad 1 **Y** to switch it on and off. Then "forward" is away from the drivers, whichever way the robot faces. - **Pause:** tap gamepad 1 **BACK**, and everything stops on brake. Tap again to go on. - **Reset "forward":** turn the robot to face away from you, then hold gamepad 1 **BACK** for 1 second. **More:** [How buttons work: the driving you get for free](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/#the-librarys-own-buttons), [the standard map](https://crossbotics.com/ftc-helper/docs/reference/controls/#controlmap). --- # Buttons and gestures URL: https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/ **Pick a free button.** Each part's usual buttons are lines in `Controls.java` too (see each part's "buttons to add" in the [reference](https://crossbotics.com/ftc-helper/docs/reference/robot-java/)). For example, the claw is on operator **B**, and the lift is on **A**, **X** and **Y**. When two jobs are on one button, INIT stops and names the button. INIT also lists the free buttons ([move a button](#how-do-i-move-a-parts-button-to-another-button)). **The questions on this page:** - [How do I make a button do something once?](#how-do-i-make-a-button-do-something-once) - [How do I run something only while a button is held?](#how-do-i-run-something-only-while-a-button-is-held) - [How do I switch something on and off with one button?](#how-do-i-switch-something-on-and-off-with-one-button) - [How do I put a tap, a hold and a double-tap on one button?](#how-do-i-put-a-tap-a-hold-and-a-double-tap-on-one-button) - [How do I make a button safe ("hold for 1 second")?](#how-do-i-make-a-button-safe-hold-for-1-second) - [How do I use two buttons together (like a shift key)?](#how-do-i-use-two-buttons-together-like-a-shift-key) - [How do I make the gamepad buzz?](#how-do-i-make-the-gamepad-buzz) - [How do I control a part with a stick?](#how-do-i-control-a-part-with-a-stick) - [How do I move a part's button to another button?](#how-do-i-move-a-parts-button-to-another-button) - [How do I put the launcher's fire button on another button?](#how-do-i-put-the-launchers-fire-button-on-another-button) - [How do I let the parts add their usual buttons by themselves?](#how-do-i-let-the-parts-add-their-usual-buttons-by-themselves) - [How do I move the library's own buttons (slow, field-centric, pause)?](#how-do-i-move-the-librarys-own-buttons-slow-field-centric-pause) - [How do I change the double-tap and hold times?](#how-do-i-change-the-double-tap-and-hold-times) - [How do I switch the alliance during TeleOp?](#how-do-i-switch-the-alliance-during-teleop) - [Buttons that are already built in](#buttons-that-are-already-built-in) ## How do I make a button do something once? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Once per press. "::" hands over the method; the button runs it later. g2.y.press(robot.claw::open).says("open the claw"); // Several commands: "() ->" starts a small piece of code (a lambda). g2.x.press(() -> robot.lift.goTo("low")).says("lift to low"); ``` **Why:** `press` runs the job once per press, the moment the button goes down. **More:** [Controls.java: add your own jobs](https://crossbotics.com/ftc-helper/docs/five-files/03-controls-java/#add-your-own-button), [Press types](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/#every-press-type). ## How do I run something only while a button is held? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Runs every loop while held; the second job runs once when it is let go. g1.a.hold(robot.intake::in, robot.intake::stop).says("intake in (hold)"); ``` **Why:** the second job stops the intake when you let go. Without it, the intake keeps running. **More:** [Press types](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/#every-press-type). ## How do I switch something on and off with one button? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Each press switches the intake on or off. rumble(): 2 buzzes = on, 1 buzz = off. g1.x.toggle(robot.intake).rumble().says("intake on/off"); ``` **Why:** `toggle` remembers on or off for you. The buzz tells the driver which one it is, so the driver does not have to look. **More:** [Press types](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/#every-press-type). ## How do I put a tap, a hold and a double-tap on one button? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Three gestures on one button: tap, hold, double-tap. g2.rb.tap(robot.launcher::fire).says("fire one") .hold(robot.launcher::fireWhileHeld, robot.launcher::ceaseFire).says("keep firing") .doubleTap(() -> robot.launcher.fire(3)).says("fire three"); ``` **Why:** one button can do several jobs, so the drivers need fewer buttons to remember. **More:** [Controls: gestures](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/#several-press-types-on-one-button). ## How do I make a button safe ("hold for 1 second")? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Runs once, after the button is held for 1 second: a safe "are you sure?". g2.dpadLeft.heldFor(1.0, robot.launcher::stop).says("hold 1 s: flywheel off"); ``` **Why:** a quick bump of the button does nothing, so nobody starts a big job by accident. **More:** [Controls: gestures](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/#several-press-types-on-one-button). ## How do I use two buttons together (like a shift key)? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Hold RB (the "shift key"), then press D-pad up: for a job that must not run by accident. g1.rb.with(g1.dpadUp, () -> robot.lift.goTo("high")).says("lift to high"); ``` **Why:** a pair is a safe place for a big job that you use only once or twice a match, like a climb. D-pad up alone still does its own job. **More:** [Controls: two buttons together](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/#two-buttons-together). ## How do I make the gamepad buzz? **Where:** `Controls.java`, inside `buttons(...)`. Add `.rumble()` after a job (see [the toggle recipe](#how-do-i-switch-something-on-and-off-with-one-button)). Or make the gamepad buzz when the robot gets ready: ```java title="Controls.java" // A buzz on gamepad 2 each time the flywheel gets to its speed. g2.rumbleWhen(robot.launcher::isReady); ``` **Why:** the drivers watch the robot, not the Driver Station. A buzz tells them "ready", so they do not have to look away. **More:** [Controls: feedback](https://crossbotics.com/ftc-helper/docs/controls/03-see-and-feel/#feedback-on-a-button). ## How do I control a part with a stick? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // A stick is a number from -1 to 1 (up and right are +). Its value goes to the job every loop. g2.rightStickY.use(robot.lift::manual).says("lift by hand"); ``` **Why:** a stick gives a number every loop, so the part moves as far as you push the stick. When you let go, the part holds. **More:** [Controls: sticks](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/#every-press-type). ## How do I move a part's button to another button? **Where:** `Controls.java`, inside `buttons(...)`. A part's buttons are lines in `Controls.java`. For example, the intake's usual buttons are operator RT and LT. To move them, change the button in their lines: ```java title="Controls.java" // The intake's usual lines are on RT and LT: here the same jobs are on the bumpers. g2.lb.hold(robot.intake::holdIn, robot.intake::stop).says("intake in (hold)"); g2.rb.hold(robot.intake::out, robot.intake::stop).says("intake out (hold)"); ``` **Why:** a part's buttons are your own lines. Put its jobs on the buttons you want, and leave its usual buttons free. **More:** [How buttons work: the buttons the parts bring](https://crossbotics.com/ftc-helper/docs/controls/01-how-buttons-work/#a-parts-buttons). ## How do I put the launcher's fire button on another button? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" robot.launcher.fireOn(g2.y); // all of RB's firing moves to Y robot.launcher.spinOn(g2.x); // LB's spin up / down moves to X ``` **Why:** the fire button does more than one job. A tap fires one piece, quick taps line up more shots, a hold keeps firing, and a tap then a hold sprays. `fireOn` moves all of these jobs in one line, and RB is then free for something else. `fireOn(null)` leaves no fire button at all. **More:** [Firing](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#firing-shot-modes-feed-stop-piece-path). ## How do I let the parts add their usual buttons by themselves? **Where:** `Controls.java`, inside the class, as a method of its own: below the `}` that ends `buttons(...)`, above the class's last `}`. ```java title="Controls.java" // true: each part adds its usual buttons by itself. A line in buttons(...) on one of them replaces it. @Override protected boolean useStandardButtons() { return true; } ``` **Why:** code written before v0.39.0 needs it. In that code, each part put its usual buttons on the gamepads with no line in `Controls.java`. Since v0.39.0, a part has no buttons until you write its lines (see each part's "buttons to add" in the [reference](https://crossbotics.com/ftc-helper/docs/reference/robot-java/)). So you can read every button as a line. **More:** [ControlMap](https://crossbotics.com/ftc-helper/docs/reference/controls/#controlmap). ## How do I move the library's own buttons (slow, field-centric, pause)? **Where:** `Controls.java`, inside the class, as a method of its own: below the `}` that ends `buttons(...)`, above the class's last `}`. At the top of the file, with the other imports: `import com.crossbotics.ftchelper.teleop.LibraryButtons;` ```java title="Controls.java" // The library's own buttons (driving, pause, menus...): move them here; null = no button. @Override protected void libraryButtons(LibraryButtons lib, Pad g1, Pad g2) { lib.fieldCentric(g1.x); // field-centric on/off: X instead of Y lib.slow(g1.rt); // slow on the right trigger: LT is free now lib.switchAlliance(g1.start, g1.back); // optional, off by default: hold START, then BACK, 1.5 s } ``` **Why:** the old button is then free for your own jobs in `buttons(...)`. When two library jobs are on one button, INIT stops and names the button. A file has only one `libraryButtons(...)` method, so put every `lib.` line in it. **More:** [Controls: move the library's buttons](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/). ## How do I change the double-tap and hold times? **Where:** `Tunables.java` (optional: leave the section out for the defaults). ```java title="Tunables.java" /** Optional: slower gestures, e.g. for new drivers. Leave the section out for the defaults (in brackets). */ public static class Buttons { // a fixed name: always Buttons public static double tapGapSec = 0.45; // most time between the taps of a double-tap (0.35) public static double holdSec = 0.4; // a press this long is a hold, not a tap (0.3) } ``` **Why:** some drivers tap slower. These times are in the tuning menu too. When you tune a value there, copy it back into `Tunables.java`, because the file is the record. **More:** [Press types](https://crossbotics.com/ftc-helper/docs/controls/02-press-types/#several-press-types-on-one-button). ## How do I switch the alliance during TeleOp? The drivers choose the alliance in INIT (gamepad 1: X = BLUE, B = RED). When they picked the wrong one and the match has started, this switch fixes it. Turn it on first. It is off by default, so nobody switches by accident. **Where:** `Controls.java`, inside the class, as a method of its own (below the `}` that ends `buttons(...)`). If you already have a `libraryButtons(...)` method, add only the `lib.switchAlliance` line to it. ```java title="Controls.java" // Controls.java, inside the class, next to buttons(...) (import // com.crossbotics.ftchelper.teleop.LibraryButtons at the top). Off by default. @Override protected void libraryButtons(LibraryButtons lib, Pad g1, Pad g2) { // Gamepad 1: hold START, then press and hold BACK too, for 1.5 s: BLUE <-> RED. lib.switchAlliance(g1.start, g1.back); } ``` **Why:** the alliance sets the goal that the camera and the turret aim at, and the light's color. With the wrong alliance, the robot aims at the other alliance's goal all match. Press START first, then BACK. BACK alone is the pause, so BACK first only pauses the robot. The 1.5 s hold means a bump does nothing. **More:** [Controls: move the library's buttons](https://crossbotics.com/ftc-helper/docs/controls/04-move-library-buttons/). ## Buttons that are already built in - **The button map:** INIT shows every button and what it does. During the match, tap **GUIDE**. - **The tuning menu:** hold **GUIDE** for 1 second (PRACTICE profile). A tap shows the map, a hold opens the menu. Copy each number you change there into `Tunables.java` ([Live tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/)). - **Two jobs on one button:** INIT stops and names the button, so you find the mistake before the match. - **Pause:** press gamepad 1 **BACK** (the small button left of the center), and everything stops at once. Tap it again to go on. - **Alliance:** choose it in INIT (gamepad 1: X = BLUE, B = RED). Switching during TeleOp is optional. [Turn it on](#how-do-i-switch-the-alliance-during-teleop). Then, on gamepad 1, hold the small **START** button, then press and hold **BACK** too, for 1.5 s. If you let go sooner, the alliance stays the same and the debug lines turn on or off. - **Set pose here** (robots with odometry): put the robot on the reset spot, let go of the sticks, and hold gamepad 1 **START** for 1 s. This works in INIT or in the match ([how](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-set-the-pose-when-autonomous-did-not-run)). **More:** [What the drivers see and feel: the button map](https://crossbotics.com/ftc-helper/docs/controls/03-see-and-feel/#the-button-map-and-the-teleops-init-screen). --- # Mechanisms URL: https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/ Each part is one line in `Robot.java`'s `define()`. It also needs a field at the top of the class (for example `public Lift lift;`) and a section with its numbers in `Tunables.java`. The section's name is the configuration name in CamelCase: `intake_deploy` reads `IntakeDeploy`. For its buttons, copy its lines into `Controls.java` (see "buttons to add" in the [reference](https://crossbotics.com/ftc-helper/docs/reference/robot-java/)). **The questions on this page:** - [How do I add an intake on a motor?](#how-do-i-add-an-intake-on-a-motor) - [How do I add an intake on CR servos?](#how-do-i-add-an-intake-on-cr-servos) - [How do I make the intake run from the start?](#how-do-i-make-the-intake-run-from-the-start) - [How do I add a lift with set heights?](#how-do-i-add-a-lift-with-set-heights) - [My lift goes down when it should go up. How do I fix it?](#my-lift-goes-down-when-it-should-go-up-how-do-i-fix-it) - [My motor isn't in the catalog](#my-motor-isnt-in-the-catalog) - [How do I run one lift on two motors?](#how-do-i-run-one-lift-on-two-motors) - [How do I add an arm that moves in degrees?](#how-do-i-add-an-arm-that-moves-in-degrees) - [How do I add a claw?](#how-do-i-add-a-claw) - [How do I run a claw on two servos?](#how-do-i-run-a-claw-on-two-servos) - [How do I add a wrist?](#how-do-i-add-a-wrist) - [How do I add any servo with named positions (a gate, a fold-out)?](#how-do-i-add-any-servo-with-named-positions-a-gate-a-fold-out) - [How do I get my servo's full range?](#how-do-i-get-my-servos-full-range) - [How do I send a part to a position from a button?](#how-do-i-send-a-part-to-a-position-from-a-button) - [My robot doesn't have this part yet. How do I keep its code?](#my-robot-doesnt-have-this-part-yet-how-do-i-keep-its-code) - [How do I add a launcher (flywheel and feeder)?](#how-do-i-add-a-launcher-flywheel-and-feeder) - [How do I add a turret that follows the goal?](#how-do-i-add-a-turret-that-follows-the-goal) - [How do I fire only when aimed, at the right speed?](#how-do-i-fire-only-when-aimed-at-the-right-speed) ## How do I add an intake on a motor? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // At the top of the class: public Intake intake; Here in define(): // "intake" = the motor's name in the robot configuration. Its numbers: Tunables.Intake. // .part(...): which motor it is (optional, recommended). intake = add(Intake.motor("intake").part("gobilda-5203-1150")); ``` ```java title="Tunables.java" public static class Intake { // "intake" in the configuration public static double inPower = DEFAULT; // power taking pieces in, 0 to 1 (1.0) public static double outPower = DEFAULT; // power pushing pieces out (0.7) } ``` **Why:** the intake reads its numbers from `Tunables.Intake`. Its buttons are lines in `Controls.java`: [Intake: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/#buttons-to-add). **More:** [Add a lift](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/#robotjava-one-line), [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/). ## How do I add an intake on CR servos? A CR (continuous rotation) servo spins all the way round, like a small motor, instead of going to a position. **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // Two continuous-rotation (CR) servos. The one that spins the wrong way is reversed. (1)! // "intake", "intake_right" = the servos' names in the robot configuration. Numbers: Tunables.Intake (the 1st name). // .part(...): which servo it is (optional, recommended). intake = add(Intake.crServos("intake", "intake_right").part("gobilda-2000-speed") .reversed("intake_right")); ``` 1. Also add the field at the top of the class: `public Intake intake;`. The two servos face each other, so one must turn the other way. `.reversed(...)` names that servo. **Why:** two servos that face each other must turn opposite ways to pull a piece in. The numbers are in `Tunables.Intake` too (`inPower`, `outPower`). **More:** [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/). ## How do I make the intake run from the start? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // Runs in from ▶ until stopped. Its button (operator RT) then switches it on/off. // .part(...): which motor it is (optional, recommended). add(Intake.motor("intake").part("gobilda-5203-1150").onAtStart()); ``` **Why:** many robots collect pieces all match. With this line, the driver does not have to switch the intake on. **More:** [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/). ## How do I add a lift with set heights? **Where:** `Robot.java` (the part) and `Tunables.java` (its numbers). ```java title="Robot.java" // At the top of the class: public Lift lift; Here in define(): // "lift", "lift_bottom" = the motor's and the bottom switch's names in the robot configuration. (1)! // .part(...): which motor it is (optional, recommended). lift = add(Lift.slide("lift").part("gobilda-5203-435").bottomSwitch("lift_bottom")); ``` 1. Each time the lift presses the bottom switch, the switch sets the lift's 0. With no switch, delete `.bottomSwitch(...)`. ```java title="Tunables.java" public static class Lift { // "lift" in the configuration public static double min = MEASURE; // lowest safe point, counts (Motor Finder) public static double max = MEASURE; // highest safe point, counts (Motor Finder) public static double kP = DEFAULT; // push toward the target (from the motor) public static double kI = DEFAULT; // fix a small steady miss (0) public static double kD = DEFAULT; // brake near the target (from the motor) public static double kF = DEFAULT; // hold up against gravity (0.05) public static double down = MEASURE; // a named height, counts: any name you like public static double low = MEASURE; // a named height (Motor Finder) public static double high = MEASURE; // a named height (Motor Finder) } ``` **Why:** the lift never goes past `min` and `max`, so it cannot break itself. INIT stops if they are missing. `MEASURE` stops INIT until you write the real number. Find yours with the [Motor Finder](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-find-a-lifts-limits-and-heights). `"lift"` must be the motor's name in your configuration. To send the lift to a height, see [from a button](#how-do-i-send-a-part-to-a-position-from-a-button). **More:** [Add a lift](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/#tunablesjava-its-numbers), [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/), [why the bottom switch matters](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/#1-what-it-is). ## My lift goes down when it should go up. How do I fix it? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // The lift goes DOWN on positive power (the Motor Finder says "add .reversed()"): flip it. // .part(...): which motor it is (optional, recommended). add(Lift.slide("lift").part("gobilda-5203-435").reversed()); ``` **Why:** the lift's limits and heights count up as it goes up, so positive power must move it up. **More:** [Motor Finder](https://crossbotics.com/ftc-helper/docs/tuning/05-motor-finder/), [Troubleshooting](https://crossbotics.com/ftc-helper/docs/troubleshooting/#robot-behavior). ## My motor isn't in the catalog **Where:** `Robot.java`, inside `define()`. ```java title="Robot.java" // A motor that is not in the catalog: its encoder counts per output turn, then its free speed (RPM). (1)! launcher = add(Launcher.flywheel("launcher", Motors.custom("my-flywheel-motor", 28, 5800))); // A servo: how far it turns (degrees), then its speed (seconds per 60 degrees, at 4.8 V). (2)! claw = add(Claw.servo("claw").part(Parts.customServo("my-claw-servo", 270, 0.16))); // Motors.unknown(...): "I know neither number" (a single unknown number: Double.NaN). (3)! lift = add(Lift.slide("lift").part(Motors.unknown("old-lift-motor"))); ``` 1. Find the two numbers on the seller's page. goBILDA: "Encoder Resolution" (the number "at the Output Shaft") and "No-Load Speed". REV: "Encoder Counts per Revolution" (at the output) and "Free Speed". The name (`"my-flywheel-motor"`) then works like a catalog id, here and in `.part(...)`. 2. When the seller lists 4.8 V and 6 V, use the 4.8 V speed, because the hub gives a servo about 5 V. 3. `Double.NaN` means "I don't know this one". The part then uses general defaults, and INIT says so. A launcher or an arm needs at least the counts per turn: `Motors.custom("...", 28, Double.NaN)`. **Why:** the library works out a part's defaults (a launcher's gains and speed, a lift's kP, a servo's move time) from its motor's or servo's numbers. When you describe yours with the seller's numbers, it works like a catalog part. INIT says `defaults from my-flywheel-motor (custom)`, and `:sim:fromRobot` writes its numbers into the simulator's robot file. For a number you do not know, write `Double.NaN` ("I don't know this one"). Or write the whole part as `Motors.unknown` / `Parts.unknownServo`. The part then uses general defaults, and INIT says so. Do not use a catalog motor that is "close": its numbers would be wrong, and nothing would warn you. **More:** [Parts not in the catalog](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-in-the-catalog), [Parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). ## How do I run one lift on two motors? **Where:** `Robot.java`, inside `define()`, and `Tunables.java`. ```java title="Robot.java" // "lift_left", "lift_right" = the motors' names in the robot configuration. Numbers: Tunables.LiftLeft. (1)! // Plug the encoder cable into the FIRST motor: only its encoder is read. (2)! // The motors face each other, so the second turns the other way: alsoMotorReversed. (3)! lift = add(Lift.slide("lift_left").part("gobilda-5203-435").alsoMotorReversed("lift_right")); ``` 1. The numbers are in `Tunables.LiftLeft` (the FIRST motor's name in CamelCase), not in `Tunables.Lift`. 2. Both motors always get the same power, also when the lift stops or pauses. So one encoder is enough. 3. When both motors turn the same way for "up", use `.alsoMotor("lift_right")` instead. ```java title="Tunables.java" // A lift on two motors, Lift.slide("lift_left").part("gobilda-5203-435").alsoMotorReversed("lift_right"): // its section is the FIRST motor's name in CamelCase. public static class LiftLeft { // "lift_left" in the configuration public static double min = MEASURE; // lowest safe point, counts (first motor) public static double max = MEASURE; // highest safe point, counts (first motor) public static double kP = DEFAULT; // push toward the target (from the motor) public static double kI = DEFAULT; // fix a small steady miss (0) public static double kD = DEFAULT; // brake near the target (from the motor) public static double kF = 0.06; // a heavier slide needs more hold (0.05) public static double down = MEASURE; // a named height (Motor Finder) public static double low = MEASURE; // a named height (Motor Finder) public static double high = MEASURE; // a named height (Motor Finder) } ``` **Why:** two motors on one slide must never fight. The library sends both the very same power in the same loop. It does this also when the lift stops or pauses (BACK). It does it also when an interlock rule (a rule that stops two parts from hitting each other) holds the lift. Your own code that copies the power every loop would miss pause and STOP. **Check the directions before the chain goes on.** With the chain or belt off, each motor must turn the way that lifts. If one is wrong, swap `alsoMotorReversed` and `alsoMotor`. Two motors that push against each other get hot and can break a gearbox. An arm works the same way: `Arm.motor("arm_left", "gobilda-5203-117").alsoMotorReversed("arm_right")`. The simulator ties both motors to one slide (`:sim:fromRobot` writes the second motor's line). **More:** [Two motors on one lift or arm](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm), [Tunables names](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#in-tunablesjava). ## How do I add an arm that moves in degrees? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // "arm" = the motor's name in the robot configuration. Its numbers: Tunables.Arm. // "gobilda-5203-117" = the motor's catalog id (needed: it works in degrees). (1)! // gearRatio: motor turns per arm turn. 0 degrees = where it is at INIT. arm = add(Arm.motor("arm", "gobilda-5203-117").gearRatio(2)); ``` 1. The arm needs the motor's counts per turn to work in degrees. So, as for a turret or a launcher, the arm's motor id is required. ```java title="Tunables.java" public static class Arm { // "arm" in the configuration public static double min = MEASURE; // lowest safe angle, degrees, 0 = at INIT public static double max = MEASURE; // highest safe angle, degrees (Motor Finder) public static double kP = DEFAULT; // push toward the target (0.02) public static double kI = DEFAULT; // fix a small steady miss (0) public static double kD = DEFAULT; // brake near the target (0.001) public static double kF = 0.1; // hold up against gravity (0) public static double stowed = MEASURE; // a named angle, degrees: any name you like public static double pickup = MEASURE; // a named angle (Motor Finder) public static double score = MEASURE; // a named angle (Motor Finder) } ``` **Why:** degrees are easier to think about than encoder counts. Put the arm at its 0 before you press INIT. **More:** [Arm](https://crossbotics.com/ftc-helper/docs/reference/parts/arm/). ## How do I add a claw? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // At the top of the class: public Claw claw; Here in define(): // "claw" = the servo's name in the robot configuration. Its numbers: Tunables.Claw. // .part(...): which servo it is (optional, recommended). claw = add(Claw.servo("claw").part("gobilda-2000-torque")); ``` ```java title="Tunables.java" public static class Claw { // "claw" in the configuration // The Servo Finder shows "Tunables.Claw: P1 = 0.210, P2 = 0.770": write P1 as open, P2 as closed. public static double open = MEASURE; // servo position, open (Servo Finder) public static double closed = MEASURE; // servo position, closed (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) } ``` **Why:** a claw needs two numbers, open and closed, and the Servo Finder gives them. Its button is a line in `Controls.java`: [Claw: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#buttons-to-add). **More:** [Add a lift](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/#robotjava-one-line), [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/). ## How do I run a claw on two servos? **Where:** `Robot.java`, inside `define()`, and `Tunables.java`. ```java title="Robot.java" // "claw_left", "claw_right" = the servos' names in the robot configuration. Numbers: Tunables.ClawLeft. // Find open and closed in Tune and check > Servo Finder on the FIRST servo: the second moves with it. // The servos face each other, so the second turns the other way: alsoServoReversed. claw = add(Claw.servo("claw_left").part("gobilda-2000-torque").alsoServoReversed("claw_right")); ``` ```java title="Tunables.java" // A claw on two servos, Claw.servo("claw_left").alsoServoReversed("claw_right"): its section is the // FIRST servo's name in CamelCase. public static class ClawLeft { // "claw_left" in the configuration public static double open = MEASURE; // servo position, open (Servo Finder on claw_left) public static double closed = MEASURE; // servo position, closed (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) public static double alsoTrim = DEFAULT; // the second servo: raw position added so the two meet (0; used at the next move) } ``` **Why:** two servos on one part must never fight. The library sends both the same position at the same moment, also when the robot pauses (BACK) or stops. Your own code that copies the position would miss some of these moments. **Reversed or not:** servos that face each other (mirror images, the usual way) turn opposite ways, so use `alsoServoReversed`. When both face the same way, use `.alsoServo("claw_right")`. **When the fingers do not quite meet:** the horns may sit a spline tooth apart. Set `alsoTrim` (a small raw position, like 0.02) for the second servo. The same line works on a Wrist, a Positioner and a servo feeder: `Indexer.servo("feeder_left").alsoServoReversed("feeder_right")` (two arms that pinch a piece into a launcher). On a CR servo feeder, it adds a second wheel that spins the other way: `Indexer.crServo("feeder_left").alsoServoReversed("feeder_right")`. **More:** [Two servos on one part](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/), [Tunables names](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/#in-tunablesjava). ## How do I add a wrist? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // At the top of the class: public Wrist wrist; Here in define(): // "wrist" = the servo's name in the robot configuration. Its numbers: Tunables.Wrist. // .part(...): which servo it is (optional, recommended). wrist = add(Wrist.servo("wrist").part("gobilda-2000-speed")); ``` ```java title="Tunables.java" public static class Wrist { // "wrist" in the configuration public static double down = MEASURE; // servo position: any name you like public static double level = MEASURE; // servo position (Servo Finder) public static double up = MEASURE; // servo position (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) } ``` **Why:** a wrist steps through its named positions. Its buttons are lines in `Controls.java`: [Wrist: buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/#buttons-to-add). **More:** [Wrist](https://crossbotics.com/ftc-helper/docs/reference/parts/wrist/). ## How do I add any servo with named positions (a gate, a fold-out)? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // Any servo with named positions: a gate, a kicker, a fold-out intake. // "intake_deploy" = the servo's name in the robot configuration. Numbers: Tunables.IntakeDeploy. // .part(...): which servo it is (optional, recommended). intakeDeploy = add(Positioner.servo("intake_deploy").part("gobilda-2000-torque")); // Right after ▶ (autonomous and TeleOp): fold the intake out. atStart(() -> Action.named("Deploy").then(() -> intakeDeploy.goTo("deployed"))); ``` ```java title="Tunables.java" public static class IntakeDeploy { // "intake_deploy" in the configuration public static double stowed = MEASURE; // servo position, folded (Servo Finder) public static double deployed = MEASURE; // servo position, folded out (Servo Finder) public static double travelSec = DEFAULT; // time for a full 0-to-1 move (0.3, or the servo's) } ``` **Why:** a `Positioner` has no usual buttons, so you choose when it moves. Here it moves at ▶. **More:** [Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/positioner/), [an action at ▶](https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/#how-do-i-run-an-action-when-the-opmode-starts). ## How do I get my servo's full range? **Where:** `Robot.java`, inside `define()`: add `.fullRange()` to the servo part. ```java title="Robot.java" // fullRange(): positions 0 to 1 = the servo's whole turn (300 degrees on a goBILDA 2000). (1)! // Turn it on FIRST, then find the positions (Servo Finder: press Y while choosing the servo). wrist = add(Wrist.servo("wrist").part("gobilda-2000-speed").fullRange()); ``` 1. For positions 0 to 1, the hub normally sends 600-2400 us (microseconds). With that signal, a goBILDA 2000 servo turns only 270 of its 300 degrees. `fullRange()` sends the whole 500-2500 us. **Why:** the FTC SDK's normal servo signal (600 to 2400 microseconds) is narrower than what most servos take (500 to 2500). So the servos turn less than the seller says: 270 degrees for a goBILDA 2000, 243 for a REV Smart Robot Servo. Add it only when you need the extra turn. It works the same on a Claw, a Positioner, `Hood.servo`, `Turret.servo` and `Indexer.servo`. After the change, the positions you measured before point somewhere else, so measure them again. Without `.fullRange()`, nothing changes. **More:** [Full range](https://crossbotics.com/ftc-helper/docs/modules/hardware/#full-range) (a table per servo), [Claw, Wrist, Positioner](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/). ## How do I send a part to a position from a button? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // The names are the ones in Tunables.java (capitals do not matter). g2.y.press(() -> robot.arm.goTo("score")).says("arm to score"); g2.a.press(() -> robot.arm.goTo("pickup")).says("arm to pick up"); g2.x.press(() -> robot.lift.goTo("high")).says("lift to high"); g2.b.press(robot.claw::toggle).says("claw open/close"); g2.back.press(() -> robot.intakeDeploy.goTo("stowed")).says("fold the intake in"); ``` **Why:** `goTo("name")` uses the position by its name, so the number is only in `Tunables.java`. These lines use Y, A, X and B. The lift's and the claw's usual lines use the same buttons, so write one or the other. See [pick a free button](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/). **More:** [Lift](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/), [Claw](https://crossbotics.com/ftc-helper/docs/reference/parts/claw/). ## My robot doesn't have this part yet. How do I keep its code? You change three places: the part's line in `Robot.java`, the action in `Actions.java`, and its button in `Controls.java`. **`Robot.java`**, inside `define()`: add `.optional()` to the part's `add` line. Here the part is a deploy servo that folds the intake out. The `atStart` line runs the action below at ▶. ```java title="Robot.java" // optional(): while "intake_deploy" is not in the robot configuration, the part is off (INIT goes on). (1)! // .part(...): which motor or servo it is (optional, recommended). intakeDeploy = add(Positioner.servo("intake_deploy").part("gobilda-2000-torque").optional()); intake = add(Intake.motor("intake").part("gobilda-5203-1150")); // At ▶: fold the intake out, then run it (the action is in Actions.java, below). (2)! atStart(() -> Actions.deployIntake(this)); ``` 1. The deploy servo is not on the robot yet. INIT shows a note and goes on (see **Why**, below). 2. With no deploy servo, the action skips the servo and the wait for it, and only starts the intake. **`Actions.java`**, inside `public class Actions { ... }`: the action. In your file the brackets say `(Robot r)`. ```java title="Actions.java" /** Folds the intake out with the deploy servo, then runs the intake. */ public static Action deployIntake(NotOnTheRobotYet r) { // in your Actions.java: (Robot r) return Action.named("Deploy intake") .then(() -> r.intakeDeploy.goTo("deployed")) .waitUntil("the deploy servo", r.intakeDeploy::isDone, 2.0) .then(r.intake::in, () -> r.intakeDeploy.goTo("stowed")); } ``` **`Controls.java`**, inside `buttons(...)`: the button, with `.needs(...)` at the end. ```java title="Controls.java" // needs(...): while the deploy servo is not on the robot, X does nothing and the // button map at INIT says "off: IntakeDeploy not on the robot". g2.x.press(Actions.deployIntake(robot)).says("deploy intake").needs(robot.intakeDeploy); ``` **Why:** teams build robots in steps. Without `optional()`, INIT stops when the part's device is not in the configuration (`No Servo named "intake_deploy" ...`). With it, INIT shows a note and goes on: `"intake_deploy" not in the configuration: IntakeDeploy is off (optional part)`. In the COMPETITION profile, the note is a warning at the top of the screen (`!! COMPETITION: ... IntakeDeploy is OFF ...`). So nobody plays a match without a part by mistake. Everything that uses the part skips it: - its commands - its buttons (the button map says `G2 X: deploy intake - off: IntakeDeploy not on the robot`) - the action steps (an autonomous keeps going, and its report says `skipped IntakeDeploy (not on the robot)`) When you wire the servo and add it to the configuration, it works, with no code to change. You need no `if (HAS_DEPLOY_SERVO)` switches. To try it in the simulator without the part, write `missing = intake_deploy` in the robot file. **More:** [Parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet). ## How do I add a launcher (flywheel and feeder)? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // A flywheel (in RPM) and the indexer that feeds it one piece at a time. // "launcher", "indexer" = names in the robot configuration. Numbers: Tunables.Launcher, .Indexer. // The motor's catalog id is in the brackets (needed). The indexer's .part(...) is optional, recommended. (1)! launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed"))); ``` 1. The launcher needs its motor's id for its speed control. The indexer's `.part(...)` is optional ([what it does](https://crossbotics.com/ftc-helper/docs/cookbook/01-the-basics/#words-you-will-meet)). ```java title="Tunables.java" public static class Launcher { // "launcher" in the configuration public static double speedRpm = DEFAULT; // shot speed without the table (60% of top) public static double stepRpm = DEFAULT; // speed change per D-pad press (100) public static double readyBandRpm = DEFAULT; // "at speed" = this close to the target (60) public static double idleRpm = 1500; // spins between shots: quicker first shot (0) public static double shotIntervalSec = DEFAULT; // least time between two pieces (0.25) // The hub's speed control: the defaults for the motor until the Flywheel Finder (INIT shows them). // Then write the Finder's numbers in their place. public static double kP = DEFAULT; // push per speed error (kF / 10) public static double kI = DEFAULT; // fix a steady error (kP / 10) public static double kD = DEFAULT; // brake changes (0) public static double kF = DEFAULT; // steady power for a speed (from the motor) // {inches to the goal, RPM}, blended between rows. Example rows: write the Shot Tuner's instead. public static double[][] speedByDistance = {{24, 2200}, {48, 2550}, {72, 2900}, {96, 3250}}; } ``` ```java title="Tunables.java" public static class Indexer { // "indexer" in the configuration public static double rest = MEASURE; // servo position, out of the way (Servo Finder) public static double push = MEASURE; // servo position, piece pushed (Servo Finder) public static double pushSec = DEFAULT; // time to push (0.25, or the servo's speed) public static double returnSec = DEFAULT; // time to come back (the same as pushSec) } ``` **Why:** the launcher feeds a piece only when the wheel is at speed, so every shot flies the same way. **More:** [Add a launcher](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/#robotjava-one-line), [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/). ## How do I feed with two wheels, one on each side? **Where:** `Robot.java`, inside `define()`. Add the intake before the launcher. ```java title="Robot.java" // Two CR servo wheels squeeze each piece into the flywheel. They face each other, so the // second spins the other way: alsoServoReversed. Numbers: Tunables.FeederLeft (power, feedSec). // feedWheelOutWith: the intake pushing out turns both wheels backward too. launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.crServo("feeder_left").alsoServoReversed("feeder_right").part("gobilda-2000-speed")) .feedWheelOutWith(intake)); ``` **Why:** two wheels that squeeze the piece push it in straight. One power (`Tunables.FeederLeft`) runs both, so they can never fight. When the intake pushes pieces out, the wheels turn backward, so a piece in the feeder comes out too. A shot always wins. **Test the direction first:** set `feedSec` to 2, fire with no piece, and watch both wheels pull in. Both pull out: add `.reversed()` to the feeder. One pulls out: use `.alsoServo(...)` in place of `.alsoServoReversed(...)`. **Stop on the shot:** `stopOnShot = true` in `Tunables.FeederLeft` stops both wheels when the flywheel sees the shot, so they do not push the next piece in behind. `feedSec` is then only the time limit. It is `boolean`, not `double`: ```java title="Tunables.java" public static class FeederLeft { // "feeder_left" in the configuration: it runs both wheels public static double power = DEFAULT; // wheel power (1) public static double feedSec = DEFAULT; // the most time the wheels run per shot (0.4) public static boolean stopOnShot = true; // stop when the flywheel sees the shot: true or false } ``` **More:** [Indexer](https://crossbotics.com/ftc-helper/docs/reference/parts/indexer/), [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/). ## How do I add a turret that follows the goal? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // The camera knows the goal of each alliance (BLUE first, then RED). camera = add(Camera.limelight("limelight").goal("BLUE SCORING", "RED SCORING")); // "turret" = the motor's name in the robot configuration. 5 motor turns per turret turn. // follows(camera): it follows the goal from ▶, but never past Tunables.Turret min and max. turret = add(Turret.motor("turret", "gobilda-5203-117").gearRatio(5).follows(camera)); ``` ```java title="Tunables.java" public static class Turret { // "turret" in the configuration public static double min = MEASURE; // furthest right, degrees (Motor Finder) public static double max = MEASURE; // furthest left, degrees: 0 = forward, + = left public static double startAngle = DEFAULT; // where you set it by hand before INIT (0) public static double kP = DEFAULT; // push per degree off (0.02) public static double kD = DEFAULT; // brake near the target (0.001) public static double maxPower = DEFAULT; // the most power (0.8) public static double tolerance = DEFAULT; // "aimed" within this, degrees (1.0) public static double cameraOffset = DEFAULT; // aims a little to one side: Aim Tuner (0) } ``` **Why:** the turret aims for the driver, and its limits keep the wires from twisting. **More:** [Add a turret: the turret](https://crossbotics.com/ftc-helper/docs/add-to-robot/06-turret/), [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/), [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/). ## How do I fire only when aimed, at the right speed? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // The speed comes from the distance to the goal (Tunables.Launcher.speedByDistance), // and a piece is only fed when the turret points at the goal. // .part(...): which servo it is (optional, recommended). launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .speedFromDistance(camera) .requireReady("turret aimed", () -> turret.isAimed())); ``` **Why:** a shot fired before the turret is on target, or at the wrong speed, is a lost piece. For a turret that follows the goal, `isAimed()` means on the goal NOW. When the camera loses the goal, it is false. **More:** [Add a camera](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/#robotjava-one-line). --- # Game pieces URL: https://crossbotics.com/ftc-helper/docs/cookbook/05-game-pieces/ A `Pieces` line in `Robot.java` counts the pieces the robot holds, and knows which kind fires next. It uses a sensor at the intake, and (optional) one at the "ready to fire" slot. Measure each kind's color (or size) with the Piece Tuner, and write it in `Tunables.java`. The full details: [Pieces and PieceSensor](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/). **The questions on this page:** - [How do I know which piece is in the robot, and how many?](#how-do-i-know-which-piece-is-in-the-robot-and-how-many) - [How do I stop the intake when the robot is full?](#how-do-i-stop-the-intake-when-the-robot-is-full) - [How do I tell pieces apart by size, or with a second camera?](#how-do-i-tell-pieces-apart-by-size-or-with-a-second-camera) - [How do I use the count (buzz, LEDs, the shot table)?](#how-do-i-use-the-count-buzz-leds-the-shot-table) - [How do I let the next piece pick the shot table?](#how-do-i-let-the-next-piece-pick-the-shot-table) - [How do I tune the piece sensors?](#how-do-i-tune-the-piece-sensors) ## How do I know which piece is in the robot, and how many? **Where:** `Robot.java`, inside `define()`. ```java title="Robot.java" // At the top of the class: public Pieces pieces; Here in define(), ABOVE the intake line. (1)! // The kinds of piece, a sensor where they come in, one at the "ready to fire" slot (optional). (2)! pieces = add(Pieces.kinds("POLLEN", "RED_NECTAR", "BLUE_NECTAR") .comingIn(PieceSensor.color("intake_color")) // a REV Color Sensor V3 .readyToFire(PieceSensor.color("ready_color")) // another one .max(4) // BIOBUZZ G407: no more than 4 .startsWith(4, "POLLEN")); // the 4 POLLEN preload ``` 1. Put it above the intake line. Then, in each loop, the count is up to date before the intake asks "full?". 2. BIOBUZZ has yellow POLLEN, and red and blue NECTAR. Then come the most pieces the rules allow (`max`) and the preload (`startsWith`). **Why:** each piece the intake sensor sees counts one in. Each feed of the indexer counts one out, the oldest first, once the piece has gone. A jammed feed counts nothing. Until you tune a kind with the Piece Tuner, it reads `"UNKNOWN"`. `robot.pieces.count()`, `robot.pieces.next()` ("POLLEN", "UNKNOWN" or "NONE") and `robot.pieces.isFull()` work anywhere in your code. **More:** [Pieces and PieceSensor](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/). ## How do I stop the intake when the robot is full? **Where:** `Robot.java`, inside `define()`. ```java title="Robot.java" // ADD .stopsWhen(...) to your intake line (no second intake line); the Pieces line goes above it. (1)! // .part(...): which motor it is (optional, recommended). intake = add(Intake.motor("intake").part("gobilda-5203-1150").stopsWhen(() -> pieces.isFull())); ``` 1. The intake then does not pull in a 5th piece. `() ->` means that the intake asks the test in every loop. Pushing out still works. ```java title="Robot.java" // Each feed counts one piece out. requireReady: no feed with nothing to fire. // .part(...): the indexer's servo (optional, recommended). launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .requireReady("a piece to fire", () -> !pieces.isEmpty())); ``` **Why:** BIOBUZZ rule G407 says that a robot may not control more than 4 pieces. The rules ask for "systems to prevent active pickup" of a 5th, and this is one. Put the intake sensor where the robot already holds a piece, so the intake does not stop with a piece half in. The count can be wrong (two pieces can read as one). So the drivers are responsible for G407, not the count. When the count says full and the robot is not, hold RT for 1 s to pull in anyway. The Driver Station warns when the intake is held back for more than 2 s. **More:** [Intake](https://crossbotics.com/ftc-helper/docs/reference/parts/intake/). ## How do I tell pieces apart by size, or with a second camera? **Where:** `Robot.java`, inside `define()`. ```java title="Robot.java" // A REV 2m Distance Sensor across the intake tells the sizes apart (not the colors). (1)! // A second webcam on the ready slot: colors. (2)! pieces = add(Pieces.kinds("POLLEN", "NECTAR") .comingIn(PieceSensor.distance("intake_distance")) .readyToFire(PieceSensor.camera("Webcam 2")) .max(4)); ``` 1. A NECTAR (3.6 in) comes closer to the sensor than a POLLEN (2.8 in). It sees size only, so it cannot tell a red NECTAR from a blue one. 2. The webcam reads the main color in a box of its picture. **Why:** a distance sensor reads 20 mm closer with a NECTAR than with a POLLEN, but it sees no color. Rule G408 forbids controlling the other alliance's NECTAR. A webcam sees colors from farther away, but it cannot tell how far the piece is. **More:** [the sensors compared](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/). ## How do I use the count (buzz, LEDs, the shot table)? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // A buzz on gamepad 2 when the robot holds the most it may. g2.rumbleWhen(robot.pieces::isFull); // Two buzzes when a NECTAR (red or blue) is next to fire. For one kind only: // robot.pieces.whenNextIs("RED_NECTAR"). g2.rumbleWhen(() -> robot.pieces.next().endsWith("NECTAR"), 2); // A light the drivers see: green = full, orange = empty (needs a Lights line in Robot.java, and // import com.crossbotics.ftchelper.robot.LightColor; at the top of this file). robot.lights.show(LightColor.GREEN).when(robot.pieces.whenFull()); robot.lights.show(LightColor.ORANGE).when(robot.pieces.whenEmpty()); // Pieces shows "3/4, next POLLEN" by itself; this adds what the intake sees now. show("At the intake", robot.pieces::atIntake); // The count went wrong? Hold G2's left stick button 1 s = count 0 (its line: below), // and hold the intake's RT 1 s to pull in although the count says full. ``` **Why:** `whenFull()`, `whenEmpty()` and `whenNextIs("POLLEN")` (one kind) are conditions that any part can watch: a buzz, a light (the [Lights](https://crossbotics.com/ftc-helper/docs/cookbook/14-lights/) recipes), or an action that waits. For "either NECTAR", the recipe asks `next()` (the next kind's name) whether it ends with `NECTAR`. When the count is wrong (for example, after you take pieces out by hand), a button sets it to 0. Add this line to `Controls.java`, inside `buttons(...)`. Then hold G2's left stick button for 1 s: ```java title="Controls.java" g2.leftStickButton.heldFor(1.0, robot.pieces::clear).says("piece count = 0"); ``` **More:** [hooks for other parts](https://crossbotics.com/ftc-helper/docs/reference/parts/pieces/). ## How do I let the next piece pick the shot table? **Where:** `Robot.java`, inside `define()`, on your launcher line (the Pieces line must be above it). Also two tables in your `Tunables.Launcher` section ([one table per piece](https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/#how-do-i-use-one-shot-table-per-game-piece)). ```java title="Robot.java" // In define(), BELOW the Pieces line: your launcher line with three more lines. The tables // are Tunables.Launcher.speedByDistancePollen and speedByDistanceNectar. launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .speedFromDistance(camera) .startTable("pollen") // before a piece is known .tableFrom(pieces.nextKind()) // the next piece picks the table .tableFor("nectar", "RED_NECTAR", "BLUE_NECTAR")); // both NECTAR colors use "nectar" ``` **Why:** POLLEN and NECTAR fly differently. With these lines, the drivers never switch tables by hand. Each time the next piece changes, the launcher uses that piece's table. A kind with the same name as a table needs no line (`POLLEN` uses `pollen`). `tableFor` puts both NECTAR colors on the `nectar` table. `NONE` and `UNKNOWN` (a kind not tuned yet) never change the table. `startTable` is the table before the robot knows the first piece. A button (D-pad right) can still pick another table until the next piece changes. **More:** [Launcher: shot tables](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/), [Add a launcher: the next piece picks the table](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/#know-which-piece-fires-next). ## How do I tune the piece sensors? **Where:** a new file next to `Robot.java`, `PieceTuner.java`. Below is the whole file. Its first line is `package org.firstinspires.ftc.teamcode;` (Android Studio writes it when you make the file), then: ```java title="PieceTuner.java" import com.crossbotics.ftchelper.finders.PieceTunerOpMode; import com.crossbotics.ftchelper.robot.RobotDefinition; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; // The Piece Tuner: each sensor's readings, and the numbers for Tunables.java. @TeleOp(name = "Cookbook Piece Tuner", group = "Finders") @Disabled // delete this line in your copy, or you will not see it public class PieceTuner extends PieceTunerOpMode { @Override protected RobotDefinition robot() { return new Robot(); // your Robot.java: the tuner finds its piece sensors } } ``` **Why:** each sensor and each robot reads colors a little differently. Hold each kind in front of the sensor and press A. Then copy the lines that the tuner shows into `Tunables.java`. **More:** [Piece Tuner](https://crossbotics.com/ftc-helper/docs/modules/finders/#piecetuneropmode). --- # Aiming and shooting URL: https://crossbotics.com/ftc-helper/docs/cookbook/06-aiming-and-shooting/ **The questions on this page:** - [How do I make the whole robot aim at the goal (no turret)?](#how-do-i-make-the-whole-robot-aim-at-the-goal-no-turret) - [How do I make the gamepad buzz when the aim is on target?](#how-do-i-make-the-gamepad-buzz-when-the-aim-is-on-target) - [How do I keep aiming when the camera loses the goal?](#how-do-i-keep-aiming-when-the-camera-loses-the-goal) - [How do I aim with the odometry only (no camera)?](#how-do-i-aim-with-the-odometry-only-no-camera) - [How do I make the camera work in any venue's light?](#how-do-i-make-the-camera-work-in-any-venues-light) - [How do I find game pieces with a HuskyLens?](#how-do-i-find-game-pieces-with-a-huskylens) - [How do I shoot while the robot is driving?](#how-do-i-shoot-while-the-robot-is-driving) - [How do I use one shot table per game piece?](#how-do-i-use-one-shot-table-per-game-piece) - [Every shot is a bit short today. How do I trim the speed (a low battery)?](#every-shot-is-a-bit-short-today-how-do-i-trim-the-speed-a-low-battery) - [How do I add a hood to my launcher?](#how-do-i-add-a-hood-to-my-launcher) ## How do I make the whole robot aim at the goal (no turret)? **Where:** `Controls.java`, inside `buttons(...)` (and `Tunables.java` for the numbers, below). The robot needs a camera with a [`goal(...)`](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/) (or odometry with a goal point). Do not use it with a turret that follows the goal. Turret-following and whole-robot aim are separate modes, so INIT stops with a message if both are there. ```java title="Controls.java" // Hold RB: the robot turns to face the goal by itself; the driver keeps forward and sideways. (1)! g1.rb.hold(robot.aimMode()::on, robot.aimMode()::off).says("hold: aim the robot at the goal"); // Or a toggle. Careful: while it is on, the robot turns by itself, even after you let go. (2)! // g1.rb.toggle(robot.aimMode()).says("aim the robot at the goal on/off").rumble(); ``` 1. When you let go, the aim is off, and the driver turns again. To turn by hand while you hold RB, move the turn stick. Do not use it with a turret that follows the goal: these are separate modes (INIT stops with a message). 2. A press switches it on, and the next press switches it off. Two buzzes = on. **Why:** the driver drives, and the robot keeps itself pointed at the goal. Start with hold-to-aim. When you let go, the robot stops turning by itself, so it never surprises anyone. The stick always wins, so the driver can take over at once. The toggle (commented out) keeps aiming after you let go. **More:** [Add a camera: aim the whole robot](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/#controlsjava-its-buttons). ## How do I make the gamepad buzz when the aim is on target? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Gamepad 2 buzzes while the aim is close: the closer, the stronger (Tunables.Aim.rumbleDeg). // It works for a turret that follows the goal and for whole-robot aim. g2.rumbleWhenAimed(); ``` **Why:** the driver who fires watches the field, not the screen. The buzz tells the driver "now". **More:** [Add a camera: feel the aim](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/#controlsjava-its-buttons). ## How do I keep aiming when the camera loses the goal? **Where:** `Robot.java`, inside `define()`, and the goal's place in `Tunables.java`. ```java title="Robot.java" // With an odometry line and Tunables.Aim goalX, goalY, the turret and the speed keep // working when the camera loses the goal: from where the robot is on the field. odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); camera = add(Camera.limelight("limelight").goal("BLUE SCORING", "RED SCORING")); turret = add(Turret.motor("turret", "gobilda-5203-117").gearRatio(5).follows(camera)); // .part(...): the indexer's servo (optional, recommended). launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .speedFromDistance(camera) .startTable("pollen")); // the table to start with ``` ```java title="Tunables.java" /** Aiming (every line is optional; leave out what you do not use). */ public static class Aim { // a fixed name: always Aim // The goal on the field, in inches, seen from your drivers' wall (the same numbers as driveTo). (1)! public static double goalX = 13; // inches right of center (BIOBUZZ) public static double goalY = -13; // inches from center, - = our half (BIOBUZZ) public static boolean mirrorForRed = false; // BIOBUZZ: turned, not mirrored (true) public static double turnKp = DEFAULT; // whole-robot aim: push per degree off (0.02) public static double turnKd = DEFAULT; // brake near the goal (0.002) public static double maxTurnPower = DEFAULT; // the most it turns by itself (0.5) public static double toleranceDeg = DEFAULT; // "aimed" within this, degrees (2) public static double aimDriveSpeed = DEFAULT; // aim mode on: forward and strafe at this share (0.5) public static double rumbleDeg = DEFAULT; // rumbleWhenAimed(): buzz within this (4) public static boolean aimOnFire = false; // no turret: a fire press turns to the goal first (2)! } ``` 1. With odometry, the aim goes on when the camera loses the goal. In BIOBUZZ, the goal is your HIVE's CELL that is up at the start, 13 in right of the center line and 13 in toward you. 2. Quick turn on fire, for a robot with no turret: with aim mode off and the goal in view, RB turns the robot to the goal, then fires (at most 0.5 s later: `aimOnFireSec`). It is off unless you set it to `true`, because it turns the robot. **Why:** a robot or a game piece can block a tag, but the odometry still knows where the goal is. The Driver Station says which one aims (`following: camera` or `following: odometry`). The backup needs the pose (the robot's position and heading) from autonomous, or from [set pose here](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-set-the-pose-when-autonomous-did-not-run). Without it, the backup stays off, and the Driver Station says so. You write `goalX`, `goalY` from your own drivers' wall, like every field number in your code. Only the simulator's map and its scenario checks use the red wall. `mirrorForRed` is ONE setting for the whole robot (the routes, the start and reset spots, this goal point). The library takes the first one it finds of `Tunables.Aim.mirrorForRed`, `Tunables.Odometry.mirrorForRed` and your autonomous's `mirrorForRed()`. If it finds none, it uses `true` (a mirrored field). BIOBUZZ's turned field needs `false`: write it once, here. INIT shows the alliance and this choice. The numbers in `Tunables.Aim` are in the tuning menu too, so copy tuned values back into `Tunables.java`. **More:** [Add a camera: when the camera loses the goal](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/#when-the-camera-loses-the-goal-the-odometry), [Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/). ## How do I aim with the odometry only (no camera)? **Where:** `Robot.java`, inside `define()` (the odometry, turret and launcher lines), and a section `Aim` in `Tunables.java`. ```java title="Robot.java" // No camera: the odometry says where the robot is, Tunables.Aim where the goal is. The // turret follows that direction and the launcher's speed comes from that distance. odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); turret = add(Turret.motor("turret", "gobilda-5203-117").gearRatio(5).followsOdometry()); // .part(...): the indexer's servo (optional, recommended). launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .speedFromOdometry() .requireReady("turret aimed", () -> turret.isAimed())); ``` ```java title="Tunables.java" public static class Aim { // a fixed name: always Aim // Where the goal is, seen from YOUR drivers' wall (inches; the same numbers as driveTo). // BIOBUZZ: your HIVE's CELL that is up at the start. public static double goalX = 13; // inches right of center (BIOBUZZ) public static double goalY = -13; // inches from center, - = our half (BIOBUZZ) public static boolean mirrorForRed = false; // BIOBUZZ's field is turned, not mirrored } ``` **Why:** you have no camera to buy, mount or tune. But the aim is only as good as the pose. It needs the start spot from autonomous (or [set pose here](https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/#how-do-i-set-the-pose-when-autonomous-did-not-run)). A bump that slips the wheels moves the aim off a little. When you have a camera too, use [the camera first, the odometry as backup](#how-do-i-keep-aiming-when-the-camera-loses-the-goal). The library takes it that the turret turns about the robot's center. Whole-robot aim (no turret) works from the odometry in the same way. **More:** [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/), [Turret](https://crossbotics.com/ftc-helper/docs/reference/parts/turret/). ## How do I make the camera work in any venue's light? **Where:** `Robot.java`, inside `define()`: the camera line. ```java title="Robot.java" // In INIT the Limelight tries these pipelines (your usual one FIRST) and keeps the best one. (1)! camera = add(Camera.limelight("limelight").autoPipelines(0, 1, 2).goal("BLUE SCORING", "RED SCORING")); // A webcam: Camera.webcam("Webcam 1").autoExposure().goal(...) tries the camera's own // exposure, then 3, 6 and 12 ms. ``` 1. Each venue's lights are different. Set up each pipeline on the Limelight's web page for one kind of light. The Limelight keeps the pipeline that sees the most AprilTags, and the Driver Station says which one. **Why:** bright stage lights or a dark corner can make a camera miss the AprilTags it saw in your shop. The test runs in INIT (nothing moves) and takes about a second per setting. The Driver Station says which setting it kept. Point the robot at the tags in INIT. Its numbers are optional. In `Tunables.Limelight`, `autoLighting = false` skips the test and uses `pipeline`. **For a camera tilted up:** add its tilt to the same section: `public static double pitchDeg = 35;` (degrees up, measured on the robot). Then a goal off to the side reads the right angle, and distances are along the floor. **More:** [Vision: venue lighting](https://crossbotics.com/ftc-helper/docs/modules/vision/#venue-lighting), [CameraTilt](https://crossbotics.com/ftc-helper/docs/modules/vision/#cameratilt), [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/). ## How do I find game pieces with a HuskyLens? **Where:** `Robot.java`, inside `define()`. First teach the camera, on the camera itself: dial to Color Recognition, turn on Learn Multiple, point the `+` at a piece, and press the learning button. ```java title="Robot.java" // At the top of the class: public Camera pieceCamera; Colors you taught it: ID1, ID2. (1)! pieceCamera = add(Camera.huskyLens("huskylens").colors().label(1, "POLLEN").label(2, "NECTAR")); // Or AprilTags: list which real tag each taught number is, and add goal(...). (2)! // camera = add(Camera.huskyLens("huskylens").tag(1, 34).tag(2, 35).goal("BLUE SCORING", "RED SCORING")); ``` 1. A HuskyLens does one job at a time: colors or tags, not both. 2. It says the number you taught it, never the tag's real number. **Why:** the camera finds the piece itself, so the hub does no picture work. Then `pieceCamera.target("POLLEN")` gives the bearing to the nearest box, or null. In `Tunables`, set `hfovDeg` (the camera's side-to-side view angle: measure it). For a rough distance, also set `sizeIn` (the longest side of the piece it sees). Nobody has tested it on a real robot yet. **More:** [HuskyLensCamera](https://crossbotics.com/ftc-helper/docs/modules/vision/#huskylenscamera), [Camera](https://crossbotics.com/ftc-helper/docs/reference/parts/camera/). ## How do I shoot while the robot is driving? **Where:** `Tunables.java` (the numbers, in your `Aim` section), and a button in `Controls.java` (inside `buttons(...)`) to switch it on and off. The robot needs [odometry](https://crossbotics.com/ftc-helper/docs/reference/parts/odometry/), because the odometry gives the robot's speed. **It stays off until you tune it on the real robot** (`shootOnMove = false`). Measure `flightSec` with a slow-motion video, and test shots while driving. Only then write `true`. ```java title="Tunables.java" // ADD these lines to your Tunables.Aim section (keep goalX, goalY and the others). public static boolean shootOnMove = false; // true only after testing on the real robot public static double flightSec = MEASURE; // seconds in the air (slow-motion video) (1)! public static double flightSecPerIn = DEFAULT; // longer shots fly longer: per inch (0) public static double maxLeadIn = DEFAULT; // never lead more than this, inches (24) // Where the shooter (a turret's pivot) and a camera on the body are from the robot's center. (2)! public static double shooterForwardIn = MEASURE; // inches forward of the center (from the edges) public static double shooterLeftIn = MEASURE; // inches left of the center (from the edges) public static double cameraForwardIn = MEASURE; // inches forward of the center (from the edges) public static double cameraLeftIn = MEASURE; // inches left of the center (from the edges) ``` 1. Film a shot in slow motion. Count the frames from when the piece leaves the launcher to when it reaches the goal. Divide by the video's frames per second. 2. In inches: forward (+) and left (+). Measure from the robot's edges, not its middle: forward = length / 2 - (from the front edge), left = width / 2 - (from the left edge). A camera on the turret sits at the turret's pivot. Then a button, in `Controls.java` inside `buttons(...)`: ```java title="Controls.java" // Shooting on the move on/off (on from ▶ when Tunables.Aim.shootOnMove = true): if // the shots go wide while driving, switch it off and shoot standing still. g2.a.toggle(robot.aim().movingShotMode()).says("shoot on the move on/off").rumble(); ``` **Why:** a piece shot from a moving robot keeps the robot's speed, so it lands to the side (30 in/s for 0.8 s: 24 in). With `shootOnMove`, the turret (or the whole robot) aims at a point that far the other way. The launcher takes its speed from that point's distance. It also brings the camera's picture forward to now, because the robot turned and moved since the camera took it. It works with a turret or whole-robot aim, with a camera on the turret or on the body, or with the odometry alone. Tell it where the shooter and the camera are. The Driver Station says `Aim : moving shot: lead 12.3 deg, 18 in` while it leads. **More:** [Add a camera: shooting while moving](https://crossbotics.com/ftc-helper/docs/add-to-robot/07-camera/#shooting-while-moving), [Aim](https://crossbotics.com/ftc-helper/docs/reference/parts/aim/). ## How do I use one shot table per game piece? **Where:** `Tunables.java` (the tables, in your `Launcher` section), then `Controls.java` (inside `buttons(...)`) or `Actions.java` (inside the class) to switch. ```java title="Tunables.java" // IN PLACE OF the speedByDistance line: one table per game piece, {inches to the goal, RPM}. (1)! // The POLLEN table (example rows: write the Shot Tuner's). public static double[][] speedByDistancePollen = {{24, 2200}, {48, 2550}, {72, 2900}}; // The NECTAR table. public static double[][] speedByDistanceNectar = {{24, 2400}, {48, 2800}, {72, 3200}}; ``` 1. Write this in your `Tunables.Launcher` section. The name after `speedByDistance` is the table's name: `"pollen"` and `"nectar"`. Fill both from the Shot Tuner. ```java title="Controls.java" // One button per game piece (the launcher's D-pad right already picks the next table). g2.x.press(() -> robot.launcher.useTable("pollen")).says("POLLEN shot table"); g2.b.press(() -> robot.launcher.useTable("nectar")).says("NECTAR shot table"); ``` ```java title="Actions.java" /** An action that picks the NECTAR table, then fires one (Actions.java). */ public static Action fireNectar(Robot r) { return Action.named("Fire NECTAR") .then(() -> r.launcher.useTable("nectar")) .then(r.launcher::fire); } ``` **Why:** POLLEN (2.8 in) and NECTAR (3.6 in) fly differently, so each needs its own speeds. **The table at ▶:** a plain `speedByDistance` table (named `main`) if there is one. If not, the first by name: here `nectar` (n before p). To start on POLLEN, add `.startTable("pollen")` to the launcher line in `Robot.java` ([like here](#how-do-i-keep-aiming-when-the-camera-loses-the-goal)). The Driver Station's `Shot table` line says which one is in use. Fill each table with the [Shot Tuner](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/) ([its file](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-build-a-shot-table-speed-for-each-distance)). Press Y until `> Table`, then pick the table you tune with the D-pad. Then copy its line into `Tunables.java`. To let the robot pick the table by itself, see [the next piece picks it](https://crossbotics.com/ftc-helper/docs/cookbook/05-game-pieces/#how-do-i-let-the-next-piece-pick-the-shot-table). **More:** [Add a launcher: two shot tables](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/#two-kinds-of-pieces-two-shot-tables), [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/). ## Every shot is a bit short today. How do I trim the speed (a low battery)? **Where:** the D-pad trim is the launcher's usual line in `Controls.java`: `robot.launcher.speedOn(g2.dpadUp, g2.dpadDown);` ([Buttons to add](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#buttons-to-add)). The numbers go in your `Tunables.Launcher` section. Your own buttons go in `Controls.java`, inside `buttons(...)`. ```java title="Tunables.java" // In your Tunables.Launcher section (change the lines you already have, add the others). public static double kP = MEASURE; // speed control (Flywheel Finder) public static double kI = MEASURE; // speed control (Flywheel Finder) public static double kD = DEFAULT; // speed control (0) public static double kF = MEASURE; // steady power (Flywheel Finder) public static double nominalVolts = MEASURE; // battery volts for kF (Flywheel Finder) public static double trimStepPercent = DEFAULT; // one D-pad press (1%) public static double trimMaxPercent = DEFAULT; // never more than this each way (15%) // Battery compensation: true = F follows the battery. Try it on a real robot and tell us. public static boolean batteryCompensation = false; // (off until proven on a real robot) ``` ```java title="Controls.java" // The launcher's usual line trims too: speedOn(g2.dpadUp, g2.dpadDown) = +/- 1% a press. // Your own: a bigger step on a button, and a far shot that sets the trim first. g2.y.press(() -> robot.launcher.trimBy(+3)).says("speed trim +3%"); g2.a.press(Action.named("Far shot +5%") .then(() -> robot.launcher.setTrim(+5), robot.launcher::fire) // The launcher fires or gives up within 3 s, so 4 s is always enough. .waitUntil("fired", () -> !robot.launcher.isShooting(), 4.0) .then(robot.launcher::resetTrim)); // Last match's trim (INIT offers it as "Trim last time"): from your own button too. g2.x.press(robot.launcher::useLastTrim).says("use last match's trim"); ``` 1. Hold the D-pad for 4 steps a second. Double-tap D-pad down to go back to 0. The launcher's first line on the Driver Station shows the trim: `Speed trim : +3% READY`. **Why:** a worn wheel or softer balls make every shot a little short. The trim fixes it for this match, for every table. It moves +/- 1% a press, at most 15%, and never past the motor's top speed. It goes back to 0 at every INIT. At INIT, the Driver Station offers last time's trim (`Trim last time : +3%`). To use it, double-tap D-pad up after ▶ (or use your own button: `useLastTrim`, in the recipe). The library never applies it by itself. Battery compensation scales the F gain by `nominalVolts` / the battery (tuned at 12.6 V, at 11.5 V: F x 1.10). Nobody has proven it on a real robot yet, so it is off: the box writes `batteryCompensation = false`. Change it to `true` only when you want to test it. It needs the `kF` and `nominalVolts` that the Flywheel Finder found together. That is why the box writes the gains as `MEASURE`. Without battery compensation, `DEFAULT` gains (from the motor) are a good start. When you need a trim every match, with a charged battery, the cause is the wheel or the balls, not the battery. The table is off. Make the trim part of the table (+3%: every speed x 1.03, `{48, 2550}` becomes `{48, 2627}`). Copy the lines into `Tunables.java`, and trim back to 0. **More:** [Add a launcher: speed trim and a low battery](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/#speed-trim-and-a-low-battery), [Launcher](https://crossbotics.com/ftc-helper/docs/reference/parts/launcher/#speed-trim-and-battery-compensation). ## How do I add a hood to my launcher? **Where:** `Robot.java`, inside `define()`: add `.hood(...)` to your launcher line. In `Tunables.java`, add a new section `Hood` (its stops), and a third number in each row of your `Launcher` section's shot table. ```java title="Robot.java" // The hood goes on the launcher; its numbers are in Tunables.Hood. // .part(...): which servos they are (optional, recommended). launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .feeder(Indexer.servo("indexer").part("gobilda-2000-speed")) .hood(Hood.servo("hood").part("gobilda-2000-torque")) .speedFromDistance(camera)); ``` A new section in `Tunables.java`: ```java title="Tunables.java" public static class Hood { // "hood" in the configuration // posA and posB: the servo positions a hair off the hood's two hard stops. Never past them. public static double posA = MEASURE; // servo position at stop A (Hood Finder) public static double posB = MEASURE; // servo position at stop B (Hood Finder) // Optional: the hood's angle at each stop (any scale, e.g. 0 = steep end, 30 = flat end). public static double angleA = MEASURE; // the angle at stop A (an angle app) public static double angleB = MEASURE; // the angle at stop B (an angle app) public static double travelSec = DEFAULT; // stop to stop, seconds (0.5, or the servo's) public static double startAngle = DEFAULT; // where it goes at ▶ (angle A) } ``` Then the shot table: ```java title="Tunables.java" // IN PLACE OF your speedByDistance line: {inches to the goal, RPM, hood angle}, blended between rows. (1)! public static double[][] speedByDistance = {{24, 2200, 3}, {48, 2550, 12}, {72, 2900, 20}}; ``` 1. This goes in your `Tunables.Launcher` section. The launcher blends the hood angle between rows, like the speed. **With no measured angles:** leave out `angleA`, `angleB`. The hood then works in servo positions, and the table's third number is a servo position. ```java title="Tunables.java" // Tunables.Hood: only posA and posB (delete angleA, angleB). Tunables.Launcher, IN PLACE OF // your speedByDistance line, {inches, RPM, servo position}: the Shot Tuner writes these for you. public static double[][] speedByDistance = {{24, 2200, 0.24}, {48, 2550, 0.38}, {72, 2900, 0.50}}; ``` **A hood on a linkage or cam:** equal servo steps do not make equal angles. Use this `Hood` section in place of the one above. It has a calibration table instead of `posA`, `posB`, `angleA`, `angleB`. ```java title="Tunables.java" public static class Hood { // "hood" in the configuration // {servo position, hood angle} rows, blended. The first and last rows are the stops (no posA / posB). (1)! // Example rows: write the Hood Finder's in their place. public static double[][] calibration = {{0.20, 0}, {0.32, 8}, {0.45, 18}, {0.65, 30}}; } ``` 1. The angles must keep going one way: in servo-position order, the angles all go up, or all go down. **A hood on a motor with an encoder** (it knows where it is): write `Hood.motor` in the launcher line, and use this `Hood` section in place of the one above. ```java title="Robot.java" add(Launcher.flywheel("launcher", "gobilda-5203-6000") .hood(Hood.motor("hood", "gobilda-5203-117")) // a motor with an encoder .speedFromDistance(camera)); ``` ```java title="Tunables.java" public static class Hood { // "hood" in the configuration // Encoder ticks at the two stops, counted from where the hood sits at INIT (start the robot // with the hood on stop A), and the angles there. public static double posA = MEASURE; // ticks at stop A, usually 0 (Hood Finder) public static double posB = MEASURE; // ticks at stop B (Hood Finder) public static double angleA = MEASURE; // the angle at stop A (an angle app) public static double angleB = MEASURE; // the angle at stop B (an angle app) public static double kP = DEFAULT; // power per tick off (0.005) public static double maxPower = DEFAULT; // the most power (0.5) public static double tolerance = DEFAULT; // ready within this (1/50 of the range) } ``` Your own hood buttons, in `Controls.java` inside `buttons(...)`: ```java title="Controls.java" // The launcher's hood already has gamepad 2's left stick Y (up = a bigger angle): a trim // while the table sets the angle, else the angle itself. Your own: steps and the start angle. g2.y.press(() -> robot.launcher.hood().step(+1)).says("hood +1 step"); g2.a.press(() -> robot.launcher.hood().step(-1)).says("hood -1 step"); g2.x.press(() -> robot.launcher.hood().goToStart()).says("hood to its start angle"); ``` **Why:** close shots need a steep angle, and far ones a flatter one. So each distance gets a speed AND a hood angle, blended between rows. `posA`, `posB` are hard limits: nothing sends the hood past a stop. The launcher waits for the hood before it fires. For a servo hood, it waits a share of `travelSec`. For a motor hood, it reads the encoder. While the camera sees a goal, the table sets the angle, and the stick (gamepad 2 left Y) is a hood trim. With no goal seen, the stick moves the hood itself, so you always see what it does. Double-tap D-pad down to clear both trims. A lift brings the same stick (gamepad 2 left Y). With a hood AND a lift, give one of them another stick ([move a button](https://crossbotics.com/ftc-helper/docs/cookbook/03-buttons/#how-do-i-move-a-parts-button-to-another-button)). INIT says which part has it. Find the stops with the [Hood Finder](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-find-my-hoods-stops-and-angles), then fill the table with the [Shot Tuner](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-build-a-shot-table-speed-for-each-distance) (press Y until `> Hood`). **More:** [Add a launcher: a hood](https://crossbotics.com/ftc-helper/docs/add-to-robot/05-launcher/#a-hood-the-shot-angle), [Hood](https://crossbotics.com/ftc-helper/docs/reference/parts/hood/). --- # Turrets and interlocks URL: https://crossbotics.com/ftc-helper/docs/cookbook/07-turrets-and-interlocks/ Every kind of turret has its own lines: motor, servo or CR servo, with a switch or not, with any range. See [Setting up a turret](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/). An interlock is a rule that stops two parts from hitting each other. Code: [`InterlockRecipes.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/cookbook/InterlockRecipes.java). **The questions on this page:** - [How do I home my turret with a switch?](#how-do-i-home-my-turret-with-a-switch) - [How do I set up a turret on a servo?](#how-do-i-set-up-a-turret-on-a-servo) - [How do I set up a slip-ring turret (round and round)?](#how-do-i-set-up-a-slip-ring-turret-round-and-round) - [How do I stop two parts from hitting each other?](#how-do-i-stop-two-parts-from-hitting-each-other) - [How do I pick up and score with a lift, a wrist and a claw?](#how-do-i-pick-up-and-score-with-a-lift-a-wrist-and-a-claw) ## How do I home my turret with a switch? **Where:** `Robot.java`, inside `define()` (the turret line), and a section `Turret` in `Tunables.java`. ```java title="Robot.java" // "turret", "turret_home" = the motor's and the home switch's names in the robot configuration. (1)! // At ▶ the turret turns slowly until it finds the switch. (2)! turret = add(Turret.motor("turret", "gobilda-5203-312").gearRatio(2.75) .homeSwitch("turret_home") .follows(camera)); ``` 1. The home switch is a touch sensor ("REV Touch Sensor" in the configuration) or a magnetic switch ("Digital Device", for example the REV Magnetic Limit Switch). 2. After that, each time the turret passes the switch, the switch sets its angle right again. ```java title="Tunables.java" public static class Turret { // "turret" in the configuration public static double min = MEASURE; // furthest right, degrees (Motor Finder) public static double max = MEASURE; // furthest left, degrees: 0 = forward, + = left public static double homeAngle = MEASURE; // where the switch closes (turret-setup.md) public static double homingPower = DEFAULT; // how slowly it looks for the switch (0.2) public static double homingTimeout = DEFAULT; // the most seconds it looks (5) } ``` **Why:** a motor's encoder counts from where the turret was at INIT. With a switch, the turret finds its real angle at ▶ by itself. It never does this during INIT, because nothing moves before ▶. Every time the turret passes the switch, the switch fixes the error from a slipping belt. Until the turret is homed (has found its real angle), it does not follow the goal and is never "aimed". You must write `homeAngle`, or INIT stops. `min`, `max` default to -90 and 90. With no switch, put the turret at `startAngle` (default 0, straight forward) by hand before INIT. **More:** [Setting up a turret: how it knows its angle](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/#2-how-does-it-know-its-angle). ## How do I set up a turret on a servo? **Where:** `Robot.java`, inside `define()` (the turret line), and a section `Turret` in `Tunables.java`. ```java title="Robot.java" // "turret" = the servo's name in the robot configuration. Numbers: Tunables.Turret. (1)! // fullRange(): the servo's whole turn. Turn it on BEFORE you measure posA and posB. (2)! turret = add(Turret.servo("turret").part("gobilda-2000-speed").fullRange().follows(camera)); ``` 1. A standard servo turns the turret to an angle by itself. It needs no encoder, no PID and no homing. 2. With it, a goBILDA 2000 servo turns 300 degrees, not 270. Find posA and posB with the Servo Finder: press Y while you choose the servo. ```java title="Tunables.java" public static class Turret { // "turret" in the configuration // Two servo positions and the turret's angle at each: 0 = straight forward, counterclockwise // (left) +. Its range is between the two angles. public static double posA = MEASURE; // servo position at one end (Servo Finder) public static double angleA = MEASURE; // the turret's angle there (an angle app) public static double posB = MEASURE; // servo position, other end (Servo Finder) public static double angleB = MEASURE; // the turret's angle there (an angle app) public static double travelSec = DEFAULT; // posA to posB, seconds (0.6, or the servo's) public static double startAngle = DEFAULT; // sent here at ▶ (0) } ``` **Why:** a servo knows how to go to a position, so the turret needs no encoder, no PID and no homing. It is the cheapest turret. But a servo cannot say where it is. So at ▶, the library sends it to `startAngle` (or the middle of its range), and "aimed" waits `travelSec` for it. You must write `posA`, `angleA`, `posB`, `angleB`, or INIT stops. Find the positions with the [Servo Finder](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-find-a-servos-open-and-closed-numbers), and measure the angle at each with a phone angle app. Its range is between `angleA` and `angleB`. Put hard stops a little past them. **More:** [Setting up a turret](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/#1-what-turns-it), [Full range](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-get-my-servos-full-range). ## How do I set up a slip-ring turret (round and round)? **Where:** `Robot.java`, inside `define()` (the turret line), and a section `Turret` in `Tunables.java`. ```java title="Robot.java" // A CR servo turns it, an absolute encoder says where it points, continuous(): no limits. (1)! // "turret", "turret_pos" = the servo's and the encoder's names in the robot configuration. // .part(...): which servo it is (optional, recommended). turret = add(Turret.crServo("turret").part("axon-max-mk2").analogEncoder("turret_pos").continuous() .follows(camera)); ``` 1. The encoder is on an analog port and knows the angle at once, so the turret needs no homing. A slip ring (a turning joint that carries the wires) lets the turret turn with no limits. With no limits, the turret always takes the shortest way. ```java title="Tunables.java" public static class Turret { // "turret" in the configuration // No min and max: it turns round and round. public static double kP = 0.015; // push per degree off, CR servo (0.02) public static double kD = DEFAULT; // brake near the target (0.001) public static double maxPower = 1.0; // a CR servo's full speed (0.8) public static double tolerance = DEFAULT; // "aimed" within this, degrees (1.0) public static double encoderOffset = MEASURE; // encoder reading, pointing forward } ``` **Why:** with a slip ring, the wires never wind up. So the turret can always take the shortest way to the goal, and is never "out of range". A motor turret can be `continuous()` too. **More:** [Setting up a turret: how far can it turn?](https://crossbotics.com/ftc-helper/docs/guides/turret-setup/#3-how-far-can-it-turn). ## How do I stop two parts from hitting each other? **Where:** `Robot.java`, inside `define()`, one line below the parts' `add` lines. Also a new section in `Tunables.java` for the zones, with the same name as the rule. ```java title="Robot.java" // AFTER the parts' add lines: the turret stays out of its zone while the lift is in its // zone, and the other way round. Whoever is in its zone first keeps it. keepApart("TurretLift", turret.zone(), lift.zoneAbove()); ``` ```java title="Tunables.java" // The rule's own section, named like the rule in Robot.java. Each zone in its part's units. public static class TurretLift { // keepApart("TurretLift", ...) in Robot.java public static double turretFrom = MEASURE; // degrees: where the turret's zone starts public static double turretTo = MEASURE; // degrees: where it ends (robot's back) public static double liftAbove = MEASURE; // counts: the slide is up from here public static double liftStopSec = 0.2; // a heavy slide takes longer to stop (0.15) } ``` **Why:** each part is safe inside its own limits, but a turret over the back and a lift at the back can still meet. The library keeps the rule every loop, whatever moves the parts: buttons, sticks, actions, a following turret or autonomous steps. The part that is in its zone first keeps it. The other part waits at the edge of its own zone, and the Driver Station says so (`TurretLift : Lift held at 216 counts: Turret is between 130 and 218 deg`). The rule slows a fast part down as it comes near, so it brakes in time, even with slow loops. To do this, the rule measures the part's speed every loop. The library reads the zones at INIT only, so change them in `Tunables.java`. **More:** [Two parts that must not collide](https://crossbotics.com/ftc-helper/docs/guides/interlocks/), [Interlock](https://crossbotics.com/ftc-helper/docs/reference/parts/interlock/). ## How do I pick up and score with a lift, a wrist and a claw? **Where:** `Actions.java`, inside the class; then a button in `Controls.java`, inside `buttons(...)`: `g2.y.press(Actions.scoreInFlower(robot)).says("score in a FLOWER");` ```java title="Actions.java" /** Lifts a held ball over a FLOWER, lets it go and comes back folded (Actions.java). */ public static Action scoreInFlower(Robot r) { return Action.named("Score in FLOWER") .then(() -> r.wrist.goTo("carry")) // 1. swing the claw out first .waitUntil("wrist out", r.wrist::isDone, 1.0) .then(() -> r.lift.goTo("flower")) // 2. lift (the interlock may make it wait) .waitUntil("lift up", r.lift::isAtTarget, 4.0) .then(() -> r.wrist.goTo("flower")) // 3. tip it over the FLOWER .waitUntil("over the FLOWER", r.wrist::isDone, 1.0) .then(r.claw::open) // 4. let go .waitUntil("let go", r.claw::isDone, 1.0) .then(() -> r.wrist.goTo("carry")) // 5. back the same way .waitUntil("wrist back", r.wrist::isDone, 1.0) .then(() -> r.lift.goTo("stowed")) .waitUntil("lift down", r.lift::isAtTarget, 3.0) .then(() -> r.wrist.goTo("folded"), r.claw::close); } ``` **Why:** the order keeps the parts out of each other's way. The claw swings out before the lift rises, and folds only after the lift is down. Each wait has a time limit, so a stuck part ends the action instead of stopping the robot. With an interlock rule, the lift waits by itself while the turret is in the way. **More:** the whole robot: [`v2bot`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/v2bot/Actions.java). --- # Actions URL: https://crossbotics.com/ftc-helper/docs/cookbook/08-actions/ **The questions on this page:** - [How do I do several things one after the other?](#how-do-i-do-several-things-one-after-the-other) - [How do I repeat steps several times?](#how-do-i-repeat-steps-several-times) - [How do I move two parts at the same time?](#how-do-i-move-two-parts-at-the-same-time) - [How do I wait half a second (like sleep in Blocks)?](#how-do-i-wait-half-a-second-like-sleep-in-blocks) - [How do I wait until something is true?](#how-do-i-wait-until-something-is-true) - [How do I start an action from a button?](#how-do-i-start-an-action-from-a-button) - [How do I stop every running action?](#how-do-i-stop-every-running-action) - [How do I run an action when the OpMode starts?](#how-do-i-run-an-action-when-the-opmode-starts) - [How do I use the same action in an autonomous?](#how-do-i-use-the-same-action-in-an-autonomous) ## How do I do several things one after the other? **Where:** `Actions.java`, inside the class. ```java title="Actions.java" /** Lift up, open the claw, lift down: one step after the other. */ public static Action scoreHigh(Robot r) { return Action.named("Score high") .then(() -> r.lift.goTo("high")) .waitUntil("lift at the top", r.lift::isAtTarget, 2.0) // at most 2 s .then(r.claw::open) .waitSeconds(0.3) // let the piece drop .then(() -> r.lift.goTo("down")); } ``` **Why:** each step starts when the one before it is done, and the driver can still drive the whole time. **More:** [Actions.java: scoreHigh](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/#your-first-action), [Action](https://crossbotics.com/ftc-helper/docs/reference/steps/#action). ## How do I repeat steps several times? **Where:** `Actions.java`, inside the class. ```java title="Actions.java" /** Pulses the intake 3 times: the for loop adds the same steps 3 times to the action. */ public static Action pulseThree(Robot r) { Action a = Action.named("Pulse three"); for (int i = 0; i < 3; i++) { // runs once, when the action is made: it never waits a.then(r.intake::in) .waitSeconds(0.4) .then(r.intake::stop) .waitSeconds(0.3); } return a; } ``` **Why:** the `for` loop runs once, while Java makes the action, and writes the steps 3 times. Then the action does them one after the other, and the robot does not wait. **More:** [Action](https://crossbotics.com/ftc-helper/docs/reference/steps/#action). ## How do I move two parts at the same time? **Where:** `Actions.java`, inside the class. ```java title="Actions.java" /** Two parts at once: then(a, b) starts both in the same loop. */ public static Action grabAndLift(Robot r) { return Action.named("Grab and lift") .then(r.claw::close, r.intake::stop) // both at once .waitUntil("claw closed", r.claw::isDone, 1.0) // isDone: it should be there .then(() -> r.lift.goTo("low")); } ``` **Why:** `then(a, b)` starts both parts in the same loop, so neither waits for the other. **More:** [Actions.java: grabAndLift](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/#the-steps). ## How do I wait half a second (like sleep in Blocks)? Search words: sleep, wait, pause, delay. **In an action** (`Actions.java`): ```java title="Actions.java" /** Opens the claw, waits half a second, then lowers the lift. */ public static Action dropAndLower(Robot r) { return Action.named("Drop and lower") .then(r.claw::open) .waitSeconds(0.5) // half a second; the robot keeps running .then(() -> r.lift.goTo("down")); } ``` **In an autonomous** (inside `steps(...)`), give the step a name first, for the report: ```java title="autos/YourAuto.java" s.run("Open the claw", robot.claw::open) .waitSeconds("Let the piece drop", 0.5) // a name for the report, then the seconds .run("Lift down", () -> robot.lift.goTo("down")); ``` **Why:** `sleep()` stops the whole robot: no driving, and no other part moves. `waitSeconds` waits while everything keeps running. **More:** [Actions.java: the rules](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/#the-rules-every-action-follows), [Non-blocking code](https://crossbotics.com/ftc-helper/docs/guides/non-blocking/). ## How do I wait until something is true? **Where:** `Actions.java`, inside the class. ```java title="Actions.java" /** Lowers the lift, and opens the claw only once the lift is down. */ public static Action lowerAndRelease(Robot r) { return Action.named("Lower and release") .then(() -> r.lift.goTo("down")) // Waits until the test is true. If 2 s pass first, the action STOPS here and says why. .waitUntil("lift down", () -> r.lift.isAt("down"), 2.0) .then(r.claw::open); } ``` **Why:** every wait has a time limit, so a stuck part cannot freeze the action forever. **More:** [Actions.java: the rules](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/#the-rules-every-action-follows). ## How do I start an action from a button? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Press Y: the action starts. Press Y again while it runs: it is canceled, safely. g2.y.press(Actions.scoreHigh(robot)).says("score high"); g2.x.press(Actions.grabAndLift(robot)).says("grab and lift"); ``` **Why:** the same button cancels it. A stick or button that moves the same part also stops it, so the driver always wins. **More:** [Actions.java: start it from a button](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/#start-it-from-a-button). ## How do I stop every running action? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Stop every running action at once (each stops what it started, safely). g2.back.press(robot::cancelAll).says("stop all actions"); ``` **Why:** a stopped action leaves each part safe: a lift holds its height, and an intake stops. **More:** [RobotDefinition: for your code](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition). ## How do I run an action when the OpMode starts? **Where:** `Robot.java`, inside `define()`. ```java title="Robot.java" // In Robot.java's define(): this action runs once, right after ▶ (autonomous and TeleOp). atStart(() -> Actions.deployIntake(this)); ``` The action it runs, in `Actions.java` inside the class (`intakeDeploy` is a [servo with named positions](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-any-servo-with-named-positions-a-gate-a-fold-out)): ```java title="Actions.java" /** Folds the intake out (the atStart line in Robot.java runs it). */ public static Action deployIntake(Robot r) { return Action.named("Deploy intake").then(() -> r.intakeDeploy.goTo("deployed")); } ``` **Why:** the library never moves anything in INIT, so a fold-out waits for ▶. This is the library's safety choice, because people are still next to the robot. The game rules would allow it (R103.B), but the robot must be still once INIT is done (G304.H). **More:** [Actions.java: an action at ▶](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/#an-action-when-the-opmode-starts). ## How do I use the same action in an autonomous? **Where:** a file in `autos/`, inside `steps(...)`. ```java title="autos/YourAuto.java" s.start("Against our wall, facing the field", 0) .forward("To the goal", 24, 0.5) .action(Actions.scoreHigh(robot), 5) // waits until it is done (at most 5 s) .back("Back up", 12, 0.5); ``` **Why:** you write the move once, and use it in TeleOp and autonomous. The report says if it timed out. **More:** [Actions.java: in an autonomous](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/#use-it-in-an-autonomous). --- # Autonomous URL: https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/ > **One rule for every angle:** angles count counterclockwise, like the IMU: 0 = forward, **90 = left**, > 180 = back, -90 = right. The rule is for a move (`.move("Left", 12, 90, 0.5)`), a turn > (`.turn("Left", 90, 0.4)`), `turnTo(...)`, and the heading in `start(...)` and `driveTo(...)`. Straight > moves and turns can use words instead: `.forward`, `.back`, `.left`, `.right`, `.turnLeft`, `.turnRight`. **The robot drives only after you run the Drive Tuner.** Until then, the autonomous shows "AUTONOMOUS IS OFF". Run the [Drive Tuner](https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/#how-do-i-tune-the-drive-for-autonomous) and copy its lines. Then set `calibrated = true` in `Tunables.java`, section `Drive`. The simulator runs the autonomous anyway, so you can try a route before tuning. **The questions on this page:** - [How do I make my first autonomous (drive 2 feet)?](#how-do-i-make-my-first-autonomous-drive-2-feet) - [How do I drive forward, sideways and turn?](#how-do-i-drive-forward-sideways-and-turn) - [Does my autonomous need a RED version?](#does-my-autonomous-need-a-red-version) - [How do I let the drivers choose before the match?](#how-do-i-let-the-drivers-choose-before-the-match) - [How do I make sure there is time to park?](#how-do-i-make-sure-there-is-time-to-park) - [How do I run a mechanism while the robot drives?](#how-do-i-run-a-mechanism-while-the-robot-drives) - [How do I wait for my alliance partner?](#how-do-i-wait-for-my-alliance-partner) - [How do I write a step the list cannot say?](#how-do-i-write-a-step-the-list-cannot-say) - [How do I change a distance in an autonomous?](#how-do-i-change-a-distance-in-an-autonomous) - [How do I share the same first steps in several autos?](#how-do-i-share-the-same-first-steps-in-several-autos) - [How do I make the start delay shorter, or use a different number on RED?](#how-do-i-make-the-start-delay-shorter-or-use-a-different-number-on-red) ## How do I make my first autonomous (drive 2 feet)? **Where:** a new file in `autos/`. In Android Studio, right-click the `autos` folder, then New, Java Class, and name it `LeaveTheStart`. Below is the whole file. Change the `package` and `import ...Robot` lines as the comment says: ```java title="autos/LeaveTheStart.java" package com.crossbotics.ftchelper.examples.cookbook.autos; // In your TeamCode, change the line above to exactly: package org.firstinspires.ftc.teamcode.autos; // and the first import below to: import org.firstinspires.ftc.teamcode.Robot; import com.crossbotics.ftchelper.examples.cookbook.Robot; import com.crossbotics.ftchelper.robot.Auto; import com.crossbotics.ftchelper.robot.Steps; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; // The name on the Driver Station, and the TeleOp it picks next (use YOUR TeleOp's name). @Autonomous(name = "Cookbook Leave the Start", group = "Cookbook", preselectTeleOp = "Cookbook TeleOp") @Disabled // delete this line in your copy, or the Driver Station will not list it public class LeaveTheStart extends Auto { @Override protected void steps(Steps s, Robot robot) { // s = the list of steps, robot = your Robot.java. Step lines go here: s.start("Against our wall, facing the field", 0) // the note the drive team reads .forward("Leave the start", 24, 0.4); // 24 inches = 2 feet, forward, 0.4 power } } ``` **Why:** `preselectTeleOp` makes the Driver Station pick your TeleOp next, so the drivers only have to press INIT. **More:** [Red and blue](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#red-and-blue). ## How do I drive forward, sideways and turn? **Where:** a file in `autos/`, inside `steps(...)`. ```java title="autos/YourAuto.java" s.start("Against our wall, facing the field", 0) .forward("Forward", 24, 0.5) // inches, max power .right("Sideways to the right", 12, 0.5) // mecanum only; also back(...), left(...) .turnLeft("Turn left 90", 90, 0.4) // also turnRight(...) .move("At an angle", 12, 45, 0.5) // angles count counterclockwise: 45 = forward and left .turn("Turn right 90", -90, 0.4) // the same rule: a right turn is minus .moveWithTurn("Back, turning", 12, 180, 90, 0.4) // mecanum only: drive and turn at once .turnTo("Face the start way", 0, 0.4); // to a heading: 0 = the way it faced at the start ``` **Why:** each move starts from where the robot is now, so the steps read like directions to a person. `moveWithTurn` is the one exception. It drives and turns at once, so its direction is fixed on the field. It counts like `turnTo`'s heading, from the way the robot faced at the start (180 = the opposite way). **More:** [Driving: move, turn, turnTo](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/#drive). ## Does my autonomous need a RED version? No. Write it once, for BLUE. BIOBUZZ's field is turned half a turn between the alliances. For it, add this to the autonomous class: ```java title="autos/YourAuto.java" // BIOBUZZ's field is turned half a turn between the alliances: one route works for both. @Override protected boolean mirrorForRed() { return false; } ``` **Why:** RED then uses the same numbers, seen from the red wall. On a mirrored field (the default), the library flips RED for you. **More:** [Field numbers](https://crossbotics.com/ftc-helper/docs/building-autos/01-what-an-auto-can-do/#field-numbers). ## How do I let the drivers choose before the match? **Where:** a file in `autos/`, inside `steps(...)`. ```java title="autos/YourAuto.java" s.start("Against our wall, facing the field", 0) .menuYesNo("Score", true) // the drivers choose in INIT with the D-pad .menuChoice("Park", "Near", "Far") .onlyIf("Score") // these steps run only if "Score" is yes .forward("To the goal", 30, 0.5) .action(Actions.scoreHigh(robot), 5) .end() // never forget end() ``` **Why:** one file covers several plans, and the drivers choose in INIT with the D-pad. The alliance and start delay choices come with it, with no code. **More:** [The INIT menu](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#add-choices-to-the-init-menu), [Branches: onlyIf](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#add-choices-to-the-init-menu). ## How do I make sure there is time to park? Add `parkWithSeconds` before the park steps. This code follows the menu recipe above: ```java title="autos/YourAuto.java" .parkWithSeconds(4) // the steps below always get the last 4 s .onlyIf("Park", "Near") .right("Park near", 20, 0.7) .end() .onlyIf("Park", "Far") .right("Park far", 40, 0.7) .end(); ``` **Why:** when 4 s are left, the main steps stop, so a slow step cannot cost you the parking points. **More:** [Keep time to park](https://crossbotics.com/ftc-helper/docs/reference/steps/#keep-time-to-park). ## How do I run a mechanism while the robot drives? **Where:** a file in `autos/`, inside `steps(...)`. ```java title="autos/YourAuto.java" s.start("Against our wall, facing the field", 0) .run("Intake on", robot.intake::in) // starts it and goes on at once .run("Lift up", () -> robot.lift.goTo("high")) .forward("To the pieces", 24, 0.4) // the intake and lift work while it drives .waitUntil("Lift at the top", robot.lift::isAtTarget, 2.0) .run("Intake off", robot.intake::stop); ``` **Why:** `run` starts a part and goes on at once. `waitUntil` waits only when the next step needs it. **More:** [Mechanisms: run and wait](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#start-something-or-wait-for-it). For whole actions while driving, use `alongside(...)` ([write each piece once](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#routes)). ## How do I wait for my alliance partner? **Where:** a file in `autos/`, inside `steps(...)`. ```java title="autos/YourAuto.java" s.menuYesNo("Wait for partner", false) .onlyIf("Wait for partner") .waitSeconds("Let our partner pass", 3) // the robot keeps running while it waits .end(); ``` **Why:** the drivers decide in INIT. For a wait before the first step, the menu already has a start delay. **More:** [Write each piece once](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#routes). ## How do I write a step the list cannot say? **Where:** a file in `autos/`, inside `steps(...)`. ```java title="autos/YourAuto.java" // Your own step, for anything the list cannot say. Wait with ctx, never sleep(). s.step("Clear the intake", ctx -> { robot.intake.out(); ctx.waitFor(0.3); // every part keeps working while it waits robot.intake.stop(); }); ``` **Why:** `ctx.waitFor` keeps every part updating and the timer working. `sleep()` would freeze them. **More:** [Your own steps](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#write-your-own-step). ## How do I change a distance in an autonomous? **Where:** the step itself, in your file in `autos/`. Change the number and build again. ```text title="autos/YourAuto.java" .forward("To the goal", 30, 0.5) // 30 = inches; change it here ``` **Why:** each autonomous keeps its own numbers, so a change to one auto does not change another. The simulator's auto builder can read the auto, change a number, and give you the new file. `Tunables.java` keeps the robot's numbers (speeds, positions, gains), which are the same in every auto. **More:** [The numbers are in the step](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#the-numbers-are-in-the-step). ## How do I share the same first steps in several autos? **Where:** your autonomous class (or a shared file), next to `steps(...)`. ```java title="autos/YourAuto.java" /** The same first steps for several autos: a method that adds them to the list. */ static Steps scorePreload(Steps s, Robot robot) { return s.forward("To the goal", 30, 0.5) .action(Actions.scoreHigh(robot), 5); } // in each autonomous: scorePreload(s.start("...", 0), robot).right("Park", 20, 0.7); ``` **Why:** when you fix the opening once, every autonomous gets the fix. **More:** [Write each piece once](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#routes). ## How do I make the start delay shorter, or use a different number on RED? Every autonomous's INIT menu already has `Alliance` and `Start delay` (0 to 10 s, D-pad left/right). **For a shorter menu line, where:** your autonomous class, as a method of its own next to `steps(...)`: ```java title="autos/YourAuto.java" // Inside your autonomous class, next to steps(...): the INIT menu's "Start delay" line // offers 0 to 5 s (the default is 0 to 10 s). @Override protected double maxStartDelaySec() { return 5; } ``` Most routes need no number that is different on RED, because the library mirrors or turns RED for you. **For one number that is different on RED, where:** inside `steps(...)`, above the steps. ```java title="autos/YourAuto.java" // Inside steps(...): alliance() is the alliance chosen in INIT. pick(blue, red) gives the // first value on BLUE and the second on RED (here: RED waits 2 s for its partner). double waitSec = alliance().pick(0.0, 2.0); s.start("Against our wall, facing the field", 0) .waitSeconds("Let our partner go first", waitSec) .forward("Leave the start", 24, 0.4); ``` **Why:** the start delay waits before the first step, so a partner can go first. 10 s is a lot to scroll through. `alliance().pick(blue, red)` works for any kind of value: a number, a name, an AprilTag id. **More:** [What the INIT menu can choose](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#add-choices-to-the-init-menu). --- # Several autos and choosing one URL: https://crossbotics.com/ftc-helper/docs/cookbook/10-several-autos/ You can have one autonomous per plan, or one autonomous with an INIT menu. Both use the same pieces. For the decision table, naming, simulator tests and a match-day checklist, see [Building autos 3: having multiple autos](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/). Each file below is whole. Copy it into `autos/`, and change the `package` and `import` lines as its comment says. The distances are plain numbers in the steps ([why](https://crossbotics.com/ftc-helper/docs/cookbook/09-autonomous/#how-do-i-change-a-distance-in-an-autonomous)). **The questions on this page:** - [How do I build several autos from the same pieces?](#how-do-i-build-several-autos-from-the-same-pieces) - [How do I make two autos that differ by one piece?](#how-do-i-make-two-autos-that-differ-by-one-piece) - [How do I let the drivers choose the start spot and the plan in INIT?](#how-do-i-let-the-drivers-choose-the-start-spot-and-the-plan-in-init) ## How do I build several autos from the same pieces? **Where:** a new file `Routes.java` in `autos/`. It has no `@Autonomous`, so it is not an OpMode (a program in the Driver Station's list). The autos below call its methods. ```java title="autos/Routes.java" package com.crossbotics.ftchelper.examples.cookbook.autos; // In your TeamCode, change the line above to exactly: package org.firstinspires.ftc.teamcode.autos; // and the first two imports below to: import org.firstinspires.ftc.teamcode.Actions; // import org.firstinspires.ftc.teamcode.Robot; import com.crossbotics.ftchelper.examples.cookbook.Actions; import com.crossbotics.ftchelper.examples.cookbook.Robot; import com.crossbotics.ftchelper.robot.Steps; /** The pieces every autonomous is made from. Write each piece once. No @Autonomous: not an OpMode. */ public class Routes { /** Score the piece the robot starts with: hold it, drive to the goal, score. */ public static Steps scorePreload(Steps s, Robot robot) { return s.run("Hold the preload", robot.claw::close) .forward("To the goal", 30, 0.6) .action(Actions.scoreHigh(robot), 5); } /** One more piece: back to the pieces, grab one, forward to the goal, score. */ public static Steps cycle(Steps s, Robot robot) { return s.back("To the pieces", 20, 0.6) .run("Grab", robot.claw::close) .waitSeconds("Let the claw close", 0.3) .forward("Back to the goal", 20, 0.6) .action(Actions.scoreHigh(robot), 5); } /** The park: back toward our wall. It keeps the last 3 seconds for itself, so it always runs. */ public static Steps park(Steps s) { return s.parkWithSeconds(3) .back("Park", 20, 0.7); } } ``` **Why:** you write each piece once, so a fix (or a new number in it) reaches every autonomous. `public static Steps scorePreload(Steps s, Robot robot)` is a method that any file can call (`public static`). It adds its steps to the list `s` and hands the list back (`return`). **More:** [Build them from shared steps](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#routes). ## How do I make two autos that differ by one piece? **Where:** two new files in `autos/`, `NearPreloadPark.java` and `NearCycle.java` (delete `@Disabled` in your copies, and write your TeleOp's name in `preselectTeleOp`). ```java title="autos/NearPreloadPark.java" package com.crossbotics.ftchelper.examples.cookbook.autos; // In your TeamCode, change the line above to exactly: package org.firstinspires.ftc.teamcode.autos; // and the first import below to: import org.firstinspires.ftc.teamcode.Robot; // (Routes is in the same autos folder: no import needed for it.) import com.crossbotics.ftchelper.examples.cookbook.Robot; import com.crossbotics.ftchelper.robot.Auto; import com.crossbotics.ftchelper.robot.Steps; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; /** Score the preload, then park. preselectTeleOp: YOUR TeleOp's name. */ @Autonomous(name = "Near: Preload + Park", group = "Autos", preselectTeleOp = "Cookbook TeleOp") @Disabled // delete this line in your copy public class NearPreloadPark extends Auto { @Override protected boolean mirrorForRed() { return false; // BIOBUZZ: the field is turned half a turn, one route for both alliances } @Override protected void steps(Steps s, Robot robot) { s.start("NEAR: against our wall, 2nd tile left of center, facing the field", -36, -61, 0); Routes.scorePreload(s, robot); Routes.park(s); } } ``` ```java title="autos/NearCycle.java" package com.crossbotics.ftchelper.examples.cookbook.autos; // In your TeamCode, change the line above to exactly: package org.firstinspires.ftc.teamcode.autos; // and the first import below to: import org.firstinspires.ftc.teamcode.Robot; import com.crossbotics.ftchelper.examples.cookbook.Robot; import com.crossbotics.ftchelper.robot.Auto; import com.crossbotics.ftchelper.robot.Steps; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; /** Score the preload, one more piece, then park. Only the Routes.cycle line is new. */ @Autonomous(name = "Near: Preload + Cycle + Park", group = "Autos", preselectTeleOp = "Cookbook TeleOp") @Disabled // delete this line in your copy public class NearCycle extends Auto { @Override protected boolean mirrorForRed() { return false; } @Override protected void steps(Steps s, Robot robot) { s.start("NEAR: against our wall, 2nd tile left of center, facing the field", -36, -61, 0); Routes.scorePreload(s, robot); Routes.cycle(s, robot); Routes.park(s); } } ``` **Why:** the Driver Station shows two lines, named after the start spot and the plan, so the drivers pick fast. Each line in `steps(...)` calls a piece, and the piece adds its steps to the same list `s`. **More:** [Write each piece once](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#routes), [names and groups](https://crossbotics.com/ftc-helper/docs/building-autos/03-multiple-autos/#names-on-the-driver-station). ## How do I let the drivers choose the start spot and the plan in INIT? **Where:** one new file in `autos/`, `ChooseInInit.java`. ```java title="autos/ChooseInInit.java" package com.crossbotics.ftchelper.examples.cookbook.autos; // In your TeamCode, change the line above to exactly: package org.firstinspires.ftc.teamcode.autos; // and the first import below to: import org.firstinspires.ftc.teamcode.Robot; import com.crossbotics.ftchelper.examples.cookbook.Robot; import com.crossbotics.ftchelper.robot.Auto; import com.crossbotics.ftchelper.robot.Steps; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; /** ONE autonomous: the drivers choose the start and the plan in INIT. */ @Autonomous(name = "Choose in INIT", group = "Autos", preselectTeleOp = "Cookbook TeleOp") @Disabled // delete this line in your copy public class ChooseInInit extends Auto { @Override protected boolean mirrorForRed() { return false; } @Override protected void steps(Steps s, Robot robot) { // Your menu lines (under the library's Alliance and Start delay lines). The FIRST option of // each is chosen at INIT: make it your safest plan. s.menuChoice("Start", "Near", "Far") .menuChoice("Plan", "Preload + Park", "Preload + Cycle + Park", "Park only"); // The start spot follows the "Start" line: the note and the simulator's robot change with it. s.onlyIf("Start", "Near") .start("NEAR: against our wall, 2nd tile left of center, facing the field", -36, -61, 0) .end() .onlyIf("Start", "Far") .start("FAR: against our wall, 2nd tile right of center, facing the field", 36, -61, 0) // Off the wall first: the FLOWER on our wall stands between the two start spots. .forward("Off the wall", 12, 0.5) .left("Across to the near side", 72, 0.7) .end(); // The plan: plain Java "if". choice(...) = the option chosen, as text. (1)! String plan = s.choice("Plan"); if (!plan.equals("Park only")) Routes.scorePreload(s, robot); if (plan.equals("Preload + Cycle + Park")) Routes.cycle(s, robot); Routes.park(s); } } ``` 1. The pieces are Java methods, so a plain `if` picks them. `choice(...)` gives the text of the option (a String). `equals(...)` tests whether two texts are the same. `!` means "not". **Why:** the library uses a `start(...)` inside an `onlyIf` only for its option. So the "Place robot" note (and the simulator's robot) changes as the drivers change the menu. The first option of each line is the default, so make it your safest plan. Your lines come after the library's two (`Alliance`, `Start delay`), so the drivers press D-pad down twice to reach `Start`. The FAR route drives off the wall first, because the FLOWER on your wall stands between the two start spots. A few Java words: `String plan` keeps a text. `plan.equals("Park only")` is true when the two texts are the same. `!` means "not". **More:** [One file, the drivers choose in INIT](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#a-whole-example-one-auto-the-drivers-choose), [what the menu can choose](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#add-choices-to-the-init-menu). --- # Odometry and driveTo URL: https://crossbotics.com/ftc-helper/docs/cookbook/11-odometry/ Odometry tells the robot where it is on the field. **Field numbers:** x = inches right of the center line, and y = inches away from your wall (negative = your half). Heading 0 = facing away from you, and counterclockwise (left) is +. **Every number in your code is seen from your own drivers' wall**, whatever your alliance: start spots, `driveTo`, the goal point, the reset spot. Only the simulator's map and its scenario checks (`expect robot x ...`) use one fixed view, from the red wall. See the [field map](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/#why-odometry). **The questions on this page:** - [How do I add a goBILDA Pinpoint?](#how-do-i-add-a-gobilda-pinpoint) - [How do I add a SparkFun OTOS?](#how-do-i-add-a-sparkfun-otos) - [How do I add dead wheels?](#how-do-i-add-dead-wheels) - [How do I tune the odometry?](#how-do-i-tune-the-odometry) - [How do I drive to a point on the field?](#how-do-i-drive-to-a-point-on-the-field) - [How do I get around field elements on the way to a spot?](#how-do-i-get-around-field-elements-on-the-way-to-a-spot) - [How do I show where the robot is?](#how-do-i-show-where-the-robot-is) - [How do I use the robot's position in an action?](#how-do-i-use-the-robots-position-in-an-action) - [How do I set the pose when autonomous did not run?](#how-do-i-set-the-pose-when-autonomous-did-not-run) ## How do I add a goBILDA Pinpoint? **Where:** `Robot.java`, inside `define()`, after the drive line. ```java title="Robot.java" // After drive(...). The robot's length and width, then where each pod's wheel is, mm: (1)! // the forward pod from the LEFT edge, the sideways pod from the FRONT edge. odometry(Odometry.pinpoint("pinpoint").robotSizeMm(430, 400).podsFromEdgesMm(284, 383)); ``` 1. Measure with a tape across the frame, bumpers off. The library finds the robot's center from the size. Here it works out `offsetsMm(-84, -168)`: the forward pod is 84 mm right of the center, and the sideways pod is 168 mm behind it. The Odometry Tuner then measures the exact offsets, and you write `.offsetsMm(...)` in place of `.podsFromEdgesMm(...)`. **Why:** the Pinpoint must know where the pods are, so a turn on the spot does not look like a move. **More:** [Add odometry: one line in Robot.java](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/#robotjava-one-line), [Pinpoint](https://crossbotics.com/ftc-helper/docs/modules/odometry/#pinpoint). ## How do I add a SparkFun OTOS? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // The robot's length and width, then the OTOS's middle from the FRONT and LEFT edges (mm), and its turn. odometry(Odometry.otos("otos").robotSizeMm(430, 400).mountFromEdgesMm(126, 200, 0)); ``` **Why:** the OTOS measures at its own spot. To give the place of the robot's center, it must know where it sits. **More:** [OTOS](https://crossbotics.com/ftc-helper/docs/modules/odometry/#otos). ## How do I add dead wheels? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" // The configuration names of the motor ports the pods plug into: left, right, sideways pod. // trackWidthIn: left pod to right pod. perpForwardIn: the sideways pod, 6 in BEHIND the center. odometry(Odometry.threeWheels("par_left", "par_right", "perp") .trackWidthIn(13.2).perpForwardIn(-6)); ``` **Why:** each pod's encoder plugs into a motor port, so the names are those ports' configuration names. **More:** [Three dead wheels](https://crossbotics.com/ftc-helper/docs/modules/odometry/#three-dead-wheels). ## How do I tune the odometry? **Where:** a new file in TeamCode (one per robot). The whole file: ```java title="OdometryTuner.java" // The Odometry Tuner: which way each pod counts, the offsets, and a loop check. @TeleOp(name = "Cookbook Odometry Tuner", group = "Finders") @Disabled // delete this line in your copy, or you will not see it public class OdometryTuner extends OdometryTunerOpMode { @Override protected RobotDefinition robot() { return new Robot(); // your Robot.java: the tuner uses its parts and numbers } } ``` **Why:** the tuner checks which way each pod counts, and measures the offsets. Then set `Tunables.Odometry.checked = true`, or `driveTo` does nothing on the robot. It is its own small file, because each program in the Driver Station's list is one class. `robot()` makes it use your `Robot.java`, so it measures the same odometry line that autonomous uses. **More:** [Odometry Tuner: the Odometry Tuner](https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/), [Finders](https://crossbotics.com/ftc-helper/docs/tuning/09-odometry-tuner/). ## How do I drive to a point on the field? **Where:** a file in `autos/`, inside `steps(...)`. It needs a mecanum drive. ```java title="autos/YourAuto.java" // The start spot (x, y, heading) must be where the robot really stands: the pose starts there. s.start("Against our wall, in the left corner tile, facing the field", -56, -61, 0) .driveTo("To the goal", -30, -30, 45, 0.6) .parkWithSeconds(4) // The last number: "close enough", in inches (default 1). .driveTo("Park", -56, -36, 0, 0.7, 2.0); ``` It replaces `.move(...)`: you give a place on the field, not a distance. **Why:** `driveTo` keeps checking where the robot is. So a bump or a wheel slip does not matter, and the robot ends on the point. On the robot, it works only after the [Odometry Tuner](#how-do-i-tune-the-odometry) and `checked = true` in `Tunables.java`, section `Odometry`. **More:** [Drive to points on the field: drive to field points](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/#drive-to-a-point-driveto), [driveTo](https://crossbotics.com/ftc-helper/docs/building-autos/04-drive-to-points/#drive-to-a-point-driveto). ## How do I get around field elements on the way to a spot? **Where:** `Robot.java`, inside `define()`, then a file in `autos/`, or `Controls.java`. It needs odometry and a mecanum drive. ```java title="Robot.java" // After odometry(...). The margin: half the robot's corner to corner size, plus some for drift. // Each box: two opposite corners, like driveTo's numbers. These are BIOBUZZ's two HIVE frames. fieldMap(FieldMap.margin(13) .keepOut("HIVE frame, near", -19.5, -24.8, 19.5, -15.4) .keepOut("HIVE frame, far", -19.5, 15.4, 19.5, 24.8)); ``` In an autonomous, `routeTo` is `driveTo` with a way around the boxes (the keep-out areas in the field map). It starts from wherever the park time stopped the robot: ```java title="autos/YourAuto.java" s.start("Against our wall, in the left corner tile, facing the field", -56, -61, 0) .driveTo("To the goal", -30, -30, 45, 0.6) .parkWithSeconds(6) // the route slows at each corner: give it more time than a straight line .routeTo("Park", -56, -36, 0, 0.8); ``` In TeleOp, a button or a time starts it, and any drive stick stops it: ```java title="Controls.java" // route(...) makes the job. It starts when the button or the time says so. Runnable park = route("Park", -56, -36, 0, 0.8); g1.dpadLeft.tap(park).says("drive to the park spot (a drive stick stops it)"); atSecondsLeft(10, park); ``` **Why:** a straight line from an unknown place can go through a field element. The robot works out the way when it sets off. It uses only its pose, so it cannot see another robot. Go slow the first time. **More:** [Keep-out boxes and routes](https://crossbotics.com/ftc-helper/docs/modules/odometry/#keep-out-boxes-and-routes). ## How do I show where the robot is? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" show("Where", () -> String.format(Locale.US, "x %.0f, y %.0f in, heading %.0f", robot.pose().x, robot.pose().y, robot.pose().headingDeg)); ``` **Why:** to check the odometry, push the robot by hand and watch the numbers. **More:** [robot.pose()](https://crossbotics.com/ftc-helper/docs/modules/odometry/#robotpose). (TeleOp also starts where autonomous ended: [Add odometry](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/#teleop-starts-where-autonomous-ended).) ## How do I use the robot's position in an action? **Where:** `Actions.java`, inside the class. ```java title="Actions.java" /** Runs the intake while the robot is on our half of the field (y below 0). */ public static Action intakeOnOurHalf(Robot r) { return Action.named("Intake on our half") .then(r.intake::in) .waitUntil("past the center line", () -> r.pose().y > 0, 10.0) .then(r.intake::stop); } ``` **Why:** the library updates `robot.pose()` every loop, so a wait can test where the robot is. **More:** [robot.pose()](https://crossbotics.com/ftc-helper/docs/modules/odometry/#robotpose). ## How do I set the pose when autonomous did not run? **Where:** `Tunables.java`, section `Odometry` (and `Controls.java` for more spots). When autonomous stopped early or did not run, TeleOp does not know where the robot is. Park the robot on the reset spot and let go of the drive sticks. Then hold gamepad 1 **START** for 1 second ("set pose here"). This works in INIT or in the match. Write the spot for BLUE, like a start spot. Write `mirrorForRed = false` because BIOBUZZ's field is turned half a turn (RED uses the same numbers from its own wall). On a mirrored field, leave it out (default `true`, RED mirrored). INIT's `Reset spot for RED` line shows which one the library uses. ```java title="Tunables.java" public static class Odometry { // a fixed name: always Odometry public static boolean checked = false; // true after the Odometry Tuner's Loop test // "Set pose here" (TeleOp: hold gamepad 1 START 1 s on this spot), written for BLUE. (1)! public static double resetX = -56; // inches right of center, - = left public static double resetY = -61; // inches from center, - = our half public static double resetHeading = 0; // degrees, 0 = facing the field // RED: false = the same numbers from the red wall; true (or left out) = mirrored left-right. (2)! public static boolean mirrorForRed = false; // BIOBUZZ: false } ``` 1. Inches and degrees seen from your wall, like a start spot. Here the spot is our left corner tile, facing the field. 2. BIOBUZZ's field is turned half a turn between the alliances, so write `false`. `true` is for a mirrored field. For more spots, or to set the pose from an action, write this in `Controls.java`, inside `buttons(...)`: ```java title="Controls.java" // A second spot of your own: hold D-pad down 1 s with the robot in the right corner tile. (1)! g1.dpadDown.heldFor(1.0, () -> robot.resetPose(56, -61, 0)).says("hold 1 s: pose = right corner tile"); // An action can set it too (the action is in Actions.java, below). (2)! g1.dpadUp.heldFor(1.0, Actions.poseHereThenIntake(robot)).says("hold 1 s: pose here, intake on"); ``` 1. x, y and heading are written for BLUE. RED uses them like the reset spot in `Tunables.Odometry`. 2. Here the action sets the `Tunables.Odometry` spot, then runs the intake. The action, in `Actions.java` inside the class: ```java title="Actions.java" /** Sets the pose to the reset spot in Tunables.Odometry, then runs the intake. */ public static Action poseHereThenIntake(Robot r) { return Action.named("Pose here, intake on") .then(r::resetPose) // resetPose() with no numbers: the Tunables.Odometry spot .then(r.intake::in); } ``` **Why:** with a pose, the aim's odometry backup and field-centric "forward" work again. The 1 s hold means a bump of the button does nothing. Write all the spots from your own drivers' wall, like every field number in your code. **More:** [Add odometry: TeleOp starts where autonomous ended](https://crossbotics.com/ftc-helper/docs/add-to-robot/09-odometry/#teleop-starts-where-autonomous-ended), [resetPose()](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#robotdefinition). --- # Pedro paths URL: https://crossbotics.com/ftc-helper/docs/cookbook/12-pedro-paths/ **The questions on this page:** - [How do I add Pedro Pathing to Robot.java?](#how-do-i-add-pedro-pathing-to-robotjava) - [How do I make a straight path and a curve?](#how-do-i-make-a-straight-path-and-a-curve) - [How do I follow a path in an autonomous?](#how-do-i-follow-a-path-in-an-autonomous) - [How do I drive two paths with no stop, slow down, or hold at the end?](#how-do-i-drive-two-paths-with-no-stop-slow-down-or-hold-at-the-end) - [How do I keep facing the goal along a path?](#how-do-i-keep-facing-the-goal-along-a-path) - [How do I drive first and turn at the end of a path (or turn first)?](#how-do-i-drive-first-and-turn-at-the-end-of-a-path-or-turn-first) - [How do I start something partway along a path?](#how-do-i-start-something-partway-along-a-path) ## How do I add Pedro Pathing to Robot.java? **Where:** `Robot.java`, inside `define()` (and `Tunables.java` for the numbers). ```java title="Robot.java" odometry(Odometry.pinpoint("pinpoint").offsetsMm(-84, -168)); // Pedro needs odometry // Pedro drives the paths with the drive and odometry lines above. PedroConstants holds the // numbers from Pedro's Foresight tuner (docs/modules/pedro.md#tuning-pedro). follower(Pedro.follower(PedroConstants.foresight)); ``` **Why:** Pedro uses your drive and odometry lines, so you describe the robot only once. **More:** [Add Pedro paths: Robot.java](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/#robotjava-one-line-and-pedros-numbers-file), [Tuning Pedro](https://crossbotics.com/ftc-helper/docs/modules/pedro/#tuning-pedro). ## How do I make a straight path and a curve? **Where:** your autonomous class, above `steps(...)`. ```java title="autos/YourAuto.java" // Make each path once. A line: from (x1, y1) to (x2, y2). A curve: start, a control point // that pulls the curve toward it (the robot does not drive through it), end. static final PedroPath OUT = PedroPath.line(-56, -61, -56, -36).keepHeading(0); static final PedroPath TO_GOAL = PedroPath.curve(-56, -36, -44, -36, -30, -30).turnTo(0, 45); ``` **Why:** Java makes a path once (`static final`), because it is the same every match. **More:** [PedroPath](https://crossbotics.com/ftc-helper/docs/modules/pedro/#pedropath-paths-in-our-field-numbers). ## How do I follow a path in an autonomous? **Where:** a file in `autos/`, inside `steps(...)`. ```java title="autos/YourAuto.java" s.start("Against our wall, in the left corner tile, facing the field", -56, -61, 0) .follow("Out", OUT) // brakes to a stop at its end .follow("To the goal", TO_GOAL) .run("Intake on", robot.intake::in) .follow("Back", WATCH_GOAL) .parkWithSeconds(4) .driveTo("Park", -56, -36, 0, 0.7); // driveTo works too (it ends any hold first) ``` **Why:** each `follow` brakes to a stop at its end. Start the next path where the last one ended. **More:** [Add Pedro paths: your first path](https://crossbotics.com/ftc-helper/docs/building-autos/05-pedro-paths/#actionsjava-and-autos-make-paths-then-follow-them), [follow](https://crossbotics.com/ftc-helper/docs/modules/pedro/#follow-the-autonomous-step). ## How do I drive two paths with no stop, slow down, or hold at the end? **Where:** your autonomous class, above `steps(...)`. ```java title="autos/YourAuto.java" // Two parts with NO stop between them (then), a slow part near the goal (maxSpeed), // and hold the end point while it scores (holdEnd: at most 5 s). static final PedroPath IN_ONE_GO = PedroPath.line(-56, -61, -48, -50).keepHeading(0) .then(PedroPath.curve(-48, -50, -44, -36, -30, -30)).turnTo(0, 45) .maxSpeed(0.6) .holdEnd(); ``` **Why:** `then` saves the time of a stop, and `holdEnd` pushes back if another robot bumps yours while it scores. **More:** [PedroPath](https://crossbotics.com/ftc-helper/docs/modules/pedro/#pedropath-paths-in-our-field-numbers), [Hold the end point](https://crossbotics.com/ftc-helper/docs/modules/pedro/#hold-the-end-point). ## How do I keep facing the goal along a path? **Where:** your autonomous class, above `steps(...)`. ```java title="autos/YourAuto.java" // Keep facing one field point the whole way (here x -60, y 60: put your goal's x and y). static final PedroPath WATCH_GOAL = PedroPath.line(-30, -30, -56, -36).facePoint(-60, 60); ``` **Why:** the robot can slide along the path while it keeps the camera or launcher on the goal. **More:** [PedroPath: the heading](https://crossbotics.com/ftc-helper/docs/modules/pedro/#pedropath-paths-in-our-field-numbers). ## How do I drive first and turn at the end of a path (or turn first)? **Where:** your autonomous class, above `steps(...)`. ```java title="autos/YourAuto.java" // Turn from 0 to 90 only in the last 30% of the line (0.7 to 1): drive first, then turn. static final PedroPath DRIVE_THEN_TURN = PedroPath.line(-56, -61, -30, -30).turnTo(0, 90, 0.7, 1); ``` **Why:** `turnTo(a, b)` turns all along the part. The two extra numbers say on which stretch it turns (0 = the part's start, 1 = its end). `0, 0.3` turns first, then drives. `0.7, 1` drives first, then turns. **More:** [PedroPath: the heading](https://crossbotics.com/ftc-helper/docs/modules/pedro/#pedropath-paths-in-our-field-numbers). ## How do I start something partway along a path? **Where:** your autonomous, `steps(...)`. Android Studio shows `PathAt` in red. Press Alt+Enter to add the import. ```java title="autos/YourAuto.java" s.start("Against our wall, in the left corner tile, facing the field", -56, -61, 0) // PathAt: start things ALONG the path, once each, while the robot keeps driving. .follow("To the goal", Paths.IN_ONE_GO, PathAt.part(2, "Intake on", robot.intake::in), // where part 2 starts PathAt.inchesLeft(6, "Intake off", robot.intake::stop)) // 6 in before the end .waitSeconds("Score (the robot holds still)", 0.5); ``` You can also use `PathAt.fraction(0.5, ...)` (halfway along the whole path), `PathAt.inchesDone(10, ...)` and `PathAt.near(x, y, 6, ...)`, for example `PathAt.inchesLeft(12, "Spin up", robot.launcher::spinUp)`. In place of a name and a command, you can give an action from your `Actions.java` (`PathAt.inchesLeft(12, Actions.scoreHigh(robot))`: any action you wrote). **Why:** the robot does not stop to start a mechanism, and Pedro has no "do this here" of its own. If the path ends early, the report says which ones did not start (`STALLED, not fired: Intake off`). **More:** [Do things along the path](https://crossbotics.com/ftc-helper/docs/modules/pedro/#do-things-along-the-path). --- # Telemetry URL: https://crossbotics.com/ftc-helper/docs/cookbook/13-telemetry/ **The questions on this page:** - [How do I show a value on the Driver Station screen?](#how-do-i-show-a-value-on-the-driver-station-screen) - [How do I round a number on the Driver Station?](#how-do-i-round-a-number-on-the-driver-station) - [How do I show lines from my own autonomous step?](#how-do-i-show-lines-from-my-own-autonomous-step) ## How do I show a value on the Driver Station screen? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // A line of its own in buttons(...). The value is read again every loop. show("Lift ticks", robot.lift::position); show("Intake on", robot.intake::isRunning); // shows "Intake on : true" show("Flywheel ready", () -> robot.launcher.isReady()); ``` **Why:** you see what the robot "thinks" while you drive. The value must be quick to read, with no waiting. **More:** [Controls: feedback](https://crossbotics.com/ftc-helper/docs/controls/03-see-and-feel/#feedback-on-a-button). For debug lines (loop time and more), hold gamepad 1 START, then press BACK. The lines turn on or off when you let go. BACK first only pauses the robot. When the alliance switch is on, let go before 1.5 s: a 1.5 s hold switches the alliance and does not change the debug lines. ## How do I round a number on the Driver Station? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // Round a number: %.0f = no decimals, %.1f = one decimal. Locale.US keeps the dot (not a comma). show("Target RPM", () -> String.format(Locale.US, "%.0f", robot.launcher.targetRpm())); ``` **Why:** `%.0f` means "a number with 0 decimals", and `%.2f` gives 2. **More:** [Controls: feedback](https://crossbotics.com/ftc-helper/docs/controls/03-see-and-feel/#feedback-on-a-button). ## How do I show lines from my own autonomous step? **Where:** a file in `autos/`, inside `steps(...)`. ```java title="autos/YourAuto.java" // In your own step: lines on the Driver Station while it runs, and a note in the report. s.step("Spin up", ctx -> { robot.launcher.spinUp(); double giveUpAt = ctx.secondsLeft() - 3; // a time limit: at most 3 s while (ctx.isActive() && !robot.launcher.isReady() && ctx.secondsLeft() > giveUpAt) { ctx.telemetry().line("Flywheel", "spinning up to %.0f RPM", robot.launcher.targetRpm()); ctx.loop(); // updates every part once: the robot keeps running } ctx.note(robot.launcher.isReady() ? "at speed" : "not at speed after 3 s"); }); ``` **Why:** `ctx.loop()` keeps the robot running inside your loop. The time limit makes sure that the loop ends. **More:** [Your own steps](https://crossbotics.com/ftc-helper/docs/building-autos/08-advanced-autos/#write-your-own-step), [The report](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/#after-the-match-read-the-report). --- # Lights URL: https://crossbotics.com/ftc-helper/docs/cookbook/14-lights/ A colored light on the robot tells the drivers what the robot "knows" (full, ready, a mode on), so they do not have to look at the Driver Station. The color names need `import com.crossbotics.ftchelper.robot.LightColor;` at the top of each file that uses them: `Controls.java`, and `Actions.java` if an action flashes the light. To add it, press Alt+Enter on a red `LightColor`. The full details: [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/). **The questions on this page:** - [How do I add a colored light for the drivers?](#how-do-i-add-a-colored-light-for-the-drivers) - [How do I change a color on a REV Blinkin?](#how-do-i-change-a-color-on-a-rev-blinkin) - [How do I show a color when something is true?](#how-do-i-show-a-color-when-something-is-true) - [How do I show the alliance on the light before the match?](#how-do-i-show-the-alliance-on-the-light-before-the-match) - [How do I flash the light when something happens?](#how-do-i-flash-the-light-when-something-happens) - [How do I flash the light when an action is done?](#how-do-i-flash-the-light-when-an-action-is-done) - [How do I blink the light in the last 20 seconds?](#how-do-i-blink-the-light-in-the-last-20-seconds) ## How do I add a colored light for the drivers? **Where:** `Robot.java`, inside `define()` (and a field `public Lights lights;`). ```java title="Robot.java" // At the top of Robot.java: import com.crossbotics.ftchelper.robot.Lights; (1)! // A goBILDA RGB Indicator Light on a servo port ("Servo" in the robot configuration): lights = add(Lights.gobilda("light")); // Or a REV Blinkin LED Driver with an LED strip ("REV Blinkin LED Driver" in the configuration): // lights = add(Lights.blinkin("blinkin")); ``` 1. `Controls.java` needs `import com.crossbotics.ftchelper.robot.LightColor;` for the colors. To add it, press Alt+Enter on a red `LightColor`. **Why:** the light is one line, like any part. It has no numbers and no buttons of its own: the colors come from your rules. **More:** [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/) (the parts and their color tables). ## How do I change a color on a REV Blinkin? **Where:** `Robot.java`, inside `define()`, below the lights line. ```java title="Robot.java" // At the top of Robot.java: import com.qualcomm.hardware.rev.RevBlinkinLedDriver; // A REV Blinkin LED Driver ("REV Blinkin LED Driver" in the robot configuration): lights = add(Lights.blinkin("blinkin")); // Plain blue too dark on your strip? Show another Blinkin pattern for BLUE. (1)! lights.blinkinPattern(LightColor.BLUE, RevBlinkinLedDriver.BlinkinPattern.BLUE_VIOLET); ``` 1. The pattern names are on REV's Blinkin page. Other lights ignore this line. **Why:** each `LightColor` is one of the Blinkin's patterns (`BLUE` is its plain blue). LED strips differ. When one color looks wrong on yours, give that color another pattern. Your rules still say `LightColor.BLUE`. A goBILDA light ignores the line. ## How do I show a color when something is true? **Where:** `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // One rule per line. The first true rule wins: put the most important first. // Red and blue are left for the alliance (shown at INIT), so no rule looks like one. robot.lights.show(LightColor.ORANGE).blinking().when(robot.intake::isPushingOut); // pushing out robot.lights.show(LightColor.GREEN).when(robot.launcher::isReady); // at speed: fire robot.lights.show(LightColor.PURPLE).when(robot.intake::isRunning); // intake on robot.lights.otherwise(LightColor.OFF); // none true ``` **Why:** any true/false works as a rule: - a part's method (`robot.intake::isRunning`) - a mode: `() -> robot.turret.followMode().isOn()` (the turret follows the goal), or on a robot without a turret, `() -> robot.aimMode().isOn()` (whole-robot aim is on) - your own test (`() -> robot.lift.position() > 1000`, if your robot has a lift) Blinking is at most 5 times a second, and the light never changes faster than every 0.1 s (FTC rule R202 J). **More:** [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/), [lambdas](https://crossbotics.com/ftc-helper/docs/five-files/04-actions-java/). ## How do I show the alliance on the light before the match? **Where:** you add nothing, because it is on by default. To change its colors or turn it off, write in `Controls.java`, inside `buttons(...)`. ```java title="Controls.java" // On by default: the alliance at INIT (solid RED or BLUE), flashed for 1 s at ▶. (1)! // Your light shows red badly? Other colors for the alliance at INIT (BLUE, and PURPLE for RED): robot.lights.allianceColors(LightColor.BLUE, LightColor.PURPLE); // No alliance color at INIT at all? Delete the line above and write: (2)! // robot.lights.allianceAtInit(false); ``` 1. Until the drivers choose an alliance, the light blinks white. You do not write anything for this. 2. Your rules then show from INIT on. Or, in `Tunables.java`, write this in the light's section: `public static class Light { public static boolean allianceAtInit = false; }`. The line in `Controls.java` wins. **Why:** with a wrong alliance pick in INIT, the robot aims at the other alliance's goal all match. The light is solid RED or BLUE before ▶ (white, blinking once a second, until the drivers pick). So the drive team sees a wrong pick from the field. The game manual has no rule against a light in your alliance color, but the ROBOT SIGNS are still required (R401, R402). Keep your own rules' colors away from red and blue. **More:** [Lights](https://crossbotics.com/ftc-helper/docs/reference/parts/lights/#the-alliance-at-init). ## How do I flash the light when something happens? **Where:** `Controls.java`, inside `buttons(...)`, above your other light rules. ```java title="Controls.java" // A flash beats every rule while it lasts (write it first: it reads that way). (1)! // A short white flash for each piece fired, and one from a button. robot.lights.show(LightColor.WHITE).forSeconds(0.2) .whenCountGoesUp(() -> robot.launcher.part().getShotsFired()); g2.a.press(() -> robot.lights.flash(LightColor.YELLOW)).says("flash the light (signal the partner)"); ``` 1. A flash wins, wherever you write it. The launcher counts the pieces it feeds. The flash is 0.2 s, so two quick shots are two flashes, not one long one. **Why:** `whenCountGoesUp` flashes each time the number goes up, so each flash is a real shot. `whenStarts(test)` flashes when a true/false turns from false to true (`whenStarts(robot.intake::isRunning)`: the intake has started). A flash lasts 0.5 s. `.forSeconds(...)` before `when...` changes it. Here it is shorter, so two shots a quarter second apart are two flashes, not one long one. `flash(color)` from a button or an action flashes once. ## How do I flash the light when an action is done? **Where:** `Actions.java`, inside the class. ```java title="Actions.java" // In Actions.java (it needs import com.crossbotics.ftchelper.robot.LightColor; at the top). // The last step: a 1 s white flash says "done" to the drivers. Pick a color your rules do not use. (1)! public static Action shootTwo(Robot r) { return Action.named("Shoot two") .then(r.launcher::spinUp) .waitUntil("at speed", r.launcher::isReady, 3.0) .then(() -> r.launcher.fire(2)) .waitUntil("both gone", () -> !r.launcher.isShooting(), 3.0) .then(() -> r.lights.flash(LightColor.WHITE, 1.0)); } ``` 1. A GREEN flash over the GREEN "ready" rule cannot be seen. Pick another color, or a longer time. **Why:** no action "claims" the light, so any action (or button) may flash it. A flash beats every rule. But you cannot see a flash in the same color as the rule under it, so pick another color, or a longer time. ## How do I blink the light in the last 20 seconds? **Where:** `Controls.java`, inside `buttons(...)`, before the other rules. ```java title="Controls.java" // Yellow, blinking, in the last 20 seconds of TeleOp: time to park (above the other rules: it wins). robot.lights.show(LightColor.YELLOW).blinking().inLastSeconds(20); ``` **Why:** the time counts from ▶ (TeleOp's 2:00), like the gamepad buzzes. It is about a second off from the field clock, which is good enough for a reminder. --- # Tuning and finders URL: https://crossbotics.com/ftc-helper/docs/cookbook/15-tuning/ **The questions on this page:** - [Where do the numbers go?](#where-do-the-numbers-go) - [How do I find a servo's open and closed numbers?](#how-do-i-find-a-servos-open-and-closed-numbers) - [How do I find a lift's limits and heights?](#how-do-i-find-a-lifts-limits-and-heights) - [How do I change a number while the robot runs?](#how-do-i-change-a-number-while-the-robot-runs) - [How do I tune the drive for autonomous?](#how-do-i-tune-the-drive-for-autonomous) - [How do I set the flywheel numbers?](#how-do-i-set-the-flywheel-numbers) - [How do I build a shot table (speed for each distance)?](#how-do-i-build-a-shot-table-speed-for-each-distance) - [How do I find my hood's stops and angles?](#how-do-i-find-my-hoods-stops-and-angles) ## Where do the numbers go? In `Tunables.java`, one section per part (see [the lift recipe](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-a-lift-with-set-heights)). A finder (a program that measures a number on the robot) shows lines like `Tunables.Claw: P1 = 0.210, P2 = 0.770`. Copy them into that section, keep the other lines, and give P1 and P2 real names. A number you leave out uses the library's default (INIT says which). The exception is a lift's or arm's `min` and `max`: you must write those. **More:** [Tunables.java](https://crossbotics.com/ftc-helper/docs/reference/tunables/), [Finding your numbers](https://crossbotics.com/ftc-helper/docs/tuning/). ## How do I find a servo's open and closed numbers? **With the five files:** you add nothing. Run **Tune and check** (the library puts it on the Driver Hub) and pick the Servo Finder ([Tune and check](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/)). **Without the five files:** a new file in TeamCode (also in the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/)). The whole file: ```java title="ServoFinder.java" // The Servo Finder: lists every servo in the configuration. No robot needed. @TeleOp(name = "Cookbook Servo Finder", group = "Finders") @Disabled // delete this line in your copy, or you will not see it public class ServoFinder extends ServoFinderOpMode { } ``` **Use it:** put the robot on a block. Run the Servo Finder. Choose the servo (D-pad, A). A servo cannot say where it is, so choose a start number close to where it sits now (D-pad, A). Nudge it with the D-pad. At each end of its safe travel (right before it pushes on the frame), press X, then B. Then move it to each position you need and press A. For example: fully open, A (that is P1); closed, A (P2). Copy the line it shows (`Tunables.Claw: P1 = 0.210, P2 = 0.770`) into `Tunables.java` and rename P1, P2 (`open`, `closed`). For a part with [`.fullRange()`](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-get-my-servos-full-range) in Robot.java, press Y first, while you choose the servo. **Why:** a servo pushed past its end hums, gets hot and breaks. The finder finds the safe numbers. **More:** [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/), [the order](https://crossbotics.com/ftc-helper/docs/tuning/#the-tuning-order). ## How do I find a lift's limits and heights? **With the five files:** you add nothing. Run **Tune and check** (the library puts it on the Driver Hub) and pick the Motor Finder ([Tune and check](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/)). **Without the five files:** a new file in TeamCode (also in the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/)). The whole file: ```java title="MotorFinder.java" // The Motor Finder: lists every motor in the configuration. No robot needed. @TeleOp(name = "Cookbook Motor Finder", group = "Finders") @Disabled // delete this line in your copy, or you will not see it public class MotorFinder extends MotorFinderOpMode { } ``` **Use it:** first put the lift all the way down, because the count starts at 0 there. Choose the motor (D-pad, A). Move it slowly with the right stick. Press X a little above the bottom and B a little below the top. Then press A at each height you need. Copy the line it shows (`Tunables.Lift: min = 0, max = 2580, P1 = 1200`) into `Tunables.java` and rename P1 (`low`). **Why:** a wrong top limit drives the lift into its hard stop. Measured limits keep it safe. **More:** [Motor Finder](https://crossbotics.com/ftc-helper/docs/tuning/05-motor-finder/). ## How do I change a number while the robot runs? With the five files, you write no code for this. In the TeleOp (PRACTICE profile), after ▶, **hold GUIDE for 1 second**, and the tuning menu opens. D-pad up/down chooses a number, and right/left changes it. **A** saves it on the hub, and **B** lists the changed values. **Then copy each good value into `Tunables.java`.** With a new Control Hub, you lose a value that you saved only on the hub. Also, your teammates cannot see it. **Why:** you see the effect at once, and you do not have to build and install again. **More:** [Tuning](https://crossbotics.com/ftc-helper/docs/tuning/16-live-tuning/#open-it-and-change-a-number), [Add a lift: tune the lift live](https://crossbotics.com/ftc-helper/docs/add-to-robot/01-lift/#4-check-it-then-tune-it). ## How do I tune the drive for autonomous? **With the five files:** you add nothing. Run **Tune and check** (the library puts it on the Driver Hub) and pick the Drive Tuner ([Tune and check](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/)). **Without the five files:** a new file in TeamCode. The whole file: ```java title="DriveTuner.java" // The Drive Tuner: wheel size and strafe correction, for the drive in your Robot.java. @TeleOp(name = "Cookbook Drive Tuner", group = "Finders") @Disabled // delete this line in your copy, or you will not see it public class DriveTuner extends DriveTunerOpMode { @Override protected RobotDefinition robot() { return new Robot(); // your Robot.java: the tuner uses its parts and numbers } } ``` **Why:** the tuner measures the real wheel size and strafe correction. Copy its lines, then set `Tunables.Drive.calibrated = true`. **More:** [Tune the drive first](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#tune-the-drive-first), [Drive Tuner](https://crossbotics.com/ftc-helper/docs/tuning/08-drive-tuner/). ## How do I set the flywheel numbers? Before you have them, write `DEFAULT` in their place, or leave the lines out. The launcher then starts from the parts catalog's numbers for its motor, and INIT says so. For a goBILDA 6000 RPM motor, these are kF 11.7, kP 1.17, kI 0.117, and 60% of its top speed, 3600 RPM. Then run the **Flywheel Finder** (in the [starter kit](https://crossbotics.com/ftc-helper/docs/starter-kit/)) and copy its line into `Tunables.Launcher` (see [the launcher recipe](https://crossbotics.com/ftc-helper/docs/cookbook/04-mechanisms/#how-do-i-add-a-launcher-flywheel-and-feeder)). Do not copy another robot's gains, because its team found them for its own wheel. **Why:** the right `kP`..`kF` (the gains: how hard the motor pushes toward the target speed) make the wheel get back to speed fast after each shot. **More:** [Flywheel Finder](https://crossbotics.com/ftc-helper/docs/tuning/06-flywheel-finder/). ## How do I build a shot table (speed for each distance)? **With the five files:** you add nothing. Run **Tune and check** (the library puts it on the Driver Hub) and pick the Shot Tuner ([Tune and check](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/)). **Without the five files:** a new file in TeamCode, `ShotTuner.java`. Run the [Aim Tuner](https://crossbotics.com/ftc-helper/docs/tuning/12-aim-tuner/) first. Below is the whole file. Its first line is `package org.firstinspires.ftc.teamcode;` (Android Studio writes it when you make the file), then: ```java title="ShotTuner.java" import com.crossbotics.ftchelper.finders.ShotTunerOpMode; import com.crossbotics.ftchelper.robot.RobotDefinition; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; // The Shot Tuner: fills Tunables.Launcher.speedByDistance from shots you mark HIT or MISS. @TeleOp(name = "Cookbook Shot Tuner", group = "Finders") @Disabled // delete this line in your copy, or you will not see it public class ShotTuner extends ShotTunerOpMode { @Override protected RobotDefinition robot() { return new Robot(); // your Robot.java: the tuner uses its parts and numbers } } ``` **Why:** the launcher needs a speed for each distance. At each distance, you shoot 3-5 times per speed and mark each HIT (A) or MISS (B), all on gamepad 1. A left stick click takes the last mark back. X keeps the speed with the best hit ratio (hits out of shots). The tuner fills `Tunables.Launcher.speedByDistance` (one line per table to copy), so the launcher picks the speed for each distance. **More:** [Shot Tuner](https://crossbotics.com/ftc-helper/docs/tuning/13-shot-tuner/). ## How do I find my hood's stops and angles? **With the five files:** you add nothing. Run **Tune and check** (the library puts it on the Driver Hub) and pick the Hood Finder ([Tune and check](https://crossbotics.com/ftc-helper/docs/tuning/01-tune-and-check/)). **Without the five files:** a new file in TeamCode, `HoodFinder.java` (first line `package org.firstinspires.ftc.teamcode;`): ```java title="HoodFinder.java" import com.crossbotics.ftchelper.finders.HoodFinderOpMode; import com.crossbotics.ftchelper.robot.RobotDefinition; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; // The Hood Finder: the hood's two stops (and its angles) for Tunables.Hood. It reads the hood // from Robot.java (servo or motor), so it works before Tunables.Hood has numbers. @TeleOp(name = "Cookbook Hood Finder", group = "Finders") @Disabled // delete this line in your copy, or you will not see it public class HoodFinder extends HoodFinderOpMode { @Override protected RobotDefinition robot() { return new Robot(); // your Robot.java: the finder finds its hood } } ``` **Why:** the hood needs its stops and angles. Nudge the hood to each stop, back off a hair, and press X and B. The finder writes `Tunables.Hood: posA = ..., posB = ...`. Before X / B, hold LB + D-pad to type in the angle you measured (or press A for a point in between, for a linkage). Copy the lines into `Tunables.java`. **More:** [Hood Finder](https://crossbotics.com/ftc-helper/docs/tuning/04-hood-finder/). --- # Simulator URL: https://crossbotics.com/ftc-helper/docs/cookbook/16-simulator/ The simulator runs your real code on a laptop, with the field in 3D. The easy way to start it is a button in Android Studio (below). Or type the commands in a terminal: in Android Studio, the **Terminal** tab at the bottom ([how](https://crossbotics.com/ftc-helper/docs/setup/09-the-terminal/)). First go into the `ftc-helper-lib` folder by typing `cd ftc-helper-lib`. It is the library's folder inside your robot project, next to `TeamCode` in Android Studio's Project panel. If it is not there, ask your mentor, or see [Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/). `./gradlew` runs Gradle, the tool that builds the code, and `-P...` gives it a setting. **The questions on this page:** - [How do I start the simulator?](#how-do-i-start-the-simulator) - [How do I see my own robot in the simulator?](#how-do-i-see-my-own-robot-in-the-simulator) - [How do I make the simulator draw my part?](#how-do-i-make-the-simulator-draw-my-part) - [How do I test my code with a script?](#how-do-i-test-my-code-with-a-script) ## How do I start the simulator? In Android Studio, pick **Simulator** in the list next to the green Run button, and click Run. If **Simulator** is not in the list, close the project and open it again ([the buttons](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/#the-simulator-buttons-you-do-nothing)). Or, in the terminal: **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:run ``` Then open **http://localhost:8780** in a browser. Choose an OpMode, press INIT, then ▶. To stop the simulator, click the red **Stop** button (or press Ctrl+C in the terminal). **Why:** you can try buttons and autonomous routes before the robot is built. **More:** [Simulator: start it](https://crossbotics.com/ftc-helper/docs/simulator/01-start-and-drive/). ## How do I see my own robot in the simulator? Start the simulator (the **Simulator** button, or `./gradlew :sim:run`). It runs your TeamCode. When it starts, it makes the simulator's robot file from your `Robot.java`, and prints `Robot file made from Robot.java: simulator/robot.properties`. **Why:** the robot file then always matches your code. The simulator keeps your own lines in it. When you change the code, stop the simulator and start it again. **More:** [A robot file from Robot.java](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#2-the-simulator-makes-it-from-robotjava), [Your own robot code](https://crossbotics.com/ftc-helper/docs/reference/robot-file/#the-commands). ## How do I make the simulator draw my part? **Where:** `Robot.java`: add `.looks(...)` to the part's line (optional). ```java title="Robot.java" // For the simulator only. All in mm. atMm(forward, left, up): from the middle of the chassis, on the tiles. (1)! // sizeMm(front to back, side to side, up). chassisMm(400, 400, 100); // the chassis box heightMm(380); // the whole robot, folded // TWO shapes on one part: name each shape, then looks(intakeArm, intakeRoller). // passive(): nothing in the code moves the arm. range: its two hard stops, degrees. (2)! Shape intakeArm = Shape.arm().name("intake_arm").atMm(150, 0, 80).sizeMm(80, 300, 20) .passive().range(-20, 0).startAt(0); Shape intakeRoller = Shape.roller("gobilda-gecko-72").on("intake_arm").atMm(80, 0, 0).lengthMm(300); intake = add(Intake.motor("intake").part("gobilda-5203-1150").looks(intakeArm, intakeRoller)); // ONE shape: write it inside looks(...). A slide at the back; travelMm: how far it rises. lift = add(Lift.slide("lift").part("gobilda-5203-435") .looks(Shape.slide().atMm(-170, 0, 20).sizeMm(40, 40, 300).travelMm(600))); // A claw on top of the slide: on(lift) makes it go up with the slide. claw = add(Claw.servo("claw").part("gobilda-2000-torque") .looks(Shape.claw().on(lift).atMm(60, 0, 300).sizeMm(80, 120, 50))); // A flywheel: its size comes from the wheel's catalog id. Only its place is yours. launcher = add(Launcher.flywheel("launcher", "gobilda-5203-6000") .looks(Shape.flywheel("gobilda-hogback-96").atMm(-40, 0, 200))); ``` 1. The real robot never reads `.looks(...)`. Measure with a tape, or shape the part in the simulator's Edit robot mode and copy the lines it shows. 2. The arm hinges at the front and rests on its stop. The roller rides on the arm's end: `on("intake_arm")`. **One shape or several:** one shape goes inside `looks(...)` on the part's line. For two or more (an arm and its roller), give each a name first (`Shape intakeArm = ...;`), then write `looks(intakeArm, intakeRoller)` ([how](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts)). **Why:** without `.looks(...)`, the simulator still runs, with a guessed box for each part (marked `TODO measure` in the robot file). With it, the 3D view shows your robot, and the size check (18 in start cube, 29 in tall) is right. Pieces also touch the intake where the real one is. Name the part (`.part(...)`) too, so a roller's or a wheel's size comes from the parts catalog. **The easy way:** use the simulator's **Edit robot** mode. Drag and size each part on the 3D robot, then copy the `.looks(...)` lines it shows into `Robot.java`. After a change, stop the simulator and start it again. **More:** [Shapes and parts](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts) (every shape and setting), [A robot file from Robot.java](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#2-the-simulator-makes-it-from-robotjava). ## How do I test my code with a script? A script (a scenario file) presses buttons and checks the robot for you. The easy way is to **record** it. In the simulator, click **Tests > Record a test**, drive, and click **Stop recording**. Keep the ticked checks and click **Save**. The simulator then writes `simulator/scenarios/NAME.sim` for you ([Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/)). Or write one by hand, for example `simulator/scenarios/intake.sim` (the library runs this same file as a test: `sim/scenarios/cookbook-intake.sim`): ```text init "Quick Start TeleOp" # your TeleOp's name start hold g2.rt 1 # hold RT (the intake runs while it is held) expect within 1 motor intake power > 0.5 release g2.rt expect within 1 motor intake power = 0 0.01 expect error none ``` To run every test in the folder, click **Tests > Run all tests** on the simulator page, or the **Simulator tests** button in Android Studio. Or use the terminal (leave out `-Pfile` for every test): **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:scenario -Pfile=../simulator/scenarios/intake.sim ``` It runs your own code (`../TeamCode`, next to the library in your robot project). **Why:** a script checks the same things every time, with no clicking, and catches a mistake before a meeting. A scenario uses the FTC button names, which can differ from the Java names. `g2.rt`, `g2.lb`, `g2.a` are the same, but `g2.dpadUp` is `g2.dpad_up` and `g2.leftStickY` is `g2.left_stick_y`. **More:** [Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/), [Scenario files](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/) (every command and button name). --- # Start it and drive URL: https://crossbotics.com/ftc-helper/docs/simulator/01-start-and-drive/ **You need:** - A laptop with Android Studio ([Install Android Studio](https://crossbotics.com/ftc-helper/docs/setup/02-android-studio/)). - Your robot project with the library in it ([Add the library](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/)). - No project yet? You can start the simulator from the `ftc-helper-lib` folder alone, with the library's example robots ([step 2](#2-or-start-it-in-the-terminal)). It works on Windows, macOS and Linux, and on a Chromebook with Linux turned on. ## 1. Start it with the Simulator button The library adds two buttons to Android Studio when it syncs your project. 1. In the list next to the green Run button, pick **Simulator**. 2. Click Run. 3. When the simulator is ready, the page http://localhost:8780 opens in your browser. No browser opens? Find `Open http://localhost:8780` in the Run window. It is a blue link: click it. The red square **Stop** button stops the simulator. **Simulator tests**, in the same list, runs your tests ([Tests](https://crossbotics.com/ftc-helper/docs/tests/)). The buttons are not in the list? Close the project (**File > Close Project**) and open it again. The buttons need no laptop setup. ## 2. Or start it in the terminal **Why:** the terminal shows every message, and it takes options (for example, another robot file). The first time on a laptop, do the [laptop setup](#laptop-setup-once) below. **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:run ``` `./gradlew` runs Gradle, the tool that builds the code. `:sim:run` is the job: the `run` job of the `sim` (simulator) part. It builds your code, makes the robot file from your `Robot.java` ([Your robot file](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/)), and starts the simulator. Open **http://localhost:8780** in a browser. Press Ctrl+C in the terminal to stop it. **Windows:** type `gradlew.bat` (or `.\gradlew` in PowerShell) instead of `./gradlew`. **With no robot project:** add `-PteamCode=none`. The simulator then runs the library's own examples. ### Laptop setup (once) The library is its own Gradle build, apart from your robot project. So the terminal needs two things, even when the robot project already builds. - **Java.** Gradle needs `JAVA_HOME`: the folder where Java is. Android Studio has its own Java, in its `jbr` folder. Check that the folder exists, then set it. It lasts until you close that terminal. - Mac: `export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"` - Windows PowerShell: `$env:JAVA_HOME = "C:\Program Files\Android\Android Studio\jbr"` No such folder? In Android Studio, open **Settings > Build, Execution, Deployment > Build Tools > Gradle**. The **Gradle JDK** line names the Java that Android Studio uses, with its folder. Use that folder. Still none? Install a JDK 17 or 21 (a **JDK** is Java with the tools that build code), for example Eclipse Temurin from [adoptium.net](https://adoptium.net). You do not need the Java from java.com. - **The Android SDK.** The first command stops with `SDK location not found`? Make a file `ftc-helper-lib/local.properties` with one line: - Mac: `sdk.dir=/Users//Library/Android/sdk` - Windows: `sdk.dir=C\:\\Users\\\\AppData\\Local\\Android\\Sdk` Put your user name in place of ``. Android Studio shows the SDK folder in **Settings > Languages & Frameworks > Android SDK**. **Why:** the library is its own build, so your robot project's `local.properties` does not count. **Warnings you can ignore:** `source value 8 is obsolete`, `SDK processing. This version only understands SDK XML versions up to 3`, `Deprecated Gradle features were used`, `[Incubating] Problems report`. **Android Studio's "Start AGP Upgrade Assistant" note: do not click it.** The FTC SDK sets its own Android build version. An upgrade can break the robot build. Close the note. ## 3. Read the page ![The simulator page: the Driver Hub on the left, the field in 3D in the middle with the gamepads under it, and the Control Hub's panels on the right](https://crossbotics.com/ftc-helper/docs/images/simulator.png) The page has three parts. It fits one laptop screen. On a narrow screen, the parts stack and the page scrolls. - **Left: the Driver Hub.** It looks like the Driver Station app: the battery, gamepad 1 and 2 (lit while used), the **Auto** and **TeleOp** lists, one big button (INIT, then ▶, then STOP), the match time and the telemetry. - **Middle: the field in 3D,** with the gamepads under it. The buttons over it are **View** and **Layers** (how to look), then **Tests**, **Edit robot** and **Auto builder** (what to do). - **Right: the Control Hub.** Its panels show the robot on the field from above, the motors, the servos and switches, the cameras, and the match. Each button at the top shows or hides one panel. The page remembers your choices in this browser: the panels, the view, and whether the gamepads show. ## 4. Run an OpMode 1. Pick an OpMode with the **TeleOp** button (or **Auto**). 2. Press **INIT**. The telemetry shows the OpMode's INIT screen. 3. Press **▶** (the same big button). 4. Press **STOP** when you are done. ![The simulator page while goBILDA's starter bot runs its TeleOp: the Driver Hub shows the running OpMode and its telemetry (time, drive, intake, launcher READY), gamepad 1 is set to Keyboard, and the robot is on the field in 3D and on the map](https://crossbotics.com/ftc-helper/docs/images/sim-teleop-running.png) Like the real Driver Station: - An autonomous stops by itself after 30 s, and a TeleOp after 2:00. A box under the clock turns each timer off. - An error shows in red, with the line where it happened. The same OpMode stays picked, so you can fix the code and press INIT again. - OpModes marked "(hidden on robot)" have `@Disabled`. The simulator shows them anyway. ## 5. Drive Each gamepad has its own source, picked in its list under the 3D view. | Source | How | | --- | --- | | Keyboard | Set the gamepad's list to **Keyboard**. Left stick: W A S D. Right stick: the arrows. D-pad: T F G H. A, B, X, Y: K, L, J, I. LB, RB: Q, E. LT, RT: Z, C. BACK: Backspace. START: Enter. GUIDE: M. Left and right stick click: X, V | | Controller | Plug in a USB or Bluetooth controller and press one of its buttons (a browser rule). Gamepad 1 takes it, or gamepad 2 when gamepad 1 already has one. Xbox, PS4 and PS5 controllers work everywhere. A Logitech F310 works on Windows (on a Mac, set its back switch to "D"). Chrome and Edge work best | | On-screen | Click the buttons, drag the sticks, slide the triggers. **Sticky buttons** (the box under the gamepads): a click holds a button until the next click, so you can hold two things with one mouse | | Phone | Start the simulator with `-Plan` ([options](https://crossbotics.com/ftc-helper/docs/reference/robot-file/#the-commands)). On a phone on the same WiFi, open the address that the page shows, with `?phone=2` at the end. The phone is then gamepad 2 (`?phone=1`: gamepad 1). Set that gamepad's list to **Phone / other page** | **Keep the simulator tab in front while you drive.** A browser tab in the background sends gamepad updates only once a second. After 2.5 s with no news, the simulator lets go of every button, like a pulled cable. **The GUIDE (PS) button** often does not reach the browser, because Windows and macOS keep it. Use the on-screen GUIDE, the M key, or hold START (Enter) for 1 second. The library accepts that too. **`-Plan` on open WiFi:** anyone on that WiFi can open the page and run OpModes. Use it on a team or home network, not on open school WiFi. ## 6. Look around and move the robot **The 3D view:** drag to turn the view, scroll to zoom, and right-drag (or use two fingers) to slide. The **View** menu, or the keys 1 to 8, look from fixed places: | Key | View | | --- | --- | | 1 | Drivers: your alliance's wall (the alliance that the running program uses; red until a program says) | | 2 | Red wall | | 3 | Blue wall | | 4 | Audience side | | 5 | Far side, across from the audience | | 6 | From above, your alliance's wall at the bottom | | 7 | Follow robot, from behind it | | 8 | HIVE close-up: your alliance's HIVE (on a field with no HIVEs: the goal nearest the robot) | ![The View menu open over the 3D field: keys 1 to 8 (Drivers, Red wall, Blue wall, Audience side, Far side, From above, Follow robot, HIVE close-up), then the Show the 3D view and Field CAD model boxes](https://crossbotics.com/ftc-helper/docs/images/sim-view-menu.png) **The robot:** a gray box with a white arrow at the front, plus its parts. It turns red when it bumps into something. A roller glows green while it takes pieces in, and orange while it pushes them out. A flywheel glows yellow while it spins. **Move it by hand:** while no program runs (or in INIT), drag the robot on the field map (Control Hub, **Robot** panel). Turn it with the mouse wheel over it. In the 3D view, double-click the robot, then drag it, or drag its yellow ring to turn it. Under the map, the page shows the spot in the numbers that an autonomous's `s.start(...)` takes. **Push the robot** (Robot panel) rolls it like a hand push, also while a program runs. **Back to start** puts the robot and every game piece back where the match starts them. **Where the robot starts:** INIT of an autonomous starts a new match. The robot goes to the autonomous's start spot, and every piece goes back. A TeleOp's INIT keeps the field as it is, so it goes on from the autonomous. More: [Watch an autonomous](https://crossbotics.com/ftc-helper/docs/simulator/04-watch-an-autonomous/#2-run-it). ## 7. After a code change Stop the simulator and start it again (the **Simulator** button, or `./gradlew :sim:run`). **Why:** the simulator builds your code and makes the robot file only when it starts. The page connects again by itself, so you do not need to reload it. While the simulator is off, a red bar across the top of the page says so. ## Problems | What you see | Why, and the fix | | --- | --- | | No **Simulator** in the Run list | Android Studio has not synced the project since the library came in. Close the project and open it again | | `SDK location not found` | The library's build cannot find the Android SDK. Make `ftc-helper-lib/local.properties` ([laptop setup](#laptop-setup-once)) | | `JAVA_HOME is not set` | Set it in this terminal ([laptop setup](#laptop-setup-once)) | | The page says the simulator stopped | The simulator program ended: you clicked Stop, or closed Android Studio. Start it again | | "press INIT to run it again" under the Driver Hub | The OpMode ended. Press INIT | | The robot does not move with the keyboard | The gamepad's list is not set to **Keyboard**, or the page is not in front. Click the page once, then try again | | The robot drives backward or spins | A motor direction in your code, or the robot file's `drive.mirrored`. See [Your robot file](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#problems) | | The page is slow | Untick **Show the 3D view** in the View menu | ## Done when - The simulator starts, and the page shows your OpModes. - You can INIT and run your TeleOp, and drive the robot with a gamepad or the keyboard. --- **Next:** [Your robot file](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/). **Look it up:** [The commands and their options](https://crossbotics.com/ftc-helper/docs/reference/robot-file/#the-commands). --- # Your robot file URL: https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/ **You need:** - The simulator running ([Start it and drive](https://crossbotics.com/ftc-helper/docs/simulator/01-start-and-drive/)). - A robot in five files ([The five files](https://crossbotics.com/ftc-helper/docs/five-files/)). No five files? See [section 6](#6-a-robot-without-the-five-files). ## 1. What the robot file is The simulator cannot read your robot. It needs to know the device names, the motors and servos, the size of the robot, and where each part sits. The **robot file** holds that, as plain `name = value` lines (a "properties" file). Text after `#` is a note for people. Your robot file is `simulator/robot.properties` in your robot project. The simulator uses it by itself. Commit it with your code. ## 2. The simulator makes it from Robot.java Each time the simulator starts (the **Simulator** button, `./gradlew :sim:run`, or a test run), it first writes the robot file from your Robot class. It prints one line: ```text Robot file made from Robot.java: simulator/robot.properties ``` ![Each start, Robot.java and Tunables.java make simulator/robot.properties, and the simulator reads it. The file has three kinds of lines: from Robot.java (written again at every start), TODO measure (a guess to replace), and your own lines (kept)](https://crossbotics.com/ftc-helper/docs/images/sim-robot-file-flow.svg) It takes these from `Robot.java` and `Tunables.java`: - every device name, as in the robot configuration. - the drive: tank or mecanum, the motors, the wheel, and which side the code reverses. - the motors' and servos' catalog parts (`.part(...)`): speed, encoder counts, range. - each part's limits and positions: a lift's stops, a claw's open and closed. - the odometry and the cameras. - one shape per part, and where game pieces go in and out (the intake, the launcher, the claw). To make the file alone, with no simulator: **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:fromRobot ``` **Why it helps:** it builds your TeamCode first. So it also tells you, with no Control Hub, whether your code builds. ## 3. Read what it guessed Open `simulator/robot.properties`. The top of a small robot's file looks like this: ```properties # The simulator's robot, made from org.firstinspires.ftc.teamcode.Robot (again at each start of the simulator). battery = 12.8 field = biobuzz-2026 # ---- from Robot.java ---- drive.type = mecanum # from Robot.java drive.motors = front_left, front_right, back_left, back_right # from Robot.java drive.part = gobilda-5203-312 # from Robot.java shape.lift = slide, at=-7,0,4, size=2x2x12, axis=up, motor=lift # from Robot.java. TODO measure: place, size and travel (at the back; ...) ``` - **`# from Robot.java`:** the simulator wrote this line, and it writes it again at every start. - **`TODO measure`** after it: a guess. Your code does not say where this part sits. So the simulator put it in a typical place: the intake across the front, a lift at the back, a turret on top in the middle, a claw on the end of the lift or arm. The guesses fit the size rules (the 18 in start cube, 29 in tall). The robot drives and its parts move with the guesses. But the size checks, and where game pieces touch the robot, are guesses too. [Make it match your robot](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/) replaces them. ## 4. Your own lines stay yours You can add lines, or change the simulator's lines. - A line with no `# from Robot.java` note is yours. The simulator keeps it, even for the same setting. - To keep your own number on a simulator line, delete its `# from Robot.java` note. - A `TODO` line keeps a number that you write on it. - When the code changes a marked line, the simulator prints the change and keeps the old file as `robot.properties.bak`. - It removes the lines for parts that are no longer in the code. **Better:** put sizes and places in `Robot.java` (`looks(...)`), not in the robot file. Then `Robot.java` stays the one record of your robot ([Make it match your robot](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/)). ## 5. MEASURE numbers and missing parts **A Tunables number written `MEASURE`** ([DEFAULT and MEASURE](https://crossbotics.com/ftc-helper/docs/reference/tunables/#default-and-measure)) stops INIT on the robot until you measure it. In the simulator, the robot file gets a **stand-in** for it: ```properties tunable.IntakeDeploy.deployed = 0.5 # from Robot.java. Simulator only: a stand-in for MEASURE (the library's default). ... ``` - INIT in the simulator uses 0.5, and says so under the Driver Hub. - The real robot never reads the robot file, so it still stops at INIT. Safety on the robot does not change. - When you write the real number in `Tunables.java`, the code's number wins, and the stand-in line goes. **A part not on the robot yet:** a part marked `optional()` in Robot.java ([parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) is in the robot file anyway. To try the robot as it is today, without the part, add a line of your own: ```properties missing = intake_deploy ``` The simulator then acts like a robot whose configuration does not have that device: INIT says `IntakeDeploy is off`, its buttons are off, and actions skip it. ## 6. A robot without the five files The simulator still runs your OpModes. It needs a robot file that you start in one of these ways: - **A starter bot:** the library has a robot file for each season's starter bot, in `ftc-helper-lib/sim/robots/` ([Starter bots](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/)). Copy the one for your robot to `simulator/robot.properties`. - **From your robot configuration:** copy the configuration file from the Control Hub, then: **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:fromConfig -Pconfig=../my-config.xml -Pout=../simulator/robot.properties ``` It writes every device name, and guesses the rest. - **With an AI coding agent:** the [robot-file skill](https://crossbotics.com/ftc-helper/docs/guides/robot-file-skill/) writes most of it from your configuration, your code and a tape measure. A robot file that you wrote by hand (no "made from" line at the top) does not change when the simulator starts. ## Problems | What you see | Why, and the fix | | --- | --- | | The simulator prints why it wrote nothing, and uses the file as it is | The file describes a device in another way than the code (`motor.claw` in the file, a claw servo in the code), or names other drive motors. Fix one of them, or delete the line from the file | | Stick forward drives the robot backward, or the robot spins | The file's `drive.mirrored` names the wrong side. It must name the side that your code reverses. The simulator writes it from `Robot.java`, so check the drive line there first | | INIT says a Tunables field is not read by any part | A name in `Tunables.java` has a typo. The simulator runs the same name checks as INIT, and prints them after it writes the file, with a "did you mean" | | A part sits in a strange place | It is a guess (`TODO measure`). [Make it match your robot](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/) | | Your number on a line went away | The line had `# from Robot.java`. Delete that note to keep your number, or put the number in `Robot.java` | | No robot file is made | The simulator found no Robot class. It looks for the class that the file names, then `org.firstinspires.ftc.teamcode.Robot`, then any class in TeamCode that extends `RobotDefinition`. Name yours with `-ProbotClass=...` | ## Done when - `simulator/robot.properties` exists in your robot project, and you committed it. - INIT of your TeleOp works in the simulator. - You know which lines say `TODO measure`. --- **Next:** [Make it match your robot](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/). **Look it up:** [The robot file](https://crossbotics.com/ftc-helper/docs/reference/robot-file/): every line, with its default. --- # Make it match your robot URL: https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/ **You need:** - Your robot file, made from `Robot.java` ([Your robot file](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/)). - A tape measure, or your robot's CAD. ## 1. Why match it With guesses, the robot still drives and its parts still move. But three things depend on the real shapes: - **The size rules.** The simulator checks the 18 in start cube and the 29 in height limit, now and with every part out. A guessed lift can pass when the real one does not. - **Game pieces.** A piece goes in where it touches the intake roller, and leaves the launcher at its angle. A roller in the wrong place takes no pieces. - **Bumps.** The robot's parts hit the field. A tall lift can hit an overhead bar. Work in this order. Each step makes the next one count. | Step | What you give | Where | | --- | --- | --- | | [2. Size and wheels](#2-size-and-wheels) | the chassis box, the robot's height, the wheels | `Robot.java` | | [3. The parts](#3-shape-the-parts-with-edit-robot) | where each part sits, and how big it is | **Edit robot**, then `Robot.java` | | [4. Pieces in and out](#4-where-pieces-go-in-and-out) | the intake roller, the launcher's shot angle, the claw | **Edit robot**, then `Robot.java` | | [5. CAD (optional)](#5-cad-models-optional) | your CAD parts in place of the boxes | the robot file | | [6. Real speeds (optional)](#6-real-speeds-optional) | how your motors move | the robot file, from the Characterizer | **Or let an AI coding agent do steps 2 to 5 with you.** The **robot-file skill** is a set of written steps for an agent such as Claude Code or Codex. Give it what you have: - **Photos** of the robot from the side, the top and the front, and of each moving part at both ends of its travel. Put a field tile or a tape measure in each photo, so the agent can read sizes. - **A tape measure.** The agent asks for the few numbers that decide a rule, always from the robot's edges and the floor. - **CAD of the robot,** if you have it. Then the agent reads the exact sizes and draws your real parts. The agent writes the sizes and shapes into `Robot.java`, runs the simulator's checks, and then checks its 3D robot against your photos with you. It marks each number it estimated, so you know what to measure. Your photos stay on your computer. Set it up: [The robot-file skill](https://crossbotics.com/ftc-helper/docs/guides/robot-file-skill/). Check what it wrote the same way as your own work: open **Edit robot** and look at every pose ([step 3](#3-shape-the-parts-with-edit-robot)). ## 2. Size and wheels **How to measure:** measure from the robot's edges and the floor, never from its middle. Take the bumpers off, or measure the frame without them. Put these lines in `define()` in `Robot.java`, after the drive: ```java chassisMm(400, 400, 100); // the chassis box: length front to back, width side to side, height from the tiles heightMm(300); // the whole robot: the tallest part that does not move ``` **The wheels:** give the drive its wheel by catalog id, and where the wheels sit. The simulator then turns the robot like yours. ```java drive(Drive.tank("left_drive", "right_drive").motor("gobilda-5203-312").wheel("gobilda-hogback-96") .wheelsAtMm(380, 290) // wheel centers: side to side, then front to back .reversed("right_drive")); ``` Measure the wheel centers from wheel edge to wheel edge, then add one wheel width: that is center to center. The wheel ids are in the [parts catalog](https://crossbotics.com/ftc-helper/docs/guides/parts-catalog/). ## 3. Shape the parts with Edit robot Typing where each part sits, in mm, is hard. **Edit robot** lets you shape the robot with the mouse. Then it gives you the Java lines for `Robot.java`. The editor writes no file: `Robot.java` stays the one record of your robot. ![Edit robot: the 3D view shows the robot close up inside the see-through 18 in start cube, with a yellow arrow where the launcher's shots leave. The panel lists the shapes (hood, intake, launcher, wheels, tower); launcher is picked, with its place (forward -40, left -5, up 172 mm), its size (length 24, diameter 96 mm), its axis and tilt.](https://crossbotics.com/ftc-helper/docs/images/edit-robot.png) 1. Click **Edit robot** (over the 3D view). The simulator holds still, the field goes away, and the view turns round your robot, close. 2. See-through guides show the size rules: the **18 in start cube**, and the 18 x 24 in box with the **29 in** line. A part that sticks out turns red. The panel says how far, and which way. ![Edit robot with the tower made 520 mm tall: the tower shows red through the top of the dashed 18 in start cube, and the panel says "tower is 103 mm too tall (more than 18 in)" and gives the new robot file line to copy](https://crossbotics.com/ftc-helper/docs/images/sim-edit-robot-red.png) 3. Click a shape to pick it. The panel shows its numbers in mm: its place (`atMm`), its size (`sizeMm`, or length and diameter for a roller), and its angles. 4. Move it to where the part is on your robot: - **Drag** the shape to move it flat. **Shift + drag** moves it up and down. With **Size** on, a drag makes it bigger or smaller. - **Arrow keys** move it forward, back, left and right. **Page Up / Page Down** move it up and down. Each press moves it 1 mm, or 10 mm with Shift. - Or type the numbers. 5. **Check every pose.** Each moving part has buttons for its named positions (`stowed`, `deployed`...) and its hard stops. **Every part out** puts each part at its farthest pose. The panel says whether every pose fits. 6. **Copy into Robot.java.** The panel shows the Java for each part you changed, and where it goes. Click **Copy** (or **Copy all**) and paste it there. Then stop the simulator and start it again. **From your tape measure to the numbers:** the numbers are from the middle of the chassis, on the floor (forward, left, up). Measure each part from the edges, then work them out: - forward = (chassis length / 2) - (part from the front edge) - left = (chassis width / 2) - (part from the left edge) - up = part from the floor ![A 400 x 400 mm chassis from above. The intake roller is 30 mm from the front edge, so forward = 200 - 30 = 170. The flywheel is 250 mm from the front edge and 140 mm from the left edge, so forward = -50 and left = 60](https://crossbotics.com/ftc-helper/docs/images/sim-measure-from-edges.svg) **Try it** puts the changed shapes into the running simulator, in memory only. Click **Back to driving**, and game pieces hit the new shapes. **Undo all** goes back to the robot file's shapes. **Where the lines go in Robot.java:** - **One short shape:** inside `looks(...)` on the line that adds the part: `.looks(Shape.flywheel("gobilda-hogback-96").atMm(-40, 0, 200))`. - **Two or more shapes:** one `Shape` line each, above the line that adds the part. That line then ends with `.looks(intakeArm, roller)`. - **A part that does not move** (a tower, a ramp): `fixed(Shape.box("tower").atMm(...).sizeMm(...));`. Every shape and setting: [Shapes and parts](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts). ## 4. Where pieces go in and out The simulator takes these from your parts, so you only check that they sit right. - **The intake:** a piece comes in where it touches the intake's roller while the roller turns inward. Put the roller where it touches the pieces: across the front, low. `holds(n)` sets how many pieces the robot holds. More rollers on one intake (`looks(arm, roller1, roller2)`): a piece comes in at any of them. - **The launcher:** a shot leaves its flywheel shape at the **shot angle**: degrees up from the robot's front (90 = straight up, more than 90 = out of the back). Edit robot shows it as a yellow arrow. Put it in `Robot.java` with `.shotAngle(...)`. A ramp or hood shape does not change the angle: the arrow does. A launcher with a hood takes its angle from the hood. - **The claw:** it holds a piece in its fingers while it is closed, and drops it when it opens. After a change, run your autonomous again ([Watch an autonomous](https://crossbotics.com/ftc-helper/docs/simulator/04-watch-an-autonomous/)) and watch the pieces. ## Worked examples Each common setup has a robot that already matches. Open its file and copy what fits your robot. | Setup | Look at | It shows | | --- | --- | --- | | A season's starter bot (goBILDA, REV, AndyMark, Studica) | its robot file in `ftc-helper-lib/sim/robots/starter-bot-*.properties` | a robot file written from the seller's CAD: size, wheels, intake rollers and spinners, launcher, a fixed hood and tower. For teams with no five files ([Starter bots](https://crossbotics.com/ftc-helper/docs/guides/starter-bots/)) | | An intake on a folding arm, and a flywheel launcher | [`flywheelbot/Robot.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/flywheelbot/Robot.java) | `chassisMm`, `heightMm`, a servo that pushes the intake arm over at ▶ (`dropsWhen`), a roller on the arm, a flywheel and its `shotAngle` | | A lift with a wrist and a claw | [`v2bot/Robot.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/main/java/com/crossbotics/ftchelper/examples/v2bot/Robot.java) | a slide in a back corner, the wrist riding on the lift (`on(lift)`), the claw on the wrist | | A drive only (odometry, Pedro, the quick start) | `chassisMm` and `heightMm`, and the drive's `wheel(...)` and `wheelsAtMm(...)` | [step 2](#2-size-and-wheels) is all it needs | ## 5. CAD models (optional) A team with CAD (Onshape, Fusion, SolidWorks) can draw its real parts in place of the boxes. The size rules then use the CAD's shape too. The physics and the game pieces still use the boxes, so do steps 2 to 4 first. 1. **Put the CAD robot in its start pose:** each lift and arm where the simulator shows it when it opens, and each servo part at its start position. 2. **Make the robot's center on the floor easy to find.** In the assembly, place the drive frame so the CAD origin is the middle of the drive frame, at the bottom of the wheels. Then write `cad.origin = 0,0,0`. Otherwise, measure that point from the origin and write it in CAD units. 3. **Export each group of parts that move together as one STL file,** in the assembly's positions. The chassis and everything fixed to it is one group. The lift's moving stage and what rides on it is another. - **Onshape:** work in the **Assembly** tab, not a Part Studio. Select every part of the group, then right-click > Export. Choose STL, and untick "Export unique parts as individual files". - **Fusion:** hide every part that is not in the group. Right-click the top component > Save As Mesh, STL, one file. 4. **Name the files in the robot file.** Put them in a `cad` folder next to it: ```properties cad.units = mm # the unit in the export window: mm, cm, m or in cad.axes = y,-x,z # the CAD axes that point the robot's forward, left and up cad.origin = 0,0,0 # the robot's center on the floor, in CAD units robot.model = cad/chassis.stl # drawn in place of the chassis box shape.lift = slide, ..., model=cad/lift-stage.stl, baseModel=cad/lift-base.stl ``` `cad.axes`: Onshape and SolidWorks have up = z (front along +y: `y,-x,z`). Fusion usually has up = y (front along +x: `x,-z,y`). 5. **Check it:** run a scenario with `print cad` ([Scenario files](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/)). It lists each model next to the box it covers. "FAR from its box" means `cad.origin`, `cad.axes` or the shape's place is wrong. "25 times smaller" means `cad.units` is wrong. Every CAD setting: [The robot file: CAD](https://crossbotics.com/ftc-helper/docs/reference/robot-file/#cad-models). CAD from a seller belongs to the seller: keep it in your team's own repository, not a public one, unless the seller allows it. ## 6. Real speeds (optional) The simulator moves each motor from the catalog's numbers. To make it move like YOUR robot, measure it: 1. Run the **Characterizer** on the real robot ([Characterizer](https://crossbotics.com/ftc-helper/docs/tuning/15-characterizer/)). 2. Copy its logs from the Control Hub (`/sdcard/FIRST/ftc-helper/characterizer/*.csv`) into a folder on the laptop. 3. Fit them: **Where:** Android Studio's **Terminal** tab, in the **`ftc-helper-lib` folder** (type `cd ftc-helper-lib` first). ```bash ./gradlew :sim:fit -Plog=../characterizer-logs -Pwrite ``` It writes the numbers into your robot file, and keeps the old file as `robot.properties.bak`. It leaves out a poor fit, and says so. Check the file and commit it. ## Problems | What you see | Why, and the fix | | --- | --- | | A part is red in Edit robot | It sticks out of the size box. Move it, or make it smaller. On the real robot, it would fail inspection too | | "Nothing may go below the tiles" | A shape or a hard stop reaches under the floor. The shape's place or the part's range is wrong | | The intake takes no pieces | The roller does not reach the pieces. Move it lower and farther forward, and check that it turns inward | | Shots go the wrong way | The shot angle. 90 is straight up. A launcher that shoots over the back needs more than 90 | | The pasted Java does not build | A line went in the wrong place. One shape goes inside `looks(...)`; named shapes go above the part's line | | Your shapes went away after a restart | You did not paste them into `Robot.java`. **Try it** is in memory only | | The CAD robot is mirrored or on its side | `cad.axes` is wrong. The simulator refuses a choice that draws the robot mirrored | ## Done when - No line in your robot file says `TODO measure`. - Edit robot shows every pose inside the size box. - Your intake takes pieces, and your launcher's shots go toward the goal. --- **Next:** [Watch an autonomous](https://crossbotics.com/ftc-helper/docs/simulator/04-watch-an-autonomous/). **Look it up:** [Shapes and parts](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#shapes-and-parts) in Robot.java. [The robot-file skill](https://crossbotics.com/ftc-helper/docs/guides/robot-file-skill/): an AI agent that does this with you. [The robot file](https://crossbotics.com/ftc-helper/docs/reference/robot-file/): every line. --- # Watch an autonomous URL: https://crossbotics.com/ftc-helper/docs/simulator/04-watch-an-autonomous/ **You need:** - An autonomous in your code ([The autos](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/)). - The simulator running your code ([Start it and drive](https://crossbotics.com/ftc-helper/docs/simulator/01-start-and-drive/)). - Your robot's size and parts in the robot file. Guesses work for a first look ([Make it match your robot](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/)). ## 1. Why watch it in the simulator A practice field is busy, and a bad route can hit a wall at full speed. In the simulator, you see the whole route, the score and the report in 30 seconds, and nothing breaks. Fix what you see, then try it on the real field. The simulator is not the real robot. Its speeds and shots are a model. A route that works here is a route worth trying, not a route that is done. ## 2. Run it 1. Pick your autonomous with the **Auto** button on the Driver Hub. 2. Press **INIT**. The simulator starts a new match: every game piece goes back to its start, the preload goes into the robot, and the robot goes to its start spot. 3. Choose the alliance in the INIT menu (X for BLUE, B for RED, as the screen says). 4. Press **▶**. The autonomous runs, and stops after 30 s. ![The Driver Hub in INIT of goBILDA's starter bot autonomous: the place-the-robot note, the INIT menu with Alliance RED, start delay and profile, and "X = BLUE B = RED"](https://crossbotics.com/ftc-helper/docs/images/sim-auto-init.png) **Where the robot starts:** - An autonomous that gives its start in inches (`s.start(note, x, y, heading)`) puts the robot there, for the alliance you chose. - An autonomous that gives its start only in words (`s.start(note, heading)`) puts the robot on your alliance's side. The Driver Hub asks you to drag the robot to the exact spot. At ▶, the simulator remembers that spot for this autonomous, so the next INIT puts the robot there. **Then TeleOp:** pick your TeleOp and press INIT. The robot stays where the autonomous left it, and the score goes on, like a match. ## 3. Watch the route - **The green line** is where the robot actually went, in its last 30 seconds of driving. - **The orange dashed line** is the path that a Pedro `follow` step plans. It stays, faded, after the step ends, so you can compare the plan with the green line. - The robot turns **red** when it bumps into something. The Control Hub's Robot panel names what it hit. **Clear lines** (Robot panel) clears both lines. The **Layers** button over the 3D view adds more: | Layer | What it shows | | --- | --- | | Path lines | the Pedro plan and the green trail | | Shot arc | where the launcher would send its next piece now, with its peak height | | Ball trails | the last half second of each loose ball's path | | Camera sight lines | which tags the camera sees now, and why it does not see the others | | Robot size box | everything the robot has out now: green while it fits, red when not | ![The Layers menu open over the 3D field, with a box for each layer and the color key for the camera sight lines](https://crossbotics.com/ftc-helper/docs/images/sim-layers-menu.png) Every layer: [How the simulator works: Layers](https://crossbotics.com/ftc-helper/docs/guides/how-the-simulator-works/#layers). ## 4. Watch the score The **score bar** over the 3D view shows RED and BLUE, the period (AUTO, TELEOP, FINAL) and the time left. Click it to open the **Match** panel. - **The score counts like a referee.** Points that change all match long (pieces in goals, parking) show gray, as "+N", until the end. The gray number shows what those points would add if the match ended now. - **Click a side** to see where its points come from, grouped like FIRST's score calculator. - **Shots** lists each shot's verdict: clean, rim, other HIVE, frame or miss. - **Fouls** lists each foul that the simulator can see. ![The Match panel after goBILDA's starter bot autonomous: RED 3 (+10), AUTO done, BLUE 0 (+10); the four FLOWERs with their pieces; Shots: 4 of 4 shots were a miss; no fouls](https://crossbotics.com/ftc-helper/docs/images/sim-match-panel.png) In this run, all 4 shots missed: the starter bot's numbers are not tuned. That is what the panel is for. The simulator is not a referee. It counts what it can see, and it plays without the other three robots. What it counts: [Game rules and the score](https://crossbotics.com/ftc-helper/docs/guides/how-the-simulator-works/#game-rules-and-the-score). ## 5. Read the report When the autonomous ends, the Driver Hub shows `Autonomous finished` and one line per step: ```text Start: done To the goal: done Score high: timed out Park: done ``` ![The Driver Hub after the autonomous: Autonomous finished, then Start: done, Fire all: done (4 fired), Away from the wall: done](https://crossbotics.com/ftc-helper/docs/images/sim-auto-report.png) Write down each step that does not say `done`, and fix it: | The report says | Look in the simulator | The fix | | --- | --- | --- | | `STALLED` | where the robot turned red | the route hits a field part. Move the route away from it | | `timed out` on an action | the part on the robot: did it get there? | the part is slow, or its numbers are off. Check the part's Tunables | | `cut short (time for park)` | the clock | the autonomous is too long. Remove a step, or drive faster | | `not seen` | the Camera sight lines layer | the camera does not see the goal from there. Aim from another spot | | `done`, but the robot ends in the wrong place | the green line against your plan | the numbers in the steps. On the real robot: tune the drive first | Every word in the report: [Match day: read the report](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/#after-the-match-read-the-report). ## 6. Change it, run it again 1. Change the steps in your autonomous. 2. Stop the simulator and start it again. **Why:** it builds your code only when it starts. 3. Run the autonomous again, and compare. **Faster for routes:** the [auto builder](https://crossbotics.com/ftc-helper/docs/building-autos/06-auto-builder-steps/) runs a plan with your real code with one click, and shows each step's result next to the plan. Copy its Java into your code when the route is right. **Keep it working:** when the autonomous does what you want, record a test of it ([Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/)). The test then checks it after every change. ## Problems | What you see | Why, and the fix | | --- | --- | | The robot does not move at ▶ | The INIT screen has an error, or the INIT menu still waits for a choice. Read the Driver Hub | | The robot starts in the wrong place | The autonomous gives its start in words only. Drag the robot to the spot in INIT, or give the start in inches | | The robot drives a mirror route on RED | Autos are written for BLUE, and the library changes them for RED. Check `mirrorForRed()` ([Red and blue](https://crossbotics.com/ftc-helper/docs/building-autos/02-put-steps-together/#red-and-blue)) | | The score stays at 0 | The field has no rules file, or the pieces did not reach a goal. Watch the Shot arc layer | | A shot falls short in the simulator but not on the robot | The simulator's shots are a model. Make a shot table ([How shots fly](https://crossbotics.com/ftc-helper/docs/guides/how-the-simulator-works/#how-shots-fly-and-shot-tables)), or trust the real robot | | The route is right here, but wrong on the real robot | The real robot's numbers differ. Tune it ([Tuning](https://crossbotics.com/ftc-helper/docs/tuning/)), and measure its speeds for the simulator ([Real speeds](https://crossbotics.com/ftc-helper/docs/simulator/03-make-it-match-your-robot/#6-real-speeds-optional)) | ## Done when - Each of your autonomous programs runs in the simulator, and every step says `done`. - You know what each one scores. - Each one has a test ([Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/)). --- **Next:** [Tuning](https://crossbotics.com/ftc-helper/docs/tuning/). **Look it up:** [Steps](https://crossbotics.com/ftc-helper/docs/reference/steps/): every step an autonomous can use. **Go deeper:** [How the simulator works](https://crossbotics.com/ftc-helper/docs/guides/how-the-simulator-works/). --- # Record a test URL: https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/ **You need:** - A robot that drives and has an autonomous ([The autos](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/)). - Your robot project with the simulator running your code: the **Simulator** button in Android Studio, or `./gradlew :sim:run` ([the simulator guide](https://crossbotics.com/ftc-helper/docs/simulator/01-start-and-drive/)). - No project yet? Try it first with goBILDA's starter bot ([Run all your tests: try it](https://crossbotics.com/ftc-helper/docs/tests/02-run-all-your-tests/#try-it-with-gobildas-starter-bot)). ## 1. Why tests? You change one number for the lift, and the autonomous stops scoring. You find out at the next event. A **test** finds it on your laptop, before the robot does. It does what a driver does (INIT, ▶ on the Driver Hub, sticks, buttons), then checks the result ("the autonomous finished", "4 pieces were shot"). A test does not prove that the robot is good. It proves that **what worked yesterday still works today**. It finds the break you did not mean to make: a typo, a wrong button, a number changed in the wrong section. ![Record once, choose checks, save, then run after each change. PASSED: go on. FAILED: if you changed it on purpose, update the test; if not, fix the code](https://crossbotics.com/ftc-helper/docs/images/tests-cycle.svg) ## 2. Record a test 1. Start the simulator with your code and open http://localhost:8780. 2. Open **Tests** (in the row of buttons above the 3D field, next to **View** and **Layers**) and choose **Record a test**. A red bar says `Recording`. The field starts fresh: the robot on its start spot, every game piece back, your numbers as in `Tunables.java`. **Why fresh:** the test always starts this way, so you must record it this way too. ![The Tests menu, open: Record a test, Record from now, Open a test, Run all tests](https://crossbotics.com/ftc-helper/docs/images/tests-menu.png) 3. Choose your OpMode and press **INIT**. In the INIT menu, choose the alliance (gamepad 1 **B** for RED, **X** for BLUE). On the keyboard (set gamepad 1's list to "Keyboard"), B is the **L** key and X is the **J** key. Or click B or X on the on-screen gamepad 1. ![Recording: the red bar with Recording 0:25, Stop recording and Cancel. The Driver Hub is in INIT with the alliance menu (X = BLUE, B = RED)](https://crossbotics.com/ftc-helper/docs/images/tests-recording.png) 4. Press **▶** and do the job, as in a match: drive to a piece, pick it up, shoot. For an autonomous, do nothing, and let it run to its end. 5. Press **Stop recording** in the red bar. A window opens: **Your test: choose the checks**. ![Your test: choose the checks. Goal checks are ticked (the autonomous finishes, steps done, pieces shot, points, no error, not pushing a wall). Details are not ticked (the end spot, the heading, screen lines). Then the name and Save (here Download, with no robot project) and Run it now](https://crossbotics.com/ftc-helper/docs/images/tests-choose-checks.png) 6. Leave the ticked checks ticked ([section 5](#5-check-goals-not-details) says why). Type a name, for example `main-teleop`, and press **Save**. The test is now `simulator/scenarios/main-teleop.sim` in your robot project. To find it in Android Studio's Project panel, open the top folder (the one that holds `TeamCode`), then `simulator`, then `scenarios`. Commit it with your code ([Every practice: pull, change, commit, push](https://crossbotics.com/ftc-helper/docs/setup/08-every-practice/)). 7. Press **Run it now**. The simulator plays your test back from a fresh field and shows **PASSED**, or **FAILED** with the line that failed. Keep your hands off, because the test drives. ![PASSED, with the report line by line: each step and each check says ok](https://crossbotics.com/ftc-helper/docs/images/tests-passed.png) The recorder writes down every gamepad button and stick (from the keyboard, a real controller or the on-screen gamepad). It also writes down how long you waited, INIT, ▶, STOP, and the robot or a piece moved by hand. - A quick tap becomes a `press`. - A button held down becomes `hold` and `release`. - A stick becomes `hold g1.left_stick_y -0.5`, in steps of 0.25. **Why:** nobody holds a stick at exactly 0.53 twice. **Record from now** (in the same menu) starts from where the robot is, without a fresh field. Use it for a quick try. A test that starts from INIT is more reliable. ## 3. Read the test, line by line A test is a short text file that you can read and change. The recorder made this test for goBILDA's starter bot's autonomous ([`sim/scenarios/recorded-gobilda-auto.sim`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/sim/scenarios/recorded-gobilda-auto.sim)): ```text # recorded-gobilda-auto.sim: made by the simulator's test recorder on 2026-10-22, from "goBILDA Bot Launch and Back Up". init "goBILDA Bot Launch and Back Up" wait 1 press g1.b wait 0.92 start # The checks expect within 6 phase STOPPED expect within 3 launched >= 4 expect within 3 points "red" >= 13 expect step 1 done expect step 2 done expect error none expect bumped none ``` | Line | What it does | | --- | --- | | `# ...` | a note for people; the test skips it | | `init "goBILDA Bot Launch and Back Up"` | INIT this OpMode (the name exactly as on the Driver Station) | | `wait 1` | wait 1 second (the recorder cuts waits before ▶ to 1 s, because they change nothing) | | `press g1.b` | press and let go of gamepad 1's B: RED in the INIT menu | | `start` | press ▶ | | `expect within 6 phase STOPPED` | **a check:** within 6 s, the OpMode stops by itself (the autonomous ends). The **phase** is where the OpMode is: `IDLE` before INIT, then `INIT`, `RUNNING` (after ▶) or `STOPPED` | | `expect within 3 launched >= 4` | within 3 s, at least 4 pieces were shot | | `expect within 3 points "red" >= 13` | RED has at least 13 points | | `expect step 1 done` | the first step of the autonomous's report says `done` ([the report](https://crossbotics.com/ftc-helper/docs/five-files/05-autos/#what-you-get-with-no-extra-code)) | | `expect error none` | no error on the Driver Station | | `expect bumped none` | the robot does not push against a wall or a field element at the end | Every `expect` line is a check. The test **passes** when every check passes. The report shows each line as `ok` or `FAIL`, with the value it saw: `FAIL 13 expect within 3 launched >= 4 -> was 2`. ## 4. How close is close enough? Tolerances A robot never stops at exactly the same spot twice, not even in the simulator. So a check says how close is close enough: | Check | What it checks | Use it for | | --- | --- | --- | | `expect robot y = -36 3` | y is -36, give or take 3 inches (from -39 to -33) | where the robot ends | | `expect robot heading = 90 5` | 90 degrees, give or take 5 | which way it faces | | `expect launched >= 4` | 4 or more | counts: pieces, points | | `expect time < 25` | less than 25 s since ▶ | "fast enough" | | `expect within 4 stored >= 1` | wait up to 4 s for it to become true | anything that takes time | The number after `=` is the value. The next number is the **tolerance**: how far off it may be. Without a tolerance, `=` means exactly, and that almost never works for a measured number. ![A number line for expect robot y = -36 3: from -39 to -33 is close enough. A robot that ends at -34.5 passes; one that ends at -40.5 fails](https://crossbotics.com/ftc-helper/docs/images/tests-tolerance.svg) The recorder picks loose numbers: 3 inches, 5 degrees, `>=` for counts, and `within` 1.5 times the time it took. - **A test that is too strict** fails for no reason, and soon nobody trusts it. - **A test that is too loose** never fails, even when the robot is broken. If a test fails now and then for no reason, make the tolerance a little bigger: in the window before you save, or in the file. ## 5. Check goals, not details The window shows two lists: - **Goal checks** (ticked): what the test is for. The autonomous finishes, its steps are done, the pieces are shot or scored, and there is no error. For a driving test with no pieces: where the robot ends. - **Details** (not ticked): the exact spot after an autonomous, the time, lines on the Driver Station screen. Tick one only if it is what you want to test. **Why:** a detail changes every time you improve something. A test that checks "the screen says `Launcher : 2600 rpm`" fails when you tune the speed, but nothing is broken. A test that checks "4 pieces were shot" fails only when the shooting is broken. Fewer, better checks make a test you trust. ## 6. A few good tests You do not need many tests. Start with these: - **One test per autonomous.** Its goal: it finishes, every step is `done`, and it scores. - **TeleOp basics:** drive forward and turn (the robot ends near the spot). Add one test for each job the drivers use most (pick up a piece: `stored >= 1`; shoot: `launched >= 1`). That is 3 to 5 tests. When a bug surprises you, add a test for it. Then it cannot come back without a warning. ## 7. After a planned change: update the test Say you made the robot faster on purpose. Now the TeleOp test fails, because the robot ends 12 inches further than the test says. The robot is right, and the test is out of date. 1. Choose **Tests > Open a test**, choose the test, and press **Run it now**. It shows FAILED. 2. Read the failed lines, and decide whether you meant to change this. - **Not on purpose:** the test caught a break. Fix the code, not the test. - **On purpose:** press **The change was on purpose: update the test**. ![FAILED: 1 check. The red line: expect within 3 points "red" >= 30, was 13.00. Below: The change was on purpose: update the test, and Run it again](https://crossbotics.com/ftc-helper/docs/images/tests-failed.png) 3. The simulator runs the test once more and measures. It shows each failed check with its old and its new number. Only the failed checks change. The steps, the tolerances and the other checks stay. 4. Press **Save the update**, then **Run it again**. It shows PASSED. A check of words (`phase`, `step`, `screen`) cannot take a new number. The window lists it, and you change it or delete it by hand. The file gets a note with the date and the lines that changed. The old numbers are in git. ## 8. Write or change a line by hand (optional) A test is plain text, so you can add a line the recorder did not write. Open the file in Android Studio (`simulator/scenarios/`) and type it. For example, check that the claw is closed: ```text expect servo claw target = 0.75 0.01 ``` **A number you have not measured yet.** A `MEASURE` in `Tunables.java` stops INIT on the robot, but not in the simulator. When the simulator starts, it puts a stand-in for it in the robot file (`tunable.IntakeDeploy.deployed = 0.5`), and the simulator uses that ([MEASURE in the simulator](https://crossbotics.com/ftc-helper/docs/simulator/02-your-robot-file/#5-measure-numbers-and-missing-parts)). So most tests need nothing for it. For another number, put this line before `init`. The test then uses 0.6, for this file only, and your code does not change: ```text set tunable IntakeDeploy.deployed 0.6 ``` **Button names in a test are the FTC names, not the Java names:** `g2.dpadLeft` in `Controls.java` is `g2.dpad_left` in a test. ## Fix a problem | What you see | Why, and the fix | | --- | --- | | The test fails on the first run after recording | Something in the run was not the same: a check is too strict ([section 4](#4-how-close-is-close-enough-tolerances)), or the robot still moved when you stopped recording. Loosen the tolerance, or record again and wait a moment before **Stop recording** | | `FAIL ... robot y = ... 3 -> was ...`, a little more than 3 off | A fast robot ends a few inches off from run to run. Make the tolerance 5 | | It fails now and then, then passes | The same cause: the check is too strict. A test you cannot trust is worse than no test | | `true only after 5.3 s` | It happens, but later than `within` allows. If the robot is slower on purpose, update the test ([section 7](#7-after-a-planned-change-update-the-test)) | | `waited 3 s: the OpMode shows nothing in INIT` | The OpMode sends no telemetry in INIT, so the test cannot count its loops. It still runs | | `unknown command`, or a check says `too short` | A line typed by hand has a mistake. The report names it. See [Scenario files](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/) | | The page says `a test is running` | A test drives the robot. Wait for it, or press **Stop the test** in the blue bar | | Save says `no robot project` | The simulator was started with `-PteamCode=none`. Press **Download**, and put the file in your robot project's `simulator/scenarios` folder | | The auto builder's Run is not in the test | A test runs your own OpModes. Copy the builder's plan into your code (its Code tab), then record that autonomous | ## Done when - Each autonomous has a test, and it passes. - One TeleOp test drives and does the drivers' main job, and it passes. - The tests are in `simulator/scenarios`, committed with your code. --- **Next:** [Run all your tests](https://crossbotics.com/ftc-helper/docs/tests/02-run-all-your-tests/). **Look it up:** [Scenario files](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/): every command and check. [Record a test](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/#the-recorder): the recorder. --- # Run all your tests URL: https://crossbotics.com/ftc-helper/docs/tests/02-run-all-your-tests/ **You need:** - At least one test in your robot project's `simulator/scenarios` folder ([Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/)). - Or no project yet: [try it with goBILDA's starter bot](#try-it-with-gobildas-starter-bot). ## 1. Run them all Each of these three ways runs every test in your `simulator/scenarios` folder: - **On the simulator page:** **Tests > Run all tests**. The page shows passed or failed for each test, with the failed lines. Click a test's name to open it. ![The Tests menu, open, with Run all tests at the bottom](https://crossbotics.com/ftc-helper/docs/images/tests-menu.png) - **In Android Studio:** pick **Simulator tests** in the list next to the green Run button, and click Run. If the list has no such button, close the project and open it again ([the simulator buttons](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/#the-simulator-buttons-you-do-nothing)). - **In the Terminal:** **Where:** the Terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:scenario ``` Each test starts from a fresh robot, so nothing carries over from one test to the next. The button and the command end with a list (paths shortened here): ```text == 3 of 3 passed PASSED ../simulator/scenarios/launch-and-back-up.sim PASSED ../simulator/scenarios/main-teleop.sim PASSED ../simulator/scenarios/pick-up.sim ``` - **The button and the command build your code first,** and make the robot file from `Robot.java`. - **The page runs the code that the simulator started with.** So after a code change, stop the simulator and start it again before you press **Run all tests**. ## 2. Run one test **Where:** the Terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:scenario -Pfile=../simulator/scenarios/main-teleop.sim ``` For several files, put commas between them: `-Pfile=a.sim,b.sim`. A folder runs every `.sim` file in it. ## 3. When to run them - **Before you commit:** a failed test means the change broke something. - **Before every event:** run them all on the code you will take. - **After you change a number in `Tunables.java`:** a test that fails tells you which job the number changed. The simulator's own automatic tests (`./gradlew :sim:testDebugUnitTest`) also run every file in your `simulator/scenarios` folder. ## 4. For programmers: laptop tests in Java (optional) A simulator test drives the whole robot, in real time. A **JUnit test** checks one piece of your code in a fraction of a second, with pretend motors and servos. For example: "after `Actions.scoreHigh`, the lift was sent to 2400 counts". **Where:** the Terminal, in your robot project's folder (the one that holds `TeamCode`). ```bash ./gradlew :TeamCode:testDebugUnitTest ``` - **It can check:** INIT's checks (a misspelled Tunables field, a missing safety number, a device used twice), which power or position each command sends, limits, interlock rules, pause and STOP, and your own `Actions.java` steps that do not wait. - **It cannot check:** how the real robot moves (gravity, a heavy lift, a slipping belt), anything that waits for time to pass (an action's `waitSeconds`), or cameras. Use a simulator test for those, and the [checks on the real robot](https://crossbotics.com/ftc-helper/docs/tests/03-checks-before-practice-and-matches/). JUnit tests need a little Java. How to set up TeamCode once, and a first test of your robot in five files: [Tutorial 13: Testing](https://crossbotics.com/ftc-helper/docs/tutorials/13-testing/#7-test-your-robot-in-five-files). The pretend devices: [the test kit](https://crossbotics.com/ftc-helper/docs/modules/testkit/). A complete example: [`V2botTest.java`](https://github.com/crossbotics/ftc-helper-lib/blob/v0.47.0/examples/src/test/java/com/crossbotics/ftchelper/examples/v2bot/V2botTest.java). ## Try it with goBILDA's starter bot With no robot project yet, try the recorder and the runner with goBILDA's starter bot. **Where:** the Terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:run -PteamCode=none -Probot=sim/robots/starter-bot-gobilda.properties ``` 1. Open http://localhost:8780. Choose **Tests > Record a test**. 2. Choose "goBILDA Bot Launch and Back Up", press INIT, press gamepad 1 **B** (RED; the **L** key on the keyboard), then ▶. Wait until the Driver Station says `Autonomous finished`. 3. Press **Stop recording**. Look at the goal checks: it finishes, steps 1 and 2 are done, and 4 pieces are shot. 4. With `-PteamCode=none` there is no robot project, so **Download** saves the file in your browser's downloads. Press **Run it now**, and it shows PASSED. 5. Run the same test without the page. This runs the library's own copy of the test (in `sim/scenarios`), not the file you downloaded. **Where:** the Terminal, in the `ftc-helper-lib` folder. ```bash ./gradlew :sim:scenario -PteamCode=none -Pfile=sim/scenarios/recorded-gobilda-auto.sim ``` 6. Record a TeleOp test the same way: "goBILDA Bot TeleOp", B, ▶. Hold the left stick forward for a second, let go, and press **Stop recording**. The goal is where the robot ends. ## Fix a problem | What you see | Why, and the fix | | --- | --- | | A test passes on the page but fails with the button or the command | The page runs the code the simulator started with. Stop the simulator, start it again, and run the test on the page again | | `No scenario file. Use: ./gradlew :sim:scenario -Pfile=...` | The command found no `simulator/scenarios` folder. Check that it is in the folder that holds `TeamCode`, and that it has a test | | `PROBLEM: no such file: ...` | A wrong `-Pfile` path. Paths start from the `ftc-helper-lib` folder: `../simulator/scenarios/...` | | **Simulator tests** is not in the Run list | Close the project and open it again ([the simulator buttons](https://crossbotics.com/ftc-helper/docs/setup/04-add-the-library/#the-simulator-buttons-you-do-nothing)) | | A test failed, and you did not change that part | Read the failed line: it names the check and the value it saw. Fix the code, or update the test if the change was on purpose ([Record a test, section 7](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/#7-after-a-planned-change-update-the-test)) | | More problems with one test | [Record a test: fix a problem](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/#fix-a-problem) | ## Done when - One button or one command runs all your tests, and they pass. - You run them before each commit, and before each event. --- **Next:** [Checks before practice and matches](https://crossbotics.com/ftc-helper/docs/tests/03-checks-before-practice-and-matches/). **Look it up:** [Scenario files](https://crossbotics.com/ftc-helper/docs/reference/scenario-files/): every command, check and flag. **Go deeper:** [Tutorial 13: Testing](https://crossbotics.com/ftc-helper/docs/tutorials/13-testing/): JUnit tests on the laptop. --- # Checks before practice and matches URL: https://crossbotics.com/ftc-helper/docs/tests/03-checks-before-practice-and-matches/ **You need:** - A robot that runs your code, and the **Tune and check** OpMode on it (its Hardware Check: [Wiring checks](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/)). - A block to put the robot on, so the wheels are off the floor. - The whole team: programmers, builders and drivers. ## 1. A fixed order
flowchart LR
    A["Laptop tests"] --> B["Hardware Check<br/>robot on a block"]
    B --> C["Mechanism checks"]
    C --> D["Floor check<br/>low power"]
    D --> E["Autonomous runs<br/>read the report"]
    E --> F["Event: before every match"]
Do the steps in this order. Each step finds problems that would be dangerous or confusing in the next step. For example, the Hardware Check finds a reversed drive motor at once. On the floor, the same motor looks like "the robot spins for no reason". | Step | When | | --- | --- | | 2. Laptop tests | after every code change | | 3. Hardware Check | after any change to the wiring or the robot configuration | | 4. Mechanism checks | after you build or change a mechanism | | 5. Floor check | before practice runs | | 6. Autonomous check | after a change to an autonomous | | 7. Before every match | at an event | ## 2. Laptop tests (every code change) Run all your simulator tests, and your JUnit tests if you have them ([Run all your tests](https://crossbotics.com/ftc-helper/docs/tests/02-run-all-your-tests/)). They need no robot. **Without tests:** run the OpMode in the [simulator](https://crossbotics.com/ftc-helper/docs/simulator/) first. It shows many problems before you touch the robot: a crash at INIT, a wrong button, a screen that does not fit. The simulator builds its robot from your code, so it cannot find a wrong wire or a motor that turns the wrong way. Only the real robot can. ## 3. Hardware Check (after a wiring or configuration change) Run the **Hardware Check** in Tune and check, with the robot on a block ([how to get there](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#get-to-the-checks)). It lists every device in the active configuration and the battery voltage. Check each device: | Device | Check | If wrong | | --- | --- | --- | | every motor | moves with positive power the way you expect, and its encoder counts UP | `.reversed()` on its part in `Robot.java`; check the encoder cable port | | drive motors | each wheel rolls FORWARD with positive power ([Motor Direction Check](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#motor-direction-check-each-wheel-rolls-forward)) | `Drive.mecanum(...).reversed("front_left", ...)` in `Robot.java` | | every motor with an encoder | its own port counts, up ([Encoder Check](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#encoder-check-each-encoder-cable-in-its-own-port)) | the encoder cable in its own motor's port, plugged in | | a lift or arm on two motors | with the chain or belt OFF, both turn the way that lifts | `alsoMotor` / `alsoMotorReversed` ([two motors](https://crossbotics.com/ftc-helper/docs/reference/parts/lift/#two-motors-on-one-lift-or-arm)) | | servos | find and write down each position you need ([Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/)) | the named positions in `Tunables.java` | | CR servos | spin both ways | the configuration must say "Continuous Rotation Servo" | | touch and magnetic switches | change when pressed, or with a magnet near | wiring; magnetic: false = near | | IMU | yaw (the heading) goes UP when the robot turns LEFT | the logo and USB directions in the drive's `.imu(...)` in `Robot.java` | | distance and color sensors | sensible numbers | wiring, I2C port, configuration type | | camera | listed; Limelight "connected"; HuskyLens `Answers: yes` and a `Sees` line per box | USB, Ethernet or I2C cable, configuration name; a HuskyLens's Protocol Type | | battery | 12.5 V or more when charged | charge or replace it. Never play a match under 12.0 V | | `Robot.java`'s devices | `Robot.java: every device is in the configuration`, or only the parts you know are not built yet (`optional, so the part is off`) | add the device to the configuration, or fix its name ([parts not on the robot yet](https://crossbotics.com/ftc-helper/docs/reference/robot-java/#parts-not-on-the-robot-yet)) | **On a lift or an arm:** the Hardware Check has no limits, and RB gives full power. Use short, gentle taps. Know where its hard stop is, and keep hands clear. ## 4. Mechanism checks (after you build or change a mechanism) | Mechanism | Procedure | Pass | | --- | --- | --- | | Lift or arm | the steps under this table | stops before the hard stops; reaches each position in about 1 s; holds | | Intake | in, out, stop; block it by hand (with jam detection) | backs out and goes on; the jam count goes up | | Servo parts | each named position; toggle; slow move | no buzzing at the ends (a buzz means the range is too wide) | | Flywheel | spin to 3 speeds; compare the RPM on the screen with a tachometer or a slow-motion video | the numbers agree within about 3%; READY within about 1 s | | Launcher | shoot 1, then 3 | each piece only when READY; `whyNotReady` names what is missing | | Turret | home; aim at 0, 90, -90, 180 and back; turn it by hand to each limit | the short way around; never past a limit; cables slack | | Camera | point it at a tag; read the bearing (positive = left), and the distance against a tape measure | the bearing sign is right; the distance is within about 5% | **Lift or arm steps:** 1. Put the hard stops in place. 2. Set a low `maxPower` in `Tunables.java`. 3. Home it (push it down to the switch). 4. Drive it by hand to each end. It slows and stops before the hard stop. 5. Try each named position. 6. Pause (gamepad 1 BACK) while it moves. It stops (both motors, if it has two). ## 5. Floor check (before practice runs) 1. Set the PRACTICE profile, and a low `Tunables.Drive.maxPower` (for example 0.4) for the first runs. 2. Drive: forward, sideways, turn, field-centric. 3. Every button on the drivers' sheet does what it says. 4. The match timer buzzes 20 s before the end of TeleOp. Run a whole TeleOp once to hear it (the simulator works too). ## 6. Autonomous check (after a change to an autonomous) 1. Run it at low speed, and read the step report. 2. Run it as RED once. 3. Run it with a start delay once. 4. Run it at full speed: it ends in less than 28 s, and parks. 5. Put a box in the way: the move ends `STALLED`, and the robot stops pushing. More: [Match day: before the event](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/#before-the-event). ## 7. Before every match (print it) The drive team's auto checklist (the partner talk, the auto, the alliance, the profile, where to place the robot) is on [Match day: before each match](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/#before-each-match). Add these checks on the robot: - [ ] Battery 12.5 V or more (the Hardware Check shows it), and a spare on the cart - [ ] The robot starts inside its size limit, with everything folded and the hard stops tight - [ ] The lift and the turret are at their start positions (the home switches in reach) - [ ] No `!! COMPETITION: ... is OFF (optional part)` warning at INIT for a part that IS on the robot (a renamed or unplugged device) - [ ] No "tuned values differ" warning at INIT - [ ] After the autonomous, TeleOp's INIT screen says "Forward: from autonomous" - [ ] Gamepads: 1 = driver (Start+A), 2 = operator (Start+B) ## 8. When something breaks ![Five steps: write it down, repeat it on the bench, find where it lives, fix it (in code: add a test), note it in the team log. The new test warns you if the problem comes back](https://crossbotics.com/ftc-helper/docs/images/tests-when-it-breaks.svg) 1. **Write it down:** what you did, what you expected, what happened. Turn the debug lines on and take a photo of the screen. 2. **Make it happen again** on the bench, before you change code. You can fix a problem for sure only when you can repeat it. 3. **Find where it lives:** the hardware (the Hardware Check shows it), the configuration (names), your code, or the library. 4. **Fix it.** When the problem was in the code, also **add a test** ([Record a test](https://crossbotics.com/ftc-helper/docs/tests/01-record-a-test/)). Then it cannot come back without a warning. When it is a library bug, tell us ([Contributing](https://crossbotics.com/ftc-helper/docs/contributing/)). 5. **Note it** in the team's log. The next driver or programmer will meet it again. ## Fix a problem | Problem | Why, and the fix | | --- | --- | | The robot spins on the floor when it should drive straight | A drive motor is reversed. Go back to the Hardware Check (step 3) | | A motor turns, but its encoder stays at 0 | The encoder cable is not plugged in, or is in another motor's port ([Encoder Check](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/#encoder-check-each-encoder-cable-in-its-own-port)) | | A servo buzzes at one end | The position is past what the servo can reach. Find the end again with the [Servo Finder](https://crossbotics.com/ftc-helper/docs/tuning/03-servo-finder/) | | INIT says a part is OFF, but the part is on the robot | Its device name in the configuration is wrong, or the cable is out | | The battery drops under 12 V in a run | Charge it or replace it. Low voltage changes how far and how fast parts move | | A problem shows on the robot, but not in the simulator | The simulator cannot see wiring. Use the Hardware Check | ## Done when - The Hardware Check passes for every device. - Each mechanism passes its check. - The team has a printed copy of the before-every-match list, and of the Match day checklist. --- **Next:** the road ends here. Before an event, read [Match day](https://crossbotics.com/ftc-helper/docs/building-autos/09-match-day/). To look something up: [Reference](https://crossbotics.com/ftc-helper/docs/reference/) and the [Cookbook](https://crossbotics.com/ftc-helper/docs/cookbook/). To learn how it works inside: [Build it by hand](https://crossbotics.com/ftc-helper/docs/tutorials/). **Look it up:** [Wiring checks](https://crossbotics.com/ftc-helper/docs/tuning/02-wiring-checks/): the Hardware, Motor Direction and Encoder Checks. [The testing module](https://crossbotics.com/ftc-helper/docs/modules/testing/): the Hardware Check OpMode. **Go deeper:** [Tutorial 19: Hardware Check](https://crossbotics.com/ftc-helper/docs/tutorials/19-testing-procedures/): the Hardware Check in your own 3-line OpMode, and what each button does.