diff options
| author | BEAST <macbook@Macbooks-MacBook-Pro-2.local> | 2026-11-17 09:40:39 +0530 |
|---|---|---|
| committer | BEAST <macbook@Macbooks-MacBook-Pro-2.local> | 2026-11-17 09:40:39 +0530 |
| commit | d358423b15bbd89ca8b34bb4ffc787811774105a (patch) | |
| tree | 5fa7233c0d5752d59e95c8070e28cd7d09b3170c | |
Add local files and custom README
77 files changed, 6466 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 Binary files differnew file mode 100644 index 0000000..4e35424 --- /dev/null +++ b/ControllerFirmware/prebuilt/controller_merged.bin 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 Binary files differnew file mode 100644 index 0000000..d3f8f1e --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/lib/xtensa-esp32s3/libHexaNRL_static.a 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..f57cae6 --- /dev/null +++ b/RobotFirmware/opmodes/drivemode.cpp @@ -0,0 +1,478 @@ +#include "NRL.h" +#include "team205_mech.h" +#include <Wire.h> +#include <math.h> + +// ============================================================ +// DriveMode — Tank Drive, IMU Auto-Level, Arm, Claw & Payload +// ============================================================ +// SERVO PORTS ON HEXA COMMAND HUB (Standard 3-pin plug, Red in middle): +// SERVO_1 (S1) -> ARM (45° = up, 115° = floor) +// SERVO_4 (S4) -> CLAW (30° = open, 95° = closed) +// SERVO_3 (S3) -> PAYLOAD GATE (0° = closed, 90° = open) +// +// Controls: +// - TRUE TANK DRIVE: +// * Left Stick Y = Left Wheels +// * Right Stick Y = Right Wheels +// - SPACESTATION AUTO-LEVEL (Onboard IMU): +// * BTN_X = Press once to START leveling, press X again to STOP +// - PRECISION TURN SHORTCUTS: +// * BTN_RB = Turn 140° at 90% speed +// * BTN_LB = Turn 50° at 80% speed +// - ARM (S1): +// * BTN_DPAD_UP = Arm UP +// * BTN_DPAD_DOWN = Arm DOWN + Automatically OPENS Claw (30°) +// - CLAW (S4): +// * BTN_DPAD_RIGHT = Claw OPEN (30°) +// * BTN_DPAD_LEFT = Claw CLOSE (95°) +// - PAYLOAD GATE (S3): +// * BTN_A = Press once to OPEN 90°, press A again to CLOSE 0° +// ============================================================ + +static HexaDCMotor leftMotor ({ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM, .flipped = true, .minDrive = 29 }); +static HexaDCMotor rightMotor({ .dirPin = MOTOR_R_DIR, .pwmPin = MOTOR_R_PWM, .flipped = false, .minDrive = 32 }); +static TankDrive drive(leftMotor, rightMotor); + +// Servo ports on the HEXA Command Hub +static constexpr uint8_t ARM_SIGNAL_PIN = SERVO_1; // S1 +static constexpr uint8_t CLAW_SIGNAL_PIN = SERVO_4; // S4 (J20) +static constexpr uint8_t PAYLOAD_SIGNAL_PIN = SERVO_3; // S3 (J17) + +// ---- IMU AUTO-LEVEL TUNING (Button X Toggle) ----------------------------- +// 1. If tilting the robot nose-up does NOT change "Tilt" on the screen, +// flip USE_Y_AXIS_FOR_PITCH from false to true. +// 2. If the robot drives DOWN the ramp instead of UP toward level, +// flip LEVEL_DRIVE_SIGN between 1.0f and -1.0f. +static constexpr bool USE_Y_AXIS_FOR_PITCH = false; +static constexpr float LEVEL_DRIVE_SIGN = 1.0f; +static constexpr float LEVEL_KP = 0.022f; // Proportional climb gain +static constexpr float LEVEL_KD = 0.008f; // Damping gain (stops see-saw bounce) +static constexpr float LEVEL_DEADBAND_DEG = 1.5f; // Stop motors within ±1.5° of flat +static constexpr float LEVEL_MIN_POWER = 0.16f; // Minimum power to overcome ramp friction +static constexpr float LEVEL_MAX_POWER = 0.48f; // Max power so robot won't overshoot ramp + +// ---- PRECISION TURN TUNING (RB = 140° @ 90%, LB = 50° @ 80%) -------------- +static constexpr float TURN_140_DIR = 1.0f; +static constexpr float TURN_140_SPEED = 0.90f; // 90% speed +static constexpr uint32_t TURN_140_MS = 380; // Duration for 140° + +static constexpr float TURN_50_DIR = -1.0f; +static constexpr float TURN_50_SPEED = 0.80f; // 80% speed +static constexpr uint32_t TURN_50_MS = 165; // Duration for 50° + +static constexpr uint32_t TURN_BRAKE_MS = 45; // Active reverse brake pulse + +// ---- ARM ANGLES (S1) ----------------------------------------------------- +static constexpr float ARM_UP_ANGLE = 45.0f; // Raised carry height +static constexpr float ARM_DOWN_ANGLE = 115.0f; // Lowered floor height +static constexpr float ARM_STEP_PER_TICK = 1.2f; // Smooth 120 deg/s travel + +// ---- CLAW ANGLES (S4 — Calibrated: 30° open, 95° fully closed) ----------- +static constexpr float CLAW_OPEN_ANGLE = 30.0f; // Fully open +static constexpr float CLAW_CLOSED_ANGLE = 95.0f; // Fully closed +static constexpr float CLAW_STEP_PER_TICK = 2.2f; // Crisp ~0.3s open/close + +// ---- PAYLOAD GATE (S3): 90° OPEN / CLOSE TOGGLE ON BUTTON A --------------- +static constexpr float PAYLOAD_CLOSED_ANGLE = 0.0f; // Closed position +static constexpr float PAYLOAD_OPEN_ANGLE = 90.0f; // +90° Open position +static constexpr float PAYLOAD_STEP_PER_TICK = 3.5f; // Crisp 90° toggle + +// ---- CARRY-MODE DRIVE PROTECTION ----------------------------------------- +static constexpr float CARRY_MAX_DRIVE = 0.80f; +static constexpr float CARRY_ACCEL_PER_TICK = 0.05f; + +static HexaServo arm ({ .signalPin = ARM_SIGNAL_PIN, .startAngle = ARM_UP_ANGLE }); +static HexaServo claw ({ .signalPin = CLAW_SIGNAL_PIN, .startAngle = CLAW_OPEN_ANGLE }); +static HexaServo payload({ .signalPin = PAYLOAD_SIGNAL_PIN, .startAngle = PAYLOAD_CLOSED_ANGLE }); + +static float armCmdDeg = ARM_UP_ANGLE; +static float clawCmdDeg = CLAW_OPEN_ANGLE; +static float payloadCmdDeg = PAYLOAD_CLOSED_ANGLE; + +static bool clawGripLocked = false; +static bool payloadOpen = false; +static float smoothedLeft = 0.0f; +static float smoothedRight = 0.0f; + +// Timed + Brake Turn state +static bool turnActive = false; +static float turnPowerCmd = 0.0f; +static uint32_t turnSpinEndMs = 0; +static uint32_t turnBrakeEndMs = 0; +static float turnTargetDegLog = 0.0f; + +// Onboard LSM6DS IMU Auto-Level state +static uint8_t imuAddr = 0; +static bool autoLevelActive = false; +static float levelZeroDeg = 0.0f; +static float filteredTiltDeg = 0.0f; +static float prevLevelErrDeg = 0.0f; +static uint32_t prevLevelMs = 0; + +static PowerGuard powerGuard; +static BrownoutBeacon brownoutBeacon; +static GripMemory gripMemory; + +static uint16_t rawButtons = 0; + +// ------------------------------------------------------------ +// Direct Non-Invasive LSM6DS IMU Helpers (Reads pitch safely) +// ------------------------------------------------------------ +static bool probeImuAddress(uint8_t addr) { + Wire.beginTransmission(addr); + Wire.write(0x0F); // WHO_AM_I register + if (Wire.endTransmission(false) != 0) return false; + if (Wire.requestFrom((uint8_t)addr, (uint8_t)1) != 1) return false; + uint8_t who = Wire.read(); + return (who == 0x69 || who == 0x6A || who == 0x6C); +} + +static bool readRawImuTilt(float& outDeg) { + if (imuAddr == 0) return false; + + Wire.beginTransmission(imuAddr); + Wire.write(0x28); // OUTX_L_A (6 accelerometer bytes) + if (Wire.endTransmission(false) != 0) return false; + if (Wire.requestFrom((uint8_t)imuAddr, (uint8_t)6) != 6) return false; + + uint8_t xl = Wire.read(); + uint8_t xh = Wire.read(); + uint8_t yl = Wire.read(); + uint8_t yh = Wire.read(); + uint8_t zl = Wire.read(); + uint8_t zh = Wire.read(); + + int16_t ax = (int16_t)((xh << 8) | xl); + int16_t ay = (int16_t)((yh << 8) | yl); + int16_t az = (int16_t)((zh << 8) | zl); + + float pitchAxis = USE_Y_AXIS_FOR_PITCH ? (float)ay : (float)ax; + float zAxis = (float)az; + if (fabsf(pitchAxis) < 1.0f && fabsf(zAxis) < 1.0f) return false; + + outDeg = atan2f(pitchAxis, zAxis) * 57.29578f; + return true; +} + +static void initImuForLeveling() { + imuAddr = 0; + if (probeImuAddress(0x6A)) { + imuAddr = 0x6A; + } else if (probeImuAddress(0x6B)) { + imuAddr = 0x6B; + } + + if (imuAddr == 0) return; + + // Ensure accelerometer is enabled (104 Hz, ±2g) if it was powered down + Wire.beginTransmission(imuAddr); + Wire.write(0x10); // CTRL1_XL + if (Wire.endTransmission(false) == 0 && Wire.requestFrom((uint8_t)imuAddr, (uint8_t)1) == 1) { + uint8_t ctrl1 = Wire.read(); + if (ctrl1 == 0x00) { + Wire.beginTransmission(imuAddr); + Wire.write(0x10); + Wire.write(0x40); + Wire.endTransmission(true); + } + } + + // Calibrate resting flat angle as 0.0° baseline + float sum = 0.0f; + int validSamples = 0; + for (int i = 0; i < 12; i++) { + float deg = 0.0f; + if (readRawImuTilt(deg)) { + sum += deg; + validSamples++; + } + delay(5); + } + + if (validSamples > 0) { + levelZeroDeg = sum / (float)validSamples; + filteredTiltDeg = levelZeroDeg; + } +} + +static void refreshRawButtons() { + float lx, ly, rx, ry; + uint16_t btns = 0; + NRLGamepad::read(lx, ly, rx, ry, btns); + rawButtons = btns; +} + +static bool isBtnPressed(uint16_t btn) { + return gamepad1.pressed(btn) || ((rawButtons & btn) != 0); +} + +static float stepAngle(float current, float target, float maxStep) { + if (target > current + maxStep) return current + maxStep; + if (target < current - maxStep) return current - maxStep; + return target; +} + +static float slewDrive(float current, float target, float maxStep) { + if (target > current + maxStep) return current + maxStep; + if (target < current - maxStep) return current - maxStep; + return target; +} + +static void startPrecisionTurn(float targetDeg, float speed, uint32_t durationMs, float directionSign) { + uint32_t now = millis(); + turnTargetDegLog = targetDeg * directionSign; + turnPowerCmd = speed * directionSign; + turnSpinEndMs = now + durationMs; + turnBrakeEndMs = turnSpinEndMs + TURN_BRAKE_MS; + turnActive = true; + autoLevelActive = false; +} + +static void updatePrecisionTurn(float driveScale) { + uint32_t now = millis(); + if (now < turnSpinEndMs) { + drive.drive(0.0f, turnPowerCmd * driveScale); + } else if (now < turnBrakeEndMs) { + drive.drive(0.0f, -turnPowerCmd * 0.55f); + } else { + drive.stop(); + turnActive = false; + } +} + +class DriveMode : public NRLOpMode { +public: + void init() override { + gripMemory.begin(); + + arm.begin(); + claw.begin(); + payload.begin(); + leftMotor.begin(); + rightMotor.begin(); + + initImuForLeveling(); + + armCmdDeg = ARM_UP_ANGLE; + payloadOpen = false; + payloadCmdDeg = PAYLOAD_CLOSED_ANGLE; + turnActive = false; + autoLevelActive = false; + smoothedLeft = 0.0f; + smoothedRight = 0.0f; + + if (gripMemory.engaged) { + clawGripLocked = true; + clawCmdDeg = CLAW_CLOSED_ANGLE; + } else { + clawGripLocked = false; + clawCmdDeg = CLAW_OPEN_ANGLE; + } + + arm.setPosition(armCmdDeg); + claw.setPosition(clawCmdDeg); + payload.setPosition(payloadCmdDeg); + + brownoutBeacon.arm(); + userLed.setSolid(0, 255, 0); + } + + void loop() override { + refreshRawButtons(); + const float driveScale = powerGuard.update(); + + // Update filtered IMU tilt angle every tick + float rawDeg = 0.0f; + if (readRawImuTilt(rawDeg)) { + filteredTiltDeg = (0.75f * filteredTiltDeg) + (0.25f * rawDeg); + } + const float relativeTiltDeg = filteredTiltDeg - levelZeroDeg; + + // -------------------------------------------------------- + // 0. BUTTON X TOGGLE — Start / Stop Spacestation Auto-Level + // -------------------------------------------------------- + if (gamepad1.justPressed(BTN_X)) { + if (imuAddr != 0) { + autoLevelActive = !autoLevelActive; + turnActive = false; + prevLevelErrDeg = relativeTiltDeg; + prevLevelMs = millis(); + if (!autoLevelActive) { + drive.stop(); + } + } else { + autoLevelActive = false; + } + } + + // Instant joystick override cancels auto-turn or auto-level if driver pushes sticks + const bool sticksMoved = (fabsf(gamepad1.leftY()) > 0.30f || fabsf(gamepad1.rightY()) > 0.30f); + if ((turnActive || autoLevelActive) && sticksMoved) { + drive.stop(); + turnActive = false; + autoLevelActive = false; + } + + // -------------------------------------------------------- + // 1. TURN SHORTCUTS (RB = 140° @ 90%, LB = 50° @ 80%) + // -------------------------------------------------------- + if (!turnActive && !autoLevelActive) { + if (gamepad1.justPressed(BTN_RB)) { + startPrecisionTurn(140.0f, TURN_140_SPEED, TURN_140_MS, TURN_140_DIR); + } else if (gamepad1.justPressed(BTN_LB)) { + startPrecisionTurn(50.0f, TURN_50_SPEED, TURN_50_MS, TURN_50_DIR); + } + } + + // -------------------------------------------------------- + // 2. DRIVE — Auto-Level, Precision Turn, or Dual-Stick Tank + // -------------------------------------------------------- + const float activeMaxDrive = clawGripLocked ? CARRY_MAX_DRIVE : 1.0f; + + if (autoLevelActive) { + smoothedLeft = 0.0f; + smoothedRight = 0.0f; + + uint32_t now = millis(); + float dt = (now - prevLevelMs) * 0.001f; + if (dt < 0.005f) dt = 0.01f; + prevLevelMs = now; + + float error = relativeTiltDeg; + float dErr = (error - prevLevelErrDeg) / dt; + prevLevelErrDeg = error; + + if (fabsf(error) <= LEVEL_DEADBAND_DEG) { + drive.stop(); + telemetry.addData("LEVEL", "BALANCED!"); + } else { + float cmd = (error * LEVEL_KP + dErr * LEVEL_KD) * LEVEL_DRIVE_SIGN; + if (cmd > 0.0f) { + cmd = constrain(cmd, LEVEL_MIN_POWER, LEVEL_MAX_POWER); + } else { + cmd = constrain(cmd, -LEVEL_MAX_POWER, -LEVEL_MIN_POWER); + } + drive.drive(cmd * driveScale, 0.0f); + telemetry.addData("LEVEL", "BALANCING..."); + } + } else if (turnActive) { + smoothedLeft = 0.0f; + smoothedRight = 0.0f; + updatePrecisionTurn(driveScale); + telemetry.addData("DRIVE", "AUTO TURN"); + telemetry.addData("Turn Deg", turnTargetDegLog); + } else { + float leftStick = gamepad1.leftY(); + float rightStick = gamepad1.rightY(); + + const float DEADZONE = 0.05f; + if (fabsf(leftStick) < DEADZONE) leftStick = 0.0f; + if (fabsf(rightStick) < DEADZONE) rightStick = 0.0f; + + float targetL = leftStick * activeMaxDrive * driveScale; + float targetR = rightStick * activeMaxDrive * driveScale; + + if (clawGripLocked) { + smoothedLeft = slewDrive(smoothedLeft, targetL, CARRY_ACCEL_PER_TICK); + smoothedRight = slewDrive(smoothedRight, targetR, CARRY_ACCEL_PER_TICK); + } else { + smoothedLeft = targetL; + smoothedRight = targetR; + } + + float forward = (smoothedLeft + smoothedRight) * 0.5f; + float turn = (smoothedLeft - smoothedRight) * 0.5f; + + drive.drive(forward, turn); + telemetry.addData("LEVEL", imuAddr != 0 ? "OFF (Press X)" : "NO IMU"); + } + + // -------------------------------------------------------- + // 3. ARM (S1) — D-Down = Arm Down + Auto-Open Claw (30°) + // D-Up = Arm Up + // -------------------------------------------------------- + const bool dpadUp = isBtnPressed(BTN_DPAD_UP); + const bool dpadDown = isBtnPressed(BTN_DPAD_DOWN); + + if (dpadUp && !dpadDown) { + armCmdDeg = stepAngle(armCmdDeg, ARM_UP_ANGLE, ARM_STEP_PER_TICK); + } else if (dpadDown && !dpadUp) { + armCmdDeg = stepAngle(armCmdDeg, ARM_DOWN_ANGLE, ARM_STEP_PER_TICK); + + // Automatically open the claw to 30° when arm goes down + clawGripLocked = false; + gripMemory.set(false); + clawCmdDeg = stepAngle(clawCmdDeg, CLAW_OPEN_ANGLE, CLAW_STEP_PER_TICK); + } + + // -------------------------------------------------------- + // 4. CLAW (S4) — D-Right = Open (30°), D-Left = Close (95°) + // -------------------------------------------------------- + const bool dpadRight = isBtnPressed(BTN_DPAD_RIGHT); + const bool dpadLeft = isBtnPressed(BTN_DPAD_LEFT); + + if (dpadRight && !dpadLeft) { + clawGripLocked = false; + gripMemory.set(false); + clawCmdDeg = stepAngle(clawCmdDeg, CLAW_OPEN_ANGLE, CLAW_STEP_PER_TICK); + } else if (dpadLeft && !dpadRight) { + clawGripLocked = true; + gripMemory.set(true); + clawCmdDeg = stepAngle(clawCmdDeg, CLAW_CLOSED_ANGLE, CLAW_STEP_PER_TICK); + } + + // -------------------------------------------------------- + // 5. PAYLOAD SERVO (S3) — Press Button A to Open / Close (90°) + // -------------------------------------------------------- + if (gamepad1.justPressed(BTN_A)) { + payloadOpen = !payloadOpen; + } + float payloadTarget = payloadOpen ? PAYLOAD_OPEN_ANGLE : PAYLOAD_CLOSED_ANGLE; + payloadCmdDeg = stepAngle(payloadCmdDeg, payloadTarget, PAYLOAD_STEP_PER_TICK); + + // -------------------------------------------------------- + // 6. SEND CLEAN POSITION COMMANDS TO ALL 3 SERVOS + // -------------------------------------------------------- + arm.setPosition(armCmdDeg); + claw.setPosition(clawCmdDeg); + payload.setPosition(payloadCmdDeg); + + // -------------------------------------------------------- + // 7. STATUS LED & LIVE TELEMETRY + // -------------------------------------------------------- + if (!brownoutBeacon.service()) { + if (power.isBatteryLow()) { + userLed.setBlink(255, 0, 0, 300); + } else if (autoLevelActive) { + userLed.setSolid(0, 180, 255); // Cyan: Auto-Level Active + } else if (clawGripLocked) { + userLed.setSolid(180, 0, 255); // Purple: Element Gripped + } else { + userLed.setSolid(0, 255, 0); // Green: Ready + } + } + + telemetry.addData("Tilt Deg", relativeTiltDeg); + telemetry.addData("Arm (S1)", armCmdDeg); + telemetry.addData("Claw (S4)", clawCmdDeg); + telemetry.addData("Pay (S3)", payloadCmdDeg); + telemetry.addData("Payload", payloadOpen ? "OPEN (90)" : "CLOSED (0)"); + team205ReportPower(telemetry, powerGuard); + } + + void stop() override { + cancelActions(); + drive.stop(); + gripMemory.set(false); + turnActive = false; + autoLevelActive = false; + + arm.detach(); + claw.detach(); + payload.detach(); + userLed.setOff(); + } +}; + +REGISTER_OPMODE(DriveMode, "Drive Mode", 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..6b6d279 --- /dev/null +++ b/RobotFirmware/opmodes/team205_mech.h @@ -0,0 +1,274 @@ +#pragma once +#include "NRL.h" +#include <Preferences.h> +#include <esp_system.h> + +// ============================================================================ +// TEAM 205 (PIXEL POKER) - SHARED MECHANISM & POWER LIBRARY (team205_mech.h) +// Supports: drivemode.cpp, normaldrive.cpp, tiltsteering.cpp, pixelpoker_auto.cpp +// ============================================================================ + +class ServoAxis { +public: + void bind(HexaServo& driver, float homeDeg, float poseADeg, float poseBDeg) { + drv = &driver; + homeAngle = homeDeg; + minAngle = fminf(poseADeg, poseBDeg); + maxAngle = fmaxf(poseADeg, poseBDeg); + targetDeg = homeDeg; + lastMoveMs = millis(); + } + + void command(float deg, bool allowOvertravel = false) { + if (!allowOvertravel) { + deg = constrain(deg, minAngle, maxAngle); + } else { + deg = constrain(deg, 0.0f, 180.0f); + } + + if (fabsf(deg - targetDeg) > 0.25f) { + targetDeg = deg; + lastMoveMs = millis(); + } + } + + void press(float gripDeg) { + command(gripDeg, true); + } + + void stopPressing() { + targetDeg = constrain(targetDeg, minAngle, maxAngle); + } + + void apply() { + if (drv != nullptr) { + drv->setPosition(targetDeg); + } + } + + float actual() const { + return (drv != nullptr) ? drv->getPosition() : targetDeg; + } + + float target() const { + return targetDeg; + } + + bool travelArrived(float tolDeg = 0.5f) const { + return fabsf(actual() - targetDeg) <= tolDeg; + } + + bool isSettled(float tolDeg = 1.0f) const { + return travelArrived(tolDeg); + } + + uint32_t msSinceCommand() const { + return millis() - lastMoveMs; + } + +private: + HexaServo* drv = nullptr; + float homeAngle = 90.0f; + float minAngle = 0.0f; + float maxAngle = 180.0f; + float targetDeg = 90.0f; + uint32_t lastMoveMs = 0; +}; + +// Non-blocking motion arbiter with 650ms auto-release timeout +static ServoAxis* activeMotionOwner = nullptr; +static uint32_t motionLockStartMs = 0; +static constexpr uint32_t MOTION_LOCK_TIMEOUT_MS = 650; + +inline bool motionRequest(ServoAxis& axis) { + uint32_t now = millis(); + + if (activeMotionOwner == &axis) { + return true; + } + + if (activeMotionOwner == nullptr || + activeMotionOwner->travelArrived(1.0f) || + (now - motionLockStartMs) >= MOTION_LOCK_TIMEOUT_MS) { + activeMotionOwner = &axis; + motionLockStartMs = now; + return true; + } + + return false; +} + +inline void motionRelease(ServoAxis& axis) { + if (activeMotionOwner == &axis) { + activeMotionOwner = nullptr; + } +} + +enum class ClawDir { NONE, EXPAND, CONTRACT }; + +class ClawControl { +public: + ClawDir dir = ClawDir::NONE; + + void bind(ServoAxis& clawAxisRef, float openDeg, float closedDeg, float gripDeg) { + axis = &clawAxisRef; + openAngle = openDeg; + closeAngle = closedDeg; + gripAngle = gripDeg; + gripping = false; + dir = ClawDir::NONE; + } + + void update(ClawDir desired) { + dir = desired; + if (axis == nullptr) return; + + if (desired == ClawDir::EXPAND) { + gripping = false; + if (motionRequest(*axis)) { + axis->command(openAngle); + } + } else if (desired == ClawDir::CONTRACT) { + if (motionRequest(*axis)) { + axis->command(closeAngle); + } + } else { + if (!gripping && prevDir != ClawDir::NONE) { + axis->command(axis->actual()); + } + motionRelease(*axis); + } + + prevDir = desired; + } + + void tryClose() { + if (axis == nullptr) return; + gripping = false; + axis->command(closeAngle); + } + + void tryOpen() { + if (axis == nullptr) return; + gripping = false; + axis->command(openAngle); + } + + void engageNow() { + if (axis == nullptr) return; + gripping = true; + axis->press(gripAngle); + } + + void releaseNow() { + gripping = false; + if (axis != nullptr) { + axis->stopPressing(); + motionRelease(*axis); + } + } + + bool isGripping() const { + return gripping; + } + +private: + ServoAxis* axis = nullptr; + ClawDir prevDir = ClawDir::NONE; + float openAngle = 125.0f; + float closeAngle = 155.0f; + float gripAngle = 160.5f; + bool gripping = false; +}; + +class PowerGuard { +public: + float update() { + if (power.isBatteryLow()) { + lowSagActive = true; + scale = fmaxf(0.65f, scale - 0.02f); + } else { + lowSagActive = false; + scale = fminf(1.00f, scale + 0.01f); + } + return scale; + } + + bool isSagging() const { return lowSagActive; } + float currentScale() const { return scale; } + +private: + float scale = 1.0f; + bool lowSagActive = false; +}; + +class BrownoutBeacon { +public: + void arm() { + wasBrownout = (esp_reset_reason() == ESP_RST_BROWNOUT); + if (wasBrownout) { + Preferences prefs; + if (prefs.begin("t205_pwr", false)) { + bootCount = prefs.getUInt("bo_cnt", 0) + 1; + prefs.putUInt("bo_cnt", bootCount); + prefs.end(); + } + beaconEndMs = millis() + 3000; + } else { + Preferences prefs; + if (prefs.begin("t205_pwr", true)) { + bootCount = prefs.getUInt("bo_cnt", 0); + prefs.end(); + } + beaconEndMs = 0; + } + } + + bool service() { + if (!wasBrownout || millis() >= beaconEndMs) { + return false; + } + bool on = ((millis() / 150) % 2) == 0; + if (on) { + userLed.setSolid(255, 0, 0); + } else { + userLed.setOff(); + } + return true; + } + + uint32_t brownoutCount() const { return bootCount; } + +private: + bool wasBrownout = false; + uint32_t beaconEndMs = 0; + uint32_t bootCount = 0; +}; + +class GripMemory { +public: + bool engaged = false; + + void begin() { + Preferences prefs; + if (prefs.begin("t205_grip", true)) { + engaged = prefs.getBool("held", false); + prefs.end(); + } + } + + void set(bool state) { + if (engaged == state) return; + engaged = state; + Preferences prefs; + if (prefs.begin("t205_grip", false)) { + prefs.putBool("held", state); + prefs.end(); + } + } +}; + +template <typename TelemetryT> +inline void team205ReportPower(TelemetryT& telem, const PowerGuard& pg) { + telem.addData("Rail", pg.isSagging() ? "LOW SAG" : "OK"); +} 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 Binary files differnew file mode 100644 index 0000000..9cf8556 --- /dev/null +++ b/lib/HexaIMU/lib/xtensa-esp32s3/libHexaIMU_static.a 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 Binary files differnew file mode 100644 index 0000000..1ddfd77 --- /dev/null +++ b/lib/HexaLED/lib/xtensa-esp32s3/libHexaLED_static.a 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 Binary files differnew file mode 100644 index 0000000..03a6bf8 --- /dev/null +++ b/lib/HexaOLED/lib/xtensa-esp32s3/libHexaOLED_static.a 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 Binary files differnew file mode 100644 index 0000000..1884764 --- /dev/null +++ b/lib/HexaPower/lib/xtensa-esp32s3/libHexaPower_static.a 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 Binary files differnew file mode 100644 index 0000000..12ba0e1 --- /dev/null +++ b/lib/HexaServos/lib/xtensa-esp32s3/libHexaServos_static.a 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()) |
