diff options
| -rw-r--r-- | LICENSE | 21 | ||||
| -rw-r--r-- | README.md | 335 | ||||
| -rw-r--r-- | RobotFirmware/opmodes/drivemode.cpp | 831 | ||||
| -rw-r--r-- | RobotFirmware/opmodes/normaldrive.cpp | 434 | ||||
| -rw-r--r-- | RobotFirmware/opmodes/team205_mech.h | 600 | ||||
| -rw-r--r-- | RobotFirmware/opmodes/tiltsteering.cpp | 312 |
6 files changed, 1682 insertions, 851 deletions
@@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 slash450 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. @@ -1,321 +1,90 @@ -# NRL SDK -### National Robotics League · for the Hexa Command Hub + <div align="center"> -The NRL SDK is the software kit teams use to program their robots: the HexaNRL runtime, the -Hexa* hardware libraries, the project and OpMode wizards, and the Blocks editor. It runs on the -Hexa Command Hub (robot) and the NRL controller, both built on ESP32-S3. Students write only -their game logic in `opmodes/`; the SDK handles hardware, wireless comms, timing, and display. +# ♠️ PIXEL POKERS ♦️ ---- +### `NRL • TECHNOLOGY • ROBOTICS • INNOVATION` -## Hardware Required +**GO ALL IN TO WIN IT.** -| Part | Quantity | Used For | -|------|----------|----------| -| ESP32-S3 DevKit | 2 | One for Robot, one for Controller | -| Servo motors | Up to 4 | Robot joints/arms | -| DC motors | Up to 4 | Drive system | -| SSD1306 OLED (128×64, I2C) | 1 | Robot status display | -| 240×320 TFT LCD (SPI) | 1 | Controller UI | -| LSM6DSOX IMU | 1 | Controller orientation | -| MCP3008 8-ch SPI ADC | 1 | Robot battery-voltage + current sensing | -| ACS712 current sensor | 2 | DC-motor rail + servo rail current | + + + --- -## Power & Current Sensing (MCP3008) - -The robot board carries an **MCP3008** (8-channel, 10-bit SPI ADC) that reads the battery -voltage and two ACS712 current sensors. There are two ways you read the data: - -**Battery voltage** — the always-available `power` object (board-level, no declaration needed): - -```cpp -power.getBatteryVoltage(); // robot pack voltage (V) -power.isBatteryLow(); // true when the pack is low -``` - -**Rail current** — read it directly from `power` (board-level, no declaration needed): - -```cpp -power.getMainCurrent(); // total battery current (A) — CH1 -power.getMotorCurrent(); // DC-motor branch current (A) — CH2 -power.getServoCurrent(); // servo rail current (A) — derived: main − motor -``` +</div> -> ⚠️ There is **one ACS712 per rail**, not one per motor/servo, and there is no dedicated -> servo-current sensor at all — servo current is *derived* as (main total − motor branch). -> `HexaDCMotor`/`HexaServo` intentionally have no `getCurrent()` of their own (it used to -> exist and just proxied to the same shared reading per motor/servo, which looked like -> individual per-device data but wasn't) — read the rail directly through `power` instead. +## ♠️ WHO WE ARE -The robot's battery voltage is also sent to the Controller and shown in its header. +We are **Pixel Pokers**, an NRL team driven by technology, creativity, engineering, and the determination to win. -**MCP3008 channel map / pins** (also in `RobotFirmware/lib/HexaNRL/src/BoardPins.h`): +We build. We experiment. We innovate. We compete. -| Channel | Signal | SPI pin | GPIO | -|---------|--------|---------|------| -| CH0 | Battery voltage sensor | CS | 8 | -| CH1 | ACS712 #1 — MAIN / total battery current | SCK | 14 | -| CH2 | ACS712 #2 — DC-motor branch current | MISO | 9 | -| CH3–CH7 | External ADC breakout connectors | MOSI | 13 | +We don't believe in playing it safe when there's something worth fighting for. -**Calibration:** VREF = **5.0 V** on this board (not 3.3 V). Defaults come from the verified -manufacturer batch logs (CH0 941 counts → 11.35 V ⇒ `vbattScale ≈ 2.468`). For trustworthy amps, -put a DMM in series and adjust `HexaPowerConfig.acsSensitivity`; for trustworthy volts, compare CH0 -against a DMM and adjust `vbattScale`. Keep the rails idle at power-up so `begin()` captures a clean -ACS712 zero offset. Run the **"Power Test"** OpMode to stream live V / motor-A / servo-A values. +> **GO ALL IN TO WIN IT.** ---- - -## External I/O & Bench Test ("IO Test") - -The board also breaks out **3 digital-I/O headers** and **5 external ADC ports**, named in -`RobotFirmware/lib/HexaNRL/src/BoardPins.h`: +## 🎯 OUR PHILOSOPHY -| Name | GPIO / Channel | Header | -|------|----------------|--------| -| `DIGITAL_D1` / `DIGITAL_D2` / `DIGITAL_D3` | IO35 / IO36 / IO37 | J14 / J15 / J16 (digital I/O) | -| `ADC_EXT_1` … `ADC_EXT_5` | MCP3008 CH3 … CH7 | external ADC connectors | +We don't fold when things get difficult. -Read an external ADC port with the global `power` object: `power.readChannelVoltage(ADC_EXT_1)`. +We don't stop when something fails. -The **"IO Test"** OpMode exercises all of these: -- **Digital:** drives `D1/D2/D3` as outputs, blinking together at ~1 Hz — plug an LED (+resistor) - into each header and watch them blink in unison. -- **Analog:** ramps a PWM signal 0→100→0 % on `DIGITAL_1` (IO1) and streams `adc3…adc7` + `pwm%` - to telemetry. Jumper `DIGITAL_1` into an ADC connector and that channel tracks the ramp. +We don't settle for ordinary. -> ⚠️ The ESP32-S3 has **no DAC**, so the ramp is a real PWM square wave. For the ADC to read a -> *smooth* voltage, low-pass it: `DIGITAL_1 ──[~10 kΩ]──┬── ADC connector`, with `[1 µF]` from that -> node to GND. An LED (+resistor) on `DIGITAL_1` dims visibly as the ramp falls. +Every challenge is an opportunity. Every setback is a lesson. Every competition is a chance to prove ourselves. ---- - -## Software Required +**We put everything on the table. We give everything we've got. We go ALL IN.** -1. [VSCode](https://code.visualstudio.com/) -2. [PlatformIO IDE extension](https://platformio.org/install/ide?install=vscode) for VSCode +## 🃏 THE FOUR SUITS -That's it. PlatformIO automatically downloads all library dependencies on first build. +| Suit | Meaning | +|:---:|---| +| ♠️ | **COURAGE** — Take the risk. Make the move. | +| ♦️ | **AMBITION** — Aim higher. Push further. | +| ♣️ | **INNOVATION** — Think differently. Build differently. | +| ♥️ | **TEAMWORK** — One team. One goal. | ---- +## ⚙️ OUR ARSENAL -## Getting Started +| Domain | What We Do | +|---|---| +| 💻 Software | Programming and digital solutions | +| 🔩 Hardware | Electronics and engineering | +| 🤖 Robotics | Designing and building robots | +| 🧠 Strategy | Solving problems and outthinking challenges | +| 🎨 Creativity | Turning crazy ideas into reality | -Every team project starts from the **project wizard**. It stamps your team number into the -project (which picks your radio channel), writes your `<ProjectName>.code-workspace`, and opens -it. Don't open or build the downloaded kit folder directly; run the wizard first. +## 🏆 OUR MISSION -**1. Get the kit.** Download the latest `.zip` from [Releases](../../releases) and extract it, -or click **"Use this template"** on GitHub and clone your copy. +To innovate without limits, engineer without fear, and compete with everything we've got. -**2. Run the project wizard** (nothing needs to be open first): -- Windows: double-click **`tools\new-nrl-project.bat`** -- macOS: double-click **`tools/new-nrl-project.command`** -- Linux: run **`bash tools/new-nrl-project.sh`** +We're not here just to participate. -It asks for **project name**, **team number**, **team name** and **location**, then creates the -project. +We're here to make our mark. -**3. Start coding.** Your new project opens in VS Code. Create OpModes with **`NRL: New OpMode`** -(see *Writing Your Code* below) and Build/Upload. PlatformIO installs dependencies on the first -build. +## 📡 THE REPOSITORY -Non-interactive use: -``` -py -3 tools/nrl_new_project.py --name MyBot --team 7539 --dir C:\Projects --yes -``` -Requires **Python 3** (PlatformIO already ships one; on Windows the `py` launcher is used). -See [tools/README.md](tools/README.md) for all options. +This is the digital headquarters of Pixel Pokers. -#### What the team number does -NRL has no roboRIO-style deploy target, so the team number instead selects the **ESP-NOW radio -channel**, round-robin over the non-overlapping channels **1, 6 and 11** (team 1 → 1, team 2 → 6, -team 3 → 11, team 4 → 1, …). The robot firmware generated for a project is pinned to that channel -via `-DNRL_WIFI_CHANNEL`, which spreads kits out when several run in one room. **Set the -controller's WiFi Channel screen to the same channel.** (Channel is a soft RF split — the button + -4-digit pairing still keeps kits logically separate.) At a competition, every robot on one field -must share that field's channel instead; set it with `py -3 tools/set-competition-channel.py`. +You'll find our: -> **Maintainers:** this source repo is opened with `NRL_Update_1.code-workspace` at its root. -> The student kit doesn't ship that file; students always start from the wizard. +- 🤖 Robotics projects +- 💻 Code and software +- ⚙️ Engineering experiments +- 🎬 Team media and videos +- 📋 Documentation and development logs --- -## Flashing the Firmware - -### Robot (Bot) -1. Open the `RobotFirmware` folder in VSCode -2. Connect the Robot ESP32-S3 via USB -3. Click **Upload** in PlatformIO (or `Ctrl+Alt+U`) - -### Controller (Handheld) -The controller ships as a **prebuilt binary** — there is nothing to compile. -1. Connect the Controller ESP32-S3 via USB (use a **data** cable, not charge-only) -2. **Windows:** double-click `ControllerFirmware\flash-controller.bat` - **macOS / Linux:** run `bash ControllerFirmware/flash-controller.sh` - (or in VS Code: `Ctrl+Shift+P` → `Tasks: Run Task` → **`NRL: Flash Controller`**) -3. Everything else is automatic: Python and esptool are installed if missing, and - the controller's serial port is detected by its USB chip (phantom system COM - ports like Intel AMT "SOL" are skipped). If several candidate ports exist, - you'll be asked to pick from a short list. -4. Afterwards, pick your team's channel on the controller's **WiFi Channel** screen - -Both devices communicate wirelessly via **ESP-NOW** — no WiFi router needed. - ---- - -## Troubleshooting - -**PlatformIO: `UnknownPlatform ... espressif32 ... version=None`** -This means the local `espressif32` platform package is corrupted or half-installed -(usually from an interrupted download), not a problem with this repo. Fix it with: -``` -pio platform uninstall espressif32 -pio platform install espressif32 -``` -If that doesn't help, delete `~/.platformio/platforms/espressif32` (Windows: -`%USERPROFILE%\.platformio\platforms\espressif32`) and rebuild — PlatformIO -re-fetches it automatically. - -**`new-nrl-project.bat` / `new-nrl-opmode.bat` say Python wasn't found, or open the -Microsoft Store** -A fresh Windows install has no real Python, so `python`/`py` resolve to the Store's -placeholder stub. Just re-run the launcher — it calls `tools/ensure-python.ps1`, -which detects this and installs a real Python 3 automatically (via winget or the -official python.org installer), then continues. This needs internet access on -first run only. - -**`flash_controller.py` says `No module named esptool`** -It now installs esptool automatically into whichever Python runs it the first -time you flash — just re-run it. If that fails (no internet, or pip unavailable -for that interpreter), install it manually with `pip install esptool` and try again. - -**Controller flash fails with `Failed to connect to ESP32-S3: No serial data received`** -Old versions of the flasher let esptool guess the port, and on many school/office -laptops it guessed a phantom system port (Intel AMT "SOL") instead of the -controller. The flasher now picks the port by its USB bridge chip and skips -phantom ports. If it reports **no USB serial device at all**: swap in a known-good -**data** USB cable (many are charge-only), plug directly into the laptop (no -hub/dock), and if the board still never appears in Device Manager under -"Ports (COM & LPT)", install the CP210x driver: -https://www.silabs.com/software-and-tools/usb-to-uart-bridge-vcp-drivers - ---- - -## Writing Your Code - -Your robot code lives in **`RobotFirmware/opmodes/`**, which is empty in the student kit -(this source repo keeps maintainer test and sample OpModes there). Each file there is -one OpMode, a program you pick from the Controller menu. Create one with -`Ctrl+Shift+P` → `Tasks: Run Task` → **`NRL: New OpMode`** (or run -`tools\new-nrl-opmode.bat` / `bash tools/new-nrl-opmode.sh`). That writes the skeleton below, -with the `REGISTER_OPMODE` line already in place. - -Every OpMode inherits from `NRLOpMode` and overrides only the hooks it needs (all four are -optional): +<div align="center"> -| Hook | When it runs | -|------|--------------| -| `init()` | Once, when INIT is pressed. `begin()` your hardware here. Keep it short: never block or `delay()`. | -| `start()` | Once, when the match starts, right before the first `loop()`. Queue an AUTO routine here. | -| `loop()` | **100 Hz**. TELEOP runs for 2:30, AUTO for 60 s. | -| `stop()` | Once, on STOP. Stop your motors and servos here. | +# ♠️ GO ALL IN TO WIN IT. ♦️ -A small TeleOp (tank drive plus a gripper on a button): +### PIXEL POKERS -```cpp -#include "NRL.h" - -// Declare hardware at file scope. Pin names come from BoardPins.h. -static HexaDCMotor leftMotor {{ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM }}; -static HexaDCMotor rightMotor{{ .dirPin = MOTOR_R_DIR, .pwmPin = MOTOR_R_PWM, .flipped = true }}; -static HexaServo gripper {{ .signalPin = SERVO_1, .startAngle = 15.0f }}; -static TankDrive drive(leftMotor, rightMotor); - -class MyTeleOp : public NRLOpMode { -public: - void init() override { - gripper.begin(); // servos first, then motors - leftMotor.begin(); - rightMotor.begin(); - } - - void loop() override { - drive.drive(gamepad1.leftY(), gamepad1.rightX()); // forward/back + turn - - if (gamepad1.justPressed(BTN_X)) gripper.setPosition(15); // open - if (gamepad1.justPressed(BTN_A)) gripper.setPosition(90); // close - - telemetry.addData("left Y", gamepad1.leftY()); - } - - void stop() override { - drive.stop(); - gripper.detach(); - } -}; - -REGISTER_OPMODE(MyTeleOp, "My TeleOp", TELEOP); -``` - -### Registering an OpMode - -The `REGISTER_OPMODE(ClassName, "Display Name", TELEOP);` line (or `AUTO`) at the bottom of -the file is what puts the OpMode on the Controller menu. Without it, the code compiles but -never appears. - -### Rules of thumb - -- **No `delay()`.** Use actions (`runAction(sequential({ ... }))`, `sleep_ms()`) for timed - sequences. In AUTO, queue the routine once in `start()`. In TELEOP, queue it on a button - press with `justPressed()`, never every tick. -- **Control each part in one place**, either `loop()` or an action, not both. -- **Telemetry:** use `telemetry.addData("key", value)`. It's sent to the Controller automatically. -- **Battery and current:** the global `power` object (see *Power & Current Sensing* above). - -`NRLOpMode.h` documents the full lifecycle and the action helpers (`instant`, `sequential`, -`parallel`, `sleep_ms`, `wait_until`, `cancelActions`, `isActionRunning`). -`NRLGamepad.h` lists every button and stick. The board has X, A, Y and the D-pad but **no B -button**. - ---- - -## Library Overview - -| Library | Purpose | -|---------|---------| -| **HexaNRL** | The robot runtime: OpMode lifecycle, match timing, wireless link, gamepad, telemetry, actions, `TankDrive`. Ships precompiled in the student kit. | -| **HexaServos** | `HexaServo` (PWM servos) and `HexaDCMotor` (DC motors) | -| **HexaIMU** | LSM6DSOX 6-DOF IMU driver with non-blocking heading (wraps Adafruit_LSM6DSOX) | -| **HexaOLED** | SSD1306 OLED display driver (I²C) | -| **HexaPower** | MCP3008 ADC: battery voltage and ACS712 rail current (HexaNRL provides the global `power` instance) | -| **HexaLED** | NeoPixel status and user LED | -| **HexaHAL** | Hardware abstraction interfaces | - -Third-party dependencies (fetched by PlatformIO on first build): Adafruit NeoPixel, -Adafruit LSM6DS and Adafruit Unified Sensor. - ---- - -## Project Structure - -``` -RobotFirmware/ ← Flash this to the robot -├── opmodes/ ← YOUR CODE: one .cpp per OpMode -├── src/RobotMain.ino ← Entry point (do not edit) -├── lib/HexaNRL/ ← Robot runtime (do not edit) -└── boards/ ← Custom board definition (reference only; platformio.ini - still targets the stock esp32-s3-devkitc-1 profile) -ControllerFirmware/ ← Controller firmware (the student kit ships it as a - prebuilt image + flasher; nothing to build there) -lib/ ← Hardware drivers (HexaServos, HexaIMU, HexaOLED, HexaPower, HexaLED, HexaHAL) -tools/ ← Project and OpMode generators, Blocks editor -``` - ---- +`NO FOLDING. NO BACKING DOWN. JUST WINNING.` -## License +**♥️ BUILT DIFFERENT. BUILT TO WIN. ♣️** -MIT — free to use, modify, and distribute for educational and competition purposes. +</div> diff --git a/RobotFirmware/opmodes/drivemode.cpp b/RobotFirmware/opmodes/drivemode.cpp index f57cae6..54b9dbc 100644 --- a/RobotFirmware/opmodes/drivemode.cpp +++ b/RobotFirmware/opmodes/drivemode.cpp @@ -1,477 +1,574 @@ #include "NRL.h" #include "team205_mech.h" -#include <Wire.h> -#include <math.h> // ============================================================ -// DriveMode — Tank Drive, IMU Auto-Level, Arm, Claw & Payload +// DriveMode — Dual-Stick Tank Drive, Arm, Claw & Payload Gate // ============================================================ -// SERVO PORTS ON HEXA COMMAND HUB (Standard 3-pin plug, Red in middle): -// SERVO_1 (S1) -> ARM (45° = up, 115° = floor) -// SERVO_4 (S4) -> CLAW (30° = open, 95° = closed) -// SERVO_3 (S3) -> PAYLOAD GATE (0° = closed, 90° = open) +// HARDWARE (3 servos, 3 separate mechanisms): +// SERVO_1 -> ARM (one axis: up / down) +// SERVO_2 -> CLAW (one axis: expand / contract) +// SERVO_3 -> PAYLOAD GATE (one axis: open / closed) // // Controls: // - TRUE TANK DRIVE: -// * Left Stick Y = Left Wheels -// * Right Stick Y = Right Wheels -// - SPACESTATION AUTO-LEVEL (Onboard IMU): -// * BTN_X = Press once to START leveling, press X again to STOP -// - PRECISION TURN SHORTCUTS: -// * BTN_RB = Turn 140° at 90% speed -// * BTN_LB = Turn 50° at 80% speed -// - ARM (S1): -// * BTN_DPAD_UP = Arm UP -// * BTN_DPAD_DOWN = Arm DOWN + Automatically OPENS Claw (30°) -// - CLAW (S4): -// * BTN_DPAD_RIGHT = Claw OPEN (30°) -// * BTN_DPAD_LEFT = Claw CLOSE (95°) -// - PAYLOAD GATE (S3): -// * BTN_A = Press once to OPEN 90°, press A again to CLOSE 0° +// * Left stick Y = Left Motor directly +// * Right stick Y = Right Motor directly +// - ARM (hold to move, release to stop): +// * BTN_DPAD_UP = arm UP +// * BTN_DPAD_DOWN = arm DOWN +// - CLAW (toggle on, travels to its limit; toggle off to stop): +// * BTN_LT = claw EXPAND +// * BTN_RT = claw CONTRACT +// - CLAW SNAPS & MACRO: +// * BTN_A = snap fully closed (and engage the grip) +// * BTN_Y = one-touch auto-grab (open -> clamp + chime) / release +// - PAYLOAD GATE (press once to toggle): +// * BTN_X = toggle the payload gate OPEN / CLOSED +// - FULL STRAIGHT DRIVE: +// * Hold BTN_RB: 100% full speed sprint with Gyro Heading Lock! +// - GYRO SPIN MACROS: +// * BTN_LB = Instant 180° gyro turnaround +// * BTN_DPAD_LEFT = Instant 90° left pivot +// * BTN_DPAD_RIGHT = Instant 90° right pivot +// +// ------------------------------------------------------------------ +// SERVO ANGLE DIRECTION — MEASURED, DO NOT "FIX" +// ------------------------------------------------------------------ +// Both servos are mounted so that a HIGHER angle rotates them in the +// direction that CLOSES / LOWERS the mechanism: +// +// ARM: 45 deg = raised (carry) 115 deg = lowered (floor) +// CLAW: 125 deg = open 155 deg = closed +// +// So the arm goes UP by DECREASING its angle, and the claw CLOSES by +// INCREASING its angle. The direction flags below are written to match that, +// and each one carries a comment saying which way the angle moves. +// +// These angles come from the team's own calibration on the real robot +// (Controller -> SERVO TEST). They are the source of truth for this robot. // ============================================================ -static HexaDCMotor leftMotor ({ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM, .flipped = true, .minDrive = 29 }); -static HexaDCMotor rightMotor({ .dirPin = MOTOR_R_DIR, .pwmPin = MOTOR_R_PWM, .flipped = false, .minDrive = 32 }); +// Drive motors on the Hexa Command Hub +static HexaDCMotor leftMotor({ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM, .flipped = true }); +static HexaDCMotor rightMotor({ .dirPin = MOTOR_R_DIR, .pwmPin = MOTOR_R_PWM, .flipped = false }); static TankDrive drive(leftMotor, rightMotor); +static DriveActions driveActions(drive); -// Servo ports on the HEXA Command Hub -static constexpr uint8_t ARM_SIGNAL_PIN = SERVO_1; // S1 -static constexpr uint8_t CLAW_SIGNAL_PIN = SERVO_4; // S4 (J20) -static constexpr uint8_t PAYLOAD_SIGNAL_PIN = SERVO_3; // S3 (J17) - -// ---- IMU AUTO-LEVEL TUNING (Button X Toggle) ----------------------------- -// 1. If tilting the robot nose-up does NOT change "Tilt" on the screen, -// flip USE_Y_AXIS_FOR_PITCH from false to true. -// 2. If the robot drives DOWN the ramp instead of UP toward level, -// flip LEVEL_DRIVE_SIGN between 1.0f and -1.0f. -static constexpr bool USE_Y_AXIS_FOR_PITCH = false; -static constexpr float LEVEL_DRIVE_SIGN = 1.0f; -static constexpr float LEVEL_KP = 0.022f; // Proportional climb gain -static constexpr float LEVEL_KD = 0.008f; // Damping gain (stops see-saw bounce) -static constexpr float LEVEL_DEADBAND_DEG = 1.5f; // Stop motors within ±1.5° of flat -static constexpr float LEVEL_MIN_POWER = 0.16f; // Minimum power to overcome ramp friction -static constexpr float LEVEL_MAX_POWER = 0.48f; // Max power so robot won't overshoot ramp - -// ---- PRECISION TURN TUNING (RB = 140° @ 90%, LB = 50° @ 80%) -------------- -static constexpr float TURN_140_DIR = 1.0f; -static constexpr float TURN_140_SPEED = 0.90f; // 90% speed -static constexpr uint32_t TURN_140_MS = 380; // Duration for 140° - -static constexpr float TURN_50_DIR = -1.0f; -static constexpr float TURN_50_SPEED = 0.80f; // 80% speed -static constexpr uint32_t TURN_50_MS = 165; // Duration for 50° - -static constexpr uint32_t TURN_BRAKE_MS = 45; // Active reverse brake pulse - -// ---- ARM ANGLES (S1) ----------------------------------------------------- -static constexpr float ARM_UP_ANGLE = 45.0f; // Raised carry height -static constexpr float ARM_DOWN_ANGLE = 115.0f; // Lowered floor height -static constexpr float ARM_STEP_PER_TICK = 1.2f; // Smooth 120 deg/s travel - -// ---- CLAW ANGLES (S4 — Calibrated: 30° open, 95° fully closed) ----------- -static constexpr float CLAW_OPEN_ANGLE = 30.0f; // Fully open -static constexpr float CLAW_CLOSED_ANGLE = 95.0f; // Fully closed -static constexpr float CLAW_STEP_PER_TICK = 2.2f; // Crisp ~0.3s open/close - -// ---- PAYLOAD GATE (S3): 90° OPEN / CLOSE TOGGLE ON BUTTON A --------------- -static constexpr float PAYLOAD_CLOSED_ANGLE = 0.0f; // Closed position -static constexpr float PAYLOAD_OPEN_ANGLE = 90.0f; // +90° Open position -static constexpr float PAYLOAD_STEP_PER_TICK = 3.5f; // Crisp 90° toggle - -// ---- CARRY-MODE DRIVE PROTECTION ----------------------------------------- -static constexpr float CARRY_MAX_DRIVE = 0.80f; -static constexpr float CARRY_ACCEL_PER_TICK = 0.05f; - -static HexaServo arm ({ .signalPin = ARM_SIGNAL_PIN, .startAngle = ARM_UP_ANGLE }); -static HexaServo claw ({ .signalPin = CLAW_SIGNAL_PIN, .startAngle = CLAW_OPEN_ANGLE }); -static HexaServo payload({ .signalPin = PAYLOAD_SIGNAL_PIN, .startAngle = PAYLOAD_CLOSED_ANGLE }); +// Which physical servo is the arm and which is the claw. +static constexpr uint8_t ARM_SIGNAL_PIN = SERVO_1; // GPIO 39 +static constexpr uint8_t CLAW_SIGNAL_PIN = SERVO_2; // GPIO 40 +static constexpr uint8_t PAYLOAD_SIGNAL_PIN = SERVO_3; // GPIO 41 -static float armCmdDeg = ARM_UP_ANGLE; -static float clawCmdDeg = CLAW_OPEN_ANGLE; -static float payloadCmdDeg = PAYLOAD_CLOSED_ANGLE; - -static bool clawGripLocked = false; -static bool payloadOpen = false; -static float smoothedLeft = 0.0f; -static float smoothedRight = 0.0f; - -// Timed + Brake Turn state -static bool turnActive = false; -static float turnPowerCmd = 0.0f; -static uint32_t turnSpinEndMs = 0; -static uint32_t turnBrakeEndMs = 0; -static float turnTargetDegLog = 0.0f; - -// Onboard LSM6DS IMU Auto-Level state -static uint8_t imuAddr = 0; -static bool autoLevelActive = false; -static float levelZeroDeg = 0.0f; -static float filteredTiltDeg = 0.0f; -static float prevLevelErrDeg = 0.0f; -static uint32_t prevLevelMs = 0; - -static PowerGuard powerGuard; -static BrownoutBeacon brownoutBeacon; -static GripMemory gripMemory; - -static uint16_t rawButtons = 0; - -// ------------------------------------------------------------ -// Direct Non-Invasive LSM6DS IMU Helpers (Reads pitch safely) -// ------------------------------------------------------------ -static bool probeImuAddress(uint8_t addr) { - Wire.beginTransmission(addr); - Wire.write(0x0F); // WHO_AM_I register - if (Wire.endTransmission(false) != 0) return false; - if (Wire.requestFrom((uint8_t)addr, (uint8_t)1) != 1) return false; - uint8_t who = Wire.read(); - return (who == 0x69 || who == 0x6A || who == 0x6C); -} +// ---- ARM: calibrated angles (measured on this robot) --------------------- +static constexpr float ARM_CARRY_ANGLE = 45.0f; // raised / carry position +static constexpr float ARM_FLOOR_ANGLE = 115.0f; // lowered to the floor +static constexpr float ARM_HOME_ANGLE = ARM_CARRY_ANGLE; -static bool readRawImuTilt(float& outDeg) { - if (imuAddr == 0) return false; +// ---- CLAW: calibrated angles (measured on this robot) -------------------- +static constexpr float CLAW_OPEN_ANGLE = 125.0f; // wide open +static constexpr float CLAW_CLOSED_ANGLE = 155.0f; // jaws shut - Wire.beginTransmission(imuAddr); - Wire.write(0x28); // OUTX_L_A (6 accelerometer bytes) - if (Wire.endTransmission(false) != 0) return false; - if (Wire.requestFrom((uint8_t)imuAddr, (uint8_t)6) != 6) return false; +// ------------------------------------------------------------------ +// GRIP PRESSURE +// +// A servo applies force only while it is still trying to REACH its commanded +// angle. If the claw is commanded to exactly CLAW_CLOSED_ANGLE, the servo +// arrives, stops pushing, and holds nothing — the piece is then held by +// friction alone and falls out the moment the robot moves. +// +// So once the jaws are shut on a piece, the servo is commanded PAST +// CLAW_CLOSED_ANGLE to CLAW_GRIP_ANGLE. The piece blocks the jaws short of +// that, so the servo never arrives, keeps straining, and presses. +// +// PRESSURE TUNING: a LARGER CLAW_GRIP_ANGLE = a tighter squeeze = more +// force. Raise it for a stronger grip; lower it if the servo starts buzzing +// hard, bogging down, or the arm lags behind when it moves. +// +// ⚠ This is also the biggest current draw on the board. See the brownout +// note below before raising it. +// ------------------------------------------------------------------ +static constexpr float CLAW_GRIP_ANGLE = 168.0f; + +// ---- PAYLOAD GATE: angles and button ------------------------------------ +// The payload gate is a third mechanism on its own servo. CLOSED is its +// starting pose; OPEN swings it 90 degrees clear. +// +// These two angles are the ones from the team's payload-toggle design. Unlike +// the arm and the claw, they were NOT measured on this robot — measure them +// in Controller -> SERVO TEST and correct them here if the gate does not +// travel the way you expect. +static constexpr float PAYLOAD_CLOSED_ANGLE = 0.0f; +static constexpr float PAYLOAD_OPEN_ANGLE = 90.0f; + +// Which button toggles the payload gate. Change this one line to move it. +static constexpr uint16_t PAYLOAD_BUTTON = BTN_X; + +// ------------------------------------------------------------------ +// TRAVEL SPEEDS — DEGREES PER SECOND +// +// The servo ramps toward the target on its own, advancing one step per +// setPosition() call. The ramp rate is the single source of truth for +// motion — do NOT also step the target angle by hand, because two rate +// systems fight and the servo never converges. +// +// These are also the current limit for the mechanism: a faster rate makes +// the battery rail dip harder (see the brownout note below). +// ------------------------------------------------------------------ +static constexpr float ARM_RATE_DEG_PER_SEC = 90.0f; // arm travel speed +static constexpr float CLAW_RATE_DEG_PER_SEC = 120.0f; // claw travel speed +static constexpr float PAYLOAD_RATE_DEG_PER_SEC = 180.0f; // gate travel speed + +// ------------------------------------------------------------------ +// BROWNOUT — why two servos moving at once can stop them working +// +// "The servos share the battery rail. There is NO BEC and no separate servo +// regulator." (HexaServo.h) Moving the arm AND the claw at the same time +// doubles the current the rail must supply. If that pulls the rail down +// far enough, the ESP32 browns out and resets. +// +// A reset is not a small inconvenience: init() runs again, and the claw is +// re-initialised OPEN. That is the "servo automatically opens" symptom — +// and the piece you were carrying is on the floor. +// +// Four things here stop that from happening: +// +// 1. MOTION ARBITRATION (see team205_mech.h). Only one mechanism TRAVELS +// at a time. A deferred move is not lost — it starts as soon as the +// rail is quiet again. This is the big one. +// +// 2. POWER DERATE (PowerGuard). When the pack sags, the drive output is +// scaled back so the robot crawls instead of pulling the rail under. +// This is what fixes "drive while gripping kills the claw". +// +// 3. GRIP MEMORY (GripMemory). If a reset does happen, the claw comes back +// CLOSED on the piece instead of open. +// +// 4. Modest travel rates. Raising them makes the rail dip harder. +// +// To confirm a brownout on the field: watch "Boot #" on the Controller. If +// it climbs while you drive, the board is resetting. +// ------------------------------------------------------------------ - uint8_t xl = Wire.read(); - uint8_t xh = Wire.read(); - uint8_t yl = Wire.read(); - uint8_t yh = Wire.read(); - uint8_t zl = Wire.read(); - uint8_t zh = Wire.read(); +// The three mechanisms. +static HexaServo arm ({ .signalPin = ARM_SIGNAL_PIN, .startAngle = ARM_HOME_ANGLE }); +static HexaServo claw ({ .signalPin = CLAW_SIGNAL_PIN, .startAngle = CLAW_OPEN_ANGLE }); +static HexaServo payload({ .signalPin = PAYLOAD_SIGNAL_PIN, .startAngle = PAYLOAD_CLOSED_ANGLE }); - int16_t ax = (int16_t)((xh << 8) | xl); - int16_t ay = (int16_t)((yh << 8) | yl); - int16_t az = (int16_t)((zh << 8) | zl); +// The mechanism wrappers. See team205_mech.h for what these fix. +static ServoAxis armAxis; +static ServoAxis clawAxis; +static ServoAxis payloadAxis; - float pitchAxis = USE_Y_AXIS_FOR_PITCH ? (float)ay : (float)ax; - float zAxis = (float)az; - if (fabsf(pitchAxis) < 1.0f && fabsf(zAxis) < 1.0f) return false; +// The claw's state machine (open / closing / gripping). +static ClawControl clawCtl; - outDeg = atan2f(pitchAxis, zAxis) * 57.29578f; - return true; -} +// Which way the arm is being driven right now. +enum class ArmDir { NONE, UP, DOWN }; -static void initImuForLeveling() { - imuAddr = 0; - if (probeImuAddress(0x6A)) { - imuAddr = 0x6A; - } else if (probeImuAddress(0x6B)) { - imuAddr = 0x6B; - } +// What an in-flight macro owns. Macro::NONE means the manual controls have the +// parts back. A macro that has run to completion stops owning anything. +enum class Macro { NONE, TURN, GRAB }; - if (imuAddr == 0) return; - - // Ensure accelerometer is enabled (104 Hz, ±2g) if it was powered down - Wire.beginTransmission(imuAddr); - Wire.write(0x10); // CTRL1_XL - if (Wire.endTransmission(false) == 0 && Wire.requestFrom((uint8_t)imuAddr, (uint8_t)1) == 1) { - uint8_t ctrl1 = Wire.read(); - if (ctrl1 == 0x00) { - Wire.beginTransmission(imuAddr); - Wire.write(0x10); - Wire.write(0x40); - Wire.endTransmission(true); - } - } +static Macro activeMacro = Macro::NONE; +static ArmDir armDir = ArmDir::NONE; +static bool objectSecured = false; +static bool fullStraightActive = false; +static float lockedHeading = 0.0f; +static bool payloadOpen = false; // payload gate state - // Calibrate resting flat angle as 0.0° baseline - float sum = 0.0f; - int validSamples = 0; - for (int i = 0; i < 12; i++) { - float deg = 0.0f; - if (readRawImuTilt(deg)) { - sum += deg; - validSamples++; - } - delay(5); - } +// Power / brownout state. +static PowerGuard powerGuard; +static BrownoutBeacon brownoutBeacon; +static GripMemory gripMemory; - if (validSamples > 0) { - levelZeroDeg = sum / (float)validSamples; - filteredTiltDeg = levelZeroDeg; - } -} +// ------------------------------------------------------------ +// Raw button state +// +// gamepad1.pressed() hides a button that was already held when the OpMode +// started, until it is released once (Gamepad::ignoreHeldButtons). That is +// right for menus, but it means a trigger the driver is ALREADY holding when +// the OpMode starts does nothing — which reads as "the button doesn't work". +// +// NRLGamepad::read() gives the raw packet contents with no hiding, so a +// held control works immediately. The arm and claw read through it for that +// reason; the discrete macros still use gamepad1.justPressed() because they +// need a clean edge. +// ------------------------------------------------------------ +static uint16_t rawButtons = 0; -static void refreshRawButtons() { +static void readRawButtons() { float lx, ly, rx, ry; uint16_t btns = 0; NRLGamepad::read(lx, ly, rx, ry, btns); rawButtons = btns; } -static bool isBtnPressed(uint16_t btn) { - return gamepad1.pressed(btn) || ((rawButtons & btn) != 0); -} - -static float stepAngle(float current, float target, float maxStep) { - if (target > current + maxStep) return current + maxStep; - if (target < current - maxStep) return current - maxStep; - return target; -} - -static float slewDrive(float current, float target, float maxStep) { - if (target > current + maxStep) return current + maxStep; - if (target < current - maxStep) return current - maxStep; - return target; -} - -static void startPrecisionTurn(float targetDeg, float speed, uint32_t durationMs, float directionSign) { - uint32_t now = millis(); - turnTargetDegLog = targetDeg * directionSign; - turnPowerCmd = speed * directionSign; - turnSpinEndMs = now + durationMs; - turnBrakeEndMs = turnSpinEndMs + TURN_BRAKE_MS; - turnActive = true; - autoLevelActive = false; -} +static bool rawPressed(uint16_t btn) { return (rawButtons & btn) != 0; } -static void updatePrecisionTurn(float driveScale) { - uint32_t now = millis(); - if (now < turnSpinEndMs) { - drive.drive(0.0f, turnPowerCmd * driveScale); - } else if (now < turnBrakeEndMs) { - drive.drive(0.0f, -turnPowerCmd * 0.55f); - } else { - drive.stop(); - turnActive = false; - } +// ------------------------------------------------------------ +// Auto-Grab Non-Blocking Action Routine +// ------------------------------------------------------------ +static ActionPtr autoGrabRoutine() { + return sequential({ + // 1. Clamp firmly on game piece immediately + instant([]{ + userLed.setSolid(255, 120, 0); // Orange: Clamping + clawCtl.tryClose(); + }), + sleep_ms(300), + + // 2. Strain the servo past the jaws so it presses on the piece + instant([]{ + clawCtl.engageNow(); + objectSecured = true; + gripMemory.set(true); + }), + sleep_ms(80), + + // 3. Dual audio chime & set secured indicator + instant([]{ + tone(BUZZER_PIN, 1800, 60); + }), + sleep_ms(60), + instant([]{ + tone(BUZZER_PIN, 2400, 100); + userLed.setSolid(180, 0, 255); // Purple: Object Secured + }) + }); } class DriveMode : public NRLOpMode { public: void init() override { - gripMemory.begin(); - + // Servos first, then drive motors + arm.setRampRate(ARM_RATE_DEG_PER_SEC); + claw.setRampRate(CLAW_RATE_DEG_PER_SEC); + payload.setRampRate(PAYLOAD_RATE_DEG_PER_SEC); arm.begin(); claw.begin(); payload.begin(); leftMotor.begin(); rightMotor.begin(); - initImuForLeveling(); - - armCmdDeg = ARM_UP_ANGLE; - payloadOpen = false; - payloadCmdDeg = PAYLOAD_CLOSED_ANGLE; - turnActive = false; - autoLevelActive = false; - smoothedLeft = 0.0f; - smoothedRight = 0.0f; - + // Bind the mechanism wrappers to the drivers. The wrapper holds the + // TARGET; apply() pushes it to the driver every tick. + armAxis.bind(arm, ARM_HOME_ANGLE, ARM_CARRY_ANGLE, ARM_FLOOR_ANGLE); + clawAxis.bind(claw, CLAW_OPEN_ANGLE, CLAW_OPEN_ANGLE, CLAW_CLOSED_ANGLE); + payloadAxis.bind(payload, PAYLOAD_CLOSED_ANGLE, PAYLOAD_CLOSED_ANGLE, PAYLOAD_OPEN_ANGLE); + clawCtl.bind(clawAxis, CLAW_OPEN_ANGLE, CLAW_CLOSED_ANGLE, CLAW_GRIP_ANGLE); + + objectSecured = false; + activeMacro = Macro::NONE; + armDir = ArmDir::NONE; + fullStraightActive = false; + payloadOpen = false; + + // If the board came up from a brownout, restore the grip so the claw + // comes back CLOSED on the piece instead of dropping it. + gripMemory.begin(); if (gripMemory.engaged) { - clawGripLocked = true; - clawCmdDeg = CLAW_CLOSED_ANGLE; + clawCtl.engageNow(); + objectSecured = true; } else { - clawGripLocked = false; - clawCmdDeg = CLAW_OPEN_ANGLE; + clawAxis.command(CLAW_OPEN_ANGLE); } - arm.setPosition(armCmdDeg); - claw.setPosition(clawCmdDeg); - payload.setPosition(payloadCmdDeg); + armAxis.command(ARM_HOME_ANGLE); + payloadAxis.command(PAYLOAD_CLOSED_ANGLE); + + armAxis.apply(); + clawAxis.apply(); + payloadAxis.apply(); + // Flash the LED red if this boot was a brownout reset. brownoutBeacon.arm(); - userLed.setSolid(0, 255, 0); + + userLed.setSolid(0, 255, 0); // Green ready } void loop() override { - refreshRawButtons(); + readRawButtons(); + + // Watch the battery rail. The scale factor backs the drive off when + // the pack sags, which is what keeps "drive while gripping" from + // resetting the board. const float driveScale = powerGuard.update(); - // Update filtered IMU tilt angle every tick - float rawDeg = 0.0f; - if (readRawImuTilt(rawDeg)) { - filteredTiltDeg = (0.75f * filteredTiltDeg) + (0.25f * rawDeg); + // A macro that has run to completion gives its part back to the + // manual controls. Checked before anything reads activeMacro. + if (activeMacro != Macro::NONE && !isActionRunning()) { + activeMacro = Macro::NONE; } - const float relativeTiltDeg = filteredTiltDeg - levelZeroDeg; // -------------------------------------------------------- - // 0. BUTTON X TOGGLE — Start / Stop Spacestation Auto-Level + // 1. GYRO SPIN MACROS (LB = 180°, DPAD_LEFT/RIGHT = ±90°) // -------------------------------------------------------- - if (gamepad1.justPressed(BTN_X)) { - if (imuAddr != 0) { - autoLevelActive = !autoLevelActive; - turnActive = false; - prevLevelErrDeg = relativeTiltDeg; - prevLevelMs = millis(); - if (!autoLevelActive) { - drive.stop(); - } - } else { - autoLevelActive = false; + // Guarded so a second press cannot stack two turns on the queue. + if (activeMacro != Macro::TURN) { + if (gamepad1.justPressed(BTN_LB)) { + runAction(driveActions.turn(180)); + activeMacro = Macro::TURN; + fullStraightActive = false; + } else if (gamepad1.justPressed(BTN_DPAD_LEFT)) { + runAction(driveActions.turn(-90)); + activeMacro = Macro::TURN; + fullStraightActive = false; + } else if (gamepad1.justPressed(BTN_DPAD_RIGHT)) { + runAction(driveActions.turn(90)); + activeMacro = Macro::TURN; + fullStraightActive = false; } } - // Instant joystick override cancels auto-turn or auto-level if driver pushes sticks - const bool sticksMoved = (fabsf(gamepad1.leftY()) > 0.30f || fabsf(gamepad1.rightY()) > 0.30f); - if ((turnActive || autoLevelActive) && sticksMoved) { - drive.stop(); - turnActive = false; - autoLevelActive = false; - } - // -------------------------------------------------------- - // 1. TURN SHORTCUTS (RB = 140° @ 90%, LB = 50° @ 80%) + // 2. DRIVE — tank, or the 100% heading-locked sprint. + // While a turn macro is running it owns the motors. // -------------------------------------------------------- - if (!turnActive && !autoLevelActive) { - if (gamepad1.justPressed(BTN_RB)) { - startPrecisionTurn(140.0f, TURN_140_SPEED, TURN_140_MS, TURN_140_DIR); - } else if (gamepad1.justPressed(BTN_LB)) { - startPrecisionTurn(50.0f, TURN_50_SPEED, TURN_50_MS, TURN_50_DIR); + if (activeMacro == Macro::TURN) { + // driveActions.turn() is driving — do not fight it for the motors. + } else if (rawPressed(BTN_RB)) { + if (!fullStraightActive) { + lockedHeading = NRLComms::getHeading(); + fullStraightActive = true; } - } - // -------------------------------------------------------- - // 2. DRIVE — Auto-Level, Precision Turn, or Dual-Stick Tank - // -------------------------------------------------------- - const float activeMaxDrive = clawGripLocked ? CARRY_MAX_DRIVE : 1.0f; - - if (autoLevelActive) { - smoothedLeft = 0.0f; - smoothedRight = 0.0f; - - uint32_t now = millis(); - float dt = (now - prevLevelMs) * 0.001f; - if (dt < 0.005f) dt = 0.01f; - prevLevelMs = now; - - float error = relativeTiltDeg; - float dErr = (error - prevLevelErrDeg) / dt; - prevLevelErrDeg = error; - - if (fabsf(error) <= LEVEL_DEADBAND_DEG) { - drive.stop(); - telemetry.addData("LEVEL", "BALANCED!"); - } else { - float cmd = (error * LEVEL_KP + dErr * LEVEL_KD) * LEVEL_DRIVE_SIGN; - if (cmd > 0.0f) { - cmd = constrain(cmd, LEVEL_MIN_POWER, LEVEL_MAX_POWER); - } else { - cmd = constrain(cmd, -LEVEL_MAX_POWER, -LEVEL_MIN_POWER); - } - drive.drive(cmd * driveScale, 0.0f); - telemetry.addData("LEVEL", "BALANCING..."); + // Gyro heading lock. The heading is meaningless until the gyro has + // finished its bias calibration (~0.5 s), so drive straight until + // then rather than steering on a garbage reference. + float headingError = 0.0f; + float turnCorrection = 0.0f; + if (NRLComms::isHeadingReady()) { + headingError = lockedHeading - NRLComms::getHeading(); + turnCorrection = constrain(headingError * 0.04f, -0.3f, 0.3f); } - } else if (turnActive) { - smoothedLeft = 0.0f; - smoothedRight = 0.0f; - updatePrecisionTurn(driveScale); - telemetry.addData("DRIVE", "AUTO TURN"); - telemetry.addData("Turn Deg", turnTargetDegLog); + + // Command 100% full forward speed + drive.drive(1.0f * driveScale, turnCorrection); + + telemetry.addData("DRIVE", "FULL STRAIGHT 100%"); + telemetry.addData("Heading Err", headingError); } else { + fullStraightActive = false; + + // -------------------------------------------------------- + // 3. TRUE DUAL-STICK TANK DRIVE + // -------------------------------------------------------- + // Left Stick Y controls Left Wheels, Right Stick Y controls Right Wheels float leftStick = gamepad1.leftY(); float rightStick = gamepad1.rightY(); const float DEADZONE = 0.05f; - if (fabsf(leftStick) < DEADZONE) leftStick = 0.0f; - if (fabsf(rightStick) < DEADZONE) rightStick = 0.0f; - - float targetL = leftStick * activeMaxDrive * driveScale; - float targetR = rightStick * activeMaxDrive * driveScale; - - if (clawGripLocked) { - smoothedLeft = slewDrive(smoothedLeft, targetL, CARRY_ACCEL_PER_TICK); - smoothedRight = slewDrive(smoothedRight, targetR, CARRY_ACCEL_PER_TICK); - } else { - smoothedLeft = targetL; - smoothedRight = targetR; - } + if (abs(leftStick) < DEADZONE) leftStick = 0.0f; + if (abs(rightStick) < DEADZONE) rightStick = 0.0f; + + // Kinematic conversion: + // Left = forward + turn = leftStick + // Right = forward - turn = rightStick + float forward = (leftStick + rightStick) * 0.5f; + float turn = (leftStick - rightStick) * 0.5f; - float forward = (smoothedLeft + smoothedRight) * 0.5f; - float turn = (smoothedLeft - smoothedRight) * 0.5f; + drive.drive(forward * driveScale, turn); - drive.drive(forward, turn); - telemetry.addData("LEVEL", imuAddr != 0 ? "OFF (Press X)" : "NO IMU"); + telemetry.addData("DRIVE", "DUAL TANK"); + telemetry.addData("Left Stick", leftStick); + telemetry.addData("Right Stick", rightStick); } // -------------------------------------------------------- - // 3. ARM (S1) — D-Down = Arm Down + Auto-Open Claw (30°) - // D-Up = Arm Up + // 4a. ARM — D-PAD UP / DOWN + // + // The D-pad is a set of momentary buttons, read as a LEVEL: hold UP + // and the arm rises, release and it stops where it is. It travels at + // ARM_RATE_DEG_PER_SEC and stops on its own at the calibrated poses. + // + // Read from the RAW button state, so a D-pad button already held + // when the OpMode starts works immediately instead of doing nothing + // until it is released and pressed again. // -------------------------------------------------------- - const bool dpadUp = isBtnPressed(BTN_DPAD_UP); - const bool dpadDown = isBtnPressed(BTN_DPAD_DOWN); - - if (dpadUp && !dpadDown) { - armCmdDeg = stepAngle(armCmdDeg, ARM_UP_ANGLE, ARM_STEP_PER_TICK); - } else if (dpadDown && !dpadUp) { - armCmdDeg = stepAngle(armCmdDeg, ARM_DOWN_ANGLE, ARM_STEP_PER_TICK); - - // Automatically open the claw to 30° when arm goes down - clawGripLocked = false; - gripMemory.set(false); - clawCmdDeg = stepAngle(clawCmdDeg, CLAW_OPEN_ANGLE, CLAW_STEP_PER_TICK); + if (rawPressed(BTN_DPAD_UP)) { + armDir = ArmDir::UP; + } else if (rawPressed(BTN_DPAD_DOWN)) { + armDir = ArmDir::DOWN; + } else { + armDir = ArmDir::NONE; + } + + if (armDir == ArmDir::UP) { + // UP = the LOWER angle on this robot (45 deg = carry). + if (motionRequest(armAxis)) armAxis.command(ARM_CARRY_ANGLE); + } else if (armDir == ArmDir::DOWN) { + // DOWN = the HIGHER angle on this robot (115 deg = floor). + if (motionRequest(armAxis)) armAxis.command(ARM_FLOOR_ANGLE); + } else { + // Nothing asked for the arm. Let go of the rail. + motionRelease(armAxis); } // -------------------------------------------------------- - // 4. CLAW (S4) — D-Right = Open (30°), D-Left = Close (95°) + // 4b. CLAW — LT / RT TRIGGERS + // + // LT and RT are TOGGLE switches on this controller, read as a LEVEL: + // flip one on and the claw travels that way, flip it off and the + // claw stops where it is. + // + // Which direction wins when BOTH are engaged: the one flipped most + // recently. `triggerDir` remembers that; the level checks below + // decide whether the remembered direction is still live. // -------------------------------------------------------- - const bool dpadRight = isBtnPressed(BTN_DPAD_RIGHT); - const bool dpadLeft = isBtnPressed(BTN_DPAD_LEFT); - - if (dpadRight && !dpadLeft) { - clawGripLocked = false; - gripMemory.set(false); - clawCmdDeg = stepAngle(clawCmdDeg, CLAW_OPEN_ANGLE, CLAW_STEP_PER_TICK); - } else if (dpadLeft && !dpadRight) { - clawGripLocked = true; - gripMemory.set(true); - clawCmdDeg = stepAngle(clawCmdDeg, CLAW_CLOSED_ANGLE, CLAW_STEP_PER_TICK); + static ClawDir triggerDir = ClawDir::NONE; + static uint16_t prevRaw = 0; + if ((rawButtons & BTN_LT) && !(prevRaw & BTN_LT)) { + triggerDir = ClawDir::EXPAND; + } else if ((rawButtons & BTN_RT) && !(prevRaw & BTN_RT)) { + triggerDir = ClawDir::CONTRACT; + } + prevRaw = rawButtons; + + const bool ltEngaged = rawPressed(BTN_LT); + const bool rtEngaged = rawPressed(BTN_RT); + + ClawDir desired = ClawDir::NONE; + if (triggerDir == ClawDir::EXPAND && ltEngaged) { + desired = ClawDir::EXPAND; // LT still on, still expanding + } else if (triggerDir == ClawDir::CONTRACT && rtEngaged) { + desired = ClawDir::CONTRACT; // RT still on, still contracting + } else if (ltEngaged) { + desired = ClawDir::EXPAND; // LT on again after RT released + } else if (rtEngaged) { + desired = ClawDir::CONTRACT; // RT on again after LT released + } + + // While the auto-grab macro is running it owns the claw. + if (activeMacro != Macro::GRAB) { + clawCtl.update(desired); + } + + // -------------------------------------------------------- + // 4c. CLAW SNAPS & AUTO-GRAB MACRO + // -------------------------------------------------------- + if (activeMacro != Macro::GRAB) { + // Tap BTN_Y to Toggle Grab / Release + if (gamepad1.justPressed(BTN_Y)) { + if (objectSecured) { + // If currently holding, release immediately + clawCtl.releaseNow(); + clawCtl.tryOpen(); + objectSecured = false; + gripMemory.set(false); + userLed.setSolid(0, 255, 0); + tone(BUZZER_PIN, 1200, 70); + } else { + // Execute Auto Grab + runAction(autoGrabRoutine()); + activeMacro = Macro::GRAB; + } + } + + // Manual snap — shut the claw and press on the piece. + // + // There is deliberately no "snap open" on BTN_X any more: that + // button is the payload gate now. To let go of a piece, press + // BTN_Y (release) or flip LT (expand). + if (gamepad1.justPressed(BTN_A)) { + clawCtl.engageNow(); + objectSecured = true; + gripMemory.set(true); + } } // -------------------------------------------------------- - // 5. PAYLOAD SERVO (S3) — Press Button A to Open / Close (90°) + // 4d. PAYLOAD GATE — press once to toggle open / closed + // + // Just a toggle between two angles. The servo ramps to the target + // on its own, so the target is set once and apply() does the rest. // -------------------------------------------------------- - if (gamepad1.justPressed(BTN_A)) { + if (gamepad1.justPressed(PAYLOAD_BUTTON)) { payloadOpen = !payloadOpen; + payloadAxis.command(payloadOpen ? PAYLOAD_OPEN_ANGLE : PAYLOAD_CLOSED_ANGLE); + tone(BUZZER_PIN, payloadOpen ? 2000 : 1400, 60); } - float payloadTarget = payloadOpen ? PAYLOAD_OPEN_ANGLE : PAYLOAD_CLOSED_ANGLE; - payloadCmdDeg = stepAngle(payloadCmdDeg, payloadTarget, PAYLOAD_STEP_PER_TICK); // -------------------------------------------------------- - // 6. SEND CLEAN POSITION COMMANDS TO ALL 3 SERVOS + // 5. PUSH THE TARGETS TO THE SERVOS + // + // This MUST run every tick, and it MUST be the only thing that + // talks to the servos. Two jobs: + // + // 1. It advances the ramp — the servo only travels while + // setPosition() is being called. + // 2. It refreshes the PWM duty every tick, so the servo keeps + // receiving pulses. A servo that is only refreshed every + // 250 ms (the driver's idle heartbeat) can drop its pulses + // when the rail sags — which is what "the servo just stops + // working" looks like on the field. // -------------------------------------------------------- - arm.setPosition(armCmdDeg); - claw.setPosition(clawCmdDeg); - payload.setPosition(payloadCmdDeg); + armAxis.apply(); + clawAxis.apply(); + payloadAxis.apply(); // -------------------------------------------------------- - // 7. STATUS LED & LIVE TELEMETRY + // 6. STATUS LED MANAGEMENT // -------------------------------------------------------- - if (!brownoutBeacon.service()) { - if (power.isBatteryLow()) { - userLed.setBlink(255, 0, 0, 300); - } else if (autoLevelActive) { - userLed.setSolid(0, 180, 255); // Cyan: Auto-Level Active - } else if (clawGripLocked) { - userLed.setSolid(180, 0, 255); // Purple: Element Gripped - } else { - userLed.setSolid(0, 255, 0); // Green: Ready + if (brownoutBeacon.service()) { + // The beacon owns the LED — it is telling the driver the last + // boot was a brownout reset. + } else if (power.isBatteryLow()) { + userLed.setBlink(255, 0, 0, 300); + + // Beep at most twice a second. A tone() on every 10 ms tick is a + // continuous buzz that drowns out the grab chime. + static uint32_t lastBeepMs = 0; + uint32_t nowMs = millis(); + if (nowMs - lastBeepMs >= 500) { + lastBeepMs = nowMs; + tone(BUZZER_PIN, 1000, 50); } + } else if (activeMacro == Macro::GRAB) { + // The grab macro owns the LED (orange = clamping, purple = secured). + } else if (fullStraightActive) { + userLed.setSolid(255, 255, 255); // White LED: FULL SPRINT + } else if (objectSecured) { + userLed.setSolid(180, 0, 255); // Purple: Object Secured + } else { + userLed.setSolid(0, 255, 0); // Green: Ready } - telemetry.addData("Tilt Deg", relativeTiltDeg); - telemetry.addData("Arm (S1)", armCmdDeg); - telemetry.addData("Claw (S4)", clawCmdDeg); - telemetry.addData("Pay (S3)", payloadCmdDeg); - telemetry.addData("Payload", payloadOpen ? "OPEN (90)" : "CLOSED (0)"); + // -------------------------------------------------------- + // 7. TELEMETRY + // -------------------------------------------------------- + // RAW shows the button bits actually arriving from the controller, so + // a control that does nothing can be traced (an empty RAW while a + // button is held means the controller is not sending that bit). + telemetry.addData("Arm Angle", armAxis.actual()); + telemetry.addData("Claw Angle", clawAxis.actual()); + telemetry.addData("Arm", armDir == ArmDir::UP ? "UP" : + armDir == ArmDir::DOWN ? "DOWN" : "HOLD"); + telemetry.addData("Claw", clawCtl.dir == ClawDir::EXPAND ? "EXPAND" : + clawCtl.dir == ClawDir::CONTRACT ? "CONTRACT" : "HOLD"); + telemetry.addData("Grip", clawCtl.isGripping() ? "PRESSING" : "loose"); + telemetry.addData("Payload", payloadOpen ? "GATE OPEN" : "GATE CLOSED"); + telemetry.addData("Pay Angle", payloadAxis.actual()); + telemetry.addData("Object", objectSecured ? "SECURED" : "NONE"); + telemetry.addData("Drive Sc", driveScale); + telemetry.addData("Heading", NRLComms::getHeading()); + telemetry.addData("RAW", rawButtons); team205ReportPower(telemetry, powerGuard); } void stop() override { cancelActions(); drive.stop(); + + // A clean stop means the match is over — clear the persisted grip so + // the next run does not come up clamping onto nothing. (A BROWNOUT + // never reaches here, which is exactly why the memory is useful.) gripMemory.set(false); - turnActive = false; - autoLevelActive = false; arm.detach(); claw.detach(); payload.detach(); userLed.setOff(); + noTone(BUZZER_PIN); } }; diff --git a/RobotFirmware/opmodes/normaldrive.cpp b/RobotFirmware/opmodes/normaldrive.cpp new file mode 100644 index 0000000..a50ef79 --- /dev/null +++ b/RobotFirmware/opmodes/normaldrive.cpp @@ -0,0 +1,434 @@ +#include "NRL.h" +#include "team205_mech.h" + +// ============================================================ +// NormalDrive — Tank/Arcade Drive with Arm & Claw +// ============================================================ +// HARDWARE (2 servos, 2 separate mechanisms): +// SERVO_1 -> ARM (one axis: up / down) +// SERVO_2 -> CLAW (one axis: expand / contract) +// +// Controls: +// - DRIVE MODE TOGGLE (BTN_X): TRUE DUAL-STICK TANK <-> SPLIT-ARCADE +// - FULL STRAIGHT DRIVE: +// * Hold BTN_RB: 100% full speed sprint with Gyro Heading Lock! +// - 180° & 90° QUICK SPINS: +// * BTN_LB = Instant 180° gyro turnaround +// * BTN_DPAD_LEFT = Instant 90° left pivot +// * BTN_DPAD_RIGHT = Instant 90° right pivot +// - ARM (hold to move, release to stop): +// * BTN_DPAD_UP = arm UP +// * BTN_DPAD_DOWN = arm DOWN +// - CLAW (toggle on, travels to its limit; toggle off to stop): +// * BTN_LT = claw EXPAND +// * BTN_RT = claw CONTRACT +// - CLAW SNAPS & MACRO: +// * BTN_A = snap fully closed (and engage the grip) +// * BTN_Y = one-touch auto-grab (open -> clamp + chime) / release +// +// ------------------------------------------------------------------ +// SERVO ANGLE DIRECTION — MEASURED, DO NOT "FIX" +// ------------------------------------------------------------------ +// Both servos are mounted so that a HIGHER angle rotates them in the +// direction that CLOSES / LOWERS the mechanism: +// +// ARM: 45 deg = raised (carry) 115 deg = lowered (floor) +// CLAW: 125 deg = open 155 deg = closed +// +// These angles come from the team's own calibration on the real robot +// (Controller -> SERVO TEST). They are the source of truth for this robot. +// ============================================================ + +// Drive motors on the Hexa Command Hub +static HexaDCMotor leftMotor({ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM, .flipped = true }); +static HexaDCMotor rightMotor({ .dirPin = MOTOR_R_DIR, .pwmPin = MOTOR_R_PWM, .flipped = false }); +static TankDrive drive(leftMotor, rightMotor); +static DriveActions driveActions(drive); + +// Which physical servo is the arm and which is the claw. +static constexpr uint8_t ARM_SIGNAL_PIN = SERVO_1; // GPIO 39 +static constexpr uint8_t CLAW_SIGNAL_PIN = SERVO_2; // GPIO 40 + +// ---- ARM: calibrated angles (measured on this robot) --------------------- +static constexpr float ARM_CARRY_ANGLE = 45.0f; // raised / carry position +static constexpr float ARM_FLOOR_ANGLE = 115.0f; // lowered to the floor +static constexpr float ARM_HOME_ANGLE = ARM_CARRY_ANGLE; + +// ---- CLAW: calibrated angles (measured on this robot) -------------------- +static constexpr float CLAW_OPEN_ANGLE = 125.0f; // wide open +static constexpr float CLAW_CLOSED_ANGLE = 155.0f; // jaws shut + +// ------------------------------------------------------------------ +// GRIP PRESSURE +// +// A servo applies force only while it is still trying to REACH its commanded +// angle. Commanding exactly CLAW_CLOSED_ANGLE means the servo arrives, +// stops pushing, and holds nothing — the piece is held by friction alone +// and falls out as soon as the robot moves. +// +// So once the jaws are shut on a piece, the servo is commanded PAST +// CLAW_CLOSED_ANGLE to CLAW_GRIP_ANGLE. The piece blocks the jaws short of +// that, so the servo never arrives, keeps straining, and presses. +// +// PRESSURE TUNING: a LARGER CLAW_GRIP_ANGLE = a tighter squeeze = more +// force. Raise it for a stronger grip; lower it if the servo starts buzzing +// hard, bogging down, or the arm lags behind when it moves. +// ------------------------------------------------------------------ +static constexpr float CLAW_GRIP_ANGLE = 168.0f; + +// ---- Travel speeds, DEGREES PER SECOND ---------------------------------- +// The servo ramps toward the target on its own, advancing one step per +// setPosition() call. The ramp rate is the single source of truth for +// motion — do NOT also step the target by hand, because two rate systems +// fight and the servo never converges. +static constexpr float ARM_RATE_DEG_PER_SEC = 90.0f; // arm travel speed +static constexpr float CLAW_RATE_DEG_PER_SEC = 120.0f; // claw travel speed + +// The two mechanisms. +static HexaServo arm ({ .signalPin = ARM_SIGNAL_PIN, .startAngle = ARM_HOME_ANGLE }); +static HexaServo claw({ .signalPin = CLAW_SIGNAL_PIN, .startAngle = CLAW_OPEN_ANGLE }); + +// The mechanism wrappers. See team205_mech.h for what these fix. +static ServoAxis armAxis; +static ServoAxis clawAxis; + +// The claw's state machine (open / closing / gripping). +static ClawControl clawCtl; + +// Which way the arm is being driven right now. +enum class ArmDir { NONE, UP, DOWN }; + +// What an in-flight macro owns. Macro::NONE means the manual controls have the +// parts back. A macro that has run to completion stops owning anything. +enum class Macro { NONE, TURN, GRAB }; + +static Macro activeMacro = Macro::NONE; +static ArmDir armDir = ArmDir::NONE; +static bool objectSecured = false; +static bool useTankDrive = true; +static bool fullStraightActive = false; +static float lockedHeading = 0.0f; + +// Power / brownout state. +static PowerGuard powerGuard; +static BrownoutBeacon brownoutBeacon; +static GripMemory gripMemory; + +// ------------------------------------------------------------ +// Raw button state — see the note in Drive Mode. gamepad1.pressed() +// hides a button already held when the OpMode started; the raw bits do +// not, so a control held from the start works immediately. +// ------------------------------------------------------------ +static uint16_t rawButtons = 0; + +static void readRawButtons() { + float lx, ly, rx, ry; + uint16_t btns = 0; + NRLGamepad::read(lx, ly, rx, ry, btns); + rawButtons = btns; +} + +static bool rawPressed(uint16_t btn) { return (rawButtons & btn) != 0; } + +// ------------------------------------------------------------ +// Auto-Grab Non-Blocking Action Routine +// ------------------------------------------------------------ +static ActionPtr autoGrabRoutine() { + return sequential({ + // 1. Clamp firmly on game piece immediately + instant([]{ + userLed.setSolid(255, 120, 0); // Orange: Clamping + clawCtl.tryClose(); + }), + sleep_ms(300), + + // 2. Strain the servo past the jaws so it presses on the piece + instant([]{ + clawCtl.engageNow(); + objectSecured = true; + gripMemory.set(true); + }), + sleep_ms(80), + + // 3. Dual audio chime & set secured indicator + instant([]{ + tone(BUZZER_PIN, 1800, 60); + }), + sleep_ms(60), + instant([]{ + tone(BUZZER_PIN, 2400, 100); + userLed.setSolid(180, 0, 255); // Purple: Object Secured + }) + }); +} + +class NormalDrive : public NRLOpMode { +public: + void init() override { + arm.setRampRate(ARM_RATE_DEG_PER_SEC); + claw.setRampRate(CLAW_RATE_DEG_PER_SEC); + arm.begin(); + claw.begin(); + leftMotor.begin(); + rightMotor.begin(); + + armAxis.bind(arm, ARM_HOME_ANGLE, ARM_CARRY_ANGLE, ARM_FLOOR_ANGLE); + clawAxis.bind(claw, CLAW_OPEN_ANGLE, CLAW_OPEN_ANGLE, CLAW_CLOSED_ANGLE); + clawCtl.bind(clawAxis, CLAW_OPEN_ANGLE, CLAW_CLOSED_ANGLE, CLAW_GRIP_ANGLE); + + objectSecured = false; + activeMacro = Macro::NONE; + armDir = ArmDir::NONE; + fullStraightActive = false; + + // If the board came up from a brownout, restore the grip so the claw + // comes back CLOSED on the piece instead of dropping it. + gripMemory.begin(); + if (gripMemory.engaged) { + clawCtl.engageNow(); + objectSecured = true; + } else { + clawAxis.command(CLAW_OPEN_ANGLE); + } + + armAxis.command(ARM_HOME_ANGLE); + armAxis.apply(); + clawAxis.apply(); + + // Flash the LED red if this boot was a brownout reset. + brownoutBeacon.arm(); + + userLed.setSolid(0, 255, 0); // Green ready + } + + void loop() override { + readRawButtons(); + + // Watch the battery rail. The scale factor backs the drive off when + // the pack sags, which is what keeps "drive while gripping" from + // resetting the board. + const float driveScale = powerGuard.update(); + + if (activeMacro != Macro::NONE && !isActionRunning()) { + activeMacro = Macro::NONE; + } + + // -------------------------------------------------------- + // 1. GYRO SPIN MACROS (LB = 180°, DPAD_LEFT/RIGHT = ±90°) + // -------------------------------------------------------- + if (activeMacro != Macro::TURN) { + if (gamepad1.justPressed(BTN_LB)) { + runAction(driveActions.turn(180)); + activeMacro = Macro::TURN; + fullStraightActive = false; + } else if (gamepad1.justPressed(BTN_DPAD_LEFT)) { + runAction(driveActions.turn(-90)); + activeMacro = Macro::TURN; + fullStraightActive = false; + } else if (gamepad1.justPressed(BTN_DPAD_RIGHT)) { + runAction(driveActions.turn(90)); + activeMacro = Macro::TURN; + fullStraightActive = false; + } + } + + // -------------------------------------------------------- + // 2. DRIVE — tank, arcade, or the 100% heading-locked sprint. + // While a turn macro is running it owns the motors. + // -------------------------------------------------------- + if (activeMacro == Macro::TURN) { + // driveActions.turn() is driving — do not fight it for the motors. + } else if (rawPressed(BTN_RB)) { + if (!fullStraightActive) { + lockedHeading = NRLComms::getHeading(); + fullStraightActive = true; + } + + float headingError = 0.0f; + float turnCorrection = 0.0f; + if (NRLComms::isHeadingReady()) { + headingError = lockedHeading - NRLComms::getHeading(); + turnCorrection = constrain(headingError * 0.04f, -0.3f, 0.3f); + } + + drive.drive(1.0f * driveScale, turnCorrection); + userLed.setSolid(255, 255, 255); // White LED: FULL SPRINT + + telemetry.addData("DRIVE", "FULL STRAIGHT 100%"); + telemetry.addData("Heading Err", headingError); + } else { + fullStraightActive = false; + + // -------------------------------------------------------- + // 3. DRIVE MODE — TRUE TANK vs SPLIT-ARCADE + // -------------------------------------------------------- + if (gamepad1.justPressed(BTN_X)) { + useTankDrive = !useTankDrive; + tone(BUZZER_PIN, useTankDrive ? 1600 : 2000, 80); + } + + const float DEADZONE = 0.05f; + + if (useTankDrive) { + // TRUE TANK DRIVE: Left Stick Y = Left, Right Stick Y = Right + float leftStick = gamepad1.leftY(); + float rightStick = gamepad1.rightY(); + + if (abs(leftStick) < DEADZONE) leftStick = 0.0f; + if (abs(rightStick) < DEADZONE) rightStick = 0.0f; + + float forward = (leftStick + rightStick) * 0.5f; + float turn = (leftStick - rightStick) * 0.5f; + drive.drive(forward * driveScale, turn); + + telemetry.addData("MODE", "TRUE TANK (2-Stick)"); + } else { + // SPLIT-ARCADE DRIVE: Left Stick Y = Fwd, Right Stick X = Turn + float forward = gamepad1.leftY(); + float turn = gamepad1.rightX(); + + if (abs(forward) < DEADZONE) forward = 0.0f; + if (abs(turn) < DEADZONE) turn = 0.0f; + drive.drive(forward * driveScale, turn); + + telemetry.addData("MODE", "ARCADE (Split-Stick)"); + } + } + + // -------------------------------------------------------- + // 4a. ARM — D-PAD UP / DOWN + // -------------------------------------------------------- + if (rawPressed(BTN_DPAD_UP)) { + armDir = ArmDir::UP; + } else if (rawPressed(BTN_DPAD_DOWN)) { + armDir = ArmDir::DOWN; + } else { + armDir = ArmDir::NONE; + } + + if (armDir == ArmDir::UP) { + // UP = the LOWER angle on this robot (45 deg = carry). + if (motionRequest(armAxis)) armAxis.command(ARM_CARRY_ANGLE); + } else if (armDir == ArmDir::DOWN) { + // DOWN = the HIGHER angle on this robot (115 deg = floor). + if (motionRequest(armAxis)) armAxis.command(ARM_FLOOR_ANGLE); + } else { + motionRelease(armAxis); + } + + // -------------------------------------------------------- + // 4b. CLAW — LT / RT TRIGGERS + // -------------------------------------------------------- + static ClawDir triggerDir = ClawDir::NONE; + static uint16_t prevRaw = 0; + if ((rawButtons & BTN_LT) && !(prevRaw & BTN_LT)) { + triggerDir = ClawDir::EXPAND; + } else if ((rawButtons & BTN_RT) && !(prevRaw & BTN_RT)) { + triggerDir = ClawDir::CONTRACT; + } + prevRaw = rawButtons; + + const bool ltEngaged = rawPressed(BTN_LT); + const bool rtEngaged = rawPressed(BTN_RT); + + ClawDir desired = ClawDir::NONE; + if (triggerDir == ClawDir::EXPAND && ltEngaged) { + desired = ClawDir::EXPAND; + } else if (triggerDir == ClawDir::CONTRACT && rtEngaged) { + desired = ClawDir::CONTRACT; + } else if (ltEngaged) { + desired = ClawDir::EXPAND; + } else if (rtEngaged) { + desired = ClawDir::CONTRACT; + } + + if (activeMacro != Macro::GRAB) { + clawCtl.update(desired); + + // Tap BTN_Y to Toggle Grab / Release + if (gamepad1.justPressed(BTN_Y)) { + if (objectSecured) { + clawCtl.releaseNow(); + clawCtl.tryOpen(); + objectSecured = false; + gripMemory.set(false); + userLed.setSolid(0, 255, 0); + tone(BUZZER_PIN, 1200, 70); + } else { + runAction(autoGrabRoutine()); + activeMacro = Macro::GRAB; + } + } + + // BTN_A snaps the claw shut and engages the grip + if (gamepad1.justPressed(BTN_A)) { + clawCtl.engageNow(); + objectSecured = true; + gripMemory.set(true); + } + } + + // -------------------------------------------------------- + // 5. PUSH THE TARGETS TO THE SERVOS + // + // This MUST run every tick, and it MUST be the only thing that + // talks to the servos. It advances the ramp (the servo only + // travels while setPosition() is called) and refreshes the PWM + // duty every tick, so the servo keeps receiving pulses. + // -------------------------------------------------------- + armAxis.apply(); + clawAxis.apply(); + + // -------------------------------------------------------- + // 6. STATUS LED MANAGEMENT + // -------------------------------------------------------- + if (brownoutBeacon.service()) { + // The beacon owns the LED — the last boot was a brownout reset. + } else if (power.isBatteryLow()) { + userLed.setBlink(255, 0, 0, 300); + + // Beep at most twice a second. A tone() on every 10 ms tick is a + // continuous buzz that drowns out the grab chime. + static uint32_t lastBeepMs = 0; + uint32_t nowMs = millis(); + if (nowMs - lastBeepMs >= 500) { + lastBeepMs = nowMs; + tone(BUZZER_PIN, 1000, 50); + } + } else if (activeMacro == Macro::GRAB) { + // The grab macro owns the LED. + } else if (fullStraightActive) { + userLed.setSolid(255, 255, 255); + } else if (objectSecured) { + userLed.setSolid(180, 0, 255); + } else { + userLed.setSolid(0, 255, 0); + } + + // Telemetry stream + telemetry.addData("Arm Angle", armAxis.actual()); + telemetry.addData("Claw Angle", clawAxis.actual()); + telemetry.addData("Grip", clawCtl.isGripping() ? "PRESSING" : "loose"); + telemetry.addData("Object", objectSecured ? "SECURED" : "NONE"); + telemetry.addData("Drive Sc", driveScale); + telemetry.addData("Heading", NRLComms::getHeading()); + telemetry.addData("RAW", rawButtons); + team205ReportPower(telemetry, powerGuard); + } + + void stop() override { + cancelActions(); + drive.stop(); + + // A clean stop means the match is over — clear the persisted grip so + // the next run does not come up clamping onto nothing. + gripMemory.set(false); + + arm.detach(); + claw.detach(); + userLed.setOff(); + noTone(BUZZER_PIN); + } +}; + +REGISTER_OPMODE(NormalDrive, "Normal Drive", TELEOP); diff --git a/RobotFirmware/opmodes/team205_mech.h b/RobotFirmware/opmodes/team205_mech.h index 6b6d279..3959fc5 100644 --- a/RobotFirmware/opmodes/team205_mech.h +++ b/RobotFirmware/opmodes/team205_mech.h @@ -1,274 +1,472 @@ #pragma once + #include "NRL.h" #include <Preferences.h> -#include <esp_system.h> +#include <cmath> +#include <cstring> // ============================================================================ -// TEAM 205 (PIXEL POKER) - SHARED MECHANISM & POWER LIBRARY (team205_mech.h) -// Supports: drivemode.cpp, normaldrive.cpp, tiltsteering.cpp, pixelpoker_auto.cpp +// TEAM 205 (PIXEL POKERS) — SHARED MECHANISM HELPERS +// ============================================================================ +// +// This is a HELPER HEADER, not an OpMode. It contains no REGISTER_OPMODE +// and adds nothing to the Controller's OpMode list. Every OpMode that needs +// it just adds one #include line. +// +// +// WHY THIS FILE EXISTS +// --------------------------------------------------------------------------- +// HexaServo::setPosition() does TWO things at once: +// +// 1. It sets the TARGET angle the servo should reach. +// 2. If a ramp rate is configured, it advances the servo ONE ramp step +// toward that target, by (elapsed_ms / 1000) * rate degrees. +// +// The ramp ONLY advances when setPosition() is called. The driver's 250 ms +// heartbeat (HexaServo::tick) re-writes the PWM duty for the CURRENT angle +// but never moves the mechanism. +// +// Four consequences, ALL of which bit this robot on the field: +// +// (a) Calling setPosition() ONCE with a new angle moves the servo by ONE +// ramp step and then it stops there. It does NOT travel to the target. +// A payload gate toggled on a button edge therefore moved ~2 degrees +// and stopped — the gate "never opens". +// +// (b) A mechanism only travels if setPosition() is called REPEATEDLY. +// The ramp IS the motion. +// +// (c) getPosition() reports the driver's RAMP position, not the real servo +// angle. The driver has no idea that the jaws are jammed on a piece, +// so it happily reports that a straining claw has "reached" 168. +// +// (d) The PWM duty is refreshed every tick when setPosition() is called +// every tick. A servo that is only refreshed every 250 ms can drop +// its pulses if the ESP32 stalls or the battery rail sags — which is +// exactly what "the servo just stops working" looks like. +// +// ServoAxis makes one rule impossible to get wrong: +// +// Every mechanism has exactly ONE owner. The owner sets the TARGET. +// apply() is called EVERY tick and pushes the target to the driver. +// +// The target lives in the axis, not in the driver, so an action can move a +// mechanism while loop() keeps re-asserting the target every tick without +// the two fighting each other. // ============================================================================ -class ServoAxis { -public: - void bind(HexaServo& driver, float homeDeg, float poseADeg, float poseBDeg) { - drv = &driver; - homeAngle = homeDeg; - minAngle = fminf(poseADeg, poseBDeg); - maxAngle = fmaxf(poseADeg, poseBDeg); - targetDeg = homeDeg; - lastMoveMs = millis(); + +// ============================================================================ +// ServoAxis — one mechanism on one servo +// ============================================================================ +struct ServoAxis { + HexaServo* servo = nullptr; + + float target = 0.0f; // the travel pose we are heading for + float lo = 0.0f; // travel limits + float hi = 180.0f; + + // Optional PRESS override. A servo only applies force while it is still + // trying to REACH its commanded angle. Commanding exactly the closed + // angle means the servo arrives, stops pushing, and holds nothing — the + // piece is then held by friction alone and falls out the moment the arm + // moves. So while gripping, the servo is commanded PAST the closed angle: + // the piece blocks the jaws short of it, the servo never arrives, and it + // keeps straining and pressing. + float pressAngle = -1.0f; // < 0 = press disabled + bool pressing = false; + + // Attach this axis to a driver. `start` is the mechanism's home pose. + void bind(HexaServo& s, float start, float travelLo, float travelHi) { + servo = &s; + lo = travelLo; + hi = travelHi; + target = constrain(start, travelLo, travelHi); + pressing = false; } - void command(float deg, bool allowOvertravel = false) { - if (!allowOvertravel) { - deg = constrain(deg, minAngle, maxAngle); - } else { - deg = constrain(deg, 0.0f, 180.0f); - } + // Set the travel target. This does NOT move the servo — apply() does. + // While `pressing` the press angle wins, so call stopPressing() first if + // the mechanism needs to travel. + void command(float angle) { + target = constrain(angle, lo, hi); + } - if (fabsf(deg - targetDeg) > 0.25f) { - targetDeg = deg; - lastMoveMs = millis(); - } + // Freeze where the mechanism is RIGHT NOW. This is what "release the + // trigger and it stops" actually requires: the ramp chases a target, so + // the target has to become the current position. + // + // A straining servo cannot be frozen — it is held by the piece, and the + // driver does not know where the jaws really are. + void hold() { + if (pressing) return; + target = actual(); } - void press(float gripDeg) { - command(gripDeg, true); + // Strain past the jaws and press. + void press(float angle) { + pressAngle = angle; + pressing = true; } + // Stop pressing. The mechanism goes back to holding `target`. void stopPressing() { - targetDeg = constrain(targetDeg, minAngle, maxAngle); + pressing = false; } - void apply() { - if (drv != nullptr) { - drv->setPosition(targetDeg); - } - } + bool isPressing() const { return pressing; } - float actual() const { - return (drv != nullptr) ? drv->getPosition() : targetDeg; + // The angle actually sent to the servo. + float commanded() const { + return (pressing && pressAngle >= 0.0f) ? pressAngle : target; } - float target() const { - return targetDeg; + // Push the commanded angle to the driver. Call this EVERY tick — this is + // what actually moves the mechanism AND what keeps its PWM alive. + void apply() { + if (servo == nullptr) return; + servo->setPosition(commanded()); } - bool travelArrived(float tolDeg = 0.5f) const { - return fabsf(actual() - targetDeg) <= tolDeg; - } + // Where the driver thinks the servo is (the ramp position). When the servo + // is straining against a piece this runs AHEAD of the real jaw angle. + float actual() const { return servo ? servo->getPosition() : commanded(); } - bool isSettled(float tolDeg = 1.0f) const { - return travelArrived(tolDeg); + // True once the driver has been ramped to the commanded angle. + bool arrived(float tol = 1.0f) const { + return fabsf(actual() - commanded()) <= tol; } - uint32_t msSinceCommand() const { - return millis() - lastMoveMs; + // True once the driver has been ramped to the TRAVEL target (ignoring any + // press override). + bool travelArrived(float tol = 1.0f) const { + return fabsf(actual() - target) <= tol; } -private: - HexaServo* drv = nullptr; - float homeAngle = 90.0f; - float minAngle = 0.0f; - float maxAngle = 180.0f; - float targetDeg = 90.0f; - uint32_t lastMoveMs = 0; + // True while the mechanism is still travelling toward its commanded + // angle. A straining (pressing) servo is NOT travelling — it is jammed + // against a piece — so it never blocks another mechanism. + bool travelling(float tol = 0.75f) const { + return fabsf(actual() - commanded()) > tol; + } }; -// Non-blocking motion arbiter with 650ms auto-release timeout -static ServoAxis* activeMotionOwner = nullptr; -static uint32_t motionLockStartMs = 0; -static constexpr uint32_t MOTION_LOCK_TIMEOUT_MS = 650; +// ============================================================================ +// MotionArbiter — never ramp two servos at the same time +// ============================================================================ +// "The servos share the battery rail. There is NO BEC and no separate servo +// regulator." (HexaServo.h) +// +// Two servos ramping at once double the current the rail must supply. On a +// loaded rail that sag is what makes one servo stop responding. +// +// The arbiter serialises mechanism travel: while one mechanism is moving, +// another mechanism's request is DEFERRED (the caller simply keeps its old +// target and asks again next tick). Nothing is dropped — the deferred move +// starts as soon as the rail is quiet again. +// +// Pressing (holding a strain against a piece) is NOT travel: a straining +// servo is not moving, so it never blocks anybody. +// +// The owner is a function-local static, so every OpMode that includes this +// header shares one arbiter per program — the arm and the claw arbitrate +// against each other without any extra wiring. inline bool motionRequest(ServoAxis& axis) { - uint32_t now = millis(); - - if (activeMotionOwner == &axis) { - return true; + static ServoAxis* owner = nullptr; + if (owner != nullptr && owner != &axis && owner->travelling()) { + return false; // rail is busy — defer this move } - - if (activeMotionOwner == nullptr || - activeMotionOwner->travelArrived(1.0f) || - (now - motionLockStartMs) >= MOTION_LOCK_TIMEOUT_MS) { - activeMotionOwner = &axis; - motionLockStartMs = now; - return true; - } - - return false; + owner = &axis; + return true; } +// Release the rail. Call when a mechanism is idle. inline void motionRelease(ServoAxis& axis) { - if (activeMotionOwner == &axis) { - activeMotionOwner = nullptr; - } + static ServoAxis* owner = nullptr; + if (owner == &axis) owner = nullptr; } -enum class ClawDir { NONE, EXPAND, CONTRACT }; -class ClawControl { -public: - ClawDir dir = ClawDir::NONE; - - void bind(ServoAxis& clawAxisRef, float openDeg, float closedDeg, float gripDeg) { - axis = &clawAxisRef; - openAngle = openDeg; - closeAngle = closedDeg; - gripAngle = gripDeg; - gripping = false; - dir = ClawDir::NONE; - } +// ============================================================================ +// PowerGuard — watch the rail so a brownout never surprises you +// ============================================================================ +// A brownout (the ESP32 resetting because the battery rail sagged) is the +// classic explanation for "the servo just stops working" and for "the claw +// opens by itself": init() runs again and puts the claw back to its open +// angle. +// +// PowerGuard does two things: +// +// 1. DERATE. When the pack sags, the drive output is scaled back so the +// robot crawls instead of pulling the rail under. This is what stops +// "drive while gripping" from resetting the board. +// +// 2. REPORT. The boot counter and reset reason go to the Controller, so a +// brownout is visible instead of mysterious. +// +// THRESHOLDS: measure your own pack. Run the Power Test OpMode, watch the +// voltage with the servos moving and the motors driving, and set these two +// numbers either side of what you saw. +struct PowerGuard { + // Start backing off below this pack voltage (V). + float sagVoltage = 9.80f; + // Resume full power above this pack voltage (V). + float recoverVoltage = 10.60f; + // Drive output scale at and below sagVoltage. + float minDerate = 0.25f; + + float minVoltage = 99.0f; // lowest pack voltage seen this run + float peakServoA = 0.0f; // peak servo-rail current seen this run + bool protecting = false; + + // Call once per tick. Returns the drive scale factor to use this tick. + float update() { + float v = power.getBatteryVoltage(); + float a = power.getServoCurrent(); - void update(ClawDir desired) { - dir = desired; - if (axis == nullptr) return; + if (v > 0.0f && v < minVoltage) minVoltage = v; + if (a > peakServoA) peakServoA = a; - if (desired == ClawDir::EXPAND) { - gripping = false; - if (motionRequest(*axis)) { - axis->command(openAngle); - } - } else if (desired == ClawDir::CONTRACT) { - if (motionRequest(*axis)) { - axis->command(closeAngle); - } - } else { - if (!gripping && prevDir != ClawDir::NONE) { - axis->command(axis->actual()); - } - motionRelease(*axis); + if (v <= 0.0f) return 1.0f; // sensor not ready — do not interfere + + if (!protecting && v < sagVoltage) { + protecting = true; + } else if (protecting && v > recoverVoltage) { + protecting = false; } - prevDir = desired; - } + if (!protecting) return 1.0f; - void tryClose() { - if (axis == nullptr) return; - gripping = false; - axis->command(closeAngle); + // Linear ramp from minDerate at sagVoltage up to 1.0 at recoverVoltage. + float span = recoverVoltage - sagVoltage; + if (span <= 0.0f) return minDerate; + float t = constrain((v - sagVoltage) / span, 0.0f, 1.0f); + return minDerate + t * (1.0f - minDerate); } - void tryOpen() { - if (axis == nullptr) return; - gripping = false; - axis->command(openAngle); - } + // True while the pack is sagging and the drive is being backed off. + bool isProtecting() const { return protecting; } +}; - void engageNow() { - if (axis == nullptr) return; - gripping = true; - axis->press(gripAngle); - } - void releaseNow() { - gripping = false; - if (axis != nullptr) { - axis->stopPressing(); - motionRelease(*axis); - } - } +// ============================================================================ +// Reset-reason helpers. Declared up here because BrownoutBeacon uses them. +// ============================================================================ - bool isGripping() const { - return gripping; - } +// Number of times the MCU has booted since power-up. If this climbs while +// you are driving, the board is resetting — that is a brownout, not firmware. +inline uint32_t team205BootCount() { return nrlBootCount(); } -private: - ServoAxis* axis = nullptr; - ClawDir prevDir = ClawDir::NONE; - float openAngle = 125.0f; - float closeAngle = 155.0f; - float gripAngle = 160.5f; - bool gripping = false; -}; +// Short token for the last reset: "BROWNOUT", "POWERON", "TASK_WDT", ... +inline const char* team205ResetReason() { return nrlLastResetReasonShort(); } -class PowerGuard { -public: - float update() { - if (power.isBatteryLow()) { - lowSagActive = true; - scale = fmaxf(0.65f, scale - 0.02f); - } else { - lowSagActive = false; - scale = fminf(1.00f, scale + 0.01f); - } - return scale; - } +// True if the last reset was a brownout. +inline bool team205LastResetWasBrownout() { + const char* r = team205ResetReason(); + return (r != nullptr) && (strcmp(r, "BROWNOUT") == 0); +} - bool isSagging() const { return lowSagActive; } - float currentScale() const { return scale; } -private: - float scale = 1.0f; - bool lowSagActive = false; -}; +// ============================================================================ +// BrownoutBeacon — make a reset visible without a laptop +// ============================================================================ +// It OWNS the user LED while active — skip your normal LED logic when +// service() returns true. +struct BrownoutBeacon { + bool active = false; + uint32_t untilMs = 0; -class BrownoutBeacon { -public: + // Call once in init(). void arm() { - wasBrownout = (esp_reset_reason() == ESP_RST_BROWNOUT); - if (wasBrownout) { - Preferences prefs; - if (prefs.begin("t205_pwr", false)) { - bootCount = prefs.getUInt("bo_cnt", 0) + 1; - prefs.putUInt("bo_cnt", bootCount); - prefs.end(); - } - beaconEndMs = millis() + 3000; - } else { - Preferences prefs; - if (prefs.begin("t205_pwr", true)) { - bootCount = prefs.getUInt("bo_cnt", 0); - prefs.end(); - } - beaconEndMs = 0; - } + if (!team205LastResetWasBrownout()) return; + active = true; + untilMs = millis() + 2000; } + // Call every tick in loop(). Returns true while it owns the LED. bool service() { - if (!wasBrownout || millis() >= beaconEndMs) { - return false; - } - bool on = ((millis() / 150) % 2) == 0; - if (on) { - userLed.setSolid(255, 0, 0); - } else { + if (!active) return false; + if ((int32_t)(millis() - untilMs) >= 0) { + active = false; userLed.setOff(); + return false; } + userLed.setSolid(255, 0, 0); return true; } +}; - uint32_t brownoutCount() const { return bootCount; } +// Publish the power / brownout state to the Controller. Call from loop(). +inline void team205ReportPower(NRLTelemetry& tel, const PowerGuard& g) { + tel.addData("Boot #", (float)team205BootCount()); + tel.addData("Reset", team205ResetReason()); + tel.addData("Servo A", power.getServoCurrent()); + tel.addData("Min V", g.minVoltage); + tel.addData("Peak A", g.peakServoA); +} -private: - bool wasBrownout = false; - uint32_t beaconEndMs = 0; - uint32_t bootCount = 0; -}; -class GripMemory { -public: +// ============================================================================ +// GripMemory — survive a brownout reset +// ============================================================================ +// If the board browns out mid-match, RAM is gone and the claw would be +// re-initialised OPEN — the piece drops on the floor and the driver has no +// idea why. +// +// Storing the grip state in NVS (flash) and re-applying it on the next boot +// means a brownout costs you a second of driving, not the piece. +// +// Writes happen only when the grip state CHANGES (a button press), so the +// flash wear is negligible. +struct GripMemory { bool engaged = false; + // Call in init(). Restores the last known grip state. void begin() { - Preferences prefs; - if (prefs.begin("t205_grip", true)) { - engaged = prefs.getBool("held", false); - prefs.end(); + Preferences p; + if (!p.begin("team205", false)) return; + engaged = p.getBool("grip", false); + p.end(); + } + + // Call when the grip state changes. + void set(bool on) { + if (engaged == on) return; + engaged = on; + Preferences p; + if (!p.begin("team205", false)) return; + p.putBool("grip", on); + p.end(); + } +}; + + +// ============================================================================ +// ClawControl — the claw's state machine +// ============================================================================ +// The claw is the one mechanism with real state (open / closing / closed / +// gripping), and getting that state wrong is what makes it "open by itself". +// It lives here so every OpMode gets the same correct behaviour. +// +// THE STATES +// --------------------------------------------------------------------------- +// NONE jaws hold wherever they are. The TARGET is frozen to the +// current position, so the servo stops where it is instead of +// creeping on toward its last commanded pose. +// EXPAND the jaws open. The grip is released first — but only once the +// rail is free, so the claw never relaxes-and-recloses while +// another mechanism is moving. +// CONTRACT the jaws close. The grip engages only after the jaws have +// REALLY arrived closed. +// GRIPPING the servo is commanded PAST the closed angle so it strains +// against the piece and presses. The grip is a LATCH: it +// survives releasing the trigger, and it is re-asserted every +// tick so the squeeze never fades. +// +// Why "really arrived closed" matters: the driver reports its own RAMP +// position, and it has no idea the jaws are blocked by a piece. If the grip +// engaged on a half-open jaw the servo would strain against nothing. +// ============================================================================ + +// Which way the jaws are being driven. +enum class ClawDir { NONE, EXPAND, CONTRACT }; + +struct ClawControl { + ServoAxis* axis = nullptr; + + float openAngle = 125.0f; + float closedAngle = 155.0f; + float gripAngle = 168.0f; + + ClawDir dir = ClawDir::NONE; + bool gripping = false; // latched: the servo is straining on a piece + bool closing = false; // we have commanded closed and are waiting + + void bind(ServoAxis& a, float open, float closed, float grip) { + axis = &a; + openAngle = open; + closedAngle = closed; + gripAngle = grip; + dir = ClawDir::NONE; + gripping = false; + closing = false; + } + + bool isGripping() const { return gripping; } + bool isClosing() const { return closing; } + + // --- transitions --------------------------------------------------- + + // Start closing. Returns false if the rail is busy — the caller should + // ask again next tick. Nothing is lost by waiting. + bool tryClose() { + if (!motionRequest(*axis)) return false; + if (!gripping) { + axis->command(closedAngle); + closing = true; } + return true; } - void set(bool state) { - if (engaged == state) return; - engaged = state; - Preferences prefs; - if (prefs.begin("t205_grip", false)) { - prefs.putBool("held", state); - prefs.end(); + // Start opening. Returns false if the rail is busy. + bool tryOpen() { + if (!motionRequest(*axis)) return false; + // Let go FIRST, then open. If we opened first while still pressing, + // the servo would relax back toward the closed angle and re-clamp. + if (gripping) { + gripping = false; + axis->stopPressing(); } + closing = false; + axis->command(openAngle); + return true; } -}; -template <typename TelemetryT> -inline void team205ReportPower(TelemetryT& telem, const PowerGuard& pg) { - telem.addData("Rail", pg.isSagging() ? "LOW SAG" : "OK"); -} + // Engage the grip now. Used by the auto-grab macro and by BTN_A. + void engageNow() { + gripping = true; + closing = false; + axis->press(gripAngle); + } + + // Release the grip now. + void releaseNow() { + gripping = false; + closing = false; + axis->stopPressing(); + } + + // --- per-tick update ----------------------------------------------- + + // Call every tick with the direction the driver is asking for. + void update(ClawDir requested) { + dir = requested; + + if (requested == ClawDir::EXPAND) { + // Deferring is safe: the claw simply holds its current command + // (still gripping, still at the grip angle) until the rail frees + // up. The piece is NOT dropped. + tryOpen(); + + } else if (requested == ClawDir::CONTRACT) { + tryClose(); + + // Engage the grip only once the jaws have REALLY arrived closed. + // The driver reports its ramp position, so this is the best + // available signal that the jaws are shut. + if (closing && axis->travelArrived(1.0f)) { + engageNow(); + } + + } else { + // No trigger engaged: the jaws stop where they are. Because the + // servo ramps toward a TARGET, "stop" means the target must + // become the current position — otherwise the claw keeps creeping + // toward its last commanded pose. + closing = false; + motionRelease(*axis); + if (!gripping) axis->hold(); + } + } +}; diff --git a/RobotFirmware/opmodes/tiltsteering.cpp b/RobotFirmware/opmodes/tiltsteering.cpp new file mode 100644 index 0000000..0510d20 --- /dev/null +++ b/RobotFirmware/opmodes/tiltsteering.cpp @@ -0,0 +1,312 @@ +#include "NRL.h" +#include "team205_mech.h" +#include <cmath> + +// ============================================================ +// TiltSteering — IMU Board Tilt Control Mode +// ============================================================ +// How it works: +// - Tilting the robot forward / backward commands Forward / Reverse drive! +// - Tilting the robot left / right commands Turning left / right! +// - Smooth 3° deadzone around neutral so it stays completely still on flat ground. +// +// ARM (hold to move, release to stop): +// * BTN_DPAD_UP = arm UP +// * BTN_DPAD_DOWN = arm DOWN +// CLAW (toggle on, travels to its limit; toggle off to stop): +// * BTN_LT = claw EXPAND +// * BTN_RT = claw CONTRACT +// CLAW SNAPS: +// * BTN_A = snap fully closed (and engage the grip) +// +// ------------------------------------------------------------------ +// SERVO ANGLE DIRECTION — MEASURED, DO NOT "FIX" +// ------------------------------------------------------------------ +// Both servos are mounted so that a HIGHER angle rotates them in the +// direction that CLOSES / LOWERS the mechanism: +// +// ARM: 45 deg = raised (carry) 115 deg = lowered (floor) +// CLAW: 125 deg = open 155 deg = closed +// +// These angles come from the team's own calibration on the real robot +// (Controller -> SERVO TEST). They are the source of truth for this robot. +// ============================================================ + +// Hardware configuration +static HexaDCMotor leftMotor({ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM, .flipped = true }); +static HexaDCMotor rightMotor({ .dirPin = MOTOR_R_DIR, .pwmPin = MOTOR_R_PWM, .flipped = false }); +static TankDrive drive(leftMotor, rightMotor); + +// On-board IMU (LSM6DSOX on dedicated Wire bus 0, 0x6B) +static HexaIMU imu{ hexaImuConfig() }; + +// Which physical servo is the arm and which is the claw. +static constexpr uint8_t ARM_SIGNAL_PIN = SERVO_1; // GPIO 39 +static constexpr uint8_t CLAW_SIGNAL_PIN = SERVO_2; // GPIO 40 + +// ---- ARM: calibrated angles (measured on this robot) --------------------- +static constexpr float ARM_CARRY_ANGLE = 45.0f; // raised / carry position +static constexpr float ARM_FLOOR_ANGLE = 115.0f; // lowered to the floor +static constexpr float ARM_HOME_ANGLE = ARM_CARRY_ANGLE; + +// ---- CLAW: calibrated angles (measured on this robot) -------------------- +static constexpr float CLAW_OPEN_ANGLE = 125.0f; // wide open +static constexpr float CLAW_CLOSED_ANGLE = 155.0f; // jaws shut + +// ------------------------------------------------------------------ +// GRIP PRESSURE +// +// A servo applies force only while it is still trying to REACH its commanded +// angle. Commanding exactly CLAW_CLOSED_ANGLE means the servo arrives, +// stops pushing, and holds nothing — the piece is held by friction alone +// and falls out as soon as the robot moves. +// +// So once the jaws are shut on a piece, the servo is commanded PAST +// CLAW_CLOSED_ANGLE to CLAW_GRIP_ANGLE. The piece blocks the jaws short of +// that, so the servo never arrives, keeps straining, and presses. +// +// PRESSURE TUNING: a LARGER CLAW_GRIP_ANGLE = a tighter squeeze = more +// force. Raise it for a stronger grip; lower it if the servo starts buzzing +// hard, bogging down, or the arm lags behind when it moves. +// ------------------------------------------------------------------ +static constexpr float CLAW_GRIP_ANGLE = 168.0f; + +// ---- Travel speeds, DEGREES PER SECOND ---------------------------------- +// The servo ramps toward the target on its own, advancing one step per +// setPosition() call. The ramp rate is the single source of truth for +// motion — do NOT also step the target by hand, because two rate systems +// fight and the servo never converges. +static constexpr float ARM_RATE_DEG_PER_SEC = 90.0f; // arm travel speed +static constexpr float CLAW_RATE_DEG_PER_SEC = 120.0f; // claw travel speed + +// Responsive tilt tuning +constexpr float TILT_DEADZONE_DEG = 3.0f; // Ignore tilts under ±3° +constexpr float TILT_MAX_DEG = 22.0f; // Full 100% motor speed reached at 22° tilt + +static HexaServo arm ({ .signalPin = ARM_SIGNAL_PIN, .startAngle = ARM_HOME_ANGLE }); +static HexaServo claw({ .signalPin = CLAW_SIGNAL_PIN, .startAngle = CLAW_OPEN_ANGLE }); + +// The mechanism wrappers. See team205_mech.h for what these fix. +static ServoAxis armAxis; +static ServoAxis clawAxis; + +// The claw's state machine (open / closing / gripping). +static ClawControl clawCtl; + +// Which way the arm is being driven right now. +enum class ArmDir { NONE, UP, DOWN }; + +static ArmDir armDir = ArmDir::NONE; +static bool objectSecured = false; + +// Power / brownout state. +static PowerGuard powerGuard; +static BrownoutBeacon brownoutBeacon; +static GripMemory gripMemory; + +// ------------------------------------------------------------ +// Raw button state — see the note in Drive Mode. gamepad1.pressed() +// hides a button already held when the OpMode started; the raw bits do +// not, so a control held from the start works immediately. +// ------------------------------------------------------------ +static uint16_t rawButtons = 0; + +static void readRawButtons() { + float lx, ly, rx, ry; + uint16_t btns = 0; + NRLGamepad::read(lx, ly, rx, ry, btns); + rawButtons = btns; +} + +static bool rawPressed(uint16_t btn) { return (rawButtons & btn) != 0; } + +class TiltSteering : public NRLOpMode { +public: + void init() override { + // Initialize sensors and actuators + imu.begin(); + arm.setRampRate(ARM_RATE_DEG_PER_SEC); + claw.setRampRate(CLAW_RATE_DEG_PER_SEC); + arm.begin(); + claw.begin(); + leftMotor.begin(); + rightMotor.begin(); + + armAxis.bind(arm, ARM_HOME_ANGLE, ARM_CARRY_ANGLE, ARM_FLOOR_ANGLE); + clawAxis.bind(claw, CLAW_OPEN_ANGLE, CLAW_OPEN_ANGLE, CLAW_CLOSED_ANGLE); + clawCtl.bind(clawAxis, CLAW_OPEN_ANGLE, CLAW_CLOSED_ANGLE, CLAW_GRIP_ANGLE); + + armDir = ArmDir::NONE; + objectSecured = false; + + // If the board came up from a brownout, restore the grip so the claw + // comes back CLOSED on the piece instead of dropping it. + gripMemory.begin(); + if (gripMemory.engaged) { + clawCtl.engageNow(); + objectSecured = true; + } else { + clawAxis.command(CLAW_OPEN_ANGLE); + } + + armAxis.command(ARM_HOME_ANGLE); + armAxis.apply(); + clawAxis.apply(); + + // Flash the LED red if this boot was a brownout reset. + brownoutBeacon.arm(); + + userLed.setSolid(0, 200, 255); // Cyan: Tilt steering active + } + + void loop() override { + readRawButtons(); + + // Watch the battery rail. The scale factor backs the drive off when + // the pack sags, which is what keeps "drive while gripping" from + // resetting the board. + const float driveScale = powerGuard.update(); + + // -------------------------------------------------------- + // 1. ACQUIRE ACCELEROMETER TILT DATA + // -------------------------------------------------------- + imu.read(); + + float ax = imu.getAccelX(); + float ay = imu.getAccelY(); + float az = imu.getAccelZ(); + + // Calculate pitch (forward/back tilt) and roll (left/right tilt) + float pitchDeg = atan2(-ax, sqrt(ay * ay + az * az)) * (180.0f / PI); + float rollDeg = atan2(ay, az) * (180.0f / PI); + + // -------------------------------------------------------- + // 2. PROPORTIONAL TILT DRIVE MAPPING + // -------------------------------------------------------- + float forward = 0.0f; + float turn = 0.0f; + + // Pitch tilt -> Forward / Reverse + if (abs(pitchDeg) > TILT_DEADZONE_DEG) { + float sign = (pitchDeg > 0.0f) ? 1.0f : -1.0f; + forward = sign * (abs(pitchDeg) - TILT_DEADZONE_DEG) / (TILT_MAX_DEG - TILT_DEADZONE_DEG); + forward = constrain(forward, -1.0f, 1.0f); + } + + // Roll tilt -> Left / Right Turn + if (abs(rollDeg) > TILT_DEADZONE_DEG) { + float sign = (rollDeg > 0.0f) ? 1.0f : -1.0f; + turn = sign * (abs(rollDeg) - TILT_DEADZONE_DEG) / (TILT_MAX_DEG - TILT_DEADZONE_DEG); + turn = constrain(turn, -1.0f, 1.0f); + } + + // Command motors + drive.drive(forward * driveScale, turn); + + // Visual feedback based on movement + if (!brownoutBeacon.service()) { + if (abs(forward) > 0.1f || abs(turn) > 0.1f) { + userLed.setSolid(0, 255, 0); // Green when actively driving + } else { + userLed.setSolid(0, 150, 255); // Cyan when resting flat + } + } + + // -------------------------------------------------------- + // 3. ARM — D-PAD UP / DOWN + // -------------------------------------------------------- + if (rawPressed(BTN_DPAD_UP)) { + armDir = ArmDir::UP; + } else if (rawPressed(BTN_DPAD_DOWN)) { + armDir = ArmDir::DOWN; + } else { + armDir = ArmDir::NONE; + } + + if (armDir == ArmDir::UP) { + // UP = the LOWER angle on this robot (45 deg = carry). + if (motionRequest(armAxis)) armAxis.command(ARM_CARRY_ANGLE); + } else if (armDir == ArmDir::DOWN) { + // DOWN = the HIGHER angle on this robot (115 deg = floor). + if (motionRequest(armAxis)) armAxis.command(ARM_FLOOR_ANGLE); + } else { + motionRelease(armAxis); + } + + // -------------------------------------------------------- + // 4. CLAW — LT / RT TRIGGERS + // -------------------------------------------------------- + static ClawDir triggerDir = ClawDir::NONE; + static uint16_t prevRaw = 0; + if ((rawButtons & BTN_LT) && !(prevRaw & BTN_LT)) { + triggerDir = ClawDir::EXPAND; + } else if ((rawButtons & BTN_RT) && !(prevRaw & BTN_RT)) { + triggerDir = ClawDir::CONTRACT; + } + prevRaw = rawButtons; + + const bool ltEngaged = rawPressed(BTN_LT); + const bool rtEngaged = rawPressed(BTN_RT); + + ClawDir desired = ClawDir::NONE; + if (triggerDir == ClawDir::EXPAND && ltEngaged) { + desired = ClawDir::EXPAND; + } else if (triggerDir == ClawDir::CONTRACT && rtEngaged) { + desired = ClawDir::CONTRACT; + } else if (ltEngaged) { + desired = ClawDir::EXPAND; + } else if (rtEngaged) { + desired = ClawDir::CONTRACT; + } + + clawCtl.update(desired); + + // BTN_A snaps the claw shut and engages the grip + if (gamepad1.justPressed(BTN_A)) { + clawCtl.engageNow(); + objectSecured = true; + gripMemory.set(true); + } + + // -------------------------------------------------------- + // 5. PUSH THE TARGETS TO THE SERVOS + // + // This MUST run every tick, and it MUST be the only thing that + // talks to the servos. It advances the ramp (the servo only + // travels while setPosition() is called) and refreshes the PWM + // duty every tick, so the servo keeps receiving pulses. + // -------------------------------------------------------- + armAxis.apply(); + clawAxis.apply(); + + // -------------------------------------------------------- + // 6. TELEMETRY STREAM + // -------------------------------------------------------- + telemetry.addData("Pitch Deg", pitchDeg); + telemetry.addData("Roll Deg", rollDeg); + telemetry.addData("Forward", forward); + telemetry.addData("Turn", turn); + telemetry.addData("Arm Angle", armAxis.actual()); + telemetry.addData("Claw Angle", clawAxis.actual()); + telemetry.addData("Grip", clawCtl.isGripping() ? "PRESSING" : "loose"); + telemetry.addData("Object", objectSecured ? "SECURED" : "NONE"); + telemetry.addData("Drive Sc", driveScale); + telemetry.addData("RAW", rawButtons); + team205ReportPower(telemetry, powerGuard); + } + + void stop() override { + drive.stop(); + + // A clean stop means the match is over — clear the persisted grip so + // the next run does not come up clamping onto nothing. + gripMemory.set(false); + + arm.detach(); + claw.detach(); + userLed.setOff(); + noTone(BUZZER_PIN); + } +}; + +REGISTER_OPMODE(TiltSteering, "Tilt Steering", TELEOP); |
