summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBEAST <macbook@Macbooks-MacBook-Pro-2.local>2026-11-16 19:23:09 +0530
committerBEAST <macbook@Macbooks-MacBook-Pro-2.local>2026-11-16 19:23:09 +0530
commit7764125350e66e464dded24ca8cf69a7e1ecef8d (patch)
treee01f8b3a15fe905d6e5ccc3da6822df238b49030
Add local project files
-rw-r--r--.gitignore41
-rw-r--r--ControllerFirmware/README.md29
-rwxr-xr-xControllerFirmware/flash-controller.bat45
-rw-r--r--ControllerFirmware/flash-controller.sh27
-rw-r--r--ControllerFirmware/flash_controller.py311
-rw-r--r--ControllerFirmware/prebuilt/build-manifest.json12
-rw-r--r--ControllerFirmware/prebuilt/controller_merged.binbin0 -> 1065392 bytes
-rw-r--r--README.md321
-rw-r--r--RobotFirmware/.gitignore5
-rw-r--r--RobotFirmware/boards/esp32s3_nrl_robot.json33
-rw-r--r--RobotFirmware/lib/HexaNRL/build-manifest.json72
-rw-r--r--RobotFirmware/lib/HexaNRL/lib/xtensa-esp32s3/libHexaNRL_static.abin0 -> 502564 bytes
-rw-r--r--RobotFirmware/lib/HexaNRL/library.json7
-rw-r--r--RobotFirmware/lib/HexaNRL/src/BoardPins.h92
-rw-r--r--RobotFirmware/lib/HexaNRL/src/DriveActions.h125
-rw-r--r--RobotFirmware/lib/HexaNRL/src/DriveTuning.h53
-rw-r--r--RobotFirmware/lib/HexaNRL/src/Gamepad.h86
-rw-r--r--RobotFirmware/lib/HexaNRL/src/NRL.h64
-rw-r--r--RobotFirmware/lib/HexaNRL/src/NRLAction.h56
-rw-r--r--RobotFirmware/lib/HexaNRL/src/NRLComms.h222
-rw-r--r--RobotFirmware/lib/HexaNRL/src/NRLGamepad.h81
-rw-r--r--RobotFirmware/lib/HexaNRL/src/NRLOpMode.h173
-rw-r--r--RobotFirmware/lib/HexaNRL/src/NRLPublic.h18
-rw-r--r--RobotFirmware/lib/HexaNRL/src/NRLTelemetry.h72
-rw-r--r--RobotFirmware/lib/HexaNRL/src/NRLVersion.h13
-rw-r--r--RobotFirmware/lib/HexaNRL/src/OpModeRegistry.h83
-rw-r--r--RobotFirmware/lib/HexaNRL/src/RobotConfig.h96
-rw-r--r--RobotFirmware/lib/HexaNRL/src/TankDrive.h87
-rw-r--r--RobotFirmware/lib/HexaNRL/src/examples/ExampleSeq.h69
-rw-r--r--RobotFirmware/lib/HexaNRL/src/examples/ExampleSubsystem.h41
-rw-r--r--RobotFirmware/lib/HexaNRL/src/examples/platformio.ini53
-rw-r--r--RobotFirmware/link_prebuilt.py57
-rw-r--r--RobotFirmware/opmodes/drivemode.cpp575
-rw-r--r--RobotFirmware/opmodes/normaldrive.cpp434
-rw-r--r--RobotFirmware/opmodes/pixelpoker_auto.cpp636
-rw-r--r--RobotFirmware/opmodes/team205_mech.h472
-rw-r--r--RobotFirmware/opmodes/tiltsteering.cpp312
-rw-r--r--RobotFirmware/partitions.csv8
-rw-r--r--RobotFirmware/platformio.ini43
-rw-r--r--RobotFirmware/src/RobotMain.ino24
-rw-r--r--Suncity 54 team 1.code-workspace75
-rw-r--r--lib/HexaHAL/build-manifest.json72
-rw-r--r--lib/HexaHAL/library.json15
-rw-r--r--lib/HexaHAL/library.properties9
-rw-r--r--lib/HexaIMU/build-manifest.json72
-rw-r--r--lib/HexaIMU/keywords.txt43
-rw-r--r--lib/HexaIMU/lib/xtensa-esp32s3/libHexaIMU_static.abin0 -> 11576 bytes
-rw-r--r--lib/HexaIMU/library.json15
-rw-r--r--lib/HexaIMU/library.properties10
-rw-r--r--lib/HexaIMU/src/HexaIMU.h164
-rw-r--r--lib/HexaLED/build-manifest.json72
-rw-r--r--lib/HexaLED/lib/xtensa-esp32s3/libHexaLED_static.abin0 -> 12552 bytes
-rw-r--r--lib/HexaLED/library.json15
-rw-r--r--lib/HexaLED/library.properties9
-rw-r--r--lib/HexaLED/src/HexaLED.h70
-rw-r--r--lib/HexaOLED/build-manifest.json72
-rw-r--r--lib/HexaOLED/keywords.txt30
-rw-r--r--lib/HexaOLED/lib/xtensa-esp32s3/libHexaOLED_static.abin0 -> 23038 bytes
-rw-r--r--lib/HexaOLED/library.json15
-rw-r--r--lib/HexaOLED/library.properties9
-rw-r--r--lib/HexaOLED/src/HexaFont.h135
-rw-r--r--lib/HexaOLED/src/HexaOLED.h214
-rw-r--r--lib/HexaPower/build-manifest.json72
-rw-r--r--lib/HexaPower/lib/xtensa-esp32s3/libHexaPower_static.abin0 -> 9140 bytes
-rw-r--r--lib/HexaPower/library.json15
-rw-r--r--lib/HexaPower/src/HexaPower.h171
-rw-r--r--lib/HexaServos/build-manifest.json72
-rw-r--r--lib/HexaServos/keywords.txt30
-rw-r--r--lib/HexaServos/lib/xtensa-esp32s3/libHexaServos_static.abin0 -> 23362 bytes
-rw-r--r--lib/HexaServos/library.json15
-rw-r--r--lib/HexaServos/library.properties9
-rw-r--r--lib/HexaServos/src/HexaDCMotor.h130
-rw-r--r--lib/HexaServos/src/HexaServo.h186
-rw-r--r--nrl-project.json7
-rw-r--r--tools/ensure-python.ps1208
-rw-r--r--tools/ensure-python.sh173
-rwxr-xr-xtools/new-nrl-opmode.bat29
-rw-r--r--tools/new-nrl-opmode.sh19
-rw-r--r--tools/nrl_new_opmode.py307
79 files changed, 7507 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e788257
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,41 @@
+# PlatformIO build artifacts
+.pio/
+RobotFirmware/.pio/
+ControllerFirmware/.pio/
+
+# VSCode generated files
+.vscode/.browse.c_cpp.db*
+.vscode/c_cpp_properties.json
+.vscode/launch.json
+.vscode/ipch
+RobotFirmware/.vscode/
+ControllerFirmware/.vscode/
+
+# OS files
+.DS_Store
+Thumbs.db
+
+# Python (project generator cache)
+__pycache__/
+*.pyc
+
+# kitbuilder output (regenerable, not committed)
+dist/
+
+# Key material. NEVER commit, encrypted or not.
+#
+# tools/kitbuilder/provisioning/.gitignore already covers keys/ and *.pem, but
+# it only applies to that subtree. `nrl_license.py backup --out backup/` writes
+# to the REPO ROOT by default, which that file cannot see -- so a real encrypted
+# signing key sat here untracked-but-not-ignored, one `git add -A` from history.
+#
+# Backups belong outside the working tree entirely (an encrypted volume, not a
+# git checkout). These rules are the second layer, for the day someone types
+# --out backup/ again out of habit.
+backup/
+*.pem
+*.p12
+*.key
+license_private*
+*_private_encrypted*
+*_backup_sheet.html
diff --git a/ControllerFirmware/README.md b/ControllerFirmware/README.md
new file mode 100644
index 0000000..673fdde
--- /dev/null
+++ b/ControllerFirmware/README.md
@@ -0,0 +1,29 @@
+# NRL Controller — Prebuilt Firmware
+
+The controller firmware ships as a single prebuilt binary. There is **no source
+to build here** — students never edit the controller. Your robot code lives in
+`RobotFirmware/opmodes/`.
+
+## Flash the controller
+
+1. Plug the controller into USB (use a **data** cable, not a charge-only one).
+2. **Windows:** double-click **`flash-controller.bat`** in this folder.
+ **macOS / Linux:** run `bash flash-controller.sh`.
+ (Or from VS Code: `Ctrl+Shift+P` → `Tasks: Run Task` → **`NRL: Flash Controller`**.)
+
+ Everything 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 are skipped. If several possible ports are found you'll be asked to pick.
+
+3. On the controller screen, open the **WiFi Channel** picker and select your
+ team's channel. It's saved on the device and survives reboots — the robot
+ must be on the same channel.
+
+**If no serial device is found:** try another USB cable/port (no hubs), and if the
+board 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
+
+Power users: `py -3 flash_controller.py --port COM7 --baud 115200` works too.
+
+`prebuilt/controller_merged.bin` is the full flash image (flashed at offset 0x0).
+`prebuilt/build-manifest.json` records exactly which commit/toolchain produced it.
diff --git a/ControllerFirmware/flash-controller.bat b/ControllerFirmware/flash-controller.bat
new file mode 100755
index 0000000..f08023a
--- /dev/null
+++ b/ControllerFirmware/flash-controller.bat
@@ -0,0 +1,45 @@
+@echo off
+rem ===================================================================
+rem NRL - Flash the Controller (double-click launcher, Windows)
+rem Writes the prebuilt controller firmware to a plugged-in controller.
+rem ===================================================================
+setlocal
+title NRL - Flash Controller
+
+set "SCRIPT=%~dp0flash_controller.py"
+
+rem Find a usable Python 3 via the kit's installer helper (in ..\tools\);
+rem if this ControllerFirmware folder was copied without tools\, fall back
+rem to whatever py/python is already on this PC.
+set "ENSURE=%~dp0..\tools\ensure-python.ps1"
+set "PYEXE="
+if exist "%ENSURE%" (
+ for /f "usebackq delims=" %%i in (`powershell -NoProfile -ExecutionPolicy Bypass -File "%ENSURE%"`) do set "PYEXE=%%i"
+)
+if defined PYEXE goto run
+
+where py >nul 2>nul
+if errorlevel 1 goto try_python
+set "PYEXE=py"
+goto run
+
+:try_python
+where python >nul 2>nul
+if errorlevel 1 goto no_python
+set "PYEXE=python"
+goto run
+
+:run
+"%PYEXE%" "%SCRIPT%" %*
+goto end
+
+:no_python
+echo.
+echo [error] Python 3 was not found and could not be installed automatically.
+echo Install Python 3 from https://www.python.org/downloads/ and re-run,
+echo ticking "Add python.exe to PATH" during setup.
+
+:end
+echo.
+if not defined NRL_NO_PAUSE pause
+endlocal
diff --git a/ControllerFirmware/flash-controller.sh b/ControllerFirmware/flash-controller.sh
new file mode 100644
index 0000000..eda9b5a
--- /dev/null
+++ b/ControllerFirmware/flash-controller.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# ===================================================================
+# NRL - Flash the Controller (launcher, macOS / Linux)
+# Writes the prebuilt controller firmware to a plugged-in controller.
+# Usage: bash flash-controller.sh (or chmod +x and run it)
+# ===================================================================
+set -euo pipefail
+
+here="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
+script="$here/flash_controller.py"
+
+# Find a usable Python 3 via the kit's installer helper (in ../tools/);
+# if this ControllerFirmware folder was copied without tools/, fall back
+# to whatever python3 is already on this machine.
+pyexe=""
+if [ -f "$here/../tools/ensure-python.sh" ]; then
+ pyexe="$(bash "$here/../tools/ensure-python.sh")" || pyexe=""
+fi
+if [ -z "$pyexe" ] && command -v python3 >/dev/null 2>&1; then
+ pyexe="python3"
+fi
+if [ -z "$pyexe" ]; then
+ echo "[error] Python 3 was not found and could not be installed automatically." >&2
+ echo " Install Python 3 from https://www.python.org/downloads/ and re-run." >&2
+ exit 1
+fi
+exec "$pyexe" "$script" "$@"
diff --git a/ControllerFirmware/flash_controller.py b/ControllerFirmware/flash_controller.py
new file mode 100644
index 0000000..a88cafe
--- /dev/null
+++ b/ControllerFirmware/flash_controller.py
@@ -0,0 +1,311 @@
+#!/usr/bin/env python3
+"""
+flash_controller.py — flash the prebuilt NRL controller firmware to a connected
+ESP32-S3 controller. No source, no compile -- this writes a single prebuilt
+image. Set your team's radio channel afterwards from the controller's on-screen
+WiFi-channel picker (it persists across reboots).
+
+Easiest: double-click flash-controller.bat (Windows) / run flash-controller.sh
+(macOS, Linux) in this folder -- they find or install Python for you and run this.
+
+Direct usage:
+ py -3 flash_controller.py # auto-detect the serial port
+ py -3 flash_controller.py --port COM7 # or name it explicitly
+ py -3 flash_controller.py --manual-download # board already in download mode
+
+If a board's auto-reset circuit does not work, flashing fails until the board is
+put into download mode by hand (hold BOOT, tap RESET, release BOOT). That is
+offered automatically after the normal attempts fail; --manual-download skips
+straight to it.
+
+Installs esptool automatically into this Python if it isn't already present.
+The controller's serial port is detected by its USB bridge chip -- phantom
+system ports (e.g. Intel AMT "SOL") are ignored automatically.
+"""
+import argparse
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+MERGED = Path(__file__).resolve().parent / "prebuilt" / "controller_merged.bin"
+
+# The NVS partition, which this script must NEVER write. Same offset and size in
+# BOTH ControllerFirmware/partitions.csv and RobotFirmware/partitions.csv
+# (nvs, 0x9000, 0x5000).
+#
+# WHY: the merged image is contiguous from 0x0, so writing it whole blanks NVS
+# along the way. On a controller that only costs the saved pairing/channel. On a
+# ROBOT -- plugged in by mistake, which happens -- NVS holds the board's licence
+# (namespace "nrl", key "lic"), and only the Flash Station can reissue it. The
+# robot then boots dark (blank OLED, no LED, ST:E27 on serial) even after the
+# correct robot firmware is uploaded again, and looks like a dead board.
+#
+# So the image is written as two pieces that skip this window. The merged image
+# holds nothing but 0xFF padding there (nothing is placed between the partition
+# table at 0x8000 and otadata at 0xe000); split_image() checks that rather than
+# assuming it.
+NVS_START = 0x9000
+NVS_END = 0xE000
+
+# USB vendor IDs of the serial bridges an NRL controller can show up as.
+# Anything NOT in this list (motherboard UARTs, Intel AMT "SOL" ports, ...)
+# is never the controller and only breaks esptool's own auto-detect.
+KNOWN_BRIDGES = {
+ 0x10C4: "CP210x USB-UART bridge",
+ 0x1A86: "CH340 USB-UART bridge",
+ 0x0403: "FTDI USB-UART bridge",
+ 0x303A: "Espressif native USB",
+}
+
+CP210X_DRIVER_URL = "https://www.silabs.com/software-and-tools/usb-to-uart-bridge-vcp-drivers"
+
+
+def ensure_esptool():
+ try:
+ import esptool # noqa: F401
+ return
+ except ImportError:
+ pass
+ print("[setup] esptool not found for this Python -- installing it now...")
+ try:
+ subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "esptool"], check=True)
+ except subprocess.CalledProcessError:
+ sys.exit(
+ "[error] Could not install esptool automatically (no internet, or pip is "
+ "unavailable for this Python). Run: pip install esptool"
+ )
+
+
+def pick_port(label: str = "the controller") -> str:
+ """Return a serial port for `label`, or None to let esptool auto-detect.
+
+ Filters out non-USB system ports entirely -- on many school/office laptops a
+ phantom 'Intel AMT SOL' COM port exists, and esptool's own auto-detect will
+ try it first and fail with 'No serial data received'.
+
+ `label` exists so this same logic serves more than the controller-flashing
+ case this file was written for. This file is copied byte-for-byte into
+ every student kit with no other files alongside it (see
+ tools/kitbuilder/build_controller_bin.py's STUDENT_FILES / copyfile), so it
+ cannot import a shared module -- it has to BE the shared implementation.
+ tools/kitbuilder/provisioning/board_ports.py imports straight from this
+ file rather than duplicating it, so there is exactly one copy of this logic
+ to ever go stale.
+ """
+ from serial.tools import list_ports # pyserial -- installed with esptool
+
+ ports = list(list_ports.comports())
+ known = [p for p in ports if p.vid in KNOWN_BRIDGES]
+ other_usb = [p for p in ports if p.vid is not None and p.vid not in KNOWN_BRIDGES]
+
+ if len(known) == 1:
+ p = known[0]
+ print(f"[setup] Using {p.device} ({KNOWN_BRIDGES[p.vid]}) for {label}")
+ return p.device
+
+ if known:
+ candidates = known
+ print(f"[setup] More than one possible port for {label} was found:")
+ elif other_usb:
+ candidates = other_usb
+ print(f"[setup] No known bridge chip found for {label}; other USB serial ports exist:")
+ else:
+ sys.exit(
+ f"[error] No USB serial device found for {label}. Check that:\n"
+ f" 1. {label.capitalize()} is plugged in and (if it has one) its power switch is ON.\n"
+ " 2. The USB cable is a DATA cable (many are charge-only!). Try another cable.\n"
+ " 3. It is plugged directly into the computer, not through a hub/dock.\n"
+ " 4. The USB driver is installed -- if the board never appears in Device\n"
+ f" Manager under 'Ports (COM & LPT)', install it from:\n {CP210X_DRIVER_URL}"
+ )
+
+ for i, p in enumerate(candidates, 1):
+ print(f" {i}. {p.device} ({p.description})")
+ while True:
+ choice = input(f"Which one is {label}? [1-{len(candidates)}]: ").strip()
+ if choice.isdigit() and 1 <= int(choice) <= len(candidates):
+ return candidates[int(choice) - 1].device
+ print("Please enter one of the listed numbers.")
+
+
+def split_image(merged, out_dir):
+ """Cut `merged` into (head, tail) files that together skip the NVS window.
+
+ Refuses -- rather than silently flashing something different -- if the
+ window holds anything but erased-flash padding: that would mean the image
+ layout changed and skipping it would drop real data.
+ """
+ data = Path(merged).read_bytes()
+ if len(data) <= NVS_END:
+ sys.exit(f"[error] {merged} is too small ({len(data)} bytes) to be a "
+ f"controller image. Re-download the kit.")
+ if data[NVS_START:NVS_END].strip(b"\xff"):
+ sys.exit(f"[error] {merged} has data inside the settings area "
+ f"(0x{NVS_START:X}-0x{NVS_END:X}), which this script never writes.\n"
+ f" The image does not match this flasher -- re-download the kit.")
+ head = Path(out_dir) / "controller_head.bin"
+ tail = Path(out_dir) / "controller_tail.bin"
+ head.write_bytes(data[:NVS_START])
+ tail.write_bytes(data[NVS_END:])
+ return head, tail
+
+
+def flash(port, baud, parts, before=None, after=None):
+ cmd = [sys.executable, "-m", "esptool", "--chip", "esp32s3"]
+ if port:
+ cmd += ["--port", port]
+ # Left unset by default so esptool keeps its own (--before default_reset,
+ # --after hard_reset). Only the manual-download path overrides them.
+ #
+ # Reset modes are spelled with UNDERSCORES, and that is not cosmetic:
+ # esptool 4.x declares choices=[default_reset, usb_reset, no_reset,
+ # no_reset_no_sync] and rejects "no-reset" in argparse, before it ever
+ # opens the port. 5.x accepts either. ensure_esptool() pins no version, so
+ # a machine that already had 4.x installed gets whichever it has -- and a
+ # hyphen there would fail exactly when the fallback was meant to rescue
+ # someone. Underscores work on both.
+ #
+ # 5.x does warn that the underscored choice is deprecated, so BOTH spellings
+ # are deprecated in one direction or the other. Underscores still win: 4.x
+ # errors out on a hyphen, 5.x only prints a warning on an underscore, and a
+ # warning is survivable where an argparse error is not.
+ if before:
+ cmd += ["--before", before]
+ if after:
+ cmd += ["--after", after]
+ # "write_flash", not "write-flash": esptool 5.x renamed the subcommand and
+ # warns that the underscored form is deprecated, but 4.x has ONLY the
+ # underscored form. The warning is the price of working on both. If a future
+ # esptool drops the alias this breaks, and the fix is to pin a version in
+ # ensure_esptool() -- not to switch spelling and break every 4.x machine.
+ #
+ # Two regions in ONE esptool call (not two calls): same single connect and
+ # reset as before, so the manual-download fallback behaves identically.
+ head, tail = parts
+ cmd += ["--baud", baud, "write_flash",
+ "0x0", str(head), f"0x{NVS_END:x}", str(tail)]
+ subprocess.run(cmd, check=True)
+
+
+def flash_manual_download(port, baud, parts):
+ """Flash a board whose auto-reset circuit does not reliably work.
+
+ esptool's default `--before default_reset` drives DTR/RTS to pull EN and
+ GPIO0 low -- that is how a healthy board enters download mode with nobody
+ touching it. Where that circuit is unreliable the board never enters
+ download mode, every attempt fails with "Failed to connect", and the
+ obvious reading of that message sends someone off swapping cables and USB
+ ports that were never the problem.
+
+ UNRELIABLE, NOT DEAD -- and the distinction matters. Controller
+ d0:cf:13:1a:94:e4 failed both auto-reset attempts twice on 2026-09-05,
+ through two different tools, and needed this path to flash at all. On
+ 2026-09-06 the same board connected first try, repeatedly, with no
+ intervention.
+
+ So do not expect a board to reproduce the fault on demand, and do not let a
+ successful flash retire this code path. An intermittent fault is worse than
+ a dead one: a board that always fails gets diagnosed, while one that fails
+ every fifth attempt gets blamed on the cable, the port, the operator, and
+ finally on nothing at all.
+
+ `--before no_reset` tells esptool the board is ALREADY in download mode, so
+ a person can do by hand what the circuit cannot.
+
+ `--after no_reset` for the same reason, and it is not optional: if DTR/RTS
+ cannot reset the board before flashing it cannot reset it afterwards
+ either, so esptool's usual hard_reset would silently do nothing and leave
+ the board sitting in download mode -- flashed correctly, but looking dead.
+ Say so instead, and have the operator press RESET.
+ """
+ print("\n" + "=" * 68)
+ print(" The board did not enter download mode on its own.")
+ print(" Common on boards whose auto-reset circuit is not working, and it")
+ print(" is NOT a cable or port fault. Put it in download mode by hand:")
+ print()
+ print(" 1. HOLD the BOOT button down")
+ print(" 2. Press and release RESET (while still holding BOOT)")
+ print(" 3. Release BOOT")
+ print("=" * 68)
+ try:
+ input("\nPress Enter once the board is in download mode (Ctrl+C to give up): ")
+ except EOFError:
+ # No console to prompt on (piped or automated run). Do not just try
+ # anyway: the board almost certainly is not in download mode, so a
+ # third identical failure would be noise rather than information.
+ sys.exit(
+ "[error] Auto-reset failed and there is no console to prompt on.\n"
+ " Put the board in download mode (hold BOOT, tap RESET,\n"
+ " release BOOT) and re-run with --manual-download."
+ )
+ flash(port, baud, parts, before="no_reset", after="no_reset")
+ print("\n[setup] Flashed. Press RESET on the board to start the new firmware --")
+ print(" auto-reset cannot do it for you on this board.")
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument("--port", help="Serial port (auto-detected if omitted).")
+ ap.add_argument("--baud", default="921600", help="Upload baud (default 921600).")
+ ap.add_argument("--manual-download", action="store_true",
+ help="The board is ALREADY in download mode (hold BOOT, tap RESET, "
+ "release BOOT). Skips auto-reset entirely -- use on boards whose "
+ "auto-reset circuit does not work.")
+ args = ap.parse_args()
+
+ if not MERGED.is_file():
+ sys.exit(f"[error] Prebuilt image not found: {MERGED}")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ # Split (and validate) before touching the board, so a bad image is
+ # refused without a single byte written.
+ parts = split_image(MERGED, tmp)
+ ensure_esptool()
+ port = args.port or pick_port()
+ _flash_with_fallbacks(args, port, parts)
+ print("\nDone. On the controller, open the WiFi-channel screen and pick your team's channel.")
+
+
+def _flash_with_fallbacks(args, port, parts):
+ try:
+ if args.manual_download:
+ # Asked for up front, so skip the two attempts already known to fail
+ # on such a board rather than making an operator sit through ~40s of
+ # them on every unit of a bad batch.
+ print("Flashing NRL controller firmware (manual download mode)...")
+ flash(port, args.baud, parts, before="no_reset", after="no_reset")
+ print("\n[setup] Press RESET on the board to start the new firmware.")
+ else:
+ print("Flashing NRL controller firmware...")
+ try:
+ flash(port, args.baud, parts)
+ except subprocess.CalledProcessError:
+ # Slow/flaky USB paths sometimes fail at full speed -- one retry, slower.
+ if args.baud != "115200":
+ print("\n[setup] Flash failed at full speed -- retrying at 115200 baud...")
+ flash(port, "115200", parts)
+ else:
+ raise
+ except subprocess.CalledProcessError as e:
+ # Every attempt that relies on auto-reset has now failed. This used to
+ # end at "Check the cable/port and try again", which is wrong whenever
+ # the auto-reset circuit is the fault: the cable and port are fine and
+ # swapping them proves nothing. Offer the route that actually works.
+ if args.manual_download:
+ sys.exit(f"[error] Flash failed in manual download mode (exit {e.returncode}).\n"
+ f" Check the board really is in download mode, and that\n"
+ f" {port or 'the auto-detected port'} is the right port.")
+ try:
+ flash_manual_download(port, "115200", parts)
+ except subprocess.CalledProcessError as e2:
+ sys.exit(f"[error] Flash failed in download mode too (exit {e2.returncode}).\n"
+ f" If BOOT+RESET was held correctly, suspect the board.")
+ except KeyboardInterrupt:
+ sys.exit("\n[error] Cancelled. Nothing was written to the board.")
+ except FileNotFoundError:
+ sys.exit("[error] Could not run Python. Is Python on your PATH?")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ControllerFirmware/prebuilt/build-manifest.json b/ControllerFirmware/prebuilt/build-manifest.json
new file mode 100644
index 0000000..c6057a4
--- /dev/null
+++ b/ControllerFirmware/prebuilt/build-manifest.json
@@ -0,0 +1,12 @@
+{
+ "artifact": "controller_merged.bin",
+ "controller_version": "1.5.5",
+ "flash_offset": "0x0",
+ "built_from_commit": "036661d7fa9340e198bf3f6d376121ae8c214f59",
+ "built_at": "2026-10-10T14:39:10.856239+00:00",
+ "env": "controller",
+ "license_pubkey_prefixes": [
+ "04f1ceb09456b9a6",
+ "0415c23c9830b4ce"
+ ]
+} \ No newline at end of file
diff --git a/ControllerFirmware/prebuilt/controller_merged.bin b/ControllerFirmware/prebuilt/controller_merged.bin
new file mode 100644
index 0000000..4e35424
--- /dev/null
+++ b/ControllerFirmware/prebuilt/controller_merged.bin
Binary files differ
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..9a7bd03
--- /dev/null
+++ b/README.md
@@ -0,0 +1,321 @@
+# NRL SDK
+### National Robotics League · for the Hexa Command Hub
+
+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.
+
+---
+
+## Hardware Required
+
+| 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
+```
+
+> ⚠️ 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.
+
+The robot's battery voltage is also sent to the Controller and shown in its header.
+
+**MCP3008 channel map / pins** (also in `RobotFirmware/lib/HexaNRL/src/BoardPins.h`):
+
+| 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 |
+
+**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.
+
+---
+
+## 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`:
+
+| 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 |
+
+Read an external ADC port with the global `power` object: `power.readChannelVoltage(ADC_EXT_1)`.
+
+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.
+
+> ⚠️ 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.
+
+---
+
+## Software Required
+
+1. [VSCode](https://code.visualstudio.com/)
+2. [PlatformIO IDE extension](https://platformio.org/install/ide?install=vscode) for VSCode
+
+That's it. PlatformIO automatically downloads all library dependencies on first build.
+
+---
+
+## Getting Started
+
+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.
+
+**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.
+
+**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`**
+
+It asks for **project name**, **team number**, **team name** and **location**, then creates the
+project.
+
+**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.
+
+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.
+
+#### 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`.
+
+> **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.
+
+---
+
+## 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):
+
+| 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. |
+
+A small TeleOp (tank drive plus a gripper on a button):
+
+```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
+```
+
+---
+
+## License
+
+MIT — free to use, modify, and distribute for educational and competition purposes.
diff --git a/RobotFirmware/.gitignore b/RobotFirmware/.gitignore
new file mode 100644
index 0000000..89cc49c
--- /dev/null
+++ b/RobotFirmware/.gitignore
@@ -0,0 +1,5 @@
+.pio
+.vscode/.browse.c_cpp.db*
+.vscode/c_cpp_properties.json
+.vscode/launch.json
+.vscode/ipch
diff --git a/RobotFirmware/boards/esp32s3_nrl_robot.json b/RobotFirmware/boards/esp32s3_nrl_robot.json
new file mode 100644
index 0000000..bc8b41d
--- /dev/null
+++ b/RobotFirmware/boards/esp32s3_nrl_robot.json
@@ -0,0 +1,33 @@
+{
+ "build": {
+ "arduino": {
+ "ldscript": "esp32s3_out.ld"
+ },
+ "core": "esp32",
+ "extra_flags": "-DARDUINO_ESP32S3_DEV -DBOARD_HAS_PSRAM",
+ "f_cpu": "240000000L",
+ "f_flash": "80000000L",
+ "flash_mode": "qio",
+ "mcu": "esp32s3",
+ "variant": "esp32s3"
+ },
+ "connectivity": ["wifi", "bluetooth"],
+ "debug": {
+ "openocd_board": "esp32s3.cfg"
+ },
+ "frameworks": ["arduino"],
+ "hwids": [
+ ["0x303A", "0x1001"],
+ ["0x1A86", "0x55D3"]
+ ],
+ "name": "NRL HEXA COMMAND HUB — Robot (ESP32-S3)",
+ "upload": {
+ "flash_size": "4MB",
+ "maximum_ram_size": 524288,
+ "maximum_size": 4194304,
+ "require_upload_port": true,
+ "speed": 460800
+ },
+ "url": "https://www.espressif.com/en/products/socs/esp32-s3",
+ "vendor": "Espressif"
+}
diff --git a/RobotFirmware/lib/HexaNRL/build-manifest.json b/RobotFirmware/lib/HexaNRL/build-manifest.json
new file mode 100644
index 0000000..13da83a
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/build-manifest.json
@@ -0,0 +1,72 @@
+{
+ "source_lib": "RobotFirmware\\lib\\HexaNRL",
+ "sdk_version": "1.4.1",
+ "built_from_commit": "036661d7fa9340e198bf3f6d376121ae8c214f59",
+ "built_at": "2026-10-10T14:36:33.316861Z",
+ "harvested_from_project": "RobotFirmware",
+ "harvested_env": "robot",
+ "cxx_path": "C:\\Users\\thein\\.platformio\\packages\\toolchain-xtensa-esp32s3\\bin\\xtensa-esp32s3-elf-g++.exe",
+ "cxx_flags": [
+ "-std=gnu++17",
+ "-fexceptions",
+ "-fno-rtti",
+ "-Os",
+ "-mlongcalls",
+ "-ffunction-sections",
+ "-fdata-sections",
+ "-Wno-error=unused-function",
+ "-Wno-error=unused-variable",
+ "-Wno-error=deprecated-declarations",
+ "-Wno-unused-parameter",
+ "-Wno-sign-compare",
+ "-ggdb",
+ "-freorder-blocks",
+ "-Wwrite-strings",
+ "-fstack-protector",
+ "-fstrict-volatile-bitfields",
+ "-Wno-error=unused-but-set-variable",
+ "-fno-jump-tables",
+ "-fno-tree-switch-conversion",
+ "-MMD",
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "defines": [
+ "PLATFORMIO=60200",
+ "ARDUINO_ESP32S3_DEV",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_RUNNING_CORE=1",
+ "ARDUINO_EVENT_RUNNING_CORE=1",
+ "CONFIG_FREERTOS_HZ=1000",
+ "CORE_DEBUG_LEVEL=3",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_USB_CDC_ON_BOOT=1",
+ "HAVE_CONFIG_H",
+ "MBEDTLS_CONFIG_FILE=\"mbedtls/esp_config.h\"",
+ "UNITY_INCLUDE_CONFIG_H",
+ "WITH_POSIX",
+ "_GNU_SOURCE",
+ "IDF_VER=\"v4.4.7-dirty\"",
+ "ESP_PLATFORM",
+ "_POSIX_READER_WRITER_LOCKS",
+ "ARDUINO_ARCH_ESP32",
+ "ESP32",
+ "F_CPU=240000000L",
+ "ARDUINO=10812",
+ "ARDUINO_VARIANT=\"esp32s3\"",
+ "ARDUINO_BOARD=\"Espressif ESP32-S3-DevKitC-1-N8 (8 MB QD, No PSRAM)\"",
+ "ARDUINO_PARTITION_partitions"
+ ],
+ "hardening": {
+ "extra_cxx_flags": [
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "symbols_stripped": true,
+ "strings_encrypted": true
+ }
+} \ No newline at end of file
diff --git a/RobotFirmware/lib/HexaNRL/lib/xtensa-esp32s3/libHexaNRL_static.a b/RobotFirmware/lib/HexaNRL/lib/xtensa-esp32s3/libHexaNRL_static.a
new file mode 100644
index 0000000..d3f8f1e
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/lib/xtensa-esp32s3/libHexaNRL_static.a
Binary files differ
diff --git a/RobotFirmware/lib/HexaNRL/library.json b/RobotFirmware/lib/HexaNRL/library.json
new file mode 100644
index 0000000..d2e9cfe
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/library.json
@@ -0,0 +1,7 @@
+{
+ "name": "HexaNRL",
+ "build": {
+ "libArchive": false,
+ "srcFilter": ["+<*>"]
+ }
+}
diff --git a/RobotFirmware/lib/HexaNRL/src/BoardPins.h b/RobotFirmware/lib/HexaNRL/src/BoardPins.h
new file mode 100644
index 0000000..1a01d07
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/BoardPins.h
@@ -0,0 +1,92 @@
+#pragma once
+
+// ============================================================
+// BoardPins.h — NRL board pin assignments
+// ============================================================
+// Use these constants when declaring hardware in your OpMode.
+//
+// Example:
+// HexaDCMotor leftMotor {{ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM }};
+// HexaServo arm {{ .signalPin = SERVO_1, .startAngle = 90.0f }};
+
+// Drive motors
+constexpr int MOTOR_L_DIR = 5;
+constexpr int MOTOR_L_PWM = 10;
+constexpr int MOTOR_R_DIR = 11;
+constexpr int MOTOR_R_PWM = 12;
+
+// Servo signal pins
+constexpr int SERVO_1 = 39;
+constexpr int SERVO_2 = 40;
+constexpr int SERVO_3 = 41;
+constexpr int SERVO_4 = 42;
+
+// I2C bus 0 — IMU (LSM6DSOX, default Wire)
+constexpr int I2C_SDA = 47;
+constexpr int I2C_SCL = 48;
+
+// I2C bus 1 — OLED display (SH1106, on Wire1)
+// Production PCB wires the OLED to its own bus, separate from the IMU.
+constexpr int OLED_SDA = 6;
+constexpr int OLED_SCL = 7;
+
+// MCP3008 8-channel SPI ADC — battery voltage + current sensing (HexaPower)
+// Dedicated SPI bus; VREF = 5.0V on this board (NOT 3.3V).
+// Channel map (as actually wired — verified by the 3-phase PowerTest):
+// CH0 → battery voltage sensor
+// CH1 → ACS712 #1 (MAIN / total battery current)
+// CH2 → ACS712 #2 (DC-motor branch current)
+// CH3..CH7 → external ADC breakout connectors
+// No dedicated servo sensor — servo current is derived as CH1 − CH2.
+constexpr int MCP3008_CS = 8;
+constexpr int MCP3008_SCK = 14;
+constexpr int MCP3008_MISO = 9;
+constexpr int MCP3008_MOSI = 13;
+
+// Misc
+constexpr int BUZZER_PIN = 21; // passive buzzer — use tone(BUZZER_PIN, freq)
+constexpr int BUTTON_PIN = 4; // tactile button — LOW when pressed
+constexpr int BOOT_PIN = 0; // ESP32-S3 BOOT strap button — LOW when pressed
+constexpr int LED_STATUS_PIN = 38; // NeoPixel status LED (WS2812B, 1 pixel)
+
+// General-purpose digital breakout (7 pins). The PCB silkscreens the first
+// 4 as encoder headers (J21/J22) and the last 3 as D1-D3 — all 7 are wired
+// as plain GPIO with no encoder-specific logic.
+constexpr int DIGITAL_1 = 1;
+constexpr int DIGITAL_2 = 2;
+constexpr int DIGITAL_3 = 15;
+constexpr int DIGITAL_4 = 16;
+constexpr int DIGITAL_5 = 35;
+constexpr int DIGITAL_6 = 36;
+constexpr int DIGITAL_7 = 37;
+
+// Bench-test-only 3rd/4th motor channels — the production board only wires
+// MOTOR_L/MOTOR_R above; these reuse the spare DIGITAL_1-4 GPIO breakout so a
+// bench test can exercise all 4 HexaDCMotor LEDC channels (motors use LEDC
+// channels 4-7). Wire an extra motor driver to these pins for testing only.
+constexpr int MOTOR_3_DIR = DIGITAL_1;
+constexpr int MOTOR_3_PWM = DIGITAL_2;
+constexpr int MOTOR_4_DIR = DIGITAL_3;
+constexpr int MOTOR_4_PWM = DIGITAL_4;
+
+// External digital-I/O headers as silkscreened D1–D3 (same pins as DIGITAL_5–7).
+// Use these names when driving the external DIO connectors (e.g. "IO Test").
+constexpr int DIGITAL_D1 = 35; // J14 PIN2
+constexpr int DIGITAL_D2 = 36; // J15 PIN2
+constexpr int DIGITAL_D3 = 37; // J16 PIN2
+
+// External ADC breakout connectors → MCP3008 channels CH3–CH7. These are ADC
+// channel numbers (not GPIO pins) — read via power.readChannelVoltage(ADC_EXT_1)
+// or power.readRaw(ADC_EXT_1). CH0–CH2 are reserved for battery/current sensing.
+constexpr int ADC_EXT_1 = 3;
+constexpr int ADC_EXT_2 = 4;
+constexpr int ADC_EXT_3 = 5;
+constexpr int ADC_EXT_4 = 6;
+constexpr int ADC_EXT_5 = 7;
+
+// External UART1 breakout (JST-XH). The QC jig fits a TX<->RX loopback jumper
+// here so the self-test can verify the port end to end — see _qcRunUartLoopback
+// in NRLRunner.cpp. Without the jumper QC:UART_OK cannot pass, and the test says
+// so ("NO DATA - check loopback jumper") rather than failing silently.
+constexpr int UART1_TX = 17;
+constexpr int UART1_RX = 18;
diff --git a/RobotFirmware/lib/HexaNRL/src/DriveActions.h b/RobotFirmware/lib/HexaNRL/src/DriveActions.h
new file mode 100644
index 0000000..5168b9c
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/DriveActions.h
@@ -0,0 +1,125 @@
+#pragma once
+#include "TankDrive.h"
+#include "NRLAction.h"
+#include "NRLComms.h"
+#include "DriveTuning.h"
+#include <cmath>
+#include <vector>
+#include <memory>
+
+// ============================================================
+// DriveActions — student-friendly motion primitives
+// ============================================================
+// Wraps TankDrive + the gyro heading already tracked by NRLComms
+// into named, chainable ActionPtrs that plug straight into
+// runAction()/runBlocking() — no hand-written wait_until/instant
+// glue needed per opmode.
+//
+// This hardware has no wheel encoders, so straight-line moves are
+// open-loop (speed * time, tune DriveTuning::msPerInch per robot)
+// while turns are closed-loop on NRLComms::getHeading().
+//
+// Single-shot usage:
+// static TankDrive drive(leftMotor, rightMotor);
+// static DriveActions driveActions(drive);
+// ...
+// runAction(driveActions.turn(90));
+//
+// Fluent chain usage:
+// runAction(driveActions.auto_()
+// .driveInches(24)
+// .turn(90)
+// .driveInches(12)
+// .turn(-90)
+// .build());
+//
+// Every method body lives in DriveActions.cpp (the prebuilt .a) — this
+// header is declarations only, so the drive/turn control logic can't be
+// read or edited from source.
+
+class DriveActions {
+public:
+ explicit DriveActions(TankDrive& drive, DriveTuning tuning = DriveTuning{})
+ : _drive(drive), _tuning(tuning) {}
+
+ void setTuning(const DriveTuning& t);
+ const DriveTuning& tuning() const;
+
+ // Relative turn: positive degrees = clockwise/right, negative = counter-
+ // clockwise/left, measured from whatever NRLComms's heading is right now
+ // (zeroes it first). This is the primitive most autos should use — it
+ // composes correctly step-to-step regardless of what "0" currently means.
+ ActionPtr turn(float degrees, int speed = -1) const;
+
+ // Absolute turn: target is an absolute heading in the current zero-frame
+ // (does NOT re-zero — use for a known fixed/field-relative heading).
+ ActionPtr turnTo(float targetHeadingDeg, int speed = -1) const;
+
+ // Open-loop timed straight drive. speed sign controls direction
+ // (positive = forward, negative = reverse); -1 is reserved as the
+ // "use DriveTuning::driveSpeed" sentinel.
+ ActionPtr driveForMs(unsigned long ms, int speed = -1) const;
+
+ // CLOSED-LOOP distance drive. Sign of `inches` sets the direction; `speed`
+ // overrides the magnitude (-1 = use tuning().driveSpeed).
+ //
+ // Drives until a FUSED estimate of distance traveled reaches the target:
+ // fused = w·imu + (1-w)·model (w = tuning.distFuseImuWeight)
+ // where `imu` is NRLComms' accel-integrated distance (senses real motion →
+ // robust to battery/surface) and `model` is the speed×time prediction
+ // (stable fallback). A hard time cap (distTimeoutScale × the speed×time
+ // estimate) guarantees it stops even if the IMU reading goes bad. Falls
+ // back to pure open-loop time if the IMU never calibrates.
+ //
+ // For pure open-loop time (no IMU), use driveForMs() instead.
+ ActionPtr driveInches(float inches, int speed = -1) const;
+
+ ActionPtr stopAll() const;
+
+ // Wait for the gyro bias calibration (~0.5 s) to finish before moving on.
+ // Put this FIRST in an auto routine if you call resetHeading() in init():
+ // it keeps the robot still until calibration completes so the bias estimate
+ // (and therefore every later turn) stays accurate.
+ ActionPtr waitForHeadingReady() const;
+
+ // ---- Fluent builder ----------------------------------------------
+ class Builder {
+ public:
+ explicit Builder(const DriveActions& owner) : _owner(owner) {}
+
+ Builder& turn(float degrees, int speed = -1);
+ Builder& turnTo(float targetHeadingDeg, int speed = -1);
+ Builder& driveForMs(unsigned long ms, int speed = -1);
+ Builder& driveInches(float inches, int speed = -1);
+ Builder& sleepMs(unsigned long ms);
+ Builder& waitForHeadingReady();
+ Builder& stopAll();
+
+ ActionPtr build();
+
+ private:
+ const DriveActions& _owner;
+ std::vector<ActionPtr> _steps;
+ };
+
+ Builder auto_() const;
+
+private:
+ TankDrive& _drive;
+ DriveTuning _tuning;
+
+ // Shared by turn()/turnTo(). Spins toward the target in a FIXED direction,
+ // easing the speed down within turnSlowdownDeg of the target so the chassis
+ // doesn't coast past it, then fires a short reverse brake pulse to cancel
+ // the leftover momentum.
+ //
+ // Sign safety: for a relative turn() we measure progress as fabs(heading)
+ // after zeroing, so it works no matter which way the gyro's sign runs (the
+ // command direction is fixed, exactly like the original hand-written turn).
+ // turnTo() uses signed progress toward an absolute heading.
+ //
+ // The turn sets a responsive ramp on TankDrive and does its OWN soft-start
+ // (limiting how fast the command rises) so deceleration near the target is
+ // not blocked by a slow inrush ramp left over from a forward drive.
+ ActionPtr _turnAction(float targetDeg, int speed, bool zeroFirst) const;
+};
diff --git a/RobotFirmware/lib/HexaNRL/src/DriveTuning.h b/RobotFirmware/lib/HexaNRL/src/DriveTuning.h
new file mode 100644
index 0000000..b53bba1
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/DriveTuning.h
@@ -0,0 +1,53 @@
+#pragma once
+
+// ============================================================
+// DriveTuning — tunable constants for DriveActions primitives
+// ============================================================
+// No encoders exist on this hardware, so straight-line distance is
+// open-loop (speed * time, empirically tuned per robot) while turns
+// are closed-loop on the gyro heading (NRLComms::getHeading()).
+//
+// Override per-robot via DriveActions::setTuning() if your chassis
+// needs different values — don't edit the defaults here.
+struct DriveTuning {
+ int driveSpeed = 255; // default PWM (0..255) for driveForMs()/driveInches()
+ int turnSpeed = 255; // MAX PWM (0..255) for turn()/turnTo() while far from target
+
+ // Turns slow down as they approach the target so the chassis doesn't coast
+ // past it (momentum overshoot). Within `turnSlowdownDeg` of the target the
+ // speed eases from turnSpeed down to turnMinSpeed; the turn stops once it is
+ // within `turnToleranceDeg`, then fires a brief reverse brake pulse
+ // (`turnBrakeMs`) to cancel the remaining momentum.
+ int turnMinSpeed = 80; // PWM floor near the target (must still overcome friction)
+ // Lowered from 110: at 110 the chassis was still
+ // moving fast at the target and coasted ~14° past
+ // (90° turn ended near 104°). Arrive slower → less
+ // momentum to brake. Raise if a turn stalls short.
+ float turnSlowdownDeg = 60.0f; // start slowing this many degrees before the target
+ // (wider than 40° → longer, gentler deceleration)
+ float turnToleranceDeg = 2.0f; // stop once within this many degrees of the target
+ unsigned long turnBrakeMs = 200; // reverse brake pulse after reaching target (0 = off)
+ // Lengthened from 120ms to cancel more residual spin.
+
+ float msPerInch = 18.0f; // ms to travel 1 inch AT driveSpeed — TUNE per robot
+ // (starting estimate; recalibrate: drive a known
+ // time at driveSpeed, measure inches, ms / inches)
+ unsigned long turnTimeoutMs = 4000; // safety cutoff if a turn never reaches target
+
+ // driveInches() is CLOSED-LOOP: it drives until a FUSED distance estimate
+ // reaches the target. The estimate blends the IMU-measured distance (senses
+ // real motion → robust to battery voltage / surface) with the speed×time
+ // model (stable fallback). Weight the IMU high — it tracks reality far better
+ // than time when the battery state changes; the model is mainly a sanity
+ // anchor. distTimeoutScale × the nominal speed×time is the hard cap so a bad
+ // IMU reading can never drive forever.
+ float distFuseImuWeight = 0.85f; // 0 = time only … 1 = IMU only
+ float distTimeoutScale = 2.5f; // max drive time = this × the speed×time estimate
+
+ // driveInches() eases its speed down within driveSlowdownIn of the target
+ // (like turns) so the bot arrives slowly and barely coasts past it. The
+ // floor must still overcome friction. driveInches owns its ramp + soft-start,
+ // so it does NOT depend on the opmode's setRampRate().
+ int driveMinSpeed = 110; // PWM floor near the target
+ float driveSlowdownIn = 10.0f; // start slowing this many inches before the target
+};
diff --git a/RobotFirmware/lib/HexaNRL/src/Gamepad.h b/RobotFirmware/lib/HexaNRL/src/Gamepad.h
new file mode 100644
index 0000000..5419aeb
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/Gamepad.h
@@ -0,0 +1,86 @@
+#pragma once
+#include "NRLGamepad.h"
+#include <functional>
+
+// ============================================================
+// Gamepad — object-oriented gamepad interface
+// ============================================================
+// Wraps the static NRLGamepad globals with named accessors,
+// built-in edge detection, and optional button bindings.
+//
+// Global instance: gamepad1 (declared in RobotConfig)
+// Updated automatically at the top of each 100Hz TELEOP tick.
+//
+// Usage:
+// drive.drive(gamepad1.leftY(), gamepad1.rightX());
+// if (gamepad1.justPressed(BTN_DPAD_RIGHT)) runAction(sequential({ ... }));
+// ^ justPressed fires on the press only — that is what keeps runAction()
+// from queuing a fresh copy of the sequence 50 times a second.
+// gamepad1.onPress(BTN_DPAD_DOWN, []{ gripper.setPosition(90); }); // in init()
+
+class Gamepad {
+public:
+ // ----------------------------------------------------------
+ // Axis accessors (-1.0 to +1.0)
+ // ----------------------------------------------------------
+ float leftX() const;
+ float leftY() const;
+ float rightX() const;
+ float rightY() const;
+
+ // ----------------------------------------------------------
+ // Button state
+ // ----------------------------------------------------------
+ bool pressed(uint16_t btn) const;
+ bool justPressed(uint16_t btn) const;
+ bool justReleased(uint16_t btn) const;
+
+ // ----------------------------------------------------------
+ // Button bindings — register once in init(), not in loop()
+ // For sequences use justPressed in loop() instead.
+ // ----------------------------------------------------------
+ static constexpr uint8_t MAX_BINDINGS = 8;
+
+ void onPress(uint16_t btn, std::function<void()> cb);
+ void onRelease(uint16_t btn, std::function<void()> cb);
+
+ // ----------------------------------------------------------
+ // Called by NRLRunner at top of each 100Hz TELEOP tick.
+ // Not for student use.
+ // ----------------------------------------------------------
+ void snapshot();
+
+ // ----------------------------------------------------------
+ // reset() — Clear snapshots and bindings for OpMode restart.
+ // Called by NRLRunner when starting a new OpMode.
+ // Prevents stale button state from previous runs.
+ // ----------------------------------------------------------
+ void reset();
+
+ // ----------------------------------------------------------
+ // ignoreHeldButtons() — Called by NRLRunner on the first tick
+ // of a run. Buttons already held at that moment (the X that
+ // pressed START) are invisible until released once, so they
+ // cannot fire justPressed()/onPress() as the run begins.
+ // Not for student use.
+ // ----------------------------------------------------------
+ void ignoreHeldButtons();
+
+private:
+ struct Snap { float lx=0, ly=0, rx=0, ry=0; uint16_t buttons=0; };
+ Snap _curr, _prev; // buttons = what pressed() reports
+ uint16_t _edgeCurr = 0, _edgePrev = 0; // what justPressed()/justReleased() compare
+ uint16_t _raw = 0; // last raw buttons read
+ uint16_t _heldAtStart = 0; // hidden from pressed() AND edges until released
+ uint16_t _heldThroughOutage = 0; // hidden from edges only until released
+ uint32_t _staleSeq = 0; // packetSeq seen while input was stale
+ bool _awaitPacket = false; // stale ended, no real packet yet
+
+ struct Binding { uint16_t btn=0; std::function<void()> cb; };
+ Binding _press[MAX_BINDINGS];
+ Binding _release[MAX_BINDINGS];
+
+ void _setBind(Binding (&arr)[MAX_BINDINGS], uint16_t btn, std::function<void()> cb);
+};
+
+extern Gamepad gamepad1;
diff --git a/RobotFirmware/lib/HexaNRL/src/NRL.h b/RobotFirmware/lib/HexaNRL/src/NRL.h
new file mode 100644
index 0000000..69b0f8c
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/NRL.h
@@ -0,0 +1,64 @@
+#pragma once
+
+// ============================================================
+// NRL.h — student umbrella include
+// ============================================================
+// One line gives you everything you need:
+//
+// #include "NRL.h"
+//
+// Declare your hardware at file-scope (above your class),
+// initialise in init(), then use in loop():
+//
+// 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 arm {{ .signalPin = SERVO_1, .startAngle = 90.0f }};
+// static HexaServo gripper {{ .signalPin = SERVO_2, .startAngle = 15.0f }};
+// static HexaIMU imu { hexaImuConfig() }; // on-board IMU (Wire)
+// static HexaOLED myOled { hexaOledConfig() }; // on-board OLED (Wire1)
+// static TankDrive drive(leftMotor, rightMotor);
+// static DriveActions driveActions(drive);
+//
+// Gamepad (always available, no declaration needed):
+// gamepad1.leftY() — axis -1.0 to +1.0
+// gamepad1.justPressed(BTN_DPAD_RIGHT) — true on the tick of press
+//
+// User LED (always available, no declaration needed):
+// userLed.setSolid(255, 0, 0) — solid red
+// userLed.setBlink(0, 255, 0, 500) — blink green, 500ms period
+// userLed.setPulse(0, 0, 255, 1000) — breathe blue, 1s cycle
+// userLed.setOff() — turn off
+//
+// Battery voltage (always available, no declaration needed):
+// power.getBatteryVoltage() — robot pack voltage (V)
+// power.isBatteryLow() — true when the pack is low
+//
+// Rail current — read directly from `power` (always available, no declaration
+// needed). There is ONE ACS712 per rail, not one per motor/servo, so this is
+// the whole rail's current regardless of how many motors/servos you declared:
+// power.getMainCurrent() — total battery current (A)
+// power.getMotorCurrent() — DC-motor branch current (A)
+// power.getServoCurrent() — servo rail current (A, derived: main − motor)
+//
+// Telemetry:
+// telemetry.addData("key", value)
+
+// Hardware types
+#include "HexaDCMotor.h" // DC motor driver
+#include "HexaServo.h" // servo driver
+#include "HexaOLED.h" // 128×64 OLED display
+#include "HexaIMU.h" // LSM6DSOX IMU (accel + gyro + heading)
+#include "HexaPower.h" // MCP3008 ADC — battery voltage + ACS712 current
+#include "TankDrive.h" // differential drive helper
+#include "DriveTuning.h" // DriveTuning struct (speed/msPerInch/timeout defaults)
+#include "DriveActions.h" // DriveActions — turn(), driveInches(), auto_() chaining
+#include "Gamepad.h" // gamepad1 object
+
+// Framework internals
+#include "BoardPins.h" // MOTOR_L_DIR, SERVO_1, I2C_SDA … pin constants
+#include "RobotConfig.h" // botOled, gamepad1 (framework globals)
+#include "NRLGamepad.h" // BTN_X/A/B/Y, BTN_DPAD_*, BTN_RB/LB/LT/RT constants, NRLGamepad raw statics
+#include "NRLComms.h" // NRLComms::sendTelemetry("key", value)
+#include "NRLAction.h" // instant(), sequential(), parallel(), sleep_ms(), wait_until()
+#include "NRLOpMode.h" // NRLOpMode base class, init()/start()/loop()/stop(), runAction()
+#include "OpModeRegistry.h" // REGISTER_OPMODE macro
diff --git a/RobotFirmware/lib/HexaNRL/src/NRLAction.h b/RobotFirmware/lib/HexaNRL/src/NRLAction.h
new file mode 100644
index 0000000..cf9e5f0
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/NRLAction.h
@@ -0,0 +1,56 @@
+#pragma once
+#include <functional>
+#include <memory>
+#include <vector>
+#include <initializer_list>
+
+// ============================================================
+// NRLAction — composable action system
+// ============================================================
+//
+// Actions are single units of work that may span multiple ticks.
+// Each call to run() advances the action by one step and returns:
+// false — still in progress, call run() again next tick
+// true — complete, move on
+//
+// Build sequences with the factory functions below:
+//
+// instant([]{ /* code */ }) — runs once, done immediately
+// sequential({ a, b, c }) — runs a, then b, then c
+// parallel({ a, b, c }) — runs a, b, c at the same time
+// sleep_ms(500) — waits 500 ms
+// wait_until([]{ return condition; }) — waits until condition is true
+//
+// Example (in run() or loop()):
+//
+// runBlocking(sequential({
+// instant([]{ leftMotor.setSpeed(150); rightMotor.setSpeed(150); }),
+// sleep_ms(2000),
+// instant([]{ leftMotor.setSpeed(0); rightMotor.setSpeed(0); }),
+// }));
+
+class Action {
+public:
+ virtual ~Action() = default;
+ virtual bool run() = 0; // returns true when complete
+ virtual void reset(); // rewind to start; called by repeat() between cycles
+};
+
+using ActionPtr = std::shared_ptr<Action>;
+
+
+// ============================================================
+// Factory functions — user-facing API
+// ============================================================
+// The concrete Action subclasses and every function body live in
+// NRLAction.cpp (the prebuilt .a) — not in this header. Only these
+// declarations are visible, so the action engine can't be read or
+// edited from source.
+
+ActionPtr instant(std::function<void()> fn);
+ActionPtr sequential(std::initializer_list<ActionPtr> actions);
+ActionPtr sequential(std::vector<ActionPtr> actions); // used by DriveActions::Builder
+ActionPtr parallel(std::initializer_list<ActionPtr> actions);
+ActionPtr sleep_ms(unsigned long ms);
+ActionPtr wait_until(std::function<bool()> cond);
+ActionPtr repeat(ActionPtr inner);
diff --git a/RobotFirmware/lib/HexaNRL/src/NRLComms.h b/RobotFirmware/lib/HexaNRL/src/NRLComms.h
new file mode 100644
index 0000000..4f1527b
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/NRLComms.h
@@ -0,0 +1,222 @@
+#pragma once
+#include <Arduino.h>
+#include <WiFi.h>
+#include <esp_now.h>
+#include <esp_wifi.h>
+#include <esp_idf_version.h>
+
+// ============================================================
+// Per-project identity — stamped by the generator
+// (-DNRL_TEAM_NUMBER / -DNRL_TEAM_NAME / -DNRL_WIFI_CHANNEL).
+// Fallbacks live here (not in a .cpp) so every translation unit
+// that includes this header — incl. NRLRunner.cpp's OLED screens —
+// sees them, and keep the un-stamped base template building unchanged.
+// ============================================================
+#ifndef NRL_TEAM_NUMBER
+#define NRL_TEAM_NUMBER 0
+#endif
+#ifndef NRL_TEAM_NAME
+#define NRL_TEAM_NAME "NRL Team"
+#endif
+#ifndef NRL_WIFI_CHANNEL
+#define NRL_WIFI_CHANNEL 1
+#endif
+
+// The wire protocol — packet type IDs (PKT_*) and on-wire struct layouts — is
+// INTERNAL and deliberately not part of this header. It lives in
+// _internal/NRLPackets.h, which is compiled into libHexaNRL_static.a but never
+// shipped in the student kit, so the protocol can't be read or altered. Only
+// NRLComms.cpp / NRLRunner.cpp (inside the .a) include it. Opmodes use the
+// NRLComms class API below and never touch packets.
+
+// Telemetry capacity knobs — kept PUBLIC because the student-facing telemetry
+// buffer (NRLTelemetry.h) sizes its storage from these. The matching on-wire
+// NRLTelemetryPacket that packs NRL_TELEM_BATCH_MAX entries lives in
+// _internal/NRLPackets.h. Raising NRL_TELEM_MAX_ENTRIES later (e.g. to 100) is
+// a one-line change rather than a hunt through hardcoded array sizes.
+#define NRL_TELEM_MAX_ENTRIES 64 // buffer capacity on both bot and controller
+#define NRL_TELEM_BATCH_MAX 8 // entries packed into one ESP-NOW telemetry packet
+
+// ============================================================
+// NRLComms — ESP-NOW layer on the Robot
+// ============================================================
+class NRLComms {
+public:
+ // Team identity is handed in from RobotMain.ino at boot. That file is
+ // compiled inside the student's project, so it sees the per-project
+ // -DNRL_TEAM_NUMBER / -DNRL_TEAM_NAME / -DNRL_WIFI_CHANNEL stamp — which
+ // this prebuilt .a, built once from the unstamped template, cannot. Call
+ // once before any status is shown or sent. baseChannel is the stamped
+ // radio channel used as the NVS resync baseline.
+ static void begin(int teamNumber, const char* teamName, uint8_t baseChannel);
+ static void sendAdvertise();
+ static void sendStatus(uint8_t stateId, uint8_t loopOverrun = 0);
+ // Sends up to NRL_TELEM_BATCH_MAX key/value pairs in ONE ESP-NOW packet.
+ // items[i].key/val must be null-terminated, matching NRLTelemetryPacket's
+ // field widths (key<=11 chars, val<=15 chars).
+ struct TelemetryItem { const char* key; const char* val; };
+ static void sendTelemetryBatch(const TelemetryItem* items, uint8_t count);
+ static void sendServoState();
+ static void releaseCalibServos();
+ static void sendMotorState();
+ static void releaseCalibMotors();
+ static void sendIMUState();
+ static void tickCalibIMU(); // call from main loop — defers I2C out of ISR context
+ static void tickCalibServoMotor(); // call from main loop — defers calib servo/motor I2C+esp_now_send out of ISR context
+ static void tickHeading(); // call from main loop — reads IMU + integrates heading at ~100 Hz
+ static void tickPairing();
+
+ // Heading API — usable from any OpMode
+ static float getHeading(); // degrees since last resetHeading() / zeroHeading()
+ static bool isHeadingReady(); // true once bias calibration (~0.5 s) is complete
+ static void zeroHeading(); // set heading to 0°, keep existing bias (use before a turn)
+ static void resetHeading(); // full reset: zero heading + re-collect bias (robot must be still)
+
+ // Distance API — accel double-integration. TEACHING/DEMO ONLY: it drifts
+ // (tilt couples gravity in; bias grows as t²). Shares the heading bias
+ // calibration window — gate on isHeadingReady() before trusting it.
+ static float getDistanceInches(); // inches since last resetDistance()
+ static void resetDistance(); // zero velocity + distance, keep bias
+ static bool isPaired();
+ static bool isReconnecting();
+
+ // QC: true once a 0xFE QC-Station ping has been received (i.e. QC:COMMS_OK
+ // was emitted). Read by the robot's QC self-test so the OLED "PASS" verdict
+ // agrees with the flash station's COMMS milestone instead of showing PASS
+ // while ESP-NOW comms silently failed.
+ static bool qcCommsOk();
+ // True when the gamepad values must not be trusted: either we are not PAIRED
+ // at all, or no controller packet has arrived for STALE_INPUT_MS. Derived
+ // from _pairState/_lastCtrlMs rather than a cached flag, so it cannot drift
+ // out of step with the staleness handling in tickPairing().
+ static bool isInputStale();
+
+ // ── Link quality, per run ───────────────────────────────────────────────
+ // Reset by resetLinkStats() when an OpMode starts. dropoutCount() counts
+ // PAIRED -> RECONNECTING transitions; longestSilentMs() is the worst gap
+ // between controller packets, which shows a link degrading long BEFORE it
+ // trips the dropout threshold.
+ static void resetLinkStats();
+ static uint32_t dropoutCount();
+ static uint32_t longestSilentMs();
+
+#ifdef NRL_LINK_FAULT_INJECTION
+ // ── Bench fault injection (env robot-linktest only) ─────────────────────
+ // Simulates a total RF blackout for ms milliseconds WITHOUT touching the
+ // radio: incoming controller packets stop refreshing _lastCtrlMs, and
+ // outgoing STATUS is suppressed. Both watchdogs therefore fire exactly as
+ // they would in a real dropout — the robot goes RECONNECTING and the
+ // controller buzzes — but deterministically and repeatably, which shielding
+ // and distance are not. Compiled out of the shipping build.
+ static void debugBlackout(uint32_t ms);
+ static bool debugBlackoutActive();
+
+ // Watchdog-race probe. debugBlackout() can never reproduce the field exit:
+ // it SUPPRESSES packets, so _lastCtrlMs only ever ages. The real fault is the
+ // opposite - the ESP-NOW callback (core 0) stamping _lastCtrlMs with a time
+ // NEWER than the `now` tickPairing() (core 1) sampled a few microseconds
+ // earlier. This arms exactly that state for the next PAIRED tick, so the
+ // interleave that happens by chance on a field happens here on demand.
+ static void debugRaceArm();
+
+ // Airtime probe. Sends `frames` ESP-NOW frames of `payloadBytes` back to
+ // back and reports how long the RADIO actually took, as one
+ // machine-parseable AIRTIME: line for dev-docs/bench/airtime.py.
+ //
+ // Times send-COMPLETION callbacks, not esp_now_send() returns: send() only
+ // queues the frame, so timing it measures the queue rather than the air.
+ // Nothing else in this firmware registers a send callback, so the probe
+ // installs its own and removes it again afterwards.
+ //
+ // Why it exists: no PHY rate is configured anywhere (no
+ // esp_wifi_config_espnow_rate, no esp_now_set_peer_rate_config), so ESP-NOW
+ // runs at whatever the IDF default is. At 1 Mbps a 235-byte telemetry frame
+ // costs ~2 ms of air; at 24 Mbps under 0.1 ms. That gap dwarfs every other
+ // airtime lever, so it must be measured before any constant is tuned.
+ //
+ // Sweep payloadBytes to tell air-limited from queue-limited: if per-frame
+ // time grows with size we are measuring the air; if it is flat we are
+ // measuring the queue and the number means nothing.
+ static void debugAirtimeProbe(uint16_t payloadBytes, uint16_t frames);
+#endif
+
+ // Active ESP-NOW channel (runtime — may differ from the -DNRL_WIFI_CHANNEL
+ // default after the controller pushes a PKT_CHANNEL_CHANGE). Used by the OLED.
+ static uint8_t channel();
+
+ // Team identity for OLED / status rendering (set by begin(), above).
+ static int teamNumber();
+ static const char* teamName();
+
+ // Authenticated pairing (called from button handler in NRLRunner)
+ static void enterPairAdvertising(); // bot button held 3s → start 3s scan window
+ static void cycleCandidate(); // short press → next controller in list
+ static void acceptCandidate(); // hold 1s → accept selected, send response
+ static void cancelPairing(); // hold 3s → abandon, restore previous state
+
+ // State queries for OLED rendering
+ static bool isUnpaired();
+ static bool isPairAdvertising();
+ static bool isPairSelecting();
+ static uint8_t candidateCount();
+ static uint8_t selectedIdx();
+ static uint16_t selectedCode();
+
+private:
+ enum class PairState : uint8_t {
+ UNPAIRED, // no saved MAC — idle, waiting for explicit button pairing action
+ SCANNING,
+ RECONNECTING,
+ PAIRED,
+ PAIR_ADVERTISING, // 3s collection window: gathering controllers' pair requests
+ PAIR_SELECTING // operator browses candidate list and confirms the correct code
+ };
+
+ struct PairCandidate { uint8_t mac[6]; uint16_t code; };
+
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
+ static void onReceive(const esp_now_recv_info_t* info, const uint8_t* data, int len);
+#else
+ static void onReceive(const uint8_t* mac, const uint8_t* data, int len);
+#endif
+
+ // Team identity, handed in via begin() from the student-compiled RobotMain.ino
+ // (see begin() above). Defaults mirror the NRLComms.h fallback macros so an
+ // un-stamped/legacy build still renders something sane.
+ static int _teamNumber;
+ static char _teamName[24];
+ static uint8_t _baseChannel;
+
+ // Runtime ESP-NOW channel + a deferred change request. onReceive() (ESP-NOW
+ // callback context) only sets _chanReqPending; tickPairing() applies it on the
+ // main loop so the NVS write + esp_wifi_set_channel never run inside the ISR.
+ static uint8_t _channel;
+ static volatile bool _chanReqPending;
+ static volatile uint8_t _chanReqValue;
+ static void _applyChannel(uint8_t ch, bool persist); // set radio + peers (+ NVS)
+ static void _persistChannelIfChanged(); // save _channel to NVS if different
+
+ static bool _peerAdded;
+ static PairState _pairState;
+ static volatile uint32_t _lastCtrlMs;
+ static uint32_t _reconnStart;
+ static uint8_t controllerMAC[6];
+ static const uint8_t _broadcastMAC[6];
+
+ // Candidate list for PAIR_ADVERTISING / PAIR_SELECTING
+ static PairCandidate _candidates[4];
+ static uint8_t _candidateCount;
+ static uint8_t _selectedIdx;
+ static uint32_t _pairAdvStart; // start of PAIR_ADVERTISING window
+ static uint32_t _pairSelStart; // start of PAIR_SELECTING timeout
+
+ static void _addBroadcastPeer();
+ static void _addUnicastPeer(const uint8_t* mac);
+ static void _removePeer(const uint8_t* mac);
+ static void _becomePaired(const uint8_t* mac);
+ static void _becomeScanning();
+ static void _sendAdvertiseTo(const uint8_t* dest);
+ static void _saveMAC();
+ static void _clearSavedMAC();
+ static bool _isValidMAC(const uint8_t* mac);
+};
diff --git a/RobotFirmware/lib/HexaNRL/src/NRLGamepad.h b/RobotFirmware/lib/HexaNRL/src/NRLGamepad.h
new file mode 100644
index 0000000..231af4e
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/NRLGamepad.h
@@ -0,0 +1,81 @@
+#pragma once
+#include <stdint.h>
+#include <freertos/FreeRTOS.h>
+#include <freertos/task.h>
+
+// ============================================================
+// NRLGamepad — gamepad state accessible inside user loop()
+// ============================================================
+// Values are updated by NRLComms::onReceive() when GAMEPAD
+// packets arrive from the Controller at ~100Hz while an OpMode runs
+// (T_GAMEPAD = 10ms); ~20Hz keepalives otherwise.
+//
+// Usage in OpMode:
+// float spd = NRLGamepad::leftY * 255;
+// if (NRLGamepad::buttons & BTN_X) { ... }
+
+// Button bitmask constants (must match Controller firmware)
+// Face buttons, D-pad, bumpers, and toggles.
+//
+// BIT 2 IS INTENTIONALLY UNUSED — there is no B button on this board. The V1
+// production PCB has 7 tactile buttons; the Controller's BTN_BIT[] skips bit 2,
+// so nothing can ever set it, and there is deliberately no constant for it.
+// Do NOT renumber the constants below to close the gap — bit positions are the
+// wire contract with the Controller firmware, and moving Y off bit 3 would
+// silently mis-map every button.
+//
+// BTN_Y is FREE while an OpMode runs. It used to be the BACK/STOP button, but
+// exit moved to the LT toggle: on SCR_CODE_RUNNING the Controller skips its
+// whole nav block (ControllerMain.ino "if (curScreen != SCR_CODE_RUNNING)"), so
+// Y never reaches handleBack() and is forwarded in the gamepad packet like any
+// other button. Y is still BACK in the menus, and it dismisses the TeleOp
+// exit-confirm popup — so while that popup is up, a Y press does both.
+#define BTN_X (1 << 0)
+#define BTN_A (1 << 1)
+// (1 << 2) — no B button on this board; bit left unused
+#define BTN_Y (1 << 3) // free during a run; BACK in menus / dismisses exit popup
+#define BTN_DPAD_RIGHT (1 << 4) // free always
+#define BTN_DPAD_DOWN (1 << 5) // free during run (UI: scroll down when idle)
+#define BTN_DPAD_UP (1 << 6) // free during run (UI: scroll up when idle)
+#define BTN_DPAD_LEFT (1 << 7)
+#define BTN_RB (1 << 8) // right bumper (GP40)
+#define BTN_LB (1 << 9) // left bumper (GP39)
+#define BTN_LT (1 << 10) // left toggle (GP42)
+#define BTN_RT (1 << 11) // right toggle (GP41)
+
+struct NRLGamepad {
+ static volatile float leftX;
+ static volatile float leftY;
+ static volatile float rightX;
+ static volatile float rightY;
+ static volatile uint16_t buttons;
+
+ // Counts real GAMEPAD packets: update() bumps it, clear() and
+ // clearIfNoPacketSince() don't. Lets a reader tell controller data from the
+ // zeros NRLComms writes while input is stale.
+ static volatile uint32_t packetSeq;
+
+ // Spinlock protecting the fields above.
+ // Both update() (WiFi task, core 0) and read() (main task, core 1) must hold it.
+ static portMUX_TYPE mux;
+
+ // Called by NRLComms on every received GAMEPAD packet (WiFi task context).
+ static void update(float lx, float ly, float rx, float ry, uint16_t btns);
+
+ // Zero every field. Not a packet, so packetSeq is left alone.
+ static void clear();
+
+ // Zero every field unless a packet arrived after packetSeq read `seq`. The
+ // stale-input path uses this so it can never overwrite a packet that landed
+ // between its silence check and the write.
+ static void clearIfNoPacketSince(uint32_t seq);
+
+ // Atomically copy all five fields — use this instead of reading fields directly.
+ static void read(float& lx, float& ly, float& rx, float& ry, uint16_t& btns);
+ // Same, plus packetSeq from the same instant.
+ static void read(float& lx, float& ly, float& rx, float& ry, uint16_t& btns, uint32_t& seq);
+
+ static bool pressed(uint16_t btn);
+};
+
+// Definitions live in NRLComms.cpp to avoid multiple-definition errors
diff --git a/RobotFirmware/lib/HexaNRL/src/NRLOpMode.h b/RobotFirmware/lib/HexaNRL/src/NRLOpMode.h
new file mode 100644
index 0000000..404616d
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/NRLOpMode.h
@@ -0,0 +1,173 @@
+#pragma once
+#include "NRLAction.h"
+#include "NRLTelemetry.h"
+#include <freertos/FreeRTOS.h>
+#include <freertos/task.h>
+#include <vector>
+
+// ============================================================
+// ABI guard
+// ============================================================
+// A student opmode is compiled against THIS header; NRLRunner (compiled
+// into libHexaNRL_static.a) calls into it through NRLOpMode's vtable --
+// a fixed slot per virtual, in declaration order. If the header a student
+// kit ships and the .a it ships were built from different versions of this
+// class layout (a virtual added/removed/reordered, a data member changed),
+// the two sides disagree about which slot is which. That is NOT a compile
+// or link error -- virtual calls resolve at runtime -- so the failure is a
+// silently wrong function called, or a jump into garbage. On a robot, that
+// surfaces as a field failure, not a build failure.
+//
+// Bump NRL_ABI_VERSION whenever you change anything that could shift the
+// layout of a class living on both sides of the header/.a boundary --
+// NRLOpMode most of all. REGISTER_OPMODE (OpModeRegistry.h), which every
+// student opmode calls, references a version-named symbol that only the
+// matching .a defines (see NRLOpMode.cpp). A stale .a then fails to LINK,
+// with an error naming the missing symbol, instead of failing silently on
+// the field.
+#define NRL_ABI_VERSION 1
+#define _NRL_ABI_CONCAT2(a, b) a##b
+#define _NRL_ABI_CONCAT(a, b) _NRL_ABI_CONCAT2(a, b)
+#define NRL_ABI_MARKER _NRL_ABI_CONCAT(nrl_abi_v, NRL_ABI_VERSION)
+
+extern "C" void NRL_ABI_MARKER();
+
+// ============================================================
+// NRLOpMode — Base class for all student programs
+// ============================================================
+//
+// Override the hooks you need:
+// init() — once when INIT is pressed. Set up hardware here.
+// start() — once when the match starts, right before the first loop().
+// Queue an AUTO routine here and it runs exactly once.
+// loop() — 100Hz. TELEOP: for 2:30; AUTO: for 60 seconds.
+// stop() — once on STOP. Motors do NOT stop automatically —
+// always call drive.stop() (or motor.stop()) here.
+//
+// Actions:
+// runAction(a) — queue an action. It advances one step per tick and
+// removes itself when finished. Actions ADD to the
+// queue: starting one does not cancel another, so
+// several can run side by side.
+// cancelActions() — drop every queued action right now
+// isActionRunning() — true while any queued action is still going
+//
+// Action helpers available everywhere:
+// instant([]{ ... }) — one-shot hardware command
+// sequential({ a, b, c }) — chain actions in order
+// parallel({ a, b, c }) — run actions at the same time
+// sleep_ms(500) — wait 500 ms
+// wait_until([]{ return ...; }) — wait for a sensor condition
+//
+// AUTO — queue it once in start(), then leave it alone:
+//
+// void start() override {
+// runAction(sequential({
+// instant([]{ drive.drive(0.6f, 0.0f); }), // drive forward
+// sleep_ms(2000), // for 2 seconds
+// instant([]{ drive.stop(); }), // then stop
+// }));
+// }
+//
+// TELEOP — fire from a button edge, never every tick:
+//
+// void loop() override {
+// drive.drive(gamepad1.leftY(), gamepad1.rightX()); // loop() owns the drive
+// if (gamepad1.justPressed(BTN_X)) runAction(armSequence()); // action owns the arm
+// }
+//
+// Control each piece of hardware in ONE place — either loop() or an action,
+// not both. Each tick runs your actions FIRST, then loop(), so anything
+// loop() sets every tick overwrites what an action just set and the action
+// looks like it did nothing. Above, loop() owns the drive and the action owns
+// the arm, so they never collide.
+//
+// If you truly need both to control the same part, skip the loop() control
+// while a sequence is playing:
+//
+// if (!isActionRunning()) arm.setPosition(90.0f + gamepad1.rightY() * 90.0f);
+//
+// Writing sequences inline like the examples above is the RIGHT way to start
+// and stays fine for most robots. When an OpMode grows — loop() too long to
+// scan, or the same sequence used twice — you can move sequences into named
+// functions (examples/ExampleSeq.h) and mechanisms into classes with named
+// states (examples/ExampleSubsystem.h). Both are optional; neither changes
+// what the robot does.
+//
+// RULES:
+// - No delay() anywhere — use sleep_ms() or runBlocking() instead
+// - No new/malloc inside loop() — allocate members in init() or as class fields
+// - Don't call runAction() every tick. Queue it in start(), or on a button
+// edge with justPressed(). The queue holds 8 actions; past that the extra
+// ones are dropped and a warning is printed to serial.
+// - cancelActions() empties the queue but does NOT stop hardware — follow it
+// with drive.stop() / setPosition() for anything that was moving.
+
+class NRLOpMode {
+public:
+ virtual ~NRLOpMode() = default;
+
+ NRLTelemetry telemetry; // call telemetry.addData("key", value) inside loop()
+
+ virtual void init() {} // optional: setup before START
+ virtual void start() {} // optional: runs once when the match starts, before the first loop()
+ virtual void loop() {} // called at 100Hz — TELEOP: for 2:30 then exits; AUTO: for 60 seconds then exits
+ virtual void stop() {} // optional: cleanup on STOP — motors do NOT stop automatically; always call drive.stop() here
+
+ // --------------------------------------------------------
+ // runBlocking(action)
+ // Executes action to completion, blocking the caller.
+ // Checks the stop signal and 60-second AUTO deadline every tick.
+ // Use inside run() for AUTO sequences.
+ // --------------------------------------------------------
+ void runBlocking(ActionPtr action);
+
+ // --------------------------------------------------------
+ // runAction(action)
+ // Adds a non-blocking action to the queue. It advances one step per
+ // tick and drops out of the queue on its own when it finishes.
+ // Queuing an action does NOT cancel the ones already running — up to
+ // 8 can be in flight together.
+ // Queue it in start() (AUTO) or on a button edge (TELEOP); calling it
+ // every tick just refills the queue with copies that never finish.
+ // --------------------------------------------------------
+ void runAction(ActionPtr action);
+
+ // --------------------------------------------------------
+ // cancelActions()
+ // Drops every queued action immediately. Hardware is left exactly as
+ // the actions last set it — follow with drive.stop() if you want the
+ // robot to hold still.
+ // --------------------------------------------------------
+ void cancelActions();
+
+ // --------------------------------------------------------
+ // isActionRunning()
+ // True while any queued action is still in progress.
+ // --------------------------------------------------------
+ bool isActionRunning() const;
+
+ // Called by NRLRunner each tick — not for student use
+ void _advanceAction();
+
+ // Called by NRLRunner before init() — not for student use
+ void _bindStopFlag(volatile bool* flag);
+
+ // Called by NRLRunner on CMD_START for AUTO — not for student use
+ void _setAutoDeadline(uint32_t deadlineMs);
+
+private:
+ // Queue depth. Deep enough for any realistic set of concurrent sequences,
+ // shallow enough that a runaway runAction()-every-tick loop is caught and
+ // reported instead of eating the heap.
+ static constexpr uint8_t MAX_ACTIONS = 8;
+
+ void _warnQueueFull();
+
+ std::vector<ActionPtr> _actions; // in flight
+ std::vector<ActionPtr> _pending; // queued since the last tick
+ bool _advancing = false; // inside the _advanceAction() run pass
+ bool _cancelRequested = false; // cancelActions() called from an action
+ volatile bool* _stopFlag = nullptr;
+ uint32_t _autoDeadlineMs = 0;
+};
diff --git a/RobotFirmware/lib/HexaNRL/src/NRLPublic.h b/RobotFirmware/lib/HexaNRL/src/NRLPublic.h
new file mode 100644
index 0000000..d1a9e46
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/NRLPublic.h
@@ -0,0 +1,18 @@
+#pragma once
+
+// ============================================================
+// NRLPublic — the robot entry-point API used by RobotMain.ino
+// ============================================================
+// RobotMain.ino calls these two functions and nothing else from the
+// framework's execution engine. The engine itself (NRLRunner, the match
+// state machine, the ESP-NOW command handling) is internal and compiled
+// into the prebuilt .a — its headers are NOT shipped, so the run loop and
+// state machine can't be read or edited. Students never call these; their
+// code lives in opmodes/.
+
+// One-time setup: ESP-NOW init + advertise (call in setup()). The team identity
+// is passed in from RobotMain.ino because that file is compiled inside the
+// student's project, so it sees the per-project -DNRL_TEAM_NUMBER /
+// -DNRL_TEAM_NAME / -DNRL_WIFI_CHANNEL stamp — the prebuilt engine .a cannot.
+void nrl_begin(int teamNumber, const char* teamName, int wifiChannel);
+void nrl_tick(); // run the active OpMode one 100Hz step (call in loop())
diff --git a/RobotFirmware/lib/HexaNRL/src/NRLTelemetry.h b/RobotFirmware/lib/HexaNRL/src/NRLTelemetry.h
new file mode 100644
index 0000000..0520ff5
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/NRLTelemetry.h
@@ -0,0 +1,72 @@
+#pragma once
+#include <Arduino.h>
+#include "NRLComms.h" // NRL_TELEM_MAX_ENTRIES, NRL_TELEM_BATCH_MAX
+
+// ============================================================
+// NRLTelemetry — student-facing telemetry buffer
+//
+// Usage inside loop():
+// telemetry.addData("speed", drive.getSpeed()); // float
+// telemetry.addData("status", "locked"); // string
+// // telemetry.update(); ← optional; auto-fires at end of each tick
+//
+// Up to NRL_TELEM_MAX_ENTRIES distinct keys are tracked by name. Sending the
+// same key twice updates the existing entry rather than adding a new line.
+//
+// Real dedup + paced batched sends: addData() only marks a key "pending"
+// when its formatted value actually changes. Each flush packs up to
+// NRL_TELEM_BATCH_MAX pending entries into ONE ESP-NOW packet (round-robin
+// across the buffer) instead of one packet per key — this both keeps each
+// tick's esp_now_send() call count low (avoids overrunning ESP-NOW's
+// pending-TX queue, which used to silently drop whichever keys landed last
+// in a big one-packet-per-key burst) and scales the buffer well past 8
+// entries without multiplying packet count 1:1 with key count.
+// ============================================================
+
+class NRLTelemetry {
+public:
+ void addData(const char* key, float value);
+ void addData(const char* key, const char* value);
+ void update(); // flush up to BATCHES_PER_TICK batches of pending entries now
+
+ // Called by NRLRunner — not for student use
+ void _autoFlush(); // paced flush, called once per loop tick
+ void _clear(); // resets all entries on OpMode stop
+private:
+ struct Entry {
+ char key[12] = {};
+ char val[16] = {};
+ bool used = false;
+ bool pending = false; // val changed since last successful send
+ };
+ // MUST be default-initialised: an OpMode that declares its own constructor
+ // (e.g. OLEDLiveDemo) is default-initialised by `new T()`, which would leave
+ // this buffer indeterminate — stale `used`/`pending` flags then get sent as
+ // garbled telemetry. The `= {}` (plus the per-field defaults above) makes the
+ // buffer clean regardless of how the enclosing OpMode is constructed.
+ Entry _buf[NRL_TELEM_MAX_ENTRIES] = {};
+ uint16_t _cursor = 0;
+
+ // Batch packets sent per flush call — keeps esp_now_send() calls/tick low
+ // regardless of total buffered key count.
+ //
+ // Was 2. _autoFlush() runs every 10ms tick, so 2 allowed up to 200 telemetry
+ // packets/s, and a 226-byte batch costs 2879us of air at the measured 1 Mbps
+ // (dev-docs/bench/AIRTIME_RESULTS.md) — 57.6% of the channel for ONE pair at
+ // worst case, by far the largest single consumer. 1 halves that ceiling.
+ //
+ // Safe because _cursor persists across calls and round-robins the whole
+ // buffer: halving the batches halves the refresh RATE but never starves a
+ // key, which is the failure that would look like the old telemetry-freeze
+ // bug (that one was an uninitialised _buf, not batching — see the comment
+ // above the Entry array).
+ //
+ // Only entries whose value actually CHANGED are pending, so a well-behaved
+ // OpMode never approaches the ceiling; this bounds the worst case rather
+ // than slowing the common one.
+ static constexpr uint8_t BATCHES_PER_TICK = 1;
+
+ Entry* _find(const char* key);
+ Entry* _findOrAlloc(const char* key);
+ void _sendPending(); // sends up to BATCHES_PER_TICK batches of pending entries
+};
diff --git a/RobotFirmware/lib/HexaNRL/src/NRLVersion.h b/RobotFirmware/lib/HexaNRL/src/NRLVersion.h
new file mode 100644
index 0000000..6df3f98
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/NRLVersion.h
@@ -0,0 +1,13 @@
+#pragma once
+// ============================================================
+// NRLVersion.h — the NRL SDK version
+// ============================================================
+//
+// The one place the SDK version is set. The robot prints it at boot
+// ("[NRL] SDK vX.Y.Z"), and the kitbuilder reads it from here for the
+// build manifest and the release tag, so bump it here and nowhere else.
+//
+// The controller has its own version: ControllerFirmware/src/ControllerVersion.h.
+// Which robot and controller versions ship together is in docs/COMPATIBILITY.md.
+
+#define NRL_SDK_VERSION "1.4.1"
diff --git a/RobotFirmware/lib/HexaNRL/src/OpModeRegistry.h b/RobotFirmware/lib/HexaNRL/src/OpModeRegistry.h
new file mode 100644
index 0000000..a904742
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/OpModeRegistry.h
@@ -0,0 +1,83 @@
+#pragma once
+#include <vector>
+#include "NRLOpMode.h"
+
+// ============================================================
+// OpModeType — used by REGISTER_OPMODE and the ADVERTISE packet
+// ============================================================
+enum class OpModeType { TELEOP, AUTO };
+
+
+// ============================================================
+// OpModeEntry — one registered OpMode
+// ============================================================
+// factory: creates a fresh instance each time the OpMode is started.
+// Fresh instance = clean member variable state every run.
+struct OpModeEntry {
+ const char* name;
+ OpModeType type;
+ bool isExample; // true = built-in example, false = student code
+ int order; // lower = shown first; default 1000 (registration order)
+ NRLOpMode* (*factory)();
+};
+
+
+// ============================================================
+// OpModeRegistry — global list of all registered OpModes
+// ============================================================
+// Uses a static local vector (Meyer's singleton) to avoid the
+// static initialisation order fiasco across translation units.
+class OpModeRegistry {
+public:
+ static std::vector<OpModeEntry>& all() {
+ static std::vector<OpModeEntry> _list;
+ return _list;
+ }
+
+ static void add(const char* name, OpModeType type, bool isExample,
+ NRLOpMode* (*factory)(), int order = 1000) {
+ all().push_back({ name, type, isExample, order, factory });
+ }
+};
+
+
+// ============================================================
+// OpModeRegistrar<T> — registers one OpMode via its constructor
+// ============================================================
+// C++ guarantees static objects are constructed before setup().
+// So every REGISTER_OPMODE call runs at startup, before anything else.
+template<typename T>
+class OpModeRegistrar {
+public:
+ OpModeRegistrar(const char* name, OpModeType type, bool isExample = false,
+ int order = 1000) {
+ // ABI guard: references a version-named symbol only a matching .a
+ // defines (see NRL_ABI_VERSION in NRLOpMode.h). Runs at static-init
+ // time, same as OpModeRegistry::add() below, so it can never be
+ // linker-GC'd away.
+ NRL_ABI_MARKER();
+ OpModeRegistry::add(name, type, isExample,
+ []() -> NRLOpMode* { return new T(); }, order);
+ }
+};
+
+
+// ============================================================
+// REGISTER_OPMODE — used internally by _impl/ wrappers
+// REGISTER_OPMODE_EX — used by built-in example files
+// ============================================================
+//
+// _reg_##ClassName makes the variable name unique per class
+// so multiple .cpp files don't clash with each other.
+#define REGISTER_OPMODE(ClassName, DisplayName, Type) \
+ static OpModeRegistrar<ClassName> _reg_##ClassName(DisplayName, OpModeType::Type, false)
+
+#define REGISTER_OPMODE_EX(ClassName, DisplayName, Type) \
+ static OpModeRegistrar<ClassName> _reg_##ClassName(DisplayName, OpModeType::Type, true)
+
+// REGISTER_OPMODE_EX_AT — like REGISTER_OPMODE_EX but pins the menu slot.
+// Order is a small integer: lower numbers appear first in the EXAMPLES menu.
+// Only the four curriculum examples use this; everything else stays at the
+// default order (1000) and is filtered out of the menu unless re-enabled.
+#define REGISTER_OPMODE_EX_AT(ClassName, DisplayName, Type, Order) \
+ static OpModeRegistrar<ClassName> _reg_##ClassName(DisplayName, OpModeType::Type, true, Order)
diff --git a/RobotFirmware/lib/HexaNRL/src/RobotConfig.h b/RobotFirmware/lib/HexaNRL/src/RobotConfig.h
new file mode 100644
index 0000000..9917dea
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/RobotConfig.h
@@ -0,0 +1,96 @@
+#pragma once
+
+// ============================================================
+// RobotConfig.h — framework-level hardware (NRL internals)
+// ============================================================
+// This file only declares hardware that the NRL framework
+// itself requires (pairing OLED, button, gamepad).
+//
+// Your robot hardware (motors, servos, IMU …) goes at the
+// top of your own opmode file — see "Writing Your Code" in README.md.
+
+#include <Wire.h>
+#include <Adafruit_NeoPixel.h>
+#include "HexaOLED.h"
+#include "HexaIMU.h"
+#include "Gamepad.h"
+#include "BoardPins.h"
+#include "HexaLED.h"
+#include "HexaPower.h"
+
+// ── Board-aware hardware presets ─────────────────────────────────────────────
+// Construct the on-board OLED / IMU without hard-coding which I2C bus, address,
+// or pins they use. Prefer these over a raw HexaOLEDConfig{}/HexaIMUConfig{} so
+// you can't accidentally point a device at the wrong bus (the #1 way to get a
+// blank OLED or an "IMU not found"):
+//
+// HexaOLED oled{ hexaOledConfig() }; // OLED on Wire1 / OLED_SDA,OLED_SCL
+// HexaIMU imu { hexaImuConfig() }; // IMU on Wire / I2C_SDA, I2C_SCL
+//
+// (camelCase functions — the PascalCase HexaOLEDConfig / HexaIMUConfig names are
+// the driver config structs these return.)
+inline HexaOLEDConfig hexaOledConfig() {
+ return HexaOLEDConfig{ .i2cAddr = 0x3C, .wire = &Wire1,
+ .sdaPin = OLED_SDA, .sclPin = OLED_SCL };
+}
+inline HexaIMUConfig hexaImuConfig() {
+ return HexaIMUConfig{ .i2cAddr = 0x6B, .wire = &Wire,
+ .sdaPin = I2C_SDA, .sclPin = I2C_SCL };
+}
+
+extern HexaOLED botOled; // SSD1306 128×64 — used by pairing UI (do not rename)
+extern Gamepad gamepad1; // controller input — updated 50× per second
+extern Adafruit_NeoPixel nrlLedStrip; // shared 2-pixel strip on LED_STATUS_PIN (NRL internal)
+extern HexaLED botLed; // pixel 0 — framework status (do not use in student code)
+extern HexaLED userLed; // pixel 1 — student-controlled RGB LED
+extern HexaPower power; // MCP3008 ADC — battery voltage + motor/servo current
+
+// Called from RobotMain.ino setup() — initialises framework hardware only
+void robotHardwareBegin();
+
+// Boot diagnostics, captured in robotHardwareBegin(). nrlBootCount() counts
+// resets since the last true power-up (>1 means something restarted the MCU);
+// nrlLastResetReason() is an esp_reset_reason_t. See RobotConfig.cpp.
+uint32_t nrlBootCount();
+uint32_t nrlLastResetReason();
+
+// True when the SECOND-STAGE BOOTLOADER hung and was watchdog-reset before this
+// boot finally succeeded. Emits "QC:BOOT_RETRY" so the flash station can fail
+// the board on it.
+//
+// Why this exists. The bootloader configures the CPU clock before it initialises
+// the console, and part of that is waiting for the BBPLL to report calibration
+// complete. That wait has no timeout. On a board whose crystal or analog supply
+// is marginal, calibration sometimes fails to converge: the bootloader hangs,
+// the watchdog resets the chip, and the ROM retries. The application never runs
+// on those attempts, so it cannot log them - and the board looks perfectly
+// healthy the moment it does come up. A controller failed exactly this way after
+// passing its factory test, and by then the failure was permanent.
+//
+// Two hardware facts outlive the failed attempts and let us reconstruct them:
+// the reset reason is latched in hardware, and RTC_NOINIT RAM holds its magic
+// only while power is maintained. So "the application has never run since power
+// was applied, yet the previous reset was a watchdog" can only mean something
+// hung before the application existed - i.e. the bootloader. That is distinct
+// from an app-level watchdog (magic valid) and from a clean start (POWERON).
+//
+// LIMIT, stated because it bounds how hard to lean on this: a brownout deep
+// enough to drop the RTC domain below its retention voltage also scrambles the
+// magic, so a watchdog reset following such a brownout would read as a retry.
+// Unlikely but not impossible - treat it as a strong reason to investigate a
+// board, not as proof on its own. It is still the only early warning available
+// for a fault that otherwise gives none until the board stops booting entirely.
+bool nrlBootloaderRetried();
+
+// Human-readable form of nrlLastResetReason(), used by the end-of-run summary so
+// a mid-run reset can be correlated with the run that was in progress.
+const char* nrlLastResetReasonName();
+
+// Same reason as a bare token ("POWERON", "BROWNOUT", "PANIC", "TASK_WDT", ...)
+// short enough for one OLED row. The robot's idle status screen shows it with
+// the boot count, so a bot that rebooted mid-match says why without a laptop.
+const char* nrlLastResetReasonShort();
+
+// Prints the boot reason / boot count. Must be called AFTER Serial.begin() and
+// the USB CDC enumeration delay - see RobotConfig.cpp.
+void nrlPrintBootDiagnostics();
diff --git a/RobotFirmware/lib/HexaNRL/src/TankDrive.h b/RobotFirmware/lib/HexaNRL/src/TankDrive.h
new file mode 100644
index 0000000..987139a
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/TankDrive.h
@@ -0,0 +1,87 @@
+#pragma once
+#include "HexaDCMotor.h"
+#include <algorithm>
+
+// ============================================================
+// TankDrive — differential drive helper
+// ============================================================
+// Wraps left/right motors with differential kinematics.
+//
+// Kinematics:
+// Left motor = (forward + turn) * scale
+// Right motor = (forward - turn) * scale
+//
+// Two-stick usage (left Y = forward, right X = turn):
+// drive.drive(gamepad1.leftY(), gamepad1.rightX());
+//
+// Single-stick usage (left stick only):
+// drive.drive(gamepad1.leftY(), gamepad1.leftX());
+//
+// drive() sets a COMMAND that the robot holds until you change it, so it
+// works whether you call it every tick (TELEOP) or once from an action:
+// instant([]{ drive.drive(0.6f, 0.0f); }), // still driving next tick
+// sleep_ms(2000),
+// instant([]{ drive.stop(); }),
+
+class TankDrive {
+public:
+ TankDrive(HexaDCMotor& left, HexaDCMotor& right)
+ : _left(left), _right(right) {}
+
+ ~TankDrive();
+
+ // Set the drive command.
+ // forward: -1.0 (back) to +1.0 (fwd)
+ // turn: -1.0 (left) to +1.0 (right)
+ // The command is held until changed. Motor output ramps toward it at
+ // _maxDelta per tick (see setRampRate) to limit reversal current spikes.
+ void drive(float forward, float turn);
+
+ // Stop now — zeroes the command AND the output, no ramp.
+ void stop();
+
+ // Scale: 0.0–1.0 (use for slow/fast mode toggle)
+ void setScale(float scale);
+ float getScale() const;
+
+ // Max motor output change per tick. At the 100Hz robot loop, 0.1 spreads a
+ // full reversal (-1→+1) over ~200ms — softening the dI/dt current spike
+ // that couples into the servo rail. Raise toward 0.2 for snappier driving,
+ // 1.0+ disables ramping. Lower = smoother/quieter but less responsive.
+ void setRampRate(float maxDeltaPerTick);
+
+ // Ramp every registered TankDrive one step toward its command and write
+ // the motors. Called by NRLRunner after loop(); not for student use.
+ static void tickAll();
+
+ // Zero every registered drive - command AND output. Called by NRLRunner when
+ // controller input goes stale during a TELEOP run. Not for student use.
+ static void stopAll();
+
+ // Clear the drive registry. Called by NRLRunner after the OpMode is
+ // deleted so stale pointers don't linger between runs. A file-static
+ // TankDrive re-registers on its next drive() call.
+ static void clearRegistry();
+
+private:
+ HexaDCMotor& _left;
+ HexaDCMotor& _right;
+ float _scale = 1.0f;
+ float _maxDelta = 0.1f; // ramp limit per tick (~100ms 0→full, ~200ms full reversal at 100Hz)
+ float _curL = 0.0f; // output actually written to the motors
+ float _curR = 0.0f;
+ float _targetL = 0.0f; // commanded output, held until drive()/stop()
+ float _targetR = 0.0f;
+
+ void _register();
+ void _tick();
+
+ static constexpr uint8_t MAX_DRIVES = 4;
+ static TankDrive* s_registry[MAX_DRIVES];
+ static uint8_t s_count;
+
+ static float _stepToward(float cur, float target, float maxD);
+};
+
+// Declare your own instance at file-scope in your opmode:
+// TankDrive drive(leftMotor, rightMotor);
diff --git a/RobotFirmware/lib/HexaNRL/src/examples/ExampleSeq.h b/RobotFirmware/lib/HexaNRL/src/examples/ExampleSeq.h
new file mode 100644
index 0000000..f112497
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/examples/ExampleSeq.h
@@ -0,0 +1,69 @@
+#pragma once
+#include "NRL.h"
+#include "ExampleSubsystem.h"
+
+// ============================================================
+// ExampleSeq.h — ADVANCED: the named-sequence pattern
+// ============================================================
+// You do NOT need this to write a working OpMode, and you should not
+// start here. Write your sequences inline first:
+//
+// if (gamepad1.justPressed(BTN_X)) {
+// runAction(sequential({
+// instant([]{ arm.setPosition(0); }),
+// sleep_ms(400),
+// instant([]{ gripper.setPosition(90); }),
+// }));
+// }
+//
+// That is the right shape for most robots, and it reads top to bottom.
+// GRADUATE TO THIS FILE when one of those becomes true:
+// - loop() has grown long enough that the buttons are hard to find
+// - you use the same sequence from more than one place
+// - two people are editing the same OpMode and colliding
+//
+// Pattern:
+// Collect related sequences in a namespace.
+// Each function takes subsystem references and returns an ActionPtr.
+// Same idea as INITSeq / ShooterSeq / ServoSeq in AG_2026.
+//
+// Then in your OpMode:
+// #include "examples/ExampleSeq.h"
+// static ExampleSubsystem sub;
+//
+// void start() override { // AUTO: queue once
+// runAction(ExampleSeq::initAll(sub));
+// }
+//
+// void loop() override { // TELEOP: on a button edge
+// if (gamepad1.justPressed(BTN_X)) runAction(ExampleSeq::pickUp(sub));
+// }
+
+namespace ExampleSeq {
+
+ // Move all subsystems to their safe starting position
+ inline ActionPtr initAll(ExampleSubsystem& sub) {
+ return parallel({
+ sub.command(ExampleSubsystem::INIT),
+ // add more subsystems here
+ });
+ }
+
+ // Grab sequence: lower arm, wait, close gripper
+ inline ActionPtr pickUp(ExampleSubsystem& sub) {
+ return sequential({
+ sub.command(ExampleSubsystem::GRAB),
+ sleep_ms(400),
+ instant([]{ gripper.setPosition(0); }),
+ });
+ }
+
+ // Release sequence: open gripper, raise arm
+ inline ActionPtr release(ExampleSubsystem& sub) {
+ return sequential({
+ instant([]{ gripper.setPosition(180); }),
+ sleep_ms(200),
+ sub.command(ExampleSubsystem::RELEASE),
+ });
+ }
+}
diff --git a/RobotFirmware/lib/HexaNRL/src/examples/ExampleSubsystem.h b/RobotFirmware/lib/HexaNRL/src/examples/ExampleSubsystem.h
new file mode 100644
index 0000000..b85a3c8
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/examples/ExampleSubsystem.h
@@ -0,0 +1,41 @@
+#pragma once
+#include "NRL.h"
+
+// ============================================================
+// ExampleSubsystem.h — optional subsystem pattern
+// ============================================================
+// You do NOT need to use this. If your code is simple, put
+// everything directly in your own opmode file.
+//
+// Use this pattern when you want to group hardware belonging
+// to one mechanism (arm, intake, shooter, etc.) into its own
+// class with named states — the same way AG_2026 works.
+//
+// Pattern:
+// 1. Define an enum for the states your mechanism can be in
+// 2. Write update() to switch hardware based on the state
+// 3. Expose command() to return an Action for use in sequences
+//
+// Then in your OpMode:
+// #include "examples/ExampleSubsystem.h"
+// ExampleSubsystem mySub;
+// runBlocking(mySub.command(ExampleSubsystem::GRAB));
+
+class ExampleSubsystem {
+public:
+ enum State { INIT, GRAB, RELEASE };
+
+ // Update hardware immediately
+ void update(State s) {
+ switch (s) {
+ case INIT: arm.setPosition(90); break;
+ case GRAB: arm.setPosition(0); break;
+ case RELEASE: arm.setPosition(180); break;
+ }
+ }
+
+ // Return an Action that can be used in sequential() / parallel()
+ ActionPtr command(State s) {
+ return instant([this, s]() { update(s); });
+ }
+};
diff --git a/RobotFirmware/lib/HexaNRL/src/examples/platformio.ini b/RobotFirmware/lib/HexaNRL/src/examples/platformio.ini
new file mode 100644
index 0000000..d1cc8d6
--- /dev/null
+++ b/RobotFirmware/lib/HexaNRL/src/examples/platformio.ini
@@ -0,0 +1,53 @@
+[platformio]
+src_dir = src
+default_envs = robot
+
+[env:robot]
+platform = espressif32@^6.4.0
+board = esp32-s3-devkitc-1
+framework = arduino
+extra_scripts = pre:link_prebuilt.py
+monitor_speed = 115200
+board_build.partitions = partitions.csv
+
+; Compile opmodes/ alongside src/ — students only ever open opmodes/
+build_src_filter = +<**/*> +<../opmodes/**/*>
+
+; FreeRTOS at 1000Hz ticks — gives 1ms resolution for vTaskDelayUntil
+build_unflags = -std=gnu++11 -std=c++11
+
+build_flags =
+ -DNRL_TEAM_NUMBER=205
+ -DNRL_WIFI_CHANNEL=1
+ "-DNRL_TEAM_NAME=\"Pixel Pokers\""
+ -DCONFIG_FREERTOS_HZ=1000
+ -DCORE_DEBUG_LEVEL=3
+ -std=gnu++17
+ -DARDUINO_USB_MODE=1
+ -DARDUINO_USB_CDC_ON_BOOT=1
+
+; NOTE: no licence-related build flag belongs in this file, and none is read
+; from it. This file is copied verbatim into every generated student project and
+; ships in the public kit, so treat everything in it as public.
+;
+; Licence behaviour is fixed at kit-build time by the keys compiled into
+; libHexaNRL_static.a -- it is not configurable from here, and adding a flag
+; would not change it.
+
+lib_deps =
+ Preferences
+ adafruit/Adafruit NeoPixel
+ adafruit/Adafruit LSM6DS
+ adafruit/Adafruit Unified Sensor
+
+; RobotFirmware/lib = runner, comms, gamepad, NRL umbrella, RobotConfig
+; Root lib/Hexa* = hardware drivers (HexaServos, HexaOLED, HexaIMU, HexaHAL,
+; HexaLED, HexaPower)
+lib_extra_dirs =
+ lib
+ ../lib/HexaServos
+ ../lib/HexaOLED
+ ../lib/HexaIMU
+ ../lib/HexaHAL
+ ../lib/HexaLED
+ ../lib/HexaPower
diff --git a/RobotFirmware/link_prebuilt.py b/RobotFirmware/link_prebuilt.py
new file mode 100644
index 0000000..b0ce9cf
--- /dev/null
+++ b/RobotFirmware/link_prebuilt.py
@@ -0,0 +1,57 @@
+Import("env")
+import os
+from pathlib import Path
+
+# Libraries whose linkage depends entirely on global-constructor side effects
+# (e.g. HexaNRL's example opmodes self-register via REGISTER_OPMODE_EX with no
+# other symbol referencing them) -- a plain -l link lets the linker prune those
+# .o's out of the archive since nothing resolves an "undefined symbol" against
+# them. --whole-archive forces every object in, so the constructors still run.
+WHOLE_ARCHIVE_LIBS = {"HexaNRL"}
+
+project_dir = Path(env["PROJECT_DIR"])
+lib_search_roots = [project_dir / "lib", project_dir.parent / "lib"]
+
+archives = []
+for lib_root in lib_search_roots:
+ if not lib_root.is_dir():
+ continue
+ for a_file in lib_root.glob("*/lib/xtensa-esp32s3/lib*_static.a"):
+ archives.append(str(a_file))
+ lib_dir_name = a_file.parents[2].name # .../<LibName>/lib/xtensa-esp32s3/lib*.a
+ if lib_dir_name in WHOLE_ARCHIVE_LIBS:
+ env.Append(LINKFLAGS=["-Wl,--whole-archive", str(a_file), "-Wl,--no-whole-archive"])
+ else:
+ lib_name = a_file.stem[len("lib"):] # "libHexaServos_static" -> "HexaServos_static"
+ env.Append(LIBPATH=[str(a_file.parent)])
+ env.Append(LIBS=[lib_name])
+
+# Make a changed .a actually force a relink.
+#
+# The appends above tell the LINKER where the archives are; they tell SCons
+# nothing about them being INPUTS. So when only a .a changes, the build is judged
+# up to date, the link is skipped, and the upload re-flashes the previous binary
+# while reporting complete success.
+#
+# Not theoretical: replacing an .a and running `-t upload` three times in a row
+# re-flashed the same stale firmware every time, each with "Wrote ... bytes" and
+# "Hash of data verified". The .a was 13 minutes newer than the firmware.elf
+# supposedly built from it. Only `-t clean` broke it.
+#
+# Why this matters for students: a mid-season update replaces these archives. A
+# student updating an EXISTING project -- which they will, since their opmodes
+# live there -- would silently keep running the old firmware: no error, no
+# warning, a successful-looking upload. They would report that the update did not
+# work and it could not be diagnosed remotely.
+#
+# Declaring the dependency is the only fix that cannot be forgotten. "Run Clean
+# after updating" relies on memory in precisely the case where being wrong is
+# invisible.
+if archives:
+ # NOTE the literal "firmware.elf". In a `pre:` script ${PROGNAME} has not been
+ # resolved yet -- it substitutes to "program", so
+ # "$BUILD_DIR/${PROGNAME}.elf" names .pio/build/<env>/program.elf, a node that
+ # is never built. The dependency is accepted in silence and does nothing,
+ # which is indistinguishable from not having written it. PlatformIO links
+ # $BUILD_DIR/firmware.elf; that is the node to hang this on.
+ env.Depends(os.path.join(env.subst("$BUILD_DIR"), "firmware.elf"), archives)
diff --git a/RobotFirmware/opmodes/drivemode.cpp b/RobotFirmware/opmodes/drivemode.cpp
new file mode 100644
index 0000000..54b9dbc
--- /dev/null
+++ b/RobotFirmware/opmodes/drivemode.cpp
@@ -0,0 +1,575 @@
+#include "NRL.h"
+#include "team205_mech.h"
+
+// ============================================================
+// DriveMode — Dual-Stick Tank Drive, Arm, Claw & Payload Gate
+// ============================================================
+// 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 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.
+// ============================================================
+
+// 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
+static constexpr uint8_t PAYLOAD_SIGNAL_PIN = SERVO_3; // GPIO 41
+
+// ---- 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. 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.
+// ------------------------------------------------------------------
+
+// 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 });
+
+// The mechanism wrappers. See team205_mech.h for what these fix.
+static ServoAxis armAxis;
+static ServoAxis clawAxis;
+static ServoAxis payloadAxis;
+
+// 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 fullStraightActive = false;
+static float lockedHeading = 0.0f;
+static bool payloadOpen = false; // payload gate state
+
+// Power / brownout state.
+static PowerGuard powerGuard;
+static BrownoutBeacon brownoutBeacon;
+static GripMemory gripMemory;
+
+// ------------------------------------------------------------
+// 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 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 DriveMode : public NRLOpMode {
+public:
+ void init() override {
+ // 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();
+
+ // 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) {
+ clawCtl.engageNow();
+ objectSecured = true;
+ } else {
+ clawAxis.command(CLAW_OPEN_ANGLE);
+ }
+
+ 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); // 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();
+
+ // 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;
+ }
+
+ // --------------------------------------------------------
+ // 1. GYRO SPIN MACROS (LB = 180°, DPAD_LEFT/RIGHT = ±90°)
+ // --------------------------------------------------------
+ // 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;
+ }
+ }
+
+ // --------------------------------------------------------
+ // 2. DRIVE — tank, 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;
+ }
+
+ // 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);
+ }
+
+ // 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 (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;
+
+ drive.drive(forward * driveScale, turn);
+
+ telemetry.addData("DRIVE", "DUAL TANK");
+ telemetry.addData("Left Stick", leftStick);
+ telemetry.addData("Right Stick", rightStick);
+ }
+
+ // --------------------------------------------------------
+ // 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.
+ // --------------------------------------------------------
+ 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);
+ }
+
+ // --------------------------------------------------------
+ // 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.
+ // --------------------------------------------------------
+ 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);
+ }
+ }
+
+ // --------------------------------------------------------
+ // 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(PAYLOAD_BUTTON)) {
+ payloadOpen = !payloadOpen;
+ payloadAxis.command(payloadOpen ? PAYLOAD_OPEN_ANGLE : PAYLOAD_CLOSED_ANGLE);
+ tone(BUZZER_PIN, payloadOpen ? 2000 : 1400, 60);
+ }
+
+ // --------------------------------------------------------
+ // 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.
+ // --------------------------------------------------------
+ armAxis.apply();
+ clawAxis.apply();
+ payloadAxis.apply();
+
+ // --------------------------------------------------------
+ // 6. STATUS LED MANAGEMENT
+ // --------------------------------------------------------
+ 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
+ }
+
+ // --------------------------------------------------------
+ // 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);
+
+ arm.detach();
+ claw.detach();
+ payload.detach();
+ userLed.setOff();
+ noTone(BUZZER_PIN);
+ }
+};
+
+REGISTER_OPMODE(DriveMode, "Drive Mode", TELEOP);
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/pixelpoker_auto.cpp b/RobotFirmware/opmodes/pixelpoker_auto.cpp
new file mode 100644
index 0000000..8123487
--- /dev/null
+++ b/RobotFirmware/opmodes/pixelpoker_auto.cpp
@@ -0,0 +1,636 @@
+#include "NRL.h"
+#include "team205_mech.h"
+#include <memory>
+#include <cmath>
+
+// ============================================================================
+// TEAM 205 (PIXEL POKER) — NRL 2026 AUTONOMOUS SKILL CHALLENGE
+//
+// This OpMode runs as an AUTO routine: queue the mission once in start(),
+// then leave loop() for telemetry only.
+//
+// ---------------------------------------------------------------------------
+// LINE FOLLOWING — READ THIS FIRST
+// ---------------------------------------------------------------------------
+// The line-following stack (HexaLineArray / LineActions / LineTuning) ships
+// in NRL SDK 1.5.0. This project vendors SDK 1.4.1, where that driver does
+// not exist, so the mission below compiles in two modes:
+//
+// NRL_HAS_LINE_API = 1 -> the real ARC-8 line follower is used, exactly
+// as the mission planner expects.
+// NRL_HAS_LINE_API = 0 -> a BLIND fallback drives the route on the gyro
+// and timed distances instead. The stage labels
+// still work and the arm/claw/payload mechanics
+// are identical, but the ROUTE DISTANCES ARE
+// GUESSES — measure them on the mat and fill in
+// the BLIND_* constants below.
+//
+// The mode is auto-detected: drop the SDK 1.5.0 libraries into
+// RobotFirmware/lib/ and this file picks the line follower up with no edits.
+// To force a mode, add -DNRL_HAS_LINE_API=1 to build_flags in platformio.ini.
+//
+// The controller does NOT need reflashing for any of this — all of it is
+// robot-side.
+// ============================================================================
+
+#if defined(__has_include)
+# if __has_include("HexaLineArray.h")
+# define NRL_HAS_LINE_API 1
+# endif
+#endif
+#ifndef NRL_HAS_LINE_API
+# define NRL_HAS_LINE_API 0
+#endif
+
+#if NRL_HAS_LINE_API
+# include "HexaLineArray.h"
+#endif
+
+// ============================================================================
+// SECTION 1: HARDWARE & TUNING CONFIGURATION (edit only this section)
+// ============================================================================
+
+// --- 1A. DRIVE MOTOR SETTINGS ----------------------------------------------
+// Measure in Controller -> CALIBRATE -> MOTOR TEST.
+constexpr bool LEFT_MOTOR_FLIPPED = true;
+constexpr bool RIGHT_MOTOR_FLIPPED = false;
+
+// Lowest PWM (0-255) where the wheel starts turning. Below this the motor
+// just buzzes, which a closed loop reads as "no response" and answers by
+// winding the command up further.
+constexpr int LEFT_MIN_DRIVE_PWM = 29;
+constexpr int RIGHT_MIN_DRIVE_PWM = 32;
+
+// --- 1B. ARC-8 LINE SENSOR ORIENTATION ------------------------------------
+// Set true ONLY if ch0 is on the robot's RIGHT.
+constexpr bool SENSOR_BAR_REVERSED = false;
+
+// --- 1C. SERVO PORTS & CALIBRATED ANGLES -----------------------------------
+// Measured in Controller -> CALIBRATE -> SERVO TEST.
+//
+// ARM: 45 deg = raised (carry) 115 deg = lowered (floor)
+// CLAW: 125 deg = open 155 deg = closed
+// The arm goes UP by DECREASING its angle; the claw CLOSES by INCREASING it.
+constexpr int ARM_SERVO_PIN = SERVO_1;
+constexpr int GRIPPER_SERVO_PIN = SERVO_2;
+constexpr int PAYLOAD_SERVO_PIN = SERVO_3;
+
+constexpr float ARM_FLOOR_ANGLE = 115.0f;
+constexpr float ARM_CARRY_ANGLE = 45.0f;
+constexpr float GRIP_OPEN_ANGLE = 125.0f;
+constexpr float GRIP_CLOSED_ANGLE = 155.0f;
+
+// The angle the servo is COMMANDED to while gripping. It is PAST the closed
+// angle on purpose: a servo only applies force while it is still trying to
+// REACH its commanded angle. Commanding exactly GRIP_CLOSED_ANGLE means the
+// servo arrives, stops pushing, and holds nothing — the piece is held by
+// friction alone and falls out the moment the arm moves.
+//
+// Command past the closed angle and the piece blocks the jaws short of it, so
+// the servo keeps straining and presses.
+//
+// PRESSURE TUNING: a LARGER value = a tighter squeeze = more force. Raise it
+// for a stronger grip; lower it if the servo buzzes hard, bogs down, or the
+// arm lags behind when it moves.
+//
+// ⚠ This is the biggest current draw on the board. See the brownout note
+// below before raising it.
+constexpr float GRIP_PRESS_ANGLE = 168.0f;
+
+// Payload gate — a third mechanism on its own servo.
+constexpr float PAYLOAD_CLOSED_ANGLE = 0.0f;
+constexpr float PAYLOAD_OPEN_ANGLE = 90.0f;
+
+// Travel speeds, in DEGREES PER SECOND.
+//
+// The SERVO's ramp rate is the single source of truth for motion. Do not
+// also step the target angle by hand each tick — two rate systems fight and
+// the servo never converges.
+//
+// These are also the current limit for each mechanism. The servos share the
+// battery rail with NO BEC, so a faster rate makes the rail dip harder. If
+// the board browns out (see the "Boot #" counter) when two servos move at
+// once, slow these down.
+constexpr float ARM_RAMP_DEG_PER_S = 90.0f;
+constexpr float GRIP_RAMP_DEG_PER_S = 120.0f;
+constexpr float PAYLOAD_RAMP_DEG_PER_S = 180.0f;
+
+// Extra dwell time (ms) after a servo reaches its target angle.
+constexpr uint32_t SERVO_SETTLE_MS = 250;
+
+// --- 1D. MISSION OPTIONS ----------------------------------------------------
+
+// Set true if the robot starts the match with the first element already in
+// the claw. The claw then presses on it from the very first tick.
+constexpr bool PRELOAD_FIRST_ELEMENT = true;
+
+// Set true if your event awards bonus points for parking back in the box.
+constexpr bool RETURN_TO_START_BOX = false;
+
+// Set true to open the payload gate when placing an element at a T-bar.
+constexpr bool PAYLOAD_OPEN_ON_PLACE = false;
+
+// --- 1E. DISTANCE / SPEED TUNING --------------------------------------------
+// Milliseconds to travel one inch at full drive speed. This is the single
+// most important number for the BLIND fallback — recalibrate by driving a
+// known time at driveSpeed and measuring the distance travelled.
+static constexpr float MS_PER_INCH = 18.0f;
+
+// BLIND-ONLY route distances, in INCHES. These are placeholders until they
+// are measured on the competition mat.
+//
+// START -> J1 -> T1 is the first leg. From J1 the robot turns left onto
+// the J1 -> J2 branch, then right onto the stem to T2.
+constexpr float BLIND_START_EXIT_INCHES = 12.0f; // out of the start box
+constexpr float BLIND_J1_INCHES = 24.0f; // start box -> J1
+constexpr float BLIND_J1_T1_INCHES = 18.0f; // J1 -> T1
+constexpr float BLIND_J1_J2_INCHES = 40.0f; // J1 -> J2
+constexpr float BLIND_J2_T2_INCHES = 20.0f; // J2 -> T2
+
+// --- 1F. PID LINE FOLLOWING & TURN TUNING -----------------------------------
+// Only used when NRL_HAS_LINE_API == 1.
+#if NRL_HAS_LINE_API
+static LineTuning buildLineTuning() {
+ LineTuning t; // starts with official NRL SDK defaults
+
+ // Line Tracking PID (P + D; I is always 0 for line following)
+ t.pid.kP = 0.50f; // raise if drifting wide on bends; lower if zig-zagging
+ t.pid.kI = 0.00f;
+ t.pid.kD = 0.04f; // raise if wobbling after turns; lower if twitching
+ t.pid.dAlpha = 0.00f; // try 0.5 if sensor readings twitch
+
+ // Speed profile (0.0 to 1.0)
+ t.followSpeed = 0.35f;
+ t.junctionSpeed = 0.25f;
+ t.speedDrop = 0.70f;
+ t.minSpeedFrac = 0.25f;
+ t.rampRate = 0.25f;
+
+ // Junction & corner detection
+ t.eventThreshold = 500;
+ t.confirmTicks = 2;
+ t.brakeMs = 80;
+ t.brakeSpeed = 0.30f;
+
+ // Turn & pivot geometry (sensor bar is 86mm ahead of the chassis pivot)
+ t.pivotMs = 60;
+ t.pivotSpeed = 0.25f;
+ t.turnSpeed = 0.45f;
+ t.turnSlowSpeed = 0.30f;
+ t.turnBrakeMs = 80;
+ t.turnTimeoutMs = 3000;
+
+ // IMU gyro & grid squaring
+ t.useGyro = true;
+ t.gyroEarlyDeg = 30;
+ t.useGrid = true;
+ t.squareTolDeg = 6;
+ t.squareDoneDeg = 2;
+
+ // Start / finish box
+ t.startSpeed = 0.35f;
+ t.startTimeoutMs = 4000;
+ t.parkMs = 300;
+ t.parkSpeed = 0.25f;
+
+ return t;
+}
+#endif
+
+// ============================================================================
+// SECTION 2: HARDWARE & STATIC STATE (must be outside the class)
+// ============================================================================
+
+static HexaDCMotor leftDriveMotor {{
+ .dirPin = MOTOR_L_DIR,
+ .pwmPin = MOTOR_L_PWM,
+ .flipped = LEFT_MOTOR_FLIPPED,
+ .minDrive = LEFT_MIN_DRIVE_PWM
+}};
+
+static HexaDCMotor rightDriveMotor {{
+ .dirPin = MOTOR_R_DIR,
+ .pwmPin = MOTOR_R_PWM,
+ .flipped = RIGHT_MOTOR_FLIPPED,
+ .minDrive = RIGHT_MIN_DRIVE_PWM
+}};
+
+static TankDrive drive(leftDriveMotor, rightDriveMotor);
+
+// Distance tuning for the BLIND fallback. DriveActions owns straight-line
+// distance on this hardware (there are no wheel encoders).
+static DriveTuning blindTuning() {
+ DriveTuning t;
+ t.msPerInch = MS_PER_INCH;
+ return t;
+}
+
+static DriveActions driveActions(drive, blindTuning());
+
+#if NRL_HAS_LINE_API
+static HexaLineArrayConfig createLineConfig() {
+ HexaLineArrayConfig cfg = hexaLineConfig();
+ cfg.reversed = SENSOR_BAR_REVERSED;
+ return cfg;
+}
+
+static HexaLineArray line{ createLineConfig() };
+static LineActions lineActions(drive, line, buildLineTuning());
+#endif
+
+// Servos. The arm starts raised in carry position; the claw starts closed
+// holding the pre-loaded first element.
+static HexaServo armServo {{ .signalPin = ARM_SERVO_PIN, .startAngle = ARM_CARRY_ANGLE }};
+static HexaServo gripperServo{{ .signalPin = GRIPPER_SERVO_PIN, .startAngle = GRIP_CLOSED_ANGLE }};
+static HexaServo payloadServo{{ .signalPin = PAYLOAD_SERVO_PIN, .startAngle = PAYLOAD_CLOSED_ANGLE }};
+
+// The mechanism wrappers. See team205_mech.h for what these fix: the target
+// lives here, and apply() pushes it to the driver every tick.
+static ServoAxis armAxis;
+static ServoAxis gripperAxis;
+static ServoAxis payloadAxis;
+
+// Route memory & live telemetry
+static int junctionJ1Mark = -1;
+static const char* activeStageLabel = "INIT_READY";
+
+// Grip state — whether the claw is straining past its closed angle.
+static bool gripEngaged = false;
+
+// Power / brownout state.
+static PowerGuard powerGuard;
+static BrownoutBeacon brownoutBeacon;
+static GripMemory gripMemory;
+
+// ============================================================================
+// SECTION 3: SERVO & MECHANISM HELPERS
+// ============================================================================
+
+// Update the Controller telemetry label at the start of each step.
+static ActionPtr logStage(const char* label) {
+ return instant([label] { activeStageLabel = label; });
+}
+
+// Engage the grip: the servo is commanded PAST the closed angle so it
+// strains against the piece and presses.
+//
+// The press is re-asserted every tick by loop() (see applyAll()), so the
+// squeeze never fades out the way a one-shot command does.
+static void engageGrip() {
+ gripperAxis.press(GRIP_PRESS_ANGLE);
+ gripEngaged = true;
+ gripMemory.set(true);
+}
+
+// Release the grip: the servo lets go and returns to holding the jaw angle.
+static void releaseGrip() {
+ gripperAxis.stopPressing();
+ gripEngaged = false;
+ gripMemory.set(false);
+}
+
+// Push every mechanism's target to its driver. Call this EVERY tick.
+//
+// This does two jobs that both matter on the field:
+// 1. It advances the ramp. The servo only travels while setPosition() is
+// being called — the driver's own 250 ms heartbeat never moves it.
+// 2. It refreshes the PWM duty every tick. A servo refreshed only every
+// 250 ms can drop its pulses when the rail sags, which is what "the
+// servo just stopped working" looks like.
+static void applyAll() {
+ armAxis.apply();
+ gripperAxis.apply();
+ payloadAxis.apply();
+}
+
+// Move a mechanism to `targetAngle` and wait `dwellMs` after it arrives.
+//
+// The action only sets the TARGET. loop() does the driving, so the ramp
+// advances continuously and the PWM stays refreshed while the move runs.
+static ActionPtr moveServoSmooth(ServoAxis& axis, float targetAngle, uint32_t dwellMs) {
+ auto arrivedTimestamp = std::make_shared<uint32_t>(0);
+ return sequential({
+ instant([&axis, targetAngle, arrivedTimestamp] {
+ axis.command(targetAngle);
+ *arrivedTimestamp = 0;
+ }),
+ wait_until([&axis, dwellMs, arrivedTimestamp] {
+ if (*arrivedTimestamp == 0) {
+ // travelArrived() compares against the TRAVEL target, so it
+ // still reports "arrived" while the claw is pressing past it.
+ if (axis.travelArrived(0.5f)) {
+ *arrivedTimestamp = millis() | 1; // non-zero arrival stamp
+ }
+ return false;
+ }
+ return (millis() - *arrivedTimestamp) >= dwellMs;
+ })
+ });
+}
+
+// PICK UP an element at a T-bar:
+// open claw -> lower arm -> close claw -> PRESS -> raise arm
+static ActionPtr executePickSequence() {
+ return sequential({
+ logStage("PICK: OPEN CLAW"),
+ moveServoSmooth(gripperAxis, GRIP_OPEN_ANGLE, 200),
+
+ logStage("PICK: ARM DOWN"),
+ moveServoSmooth(armAxis, ARM_FLOOR_ANGLE, SERVO_SETTLE_MS),
+
+ logStage("PICK: GRAB ELEMENT"),
+ moveServoSmooth(gripperAxis, GRIP_CLOSED_ANGLE, SERVO_SETTLE_MS),
+
+ // Strain the servo past the jaws so it actually presses on the
+ // element. Without this the claw holds nothing and the element falls
+ // out the moment the arm moves.
+ logStage("PICK: PRESS"),
+ instant([]{ engageGrip(); }),
+ sleep_ms(150),
+
+ logStage("PICK: ARM UP"),
+ moveServoSmooth(armAxis, ARM_CARRY_ANGLE, 200)
+ });
+}
+
+// PLACE an element at a T-bar:
+// lower arm -> open claw -> (optional payload gate) -> raise arm
+static ActionPtr executePlaceSequence() {
+ return sequential({
+ logStage("PLACE: ARM DOWN"),
+ moveServoSmooth(armAxis, ARM_FLOOR_ANGLE, SERVO_SETTLE_MS),
+
+ logStage("PLACE: RELEASE"),
+ instant([]{ releaseGrip(); }),
+ moveServoSmooth(gripperAxis, GRIP_OPEN_ANGLE, SERVO_SETTLE_MS),
+
+ // Open the payload gate at the T-bar if the mission wants that.
+ instant([]{
+ if (PAYLOAD_OPEN_ON_PLACE) {
+ payloadAxis.command(PAYLOAD_OPEN_ANGLE);
+ }
+ }),
+
+ logStage("PLACE: ARM UP"),
+ moveServoSmooth(armAxis, ARM_CARRY_ANGLE, 200)
+ });
+}
+
+// ============================================================================
+// SECTION 4: THE AUTONOMOUS MISSION
+// ============================================================================
+
+#if NRL_HAS_LINE_API
+
+// ---------------------------------------------------------------------------
+// FULL LINE-FOLLOWING MISSION
+//
+// Every turn (left/right) is written from the ROBOT'S perspective at that
+// moment. If any step hits a fault, the remaining steps are skipped by the
+// SDK's own fault handling.
+//
+// NOTE: this branch uses the SDK 1.5.0 builder API, which is why it only
+// compiles when the 1.5.0 line-following libraries are present.
+// ---------------------------------------------------------------------------
+static ActionPtr buildAutonomousMission() {
+ auto plan = lineActions.auto_()
+ // Phase 1: Exit start box & deliver the pre-loaded element to T1
+ .then(logStage("01. LEAVE START")) .leaveStart()
+ .then(logStage("02. DRIVE TO J1")) .followToJunction()
+ .markHere(&junctionJ1Mark)
+ .then(logStage("03. DRIVE TO T1")) .followToEnd()
+ .then(executePlaceSequence())
+
+ // Phase 2: Navigate from T1 -> J1 -> J2 -> T2
+ .then(logStage("04. U-TURN AT T1")) .uTurn()
+ .then(logStage("05. RETURN TO J1")) .retraceTo(&junctionJ1Mark)
+ .then(logStage("06. TURN LEFT J1")) .left()
+ .then(logStage("07. DRIVE TO J2")) .followToJunction()
+ .then(logStage("08. TURN RIGHT J2")) .right()
+ .then(logStage("09. DRIVE TO T2")) .followToEnd()
+
+ // Phase 3: Pick up the 2nd element at T2
+ .then(executePickSequence())
+
+ // Phase 4: Return via route memory & deliver the 2nd element to T1
+ .then(logStage("10. U-TURN AT T2")) .uTurn()
+ .then(logStage("11. RETRACE TO J1")) .retraceTo(&junctionJ1Mark)
+ .then(logStage("12. TURN RIGHT J1")) .right()
+ .then(logStage("13. DRIVE TO T1")) .followToEnd()
+ .then(executePlaceSequence());
+
+ // Optional Phase 5: Return to the start / finish grey box
+ if (RETURN_TO_START_BOX) {
+ plan.then(logStage("14. U-TURN T1")) .uTurn()
+ .then(logStage("15. RETRACE HOME")).retraceHome()
+ .then(logStage("16. FIND GREY")) .followToGrey()
+ .then(logStage("17. PARK IN BOX")) .park();
+ }
+
+ return plan.then(logStage("18. MISSION COMPLETE")).build();
+}
+
+#else
+
+// ---------------------------------------------------------------------------
+// BLIND FALLBACK MISSION (SDK 1.4.1 — no line sensor driver)
+//
+// The same sequence of STAGES as the real mission, but each leg is driven
+// blind on the gyro and a measured distance instead of by following a line.
+//
+// ⚠ THE DISTANCES ARE PLACEHOLDERS. Measure them on the mat and put the
+// real numbers into the BLIND_* constants in Section 1 before running this
+// in competition. A wrong distance here means the robot drives into things.
+//
+// The arm/claw/payload behaviour is identical to the line-following version.
+//
+// This branch uses sequential() rather than the DriveActions builder,
+// because the 1.4.1 builder has no .then() — it only exposes the drive
+// primitives. Stage labels match the line-following mission exactly, so the
+// telemetry reads the same either way.
+// ---------------------------------------------------------------------------
+static ActionPtr buildAutonomousMission() {
+ return sequential({
+ // Phase 1: Exit start box & deliver the pre-loaded element to T1
+ logStage("01. LEAVE START"),
+ driveActions.waitForHeadingReady(),
+ driveActions.driveForMs((unsigned long)(BLIND_START_EXIT_INCHES * MS_PER_INCH)),
+
+ logStage("02. DRIVE TO J1"),
+ driveActions.driveInches(BLIND_J1_INCHES),
+
+ logStage("03. DRIVE TO T1"),
+ driveActions.driveInches(BLIND_J1_T1_INCHES),
+ executePlaceSequence(),
+
+ // Phase 2: Navigate from T1 back to J1, then along the J1 -> J2 branch
+ logStage("04. U-TURN AT T1"),
+ driveActions.turn(180),
+
+ logStage("05. RETURN TO J1"),
+ driveActions.driveInches(BLIND_J1_T1_INCHES),
+
+ logStage("06. TURN LEFT J1"),
+ driveActions.turn(-90),
+
+ logStage("07. DRIVE TO J2"),
+ driveActions.driveInches(BLIND_J1_J2_INCHES),
+
+ logStage("08. TURN RIGHT J2"),
+ driveActions.turn(90),
+
+ logStage("09. DRIVE TO T2"),
+ driveActions.driveInches(BLIND_J2_T2_INCHES),
+
+ // Phase 3: Pick up the 2nd element at T2
+ executePickSequence(),
+
+ // Phase 4: Return and deliver the 2nd element to T1
+ logStage("10. U-TURN AT T2"),
+ driveActions.turn(180),
+
+ logStage("11. RETRACE TO J1"),
+ driveActions.driveInches(BLIND_J2_T2_INCHES + BLIND_J1_J2_INCHES),
+
+ logStage("12. TURN RIGHT J1"),
+ driveActions.turn(90),
+
+ logStage("13. DRIVE TO T1"),
+ driveActions.driveInches(BLIND_J1_T1_INCHES),
+ executePlaceSequence()
+ });
+}
+
+#endif // NRL_HAS_LINE_API
+
+// ============================================================================
+// SECTION 5: OPMODE LIFECYCLE
+// ============================================================================
+
+class PixelPokerAuto : public NRLOpMode {
+public:
+ // Runs once on INIT. Initialise hardware without blocking.
+ void init() override {
+ leftDriveMotor.begin();
+ rightDriveMotor.begin();
+
+#if NRL_HAS_LINE_API
+ line.begin();
+#endif
+
+ // setRampRate() must be called before the first setPosition() for the
+ // ramp to apply from the very start.
+ armServo.setRampRate(ARM_RAMP_DEG_PER_S);
+ gripperServo.setRampRate(GRIP_RAMP_DEG_PER_S);
+ payloadServo.setRampRate(PAYLOAD_RAMP_DEG_PER_S);
+
+ armServo.begin();
+ gripperServo.begin();
+ payloadServo.begin();
+
+ armAxis.bind(armServo, ARM_CARRY_ANGLE, ARM_CARRY_ANGLE, ARM_FLOOR_ANGLE);
+ gripperAxis.bind(gripperServo, GRIP_CLOSED_ANGLE, GRIP_OPEN_ANGLE, GRIP_CLOSED_ANGLE);
+ payloadAxis.bind(payloadServo, PAYLOAD_CLOSED_ANGLE, PAYLOAD_CLOSED_ANGLE, PAYLOAD_OPEN_ANGLE);
+
+ junctionJ1Mark = -1;
+ activeStageLabel = "READY (PRESS START)";
+
+ // 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) {
+ gripperAxis.command(GRIP_CLOSED_ANGLE);
+ gripperAxis.press(GRIP_PRESS_ANGLE);
+ gripEngaged = true;
+ } else {
+ gripperAxis.command(GRIP_CLOSED_ANGLE);
+ if (PRELOAD_FIRST_ELEMENT) {
+ // The first element is already in the jaws — press on it so
+ // it cannot fall out when the robot starts moving.
+ gripperAxis.press(GRIP_PRESS_ANGLE);
+ gripEngaged = true;
+ gripMemory.set(true);
+ }
+ }
+
+ armAxis.command(ARM_CARRY_ANGLE);
+ payloadAxis.command(PAYLOAD_CLOSED_ANGLE);
+ applyAll();
+
+ // Flash the LED red if this boot was a brownout reset.
+ brownoutBeacon.arm();
+ }
+
+ // Runs once when the AUTO match starts. Queue the mission here — it runs
+ // exactly once, instead of restarting 100 times a second.
+ void start() override {
+#if NRL_HAS_LINE_API
+ lineActions.clearFault();
+ lineActions.resetCounts();
+ lineActions.clearRoute();
+#endif
+
+ activeStageLabel = "STARTING MISSION";
+ runAction(buildAutonomousMission());
+ }
+
+ // Runs at 100 Hz. The mission owns the mechanisms' TARGETS; loop() owns
+ // the actual servo commands.
+ void loop() override {
+ // 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.
+ powerGuard.update();
+
+ // Push every target to its driver. This is what makes the mechanisms
+ // move (the ramp only advances inside setPosition) and what keeps
+ // their PWM alive every tick.
+ applyAll();
+
+ telemetry.addData("STAGE", activeStageLabel);
+ telemetry.addData("Arm", armAxis.actual());
+ telemetry.addData("Grip", gripperAxis.actual());
+ telemetry.addData("Gripping", gripEngaged ? "PRESSING" : "loose");
+ telemetry.addData("Payload", payloadAxis.actual());
+ telemetry.addData("Heading", NRLComms::getHeading());
+ team205ReportPower(telemetry, powerGuard);
+
+#if NRL_HAS_LINE_API
+ const LineJunction& j = lineActions.lastJunction();
+ char junctionShape[4] = {
+ j.left ? 'L' : '-',
+ j.right ? 'R' : '-',
+ j.straight ? 'S' : '-',
+ '\0'
+ };
+
+ telemetry.addData("FAULT", lineActions.faultName());
+ telemetry.addData("JX", (float)lineActions.junctionCount());
+ telemetry.addData("CNR", (float)lineActions.cornerCount());
+ telemetry.addData("TURN", lineActions.lastTurnDegrees());
+ telemetry.addData("LAST", junctionShape);
+ telemetry.addData("ERR", (float)line.error());
+#else
+ telemetry.addData("MODE", "BLIND (no line sensor)");
+#endif
+ }
+
+ // Cancel every queued action and stop the motors on STOP.
+ 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);
+
+ armServo.detach();
+ gripperServo.detach();
+ payloadServo.detach();
+ userLed.setOff();
+ noTone(BUZZER_PIN);
+ }
+};
+
+REGISTER_OPMODE(PixelPokerAuto, "205 PixelPoker Auto", AUTO);
diff --git a/RobotFirmware/opmodes/team205_mech.h b/RobotFirmware/opmodes/team205_mech.h
new file mode 100644
index 0000000..3959fc5
--- /dev/null
+++ b/RobotFirmware/opmodes/team205_mech.h
@@ -0,0 +1,472 @@
+#pragma once
+
+#include "NRL.h"
+#include <Preferences.h>
+#include <cmath>
+#include <cstring>
+
+// ============================================================================
+// 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.
+// ============================================================================
+
+
+// ============================================================================
+// 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;
+ }
+
+ // 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);
+ }
+
+ // 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();
+ }
+
+ // 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() {
+ pressing = false;
+ }
+
+ bool isPressing() const { return pressing; }
+
+ // The angle actually sent to the servo.
+ float commanded() const {
+ return (pressing && pressAngle >= 0.0f) ? pressAngle : target;
+ }
+
+ // 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());
+ }
+
+ // 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(); }
+
+ // True once the driver has been ramped to the commanded angle.
+ bool arrived(float tol = 1.0f) const {
+ return fabsf(actual() - commanded()) <= tol;
+ }
+
+ // 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;
+ }
+
+ // 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;
+ }
+};
+
+
+// ============================================================================
+// 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) {
+ static ServoAxis* owner = nullptr;
+ if (owner != nullptr && owner != &axis && owner->travelling()) {
+ return false; // rail is busy — defer this move
+ }
+ owner = &axis;
+ return true;
+}
+
+// Release the rail. Call when a mechanism is idle.
+inline void motionRelease(ServoAxis& axis) {
+ static ServoAxis* owner = nullptr;
+ if (owner == &axis) owner = nullptr;
+}
+
+
+// ============================================================================
+// 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();
+
+ if (v > 0.0f && v < minVoltage) minVoltage = v;
+ if (a > peakServoA) peakServoA = a;
+
+ 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;
+ }
+
+ if (!protecting) return 1.0f;
+
+ // 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);
+ }
+
+ // True while the pack is sagging and the drive is being backed off.
+ bool isProtecting() const { return protecting; }
+};
+
+
+// ============================================================================
+// Reset-reason helpers. Declared up here because BrownoutBeacon uses them.
+// ============================================================================
+
+// 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(); }
+
+// Short token for the last reset: "BROWNOUT", "POWERON", "TASK_WDT", ...
+inline const char* team205ResetReason() { return nrlLastResetReasonShort(); }
+
+// True if the last reset was a brownout.
+inline bool team205LastResetWasBrownout() {
+ const char* r = team205ResetReason();
+ return (r != nullptr) && (strcmp(r, "BROWNOUT") == 0);
+}
+
+
+// ============================================================================
+// 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;
+
+ // Call once in init().
+ void arm() {
+ if (!team205LastResetWasBrownout()) return;
+ active = true;
+ untilMs = millis() + 2000;
+ }
+
+ // Call every tick in loop(). Returns true while it owns the LED.
+ bool service() {
+ if (!active) return false;
+ if ((int32_t)(millis() - untilMs) >= 0) {
+ active = false;
+ userLed.setOff();
+ return false;
+ }
+ userLed.setSolid(255, 0, 0);
+ return true;
+ }
+};
+
+// 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);
+}
+
+
+// ============================================================================
+// 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 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;
+ }
+
+ // 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;
+ }
+
+ // 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);
diff --git a/RobotFirmware/partitions.csv b/RobotFirmware/partitions.csv
new file mode 100644
index 0000000..9a51e54
--- /dev/null
+++ b/RobotFirmware/partitions.csv
@@ -0,0 +1,8 @@
+# NRL Robot — Custom Partition Table (4MB Flash)
+# Default table gives ~1.4MB app space — not enough for FreeRTOS + NRL libs.
+# app0 is 3MB so there is headroom for future features (OTA, LVGL).
+# Name, Type, SubType, Offset, Size
+nvs, data, nvs, 0x9000, 0x5000
+otadata, data, ota, 0xe000, 0x2000
+app0, app, ota_0, 0x10000, 0x300000
+spiffs, data, spiffs, 0x310000, 0xF0000
diff --git a/RobotFirmware/platformio.ini b/RobotFirmware/platformio.ini
new file mode 100644
index 0000000..d533e14
--- /dev/null
+++ b/RobotFirmware/platformio.ini
@@ -0,0 +1,43 @@
+[platformio]
+src_dir = src
+default_envs = robot
+
+[env:robot]
+platform = espressif32 @ 6.9.0
+board = esp32-s3-devkitc-1
+framework = arduino
+extra_scripts = pre:link_prebuilt.py
+monitor_speed = 115200
+board_build.partitions = partitions.csv
+upload_speed = 115200
+
+; Compile opmodes/ alongside src/ — students only ever open opmodes/
+build_src_filter = +<*> +<**/*> +<../opmodes/**/*>
+
+; FreeRTOS at 1000Hz ticks — gives 1ms resolution for vTaskDelayUntil
+build_unflags = -std=gnu++11 -std=c++11
+
+build_flags =
+ -DNRL_TEAM_NUMBER=205
+ -DNRL_WIFI_CHANNEL=1
+ "-DNRL_TEAM_NAME=\"Pixel Pokers\""
+ -DCONFIG_FREERTOS_HZ=1000
+ -DCORE_DEBUG_LEVEL=3
+ -std=gnu++17
+ -DARDUINO_USB_MODE=1
+ -DARDUINO_USB_CDC_ON_BOOT=1
+
+lib_deps =
+ Preferences
+ adafruit/Adafruit NeoPixel
+ adafruit/Adafruit LSM6DS
+ adafruit/Adafruit Unified Sensor
+
+lib_extra_dirs =
+ lib
+ ../lib/HexaServos
+ ../lib/HexaOLED
+ ../lib/HexaIMU
+ ../lib/HexaHAL
+ ../lib/HexaLED
+ ../lib/HexaPower
diff --git a/RobotFirmware/src/RobotMain.ino b/RobotFirmware/src/RobotMain.ino
new file mode 100644
index 0000000..ebdb70a
--- /dev/null
+++ b/RobotFirmware/src/RobotMain.ino
@@ -0,0 +1,24 @@
+// ╔════════════════════════════════════════════════════════════╗
+// ║ DO NOT EDIT — NRL Robot entry point ║
+// ║ Your code goes in: RobotFirmware/opmodes/ ║
+// ║ Create one with the 'NRL: New OpMode' task. ║
+// ╚════════════════════════════════════════════════════════════╝
+
+#include <Arduino.h>
+#include "NRL.h"
+#include "NRLPublic.h"
+
+void setup() {
+ robotHardwareBegin(); // must be first — releases servo pins from JTAG before any delay
+ Serial.begin(115200);
+ delay(1500); // wait for USB CDC host enumeration
+ Serial.println("[NRL] Boot");
+ // Pass this project's stamped identity into the engine. These macros resolve
+ // HERE (RobotMain.ino is compiled in your project, so it sees the
+ // -DNRL_TEAM_* / -DNRL_WIFI_CHANNEL flags); the prebuilt engine .a cannot.
+ nrl_begin(NRL_TEAM_NUMBER, NRL_TEAM_NAME, NRL_WIFI_CHANNEL);
+}
+
+void loop() {
+ nrl_tick();
+} \ No newline at end of file
diff --git a/Suncity 54 team 1.code-workspace b/Suncity 54 team 1.code-workspace
new file mode 100644
index 0000000..8f07921
--- /dev/null
+++ b/Suncity 54 team 1.code-workspace
@@ -0,0 +1,75 @@
+{
+ "folders": [
+ {
+ "name": "ControllerFirmware",
+ "path": "ControllerFirmware"
+ },
+ {
+ "name": "RobotFirmware",
+ "path": "RobotFirmware"
+ }
+ ],
+ "tasks": {
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "label": "NRL: Flash Controller",
+ "detail": "Flash the prebuilt NRL controller firmware to a connected ESP32-S3 (no compile). Set your team's channel afterwards on the controller's WiFi-channel screen.",
+ "type": "shell",
+ "command": "bash",
+ "args": [
+ "${workspaceFolder:ControllerFirmware}/flash-controller.sh"
+ ],
+ "windows": {
+ "command": "cmd",
+ "args": [
+ "/c",
+ "${workspaceFolder:ControllerFirmware}\\flash-controller.bat"
+ ]
+ },
+ "options": {
+ "cwd": "${workspaceFolder:ControllerFirmware}",
+ "env": {
+ "NRL_NO_PAUSE": "1"
+ }
+ },
+ "presentation": {
+ "reveal": "always",
+ "panel": "dedicated",
+ "focus": true,
+ "clear": true
+ },
+ "problemMatcher": []
+ },
+ {
+ "label": "NRL: New OpMode",
+ "detail": "Create a new robot OpMode (TeleOp or Auto) from a minimal template.",
+ "type": "shell",
+ "command": "bash",
+ "args": [
+ "${workspaceFolder:RobotFirmware}/../tools/new-nrl-opmode.sh"
+ ],
+ "windows": {
+ "command": "cmd",
+ "args": [
+ "/c",
+ "${workspaceFolder:RobotFirmware}\\..\\tools\\new-nrl-opmode.bat"
+ ]
+ },
+ "options": {
+ "cwd": "${workspaceFolder:RobotFirmware}/..",
+ "env": {
+ "NRL_NO_PAUSE": "1"
+ }
+ },
+ "presentation": {
+ "reveal": "always",
+ "panel": "dedicated",
+ "focus": true,
+ "clear": true
+ },
+ "problemMatcher": []
+ }
+ ]
+ }
+}
diff --git a/lib/HexaHAL/build-manifest.json b/lib/HexaHAL/build-manifest.json
new file mode 100644
index 0000000..c7c0a85
--- /dev/null
+++ b/lib/HexaHAL/build-manifest.json
@@ -0,0 +1,72 @@
+{
+ "source_lib": "lib\\HexaHAL",
+ "sdk_version": "1.4.1",
+ "built_from_commit": "036661d7fa9340e198bf3f6d376121ae8c214f59",
+ "built_at": "2026-10-10T14:37:17.742212Z",
+ "harvested_from_project": "RobotFirmware",
+ "harvested_env": "robot",
+ "cxx_path": "C:\\Users\\thein\\.platformio\\packages\\toolchain-xtensa-esp32s3\\bin\\xtensa-esp32s3-elf-g++.exe",
+ "cxx_flags": [
+ "-std=gnu++17",
+ "-fexceptions",
+ "-fno-rtti",
+ "-Os",
+ "-mlongcalls",
+ "-ffunction-sections",
+ "-fdata-sections",
+ "-Wno-error=unused-function",
+ "-Wno-error=unused-variable",
+ "-Wno-error=deprecated-declarations",
+ "-Wno-unused-parameter",
+ "-Wno-sign-compare",
+ "-ggdb",
+ "-freorder-blocks",
+ "-Wwrite-strings",
+ "-fstack-protector",
+ "-fstrict-volatile-bitfields",
+ "-Wno-error=unused-but-set-variable",
+ "-fno-jump-tables",
+ "-fno-tree-switch-conversion",
+ "-MMD",
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "defines": [
+ "PLATFORMIO=60200",
+ "ARDUINO_ESP32S3_DEV",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_RUNNING_CORE=1",
+ "ARDUINO_EVENT_RUNNING_CORE=1",
+ "CONFIG_FREERTOS_HZ=1000",
+ "CORE_DEBUG_LEVEL=3",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_USB_CDC_ON_BOOT=1",
+ "HAVE_CONFIG_H",
+ "MBEDTLS_CONFIG_FILE=\"mbedtls/esp_config.h\"",
+ "UNITY_INCLUDE_CONFIG_H",
+ "WITH_POSIX",
+ "_GNU_SOURCE",
+ "IDF_VER=\"v4.4.7-dirty\"",
+ "ESP_PLATFORM",
+ "_POSIX_READER_WRITER_LOCKS",
+ "ARDUINO_ARCH_ESP32",
+ "ESP32",
+ "F_CPU=240000000L",
+ "ARDUINO=10812",
+ "ARDUINO_VARIANT=\"esp32s3\"",
+ "ARDUINO_BOARD=\"Espressif ESP32-S3-DevKitC-1-N8 (8 MB QD, No PSRAM)\"",
+ "ARDUINO_PARTITION_partitions"
+ ],
+ "hardening": {
+ "extra_cxx_flags": [
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "symbols_stripped": true,
+ "strings_encrypted": true
+ }
+} \ No newline at end of file
diff --git a/lib/HexaHAL/library.json b/lib/HexaHAL/library.json
new file mode 100644
index 0000000..a9340c2
--- /dev/null
+++ b/lib/HexaHAL/library.json
@@ -0,0 +1,15 @@
+{
+ "name": "HexaHAL",
+ "version": "1.0.0",
+ "description": "Hardware abstraction interfaces for HEXA COMMAND HUB",
+ "keywords": ["hal", "abstraction", "interface", "esp32", "hexa"],
+ "authors": [
+ {
+ "name": "Rush",
+ "maintainer": true
+ }
+ ],
+ "license": "MIT",
+ "platforms": "*",
+ "frameworks": "arduino"
+}
diff --git a/lib/HexaHAL/library.properties b/lib/HexaHAL/library.properties
new file mode 100644
index 0000000..d7f65ec
--- /dev/null
+++ b/lib/HexaHAL/library.properties
@@ -0,0 +1,9 @@
+name=HexaHAL
+version=1.0.0
+author=Rush
+maintainer=Rush
+sentence=Hardware abstraction interfaces for HEXA COMMAND HUB
+paragraph=Pure abstract interfaces (IServo, IMotor, ISensor) that define the contract between application code and hardware drivers. Contains zero implementation code.
+category=Device Control
+url=
+architectures=*
diff --git a/lib/HexaIMU/build-manifest.json b/lib/HexaIMU/build-manifest.json
new file mode 100644
index 0000000..a1ca16b
--- /dev/null
+++ b/lib/HexaIMU/build-manifest.json
@@ -0,0 +1,72 @@
+{
+ "source_lib": "lib\\HexaIMU",
+ "sdk_version": "1.4.1",
+ "built_from_commit": "036661d7fa9340e198bf3f6d376121ae8c214f59",
+ "built_at": "2026-10-10T14:37:09.526196Z",
+ "harvested_from_project": "RobotFirmware",
+ "harvested_env": "robot",
+ "cxx_path": "C:\\Users\\thein\\.platformio\\packages\\toolchain-xtensa-esp32s3\\bin\\xtensa-esp32s3-elf-g++.exe",
+ "cxx_flags": [
+ "-std=gnu++17",
+ "-fexceptions",
+ "-fno-rtti",
+ "-Os",
+ "-mlongcalls",
+ "-ffunction-sections",
+ "-fdata-sections",
+ "-Wno-error=unused-function",
+ "-Wno-error=unused-variable",
+ "-Wno-error=deprecated-declarations",
+ "-Wno-unused-parameter",
+ "-Wno-sign-compare",
+ "-ggdb",
+ "-freorder-blocks",
+ "-Wwrite-strings",
+ "-fstack-protector",
+ "-fstrict-volatile-bitfields",
+ "-Wno-error=unused-but-set-variable",
+ "-fno-jump-tables",
+ "-fno-tree-switch-conversion",
+ "-MMD",
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "defines": [
+ "PLATFORMIO=60200",
+ "ARDUINO_ESP32S3_DEV",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_RUNNING_CORE=1",
+ "ARDUINO_EVENT_RUNNING_CORE=1",
+ "CONFIG_FREERTOS_HZ=1000",
+ "CORE_DEBUG_LEVEL=3",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_USB_CDC_ON_BOOT=1",
+ "HAVE_CONFIG_H",
+ "MBEDTLS_CONFIG_FILE=\"mbedtls/esp_config.h\"",
+ "UNITY_INCLUDE_CONFIG_H",
+ "WITH_POSIX",
+ "_GNU_SOURCE",
+ "IDF_VER=\"v4.4.7-dirty\"",
+ "ESP_PLATFORM",
+ "_POSIX_READER_WRITER_LOCKS",
+ "ARDUINO_ARCH_ESP32",
+ "ESP32",
+ "F_CPU=240000000L",
+ "ARDUINO=10812",
+ "ARDUINO_VARIANT=\"esp32s3\"",
+ "ARDUINO_BOARD=\"Espressif ESP32-S3-DevKitC-1-N8 (8 MB QD, No PSRAM)\"",
+ "ARDUINO_PARTITION_partitions"
+ ],
+ "hardening": {
+ "extra_cxx_flags": [
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "symbols_stripped": true,
+ "strings_encrypted": true
+ }
+} \ No newline at end of file
diff --git a/lib/HexaIMU/keywords.txt b/lib/HexaIMU/keywords.txt
new file mode 100644
index 0000000..9fa0d38
--- /dev/null
+++ b/lib/HexaIMU/keywords.txt
@@ -0,0 +1,43 @@
+# ═══════════════════════════════════════════════
+# Syntax Highlighting for HexaIMU Library
+# ═══════════════════════════════════════════════
+# KEYWORD1 = Classes (highlighted as types)
+# KEYWORD2 = Methods (highlighted as functions)
+# LITERAL1 = Constants / enum values
+
+# ── Classes ──
+HexaIMU KEYWORD1
+HexaIMUConfig KEYWORD1
+HexaIMUData KEYWORD1
+
+# ── Methods ──
+begin KEYWORD2
+isReady KEYWORD2
+read KEYWORD2
+getData KEYWORD2
+getAccelX KEYWORD2
+getAccelY KEYWORD2
+getAccelZ KEYWORD2
+getGyroX KEYWORD2
+getGyroY KEYWORD2
+getGyroZ KEYWORD2
+getTemp KEYWORD2
+setAccelRange KEYWORD2
+getAccelRange KEYWORD2
+setGyroRange KEYWORD2
+getGyroRange KEYWORD2
+tick KEYWORD2
+getHeading KEYWORD2
+isHeadingReady KEYWORD2
+zeroHeading KEYWORD2
+resetHeading KEYWORD2
+
+# ── Enum Constants ──
+HEXA_ACCEL_RANGE_2G LITERAL1
+HEXA_ACCEL_RANGE_4G LITERAL1
+HEXA_ACCEL_RANGE_8G LITERAL1
+HEXA_ACCEL_RANGE_16G LITERAL1
+HEXA_GYRO_RANGE_250_DPS LITERAL1
+HEXA_GYRO_RANGE_500_DPS LITERAL1
+HEXA_GYRO_RANGE_1000_DPS LITERAL1
+HEXA_GYRO_RANGE_2000_DPS LITERAL1
diff --git a/lib/HexaIMU/lib/xtensa-esp32s3/libHexaIMU_static.a b/lib/HexaIMU/lib/xtensa-esp32s3/libHexaIMU_static.a
new file mode 100644
index 0000000..9cf8556
--- /dev/null
+++ b/lib/HexaIMU/lib/xtensa-esp32s3/libHexaIMU_static.a
Binary files differ
diff --git a/lib/HexaIMU/library.json b/lib/HexaIMU/library.json
new file mode 100644
index 0000000..b675b51
--- /dev/null
+++ b/lib/HexaIMU/library.json
@@ -0,0 +1,15 @@
+{
+ "name": "HexaIMU",
+ "version": "2.0.0",
+ "description": "LSM6DSOX IMU driver for HEXA COMMAND HUB",
+ "keywords": ["imu", "lsm6dsox", "accelerometer", "gyroscope", "heading", "esp32", "hexa"],
+ "authors": [
+ {
+ "name": "Rush",
+ "maintainer": true
+ }
+ ],
+ "license": "MIT",
+ "platforms": "espressif32",
+ "frameworks": "arduino"
+}
diff --git a/lib/HexaIMU/library.properties b/lib/HexaIMU/library.properties
new file mode 100644
index 0000000..7e44d97
--- /dev/null
+++ b/lib/HexaIMU/library.properties
@@ -0,0 +1,10 @@
+name=HexaIMU
+version=2.0.0
+author=Rush
+maintainer=Rush
+sentence=LSM6DSOX IMU driver for HEXA COMMAND HUB
+paragraph=Thin wrapper around Adafruit_LSM6DSOX matching the HexaDCMotor/HexaServo/HexaOLED object idiom. Reads accelerometer (m/s2), gyroscope (rad/s), and temperature (degC), plus a non-blocking tick()-driven heading API (gyro-Z bias calibration + integration) so students never need a blocking calibration loop in init().
+category=Sensors
+url=
+architectures=esp32
+depends=Adafruit LSM6DS, Adafruit Unified Sensor
diff --git a/lib/HexaIMU/src/HexaIMU.h b/lib/HexaIMU/src/HexaIMU.h
new file mode 100644
index 0000000..7be5527
--- /dev/null
+++ b/lib/HexaIMU/src/HexaIMU.h
@@ -0,0 +1,164 @@
+/**
+ * HexaIMU.h — LSM6DSOX IMU Driver for HEXA COMMAND HUB
+ *
+ * Thin wrapper around Adafruit_LSM6DSOX — the LSM6DSOX is the IMU actually
+ * fitted on the robot board (I2C 0x6B), and Adafruit_LSM6DSOX is already a
+ * required dependency of this firmware (see NRLComms.cpp), so wrapping it
+ * here adds no new dependency. The point of this class is the same simple
+ * "declare an object, call its methods" idiom used by HexaDCMotor/HexaServo/
+ * HexaOLED, plus a non-blocking heading API students can't get wrong.
+ *
+ * Chip: ST LSM6DSOX
+ * Part of: HexaIMU library
+ * Author: Rush / HEXA Robotics
+ */
+
+#pragma once
+
+#include <Arduino.h>
+#include <Wire.h>
+#include <Adafruit_LSM6DSOX.h>
+
+
+// Enumerations — simplified names over the underlying Adafruit_LSM6DSOX enums.
+
+typedef enum {
+ HEXA_ACCEL_RANGE_2G = 0, // ±2g (highest precision)
+ HEXA_ACCEL_RANGE_4G = 1, // ±4g (default)
+ HEXA_ACCEL_RANGE_8G = 2, // ±8g
+ HEXA_ACCEL_RANGE_16G = 3, // ±16g
+} hexa_accel_range_t;
+
+typedef enum {
+ HEXA_GYRO_RANGE_250_DPS = 0, // ±250 deg/s (default)
+ HEXA_GYRO_RANGE_500_DPS = 1, // ±500 deg/s
+ HEXA_GYRO_RANGE_1000_DPS = 2, // ±1000 deg/s
+ HEXA_GYRO_RANGE_2000_DPS = 3, // ±2000 deg/s
+} hexa_gyro_range_t;
+
+
+// Data struct
+
+/**
+ * All IMU readings from one read() call.
+ */
+struct HexaIMUData {
+ float accelX; // Acceleration X (m/s²)
+ float accelY; // Acceleration Y (m/s²)
+ float accelZ; // Acceleration Z (m/s², ≈9.81 when flat on a table)
+ float gyroX; // Angular rate X (rad/s)
+ float gyroY; // Angular rate Y (rad/s)
+ float gyroZ; // Angular rate Z (rad/s)
+ float tempC; // Die temperature (°C, not ambient)
+};
+
+
+/**
+ * Configuration for one LSM6DSOX.
+ * Defaults to 0x6B (the robot board's onboard IMU address).
+ */
+struct HexaIMUConfig {
+ uint8_t i2cAddr = 0x6B; // LSM6DSOX default (SDO high)
+ TwoWire* wire = &Wire; // Wire instance (Wire.h is Arduino built-in)
+ int8_t sdaPin = -1; // SDA pin (-1 = use board default)
+ int8_t sclPin = -1; // SCL pin (-1 = use board default)
+};
+
+
+class HexaIMU {
+public:
+ /**
+ * Constructor — stores config, does NOT touch hardware.
+ * Call begin() in setup()/init() to initialize.
+ */
+ HexaIMU() : HexaIMU(HexaIMUConfig{}) {}
+ explicit HexaIMU(const HexaIMUConfig& config);
+
+ /**
+ * Initialize the IMU. Returns true on success.
+ * Sets defaults: ±4g accel, ±250°/s gyro, 104 Hz data rate.
+ * Safe to call from an OpMode's init() — does not block longer
+ * than Adafruit_LSM6DSOX's own begin_I2C() already does.
+ */
+ bool begin();
+
+ /** Returns true if begin() succeeded. */
+ bool isReady() const;
+
+
+ // Core Data Acquisition
+
+ /**
+ * Read all sensor data in one call. Caches the result for the get*()
+ * functions below. Call this in loop() before reading any values.
+ * Returns false if not ready (begin() was not called/failed).
+ */
+ bool read();
+
+ /** Return all last readings as a single struct. */
+ HexaIMUData getData() const;
+
+ float getAccelX() const; // Acceleration X (m/s²)
+ float getAccelY() const; // Acceleration Y (m/s²)
+ float getAccelZ() const; // Acceleration Z (m/s²)
+ float getGyroX() const; // Angular rate X (rad/s)
+ float getGyroY() const; // Angular rate Y (rad/s)
+ float getGyroZ() const; // Angular rate Z (rad/s)
+ float getTemp() const; // Die temperature (°C)
+
+
+ // Range Configuration
+
+ /** Set accelerometer full-scale range. Default: HEXA_ACCEL_RANGE_4G */
+ void setAccelRange(hexa_accel_range_t range);
+ hexa_accel_range_t getAccelRange() const;
+
+ /** Set gyroscope full-scale range. Default: HEXA_GYRO_RANGE_250_DPS */
+ void setGyroRange(hexa_gyro_range_t range);
+ hexa_gyro_range_t getGyroRange() const;
+
+
+ // Heading (gyro-Z integration, non-blocking calibration)
+
+ /**
+ * Call every loop() tick with the current millis() (or micros()/1000).
+ * For the first ~50 calls, accumulates a gyro-Z bias estimate while
+ * the robot should be held still (no delay() — calibration is simply
+ * spread across however many loop iterations happen in ~0.5s).
+ * After that, integrates heading from bias-corrected, deadbanded gz.
+ */
+ void tick(uint32_t nowMs);
+
+ /** Current integrated heading, in degrees. */
+ float getHeading() const;
+
+ /** True once the initial gyro bias calibration has completed. */
+ bool isHeadingReady() const;
+
+ /** Reset the accumulated angle only — keeps the existing bias estimate. */
+ void zeroHeading();
+
+ /** Full reset — re-run bias calibration AND zero the angle. Hold the robot still for ~0.5s after calling this. */
+ void resetHeading();
+
+
+private:
+ HexaIMUConfig m_cfg;
+ Adafruit_LSM6DSOX m_lsm;
+ HexaIMUData m_data = {};
+ bool m_ready = false;
+
+ hexa_accel_range_t m_accelRange = HEXA_ACCEL_RANGE_4G;
+ hexa_gyro_range_t m_gyroRange = HEXA_GYRO_RANGE_250_DPS;
+
+ // Heading state — owned per-instance, independent of any other HexaIMU
+ // or framework-internal IMU instance that may also be polling the bus.
+ static constexpr uint8_t HDG_CALIB_N = 50; // samples for bias estimate (~0.5s at ~100Hz tick())
+ static constexpr float HDG_DEADBAND = 0.003f; // rad/s — suppress residual noise (~0.17 deg/s)
+
+ float m_headingDeg = 0.0f;
+ float m_gzBias = 0.0f;
+ uint8_t m_calibCount = 0;
+ bool m_calibDone = false;
+ uint32_t m_lastTickMs = 0;
+};
diff --git a/lib/HexaLED/build-manifest.json b/lib/HexaLED/build-manifest.json
new file mode 100644
index 0000000..5ca9e3b
--- /dev/null
+++ b/lib/HexaLED/build-manifest.json
@@ -0,0 +1,72 @@
+{
+ "source_lib": "lib\\HexaLED",
+ "sdk_version": "1.4.1",
+ "built_from_commit": "036661d7fa9340e198bf3f6d376121ae8c214f59",
+ "built_at": "2026-10-10T14:37:40.848498Z",
+ "harvested_from_project": "RobotFirmware",
+ "harvested_env": "robot",
+ "cxx_path": "C:\\Users\\thein\\.platformio\\packages\\toolchain-xtensa-esp32s3\\bin\\xtensa-esp32s3-elf-g++.exe",
+ "cxx_flags": [
+ "-std=gnu++17",
+ "-fexceptions",
+ "-fno-rtti",
+ "-Os",
+ "-mlongcalls",
+ "-ffunction-sections",
+ "-fdata-sections",
+ "-Wno-error=unused-function",
+ "-Wno-error=unused-variable",
+ "-Wno-error=deprecated-declarations",
+ "-Wno-unused-parameter",
+ "-Wno-sign-compare",
+ "-ggdb",
+ "-freorder-blocks",
+ "-Wwrite-strings",
+ "-fstack-protector",
+ "-fstrict-volatile-bitfields",
+ "-Wno-error=unused-but-set-variable",
+ "-fno-jump-tables",
+ "-fno-tree-switch-conversion",
+ "-MMD",
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "defines": [
+ "PLATFORMIO=60200",
+ "ARDUINO_ESP32S3_DEV",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_RUNNING_CORE=1",
+ "ARDUINO_EVENT_RUNNING_CORE=1",
+ "CONFIG_FREERTOS_HZ=1000",
+ "CORE_DEBUG_LEVEL=3",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_USB_CDC_ON_BOOT=1",
+ "HAVE_CONFIG_H",
+ "MBEDTLS_CONFIG_FILE=\"mbedtls/esp_config.h\"",
+ "UNITY_INCLUDE_CONFIG_H",
+ "WITH_POSIX",
+ "_GNU_SOURCE",
+ "IDF_VER=\"v4.4.7-dirty\"",
+ "ESP_PLATFORM",
+ "_POSIX_READER_WRITER_LOCKS",
+ "ARDUINO_ARCH_ESP32",
+ "ESP32",
+ "F_CPU=240000000L",
+ "ARDUINO=10812",
+ "ARDUINO_VARIANT=\"esp32s3\"",
+ "ARDUINO_BOARD=\"Espressif ESP32-S3-DevKitC-1-N8 (8 MB QD, No PSRAM)\"",
+ "ARDUINO_PARTITION_partitions"
+ ],
+ "hardening": {
+ "extra_cxx_flags": [
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "symbols_stripped": true,
+ "strings_encrypted": true
+ }
+} \ No newline at end of file
diff --git a/lib/HexaLED/lib/xtensa-esp32s3/libHexaLED_static.a b/lib/HexaLED/lib/xtensa-esp32s3/libHexaLED_static.a
new file mode 100644
index 0000000..1ddfd77
--- /dev/null
+++ b/lib/HexaLED/lib/xtensa-esp32s3/libHexaLED_static.a
Binary files differ
diff --git a/lib/HexaLED/library.json b/lib/HexaLED/library.json
new file mode 100644
index 0000000..14f2eab
--- /dev/null
+++ b/lib/HexaLED/library.json
@@ -0,0 +1,15 @@
+{
+ "name": "HexaLED",
+ "version": "1.0.0",
+ "description": "NeoPixel status and user LED driver for HEXA COMMAND HUB",
+ "keywords": ["led", "neopixel", "ws2812b", "rgb", "status", "esp32", "hexa"],
+ "authors": [
+ {
+ "name": "Rush",
+ "maintainer": true
+ }
+ ],
+ "license": "MIT",
+ "platforms": "espressif32",
+ "frameworks": "arduino"
+}
diff --git a/lib/HexaLED/library.properties b/lib/HexaLED/library.properties
new file mode 100644
index 0000000..b43aa73
--- /dev/null
+++ b/lib/HexaLED/library.properties
@@ -0,0 +1,9 @@
+name=HexaLED
+version=1.0.0
+author=Rush
+maintainer=Rush
+sentence=NeoPixel status and user LED driver for HEXA COMMAND HUB
+paragraph=Drives WS2812B NeoPixels with solid, blink, and pulse patterns. Supports standalone and shared-strip modes for chained pixels. Framework status LED and student-controlled user LED on the same data line.
+category=Display
+url=
+architectures=esp32
diff --git a/lib/HexaLED/src/HexaLED.h b/lib/HexaLED/src/HexaLED.h
new file mode 100644
index 0000000..67714a9
--- /dev/null
+++ b/lib/HexaLED/src/HexaLED.h
@@ -0,0 +1,70 @@
+#pragma once
+#include <Adafruit_NeoPixel.h>
+
+// ============================================================
+// HexaLED — NeoPixel status/user indicator for NRL
+// ============================================================
+//
+// Two usage modes:
+//
+// 1. Standalone — HexaLED owns its own strip (controller ctrlLed):
+// HexaLED ctrlLed(38, 1);
+//
+// 2. Shared — HexaLED controls one pixel inside an external strip
+// (robot botLed + userLed share the same GPIO 38 data line):
+// Adafruit_NeoPixel nrlLedStrip(2, 38, NEO_GRB + NEO_KHZ800);
+// HexaLED botLed(nrlLedStrip, 0); // pixel 0 — framework status
+// HexaLED userLed(nrlLedStrip, 1); // pixel 1 — student use
+//
+// Call begin() once, then tick(millis()) every loop iteration.
+// Call the stateXxx() / setSolid() / setBlink() / setPulse() methods
+// to change the LED; tick() handles all animation without blocking.
+
+class HexaLED {
+public:
+ // Standalone mode — owns a dedicated strip
+ HexaLED(uint8_t pin, uint8_t count = 1);
+
+ // Shared mode — controls one pixel inside an externally-owned strip
+ HexaLED(Adafruit_NeoPixel& strip, uint8_t pixelIndex);
+
+ void begin();
+ void tick(uint32_t nowMs);
+
+ // ── Color / pattern methods (student-facing API) ──────────
+ void setOff();
+ void setSolid(uint8_t r, uint8_t g, uint8_t b);
+ void setBlink(uint8_t r, uint8_t g, uint8_t b, uint16_t periodMs = 500);
+ void setPulse(uint8_t r, uint8_t g, uint8_t b, uint16_t periodMs = 1000);
+
+ // ── Named NRL framework states (framework use only) ───────
+ void stateUnpaired();
+ void statePairing();
+ void stateReconnecting();
+ void stateIdle();
+ void stateInit();
+ void stateRunningTeleop();
+ void stateRunningAuto();
+ void stateLoopOverrun();
+
+private:
+ enum class Pattern : uint8_t { SOLID, BLINK, PULSE };
+
+ void _set(uint8_t r, uint8_t g, uint8_t b, Pattern p, uint16_t periodMs);
+ void _write(uint8_t r, uint8_t g, uint8_t b);
+
+ Adafruit_NeoPixel _ownStrip; // used in standalone mode
+ Adafruit_NeoPixel* _strip; // points to _ownStrip (standalone) or external (shared)
+ uint8_t _pixelIndex; // which pixel in the strip this instance controls
+ uint8_t _count; // number of pixels controlled (always 1 in shared mode)
+
+ uint8_t _r, _g, _b;
+ Pattern _pattern;
+ uint16_t _period;
+ uint32_t _phaseStart;
+ bool _on;
+
+ // Last time _write() actually pushed bytes to the strip. SOLID uses this to
+ // periodically re-assert its colour — see tick().
+ uint32_t _lastWriteMs = 0;
+};
diff --git a/lib/HexaOLED/build-manifest.json b/lib/HexaOLED/build-manifest.json
new file mode 100644
index 0000000..34ff1f6
--- /dev/null
+++ b/lib/HexaOLED/build-manifest.json
@@ -0,0 +1,72 @@
+{
+ "source_lib": "lib\\HexaOLED",
+ "sdk_version": "1.4.1",
+ "built_from_commit": "036661d7fa9340e198bf3f6d376121ae8c214f59",
+ "built_at": "2026-10-10T14:36:58.768212Z",
+ "harvested_from_project": "RobotFirmware",
+ "harvested_env": "robot",
+ "cxx_path": "C:\\Users\\thein\\.platformio\\packages\\toolchain-xtensa-esp32s3\\bin\\xtensa-esp32s3-elf-g++.exe",
+ "cxx_flags": [
+ "-std=gnu++17",
+ "-fexceptions",
+ "-fno-rtti",
+ "-Os",
+ "-mlongcalls",
+ "-ffunction-sections",
+ "-fdata-sections",
+ "-Wno-error=unused-function",
+ "-Wno-error=unused-variable",
+ "-Wno-error=deprecated-declarations",
+ "-Wno-unused-parameter",
+ "-Wno-sign-compare",
+ "-ggdb",
+ "-freorder-blocks",
+ "-Wwrite-strings",
+ "-fstack-protector",
+ "-fstrict-volatile-bitfields",
+ "-Wno-error=unused-but-set-variable",
+ "-fno-jump-tables",
+ "-fno-tree-switch-conversion",
+ "-MMD",
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "defines": [
+ "PLATFORMIO=60200",
+ "ARDUINO_ESP32S3_DEV",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_RUNNING_CORE=1",
+ "ARDUINO_EVENT_RUNNING_CORE=1",
+ "CONFIG_FREERTOS_HZ=1000",
+ "CORE_DEBUG_LEVEL=3",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_USB_CDC_ON_BOOT=1",
+ "HAVE_CONFIG_H",
+ "MBEDTLS_CONFIG_FILE=\"mbedtls/esp_config.h\"",
+ "UNITY_INCLUDE_CONFIG_H",
+ "WITH_POSIX",
+ "_GNU_SOURCE",
+ "IDF_VER=\"v4.4.7-dirty\"",
+ "ESP_PLATFORM",
+ "_POSIX_READER_WRITER_LOCKS",
+ "ARDUINO_ARCH_ESP32",
+ "ESP32",
+ "F_CPU=240000000L",
+ "ARDUINO=10812",
+ "ARDUINO_VARIANT=\"esp32s3\"",
+ "ARDUINO_BOARD=\"Espressif ESP32-S3-DevKitC-1-N8 (8 MB QD, No PSRAM)\"",
+ "ARDUINO_PARTITION_partitions"
+ ],
+ "hardening": {
+ "extra_cxx_flags": [
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "symbols_stripped": true,
+ "strings_encrypted": true
+ }
+} \ No newline at end of file
diff --git a/lib/HexaOLED/keywords.txt b/lib/HexaOLED/keywords.txt
new file mode 100644
index 0000000..2849081
--- /dev/null
+++ b/lib/HexaOLED/keywords.txt
@@ -0,0 +1,30 @@
+# ═══════════════════════════════════════════════
+# Syntax Highlighting for HexaOLED Library
+# ═══════════════════════════════════════════════
+# KEYWORD1 = Classes (highlighted as types)
+# KEYWORD2 = Methods (highlighted as functions)
+# LITERAL1 = Constants
+
+# ── Classes ──
+HexaOLED KEYWORD1
+HexaOLEDConfig KEYWORD1
+
+# ── Methods ──
+begin KEYWORD2
+isReady KEYWORD2
+clearDisplay KEYWORD2
+display KEYWORD2
+drawPixel KEYWORD2
+drawLine KEYWORD2
+drawRect KEYWORD2
+fillRect KEYWORD2
+setCursor KEYWORD2
+setTextColor KEYWORD2
+setTextSize KEYWORD2
+print KEYWORD2
+println KEYWORD2
+
+# ── Constants ──
+WHITE LITERAL1
+BLACK LITERAL1
+INVERSE LITERAL1
diff --git a/lib/HexaOLED/lib/xtensa-esp32s3/libHexaOLED_static.a b/lib/HexaOLED/lib/xtensa-esp32s3/libHexaOLED_static.a
new file mode 100644
index 0000000..03a6bf8
--- /dev/null
+++ b/lib/HexaOLED/lib/xtensa-esp32s3/libHexaOLED_static.a
Binary files differ
diff --git a/lib/HexaOLED/library.json b/lib/HexaOLED/library.json
new file mode 100644
index 0000000..8843a0b
--- /dev/null
+++ b/lib/HexaOLED/library.json
@@ -0,0 +1,15 @@
+{
+ "name": "HexaOLED",
+ "version": "1.0.0",
+ "description": "Standalone SSD1306 OLED driver for HEXA COMMAND HUB",
+ "keywords": ["oled", "ssd1306", "display", "i2c", "esp32", "hexa"],
+ "authors": [
+ {
+ "name": "Rush",
+ "maintainer": true
+ }
+ ],
+ "license": "MIT",
+ "platforms": "espressif32",
+ "frameworks": "arduino"
+}
diff --git a/lib/HexaOLED/library.properties b/lib/HexaOLED/library.properties
new file mode 100644
index 0000000..feaa6d9
--- /dev/null
+++ b/lib/HexaOLED/library.properties
@@ -0,0 +1,9 @@
+name=HexaOLED
+version=1.0.0
+author=Rush
+maintainer=Rush
+sentence=Standalone SSD1306 OLED driver for HEXA COMMAND HUB
+paragraph=Zero Adafruit dependency. Uses only Wire.h (Arduino built-in). Built-in 5x7 font, frame buffer, and drawing primitives (pixel, line, rect, text).
+category=Display
+url=
+architectures=esp32
diff --git a/lib/HexaOLED/src/HexaFont.h b/lib/HexaOLED/src/HexaFont.h
new file mode 100644
index 0000000..e07366e
--- /dev/null
+++ b/lib/HexaOLED/src/HexaFont.h
@@ -0,0 +1,135 @@
+/**
+ * ============================================================
+ * HexaFont.h — Built-in 5×7 ASCII Font
+ * ============================================================
+ *
+ * Standard 5×7 pixel monospace font covering ASCII 32–126.
+ * Stored in PROGMEM (flash memory) so it costs zero RAM.
+ *
+ * Layout of each glyph (5 bytes = 5 columns):
+ *
+ * Byte index → column (left to right)
+ * Bit index → row (bit 0 = top row, bit 6 = bottom row)
+ *
+ * Example: 'A' (0x7E, 0x11, 0x11, 0x11, 0x7E)
+ *
+ * col: 0 1 2 3 4
+ * 0x7E 0x11 0x11 0x11 0x7E
+ * row0: 0 1 1 1 0 ← bit 0
+ * row1: 1 0 0 0 1 ← bit 1
+ * row2: 1 0 0 0 1 ← bit 2
+ * row3: 1 1 1 1 1 ← bit 3
+ * row4: 1 0 0 0 1 ← bit 4
+ * row5: 1 0 0 0 1 ← bit 5
+ * row6: 0 0 0 0 0 ← bit 6
+ *
+ * Each character cell is 6×8 px (5 glyph + 1 gap column,
+ * 7 glyph + 1 gap row) giving clean spacing between chars.
+ *
+ * Part of: HexaOLED library
+ * Author: Rush / HEXA Robotics
+ * ============================================================
+ */
+
+#pragma once
+
+#include <Arduino.h> // for PROGMEM, pgm_read_byte
+
+// ASCII 32 (space) through 126 (~) = 95 characters × 5 bytes
+static const uint8_t HEXA_FONT[][5] PROGMEM = {
+ { 0x00, 0x00, 0x00, 0x00, 0x00 }, // 32 (space)
+ { 0x00, 0x00, 0x5F, 0x00, 0x00 }, // 33 !
+ { 0x00, 0x07, 0x00, 0x07, 0x00 }, // 34 "
+ { 0x14, 0x7F, 0x14, 0x7F, 0x14 }, // 35 #
+ { 0x24, 0x2A, 0x7F, 0x2A, 0x12 }, // 36 $
+ { 0x23, 0x13, 0x08, 0x64, 0x62 }, // 37 %
+ { 0x36, 0x49, 0x55, 0x22, 0x50 }, // 38 &
+ { 0x00, 0x05, 0x03, 0x00, 0x00 }, // 39 '
+ { 0x00, 0x1C, 0x22, 0x41, 0x00 }, // 40 (
+ { 0x00, 0x41, 0x22, 0x1C, 0x00 }, // 41 )
+ { 0x14, 0x08, 0x3E, 0x08, 0x14 }, // 42 *
+ { 0x08, 0x08, 0x3E, 0x08, 0x08 }, // 43 +
+ { 0x00, 0x50, 0x30, 0x00, 0x00 }, // 44 ,
+ { 0x08, 0x08, 0x08, 0x08, 0x08 }, // 45 -
+ { 0x00, 0x60, 0x60, 0x00, 0x00 }, // 46 .
+ { 0x20, 0x10, 0x08, 0x04, 0x02 }, // 47 /
+ { 0x3E, 0x51, 0x49, 0x45, 0x3E }, // 48 0
+ { 0x00, 0x42, 0x7F, 0x40, 0x00 }, // 49 1
+ { 0x42, 0x61, 0x51, 0x49, 0x46 }, // 50 2
+ { 0x21, 0x41, 0x45, 0x4B, 0x31 }, // 51 3
+ { 0x18, 0x14, 0x12, 0x7F, 0x10 }, // 52 4
+ { 0x27, 0x45, 0x45, 0x45, 0x39 }, // 53 5
+ { 0x3C, 0x4A, 0x49, 0x49, 0x30 }, // 54 6
+ { 0x01, 0x71, 0x09, 0x05, 0x03 }, // 55 7
+ { 0x36, 0x49, 0x49, 0x49, 0x36 }, // 56 8
+ { 0x06, 0x49, 0x49, 0x29, 0x1E }, // 57 9
+ { 0x00, 0x36, 0x36, 0x00, 0x00 }, // 58 :
+ { 0x00, 0x56, 0x36, 0x00, 0x00 }, // 59 ;
+ { 0x08, 0x14, 0x22, 0x41, 0x00 }, // 60 <
+ { 0x14, 0x14, 0x14, 0x14, 0x14 }, // 61 =
+ { 0x00, 0x41, 0x22, 0x14, 0x08 }, // 62 >
+ { 0x02, 0x01, 0x51, 0x09, 0x06 }, // 63 ?
+ { 0x32, 0x49, 0x79, 0x41, 0x3E }, // 64 @
+ { 0x7E, 0x11, 0x11, 0x11, 0x7E }, // 65 A
+ { 0x7F, 0x49, 0x49, 0x49, 0x36 }, // 66 B
+ { 0x3E, 0x41, 0x41, 0x41, 0x22 }, // 67 C
+ { 0x7F, 0x41, 0x41, 0x22, 0x1C }, // 68 D
+ { 0x7F, 0x49, 0x49, 0x49, 0x41 }, // 69 E
+ { 0x7F, 0x09, 0x09, 0x09, 0x01 }, // 70 F
+ { 0x3E, 0x41, 0x49, 0x49, 0x7A }, // 71 G
+ { 0x7F, 0x08, 0x08, 0x08, 0x7F }, // 72 H
+ { 0x00, 0x41, 0x7F, 0x41, 0x00 }, // 73 I
+ { 0x20, 0x40, 0x41, 0x3F, 0x01 }, // 74 J
+ { 0x7F, 0x08, 0x14, 0x22, 0x41 }, // 75 K
+ { 0x7F, 0x40, 0x40, 0x40, 0x40 }, // 76 L
+ { 0x7F, 0x02, 0x0C, 0x02, 0x7F }, // 77 M
+ { 0x7F, 0x04, 0x08, 0x10, 0x7F }, // 78 N
+ { 0x3E, 0x41, 0x41, 0x41, 0x3E }, // 79 O
+ { 0x7F, 0x09, 0x09, 0x09, 0x06 }, // 80 P
+ { 0x3E, 0x41, 0x51, 0x21, 0x5E }, // 81 Q
+ { 0x7F, 0x09, 0x19, 0x29, 0x46 }, // 82 R
+ { 0x46, 0x49, 0x49, 0x49, 0x31 }, // 83 S
+ { 0x01, 0x01, 0x7F, 0x01, 0x01 }, // 84 T
+ { 0x3F, 0x40, 0x40, 0x40, 0x3F }, // 85 U
+ { 0x1F, 0x20, 0x40, 0x20, 0x1F }, // 86 V
+ { 0x3F, 0x40, 0x38, 0x40, 0x3F }, // 87 W
+ { 0x63, 0x14, 0x08, 0x14, 0x63 }, // 88 X
+ { 0x07, 0x08, 0x70, 0x08, 0x07 }, // 89 Y
+ { 0x61, 0x51, 0x49, 0x45, 0x43 }, // 90 Z
+ { 0x00, 0x7F, 0x41, 0x41, 0x00 }, // 91 [
+ { 0x02, 0x04, 0x08, 0x10, 0x20 }, // 92 backslash
+ { 0x00, 0x41, 0x41, 0x7F, 0x00 }, // 93 ]
+ { 0x04, 0x02, 0x01, 0x02, 0x04 }, // 94 ^
+ { 0x40, 0x40, 0x40, 0x40, 0x40 }, // 95 _
+ { 0x00, 0x01, 0x02, 0x04, 0x00 }, // 96 `
+ { 0x20, 0x54, 0x54, 0x54, 0x78 }, // 97 a
+ { 0x7F, 0x48, 0x44, 0x44, 0x38 }, // 98 b
+ { 0x38, 0x44, 0x44, 0x44, 0x20 }, // 99 c
+ { 0x38, 0x44, 0x44, 0x48, 0x7F }, // 100 d
+ { 0x38, 0x54, 0x54, 0x54, 0x18 }, // 101 e
+ { 0x08, 0x7E, 0x09, 0x01, 0x02 }, // 102 f
+ { 0x0C, 0x52, 0x52, 0x52, 0x3E }, // 103 g
+ { 0x7F, 0x08, 0x04, 0x04, 0x78 }, // 104 h
+ { 0x00, 0x44, 0x7D, 0x40, 0x00 }, // 105 i
+ { 0x20, 0x40, 0x44, 0x3D, 0x00 }, // 106 j
+ { 0x7F, 0x10, 0x28, 0x44, 0x00 }, // 107 k
+ { 0x00, 0x41, 0x7F, 0x40, 0x00 }, // 108 l
+ { 0x7C, 0x04, 0x18, 0x04, 0x78 }, // 109 m
+ { 0x7C, 0x08, 0x04, 0x04, 0x78 }, // 110 n
+ { 0x38, 0x44, 0x44, 0x44, 0x38 }, // 111 o
+ { 0x7C, 0x14, 0x14, 0x14, 0x08 }, // 112 p
+ { 0x08, 0x14, 0x14, 0x18, 0x7C }, // 113 q
+ { 0x7C, 0x08, 0x04, 0x04, 0x08 }, // 114 r
+ { 0x48, 0x54, 0x54, 0x54, 0x20 }, // 115 s
+ { 0x04, 0x3F, 0x44, 0x40, 0x20 }, // 116 t
+ { 0x3C, 0x40, 0x40, 0x20, 0x7C }, // 117 u
+ { 0x1C, 0x20, 0x40, 0x20, 0x1C }, // 118 v
+ { 0x3C, 0x40, 0x30, 0x40, 0x3C }, // 119 w
+ { 0x44, 0x28, 0x10, 0x28, 0x44 }, // 120 x
+ { 0x0C, 0x50, 0x50, 0x50, 0x3C }, // 121 y
+ { 0x44, 0x64, 0x54, 0x4C, 0x44 }, // 122 z
+ { 0x00, 0x08, 0x36, 0x41, 0x00 }, // 123 {
+ { 0x00, 0x00, 0x7F, 0x00, 0x00 }, // 124 |
+ { 0x00, 0x41, 0x36, 0x08, 0x00 }, // 125 }
+ { 0x10, 0x08, 0x08, 0x10, 0x08 }, // 126 ~
+};
diff --git a/lib/HexaOLED/src/HexaOLED.h b/lib/HexaOLED/src/HexaOLED.h
new file mode 100644
index 0000000..e16aa97
--- /dev/null
+++ b/lib/HexaOLED/src/HexaOLED.h
@@ -0,0 +1,214 @@
+/**
+ * HexaOLED.h — SH1106G OLED Driver for HEXA COMMAND HUB
+ *
+ * Standalone SH1106G driver — no Adafruit dependency, only Wire.h.
+ * Maintains a 1024-byte local frame buffer (SH1106G cannot be read back over I2C).
+ * All drawing writes to the buffer; call display() to push the buffer to hardware.
+ *
+ * Font: HexaFont.h (5x7 ASCII bitmap, stored in flash)
+ * Part of: HexaOLED library
+ * Author: Rush / HEXA Robotics
+ */
+
+#pragma once
+
+#include <Arduino.h>
+#include <Wire.h>
+#include "HexaFont.h"
+
+
+/**
+ * Configuration for one OLED display.
+ * Example: HexaOLEDConfig cfg = { .i2cAddr = 0x3C, .sdaPin = 21, .sclPin = 22 };
+ */
+struct HexaOLEDConfig {
+ uint8_t i2cAddr = 0x3C; // SH1106G default I2C address (0x3C or 0x3D)
+ uint8_t width = 128; // Display width in pixels
+ uint8_t height = 64; // Display height in pixels (32 or 64)
+ TwoWire* wire = &Wire; // Wire instance (Wire.h is Arduino built-in)
+ int8_t sdaPin = -1; // SDA pin (-1 = use board default)
+ int8_t sclPin = -1; // SCL pin (-1 = use board default)
+};
+
+
+class HexaOLED {
+public:
+ // Color constants
+ static constexpr uint8_t WHITE = 1; // Turn pixel on
+ static constexpr uint8_t BLACK = 0; // Turn pixel off
+ static constexpr uint8_t INVERSE = 2; // Flip pixel state
+
+ /**
+ * Constructor — stores config, does NOT touch hardware.
+ * Call begin() in setup() to initialize.
+ */
+ HexaOLED(const HexaOLEDConfig& config);
+
+ /**
+ * Initialize the display. Call in setup().
+ * Returns true on success, false if display not found on I2C bus.
+ */
+ bool begin();
+
+ /**
+ * Returns true if begin() succeeded.
+ */
+ bool isReady() const;
+
+ // Non-blocking self-heal after a transient I2C/power fault. No-op while
+ // healthy. Call every loop from main-loop context (never the ESP-NOW callback).
+ void tickRecovery(uint32_t nowMs);
+
+#ifdef NRL_LINK_FAULT_INJECTION
+ // Bench only: trip the m_ready latch exactly as 5 consecutive I2C failures
+ // would, so tickRecovery() can be verified without physically interrupting
+ // the bus. Compiled out of the shipping build.
+ void debugForceFail() { m_ready = false; m_i2cFailCount = 255; }
+#endif
+
+ // Buffer operations
+
+ /**
+ * Fill the entire frame buffer with BLACK (all pixels off).
+ * Call before redrawing the screen each frame.
+ */
+ void clearDisplay();
+
+ /**
+ * Push the local frame buffer to the SH1106G hardware.
+ * Nothing you draw appears on screen until you call this.
+ */
+ void display();
+
+ /**
+ * Push only the pages that changed since the last displayDirty() call.
+ * Use this in tight loops instead of display() to minimize I2C transfer
+ * time and eliminate visible screen-sweep flicker.
+ */
+ void displayDirty();
+
+ // Drawing primitives
+
+ /**
+ * Set a single pixel. color = WHITE | BLACK | INVERSE.
+ * Out-of-bounds coordinates are silently ignored.
+ */
+ void drawPixel(int16_t x, int16_t y, uint8_t color);
+
+ /**
+ * Draw a straight line between two points.
+ * Uses Bresenham's algorithm — no floating point.
+ */
+ void drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint8_t color);
+
+ /**
+ * Draw an unfilled rectangle outline.
+ */
+ void drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint8_t color);
+
+ /**
+ * Draw a solid filled rectangle.
+ */
+ void fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint8_t color);
+
+ /**
+ * Draw an unfilled circle outline. Uses midpoint circle algorithm — no floating point.
+ */
+ void drawCircle(int16_t x0, int16_t y0, int16_t r, uint8_t color);
+
+ /**
+ * Draw a solid filled circle.
+ */
+ void fillCircle(int16_t x0, int16_t y0, int16_t r, uint8_t color);
+
+ // Text
+
+ /**
+ * Set cursor position for the next print() call.
+ * (0, 0) is the top-left corner of the display.
+ */
+ void setCursor(int16_t x, int16_t y);
+
+ /**
+ * Set text color. WHITE = visible, BLACK = background,
+ * INVERSE = flip each pixel as it is drawn.
+ */
+ void setTextColor(uint8_t color);
+
+ /**
+ * Set text scale factor.
+ * size=1 → 6×8 px per character (default)
+ * size=2 → 12×16 px per character
+ */
+ void setTextSize(uint8_t size);
+
+ /** Print a null-terminated string at the current cursor. */
+ void print(const char* str);
+
+ /** Print a string followed by a newline. */
+ void println(const char* str);
+
+ /** Print a signed integer. */
+ void print(int32_t value);
+
+ /** Print a float with a given number of decimal places (0-2). */
+ void print(float value, uint8_t decimals = 2);
+
+private:
+ HexaOLEDConfig m_cfg;
+
+ // Frame buffer: 128×64 / 8 = 1024 bytes max
+ // Indexed as: buf[x + (y/8)*width], bit = y%8
+ uint8_t m_buf[128 * 64 / 8];
+
+ int16_t m_cursorX = 0;
+ int16_t m_cursorY = 0;
+ uint8_t m_textColor = WHITE;
+ uint8_t m_textSize = 1;
+ bool m_ready = false;
+ uint8_t m_dirty = 0xFF; // bitmask: bit N = page N needs sending
+ uint8_t m_i2cFailCount = 0; // consecutive endTransmission() failures since last success
+
+ // SH1106G power-on init sequence. Defined at the top of HexaOLED.cpp, shared by
+ // begin() and tickRecovery() so the two cannot drift apart. Class-scope because
+ // the CMD_* values it uses are class members.
+ static const uint8_t SH1106_INIT_CMDS[];
+
+ // tickRecovery() state — see HexaOLED.cpp.
+ enum class Recovery : uint8_t { Idle, AwaitDisplayOn };
+ Recovery m_recovery = Recovery::Idle;
+ uint32_t m_recoveryMs = 0; // last probe, or when init finished
+
+ // Internal helpers
+
+ // Send one page of pixel data (used by display() and displayDirty())
+ void _sendPage(uint8_t page);
+
+ // Send a single command byte to the SH1106G
+ void sh1106_cmd(uint8_t c);
+
+ // Send a list of command bytes
+ void sh1106_cmdList(const uint8_t* list, uint8_t len);
+
+ // Draw one character glyph from HexaFont at (x, y)
+ void drawChar(int16_t x, int16_t y, char c, uint8_t color, uint8_t size);
+
+ // SH1106G command constants
+ static constexpr uint8_t CMD_DISPLAYOFF = 0xAE;
+ static constexpr uint8_t CMD_DISPLAYON = 0xAF;
+ static constexpr uint8_t CMD_SETDISPLAYCLOCKDIV = 0xD5;
+ static constexpr uint8_t CMD_SETMULTIPLEX = 0xA8;
+ static constexpr uint8_t CMD_SETDISPLAYOFFSET = 0xD3;
+ static constexpr uint8_t CMD_SETSTARTLINE = 0x40;
+ static constexpr uint8_t CMD_DCDC = 0xAD; // internal DC/DC control
+ static constexpr uint8_t CMD_MEMORYMODE = 0x20;
+ static constexpr uint8_t CMD_SEGREMAP = 0xA1;
+ static constexpr uint8_t CMD_COMSCANDEC = 0xC8;
+ static constexpr uint8_t CMD_SETCOMPINS = 0xDA;
+ static constexpr uint8_t CMD_SETCONTRAST = 0x81;
+ static constexpr uint8_t CMD_SETPRECHARGE = 0xD9;
+ static constexpr uint8_t CMD_SETVCOMDETECT = 0xDB;
+ static constexpr uint8_t CMD_DISPLAYALLON_RESUME= 0xA4;
+ static constexpr uint8_t CMD_NORMALDISPLAY = 0xA6;
+ static constexpr uint8_t CMD_SETPAGEADDR = 0xB0; // page addressing base
+};
diff --git a/lib/HexaPower/build-manifest.json b/lib/HexaPower/build-manifest.json
new file mode 100644
index 0000000..6828a85
--- /dev/null
+++ b/lib/HexaPower/build-manifest.json
@@ -0,0 +1,72 @@
+{
+ "source_lib": "lib\\HexaPower",
+ "sdk_version": "1.4.1",
+ "built_from_commit": "036661d7fa9340e198bf3f6d376121ae8c214f59",
+ "built_at": "2026-10-10T14:38:01.873467Z",
+ "harvested_from_project": "RobotFirmware",
+ "harvested_env": "robot",
+ "cxx_path": "C:\\Users\\thein\\.platformio\\packages\\toolchain-xtensa-esp32s3\\bin\\xtensa-esp32s3-elf-g++.exe",
+ "cxx_flags": [
+ "-std=gnu++17",
+ "-fexceptions",
+ "-fno-rtti",
+ "-Os",
+ "-mlongcalls",
+ "-ffunction-sections",
+ "-fdata-sections",
+ "-Wno-error=unused-function",
+ "-Wno-error=unused-variable",
+ "-Wno-error=deprecated-declarations",
+ "-Wno-unused-parameter",
+ "-Wno-sign-compare",
+ "-ggdb",
+ "-freorder-blocks",
+ "-Wwrite-strings",
+ "-fstack-protector",
+ "-fstrict-volatile-bitfields",
+ "-Wno-error=unused-but-set-variable",
+ "-fno-jump-tables",
+ "-fno-tree-switch-conversion",
+ "-MMD",
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "defines": [
+ "PLATFORMIO=60200",
+ "ARDUINO_ESP32S3_DEV",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_RUNNING_CORE=1",
+ "ARDUINO_EVENT_RUNNING_CORE=1",
+ "CONFIG_FREERTOS_HZ=1000",
+ "CORE_DEBUG_LEVEL=3",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_USB_CDC_ON_BOOT=1",
+ "HAVE_CONFIG_H",
+ "MBEDTLS_CONFIG_FILE=\"mbedtls/esp_config.h\"",
+ "UNITY_INCLUDE_CONFIG_H",
+ "WITH_POSIX",
+ "_GNU_SOURCE",
+ "IDF_VER=\"v4.4.7-dirty\"",
+ "ESP_PLATFORM",
+ "_POSIX_READER_WRITER_LOCKS",
+ "ARDUINO_ARCH_ESP32",
+ "ESP32",
+ "F_CPU=240000000L",
+ "ARDUINO=10812",
+ "ARDUINO_VARIANT=\"esp32s3\"",
+ "ARDUINO_BOARD=\"Espressif ESP32-S3-DevKitC-1-N8 (8 MB QD, No PSRAM)\"",
+ "ARDUINO_PARTITION_partitions"
+ ],
+ "hardening": {
+ "extra_cxx_flags": [
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "symbols_stripped": true,
+ "strings_encrypted": true
+ }
+} \ No newline at end of file
diff --git a/lib/HexaPower/lib/xtensa-esp32s3/libHexaPower_static.a b/lib/HexaPower/lib/xtensa-esp32s3/libHexaPower_static.a
new file mode 100644
index 0000000..1884764
--- /dev/null
+++ b/lib/HexaPower/lib/xtensa-esp32s3/libHexaPower_static.a
Binary files differ
diff --git a/lib/HexaPower/library.json b/lib/HexaPower/library.json
new file mode 100644
index 0000000..da3d5c2
--- /dev/null
+++ b/lib/HexaPower/library.json
@@ -0,0 +1,15 @@
+{
+ "name": "HexaPower",
+ "version": "1.0.0",
+ "description": "MCP3008 ADC battery-voltage and ACS712 current sensing for HEXA COMMAND HUB",
+ "keywords": ["mcp3008", "acs712", "adc", "current", "voltage", "battery", "esp32", "hexa"],
+ "authors": [
+ {
+ "name": "Rush",
+ "maintainer": true
+ }
+ ],
+ "license": "MIT",
+ "platforms": "espressif32",
+ "frameworks": "arduino"
+}
diff --git a/lib/HexaPower/src/HexaPower.h b/lib/HexaPower/src/HexaPower.h
new file mode 100644
index 0000000..9a2d5d1
--- /dev/null
+++ b/lib/HexaPower/src/HexaPower.h
@@ -0,0 +1,171 @@
+/**
+ * HexaPower.h — Battery-voltage & current sensing for HEXA COMMAND HUB
+ *
+ * Wraps the onboard MCP3008 (8-channel, 10-bit SPI ADC) that feeds the
+ * battery voltage sensor and two ACS712 Hall-effect current sensors. Gives
+ * the same "declare an object, call its methods" idiom used by HexaDCMotor/
+ * HexaServo/HexaOLED/HexaIMU.
+ *
+ * Board wiring (verified against the manufacturer Master Protocol
+ * HEXA-CH-VVR-001 §TC006–TC008 and the batch serial logs):
+ *
+ * MCP3008 channel map (as ACTUALLY wired — verified by the 3-phase PowerTest
+ * isolation, which differs from the manufacturer's rail labels):
+ * CH0 → battery voltage sensor (through a resistive divider)
+ * CH1 → ACS712 #1 — MAIN / total battery current (upstream: motor + servo)
+ * CH2 → ACS712 #2 — DC-motor branch current
+ * CH3..CH7 → external ADC breakout connectors (readRaw/readChannelVoltage)
+ * There is NO dedicated servo-rail sensor, so servo current is DERIVED as
+ * (main − motor) = CH1 − CH2. See getServoCurrent().
+ *
+ * SPI pins (dedicated bus, free on the robot board):
+ * CS=8 SCK=14 MISO=9 MOSI=13
+ *
+ * NOTE ON CALIBRATION: the MCP3008 reference (VREF) on this board is 5.0 V,
+ * not 3.3 V. The bring-up sketches that shipped with the prototype used 3.3 V
+ * and were explicitly flagged as "the WRONG protocol" — do not copy those
+ * constants. The defaults below come from the verified batch logs
+ * (CH0 941 counts → 11.35 V ⇒ scale ≈ 2.468). ACS712 sensitivity and the
+ * voltage divider still want a per-board recalibration against a multimeter.
+ *
+ * Part of: HexaPower library
+ * Author: Rush / HEXA Robotics
+ */
+
+#pragma once
+
+#include <Arduino.h>
+#include <SPI.h>
+
+
+// Data struct
+
+/** One snapshot from read(): the onboard rails. */
+struct HexaPowerData {
+ float batteryV; // battery pack voltage (V)
+ float mainA; // main/total battery current (A)
+ float motorA; // DC-motor rail current (A)
+ float servoA; // servo rail current (A)
+};
+
+
+/**
+ * Configuration for the MCP3008 power-sensing front end.
+ * Defaults match the robot board — most students never change these.
+ */
+struct HexaPowerConfig {
+ // SPI pins (robot board defaults)
+ int8_t csPin = 8;
+ int8_t sckPin = 14;
+ int8_t misoPin = 9;
+ int8_t mosiPin = 13;
+
+ // ADC reference (MCP3008 VREF). 5.0 V on this board — NOT 3.3 V.
+ float vref = 5.0f;
+
+ // Channel assignments (see the wiring note at the top of this file).
+ uint8_t vbattChannel = 0; // CH0 → voltage sensor
+ uint8_t mainCurrChannel = 1; // CH1 → ACS712 #1 (MAIN / total battery current)
+ uint8_t motorCurrChannel = 2; // CH2 → ACS712 #2 (DC-motor branch)
+ // No servoCurrChannel: servo current is derived as (main − motor).
+
+ // Battery divider scale: multiply the CH0 ADC voltage to get pack volts.
+ // Verified from batch log (941 counts → 11.35 V). Recalibrate per board.
+ float vbattScale = 2.468f;
+
+ // ACS712 sensitivity (V per Amp). ACS712-20A ≈ 0.100 V/A. The batch log
+ // implies ~0.088 V/A for the fitted part — RECALIBRATE against a DMM in
+ // series before trusting the amps reading.
+ float acsSensitivity = 0.100f;
+
+ // Exponential-moving-average factor for current smoothing (0..1, higher =
+ // snappier / noisier). Matches the prototype current sketch.
+ float emaAlpha = 0.25f;
+
+ // Low-battery warning threshold (V). Default sized for a 3S LiPo.
+ float lowBatteryV = 10.5f;
+
+ // SPI clock for the MCP3008 (1 MHz is comfortably within spec at 5 V).
+ uint32_t spiHz = 1000000;
+};
+
+
+class HexaPower {
+public:
+ /**
+ * Constructor — stores config, does NOT touch hardware.
+ * Call begin() in setup()/init() to initialize.
+ */
+ HexaPower() : HexaPower(HexaPowerConfig{}) {}
+ explicit HexaPower(const HexaPowerConfig& config);
+
+ /**
+ * Initialize the SPI bus and the MCP3008, then capture the ACS712
+ * zero-current offsets (a short averaged read — safe to call from an
+ * OpMode init(); it does NOT block for hundreds of milliseconds).
+ * Returns true (the MCP3008 has no ID register to probe).
+ */
+ bool begin();
+
+ /** True once begin() has run. */
+ bool isReady() const;
+
+ /**
+ * Re-capture the ACS712 zero-current offsets. Call with both the motor
+ * and servo rails idle. begin() already does this once.
+ */
+ void calibrateCurrentZero();
+
+
+ // Core Data Acquisition
+
+ /**
+ * Sample CH1/CH2 (and the battery divider) exactly ONCE, advance the EMA
+ * current filters from those single samples, and cache everything for
+ * the get*() functions below. Called once per tick by the framework
+ * (NRLRunner::tick()) — students never need to call this themselves.
+ * Returns false if begin() has not run.
+ */
+ bool read();
+
+ /** All cached rail readings as one struct. */
+ HexaPowerData getData() const;
+
+ // Pure cache reads — no SPI, no side effects. Safe to call any number of
+ // times per tick (e.g. once per motor/servo object) and always returns
+ // the same value for a given rail, because it IS the same rail: there is
+ // one ACS712 per branch, not one per motor/servo. Values refresh once per
+ // tick via read().
+ float getBatteryVoltage(); // battery pack voltage (V)
+ float getMainCurrent(); // MAIN/total battery current (A), CH1, EMA-smoothed
+ float getMotorCurrent(); // DC-motor branch current (A), CH2, EMA-smoothed
+ float getServoCurrent(); // servo current (A) = main − motor (CH1 − CH2), EMA-smoothed
+
+ /** True while the last-read battery voltage is below lowBatteryV. */
+ bool isBatteryLow() const;
+
+
+ // Generic MCP3008 access (also serves external ADC ports CH3..CH7)
+
+ /** Raw 10-bit reading (0..1023) for any channel 0..7. */
+ uint16_t readRaw(uint8_t channel);
+
+ /** Channel voltage at the ADC pin (0..vref), before any scaling. */
+ float readChannelVoltage(uint8_t channel);
+
+
+private:
+ HexaPowerConfig m_cfg;
+ SPIClass m_spi{HSPI};
+ HexaPowerData m_data = {};
+ bool m_ready = false;
+
+ float m_mainZeroV = 0.0f; // CH1 (main/total) ACS712 quiescent output (V)
+ float m_motorZeroV = 0.0f; // CH2 (motor branch) ACS712 quiescent output (V)
+ float m_mainEMA = 0.0f; // smoothed main/total current (A)
+ float m_motorEMA = 0.0f; // smoothed motor current (A)
+ float m_servoEMA = 0.0f; // smoothed servo current (A) = main − motor
+
+ // Raw (unsmoothed, zero-subtracted) amps for one ACS712 channel.
+ float rawAmps(uint8_t channel, float zeroV);
+};
diff --git a/lib/HexaServos/build-manifest.json b/lib/HexaServos/build-manifest.json
new file mode 100644
index 0000000..809b3a0
--- /dev/null
+++ b/lib/HexaServos/build-manifest.json
@@ -0,0 +1,72 @@
+{
+ "source_lib": "lib\\HexaServos",
+ "sdk_version": "1.4.1",
+ "built_from_commit": "036661d7fa9340e198bf3f6d376121ae8c214f59",
+ "built_at": "2026-10-10T14:36:47.795153Z",
+ "harvested_from_project": "RobotFirmware",
+ "harvested_env": "robot",
+ "cxx_path": "C:\\Users\\thein\\.platformio\\packages\\toolchain-xtensa-esp32s3\\bin\\xtensa-esp32s3-elf-g++.exe",
+ "cxx_flags": [
+ "-std=gnu++17",
+ "-fexceptions",
+ "-fno-rtti",
+ "-Os",
+ "-mlongcalls",
+ "-ffunction-sections",
+ "-fdata-sections",
+ "-Wno-error=unused-function",
+ "-Wno-error=unused-variable",
+ "-Wno-error=deprecated-declarations",
+ "-Wno-unused-parameter",
+ "-Wno-sign-compare",
+ "-ggdb",
+ "-freorder-blocks",
+ "-Wwrite-strings",
+ "-fstack-protector",
+ "-fstrict-volatile-bitfields",
+ "-Wno-error=unused-but-set-variable",
+ "-fno-jump-tables",
+ "-fno-tree-switch-conversion",
+ "-MMD",
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "defines": [
+ "PLATFORMIO=60200",
+ "ARDUINO_ESP32S3_DEV",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_RUNNING_CORE=1",
+ "ARDUINO_EVENT_RUNNING_CORE=1",
+ "CONFIG_FREERTOS_HZ=1000",
+ "CORE_DEBUG_LEVEL=3",
+ "ARDUINO_USB_MODE=1",
+ "ARDUINO_USB_CDC_ON_BOOT=1",
+ "HAVE_CONFIG_H",
+ "MBEDTLS_CONFIG_FILE=\"mbedtls/esp_config.h\"",
+ "UNITY_INCLUDE_CONFIG_H",
+ "WITH_POSIX",
+ "_GNU_SOURCE",
+ "IDF_VER=\"v4.4.7-dirty\"",
+ "ESP_PLATFORM",
+ "_POSIX_READER_WRITER_LOCKS",
+ "ARDUINO_ARCH_ESP32",
+ "ESP32",
+ "F_CPU=240000000L",
+ "ARDUINO=10812",
+ "ARDUINO_VARIANT=\"esp32s3\"",
+ "ARDUINO_BOARD=\"Espressif ESP32-S3-DevKitC-1-N8 (8 MB QD, No PSRAM)\"",
+ "ARDUINO_PARTITION_partitions"
+ ],
+ "hardening": {
+ "extra_cxx_flags": [
+ "-g0",
+ "-fno-rtti",
+ "-fno-exceptions",
+ "-fno-asynchronous-unwind-tables"
+ ],
+ "symbols_stripped": true,
+ "strings_encrypted": true
+ }
+} \ No newline at end of file
diff --git a/lib/HexaServos/keywords.txt b/lib/HexaServos/keywords.txt
new file mode 100644
index 0000000..9260f27
--- /dev/null
+++ b/lib/HexaServos/keywords.txt
@@ -0,0 +1,30 @@
+# ═══════════════════════════════════════════════
+# Syntax Highlighting for HexaServos Library
+# ═══════════════════════════════════════════════
+# KEYWORD1 = Classes (highlighted as types)
+# KEYWORD2 = Methods (highlighted as functions)
+# LITERAL1 = Constants
+
+# ── Classes ──
+HexaServo KEYWORD1
+HexaServoConfig KEYWORD1
+HexaDCMotor KEYWORD1
+HexaDCMotorConfig KEYWORD1
+
+# ── Servo Methods ──
+begin KEYWORD2
+setPosition KEYWORD2
+moveBy KEYWORD2
+getPosition KEYWORD2
+getMinAngle KEYWORD2
+getMaxAngle KEYWORD2
+isReady KEYWORD2
+detach KEYWORD2
+attach KEYWORD2
+writeMicroseconds KEYWORD2
+
+# ── Motor Methods ──
+setSpeed KEYWORD2
+getSpeed KEYWORD2
+stop KEYWORD2
+setFlipped KEYWORD2
diff --git a/lib/HexaServos/lib/xtensa-esp32s3/libHexaServos_static.a b/lib/HexaServos/lib/xtensa-esp32s3/libHexaServos_static.a
new file mode 100644
index 0000000..12ba0e1
--- /dev/null
+++ b/lib/HexaServos/lib/xtensa-esp32s3/libHexaServos_static.a
Binary files differ
diff --git a/lib/HexaServos/library.json b/lib/HexaServos/library.json
new file mode 100644
index 0000000..de9dc16
--- /dev/null
+++ b/lib/HexaServos/library.json
@@ -0,0 +1,15 @@
+{
+ "name": "HexaServos",
+ "version": "1.0.0",
+ "description": "Servo and DC motor driver for HEXA COMMAND HUB using ESP32-S3 LEDC peripheral",
+ "keywords": ["servo", "motor", "ledc", "pwm", "esp32", "hexa"],
+ "authors": [
+ {
+ "name": "Rush",
+ "maintainer": true
+ }
+ ],
+ "license": "MIT",
+ "platforms": "espressif32",
+ "frameworks": "arduino"
+}
diff --git a/lib/HexaServos/library.properties b/lib/HexaServos/library.properties
new file mode 100644
index 0000000..c5982a1
--- /dev/null
+++ b/lib/HexaServos/library.properties
@@ -0,0 +1,9 @@
+name=HexaServos
+version=1.0.0
+author=Rush
+maintainer=Rush
+sentence=Servo and DC motor driver for HEXA COMMAND HUB (ESP32-S3 LEDC)
+paragraph=Standalone servo and DC motor control using ESP32-S3 LEDC peripheral. Servos at 50Hz/16-bit, DC motors at 20kHz/8-bit. No external dependencies.
+category=Device Control
+url=
+architectures=esp32
diff --git a/lib/HexaServos/src/HexaDCMotor.h b/lib/HexaServos/src/HexaDCMotor.h
new file mode 100644
index 0000000..41cf274
--- /dev/null
+++ b/lib/HexaServos/src/HexaDCMotor.h
@@ -0,0 +1,130 @@
+/**
+ * HexaDCMotor.h — DC Motor Driver for HEXA COMMAND HUB
+ *
+ * Controls a brushed DC motor via DIR + PWM pins using ESP32 LEDC at 20kHz.
+ * Speed range: -255 (full reverse) to +255 (full forward), 0 = stopped.
+ * 20kHz is above human hearing so there's no audible whine at low speeds.
+ *
+ * PWM: 20kHz, 8-bit (0-255)
+ * Part of: HexaServos library
+ * Author: Rush / HEXA Robotics
+ */
+
+#pragma once
+
+#include <Arduino.h>
+
+
+/**
+ * Configuration struct for one DC motor channel.
+ * Example: HexaDCMotorConfig cfg = { .dirPin = 32, .pwmPin = 33 };
+ */
+struct HexaDCMotorConfig {
+ uint8_t dirPin; // GPIO pin for direction (HIGH = forward, LOW = reverse or coast)
+ uint8_t pwmPin; // GPIO pin for speed (LEDC PWM output)
+ bool flipped = false; // Set true to software-reverse this motor's direction.
+ // Useful when a motor is wired backwards on the frame —
+ // flip it here instead of rewiring.
+
+ // Stiction floor. 0 (default) = off, behaviour unchanged.
+ //
+ // Nonzero: a nonzero command has its MAGNITUDE remapped into [minDrive, 255],
+ // so a small command still makes the motor actually turn instead of just
+ // buzzing. Below the floor a geared DC motor draws current and produces no
+ // rotation, which a closed loop reads as "no response" and answers by
+ // winding the command up further.
+ //
+ // Opposite of MOTOR_DEADBAND, and the two coexist on purpose: the deadband
+ // is a noise gate that collapses near-zero commands TO zero; minDrive lifts
+ // the surviving commands UP to something the motor can act on.
+ //
+ // MEASURE it, do not tune it — it is a property of this motor and gearbox.
+ // Ramp the command up from 0 and note where the wheels first turn.
+ uint8_t minDrive = 0;
+};
+
+
+class HexaDCMotor {
+public:
+ /**
+ * Constructor — stores config, does NOT touch hardware.
+ * Call begin() in setup() to initialize.
+ */
+ HexaDCMotor(const HexaDCMotorConfig& config);
+
+ /**
+ * Initialize the motor driver. Call in setup(). Returns true on success.
+ */
+ bool begin();
+
+ /**
+ * Set motor speed. Range: -255 (full reverse) to +255 (full forward), 0 = coast stop.
+ * Values outside range are clamped. If flipped=true in config, directions are swapped.
+ */
+ void setSpeed(int speed);
+
+ /**
+ * Get the last commanded speed (-255 to +255).
+ */
+ int getSpeed() const;
+
+ /**
+ * Stop the motor (equivalent to setSpeed(0)).
+ */
+ void stop();
+
+ /**
+ * Reverse direction in software without rewiring.
+ * Takes effect immediately — reapplies current speed
+ * with the new direction.
+ */
+ void setFlipped(bool flipped);
+
+ /**
+ * Returns true if begin() has been called successfully.
+ */
+ bool isReady() const;
+
+ // NOTE: there is no per-motor getCurrent() here. The board has ONE ACS712
+ // sensor on the shared DC-motor rail — every motor would report the exact
+ // same total, which was a source of confusion (looked like each motor had
+ // its own reading, but it was one shared value sampled inconsistently).
+ // Read the actual rail current via `power.getMotorCurrent()` instead
+ // (see RobotFirmware/lib/HexaNRL/src/RobotConfig.h).
+
+ /**
+ * Stop every motor that has been initialised via begin().
+ * Called automatically by NRLRunner when an OpMode ends — students do not
+ * need to call this directly, but may call it from stop() if they wish.
+ */
+ static void stopAll();
+
+ /**
+ * Clear the internal motor registry.
+ * Called by NRLRunner after the OpMode is deleted so stale pointers
+ * from destroyed class-member motors don't linger between runs.
+ * Motors re-register automatically on the next begin() call.
+ */
+ static void clearRegistry();
+
+private:
+ HexaDCMotorConfig m_cfg;
+ int m_currentSpeed = 0;
+ bool m_ready = false;
+ bool m_registered = false; // true once registered in s_registry
+ uint8_t m_channel = 0; // LEDC channel (Core 2.x only; unused on Core 3.x)
+
+ // 20kHz is above human hearing — no motor whine at low PWM duty.
+ // 8-bit gives 256 speed steps (0-255), matching analogWrite() range.
+ static constexpr uint32_t MOTOR_FREQ_HZ = 20000;
+ static constexpr uint8_t MOTOR_RES_BITS = 8;
+ static constexpr int MAX_SPEED = 255;
+
+ // Deadband: commands within ±MOTOR_DEADBAND of zero are rounded to zero.
+ // Prevents rapid direction toggling (and the resulting stall/jitter) when
+ // the computed drive signal oscillates near zero — most common on the inner
+ // motor during tank-drive turns where (forward − turn) ≈ 0.
+ // Value is ~4 % of full scale; imperceptible to the driver but eliminates
+ // the 25 Hz direction-flip that causes visible motor stall.
+ static constexpr int MOTOR_DEADBAND = 10;
+};
diff --git a/lib/HexaServos/src/HexaServo.h b/lib/HexaServos/src/HexaServo.h
new file mode 100644
index 0000000..9ba109d
--- /dev/null
+++ b/lib/HexaServos/src/HexaServo.h
@@ -0,0 +1,186 @@
+/**
+ * HexaServo.h — Servo Driver for HEXA COMMAND HUB
+ *
+ * Drives the RKI-1248 servo using the ESP32-S3 LEDC peripheral.
+ * Pulse range: 500µs=0°, 1500µs=90°, 2500µs=180°, period=20ms (50Hz).
+ * Uses LEDC (not analogWrite) for 14-bit resolution and independent channel control.
+ * At 14-bit / 50Hz: one tick ~1.22µs — well within the servo's 3µs dead band.
+ *
+ * Tuned for: RKI-1248 (500-2500µs, 180°, 50-330Hz)
+ * Part of: HexaServos library
+ * Author: Rush / HEXA Robotics
+ */
+
+#pragma once
+
+#include <Arduino.h>
+
+
+/**
+ * Configuration struct for a single servo.
+ * Struct keeps the constructor clean and lets you define named configs as constants.
+ */
+struct HexaServoConfig {
+
+ uint8_t signalPin; // ESP32-S3 GPIO pin routed through HEXA HUB
+ // to the servo's signal wire (typically orange/white)
+
+ // Pulse width range (from the RKI-1248 datasheet)
+ uint16_t minPulseUs = 500; // Pulse width in microseconds at 0°
+ uint16_t maxPulseUs = 2500; // Pulse width in microseconds at 180°
+
+ // Mechanical angle range
+ float minAngle = 0.0f; // Minimum angle in degrees
+ float maxAngle = 180.0f; // Maximum angle in degrees
+
+ // Calibration offset
+ // If your servo's "0°" position is physically off by a few
+ // degrees (e.g., the horn isn't perfectly aligned), you can
+ // compensate here instead of hacking your application code.
+ // A positive offset shifts the output clockwise.
+ float offsetDeg = 0.0f;
+
+ // Initial position
+ // Where the servo moves to when begin() is called.
+ // Default is center (90°). Set to your preferred safe position.
+ float startAngle = 90.0f;
+
+ // Auto-settle: detach LEDC after this many ms of no setPosition() calls.
+ // 0 = DISABLED (default) — the servo keeps its 50Hz signal and HOLDS its
+ // commanded angle, including the INIT pose, instead of going limp/drooping.
+ // Holding is the right default: a servo that goes limp drops whatever the
+ // arm was carrying.
+ //
+ // ABOUT THIS BOARD: the servos share the battery rail. There is NO BEC and
+ // no separate servo regulator. A held servo can therefore buzz audibly on
+ // battery power alone. That buzz is the rail, not a firmware fault, and the
+ // commanded angle is still correct.
+ //
+ // Set to a positive value (e.g. 300) to trade holding for silence: the
+ // servo detaches once idle, stops buzzing, and goes limp until the next
+ // setPosition().
+ uint32_t settleMs = 0;
+};
+
+
+class HexaServo {
+public:
+ /**
+ * Constructor — stores config, does NOT touch hardware.
+ * Global objects are constructed before hardware is ready, so all
+ * hardware init is deferred to begin(). Call begin() in setup().
+ */
+ HexaServo(const HexaServoConfig& config);
+
+ /**
+ * Initialize the hardware. Call in setup().
+ * Sets up the LEDC channel and moves servo to start position.
+ * Returns true on success.
+ */
+ bool begin();
+
+ // Servo control
+
+ void setPosition(float angleDeg); // Move to an absolute angle (0–180°)
+ void moveBy(float deltaDeg); // Move relative to current angle
+ float getPosition() const; // Read back the current angle
+ float getMinAngle() const;
+ float getMaxAngle() const;
+ bool isReady() const;
+
+ // NOTE: there is no per-servo getCurrent() here. The board has no dedicated
+ // servo-current sensor — this value is DERIVED as (main total − motor
+ // branch) = CH1 − CH2 on the MCP3008, so it's the TOTAL current drawn by
+ // all servos together, not any individual servo's current. Every HexaServo
+ // would report the exact same value, which was a source of confusion. Read
+ // the actual rail current via `power.getServoCurrent()` instead
+ // (see RobotFirmware/lib/HexaNRL/src/RobotConfig.h).
+
+ // Ramp rate: limit how fast the servo output moves (degrees per second).
+ // Default 0 = instant (no ramp). Set e.g. 90.0f to limit to 90°/s.
+ // Must be called before the first setPosition() to take effect from the start.
+ void setRampRate(float degsPerSec);
+
+ // Advanced / power management
+
+ /**
+ * Detach the LEDC channel from the pin.
+ * After detaching, the servo receives no signal and will
+ * go limp (no holding torque). Useful for saving power or
+ * when you want the servo to be manually movable.
+ */
+ void detach();
+
+ /**
+ * Re-attach after a detach(). Moves to the last known angle.
+ */
+ void attach();
+
+ /**
+ * Write a raw pulse width in microseconds.
+ * For advanced use — bypasses the angle-to-pulse mapping.
+ * Use this if you need to fine-tune beyond what angles give you.
+ */
+ void writeMicroseconds(uint16_t pulseUs);
+
+ /**
+ * Call every loop iteration — handles auto-detach after settleMs of idle.
+ * Called automatically by NRLRunner via tickAll(); student code does not need this.
+ */
+ void tick(uint32_t nowMs);
+
+ /**
+ * Tick all registered servos. Called by NRLRunner after loop().
+ */
+ static void tickAll(uint32_t nowMs);
+
+ /**
+ * Clear the servo registry. Called by NRLRunner after the OpMode is deleted
+ * so stale pointers from destroyed servos don't linger between runs.
+ * Servos re-register on the next begin() call.
+ */
+ static void clearRegistry();
+
+ /**
+ * Detach every registered servo (release LEDC + drive pin LOW so it goes limp).
+ * Called by NRLRunner on OpMode stop so servos don't keep emitting PWM after exit.
+ */
+ static void detachAll();
+
+private:
+ HexaServoConfig m_config; // Stored configuration (immutable after construction)
+ float m_currentAngle; // Last written angle in degrees (tracks hardware output)
+ bool m_ready; // Has begin() been called successfully?
+ bool m_attached; // Is the LEDC channel currently active?
+ uint8_t m_channel; // LEDC channel (Core 2.x only; unused on Core 3.x)
+ float m_degsPerSec; // Ramp rate limit; 0 = instant
+ uint32_t m_lastTickMs; // millis() at last setPosition() call (for ramp dt)
+ uint32_t m_lastWriteMs; // millis() at last setPosition() call (for auto-settle)
+ bool m_registered; // true once registered in s_registry
+
+ static HexaServo* s_registry[8];
+ static uint8_t s_count;
+
+ // Internal helpers
+ // Converts an angle in degrees to a pulse width in microseconds,
+ // applying the calibration offset. This is the core math of
+ // the entire driver.
+ uint16_t angleToPulseUs(float angleDeg) const;
+
+ // Converts a pulse width in microseconds to an LEDC duty value
+ // (the raw number we write to the hardware register).
+ uint32_t pulseUsToDuty(uint16_t pulseUs) const;
+
+ // Reverse mapping: pulse width back to angle (for writeMicroseconds)
+ float pulseUsToAngle(uint16_t pulseUs) const;
+
+ // Constants
+ static constexpr uint32_t SERVO_FREQ_HZ = 50; // 50Hz = standard servo frequency
+ static constexpr uint8_t SERVO_RESOLUTION = 14; // 14-bit = max for ESP32-S3 (16384 steps)
+ static constexpr uint32_t CYCLE_US = 20000; // 1/50Hz = 20ms = 20000µs
+ static constexpr uint32_t MAX_DUTY = 16384; // 2^14
+ static constexpr uint32_t HEARTBEAT_MS = 250; // held-servo duty re-assert interval (see tick())
+
+ // 14-bit: SOC_LEDC_TIMER_BIT_WIDTH on ESP32-S3 is 14 — 16-bit causes ledcAttach() to fail.
+ // At 14-bit / 50Hz each tick ~1.22µs, still well within the RKI-1248's 3µs dead band.
+};
diff --git a/nrl-project.json b/nrl-project.json
new file mode 100644
index 0000000..3642a70
--- /dev/null
+++ b/nrl-project.json
@@ -0,0 +1,7 @@
+{
+ "name": "Suncity 54 team 1",
+ "teamNumber": 205,
+ "teamName": "Pixel Pokers",
+ "channel": 1,
+ "createdYear": 2026
+}
diff --git a/tools/ensure-python.ps1 b/tools/ensure-python.ps1
new file mode 100644
index 0000000..7d97666
--- /dev/null
+++ b/tools/ensure-python.ps1
@@ -0,0 +1,208 @@
+<#
+=====================================================================
+ ensure-python.ps1 - Detect a usable Python 3, installing one if
+ none is found, then print its path/command on stdout.
+
+ Used by the Windows launcher (new-nrl-project.bat).
+ A brand-new student who has never installed Python can double-click the
+ launcher and have it "just work": this script installs Python 3 via
+ winget (built into Win10/11) and falls back to the official python.org
+ silent installer on older Windows.
+
+ Contract:
+ - stdout : exactly ONE line, the interpreter to run (e.g. a full path
+ to python.exe, or "py" when the launcher is on PATH).
+ - stderr : all human-readable progress / status / error text.
+ - exit 0 : interpreter found/installed; its path is on stdout.
+ - exit 1 : no interpreter could be found or installed.
+=====================================================================
+#>
+$ErrorActionPreference = 'Stop'
+
+# Anything we want the user to read goes to stderr so stdout stays clean
+# for the single interpreter path the .bat captures.
+function Say([string]$msg) { [Console]::Error.WriteLine($msg) }
+
+# Emit the chosen interpreter on stdout and exit success.
+function Emit([string]$exe) {
+ Write-Output $exe
+ exit 0
+}
+
+# Resolve a candidate to its real python.exe IFF it is a Python 3 that ALSO
+# has tkinter -- the wizard's folder picker needs it. Prints the resolved
+# path, or $null when the candidate is missing / not Python 3 / has no tkinter.
+function Resolve-Usable([string]$exe, [string[]]$prefix) {
+ # Probe inside a job with a timeout. A Microsoft Store "python.exe" alias
+ # stub (present by default when no real Python is installed) HANGS when
+ # invoked -- it tries to open the Store -- so a plain call could freeze the
+ # launcher. An installed interpreter prints its path in well under a second;
+ # anything that hasn't answered in time is treated as unusable.
+ $job = $null
+ try {
+ $job = Start-Job -ScriptBlock {
+ param($e, $p)
+ $o = & $e @p -c "import sys, tkinter; print(sys.executable)" 2>$null
+ if ($LASTEXITCODE -eq 0) { $o }
+ } -ArgumentList $exe, $prefix
+ if (Wait-Job $job -Timeout 30) {
+ $out = Receive-Job $job
+ if ($out) {
+ return ([string]($out | Where-Object { $_ } | Select-Object -Last 1)).Trim()
+ }
+ } else {
+ Stop-Job $job -ErrorAction SilentlyContinue
+ }
+ } catch {
+ } finally {
+ if ($job) { Remove-Job $job -Force -ErrorAction SilentlyContinue }
+ }
+ return $null
+}
+
+# ----- 1) Detect an existing, USABLE interpreter ---------------------------
+# We require a "real" Python 3 WITH tkinter. PlatformIO's bundled Python is
+# deliberately NOT accepted here: it ships without tkinter, so the wizard's
+# folder picker would silently break. When only that exists we install a real
+# Python below instead.
+function Find-Python {
+ if (Get-Command py -ErrorAction SilentlyContinue) {
+ $p = Resolve-Usable 'py' @('-3'); if ($p) { return $p }
+ }
+ $python = Get-Command python -ErrorAction SilentlyContinue
+ if ($python) {
+ $p = Resolve-Usable $python.Source @(); if ($p) { return $p }
+ }
+ return $null
+}
+
+# Search the well-known per-user install locations for an interpreter that a
+# fresh install just dropped (PATH is NOT refreshed in this session). Each
+# candidate is validated with Resolve-Usable so we only return a tkinter-
+# capable Python 3.
+function Find-FreshlyInstalled {
+ $roots = @(
+ (Join-Path $env:LOCALAPPDATA 'Programs\Python'), # python.org / winget per-user
+ (Join-Path $env:LOCALAPPDATA 'Python'), # Windows Python Install Manager (pythoncore-*)
+ 'C:\Program Files\Python*',
+ 'C:\Python3*'
+ )
+ foreach ($root in $roots) {
+ $exes = Get-ChildItem -Path $root -Filter 'python.exe' -Recurse -ErrorAction SilentlyContinue |
+ Sort-Object FullName -Descending
+ foreach ($exe in $exes) {
+ $p = Resolve-Usable $exe.FullName @(); if ($p) { return $p }
+ }
+ }
+ return $null
+}
+
+# Discover the latest STABLE Python from python.org's release index, verifying
+# that the Windows amd64 installer actually exists for it (newest first). This
+# keeps us on the current release instead of a hard-coded, ageing version.
+# Returns @{ Version='3.14.6'; Minor='3.14'; Url='https://.../python-3.14.6-amd64.exe' } or $null.
+function Get-LatestPython {
+ try {
+ $ProgressPreference = 'SilentlyContinue'
+ $idx = Invoke-WebRequest -Uri 'https://www.python.org/ftp/python/' -UseBasicParsing -TimeoutSec 20
+ # Match only pure X.Y.Z folders -> pre-releases like 3.15.0a1/ are excluded.
+ $vers = [regex]::Matches($idx.Content, 'href="(\d+\.\d+\.\d+)/"') |
+ ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique |
+ Sort-Object { [version]$_ } -Descending
+ foreach ($v in ($vers | Select-Object -First 12)) {
+ $url = "https://www.python.org/ftp/python/$v/python-$v-amd64.exe"
+ try {
+ $h = Invoke-WebRequest -Uri $url -Method Head -UseBasicParsing -TimeoutSec 15
+ if ($h.StatusCode -eq 200) {
+ return @{ Version = $v; Minor = (($v -split '\.')[0..1] -join '.'); Url = $url }
+ }
+ } catch {} # no binary installer for this version (e.g. security-only) -> try next
+ }
+ } catch {}
+ return $null
+}
+
+$found = Find-Python
+if ($found) { Emit $found }
+
+# ----- 2) No usable Python found: install one ------------------------------
+# (Reached when there is no Python at all, OR only PlatformIO's bundled Python,
+# which lacks the tkinter the wizard's folder picker needs.)
+Say ''
+Say '[setup] No usable Python 3 (with tkinter) was found on this PC.'
+Say '[setup] Installing Python 3 automatically (one-time, ~1-2 min)...'
+Say ''
+
+$installed = $false
+
+# Discover the LATEST stable Python from python.org's release listing, so we
+# don't pin to an ageing version. Returns @{Version; Minor; Url} or $null.
+$latest = Get-LatestPython
+if ($latest) { Say "[setup] Latest stable Python is $($latest.Version)." }
+
+# a) Preferred: winget (built into Windows 10 1709+/11, no admin needed).
+# Target the latest minor line (e.g. Python.Python.3.14) so we don't pin
+# to an old one; fall back to a recent id if discovery failed.
+$winget = Get-Command winget -ErrorAction SilentlyContinue
+if ($winget) {
+ $wingetId = if ($latest) { "Python.Python.$($latest.Minor)" } else { 'Python.Python.3.13' }
+ Say "[setup] Using winget to install $wingetId ..."
+ try {
+ # Route winget's chatter to stderr so stdout stays a clean interpreter path.
+ & winget install -e --id $wingetId --scope user `
+ --accept-source-agreements --accept-package-agreements 2>&1 |
+ ForEach-Object { Say ([string]$_) }
+ if ($LASTEXITCODE -eq 0) { $installed = $true }
+ else { Say "[setup] winget exited with code $LASTEXITCODE; trying the python.org installer..." }
+ } catch {
+ Say "[setup] winget failed ($($_.Exception.Message)); trying the python.org installer..."
+ }
+}
+
+# b) Fallback: download the official python.org installer (latest) silently.
+if (-not $installed) {
+ $ver = if ($latest) { $latest.Version } else { '3.13.1' }
+ $url = if ($latest) { $latest.Url } else { "https://www.python.org/ftp/python/$ver/python-$ver-amd64.exe" }
+ $dest = Join-Path $env:TEMP "python-$ver-amd64.exe"
+ Say "[setup] Downloading the official Python $ver installer..."
+ try {
+ $ProgressPreference = 'SilentlyContinue'
+ Invoke-WebRequest -Uri $url -OutFile $dest -UseBasicParsing
+ Say '[setup] Running the installer silently (per-user)...'
+ $p = Start-Process -FilePath $dest -Wait -PassThru -ArgumentList `
+ '/quiet','InstallAllUsers=0','PrependPath=1','Include_launcher=1'
+ if ($p.ExitCode -eq 0) { $installed = $true }
+ else { Say "[setup] Installer exited with code $($p.ExitCode)." }
+ } catch {
+ Say "[setup] Could not download/run the python.org installer: $($_.Exception.Message)"
+ }
+}
+
+if (-not $installed) {
+ Say ''
+ Say '[error] Automatic install of Python 3 failed.'
+ Say ' Please install Python 3 from https://www.python.org/downloads/'
+ Say ' and tick "Add python.exe to PATH" during setup, then re-run.'
+ exit 1
+}
+
+# ----- 3) Re-resolve the just-installed interpreter (PATH not refreshed) ----
+$fresh = Find-FreshlyInstalled
+if (-not $fresh) {
+ # winget may have updated this process's environment block; try detection again.
+ $fresh = Find-Python
+}
+if ($fresh) {
+ Say '[setup] Python 3 installed successfully.'
+ # The installer adds Python to PATH, but already-open terminals (and new tabs
+ # of an existing one) keep the OLD PATH. Tell the user so `python` "not found"
+ # in a stale window isn't mistaken for a failed install. The wizard itself
+ # runs fine right now -- it uses the full path below, not PATH.
+ Say "[setup] To use the 'python' command yourself, open a NEW terminal window."
+ Emit $fresh
+}
+
+Say ''
+Say '[error] Python 3 was installed but could not be located automatically.'
+Say ' Please close this window and re-run -- it should be found now.'
+exit 1
diff --git a/tools/ensure-python.sh b/tools/ensure-python.sh
new file mode 100644
index 0000000..0d69ffe
--- /dev/null
+++ b/tools/ensure-python.sh
@@ -0,0 +1,173 @@
+#!/usr/bin/env bash
+# ===================================================================
+# ensure-python.sh - Detect a usable Python 3, installing one if
+# none is found, then print its path on stdout.
+#
+# Used by the Unix launcher (new-nrl-project.sh).
+# A brand-new student on macOS can double-click the .command launcher
+# and have it "just work": this script installs Python 3 via Homebrew
+# (if present) or the official python.org universal2 .pkg.
+#
+# Contract:
+# - stdout : exactly ONE line, the interpreter to run.
+# - stderr : all human-readable progress / status / error text.
+# - exit 0 : interpreter found/installed; its path is on stdout.
+# - exit 1 : no interpreter could be found or installed.
+# ===================================================================
+set -euo pipefail
+
+# Human-readable text goes to stderr so stdout stays a clean interpreter path.
+say() { printf '%s\n' "$*" >&2; }
+
+# Resolve a candidate to its real interpreter path IFF it is a Python 3 that
+# ALSO has tkinter (the wizard's folder picker needs it). Echoes the path, or
+# nothing (non-zero) when the candidate is missing / not Python 3 / no tkinter.
+#
+# Probed UNDER A TIMEOUT: on macOS, invoking python3 without the Xcode Command
+# Line Tools pops a GUI dialog and BLOCKS (the Windows Store-stub equivalent),
+# so a hanging probe could freeze the launcher. macOS ships no coreutils
+# `timeout`, so we background the probe (its stdout redirected straight to a
+# temp file) and poll it, killing anything that hasn't answered in 20s.
+resolve_usable() {
+ local exe="$1"; shift
+ local tmp out pid i=0
+ tmp="$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/nrl-ensurepy.$$")"
+ "$exe" "$@" -c 'import sys, tkinter; print(sys.executable)' >"$tmp" 2>/dev/null &
+ pid=$!
+ while kill -0 "$pid" 2>/dev/null; do
+ if [ "$i" -ge 20 ]; then
+ kill -TERM "$pid" 2>/dev/null || true
+ sleep 1
+ kill -KILL "$pid" 2>/dev/null || true
+ wait "$pid" 2>/dev/null || true
+ rm -f "$tmp"
+ return 1
+ fi
+ sleep 1
+ i=$((i + 1))
+ done
+ if wait "$pid"; then
+ out="$(tail -n1 "$tmp" 2>/dev/null || true)"
+ rm -f "$tmp"
+ [ -n "$out" ] && { printf '%s\n' "$out"; return 0; }
+ fi
+ rm -f "$tmp"
+ return 1
+}
+
+# Detect a "real" Python 3 WITH tkinter: python3 -> py -3. PlatformIO's bundled
+# Python is deliberately NOT accepted -- it lacks tkinter, so the folder picker
+# would break; when only that exists we install a real Python instead.
+find_python() {
+ if command -v python3 >/dev/null 2>&1; then
+ if p="$(resolve_usable python3)"; then printf '%s\n' "$p"; return 0; fi
+ fi
+ if command -v py >/dev/null 2>&1; then
+ if p="$(resolve_usable py -3)"; then printf '%s\n' "$p"; return 0; fi
+ fi
+ return 1
+}
+
+if pyexe="$(find_python)"; then
+ printf '%s\n' "$pyexe"
+ exit 0
+fi
+
+# Discover the latest STABLE Python from python.org whose macOS installer .pkg
+# actually exists (newest first), so we don't pin to an ageing version. Echoes
+# X.Y.Z, or nothing on failure (the caller then uses a hard-coded fallback).
+get_latest_python() {
+ local listing v
+ listing="$(curl -fsSL https://www.python.org/ftp/python/ 2>/dev/null || true)"
+ [ -z "$listing" ] && return 1
+ # X.Y.Z folders only, newest first; pre-releases (3.15.0a1) lack this exact shape.
+ for v in $(printf '%s\n' "$listing" \
+ | grep -oE 'href="[0-9]+\.[0-9]+\.[0-9]+/"' \
+ | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' \
+ | sort -t. -k1,1nr -k2,2nr -k3,3nr -u | head -n 12); do
+ if curl -fsI "https://www.python.org/ftp/python/${v}/python-${v}-macos11.pkg" >/dev/null 2>&1; then
+ printf '%s\n' "$v"; return 0
+ fi
+ done
+ return 1
+}
+
+# ----- No usable Python found: install one --------------------------------
+# (No Python at all, OR only PlatformIO's bundled Python without tkinter.)
+say ''
+say '[setup] No usable Python 3 (with tkinter) was found on this Mac.'
+
+uname_s="$(uname -s 2>/dev/null || echo unknown)"
+if [ "$uname_s" != "Darwin" ]; then
+ # Linux / other: keep the previous behavior (don't silently apt/dnf-install).
+ say '[error] Python 3 not found. Please install Python 3 and re-run.'
+ exit 1
+fi
+
+say '[setup] Installing Python 3 automatically (one-time)...'
+say ''
+installed=0
+
+# a) Preferred: Homebrew, if the student already has it. Install python-tk too
+# so tkinter (the folder picker) is present; then verify before accepting.
+if command -v brew >/dev/null 2>&1; then
+ say '[setup] Using Homebrew to install Python 3 (with tkinter) ...'
+ # >&2 so brew's progress doesn't pollute our single-line stdout contract.
+ if brew install python python-tk >&2; then
+ hash -r 2>/dev/null || true
+ if find_python >/dev/null 2>&1; then
+ installed=1
+ else
+ say '[setup] Homebrew Python lacks tkinter; falling back to the python.org installer...'
+ fi
+ fi
+fi
+
+# b) Fallback: the official python.org universal2 installer package (bundles tkinter).
+if [ "$installed" -ne 1 ]; then
+ ver="$(get_latest_python || true)"
+ [ -z "$ver" ] && ver='3.13.1' # last-resort fallback if discovery fails
+ url="https://www.python.org/ftp/python/${ver}/python-${ver}-macos11.pkg"
+ pkg="${TMPDIR:-/tmp}/python-${ver}-macos11.pkg"
+ say "[setup] Downloading the official Python ${ver} installer..."
+ if curl -fL -o "$pkg" "$url"; then
+ say '[setup] Installing (you may be asked for your Mac password)...'
+ # >&2 so `installer` chatter doesn't pollute our single-line stdout contract.
+ if sudo installer -pkg "$pkg" -target / >&2; then installed=1; fi
+ else
+ say '[setup] Could not download the python.org installer.'
+ fi
+fi
+
+if [ "$installed" -ne 1 ]; then
+ say ''
+ say '[error] Automatic install of Python 3 failed.'
+ say ' Please install Python 3 from https://www.python.org/downloads/ and re-run.'
+ exit 1
+fi
+
+# ----- Re-resolve the just-installed interpreter --------------------------
+# The python.org .pkg symlinks python3 into /usr/local/bin; brew into its prefix.
+hash -r 2>/dev/null || true
+if pyexe="$(find_python)"; then
+ say '[setup] Python 3 installed successfully.'
+ # Already-open terminals keep the OLD PATH, so `python3` may look "not found"
+ # there even though the install worked. The wizard runs fine now (full path).
+ say "[setup] To use the 'python3' command yourself, open a NEW terminal window."
+ printf '%s\n' "$pyexe"
+ exit 0
+fi
+for cand in /usr/local/bin/python3 /opt/homebrew/bin/python3 \
+ /Library/Frameworks/Python.framework/Versions/Current/bin/python3; do
+ if [ -x "$cand" ] && p="$(resolve_usable "$cand")"; then
+ say '[setup] Python 3 installed successfully.'
+ say "[setup] To use the 'python3' command yourself, open a NEW terminal window."
+ printf '%s\n' "$p"
+ exit 0
+ fi
+done
+
+say ''
+say '[error] Python 3 was installed but could not be located automatically.'
+say ' Please close this window and re-run -- it should be found now.'
+exit 1
diff --git a/tools/new-nrl-opmode.bat b/tools/new-nrl-opmode.bat
new file mode 100755
index 0000000..c2f37ce
--- /dev/null
+++ b/tools/new-nrl-opmode.bat
@@ -0,0 +1,29 @@
+@echo off
+rem ===================================================================
+rem NRL - Create a New OpMode (double-click launcher, Windows)
+rem Scaffolds a robot OpMode from a minimal template, then opens it.
+rem ===================================================================
+setlocal
+title NRL - Create a New OpMode
+
+rem This .bat lives in <repo>\tools\ ; the generator sits next to it.
+set "SCRIPT=%~dp0nrl_new_opmode.py"
+
+rem Find a usable Python 3 (real py/python); if none is found, ensure-python.ps1
+rem installs one automatically and prints its path.
+set "PYEXE="
+for /f "usebackq delims=" %%i in (`powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0ensure-python.ps1"`) do set "PYEXE=%%i"
+if not defined PYEXE goto no_python
+"%PYEXE%" "%SCRIPT%" --open %*
+goto end
+
+:no_python
+echo.
+echo [error] Python 3 was not found and could not be installed automatically.
+echo Install Python 3 from https://www.python.org/downloads/ and re-run,
+echo ticking "Add python.exe to PATH" during setup.
+
+:end
+echo.
+if not defined NRL_NO_PAUSE pause
+endlocal
diff --git a/tools/new-nrl-opmode.sh b/tools/new-nrl-opmode.sh
new file mode 100644
index 0000000..6fb5400
--- /dev/null
+++ b/tools/new-nrl-opmode.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# ===================================================================
+# NRL - Create a New OpMode (launcher, macOS / Linux)
+# Scaffolds a robot OpMode from a minimal template, then opens it.
+# Usage: bash tools/new-nrl-opmode.sh (or chmod +x and run it)
+# ===================================================================
+set -euo pipefail
+
+here="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
+script="$here/nrl_new_opmode.py"
+
+# Find a usable Python 3; if none is found, ensure-python.sh installs one
+# automatically and prints its path.
+pyexe="$(bash "$here/ensure-python.sh")" || {
+ echo "[error] Python 3 was not found and could not be installed automatically." >&2
+ echo " Install Python 3 from https://www.python.org/downloads/ and re-run." >&2
+ exit 1
+}
+exec "$pyexe" "$script" --open "$@"
diff --git a/tools/nrl_new_opmode.py b/tools/nrl_new_opmode.py
new file mode 100644
index 0000000..113fe54
--- /dev/null
+++ b/tools/nrl_new_opmode.py
@@ -0,0 +1,307 @@
+#!/usr/bin/env python3
+"""
+NRL — Create a New OpMode
+=========================
+
+Scaffolds a fresh robot OpMode from a minimal template so a student never
+starts from a blank file. Writes <Name>.cpp into RobotFirmware/opmodes/ with
+empty init()/loop()/stop() overrides and the REGISTER_OPMODE line already
+filled in (that line is what makes the OpMode show up on the Controller menu).
+
+This is the "guided new file" companion to the in-editor snippets
+(type `nrlteleop` / `nrlauto` + Tab inside any opmodes/*.cpp).
+
+Run it
+------
+Interactive (recommended): py -3 tools/nrl_new_opmode.py
+Or via VS Code: Ctrl+Shift+P -> Tasks: Run Task -> "NRL: New OpMode"
+Non-interactive: py -3 tools/nrl_new_opmode.py --name Drive --type teleop --yes
+
+Requires Python 3.7+ (stdlib only). PlatformIO already ships a Python.
+"""
+
+import argparse
+import os
+import re
+import shutil
+import sys
+from pathlib import Path
+
+WORKSPACE_FILE = "NRL_Update_1.code-workspace"
+
+# A valid C++ identifier (also used as the file name). Must start with a
+# letter, then letters/digits/underscores — no spaces or punctuation.
+_IDENT_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
+
+
+# --------------------------------------------------------------------------- #
+# Validation / prompting
+# --------------------------------------------------------------------------- #
+def valid_opmode_name(name: str):
+ """Return (ok, message). Must be a legal C++ class/file identifier."""
+ name = name.strip()
+ if not name:
+ return False, "OpMode name cannot be empty."
+ if not _IDENT_RE.match(name):
+ return False, ("OpMode name must start with a letter and contain only "
+ "letters, numbers, or underscores (no spaces).")
+ if len(name) > 40:
+ return False, "OpMode name must be 40 characters or fewer."
+ return True, ""
+
+
+def valid_type(value: str):
+ """Return (ok, normalized, message). Accepts teleop/auto (any case)."""
+ v = str(value).strip().lower()
+ if v in ("teleop", "tele", "t"):
+ return True, "TELEOP", ""
+ if v in ("auto", "a"):
+ return True, "AUTO", ""
+ return False, "", "Type must be 'teleop' or 'auto'."
+
+
+def _interactive() -> bool:
+ return sys.stdin is not None and sys.stdin.isatty()
+
+
+def ask(prompt: str, default: str = None, validate=None) -> str:
+ """Prompt until a valid answer is given. `validate` returns (ok, ..., message)."""
+ suffix = f" [{default}]" if default not in (None, "") else ""
+ while True:
+ try:
+ raw = input(f"{prompt}{suffix}: ").strip()
+ except (EOFError, KeyboardInterrupt):
+ print("\nCancelled.")
+ sys.exit(1)
+ if not raw and default is not None:
+ raw = default
+ if validate is not None:
+ result = validate(raw)
+ ok, message = (result[0], result[-1]) if isinstance(result, tuple) else (bool(result), "")
+ if not ok:
+ print(f" ! {message}")
+ continue
+ elif not raw:
+ print(" ! A value is required.")
+ continue
+ return raw
+
+
+# --------------------------------------------------------------------------- #
+# Template
+# --------------------------------------------------------------------------- #
+def render_opmode(name: str, optype: str, display: str) -> str:
+ """Minimal skeleton — empty init/loop/stop + REGISTER_OPMODE. Mirrors the
+ nrlteleop/nrlauto editor snippets so both paths produce the same shape."""
+ if optype == "AUTO":
+ loop_comment = "// Runs at 100 Hz for ~60 s — telemetry and sensor reads go here."
+ # AUTO routines belong in start(), not loop(): queued there they run
+ # exactly once instead of restarting 100 times a second.
+ start_block = (
+ " void start() override {\n"
+ " // Runs once when the match starts — queue your routine\n"
+ " // with runAction(...) here.\n"
+ " }\n\n"
+ )
+ else:
+ # The ownership rule belongs here, not only in NRLOpMode.h: the clash it
+ # prevents (loop() silently overwriting an action) only shows up in
+ # TELEOP, where loop() drives hardware every tick.
+ loop_comment = (
+ "// Runs at 100 Hz until STOP — read gamepad1, drive motors here.\n"
+ " //\n"
+ " // Control each part in ONE place: loop() or an action, not\n"
+ " // both. Actions run before loop() each tick, so loop() would\n"
+ " // overwrite them. To share one part, step aside while a\n"
+ " // sequence plays: if (!isActionRunning()) { ... }"
+ )
+ start_block = ""
+ return f"""#include "NRL.h"
+
+// Declare your hardware here (file-scope), e.g.:
+// static HexaDCMotor leftMotor {{{{ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM }}}};
+
+class {name} : public NRLOpMode {{
+public:
+ void init() override {{
+ // Runs once when INIT is pressed — begin() your hardware here.
+ }}
+
+{start_block} void loop() override {{
+ {loop_comment}
+ }}
+
+ void stop() override {{
+ // Runs once on STOP — stop your motors/servos here.
+ }}
+}};
+
+REGISTER_OPMODE({name}, "{display}", {optype});
+"""
+
+
+# --------------------------------------------------------------------------- #
+# VS Code open (mirrors nrl_new_project.find_vscode)
+# --------------------------------------------------------------------------- #
+def find_vscode() -> str:
+ """Locate the real VS Code CLI, preferring a genuine VS Code install over
+ look-alikes (Cursor, VSCodium). Override with the NRL_VSCODE env var."""
+ candidates = []
+ override = os.environ.get("NRL_VSCODE")
+ if override:
+ candidates.append(override)
+
+ if sys.platform == "win32":
+ for base in (os.environ.get("LOCALAPPDATA", ""),
+ os.environ.get("ProgramFiles", ""),
+ os.environ.get("ProgramFiles(x86)", "")):
+ if base:
+ candidates.append(os.path.join(base, "Programs", "Microsoft VS Code", "bin", "code.cmd"))
+ candidates.append(os.path.join(base, "Microsoft VS Code", "bin", "code.cmd"))
+ elif sys.platform == "darwin":
+ candidates += [
+ "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code",
+ os.path.expanduser("~/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"),
+ ]
+ else:
+ candidates += ["/usr/bin/code", "/usr/local/bin/code",
+ "/usr/share/code/bin/code", "/snap/bin/code"]
+
+ for name in ("code", "code.cmd", "code.exe"):
+ found = shutil.which(name)
+ if found:
+ candidates.append(found)
+
+ for c in candidates:
+ if c and os.path.exists(c) and "cursor" not in c.lower():
+ return c
+ return ""
+
+
+def try_open_in_vscode(path: Path) -> bool:
+ """Open (and focus) the new file in VS Code, reusing the current window."""
+ import subprocess
+ code = find_vscode()
+ if not code:
+ return False
+ try:
+ if sys.platform == "win32":
+ subprocess.Popen(f'"{code}" -r "{path}"', shell=True)
+ else:
+ subprocess.Popen([code, "-r", str(path)])
+ return True
+ except OSError:
+ return False
+
+
+# --------------------------------------------------------------------------- #
+# Main
+# --------------------------------------------------------------------------- #
+def parse_args(argv):
+ p = argparse.ArgumentParser(
+ prog="nrl_new_opmode",
+ description="Create a new NRL robot OpMode from a minimal template.",
+ )
+ p.add_argument("--name", help="OpMode name (also the class and file name).")
+ p.add_argument("--type", help="OpMode type: teleop or auto.")
+ p.add_argument("--display", help="Name shown on the Controller (defaults to the OpMode name).")
+ p.add_argument("--open", action="store_true",
+ help="Open the new file in VS Code when done.")
+ p.add_argument("-y", "--yes", action="store_true",
+ help="Skip the confirmation prompt.")
+ return p.parse_args(argv)
+
+
+def resolve_repo_root() -> Path:
+ repo_root = Path(__file__).resolve().parent.parent
+ if not (repo_root / "RobotFirmware" / "opmodes").is_dir():
+ sys.exit(
+ f"[error] Can't find RobotFirmware/opmodes under {repo_root}. "
+ "Run this script from inside the NRL project (tools/nrl_new_opmode.py)."
+ )
+ return repo_root
+
+
+def main(argv=None):
+ args = parse_args(sys.argv[1:] if argv is None else argv)
+ repo_root = resolve_repo_root()
+ interactive = _interactive()
+ can_prompt = interactive and not args.yes
+
+ print("=" * 60)
+ print(" NRL · Create a New OpMode")
+ print("=" * 60)
+
+ # --- Name ---
+ if args.name is not None:
+ ok, msg = valid_opmode_name(args.name)
+ if not ok:
+ sys.exit(f"[error] {msg}")
+ name = args.name.strip()
+ elif can_prompt:
+ name = ask("OpMode name (e.g. DriveStraight)", validate=valid_opmode_name).strip()
+ else:
+ sys.exit("[error] --name is required (pass --name, or run in a terminal without --yes).")
+
+ # --- Type ---
+ if args.type is not None:
+ ok, optype, msg = valid_type(args.type)
+ if not ok:
+ sys.exit(f"[error] {msg}")
+ elif can_prompt:
+ optype = valid_type(ask("Type (teleop/auto)", default="teleop", validate=valid_type))[1]
+ else:
+ sys.exit("[error] --type is required (pass --type teleop|auto, or run without --yes).")
+
+ # --- Display name ---
+ if args.display is not None and args.display.strip():
+ display = args.display.strip()
+ elif can_prompt:
+ display = ask("Controller display name", default=name).strip()
+ else:
+ display = name
+ # Keep the display label clean for the firmware C-string literal.
+ display = display.replace('"', "'")
+
+ target = repo_root / "RobotFirmware" / "opmodes" / f"{name}.cpp"
+
+ # --- Summary ---
+ print("\n" + "-" * 60)
+ print(f" OpMode name : {name}")
+ print(f" Type : {optype}")
+ print(f" Display name : {display} (shown on the Controller)")
+ print(f" File : {target}")
+ print("-" * 60)
+
+ if target.exists():
+ sys.exit(f"[error] {target.name} already exists. Choose a different name "
+ "(or delete the old file first).")
+
+ if not args.yes:
+ if not interactive:
+ sys.exit("[error] Refusing to create without confirmation; pass --yes.")
+ if ask("Create this OpMode? (y/n)", default="y").strip().lower() not in ("y", "yes"):
+ print("Cancelled.")
+ return 1
+
+ # --- Write ---
+ try:
+ target.write_text(render_opmode(name, optype, display), encoding="utf-8")
+ except OSError as exc:
+ sys.exit(f"[error] Could not write {target}: {exc}")
+
+ print("\n[ done ] OpMode created.\n")
+ print("Next steps:")
+ print(f" 1. Edit {target}")
+ print(" 2. Click Build/Upload in PlatformIO to flash it to the robot")
+ print(f" 3. On the Controller, pick \"{display}\" from the menu\n")
+
+ if args.open and not try_open_in_vscode(target):
+ print(f"(VS Code not found — open {target} manually,")
+ print(" or set the NRL_VSCODE environment variable to your code.cmd path.)")
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())