10 Commits
Author SHA1 Message Date
mangavalkandClaude Opus 5.5 179afdb705 2026 docs: review of every README against today's state
- README / CLAUDE.md layout: dongle/, hardware/, tools/ submodule,
  make_remote_hmi.py; telemetry in the protocol; the PC can take the
  robot's place on the radio. CLAUDE.md: NextionUI is on Serial2 (said
  Serial1); remote-without-robot via the dongle + sim.
- remote/README: MPU6050 supply row; stick calibration button names of the
  new SETUP page; upload/USB-port hints.
- remote/NEXTION.md: display on Serial2, how the Editor upload goes.
- robot/README: Battery in the file list, Comms/ServoDriver roles, packet
  structs instead of payload size, check the IMU gives live data (the
  remote's MPU6050 needed a full reset; RobotIMU::begin() only wakes it).
- sim/README: smoke test covers telemetry and servo calibration;
  OpenScadModel.
- dongle/README: AT2401C test result, app command table, SignalRGB note,
  air settings incl. ack payloads.
- PLANNING.md: the display direction is in the generated HMI.
- Unity README: what the project is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:56:14 +01:00
mangavalkandClaude Opus 5.5 a59faf3b03 2026 docs: update the planned/future notes
- PLANNING.md: IMU on the pin headers is done; battery firmware is done
  except the % curve and the low-battery warning.
- README "Where to go next": link sim/README and dongle/README.
- remote/README intro: telemetry comes back; the sim can answer via the dongle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:54:10 +01:00
mangavalkandClaude Opus 5.5 175a1a0da8 2026 docs: catch the READMEs up with today's state
- README: the HMI is generated turned round (nothing to set in the Editor);
  PC radio link: bridge mode done, no USB links any more, what's left
  (Unity driving the real robot, three nodes at once).
- remote/README checklist: sticks and IMU checked, display uploaded, radio
  checked against the sim through the dongle; replace the IMU board.
- CLAUDE.md: display runs the new HMI; next steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:52:44 +01:00
mangavalkandClaude Opus 5.5 1591105f26 2026 Unity: drop the auto-generated GDKEdition settings asset
Unity 6000.6.3 removed Assets/Resources/GDKEditionAutoGen when it opened the
project (Microsoft GDK package settings; the project doesn't use the GDK).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:50:49 +01:00
mangavalkandClaude Opus 5.5 3d6c4dd2f0 2026 remote_v2 case: taller top shell, measured display, M3 display posts
- TOP_GROW: top shell 10 mm taller (room behind the display); the bottom
  shell is unchanged, dependent heights follow Z_SPLIT / Z_BOT.
- Nextion dimensions as measured by the owner: board 100.6 x 55, LCD
  85.7 x 55 x 3.86 plus a 1.3 mm flex cable, 11.21 mm glass to back of J1.
  LCD pocket allows the cable on either short side; bezel 1.0 mm (the
  display sat on the Teensy).
- Display posts tapped M3 for M3 x 5 machine screws, 1.2 mm skin under the
  top face (was M2.5 self-tapping). README screw list and PLANNING.md
  updated; STLs regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:50:48 +01:00
mangavalkandClaude Opus 5.5 2b4750f8f4 2026 sim: drive the Unity simulation with the real remote over the radio
Dongle (app):
- bridge mode: stands in for the robot's radio (ch 96 / 250k / HXPD1,
  auto-ack, dynamic payloads, ack payloads). Received packets go to the PC
  as A5-framed 'R' frames; the PC's 'A' frames become the ack payload of
  the next packet, like robot/Comms.cpp; dropped after ~0.5 s without a
  refresh. 'S' status once a second.
- USART RX through circular DMA into a ring buffer, overrun stall
  disabled, error flags cleared: a burst (e.g. SignalRGB probing the port)
  used to deafen the app until a replug.
- RX test mode ('x') accepts protocol v4's dynamic-length packets.
- safeboot_flash.py --knock: keeps knocking across a replug to catch
  safeboot's cold-boot window when the app doesn't answer.

Unity:
- SimRemote sources: Keyboard, or the real remote via the dongle
  (DongleLink.cs: kernel32 serial, auto-finds the CH340, all port I/O on
  one background thread). Packets go into the firmware byte for byte, the
  robot's telemetry goes back on the ack, so the remote's display shows
  the sim. Tested end to end with the real remote.
- Dropped the USB joystick and robot-serial-harness inputs and the old
  Serial/Serial2/Serial3/HandleHoystick scripts (and their components in
  Main.unity): no USB links to remote or robot any more.
- Test panel: dongle status; no sideways scroll bar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:48:41 +01:00
mangavalkandClaude Opus 5.5 6b3b2629cd 2026 remote: display turned 180 degrees (it sits upside down in the remote)
make_remote_hmi.py now builds the project with Editor display direction 270
(landscape, flipped) before adding pictures and fonts, so they're stored for
that direction. Checked in Nextion Editor and on the real display.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:48:41 +01:00
mangavalkandClaude Opus 5.5 aeccba3be7 2026 remote: wiring as found on the real remote, IMU reset fix
- Nextion is on Serial2 (pins 7/8) - already in the last commit; docs updated.
- MPU6050 on Wire (18/19) so everything is on the edge headers (owner's
  choice); the two stick wires from 18/19 move to A7/A8 (21/22).
- Stick mapping checked on the real remote: left stick X/Y/twist on
  A3/A7/A8, right on A0/A1/A2, all inverted but the right twist.
- RemoteIMU: full device reset before waking. The remote's MPU6050 (likely
  a clone) answers and wakes without it but every data register reads 0.
  Axis defaults confirmed (+pitch nose down, +roll right side down).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:03:08 +01:00
mangavalkandClaude Opus 5.5 0b836af8de 2026 remote: tabbed Nextion UI, robot telemetry, servo centre calibration
Protocol v4: CmdPacket grows to 26 bytes (cal_cmd, cal_servo, cal_value);
new 30-byte Telemetry rides back on the nRF24 ack payload (robot state,
IMU, battery, 18 joint angles, packets/s, servo-cal echo). Each end drops
wrong-length packets, so version mismatches still fail closed.

Robot (owner-approved): SERVO_CAL state while disarmed, per-servo centre
trims (+-200 us) in EEPROM, telemetry, battery reading; the IMU estimate
now always runs (leveling still gated by ROBOT GYRO).

Remote: generated HMI (scripts/make_remote_hmi.py) with pages splash,
drive, status, servos, cal, setup, upload; page-aware NextionUI that only
writes the showing page and only what changed; servo calibration and
UPDATE DISPLAY on the touchscreen and serial console; battery module.
The display is on Serial2 (pins 7/8), found on the real remote; the old
sketch's Serial1 was never connected to it.

Sim: RF24 shim supports ack payloads, API version 8
(hxsim_get_ack_payload); sim_smoke checks telemetry and every CAL command.
Unity CmdPacket mirror updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:42:37 +01:00
mangavalkandClaude Opus 5.5 481610c9fd Add nextion-hmi-tools submodule and nxhmi MCP server config
The nxhmi MCP server (.mcp.json) edits and renders the remote's Nextion HMI;
scripts/make_remote_hmi.py uses its Python package from the submodule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:42:28 +01:00
75 changed files with 2377 additions and 1149 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
[submodule "2026-current/tools/nextion-hmi-tools"]
path = 2026-current/tools/nextion-hmi-tools
url = https://mangavalk.com/mangavalk/openhmi-nx.git
+9
View File
@@ -0,0 +1,9 @@
{
"mcpServers": {
"nxhmi": {
"command": "python",
"args": ["-m", "nxhmi.mcp_server"],
"env": {"PYTHONPATH": "2026-current/tools/nextion-hmi-tools/src"}
}
}
}
+100 -51
View File
@@ -1,7 +1,7 @@
# Hexapod: project memory # Hexapod: project memory
Hexapod walking robot plus a custom handheld remote, both Teensy-based and Hexapod walking robot plus a custom handheld remote, both Teensy-based and
linked one-way over nRF24L01 (remote → robot, with hardware auto-ack only). linked over nRF24L01: commands remote → robot, telemetry back in the radio's ack payloads.
A Unity simulation runs the *unchanged* robot firmware as a DLL. This file A Unity simulation runs the *unchanged* robot firmware as a DLL. This file
is the persistent context for working on any part of it. Read it fully is the persistent context for working on any part of it. Read it fully
before changing anything. before changing anything.
@@ -14,7 +14,10 @@ remote/ Teensy 4.0 firmware (PlatformIO env remote)
shared/HexapodProtocol/ wire protocol, used by robot, remote and sim shared/HexapodProtocol/ wire protocol, used by robot, remote and sim
sim/ robot firmware -> hexapod_sim.dll (CMake + g++), headless smoke test sim/ robot firmware -> hexapod_sim.dll (CMake + g++), headless smoke test
Hexapod_Simulation_Unity/ Unity 6000.6 project that loads the DLL (Assets/HexapodSim/) Hexapod_Simulation_Unity/ Unity 6000.6 project that loads the DLL (Assets/HexapodSim/)
scripts/ PlatformIO helper dongle/ USB nRF24 stick firmware (STM32F030): the PC's radio, bridge mode for Unity
hardware/ OpenSCAD rebuild + new remote case, Fusion 360 designs, PCB notes
scripts/ PlatformIO helper, make_remote_hmi.py (generates remote/remote.HMI)
tools/nextion-hmi-tools/ git submodule: nxhmi (.HMI read/write/render, MCP server)
``` ```
This folder is `2026-current/` inside the `hexapod-robot` repo. The older generations sit next to it This folder is `2026-current/` inside the `hexapod-robot` repo. The older generations sit next to it
@@ -51,7 +54,7 @@ PlatformIO, one `platformio.ini`, two environments:
## Communication contract (`shared/HexapodProtocol/HexapodProtocol.h`) ## Communication contract (`shared/HexapodProtocol/HexapodProtocol.h`)
`CmdPacket`, 22 bytes (static_asserted; protocol v3), sent remote → robot at 100 Hz `CmdPacket`, 26 bytes (static_asserted; protocol v4, `HXP_PROTOCOL_VERSION`), sent remote → robot at 100 Hz
(robot `CONTROL_HZ` is 60): (robot `CONTROL_HZ` is 60):
| Field | Range | Meaning | | Field | Range | Meaning |
@@ -65,6 +68,16 @@ PlatformIO, one `platformio.ini`, two environments:
| `speed_scale` | 0–255 | multiplies vx/vy on the robot | | `speed_scale` | 0–255 | multiplies vx/vy on the robot |
| `flags` | bits | `ARMED, STAND, WALK, MODE_B, RSTICK_XLATE, GAIT_WAVE, REMOTE_GYRO, ROBOT_GYRO` (bits 0–7) | | `flags` | bits | `ARMED, STAND, WALK, MODE_B, RSTICK_XLATE, GAIT_WAVE, REMOTE_GYRO, ROBOT_GYRO` (bits 0–7) |
| `seq` | 0–255 | increments per packet (robot doesn't check it yet) | | `seq` | 0–255 | increments per packet (robot doesn't check it yet) |
| `cal_cmd` | `CAL_*` | servo centre calibration, only while not armed: `CAL_NONE` normal, `HOLD` centre pose, `SET` trim, `SAVE` / `REVERT` EEPROM. States, not events: repeats are harmless |
| `cal_servo`, `cal_value` | 0–17, ±200 µs | selected servo (leg × 3 + joint) and its trim for `CAL_SET` |
`Telemetry`, 30 bytes, robot → remote as the **ack payload** of the remote's
next packet (`Comms::loadAckPayload` after every packet received; no extra
transmissions): robot state (`TSTATE_*`, 4 = SERVO_CAL), status bits
(`TSTAT_*`: IMU ok, gyro on, servos driven, trims dirty / stored), IMU
roll/pitch in 0.1°, battery mV (0 = not measured), the 18 commanded joint
angles as int8 (tibia stored + 90), packets received per second, and the
echo of `cal_servo` with its trim.
- **Axis convention** (ROS REP-103 style): body +X forward, +Y left, +Z up. - **Axis convention** (ROS REP-103 style): body +X forward, +Y left, +Z up.
+roll = right side down, +pitch = nose down, +yaw = CCW. +roll = right side down, +pitch = nose down, +yaw = CCW.
@@ -72,11 +85,15 @@ PlatformIO, one `platformio.ini`, two environments:
`InputMapper` owns the scaling: `MAX_LINEAR_MM_S` 150, `InputMapper` owns the scaling: `MAX_LINEAR_MM_S` 150,
`MAX_TURN_RATE_DEG_S` 90, `MAX_TILT_DEG` 20, `MAX_POSE_OFFSET_MM` 40. `MAX_TURN_RATE_DEG_S` 90, `MAX_TILT_DEG` 20, `MAX_POSE_OFFSET_MM` 40.
- **Radio settings** live in the same header: address `"HXPD1"`, channel - **Radio settings** live in the same header: address `"HXPD1"`, channel
96, 250 kbps, PA LOW, **static payload size = sizeof(CmdPacket)** on both 96, 250 kbps, PA LOW. Ack payloads need dynamic payload lengths
radios. That makes version mismatches fail closed: packets are not (`enableAckPayload()` on both radios), so **each end drops any packet
received, the robot times out, and it disarms. whose length isn't sizeof() of its struct**. That keeps version
- **Changing the protocol means reflashing both boards.** Keep it ≤ 32 mismatches failing closed: packets are ignored, the robot times out, and
bytes and update the `static_assert`. it disarms.
- **Changing the protocol means reflashing both boards.** Keep both
structs ≤ 32 bytes, update the `static_assert`s, bump
`HXP_PROTOCOL_VERSION`, and mirror `CmdPacket` in the Unity
`HexapodSimNative.cs`.
- **Failsafes:** the robot sets `linkOk()` false after `LINK_TIMEOUT_SEC` - **Failsafes:** the robot sets `linkOk()` false after `LINK_TIMEOUT_SEC`
(0.3 s) without packets and then uses a default `CmdPacket` (flags 0 = (0.3 s) without packets and then uses a default `CmdPacket` (flags 0 =
disarmed, servos detached). The remote disarms itself after disarmed, servos detached). The remote disarms itself after
@@ -101,33 +118,41 @@ joint-rate clamp → servos.
| `Kinematics` | per-leg 3-DOF analytic IK, `neutralStance()` | | `Kinematics` | per-leg 3-DOF analytic IK, `neutralStance()` |
| `GaitEngine` | tripod/wave patterns, per-leg phase, pattern swap only at touchdown. `limitTwist()` (called in robot.ino right after InputMapper, so the heading estimate integrates the *achieved* ω) scales the walk command until its stride envelope (`strideEnvelope()`: even/odd legs at opposite stride ends, plus a lifted set) is feasible, so full-rate turning can't make neighbouring legs collide. Stance feet are *integrated* each tick from the current twist (v + ω×r at the foot); swing feet arc from lift-off to the next leading edge. `resetFeet()` on entering WALKING restarts the cycle with grounded legs at mid-stance | | `GaitEngine` | tripod/wave patterns, per-leg phase, pattern swap only at touchdown. `limitTwist()` (called in robot.ino right after InputMapper, so the heading estimate integrates the *achieved* ω) scales the walk command until its stride envelope (`strideEnvelope()`: even/odd legs at opposite stride ends, plus a lifted set) is feasible, so full-rate turning can't make neighbouring legs collide. Stance feet are *integrated* each tick from the current twist (v + ω×r at the foot); swing feet arc from lift-off to the next leading edge. `resetFeet()` on entering WALKING restarts the cycle with grounded legs at mid-stance |
| `BodyPose` | 6-axis body pose (smoothed command + IMU roll/pitch correction), applied to foot targets as the *inverse* rotation, so the body moves as commanded. `fitToReach()` scales the *whole* pose by one factor (binary search on `Limits::feetFeasible`; drops at once, recovers at 1/s) so combined poses never bend individual legs out of a rigid foot pattern or into each other. While walking it fits against the stride envelope, not the current feet, so it doesn't saw with the step cycle | | `BodyPose` | 6-axis body pose (smoothed command + IMU roll/pitch correction), applied to foot targets as the *inverse* rotation, so the body moves as commanded. `fitToReach()` scales the *whole* pose by one factor (binary search on `Limits::feetFeasible`; drops at once, recovers at 1/s) so combined poses never bend individual legs out of a rigid foot pattern or into each other. While walking it fits against the stride envelope, not the current feet, so it doesn't saw with the step cycle |
| `RobotIMU` | MPU6050 complementary filter (α 0.98), gated by `FLAG_ROBOT_GYRO` | | `RobotIMU` | MPU6050 complementary filter (α 0.98). Always estimates (the remote shows it); only the self-leveling in robot.ino is gated by `FLAG_ROBOT_GYRO` |
| `StateMachine` | DISARMED → SIT → STAND → WALKING, sit/stand blend at 1/s. Disarm is instant | | `StateMachine` | DISARMED → SIT → STAND → WALKING, sit/stand blend at 1/s. Disarm is instant |
| `InputMapper` | CmdPacket → Twist + PoseCommand + mode flags + stance height. Mode B = steering **relative to where the body faces right now**: the forward/back stick component sets walking direction (vx sign), the sideways component steers (target = current heading + atan2(vy, |vx|) every tick). So W = straight on, S = straight **back** (not turn around; owner's request), W/S+A = walk while turning left, A alone = turn on the spot while held. On release the target freezes at the current heading (hold). An earlier version froze the reference at the first push, so heading only changed after releasing W; the owner rejected that. Mode A keeps the target = current heading so switching to B never jumps. Forward speed × max(0, cos(heading error)), so big corrections turn in place first. Adds remote tilt on top of stick pose when `FLAG_REMOTE_GYRO`, clamped to `MAX_TILT_DEG` | | `InputMapper` | CmdPacket → Twist + PoseCommand + mode flags + stance height. Mode B = steering **relative to where the body faces right now**: the forward/back stick component sets walking direction (vx sign), the sideways component steers (target = current heading + atan2(vy, |vx|) every tick). So W = straight on, S = straight **back** (not turn around; owner's request), W/S+A = walk while turning left, A alone = turn on the spot while held. On release the target freezes at the current heading (hold). An earlier version froze the reference at the first push, so heading only changed after releasing W; the owner rejected that. Mode A keeps the target = current heading so switching to B never jumps. Forward speed × max(0, cos(heading error)), so big corrections turn in place first. Adds remote tilt on top of stick pose when `FLAG_REMOTE_GYRO`, clamped to `MAX_TILT_DEG` |
| `Limits` | workspace clamp (70 mm horiz / 60 mm vert), joint rate clamp, ≥3-legs-in-stance check (not acted on yet). `feetFeasible()` = every foot in its workspace with valid IK **and** neighbouring legs' segments (coxa/femur/tibia, via `Kinematics::jointPositions`) ≥ `LEG_CLEARANCE_MM` apart. This is the single "physically possible" test used by gait and pose limiting | | `Limits` | workspace clamp (70 mm horiz / 60 mm vert), joint rate clamp, ≥3-legs-in-stance check (not acted on yet). `feetFeasible()` = every foot in its workspace with valid IK **and** neighbouring legs' segments (coxa/femur/tibia, via `Kinematics::jointPositions`) ≥ `LEG_CLEARANCE_MM` apart. This is the single "physically possible" test used by gait and pose limiting |
| `Comms` | nRF24 RX, link timeout, `injectPacket()` for the harness | | `Comms` | nRF24 RX (drops wrong-length packets), link timeout, telemetry as ack payload, packets/s, `injectPacket()` for the harness |
| `ServoDriver` | 18 servos on hardware PWM (50 Hz, 16-bit), per-servo calibration from `Config.h` `SERVOS`, duty 0 = relaxed, skips invalid IK solutions | | `ServoDriver` | 18 servos on hardware PWM (50 Hz, 16-bit), per-servo calibration from `Config.h` `SERVOS` plus a per-servo centre trim (µs, EEPROM record at address 0, loaded in setup), duty 0 = relaxed, skips invalid IK solutions. `calibrate()` = SERVO_CAL: applies a `CAL_*` command and holds `CAL_POSE` (coxa 0, femur 0, tibia −90) |
| `Battery` | battery voltage through a divider; `BATTERY_SENSE_PIN` 255 = not wired yet |
`robot.ino` also runs SERVO_CAL (disarmed + `cal_cmd != CAL_NONE`; leaving
it relaxes the servos) and fills the `Telemetry` every loop
(`sendTelemetry`).
## Remote architecture (`remote/`, Teensy 4.0) ## Remote architecture (`remote/`, Teensy 4.0)
Loop: drain Nextion + USB serial input every pass. On each `TX_HZ` (100) Loop: drain Nextion + USB serial input every pass. On each `TX_HZ` (100)
tick: sticks → IMU → radio link status → RemoteState (smoothers, tick: sticks → IMU → radio link status → battery → RemoteState (smoothers,
link-loss disarm) → PacketBuilder → `radio.write` → Nextion render. link-loss disarm, servo-trim read-back from telemetry) → PacketBuilder →
`radio.write` (+ read the ack payload's telemetry) → Nextion render.
| Module | Role | | Module | Role |
|--------|------| |--------|------|
| `remote.ino` | loop wiring, status print, packet dump | | `remote.ino` | loop wiring, status print, packet dump |
| `Config.h` | **all placeholder pins, calibration defaults, deadzones, rates** | | `Config.h` | **all placeholder pins, calibration defaults, deadzones, rates** |
| `UiTypes.h` | `UiCmd`/`UiEvent` (operator requests), `UiView` (what the display shows) | | `UiTypes.h` | `UiCmd`/`UiEvent` (operator requests), `UiPage` (HMI page ids), `UiView` (what the display shows, incl. robot telemetry) |
| `Sticks` | 6 analog axes: ADC averaging + IIR, piecewise calibration around center, invert, deadzone with rescale, expo → ±1000. Boot-time center capture, sweep calibration saved to EEPROM (magic/version/checksum) | | `Sticks` | 6 analog axes: ADC averaging + IIR, piecewise calibration around center, invert, deadzone with rescale, expo → ±1000. Boot-time center capture, sweep calibration saved to EEPROM (magic/version/checksum) |
| `RemoteIMU` | MPU6050, same complementary filter as the robot, axis remap for mounting, boot gyro-bias capture, "level" zero | | `RemoteIMU` | MPU6050, same complementary filter as the robot, axis remap for mounting, boot gyro-bias capture, "level" zero |
| `RemoteState` | authoritative operator state and interlocks: arm needs centered sticks, disarm clears stand, stand needs armed, calibrate needs disarmed, link-loss auto-disarm. Smooths speed scale and fades remote tilt in/out | | `RemoteState` | authoritative operator state and interlocks: arm needs centered sticks, disarm clears stand, stand needs armed, calibrate needs disarmed, link-loss auto-disarm. Smooths speed scale and fades remote tilt in/out. Servo calibration: only while disarmed and on the CAL page; a newly selected servo is `CAL_HOLD` until its trim has been read back from telemetry, then `CAL_SET`; SAVE/REVERT go out for 300 ms. UPDATE DISPLAY needs a second tap |
| `PacketBuilder` | the inverse of InputMapper: stick frame → body frame per the contract, per-submode right-stick mapping, `FLAG_WALK` with 250 ms linger (twist ignored in mode B), tilt deadzone/scale × fade, zeros motion when disarmed | | `PacketBuilder` | the inverse of InputMapper: stick frame → body frame per the contract, per-submode right-stick mapping, `FLAG_WALK` with 250 ms linger (twist ignored in mode B), tilt deadzone/scale × fade, zeros motion when disarmed |
| `RadioLink` | nRF24 TX, short retries (1, 3), ack-based link status and 32-packet quality % | | `RadioLink` | nRF24 TX, short retries (1, 3), ack-based link status and 32-packet quality %, telemetry from the ack payloads (stale after `TELEMETRY_STALE_MS`) |
| `NextionUI` | library-free Nextion driver on `Serial1`. HMI sends `'#' len cmd [val]` frames via `printh`. Remote pushes state by component name, as `control.<name>` (the owner adds a `control` page with vscope-global components to the old HMI), with diffing, a 2 s full refresh, and a redraw on the Nextion 0x88 "ready" frame. Also writes the old HMI's `t1` status texts (`NEXTION_STATUS_TEXTS`). The old page-1 `b2` sends a standard 0x65 touch frame, which triggers `runUploadPassthrough()`: USB ↔ display bridge for Nextion Editor, following `Serial.baud()`, never returns. Serial key `U` does the same | | `Battery` | handset battery through a divider; `BATTERY_SENSE_PIN` 255 = not wired yet (planned A6) |
| `NextionUI` | library-free Nextion driver on `Serial2` (pins 7/8). HMI sends `'#' len cmd [val]` frames via `printh`; every page's Preinitialize sends `'P'` + page id (and `sendme` / 0x66 recovers the page after a remote restart). The remote writes **only the showing page**, by local component name, and only what changed (FNV hash per instruction in a per-page slot cache), 20 Hz (SERVOS 10 Hz), never blocking on a full TX buffer; full refresh every 2 s and on the 0x88 "ready" frame. UPDATE DISPLAY (tapped twice) or serial `U` runs `runUploadPassthrough()`: USB ↔ display bridge for Nextion Editor, following `Serial.baud()`, never returns |
| `SerialConsole` | USB keystrokes that mirror every UI command plus diagnostics | | `SerialConsole` | USB keystrokes that mirror every UI command plus diagnostics |
| `SmoothedValue.h` | copy of the robot's (kept separate so robot/ stays untouched) | | `SmoothedValue.h` | copy of the robot's (kept separate so robot/ stays untouched) |
| `NEXTION.md` | HMI build guide: component names, txt_maxl, touch event code | | `NEXTION.md` | the HMI: pages, command bytes, which components the firmware writes |
| `remote.HMI` | **generated** by `scripts/make_remote_hmi.py` (pages splash, drive, status, servos, cal, setup, upload; tabs + top bar with DISARM). Change the layout in the script, not in the Editor |
Remote stick-frame convention: logical X + = right, Y + = forward, twist + Remote stick-frame convention: logical X + = right, Y + = forward, twist +
= CCW. The mapping into the packet is in `PacketBuilder.cpp` (e.g. = CCW. The mapping into the packet is in `PacketBuilder.cpp` (e.g.
@@ -166,8 +191,10 @@ Remote stick-frame convention: logical X + = right, Y + = forward, twist +
`Knie.x = −(tibia + 90)`. `Knie.x = −(tibia + 90)`.
- **Unity (`Assets/HexapodSim/`):** - **Unity (`Assets/HexapodSim/`):**
- `HexapodSimBootstrap` auto-adds `HexapodSimulation` in any scene and - `HexapodSimBootstrap` auto-adds `HexapodSimulation` in any scene and
disables the old scripts (`Walk`, `RotationControl`, `Leg`, disables the old scripts (`Walk`, `RotationControl`, `Leg`). Those are
`HandleHoystick`). Those are kept for reference only. kept for reference only. The old USB serial / joystick scripts
(`Serial*`, `HandleHoystick`) were removed (owner, 2026-11-17: no USB
links to remote or robot any more, everything goes over the radio).
- `OpenScadModel` replaces the old scene's robot with the OpenSCAD model - `OpenScadModel` replaces the old scene's robot with the OpenSCAD model
(meshes from `hardware/openscad/export_unity.py` in (meshes from `hardware/openscad/export_unity.py` in
`Resources/OpenScadModel/`): it builds a new rig with the same names at `Resources/OpenScadModel/`): it builds a new rig with the same names at
@@ -176,9 +203,16 @@ Remote stick-frame convention: logical X + = right, Y + = forward, twist +
- `HexapodSimNative` loads a temp copy of the DLL via - `HexapodSimNative` loads a temp copy of the DLL via
LoadLibrary/GetProcAddress, so there's no file lock and each Play is a LoadLibrary/GetProcAddress, so there's no file lock and each Play is a
fresh power-on. fresh power-on.
- `SimRemote` stands in for the remote (Joystick axes "1"–"6" as in the - `SimRemote` has two sources. **Keyboard** stands in for the remote and
old project, Keyboard, or the robot's own serial harness) and mirrors mirrors `remote/PacketBuilder.cpp` + `RemoteState.cpp` rules (keep them
`remote/PacketBuilder.cpp` + `RemoteState.cpp` rules. Keep them in sync. in sync). **Real remote** takes the real remote's packets over the air
from the USB nRF24 dongle (`DongleLink.cs`, the dongle's bridge mode,
see `dongle/README.md`), feeds them to the firmware unchanged
(`HexapodSimNative.RadioSend(byte[])`) and returns the robot's
telemetry as the ack payload, so the remote's display shows the sim.
`DongleLink` opens the port through kernel32 (no `System.IO.Ports`),
auto-finds the CH340 (VID 1A86 PID 7523), and does all port I/O on one
background thread.
- `SimTestPanel` is the IMGUI panel (F1). - `SimTestPanel` is the IMGUI panel (F1).
- Body motion is kinematic and lives **in the DLL** (`sim/SimBody.cpp`, - Body motion is kinematic and lives **in the DLL** (`sim/SimBody.cpp`,
`hxsim_get_body`), so Unity shows exactly what `sim_smoke` checks. `hxsim_get_body`), so Unity shows exactly what `sim_smoke` checks.
@@ -203,8 +237,11 @@ Remote stick-frame convention: logical X + = right, Y + = forward, twist +
stand → walk. The harness does not exercise the right stick or remote stand → walk. The harness does not exercise the right stick or remote
tilt. Add keys if needed. tilt. Add keys if needed.
- **Robot firmware in simulation:** `sim/build/sim_smoke.exe` (headless, - **Robot firmware in simulation:** `sim/build/sim_smoke.exe` (headless,
scripted checks), or Unity Play mode with Keyboard / Joystick / Robot scripted checks), or Unity Play mode with Keyboard input or the real
serial input. remote over the radio (USB nRF24 dongle).
- **Remote without robot:** the Unity sim behind the USB nRF24 dongle
answers like the robot (telemetry, servo calibration), see
`sim/README.md`.
- **Remote without robot or display:** the USB serial console (see - **Remote without robot or display:** the USB serial console (see
`remote/README.md`). `p` shows raw/mapped sticks, IMU, link and state. `remote/README.md`). `p` shows raw/mapped sticks, IMU, link and state.
`d` dumps packets at 10 Hz. With no robot, the link shows DOWN and `d` dumps packets at 10 Hz. With no robot, the link shows DOWN and
@@ -235,7 +272,7 @@ Robot (`robot/README.md` has detail):
limits now in `Config.h`: coxa limits are **per leg** limits now in `Config.h`: coxa limits are **per leg**
(`COXA_MIN_DEG[i]`/`COXA_MAX_DEG[i]`; all ±60 in the hexagon layout, but in (`COXA_MIN_DEG[i]`/`COXA_MAX_DEG[i]`; all ±60 in the hexagon layout, but in
the old sideways layout a corner leg only swung ~36° towards its mid leg), the old sideways layout a corner leg only swung ~36° towards its mid leg),
and `LEG_CLEARANCE_MM` is 56 (a leg is 55.2 mm wide at the joints). The sim API exports the per-leg coxa limits (version 7). and `LEG_CLEARANCE_MM` is 56 (a leg is 55.2 mm wide at the joints). The sim API exports the per-leg coxa limits (version 7). Version 8 adds `hxsim_get_ack_payload` (the robot's telemetry); sim_smoke checks telemetry and every `CAL_*` command.
- **Fixed (owner-approved):** the `Kinematics.cpp` femur elevation sign - **Fixed (owner-approved):** the `Kinematics.cpp` femur elevation sign
(`atan2(local_z, horiz)`; it used to solve for a foot above the hip, so (`atan2(local_z, horiz)`; it used to solve for a foot above the hip, so
every solution was invalid). Stance pose is now femur −1.2°, tibia every solution was invalid). Stance pose is now femur −1.2°, tibia
@@ -365,22 +402,35 @@ Robot (`robot/README.md` has detail):
Remote (`remote/README.md` has detail): Remote (`remote/README.md` has detail):
- Pins in `remote/Config.h`, taken from the old remote sketch: radio CE 9 / - Pins in `remote/Config.h`, taken from the old remote sketch: radio CE 9 /
CSN 10, sticks A0–A5, Nextion on Serial1 (0/1). The MPU6050 is on CSN 10, Nextion on **Serial2 (7/8)**, confirmed on the real remote. Owner's choice
**Wire2 (25/24, solder pads under the Teensy 4.0)**, since A4/A5 = Wire's SDA/SCL are stick pins; that's (2026-11-17): edge headers only, no pads underneath. So the MPU6050 is on **Wire (18/19)**
the owner's choice and needs rewiring the MPU. Which stick axis is on and the two stick wires that were on A4/A5 (18/19) move to **A7/A8 (21/22)**: sticks
which pin is still unknown. `{ A0, A1, A2, A3, A7, A8 }`. A6 (20) is kept for the battery divider. Checked on the real
remote (2026-11-17): left stick X/Y/twist = A3/A7/A8, right = A0/A1/A2, all inverted but the
right twist; each stick only moves about ±700 counts from centre, so run the sweep
calibration. The IMU axis defaults are right. Its MPU6050 (likely a clone) reads all zeros
until it gets a full device reset, so `RemoteIMU::begin()` resets it first. `RobotIMU` only
wakes its chip (owner-verified code, not changed): check the robot's IMU once it's flashed.
- `STICK_INVERT[]`, calibration defaults, deadzones, expo. - `STICK_INVERT[]`, calibration defaults, deadzones, expo.
- `IMU_AXIS_FROM_CHIP` / `IMU_AXIS_SIGN` depend on how the MPU6050 is
mounted in the handset.
- The Nextion must have `bauds=115200` in Program.s, and the HMI must match - The Nextion must have `bauds=115200` in Program.s, and the HMI must match
`NEXTION.md`. The owner's old 6-page HMI is in `../2019-teensy-nrf24/remote-nextion/remote.HMI`; `NEXTION.md`. The working HMI is `remote/remote.HMI`, generated by
its component names aren't readable outside Nextion Editor. The compiled `scripts/make_remote_hmi.py` (owner-approved design, 2026-11-17; the old 6-page one in
`.tft` is gitignored. `../2019-teensy-nrf24/remote-nextion/` only lends its splash picture). It's on the real
display (turned 180°, see `remote/NEXTION.md`). Edit and render it with the `nxhmi` MCP server
(registered in the repo root `.mcp.json`; code is the git submodule `tools/nextion-hmi-tools`,
run `git submodule update --init` after cloning; CLI `python -m nxhmi` with `PYTHONPATH` =
`tools/nextion-hmi-tools/src`): `info`, `get_page`, `render_page`, `set_attributes`,
`set_event`, `add_component`, `add_page`, `verify`, `build_tft`. Its `.tft` builder is
partial and needs the Nextion firmware files, which aren't in the submodule (they're kept
locally in `D:\Claude\nextion-hmi-tools\firmware`), so compile the upload `.tft` in Nextion
Editor. The compiled `.tft` is gitignored.
- What the old remote sketch (`../2019-teensy-nrf24/remote/`, last ran on a - What the old remote sketch (`../2019-teensy-nrf24/remote/`, last ran on a
Teensy) tells us about the real hardware: Teensy) tells us about the real hardware:
- **Nextion on `Serial1` (pins 0/1)**, driven by the ITEAD Nextion - **Nextion on `Serial2` (pins 7/8)**, driven by the ITEAD Nextion
library, whose `nexInit()` runs at 9600. `remote/Config.h` now uses library (its `nexSerial` is Serial2). The sketch's `Serial1.begin()` and
Serial1 and expects 115200 via `bauds=` in the HMI. its USB ↔ Serial1 passthrough never reached the display: a probe on the
real remote (2026-11-17) got `comok` only on Serial2, at 115200.
`remote/Config.h` uses Serial2 at 115200 (`bauds=` in the HMI).
- The old HMI is a *servo monitor*, not the control UI in `NEXTION.md`: - The old HMI is a *servo monitor*, not the control UI in `NEXTION.md`:
- page 1: `t1` "connected"/"not connected", and `b2` = enter - page 1: `t1` "connected"/"not connected", and `b2` = enter
upload mode; upload mode;
@@ -388,15 +438,16 @@ Remote (`remote/README.md` has detail):
`t1` status; `t1` status;
- page 4: `uploadscreen`. - page 4: `uploadscreen`.
None of the arm/stand/gait/mode/gyro/speed/height controls exist yet. It had none of the arm/stand/gait/mode/gyro/speed/height controls.
The owner chose to add a `control` page per `NEXTION.md`. It was replaced by the generated tabbed HMI (see above).
- `b2` → **Nextion upload passthrough**: shows `uploadscreen`, then - `b2` → **Nextion upload passthrough**: shows `uploadscreen`, then
bridges USB ↔ Serial1 forever, so Nextion Editor can upload a `.tft` bridges USB ↔ the display serial forever, so Nextion Editor can upload a `.tft`
through the remote's USB port. The new firmware keeps this. through the remote's USB port. The new firmware keeps this as SETUP ›
UPDATE DISPLAY (page `upload`).
- Sticks on **A0–A5**, contiguous (`analogInPin + i`). On the Teensy 4.0, - Sticks on **A0–A5**, contiguous (`analogInPin + i`). On the Teensy 4.0,
A4/A5 are pins 18/19 = Wire SDA/SCL, which the MPU6050 needs. The old A4/A5 are pins 18/19 = Wire SDA/SCL, which the MPU6050 needs. The old
code had the MPU code disabled (`if (false)`). Owner's decision: keep code had the MPU code disabled (`if (false)`). Owner's decision: MPU on
the sticks, move the MPU to Wire2. Wire (18/19), those two stick wires move to A7/A8 (21/22).
- nRF24 on CE 9 / CSN 10, the same as `remote/Config.h`. It used - nRF24 on CE 9 / CSN 10, the same as `remote/Config.h`. It used
RF24Network on channel 90, which the new protocol doesn't. RF24Network on channel 90, which the new protocol doesn't.
- Stick calibration was a 10 s min/max sweep saved to EEPROM, output - Stick calibration was a 10 s min/max sweep saved to EEPROM, output
@@ -404,9 +455,6 @@ Remote (`remote/README.md` has detail):
- USB serial at 250000. It received 18 servo bytes + checksum + `0xFE` - USB serial at 250000. It received 18 servo bytes + checksum + `0xFE`
from the old Unity `Serial.cs` (servo passthrough, forwarded over RF from the old Unity `Serial.cs` (servo passthrough, forwarded over RF
to the robot) and printed `i_value,...` stick lines. to the robot) and printed `i_value,...` stick lines.
- The Unity remote stand-in's joystick axis assignment (which of axes 4/6
is forward) couldn't be recovered from the old code. Check it with the
panel's raw-axis readout.
- Radio retry timing (`RADIO_RETRY_*`) is untested under real link loss. - Radio retry timing (`RADIO_RETRY_*`) is untested under real link loss.
## Working rules for this repo ## Working rules for this repo
@@ -424,7 +472,8 @@ Remote (`remote/README.md` has detail):
with BENCH comments for anything hardware-dependent, `SmoothedValue` with BENCH comments for anything hardware-dependent, `SmoothedValue`
rate limiting on any setpoint that can jump, and paired `.h/.cpp` per rate limiting on any setpoint that can jump, and paired `.h/.cpp` per
concern. concern.
- Planned or possible next steps: an ack-payload telemetry channel from - Planned or possible next steps: wire the battery dividers (firmware is
robot → remote (state, battery, link) to show real robot state on the ready on both sides, pins still 255) and add a low-battery warning;
Nextion, battery monitoring on both sides, a `.HMI` file checked into flash the robot with protocol v4 and try telemetry and servo calibration
`remote/`. with it (the real remote ↔ dongle ↔ Unity sim path already works over the
air, 2026-11-17); Unity driving the real robot through the dongle.
@@ -0,0 +1,256 @@
using System;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace HexapodSim
{
// The USB nRF24 dongle (2026-current/dongle/) in bridge mode: it stands in for
// the robot's radio. Every packet the real remote sends comes in here; the
// simulated robot's Telemetry goes back out as the radio's ack payload, so the
// remote and its display see the simulation exactly like the real robot.
//
// Wire format both ways: A5 type len payload[len] sum (sum = type+len+payload).
// to dongle 'L' listen (bridge on), 'X' stop, 'A' ack payload (<= 32 B)
// from dongle 'R' received packet, 'S' status (packets u16, acks loaded u16)
// The dongle drops the ack payload if it isn't refreshed for ~0.5 s.
//
// Windows only (the dev PC): the port is opened through kernel32, so there's
// no dependency on System.IO.Ports or the project's API compatibility level.
public sealed class DongleLink : IDisposable
{
public string PortName { get; private set; }
public bool IsOpen => handle_ != IntPtr.Zero && handle_ != InvalidHandle;
public string Error { get; private set; }
public int DonglePacketsPerSec { get; private set; } // from the dongle's status frame
public int DongleAcksPerSec { get; private set; }
public int BadFrames { get; private set; }
readonly ConcurrentQueue<byte[]> packets_ = new ConcurrentQueue<byte[]>();
byte[] pendingAck_; // newest telemetry frame, written by the I/O thread
IntPtr handle_ = IntPtr.Zero;
Thread io_;
volatile bool running_;
// ---- Opening ----
// "auto" = the first USB-serial CH340 port Windows knows about (the dongle's
// CH330N shows up as VID 1A86 / PID 7523); otherwise e.g. "COM7".
public static DongleLink Open(string port)
{
var link = new DongleLink();
string name = port;
if (string.IsNullOrEmpty(name) || name.Equals("auto", StringComparison.OrdinalIgnoreCase))
{
name = FindCh340Port();
if (name == null) { link.Error = "no USB nRF24 dongle (CH340, VID 1A86 PID 7523) found"; return link; }
}
link.PortName = name;
link.OpenPort(name);
if (link.IsOpen)
{
link.Write(Frame((byte)'L', null, 0));
link.running_ = true;
link.io_ = new Thread(link.IoLoop) { IsBackground = true, Name = "DongleLink" };
link.io_.Start();
}
return link;
}
void OpenPort(string name)
{
// Retry briefly: SignalRGB and similar tools grab CH340 ports on enumeration.
for (int attempt = 0; attempt < 25; attempt++)
{
handle_ = CreateFile(@"\\.\" + name, GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (handle_ != InvalidHandle) break;
Thread.Sleep(20);
}
if (handle_ == InvalidHandle)
{
Error = $"can't open {name} (Win32 error {Marshal.GetLastWin32Error()}; is SignalRGB or a serial monitor holding it?)";
handle_ = IntPtr.Zero;
return;
}
var dcb = new DCB { DCBlength = (uint)Marshal.SizeOf<DCB>() };
GetCommState(handle_, ref dcb);
dcb.BaudRate = 115200;
dcb.ByteSize = 8;
dcb.Parity = 0;
dcb.StopBits = 0;
dcb.Flags = 0x0001 | 0x0010; // fBinary, fDtrControl = DTR_CONTROL_ENABLE
SetCommState(handle_, ref dcb);
// Reads return within ~3 ms, so queued telemetry goes out promptly
// (reads and writes on one handle take turns: both run on the I/O thread).
var to = new COMMTIMEOUTS { ReadIntervalTimeout = 1, ReadTotalTimeoutConstant = 3, WriteTotalTimeoutConstant = 200 };
SetCommTimeouts(handle_, ref to);
PurgeComm(handle_, 0x0004 | 0x0008); // RXCLEAR | TXCLEAR
}
public void Dispose()
{
running_ = false;
io_?.Join(300);
if (IsOpen)
{
Write(Frame((byte)'X', null, 0)); // bridge off: the remote sees the link drop
CloseHandle(handle_);
}
handle_ = IntPtr.Zero;
}
// ---- Traffic ----
public bool TryTakePacket(out byte[] packet) => packets_.TryDequeue(out packet);
// Queues the robot's telemetry for the ack of the remote's next packet.
// Only the newest one matters, so an unsent older one is replaced.
public void SendAckPayload(byte[] data, int len)
{
if (len <= 32) Volatile.Write(ref pendingAck_, Frame((byte)'A', data, len));
}
static byte[] Frame(byte type, byte[] data, int len)
{
var f = new byte[4 + len];
f[0] = 0xA5; f[1] = type; f[2] = (byte)len;
int sum = type + len;
for (int i = 0; i < len; i++) { f[3 + i] = data[i]; sum += data[i]; }
f[3 + len] = (byte)sum;
return f;
}
bool Write(byte[] f)
{
if (WriteFile(handle_, f, (uint)f.Length, out _, IntPtr.Zero)) return true;
Error = $"write failed (Win32 error {Marshal.GetLastWin32Error()}): dongle unplugged?";
return false;
}
void IoLoop()
{
var chunk = new byte[512];
var buf = new byte[4096];
int have = 0;
while (running_)
{
byte[] ack = Interlocked.Exchange(ref pendingAck_, null);
if (ack != null && !Write(ack)) break;
if (!ReadFile(handle_, chunk, (uint)chunk.Length, out uint got, IntPtr.Zero))
{
if (running_) Error = $"read failed (Win32 error {Marshal.GetLastWin32Error()}): dongle unplugged?";
break;
}
if (got == 0) continue;
if (have + got > buf.Length) have = 0; // garbage flood: start over
Buffer.BlockCopy(chunk, 0, buf, have, (int)got);
have += (int)got;
have = ParseFrames(buf, have);
}
}
// Consumes complete frames from buf[0..len), returns how many bytes remain.
int ParseFrames(byte[] buf, int len)
{
int i = 0;
while (true)
{
while (i < len && buf[i] != 0xA5) i++; // skip text between frames
if (len - i < 4) break;
byte type = buf[i + 1], n = buf[i + 2];
if (n > 32) { i++; continue; }
if (len - i < 4 + n) break;
int sum = type + n;
for (int k = 0; k < n; k++) sum += buf[i + 3 + k];
if ((byte)sum != buf[i + 3 + n]) { BadFrames++; i++; continue; }
var payload = new byte[n];
Buffer.BlockCopy(buf, i + 3, payload, 0, n);
i += 4 + n;
if (type == 'R') packets_.Enqueue(payload);
else if (type == 'S' && n >= 4)
{
DonglePacketsPerSec = payload[0] | payload[1] << 8;
DongleAcksPerSec = payload[2] | payload[3] << 8;
}
}
int rest = len - i;
if (rest > 0 && i > 0) Buffer.BlockCopy(buf, i, buf, 0, rest);
return rest;
}
// ---- Finding the port: HKLM\SYSTEM\CurrentControlSet\Enum\USB\VID_1A86&PID_7523\<inst>\Device Parameters\PortName ----
static string FindCh340Port()
{
const string baseKey = @"SYSTEM\CurrentControlSet\Enum\USB\VID_1A86&PID_7523";
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, baseKey, 0, KEY_READ, out IntPtr key) != 0) return null;
try
{
var sb = new StringBuilder(256);
for (uint idx = 0; ; idx++)
{
uint len = (uint)sb.Capacity;
if (RegEnumKeyEx(key, idx, sb, ref len, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) != 0) break;
string port = ReadString(HKEY_LOCAL_MACHINE, baseKey + "\\" + sb + "\\Device Parameters", "PortName");
if (port != null && PortExists(port)) return port;
}
}
finally { RegCloseKey(key); }
return null;
}
static string ReadString(IntPtr root, string path, string value)
{
var data = new StringBuilder(64);
uint size = (uint)(data.Capacity * 2);
return RegGetValue(root, path, value, RRF_RT_REG_SZ, IntPtr.Zero, data, ref size) == 0 ? data.ToString() : null;
}
static bool PortExists(string name) => QueryDosDevice(name, new StringBuilder(256), 256) != 0;
// ---- Win32 ----
static readonly IntPtr InvalidHandle = new IntPtr(-1);
static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002));
const uint GENERIC_READ = 0x80000000, GENERIC_WRITE = 0x40000000, OPEN_EXISTING = 3;
const int KEY_READ = 0x20019;
const uint RRF_RT_REG_SZ = 0x00000002;
[StructLayout(LayoutKind.Sequential)]
struct DCB
{
public uint DCBlength, BaudRate, Flags;
public ushort wReserved, XonLim, XoffLim;
public byte ByteSize, Parity, StopBits;
public sbyte XonChar, XoffChar, ErrorChar, EofChar, EvtChar;
public ushort wReserved1;
}
[StructLayout(LayoutKind.Sequential)]
struct COMMTIMEOUTS
{
public uint ReadIntervalTimeout, ReadTotalTimeoutMultiplier, ReadTotalTimeoutConstant,
WriteTotalTimeoutMultiplier, WriteTotalTimeoutConstant;
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern IntPtr CreateFile(string name, uint access, uint share, IntPtr sec, uint disposition, uint flags, IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr h);
[DllImport("kernel32.dll", SetLastError = true)] static extern bool GetCommState(IntPtr h, ref DCB dcb);
[DllImport("kernel32.dll", SetLastError = true)] static extern bool SetCommState(IntPtr h, ref DCB dcb);
[DllImport("kernel32.dll", SetLastError = true)] static extern bool SetCommTimeouts(IntPtr h, ref COMMTIMEOUTS t);
[DllImport("kernel32.dll", SetLastError = true)] static extern bool PurgeComm(IntPtr h, uint flags);
[DllImport("kernel32.dll", SetLastError = true)] static extern bool ReadFile(IntPtr h, byte[] buf, uint n, out uint got, IntPtr ov);
[DllImport("kernel32.dll", SetLastError = true)] static extern bool WriteFile(IntPtr h, byte[] buf, uint n, out uint put, IntPtr ov);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern uint QueryDosDevice(string device, StringBuilder target, int max);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
static extern int RegOpenKeyEx(IntPtr key, string sub, int options, int sam, out IntPtr result);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
static extern int RegEnumKeyEx(IntPtr key, uint index, StringBuilder name, ref uint nameLen, IntPtr reserved, IntPtr cls, IntPtr clsLen, IntPtr lastWrite);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
static extern int RegGetValue(IntPtr key, string sub, string value, uint flags, IntPtr type, StringBuilder data, ref uint size);
[DllImport("advapi32.dll")] static extern int RegCloseKey(IntPtr key);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d16e6c95081705a4788b93525709e796
@@ -14,7 +14,10 @@ namespace HexapodSim
public short rx, ry, rz; public short rx, ry, rz;
public short remote_roll, remote_pitch; public short remote_roll, remote_pitch;
public short body_height; // -1000 lowest .. 0 default .. 1000 highest public short body_height; // -1000 lowest .. 0 default .. 1000 highest
public short cal_value; // servo centre calibration (remote only; 0 here)
public byte speed_scale, flags, seq; public byte speed_scale, flags, seq;
public byte cal_cmd; // CAL_NONE (0): the sim's remote never calibrates servos
public byte cal_servo;
public const byte FLAG_ARMED = 1 << 0; public const byte FLAG_ARMED = 1 << 0;
public const byte FLAG_STAND = 1 << 1; public const byte FLAG_STAND = 1 << 1;
@@ -73,7 +76,7 @@ namespace HexapodSim
// "Reload firmware" and the new code runs. Each load is a fresh power-on. // "Reload firmware" and the new code runs. Each load is a fresh power-on.
public sealed class HexapodSimNative : IDisposable public sealed class HexapodSimNative : IDisposable
{ {
public const int ExpectedApiVersion = 7; // HXSIM_API_VERSION public const int ExpectedApiVersion = 8; // HXSIM_API_VERSION
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int IntFn(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int IntFn();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void VoidFn(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void VoidFn();
@@ -88,6 +91,7 @@ namespace HexapodSim
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void ServosFn(int[] us, int[] attached, uint[] writes); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void ServosFn(int[] us, int[] attached, uint[] writes);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void FloatsFn(float[] values); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void FloatsFn(float[] values);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void TwoFloatsFn(float a, float b); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void TwoFloatsFn(float a, float b);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int AckFn(byte[] bytes, int cap);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void BodyFn(float[] pos3, float[] quatWxyz4, out float yawDeg, out int contactMask); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void BodyFn(float[] pos3, float[] quatWxyz4, out float yawDeg, out int contactMask);
IntPtr handle_; IntPtr handle_;
@@ -99,14 +103,15 @@ namespace HexapodSim
VoidFn start_; VoidFn start_;
UIntArgFn step_; UIntArgFn step_;
PacketFn radioSend_; PacketFn radioSend_;
BytesInFn radioSendBytes_;
ImuFn setImu_; ImuFn setImu_;
BytesInFn serialInput_;
BytesOutFn serialOutput_; BytesOutFn serialOutput_;
ServosFn getServos_; ServosFn getServos_;
FloatsFn getJoints_, getFeet_; FloatsFn getJoints_, getFeet_;
StatusFn getStatus_; StatusFn getStatus_;
TwoFloatsFn setGroundTilt_; TwoFloatsFn setGroundTilt_;
BodyFn getBody_; BodyFn getBody_;
AckFn getAckPayload_;
public string LoadedFrom { get; private set; } public string LoadedFrom { get; private set; }
@@ -137,8 +142,8 @@ namespace HexapodSim
n.start_ = n.Fn<VoidFn>("hxsim_start"); n.start_ = n.Fn<VoidFn>("hxsim_start");
n.step_ = n.Fn<UIntArgFn>("hxsim_step"); n.step_ = n.Fn<UIntArgFn>("hxsim_step");
n.radioSend_ = n.Fn<PacketFn>("hxsim_radio_send"); n.radioSend_ = n.Fn<PacketFn>("hxsim_radio_send");
n.radioSendBytes_ = n.Fn<BytesInFn>("hxsim_radio_send");
n.setImu_ = n.Fn<ImuFn>("hxsim_set_imu"); n.setImu_ = n.Fn<ImuFn>("hxsim_set_imu");
n.serialInput_ = n.Fn<BytesInFn>("hxsim_serial_input");
n.serialOutput_ = n.Fn<BytesOutFn>("hxsim_serial_output"); n.serialOutput_ = n.Fn<BytesOutFn>("hxsim_serial_output");
n.getServos_ = n.Fn<ServosFn>("hxsim_get_servos"); n.getServos_ = n.Fn<ServosFn>("hxsim_get_servos");
n.getJoints_ = n.Fn<FloatsFn>("hxsim_get_joints_deg"); n.getJoints_ = n.Fn<FloatsFn>("hxsim_get_joints_deg");
@@ -146,6 +151,7 @@ namespace HexapodSim
n.getStatus_ = n.Fn<StatusFn>("hxsim_get_status"); n.getStatus_ = n.Fn<StatusFn>("hxsim_get_status");
n.setGroundTilt_ = n.Fn<TwoFloatsFn>("hxsim_set_ground_tilt"); n.setGroundTilt_ = n.Fn<TwoFloatsFn>("hxsim_set_ground_tilt");
n.getBody_ = n.Fn<BodyFn>("hxsim_get_body"); n.getBody_ = n.Fn<BodyFn>("hxsim_get_body");
n.getAckPayload_ = n.Fn<AckFn>("hxsim_get_ack_payload");
int version = n.apiVersion_(); int version = n.apiVersion_();
if (version != ExpectedApiVersion) if (version != ExpectedApiVersion)
@@ -178,16 +184,24 @@ namespace HexapodSim
public void Start() => start_(); public void Start() => start_();
public void Step(uint dtMicros) => step_(dtMicros); public void Step(uint dtMicros) => step_(dtMicros);
public void RadioSend(CmdPacket p) => radioSend_(ref p, Marshal.SizeOf<CmdPacket>()); public void RadioSend(CmdPacket p) => radioSend_(ref p, Marshal.SizeOf<CmdPacket>());
// A packet exactly as it came over the air (the real remote, via the dongle).
// Any length: the firmware itself drops ones that aren't sizeof(CmdPacket).
public void RadioSend(byte[] bytes) => radioSendBytes_(bytes, bytes.Length);
// Decodes on-air bytes for display; false if the length doesn't match.
public static bool TryDecode(byte[] bytes, out CmdPacket p)
{
p = default;
if (bytes == null || bytes.Length != Marshal.SizeOf<CmdPacket>()) return false;
var h = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try { p = Marshal.PtrToStructure<CmdPacket>(h.AddrOfPinnedObject()); }
finally { h.Free(); }
return true;
}
// Overrides the body-driven IMU with fixed readings from then on (normally unused). // Overrides the body-driven IMU with fixed readings from then on (normally unused).
public void SetImu(Vector3 accelG, Vector3 gyroDps) => public void SetImu(Vector3 accelG, Vector3 gyroDps) =>
setImu_(accelG.x, accelG.y, accelG.z, gyroDps.x, gyroDps.y, gyroDps.z); setImu_(accelG.x, accelG.y, accelG.z, gyroDps.x, gyroDps.y, gyroDps.z);
public void SerialInput(string text)
{
if (string.IsNullOrEmpty(text)) return;
byte[] b = System.Text.Encoding.ASCII.GetBytes(text);
serialInput_(b, b.Length);
}
readonly byte[] serialBuf_ = new byte[4096]; readonly byte[] serialBuf_ = new byte[4096];
public string SerialOutput() public string SerialOutput()
@@ -205,6 +219,10 @@ namespace HexapodSim
readonly float[] bodyPos_ = new float[3], bodyQuat_ = new float[4]; readonly float[] bodyPos_ = new float[3], bodyQuat_ = new float[4];
// Kinematic body from the DLL, robot-world frame. The rotation is a // Kinematic body from the DLL, robot-world frame. The rotation is a
// robot-frame quaternion held in a Unity Quaternion for its math only. // robot-frame quaternion held in a Unity Quaternion for its math only.
// The robot's telemetry (HexapodProtocol.h Telemetry, 30 bytes) from the
// last ack payload; returns its length, 0 before the first packet.
public int GetAckPayload(byte[] buf) => getAckPayload_(buf, buf.Length);
public void GetBody(out Vector3 posMm, out Quaternion rotRobot, out float yawDeg, out int contactMask) public void GetBody(out Vector3 posMm, out Quaternion rotRobot, out float yawDeg, out int contactMask)
{ {
getBody_(bodyPos_, bodyQuat_, out yawDeg, out contactMask); getBody_(bodyPos_, bodyQuat_, out yawDeg, out contactMask);
@@ -81,7 +81,7 @@ namespace HexapodSim
StringBuilder serialLine_ = new StringBuilder(); StringBuilder serialLine_ = new StringBuilder();
static readonly string[] LegacyMovementScripts = static readonly string[] LegacyMovementScripts =
{ "Walk", "RotationControl", "Leg", "HandleHoystick", "Serial2", "Serial3" }; { "Walk", "RotationControl", "Leg" };
// Robot-frame axes, for readability (Unity's Vector3.up etc. are Unity axes). // Robot-frame axes, for readability (Unity's Vector3.up etc. are Unity axes).
static readonly Vector3 AxisX = new Vector3(1, 0, 0); // forward static readonly Vector3 AxisX = new Vector3(1, 0, 0); // forward
@@ -1,47 +1,28 @@
using System;
using UnityEngine; using UnityEngine;
namespace HexapodSim namespace HexapodSim
{ {
// Stand-in for the handheld remote. Produces CmdPackets exactly per the // Where the simulated robot's commands come from. Two sources:
// protocol contract and sends them over the simulated radio. Toggles and // Keyboard - a stand-in remote: builds CmdPackets per the protocol contract
// interlocks mirror remote/RemoteState.cpp and remote/PacketBuilder.cpp - // and sends them over the simulated radio. Toggles and
// keep them in sync if those change. // interlocks mirror remote/RemoteState.cpp and
// // remote/PacketBuilder.cpp - keep them in sync if those change.
// Input sources: // RealRemote - the real handheld remote, over the air: the USB nRF24 dongle
// Joystick - the real remote as a USB game controller, read through // (2026-current/dongle/, bridge mode) receives its packets, they
// Unity input axes "1".."6" like the old HandleHoystick. // go into the firmware unchanged, and the robot's Telemetry goes
// Keyboard - test without any remote (keys listed in SimTestPanel). // back as the radio's ack payload. The remote's display then
// RobotSerialHarness - no radio at all; typed keys go to the firmware's own // shows the simulated robot. Nothing about the remote is
// TEST_SERIAL_INPUT harness, like the Arduino Serial Monitor. // mirrored here: its own firmware does all of it.
// Toggles, the speed slider and the handset tilt sliders live in SimTestPanel. // Toggles, the speed slider and the handset tilt sliders live in SimTestPanel.
public class SimRemote : MonoBehaviour public class SimRemote : MonoBehaviour
{ {
public enum InputSource { Joystick, Keyboard, RobotSerialHarness } public enum InputSource { Keyboard, RealRemote }
[Serializable]
public class AxisBinding
{
public string axis;
public bool invert;
public AxisBinding(string axis, bool invert) { this.axis = axis; this.invert = invert; }
}
public InputSource source = InputSource.Keyboard; public InputSource source = InputSource.Keyboard;
// Defaults follow the old HandleHoystick: axes 4/6/5 were the walk stick [Header("Real remote (USB nRF24 dongle)")]
// (b2/b1/b3), 2/1/3 the rotation stick (a1/a2/a3), with 1 and 2 inverted. [Tooltip("\"auto\" finds the dongle's CH340 port; or e.g. COM7.")]
// Which of 4/6 is forward vs sideways wasn't recoverable from the old code: public string donglePort = "auto";
// check the raw axis readout in the test panel and fix here.
[Header("Joystick axes (Input Manager names)")]
[Tooltip("Stick convention after invert: X + = right, Y + = forward, twist + = counterclockwise.")]
public AxisBinding leftX = new AxisBinding("4", false);
public AxisBinding leftY = new AxisBinding("6", false);
public AxisBinding leftTwist = new AxisBinding("5", false);
public AxisBinding rightX = new AxisBinding("2", true);
public AxisBinding rightY = new AxisBinding("1", true);
public AxisBinding rightTwist = new AxisBinding("3", false);
[Range(0, 0.5f)] public float deadzone = 0.08f;
[Header("Operator state (same toggles as the Nextion screen)")] [Header("Operator state (same toggles as the Nextion screen)")]
public bool armed; public bool armed;
@@ -66,49 +47,61 @@ namespace HexapodSim
public float armCenterTolerance = 0.05f; // ARM_CENTER_TOLERANCE / 1000 public float armCenterTolerance = 0.05f; // ARM_CENTER_TOLERANCE / 1000
public float keyStickRatePerSec = 4f; // how fast a held key moves the virtual stick public float keyStickRatePerSec = 4f; // how fast a held key moves the virtual stick
// Latest processed sticks, -1..1: [L_X, L_Y, L_TWIST, R_X, R_Y, R_TWIST]. // Latest processed sticks, -1..1: [L_X, L_Y, L_TWIST, R_X, R_Y, R_TWIST] (keyboard).
public readonly float[] sticks = new float[6]; public readonly float[] sticks = new float[6];
public readonly float[] rawAxes = new float[6]; // Input axes "1".."6" as read
public CmdPacket LastPacket { get; private set; } public CmdPacket LastPacket { get; private set; }
public string Message { get; private set; } = ""; public string Message { get; private set; } = "";
public bool JoystickAxesMissing { get; private set; }
// Real remote, for the panel.
public DongleLink Dongle { get; private set; }
public int RemotePacketsPerSec { get; private set; }
public int LastPacketLength { get; private set; }
public float SecondsSinceRemotePacket => Time.time - lastRemotePacket_;
float speedCurrent_ = 128; float speedCurrent_ = 128;
float lastWalkInputTime_ = -999f; float lastWalkInputTime_ = -999f;
byte seq_; byte seq_;
string serialKeys_ = "";
float messageUntil_; float messageUntil_;
float lastRemotePacket_ = -999f;
int packetsThisSecond_;
float secondStart_;
readonly byte[] ack_ = new byte[32];
public void ResetState() public void ResetState()
{ {
armed = stand = false; armed = stand = false;
speedCurrent_ = speedTarget; speedCurrent_ = speedTarget;
lastWalkInputTime_ = -999f; lastWalkInputTime_ = -999f;
serialKeys_ = "";
}
void Awake()
{
if (Input.GetJoystickNames().Length > 0 && !string.IsNullOrEmpty(Input.GetJoystickNames()[0]))
source = InputSource.Joystick;
} }
void Update() void Update()
{ {
for (int i = 0; i < 6; i++) rawAxes[i] = ReadAxis((i + 1).ToString()); // Open the dongle while the real remote is selected, release it otherwise.
if (source == InputSource.RealRemote && Dongle == null) ConnectDongle();
else if (source != InputSource.RealRemote && Dongle != null) DisconnectDongle();
if (source == InputSource.RobotSerialHarness) if (source == InputSource.Keyboard)
{ {
serialKeys_ += Input.inputString; // raw keystrokes for the firmware's harness HandleToggleKeys();
return; ReadKeyboardSticks(Time.deltaTime);
} }
HandleToggleKeys();
if (source == InputSource.Joystick) ReadJoystick();
else ReadKeyboardSticks(Time.deltaTime);
if (Time.time > messageUntil_) Message = ""; if (Time.time > messageUntil_) Message = "";
} }
void OnDisable() => DisconnectDongle();
public void ConnectDongle()
{
DisconnectDongle();
Dongle = DongleLink.Open(donglePort);
}
public void DisconnectDongle()
{
Dongle?.Dispose();
Dongle = null;
}
// ---- Operator commands (also called by SimTestPanel buttons) ---- // ---- Operator commands (also called by SimTestPanel buttons) ----
public void ToggleArm() public void ToggleArm()
@@ -144,32 +137,6 @@ namespace HexapodSim
if (Input.GetKeyDown(KeyCode.PageDown)) height = Mathf.Max(-1000, height - 100); if (Input.GetKeyDown(KeyCode.PageDown)) height = Mathf.Max(-1000, height - 100);
} }
// ---- Sticks ----
float ReadAxis(string name)
{
try { return Input.GetAxis(name); }
catch (ArgumentException) { JoystickAxesMissing = true; return 0; } // axis not defined in Input Manager
}
float Read(AxisBinding b)
{
float v = ReadAxis(b.axis) * (b.invert ? -1 : 1);
float mag = Mathf.Abs(v);
if (mag <= deadzone) return 0;
return Mathf.Sign(v) * Mathf.Clamp01((mag - deadzone) / (1 - deadzone));
}
void ReadJoystick()
{
sticks[0] = Read(leftX);
sticks[1] = Read(leftY);
sticks[2] = Read(leftTwist);
sticks[3] = Read(rightX);
sticks[4] = Read(rightY);
sticks[5] = Read(rightTwist);
}
// WASD + Q/E = left stick (walk, turn), IJKL + U/O = right stick. // WASD + Q/E = left stick (walk, turn), IJKL + U/O = right stick.
void ReadKeyboardSticks(float dt) void ReadKeyboardSticks(float dt)
{ {
@@ -187,17 +154,36 @@ namespace HexapodSim
// Called by HexapodSimulation once per remote TX period. // Called by HexapodSimulation once per remote TX period.
public void Transmit(HexapodSimNative native, float dt) public void Transmit(HexapodSimNative native, float dt)
{ {
if (source == InputSource.RobotSerialHarness) if (source == InputSource.RealRemote) { ForwardRealRemote(native); return; }
{
native.SerialInput(serialKeys_); // no radio: the firmware's harness injects its own packets
serialKeys_ = "";
return;
}
speedCurrent_ = Mathf.MoveTowards(speedCurrent_, speedTarget, speedRatePerSec * dt); speedCurrent_ = Mathf.MoveTowards(speedCurrent_, speedTarget, speedRatePerSec * dt);
LastPacket = BuildPacket(); LastPacket = BuildPacket();
native.RadioSend(LastPacket); native.RadioSend(LastPacket);
} }
// Everything the dongle heard since last time goes into the firmware in
// order, and each packet's ack carries the telemetry the robot loaded in
// reply - the same exchange as on the real robot (robot/Comms.cpp).
void ForwardRealRemote(HexapodSimNative native)
{
if (Time.time - secondStart_ >= 1f)
{
RemotePacketsPerSec = packetsThisSecond_;
packetsThisSecond_ = 0;
secondStart_ = Time.time;
}
if (Dongle == null || !Dongle.IsOpen) return;
while (Dongle.TryTakePacket(out byte[] pkt))
{
native.RadioSend(pkt);
int n = native.GetAckPayload(ack_);
if (n > 0) Dongle.SendAckPayload(ack_, n);
LastPacketLength = pkt.Length;
if (HexapodSimNative.TryDecode(pkt, out var p)) LastPacket = p;
lastRemotePacket_ = Time.time;
packetsThisSecond_++;
}
}
static short Wire(float v) => (short)Mathf.RoundToInt(Mathf.Clamp(v, -1f, 1f) * 1000f); static short Wire(float v) => (short)Mathf.RoundToInt(Mathf.Clamp(v, -1f, 1f) * 1000f);
// Same mapping as remote/PacketBuilder.cpp. // Same mapping as remote/PacketBuilder.cpp.
@@ -208,6 +194,7 @@ namespace HexapodSim
seq = seq_++, seq = seq_++,
speed_scale = (byte)Mathf.RoundToInt(speedCurrent_), speed_scale = (byte)Mathf.RoundToInt(speedCurrent_),
body_height = (short)Mathf.Clamp(height, -1000, 1000), // a setting: sent even while disarmed body_height = (short)Mathf.Clamp(height, -1000, 1000), // a setting: sent even while disarmed
cal_servo = 0xFF, // CAL_NO_SERVO: never calibrates
}; };
byte f = 0; byte f = 0;
if (armed) f |= CmdPacket.FLAG_ARMED; if (armed) f |= CmdPacket.FLAG_ARMED;
@@ -16,7 +16,7 @@ namespace HexapodSim
Vector2 scroll_; Vector2 scroll_;
GUIStyle mono_; GUIStyle mono_;
static readonly string[] SourceNames = { "Joystick", "Keyboard", "Robot serial" }; static readonly string[] SourceNames = { "Keyboard", "Real remote (radio)" };
void Awake() void Awake()
{ {
@@ -35,8 +35,10 @@ namespace HexapodSim
if (mono_ == null) if (mono_ == null)
mono_ = new GUIStyle(GUI.skin.label) { font = Font.CreateDynamicFontFromOSFont("Consolas", 12), fontSize = 12, wordWrap = false }; mono_ = new GUIStyle(GUI.skin.label) { font = Font.CreateDynamicFontFromOSFont("Consolas", 12), fontSize = 12, wordWrap = false };
GUILayout.BeginArea(new Rect(10, 10, 390, Screen.height - 20), GUI.skin.box); GUILayout.BeginArea(new Rect(10, 10, 420, Screen.height - 20), GUI.skin.box);
scroll_ = GUILayout.BeginScrollView(scroll_); // Vertical scrolling only: the monospace lines run a little past the
// width, and a sideways bar for that is just noise.
scroll_ = GUILayout.BeginScrollView(scroll_, false, false, GUIStyle.none, GUI.skin.verticalScrollbar);
GUILayout.Label("<b>Hexapod firmware simulation</b> (F1 hides)", new GUIStyle(GUI.skin.label) { richText = true }); GUILayout.Label("<b>Hexapod firmware simulation</b> (F1 hides)", new GUIStyle(GUI.skin.label) { richText = true });
if (sim_.LoadError != null) if (sim_.LoadError != null)
@@ -65,18 +67,13 @@ namespace HexapodSim
// ---- Input source ---- // ---- Input source ----
GUILayout.Space(6); GUILayout.Space(6);
remote_.source = (SimRemote.InputSource)GUILayout.Toolbar((int)remote_.source, SourceNames); remote_.source = (SimRemote.InputSource)GUILayout.Toolbar((int)remote_.source, SourceNames);
if (remote_.source == SimRemote.InputSource.RobotSerialHarness) if (remote_.source == SimRemote.InputSource.RealRemote)
{ {
GUILayout.Label("Keys go to robot.ino's TEST_SERIAL_INPUT harness (no radio):\n" + DongleSection();
"a arm s sit/stand w/x fwd/back q/e strafe L/R\n" +
"z/c yaw g gait m mode space stop", mono_);
} }
else else
{ {
if (remote_.source == SimRemote.InputSource.Keyboard) GUILayout.Label("WASD walk Q/E turn IJKL + U/O right stick\n1 arm 2 stand 3 gait 4 mode 5 R-stick 6/7 gyros\nBackspace disarm +/- speed PgUp/PgDn height", mono_);
GUILayout.Label("WASD walk Q/E turn IJKL + U/O right stick\n1 arm 2 stand 3 gait 4 mode 5 R-stick 6/7 gyros\nBackspace disarm +/- speed PgUp/PgDn height", mono_);
if (remote_.source == SimRemote.InputSource.Joystick && remote_.JoystickAxesMissing)
GUILayout.Label("Input axes \"1\"..\"6\" are missing from the Input Manager.");
// ---- Toggles: same set as the remote's touchscreen ---- // ---- Toggles: same set as the remote's touchscreen ----
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
@@ -116,11 +113,10 @@ namespace HexapodSim
// ---- Live values ---- // ---- Live values ----
GUILayout.Space(6); GUILayout.Space(6);
var st = remote_.sticks; var st = remote_.sticks;
var raw = remote_.rawAxes;
var p = remote_.LastPacket; var p = remote_.LastPacket;
GUILayout.Label( GUILayout.Label(
$"sticks L {st[0],5:F2} {st[1],5:F2} {st[2],5:F2} R {st[3],5:F2} {st[4],5:F2} {st[5],5:F2}\n" + (remote_.source == SimRemote.InputSource.Keyboard
$"axes 1-6 {raw[0],5:F2} {raw[1],5:F2} {raw[2],5:F2} {raw[3],5:F2} {raw[4],5:F2} {raw[5],5:F2}\n" + ? $"sticks L {st[0],5:F2} {st[1],5:F2} {st[2],5:F2} R {st[3],5:F2} {st[4],5:F2} {st[5],5:F2}\n" : "") +
$"packet #{p.seq,3} vx {p.vx,5} vy {p.vy,5} yaw {p.yaw_rate,5}\n" + $"packet #{p.seq,3} vx {p.vx,5} vy {p.vy,5} yaw {p.yaw_rate,5}\n" +
$" r {p.rx,5} {p.ry,5} {p.rz,5} tilt {p.remote_roll,5} {p.remote_pitch,5}\n" + $" r {p.rx,5} {p.ry,5} {p.rz,5} tilt {p.remote_roll,5} {p.remote_pitch,5}\n" +
$" height {p.body_height,5} speed {p.speed_scale,3} flags {System.Convert.ToString(p.flags, 2).PadLeft(8, '0')}", $" height {p.body_height,5} speed {p.speed_scale,3} flags {System.Convert.ToString(p.flags, 2).PadLeft(8, '0')}",
@@ -136,6 +132,36 @@ namespace HexapodSim
GUILayout.EndArea(); GUILayout.EndArea();
} }
// The real remote drives the simulation over the air through the USB dongle;
// every control is on the remote itself, so this only shows the link.
void DongleSection()
{
var d = remote_.Dongle;
var rich = new GUIStyle(GUI.skin.label) { richText = true, wordWrap = true };
GUILayout.BeginHorizontal();
GUILayout.Label("dongle port", GUILayout.Width(80));
remote_.donglePort = GUILayout.TextField(remote_.donglePort, GUILayout.Width(70));
if (GUILayout.Button("Reconnect")) remote_.ConnectDongle();
GUILayout.EndHorizontal();
if (d == null) { GUILayout.Label("connecting..."); return; }
if (!d.IsOpen || d.Error != null)
{
GUILayout.Label("<color=#ff6060>" + (d.Error ?? "not open") + "</color>", rich);
if (!d.IsOpen) return;
}
float age = remote_.SecondsSinceRemotePacket;
string link = age < 0.5f ? "<color=#60ff60>receiving</color>" : "<color=#ffb040>no packets - is the remote on?</color>";
GUILayout.Label(
$"{d.PortName}: {link}\n" +
$"remote {remote_.RemotePacketsPerSec} pkt/s here, dongle {d.DonglePacketsPerSec} pkt/s, acks {d.DongleAcksPerSec}/s" +
(remote_.LastPacketLength != 0 && remote_.LastPacketLength != System.Runtime.InteropServices.Marshal.SizeOf<CmdPacket>()
? $"\n<color=#ff6060>packets are {remote_.LastPacketLength} bytes: remote and sim built from different protocol versions</color>" : "") +
(d.BadFrames > 0 ? $"\n{d.BadFrames} corrupt frames" : ""),
rich);
GUILayout.Label("Use the remote's sticks and touchscreen. Its display shows this simulated robot.", rich);
}
static string StanceString(int mask) static string StanceString(int mask)
{ {
var sb = new StringBuilder(6); var sb = new StringBuilder(6);
@@ -1,10 +0,0 @@
fileFormatVersion: 2
guid: 5f676c461da1c254990d7719d77e6250
folderAsset: yes
timeCreated: 1641405303
licenseType: Free
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,72 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.JoyStick
{
class HandleHoystick : MonoBehaviour
{
public RotationControl bot;
public Walk walk;
public void Update()
{
float a2 = Remap(Input.GetAxis("1"), 1, -127, -1, 127);
float a1 = Remap(Input.GetAxis("2"), 1, -127, -1, 127);
float a3 = Remap(Input.GetAxis("3"), -1, -127, 1, 127);
float b2 = Remap(Input.GetAxis("4"), -1, -127, 1, 127);
float b3 = Remap(Input.GetAxis("5"), -1, -127, 1, 127);
float b1 = Remap(Input.GetAxis("6"), -1, -127, 1, 127);
//Debug.Log(Input.GetAxis("4"));
//Debug.Log(Remap(Input.GetAxis("4"), -1, -127, 1, 127));
bot.rotation = new Quaternion(limit(a2, -20, 20), -1 * limit(a3, -20, 20), -1 * limit(a1, -20, 20),
1);
float speed = (float)(Math.Sqrt(b1 * b1 + b2 * b2) / 127) * 3;
walk.walkspeed = speed < 0.5f ? 0 : speed;
float rotation = -1 * limit(b3 / 4, -5, 5);
walk.centerRotation = rotation < 0.5f && rotation > -0.5f ? 0 : rotation;
walk.walkDirection = (-1 * ConvertRadiansToDegrees((float)Math.Atan2(b2, b1)));
float rotationabs = Math.Abs(walk.centerRotation);
float speed2 = ((6 / 3) * walk.walkspeed) + ((6 / 5) * rotationabs);
speed2 = speed2 < 6 ? speed2 : 6;
walk.speed2 = (int)(10 - speed2);
}
public float limit(float input, float min, float max)
{
input = input / 6;
return (input < max & input > min) ? input : input < min ? min : max;
}
public float ConvertRadiansToDegrees(float radians)
{
float degrees = (float)((180 / Math.PI) * radians);
return (degrees);
}
public float Remap(float from, float fromMin, float toMin, float fromMax, float toMax)
{
var fromAbs = from - fromMin;
var fromMaxAbs = fromMax - fromMin;
var normal = fromAbs / fromMaxAbs;
var toMaxAbs = toMax - toMin;
var toAbs = toMaxAbs * normal;
var to = toAbs + toMin;
return to;
}
}
}
@@ -1,13 +0,0 @@
fileFormatVersion: 2
guid: c5ce8a2605d301e44a4a210aa345ed62
timeCreated: 1641405303
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -79,11 +79,8 @@ public class Leg : MonoBehaviour {
// (int)Remap((float)a1, -90, 90, 2500, 500), // (int)Remap((float)a1, -90, 90, 2500, 500),
// (int)Remap((float)a2, -90, 90, 2500, 500), // 0 is middel // (int)Remap((float)a2, -90, 90, 2500, 500), // 0 is middel
// (int)Remap((float)a3, 90, -90, 2500, 500)); // 0 is middel // (int)Remap((float)a3, 90, -90, 2500, 500)); // 0 is middel
if(false) // (servo angles used to go out over USB serial here; dropped 2026-11-17,
Serial.Instance.send(startServo, // the 2026 robot runs its own firmware and takes commands over the radio)
(int)Remap((float)a1, -90, 90, 0, 180),
(int)Remap((float)a2, 90, -90, 0, 180), // 0 is middel
(int)Remap((float)a3, -90, 90, 0, 180)); // 0 is middel
} }
else if (invertForLeftLeg && startServo != -1) else if (invertForLeftLeg && startServo != -1)
{ {
@@ -95,11 +92,6 @@ public class Leg : MonoBehaviour {
// (int)Remap((float)a1, -90, 90, 500, 2500), // (int)Remap((float)a1, -90, 90, 500, 2500),
// (int)Remap((float)a2, -90, 90, 500, 2500), // 0 is middel // (int)Remap((float)a2, -90, 90, 500, 2500), // 0 is middel
// (int)Remap((float)a3, 90, -90, 500, 2500)); // 0 is middel // (int)Remap((float)a3, 90, -90, 500, 2500)); // 0 is middel
if (false)
Serial.Instance.send(startServo,
(int)Remap((float)a1, 90, -90, 0, 180),
(int)Remap((float)a2, -90, 90, 0, 180), // 0 is middel
(int)Remap((float)a3, 90, -90, 0, 180)); // 0 is middel
} }
Hip1.transform.localRotation = Quaternion.Euler(0, (float)a1, 0); Hip1.transform.localRotation = Quaternion.Euler(0, (float)a1, 0);
@@ -12875,7 +12875,6 @@ GameObject:
serializedVersion: 6 serializedVersion: 6
m_Component: m_Component:
- component: {fileID: 73925799} - component: {fileID: 73925799}
- component: {fileID: 73925800}
m_Layer: 0 m_Layer: 0
m_Name: SerialIn m_Name: SerialIn
m_TagString: Untagged m_TagString: Untagged
@@ -12898,28 +12897,6 @@ Transform:
m_Children: [] m_Children: []
m_Father: {fileID: 0} m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &73925800
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 73925798}
m_Enabled: 0
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 7fa025fa8dcb3a249b67fc0e2fe67b44, type: 3}
m_Name:
m_EditorClassIdentifier:
bot: {fileID: 311513962}
walk: {fileID: 311513965}
a1: 0
a2: 0
a3: 0
b1: 0
b2: 0
b3: 0
enabled: 0
enabled_send: 0
--- !u!1 &74230589 --- !u!1 &74230589
GameObject: GameObject:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
@@ -325049,7 +325026,6 @@ GameObject:
serializedVersion: 6 serializedVersion: 6
m_Component: m_Component:
- component: {fileID: 1645933599} - component: {fileID: 1645933599}
- component: {fileID: 1645933598}
m_Layer: 0 m_Layer: 0
m_Name: Input m_Name: Input
m_TagString: Untagged m_TagString: Untagged
@@ -325057,20 +325033,6 @@ GameObject:
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0
m_IsActive: 1 m_IsActive: 1
--- !u!114 &1645933598
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1645933597}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c5ce8a2605d301e44a4a210aa345ed62, type: 3}
m_Name:
m_EditorClassIdentifier:
bot: {fileID: 311513962}
walk: {fileID: 311513965}
--- !u!4 &1645933599 --- !u!4 &1645933599
Transform: Transform:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: fc34dbb2de5c9264996b3a62ab44041a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,15 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 84c25d82fb814954a15a26feee052c98, type: 3}
m_Name: GDKEdition
m_EditorClassIdentifier: Unity.Microsoft.GDK::Unity.XGamingRuntime.GdkEditionAsset
m_EditionNumber: -1
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 191b1a487084bf849be4570078df21cc
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
@@ -1,10 +0,0 @@
fileFormatVersion: 2
guid: 942facdab943ceb4ca29453f4ee4d1b3
folderAsset: yes
timeCreated: 1641404792
licenseType: Free
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,119 +0,0 @@
using System;
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using Random = System.Random;
public class Serial
{
private static Serial instance;
private int rnd = 0;
private Serial()
{
}
~Serial()
{
serialPort.Close();
serialPort.Dispose();
}
public static Serial Instance
{
get
{
if (instance == null)
{
instance = new Serial();
}
return instance;
}
}
public bool enabled = false;
public SerialPort serialPort;
public int[] values = new int[18];
public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-", " ");
}
public void send(int start, int a, int b, int c)
{
if (serialPort == null)
{
serialPort = new SerialPort(@"\\.\" + "COM4", 250000);
try
{
serialPort.Parity = Parity.Even;
serialPort.StopBits = StopBits.One;
serialPort.DataBits = 8;
serialPort.Open();
serialPort.DiscardOutBuffer();
serialPort.DiscardInBuffer();
System.Threading.Thread.Sleep(1000);
enabled = true;
}
catch
{
enabled = false;
}
}
if (enabled)
{
values[start] = a;
values[++start] = b;
values[++start] = c;
if (serialPort is SerialPort && start == 17)
{
// string send = "s";
byte[] send = new byte[18+1+2];
send[18] = 0x00;
send[19] = 0xfe;
send[20] = 0xff;
// send[21] = 0xff;
// if (rnd == 0)
// {
//rnd = 1;
for (int i = 0; i < 18; i++)
{
//string crc = ((i) * (values[i])) + "";
//send = send + (i).ToString() + "_" + (values[i]).ToString() + "," + crc + "=";
byte[] intBytes = BitConverter.GetBytes(values[i]);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
send[i] = intBytes[3];
send[18] += send[i];
}
// Debug.Log(ByteArrayToString(send));
serialPort.Write(send, 0, 18+1+2);
serialPort.BaseStream.Flush();
// }
// else
// {
// rnd = 0;
// for (int i = 10; i < 18; i++)
// {
// string crc = ((i + 3) * (values[i])) + "";
//
// send = send + (i + 2).ToString() + "_" + (values[i]).ToString() + "," + crc + "=";
// }
//
// Debug.Log(send);
// serialPort.Write(send);
// }
}
}
}
}
@@ -1,13 +0,0 @@
fileFormatVersion: 2
guid: c99b6d9374ff6d3419c7692fdf3c1791
timeCreated: 1542057315
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,70 +0,0 @@
/*using System;
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Linq;
public class Serial2 : MonoBehaviour{
public float x;
public float y;
public RotationControl bot;
~Serial2() {
serialPort.Close();
}
public bool enabled = false;
SerialPort serialPort;
public void Update()
{
if (serialPort == null)
{
serialPort = new SerialPort(@"\\.\" + "COM7", 115200);
try
{
serialPort.NewLine = "\n";
serialPort.Open();
serialPort.DiscardOutBuffer();
serialPort.DiscardInBuffer();
enabled = true;
}
catch
{
enabled = false;
}
}
if (enabled)
{
if (serialPort is SerialPort)
{
string received = serialPort.ReadLine();
string[] data = received.Split(',');
x = ConvertRadiansToDegrees(float.Parse(data.First()));
y = ConvertRadiansToDegrees(float.Parse(data.Last()));
bot.rotation = new Quaternion(-1* limit(y, -30, 30), 0, -1* limit(x, -30, 30), 1);
}
}
}
public float limit(float input, float min, float max)
{
return (input < max & input > min) ? input : input < min ? min : max;
}
public float ConvertRadiansToDegrees(float radians)
{
float degrees = (float) ((180 / Math.PI) * radians);
return (degrees);
}
}
*/
@@ -1,13 +0,0 @@
fileFormatVersion: 2
guid: ac6468bb4d2734947a923ea42d6d8192
timeCreated: 1557262171
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,170 +0,0 @@
//using System;
//using UnityEngine;
//using System.Collections;
//using System.IO.Ports;
//using System.Linq;
//using UnityEngine.UI;
//public class Serial3 : MonoBehaviour{
// public RotationControl bot;
// public Walk walk;
// public float a1, a2, a3, b1, b2, b3;
// // ~Serial3()
// // {
// // serialPort.Close();
// // serialPort.Dispose();
// // }
// public bool enabled = false;
// public bool enabled_send = false;
// SerialPort serialPort;
// public void Update()
// {
// if (serialPort == null)
// {
// serialPort = new SerialPort(@"\\.\" + "COM7", 230400);
// try
// {
// serialPort.NewLine = "\r\n";
//// serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// serialPort.Open();
// serialPort.DiscardOutBuffer();
// serialPort.DiscardInBuffer();
// enabled = true;
// }
// catch
// {
// enabled = false;
// }
// }
// if (enabled)
// {
// serialPort = Serial.Instance.serialPort;
// Serial.Instance.enabled = enabled_send;
// if (serialPort is SerialPort)
// {
// string received = serialPort.ReadLine();
// string[] data = received.Split(',');
// foreach (string d in data)
// {
// string[] ch = d.Split('_');
// int channel = int.Parse(ch.First());
// float value = float.Parse(ch.Last());
// switch (channel)
// {
// case 0:
// a1 = value - 127;
// break;
// case 1:
// a2 = value - 127;
// break;
// case 2:
// a3 = value - 127;
// break;
// case 3:
// b1 = value - 127;
// break;
// case 4:
// b2 = value - 127;
// break;
// case 5:
// b3 = value - 127;
// break;
// }
// bot.rotation = new Quaternion(limit(a2, -20, 20), -1 * limit(a3, -20, 20), -1 * limit(a1, -20, 20),
// 1);
// float speed = (float) (Math.Sqrt(b1 * b1 + b2 * b2) / 127) * 3;
// walk.walkspeed = speed < 0.5f ? 0 : speed;
// float rotation = -1 * limit(b3/4, -5, 5);
// walk.centerRotation = rotation < 0.5f && rotation > -0.5f ? 0 : rotation;
// walk.walkDirection = (-1 * ConvertRadiansToDegrees((float) Math.Atan2(b2, b1)));
// float rotationabs = Math.Abs(walk.centerRotation);
// float speed2 = ((6 / 3) * walk.walkspeed) + ((6/5) * rotationabs);
// speed2 = speed2 < 6 ? speed2 : 6;
// walk.speed2 = (int)(10 - speed2);
// }
// }
// }
// }
// private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
// {
// SerialPort serialPort = (SerialPort)sender;
// if (enabled)
// {
// if (serialPort is SerialPort)
// {
// string received = serialPort.ReadLine();
// string[] data = received.Split(',');
// foreach (string d in data)
// {
// // if (data == "\r")
// // continue;
// string[] ch = d.Split('_');
// int channel = int.Parse(ch.First());
// float value = float.Parse(ch.Last());
// switch (channel)
// {
// case 0:
// a1 = value;
// break;
// case 1:
// a2 = value;
// break;
// case 2:
// a3 = value;
// break;
// case 3:
// b1 = value;
// break;
// case 4:
// b2 = value;
// break;
// case 5:
// b3 = value;
// break;
// }
// }
// // bot.rotation = new Quaternion(-1* limit(y, -30, 30), 0, -1* limit(x, -30, 30), 1);
// }
// }
// }
// public float limit(float input, float min, float max)
// {
// input = input / 6;
// return (input < max & input > min) ? input : input < min ? min : max;
// }
// public float ConvertRadiansToDegrees(float radians)
// {
// float degrees = (float)((180 / Math.PI) * radians);
// return (degrees);
// }
//}
@@ -1,13 +0,0 @@
fileFormatVersion: 2
guid: 7fa025fa8dcb3a249b67fc0e2fe67b44
timeCreated: 1558207463
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1 +1,5 @@
Hexapod Hexapod
The Unity side of the firmware simulation: it runs the unchanged robot firmware
(`../sim/build/hexapod_sim.dll`) on the 3D model, driven by the keyboard or by the
real remote over the radio (USB nRF24 dongle). See `../sim/README.md`.
+40 -34
View File
@@ -1,7 +1,9 @@
# Hexapod # Hexapod
A six-legged walking robot (Teensy 3.6) and its handheld remote A six-legged walking robot (Teensy 3.6) and its handheld remote
(Teensy 4.0 + Nextion touchscreen), linked over nRF24L01. (Teensy 4.0 + Nextion touchscreen), linked over nRF24L01: commands from the
remote, telemetry back from the robot. A USB nRF24 stick lets the PC (the
Unity simulation) take the robot's place on the radio.
![The hexapod, OpenSCAD model in its standing pose](hardware/openscad/renders/hexapod.png) ![The hexapod, OpenSCAD model in its standing pose](hardware/openscad/renders/hexapod.png)
![The remote (v2), OpenSCAD model: black ASA with a red honeycomb and white ON/OFF inlay](hardware/openscad/renders/remote_v2.png) ![The remote (v2), OpenSCAD model: black ASA with a red honeycomb and white ON/OFF inlay](hardware/openscad/renders/remote_v2.png)
@@ -11,16 +13,19 @@ printed yet). The original printed remote is on the
[archive page](hardware/openscad/ARCHIVE.md). [archive page](hardware/openscad/ARCHIVE.md).
``` ```
robot/ robot firmware: IK, gait, body pose, IMU stabilization, state machine robot/ robot firmware: IK, gait, body pose, IMU stabilization, state machine,
remote/ remote firmware: 2 x 3-axis sticks, MPU6050 tilt, Nextion UI, RF24 TX servo centre calibration, telemetry
shared/ HexapodProtocol: the CmdPacket wire format + radio settings used by both remote/ remote firmware: 2 x 3-axis sticks, MPU6050 tilt, Nextion UI, RF24 link
(+ remote.HMI, the touchscreen project)
shared/ HexapodProtocol: CmdPacket + Telemetry wire formats + radio settings
sim/ the unchanged robot firmware compiled into a DLL for the simulation sim/ the unchanged robot firmware compiled into a DLL for the simulation
Hexapod_Simulation_Unity/ Unity project that runs that DLL on the 3D model Hexapod_Simulation_Unity/ Unity project that runs that DLL on the 3D model
dongle/ USB nRF24 stick firmware (STM32F030): the PC-side radio, see dongle/README.md dongle/ USB nRF24 stick firmware (STM32F030): the PC-side radio, see dongle/README.md
hardware/openscad/ OpenSCAD model of the robot (rebuilt from the Fusion designs) and the new remote hardware/openscad/ OpenSCAD model of the robot (rebuilt from the Fusion designs) and the new remote
hardware/openscad/stl/ print-ready STL exports hardware/openscad/stl/ print-ready STL exports
hardware/fusion360/ Fusion 360 designs: body, legs, servo, servo horn, remote case hardware/fusion360/ Fusion 360 designs: body, legs, servo, servo horn, remote case
scripts/ PlatformIO helper (per-environment sketch folder) scripts/ PlatformIO helper (per-environment sketch folder), make_remote_hmi.py
tools/nextion-hmi-tools/ git submodule: .HMI reader/writer/renderer (nxhmi), used by the HMI generator
``` ```
This is the `2026-current/` folder of the hexapod-robot repo; the earlier This is the `2026-current/` folder of the hexapod-robot repo; the earlier
@@ -70,38 +75,35 @@ Hardware (besides the electronics of the old remote):
- M3 x 12 x 4 (shells), M3 x 8 button head x 2 (eyelet), M3 x 16 button - M3 x 12 x 4 (shells), M3 x 8 button head x 2 (eyelet), M3 x 16 button
head + washer x 2 (brace), M3 x 8 button head + 7 mm washer x 4 (main head + washer x 2 (brace), M3 x 8 button head + 7 mm washer x 4 (main
board clamps, no holes in the board), M3 x 40 + nut (kickstand pin) board clamps, no holes in the board), M3 x 40 + nut (kickstand pin)
- M2.5 x 14 x 8 (joysticks, into their own boxes), M2.5 self-tapping x 4 - M2.5 x 14 x 8 (joysticks, into their own boxes), M3 x 5 machine screws x 4
(display), M3 self-tapping x 2 (UPS board), M2 self-tapping x 2 (switch) (display, tap the posts M3), M3 self-tapping x 2 (UPS board), M2 self-tapping x 2 (switch)
- Set the Nextion's display direction to 180 in the Nextion Editor: the - The display is mounted turned round so its connector clears the Teensy's USB
display is mounted turned round so its connector clears the Teensy's USB plug. plug. `remote.HMI` is generated for that (display direction 270 in the
Editor's terms, see [remote/NEXTION.md](remote/NEXTION.md)), nothing to set.
Design notes, checks and open points: [hardware/openscad/PLANNING.md](hardware/openscad/PLANNING.md). Design notes, checks and open points: [hardware/openscad/PLANNING.md](hardware/openscad/PLANNING.md).
## Planned ## Planned
- **PC radio link (owner, later):** a USB nRF24L01 stick on the PC as the - **PC radio link:** a USB nRF24L01 stick on the PC as the PC-side radio, on
PC-side radio, on the same air settings as the robot and the remote, so Unity the same air settings as the robot and the remote. It's reverse-engineered
on the PC can both receive data from (telemetry) and send data to the robot and runs our own firmware (STM32F030 + Si24R1 + AT2401C, updated wire-free
and the remote. The stick is now reverse-engineered and reflashed with our own over USB), see **[dongle/README.md](dongle/README.md)**. Done (2026-11-17):
firmware (STM32F030 + Si24R1 + AT2401C); it shows up as a COM port and is its **bridge mode** lets the real remote drive the Unity simulation over the
updated wire-free over USB. See **[dongle/README.md](dongle/README.md)**. Still air, with the sim's telemetry going back to the remote's display as the ack
to do: payload ([sim/README.md](sim/README.md), "Using it in Unity"). There's no USB
- map the stick's LED and AT2401C power-amp control pins (app toggles them); link to the remote or the robot any more; everything goes over the radio.
- the radio protocol: today the remote only transmits a `CmdPacket` to the Still to do:
robot and nothing comes back. Three nodes need an address per node (or - Unity driving the **real** robot (the dongle transmitting instead of
per pipe), a packet type byte, and telemetry back (e.g. as ack payloads listening) and mirroring it;
or in time slots) so the nodes don't talk over each other; who has - three nodes at once: today the dongle answers the remote *instead of* the
priority when the PC and the remote both send commands. Owner's robot. Needs an address per node (or per pipe), a packet type byte, and a
decisions: the remote wins, with a toggle on the remote that hands the rule for who has priority. Owner's decisions: the remote wins, with a
robot to Unity and lets the remote's sticks control Unity instead; the toggle on the remote that hands the robot to Unity and lets the remote's
PC is the hub while it's online, the robot is the hub when it isn't; sticks control Unity instead; the PC is the hub while it's online, the
goals: mirror the real robot in Unity, drive it from Unity, remote data robot is the hub when it isn't; goals: mirror the real robot in Unity,
to the PC, and PC data to the remote; drive it from Unity, remote data to the PC, and PC data to the remote.
- Unity side: a serial-port reader/writer next to the simulation (the - Remote battery level: see [remote/README.md](remote/README.md), "Planned".
2019 generation already drove the robot from Unity, through the remote
over USB: see `../2019-teensy-nrf24/`).
- Remote battery level and the IMU on the normal pin headers: see
[remote/README.md](remote/README.md), "Planned".
- Robot power: a stable 6 V supply for the 18 servos, see - Robot power: a stable 6 V supply for the 18 servos, see
[hardware/openscad/PLANNING.md](hardware/openscad/PLANNING.md), "Notes for [hardware/openscad/PLANNING.md](hardware/openscad/PLANNING.md), "Notes for
future designs". future designs".
@@ -113,7 +115,11 @@ Design notes, checks and open points: [hardware/openscad/PLANNING.md](hardware/o
robot without a remote. robot without a remote.
- **[remote/README.md](remote/README.md)**: wiring, control scheme, stick - **[remote/README.md](remote/README.md)**: wiring, control scheme, stick
calibration, and the remote's serial console. calibration, and the remote's serial console.
- **[remote/NEXTION.md](remote/NEXTION.md)**: how to build the touchscreen - **[remote/NEXTION.md](remote/NEXTION.md)**: the touchscreen HMI (generated
HMI. by `scripts/make_remote_hmi.py`).
- **[sim/README.md](sim/README.md)**: the robot firmware in simulation, headless
and in Unity, with the keyboard or the real remote over the radio.
- **[dongle/README.md](dongle/README.md)**: the USB nRF24 stick, its firmware,
flashing and the bridge protocol.
- **[shared/HexapodProtocol/HexapodProtocol.h](shared/HexapodProtocol/HexapodProtocol.h)**: - **[shared/HexapodProtocol/HexapodProtocol.h](shared/HexapodProtocol/HexapodProtocol.h)**:
the protocol. Change it only by reflashing both boards. the protocol. Change it only by reflashing both boards.
+63 -14
View File
@@ -30,15 +30,31 @@ Found by probing the board over SWD and confirmed at runtime by our firmware:
| SPI1 SCK / MISO / MOSI | PA5 / PA6 / PA7 → Si24R1 | | SPI1 SCK / MISO / MOSI | PA5 / PA6 / PA7 → Si24R1 |
| nRF CSN / CE / IRQ | PA3 / PA4 / PA2 | | nRF CSN / CE / IRQ | PA3 / PA4 / PA2 |
| status LED (active-high) | **PA0** — confirmed by eye | | status LED (active-high) | **PA0** — confirmed by eye |
| AT2401C TX/RX enable + unused | PA1, PB1, PF0, PF1 — **not yet distinguished** | | AT2401C TX/RX enable + unused | PA1, PB1, PF0, PF1 — **not distinguishable** (see below) |
PA0 drives the LED (HIGH = on). The AT2401C control lines are among PA1, PB1, PA0 drives the LED (HIGH = on). The AT2401C control lines would be among PA1,
PF0, PF1 (the TSSOP-20 has no other GPIO). Listening for ambient 2.4 GHz with PB1, PF0, PF1 (the TSSOP-20 has no other GPIO). Listening for ambient 2.4 GHz
the radio's carrier-detect bit was too noisy to tell them apart, so they need a with the radio's carrier-detect bit was too noisy to tell them apart. The real
real link test (dongle ↔ robot/remote, trying each pin while watching whether link test (2026-11-17: receiving the remote while switching all 16 on/off
packets get through). The radio still works without driving the amplifier, just combinations, at the desk and a few rooms away with the remote at minimum
at reduced range. The app firmware can drive any pin (`0`-`4`), sweep them all power) got every packet in every combination, so either the link has plenty of
(`a`), and run a carrier-detect finder (`f`/`n`). margin or the amplifier is switched in hardware. The firmware leaves them low;
the link works.
### App commands (USB serial, 115200, single keys, when not bridging)
| Key | Action |
|-----|--------|
| `v` | banner: version and a few radio registers |
| `r` | dump nRF registers |
| `x` | RX test on the hexapod's air settings; prints packets/s once a second |
| `0`-`4` | toggle PA0 (LED) / PA1 / PB1 / PF0 / PF1 |
| `a` | sweep every free pin high for 3 s each |
| `f` / `n` | carrier-detect finder on / next channel |
| `b` | reset into safeboot (what `safeboot_flash.py` uses) |
**SignalRGB** (if installed) opens every CH340 COM port it sees and holds it;
quit it while using the dongle.
### Programming header (5 holes next to the CH330N) ### Programming header (5 holes next to the CH330N)
@@ -155,19 +171,52 @@ python tools/safeboot_flash.py firmware/build/app.bin
``` ```
This resets the running app into safeboot and rewrites only the app region. If This resets the running app into safeboot and rewrites only the app region. If
the app is dead, replug the stick and re-run — it will catch the knock window. the app is dead or doesn't answer, start it with `--knock` and then replug the
stick: it keeps knocking (reopening the port as it comes back) until it lands in
safeboot's 1.5 s cold-boot window.
## Air settings ## Air settings
Matches `shared/HexapodProtocol/HexapodProtocol.h`: 2.4 GHz channel 96 Matches `shared/HexapodProtocol/HexapodProtocol.h`: 2.4 GHz channel 96
(2.496 GHz), 250 kbps, 5-byte address `HXPD1`, 16-bit CRC. The app sets these on (2.496 GHz), 250 kbps, 5-byte address `HXPD1`, 16-bit CRC, auto-ack with
dynamic payload lengths and ack payloads (protocol v4). The app sets these on
the Si24R1 over SPI (same register layout as the nRF24L01+). the Si24R1 over SPI (same register layout as the nRF24L01+).
## Status / next ## Status / next
- [x] identify the hardware, map the radio + serial pins - [x] identify the hardware, map the radio + serial pins
- [x] permanent two-stage firmware, wire-free USB flashing - [x] permanent two-stage firmware, wire-free USB flashing
- [ ] identify the LED and AT2401C TX/RX-enable pins (app toggles the 5 free pins) - [x] LED pin (PA0)
- [ ] radio hub app: carry `CmdPacket` both ways, per-node addressing, telemetry - [x] bridge mode: the dongle stands in for the robot's radio, Unity runs the
- [ ] Unity serial bridge (PC as hub when online, robot as hub when not) — see robot firmware (sim) behind it — see "Bridge mode" below
`../README.md` "Planned" - [ ] the other direction: Unity as the remote, driving the real robot
- [ ] AT2401C pins: at desk range and even a few rooms away with the remote at
minimum power, every on/off combination of PA1/PB1/PF0/PF1 received
every packet, so they couldn't be told apart; the link works without
driving them
## Bridge mode (Unity ↔ real remote)
The app listens on the hexapod's air settings as if it were the robot
(ch 96, 250 kbps, `HXPD1`, auto-ack, dynamic payload lengths, ack payloads)
and passes everything to the PC. Framing both ways over the USB serial
(115200 8N1):
```
A5 type len payload[len] sum sum = type + len + payload bytes (mod 256)
```
| Direction | Type | Payload |
|-----------|------|---------|
| PC → dongle | `L` | — : start bridging (LED on) |
| PC → dongle | `X` | — : stop |
| PC → dongle | `A` | ≤ 32 bytes: the robot's `Telemetry`, sent back on the auto-ack of the remote's next packet (reloaded after every packet, like `robot/Comms.cpp`). Dropped if not refreshed for ~0.5 s, so the remote never shows stale telemetry as live |
| dongle → PC | `R` | a packet the remote sent (its `CmdPacket`, any length; the firmware checks it) |
| dongle → PC | `S` | once a "second": packets received (u16 LE), ack payloads loaded (u16 LE). Its second runs ~30% long (blocking UART sends miss SysTick ticks); it's only for display |
Plain text never contains `A5`, so the PC skips anything between frames;
while bridging the app prints no text and only takes frames (and `b` for a
reflash). USB serial input goes through DMA into a ring buffer (no
interrupts in this app), and the USART's overrun stall is disabled, so a
burst can't deafen it. Unity's side is
`Hexapod_Simulation_Unity/Assets/HexapodSim/DongleLink.cs`.
+163 -14
View File
@@ -52,11 +52,14 @@ static void nrf_write_buf(uint8_t reg, const uint8_t *d, int n)
} }
static void nrf_cmd(uint8_t c) { CSN_LO(); spi_xfer(c); CSN_HI(); } static void nrf_cmd(uint8_t c) { CSN_LO(); spi_xfer(c); CSN_HI(); }
/* Receive on the hexapod protocol (ch 96, 250 kbps, addr HXPD1, 22-byte). Lets /* Receive on the hexapod protocol (ch 96, 250 kbps, addr HXPD1). Protocol v4
* us find the AT2401C RX-enable pin: packets only arrive when the LNA/antenna * uses dynamic payload lengths (the remote's CmdPacket is 26 bytes, with ack
* path is on. */ * payloads), so this does too and accepts any length. Auto-ack is on, so the
* remote's link % also shows whether our acks get back out (TX path). Lets us
* find the AT2401C enable pins: packets only arrive when the LNA path is on. */
static uint8_t rxmode; static uint8_t rxmode;
static uint16_t rx_count; static uint16_t rx_count;
static uint8_t rx_len;
static void rx_setup(void) static void rx_setup(void)
{ {
static const uint8_t addr[5] = { 0x48, 0x58, 0x50, 0x44, 0x31 }; /* "HXPD1" */ static const uint8_t addr[5] = { 0x48, 0x58, 0x50, 0x44, 0x31 }; /* "HXPD1" */
@@ -68,18 +71,22 @@ static void rx_setup(void)
nrf_write(0x05, 96); /* RF_CH */ nrf_write(0x05, 96); /* RF_CH */
nrf_write(0x06, 0x26); /* RF_SETUP: 250 kbps, max power */ nrf_write(0x06, 0x26); /* RF_SETUP: 250 kbps, max power */
nrf_write_buf(0x0A, addr, 5); /* RX_ADDR_P0 */ nrf_write_buf(0x0A, addr, 5); /* RX_ADDR_P0 */
nrf_write(0x11, 22); /* RX_PW_P0 */ nrf_write(0x1D, 0x04); /* FEATURE: EN_DPL */
nrf_write(0x1C, 0x01); /* DYNPD: pipe0 */
nrf_write(0x07, 0x70); /* clear status flags */ nrf_write(0x07, 0x70); /* clear status flags */
nrf_cmd(0xE2); /* FLUSH_RX */ nrf_cmd(0xE2); /* FLUSH_RX */
rx_count = 0; rx_count = 0;
rx_len = 0;
CE_HI(); CE_HI();
} }
static void rx_poll(void) static void rx_poll(void)
{ {
if (nrf_read(0x07) & 0x40) { /* RX_DR */ while (nrf_read(0x07) & 0x40) { /* RX_DR */
uint8_t buf[22]; CSN_LO(); spi_xfer(0x60); uint8_t n = spi_xfer(0xFF); CSN_HI(); /* R_RX_PL_WID */
CSN_LO(); spi_xfer(0x61); for (int i = 0; i < 22; i++) buf[i] = spi_xfer(0xFF); CSN_HI(); if (n > 32) { nrf_cmd(0xE2); nrf_write(0x07, 0x40); break; } /* corrupt: flush */
CSN_LO(); spi_xfer(0x61); for (int i = 0; i < n; i++) spi_xfer(0xFF); CSN_HI();
nrf_write(0x07, 0x40); /* clear RX_DR */ nrf_write(0x07, 0x40); /* clear RX_DR */
rx_len = n;
rx_count++; rx_count++;
} }
} }
@@ -132,7 +139,7 @@ static void banner(void)
uart_puts("\r\nhexapod dongle app v0 (@0x08001000)\r\n"); uart_puts("\r\nhexapod dongle app v0 (@0x08001000)\r\n");
uart_puts("nRF CONFIG=0x"); hex2(nrf_read(0)); uart_puts(" STATUS=0x"); hex2(nrf_read(7)); uart_puts("nRF CONFIG=0x"); hex2(nrf_read(0)); uart_puts(" STATUS=0x"); hex2(nrf_read(7));
uart_puts(" RF_CH=0x"); hex2(nrf_read(5)); uart_puts(" RF_SETUP=0x"); hex2(nrf_read(6)); uart_puts(" RF_CH=0x"); hex2(nrf_read(5)); uart_puts(" RF_SETUP=0x"); hex2(nrf_read(6));
uart_puts("\r\ncmds: v r 0-4(PA0/PA1/PB1/PF0/PF1) b=reflash\r\n"); uart_puts("\r\ncmds: v r 0-4(PA0/PA1/PB1/PF0/PF1) x=rx test b=reflash; bridge: frame A5 'L'\r\n");
} }
static void regdump(void) static void regdump(void)
{ {
@@ -156,6 +163,134 @@ static void finder_rx(void)
delay_ms(2); delay_ms(2);
} }
/* ---- USART1 RX through circular DMA ------------------------------------
* The bridge moves ~100 frames/s each way at 115200 baud. Polled single-byte
* RX loses bytes while we block on a TX frame or an SPI read, and this M0 app
* runs without interrupts (no vector relocation), so DMA channel 3 (USART1_RX)
* writes every byte into a ring we drain at leisure. */
#define DMA_CCR3 REG(0x40020030)
#define DMA_CNDTR3 REG(0x40020034)
#define DMA_CPAR3 REG(0x40020038)
#define DMA_CMAR3 REG(0x4002003C)
#define USART1_CR3 REG(0x40013808)
#define RXRING 256u
static volatile uint8_t rxring[RXRING];
static uint16_t rxtail;
static void uart_dma_init(void)
{
RCC_AHBENR |= 1u; /* DMA1 */
while (!(USART1_ISR & (1u << 6))) {} /* let any TX finish */
USART1_CR1 &= ~1u; /* UE off: CR3 OVRDIS needs it */
USART1_CR3 = (1u << 6) | (1u << 12); /* DMAR, OVRDIS (never stall on overrun) */
USART1_CR1 |= 1u;
DMA_CCR3 = 0;
DMA_CPAR3 = 0x40013824u; /* USART1_RDR */
DMA_CMAR3 = (uint32_t)rxring;
DMA_CNDTR3 = RXRING;
DMA_CCR3 = (1u << 7) | (1u << 5) | 1u; /* MINC, CIRC, EN; 8-bit, periph -> mem */
}
static int rx_getc(void)
{
uint16_t head = (uint16_t)(RXRING - DMA_CNDTR3) % RXRING;
if (head == rxtail) return -1;
uint8_t c = rxring[rxtail];
rxtail = (uint16_t)((rxtail + 1) % RXRING);
return c;
}
/* ---- Bridge: the dongle stands in for the robot's radio ------------------
* Framing both ways: A5 type len payload[len] sum, sum = type+len+payload (mod 256).
* host -> dongle 'L' listen (enter bridge) 'X' leave
* 'A' ack payload (<= 32 B): goes back on the auto-ack of the
* next packet, like the robot's Comms::loadAckPayload.
* Dropped if the host stops refreshing it for 500 ms, so
* the remote doesn't see stale telemetry as live.
* dongle -> host 'R' a received packet (the remote's CmdPacket)
* 'S' once a second: packets received (u16 LE), acks loaded (u16 LE)
* Plain text never contains A5, so the host can skip anything between frames. */
static uint8_t bridge;
static uint8_t ack_buf[32], ack_len;
static uint32_t ack_ms;
static uint16_t br_rx, br_acks;
static void frame_send(uint8_t type, const uint8_t *d, uint8_t n)
{
uint8_t sum = (uint8_t)(type + n);
uart_putc((char)0xA5); uart_putc((char)type); uart_putc((char)n);
for (uint8_t i = 0; i < n; i++) { uart_putc((char)d[i]); sum = (uint8_t)(sum + d[i]); }
uart_putc((char)sum);
}
static void ack_load(void)
{
nrf_cmd(0xE1); /* FLUSH_TX: only the newest one */
if (!ack_len) return;
CSN_LO(); spi_xfer(0xA8); for (uint8_t i = 0; i < ack_len; i++) spi_xfer(ack_buf[i]); CSN_HI(); /* W_ACK_PAYLOAD pipe 0 */
br_acks++;
}
static void bridge_start(void)
{
rx_setup(); /* ch96 / 250k / HXPD1 / auto-ack / dynamic length */
CE_LO();
nrf_write(0x1D, 0x06); /* FEATURE: EN_DPL | EN_ACK_PAY */
nrf_write(0x1C, 0x01); /* DYNPD pipe 0 */
nrf_cmd(0xE1);
ack_len = 0; br_rx = br_acks = 0;
rxmode = 0; finder = 0; bridge = 1;
BSRR(GPIOA) = 1u; /* LED on while bridging */
CE_HI();
}
static void bridge_stop(void)
{
bridge = 0; ack_len = 0;
CE_LO(); nrf_write(0, 0x0E); nrf_cmd(0xE1);
BSRR(GPIOA) = 1u << 16;
}
static void bridge_poll(uint32_t now)
{
if (ack_len && now - ack_ms > 500) { ack_len = 0; nrf_cmd(0xE1); } /* host went quiet */
while (nrf_read(0x07) & 0x40) { /* RX_DR */
uint8_t buf[32];
CSN_LO(); spi_xfer(0x60); uint8_t n = spi_xfer(0xFF); CSN_HI(); /* R_RX_PL_WID */
if (n > 32) { nrf_cmd(0xE2); nrf_write(0x07, 0x40); break; }
CSN_LO(); spi_xfer(0x61); for (uint8_t i = 0; i < n; i++) buf[i] = spi_xfer(0xFF); CSN_HI();
nrf_write(0x07, 0x40);
ack_load(); /* the ack for the NEXT packet */
frame_send('R', buf, n);
br_rx++;
if ((br_rx & 31) == 0) BSRR(GPIOA) = (IDR(GPIOA) & 1u) ? (1u << 16) : 1u; /* LED flicker */
}
}
/* Host frame parser; returns 1 while inside a frame (so its bytes aren't
* taken as single-letter commands). */
static uint8_t fr_state, fr_type, fr_len, fr_got, fr_sum, fr_buf[32];
static int frame_rx(int c, uint32_t now)
{
/* if-chain, not switch: a switch becomes a jump table needing libgcc */
if (fr_state == 0) {
if (c != 0xA5) return 0;
fr_state = 1;
} else if (fr_state == 1) {
fr_type = (uint8_t)c;
fr_state = 2;
} else if (fr_state == 2) {
fr_len = (uint8_t)c; fr_got = 0; fr_sum = (uint8_t)(fr_type + fr_len);
fr_state = (fr_len > 32) ? 0 : (fr_len ? 3 : 4);
} else if (fr_state == 3) {
fr_buf[fr_got++] = (uint8_t)c; fr_sum = (uint8_t)(fr_sum + c);
if (fr_got == fr_len) fr_state = 4;
} else {
fr_state = 0;
if ((uint8_t)c != fr_sum) return 1; /* corrupt: drop */
if (fr_type == 'L') bridge_start();
else if (fr_type == 'X') bridge_stop();
else if (fr_type == 'A' && bridge) {
for (uint8_t i = 0; i < fr_len; i++) ack_buf[i] = fr_buf[i];
ack_len = fr_len; ack_ms = now;
ack_load();
}
}
return 1;
}
static void reflash(void) /* ask safeboot to take over, no wire needed */ static void reflash(void) /* ask safeboot to take over, no wire needed */
{ {
uart_puts("resetting into safeboot flash mode...\r\n"); uart_puts("resetting into safeboot flash mode...\r\n");
@@ -168,16 +303,25 @@ static void reflash(void) /* ask safeboot to take over, no wire needed */
int main(void) int main(void)
{ {
uart_init8n1(); uart_init8n1();
uart_dma_init();
spi_init(); spi_init();
free_init(); free_init();
nrf_write(0, 0x0E); nrf_write(0, 0x0E);
delay_ms(5); delay_ms(5);
banner(); banner();
uint32_t t = 0; uint32_t now = 0, t = 0;
systick_setup();
for (;;) { for (;;) {
int c = uart_getc(); uint32_t ctrl = STK_CTRL; /* one read: reading clears COUNTFLAG */
if (c == 'v' || c == 'V') banner(); if (ctrl == 0) systick_setup(); /* delay_ms() (sweep, finder) stops it */
else if (ctrl & 0x10000) { now++; t++; } /* 1 ms ticks, polled */
if (bridge) bridge_poll(now);
int c = rx_getc();
if (c >= 0 && frame_rx(c, now)) c = -1; /* consumed by a host frame */
if (c < 0) {}
else if (bridge && c != 'b' && c != 'B') {} /* bridging: only frames (and reflash) */
else if (c == 'v' || c == 'V') banner();
else if (c == 'r' || c == 'R') regdump(); else if (c == 'r' || c == 'R') regdump();
else if (c == 'b' || c == 'B') reflash(); else if (c == 'b' || c == 'B') reflash();
else if (c == 'x' || c == 'X') { rxmode = !rxmode; finder = 0; if (rxmode) rx_setup(); else { CE_LO(); nrf_write(0, 0x0E); } uart_puts(rxmode ? "RX mode on (ch96/250k/HXPD1)\r\n" : "RX off\r\n"); } else if (c == 'x' || c == 'X') { rxmode = !rxmode; finder = 0; if (rxmode) rx_setup(); else { CE_LO(); nrf_write(0, 0x0E); } uart_puts(rxmode ? "RX mode on (ch96/250k/HXPD1)\r\n" : "RX off\r\n"); }
@@ -193,10 +337,15 @@ int main(void)
uart_puts("\r\n"); uart_puts("\r\n");
} }
if (rxmode) rx_poll(); if (rxmode) rx_poll();
delay_ms(1); if (t >= 1000) {
if (++t >= 1000) {
t = 0; t = 0;
if (rxmode) { uart_puts("RX pkts="); hex2(rx_count >> 8); hex2(rx_count & 0xFF); if (bridge) {
uint8_t s[4] = { (uint8_t)br_rx, (uint8_t)(br_rx >> 8), (uint8_t)br_acks, (uint8_t)(br_acks >> 8) };
frame_send('S', s, 4);
br_rx = br_acks = 0;
}
else if (rxmode) { uart_puts("RX pkts="); hex2(rx_count >> 8); hex2(rx_count & 0xFF);
uart_puts(" len="); hex2(rx_len);
uart_puts(" pins="); for (int i = 0; i < NFREE; i++) uart_putc(fst[i] ? '1' : '0'); uart_puts(" pins="); for (int i = 0; i < NFREE; i++) uart_putc(fst[i] ? '1' : '0');
uart_puts(" (0=PA0LED,1=PA1,2=PB1,3=PF0,4=PF1)\r\n"); rx_count = 0; } uart_puts(" (0=PA0LED,1=PA1,2=PB1,3=PF0,4=PF1)\r\n"); rx_count = 0; }
else if (finder) { uart_puts("finder ch=0x"); hex2(finder_ch); uart_puts(" RPD="); hex2(nrf_read(9)); else if (finder) { uart_puts("finder ch=0x"); hex2(finder_ch); uart_puts(" RPD="); hex2(nrf_read(9));
+10 -1
View File
@@ -36,6 +36,7 @@
#define USART1_CR1 REG(0x40013800) #define USART1_CR1 REG(0x40013800)
#define USART1_BRR REG(0x4001380C) #define USART1_BRR REG(0x4001380C)
#define USART1_ISR REG(0x4001381C) #define USART1_ISR REG(0x4001381C)
#define USART1_ICR REG(0x40013820)
#define USART1_RDR REG(0x40013824) #define USART1_RDR REG(0x40013824)
#define USART1_TDR REG(0x40013828) #define USART1_TDR REG(0x40013828)
/* SysTick */ /* SysTick */
@@ -65,14 +66,22 @@ static inline void uart_putc(char c)
USART1_TDR = (uint8_t)c; USART1_TDR = (uint8_t)c;
} }
static inline void uart_puts(const char *s) { while (*s) uart_putc(*s++); } static inline void uart_puts(const char *s) { while (*s) uart_putc(*s++); }
/* Clear overrun / noise / framing / parity errors. While ORE is set the USART
* stops moving new bytes into RDR, so one burst the app didn't read in time
* (e.g. SignalRGB probing the COM port) used to deafen it until a replug. */
static inline void uart_clear_errors(void)
{
if (USART1_ISR & 0x0Fu) USART1_ICR = 0x0Fu; /* ORECF NCF FECF PECF */
}
static inline int uart_getc(void) /* non-blocking, -1 if none */ static inline int uart_getc(void) /* non-blocking, -1 if none */
{ {
uart_clear_errors();
if (USART1_ISR & (1u << 5)) return (uint8_t)USART1_RDR; if (USART1_ISR & (1u << 5)) return (uint8_t)USART1_RDR;
return -1; return -1;
} }
static inline uint8_t uart_getc_block(void) static inline uint8_t uart_getc_block(void)
{ {
while (!(USART1_ISR & (1u << 5))) {} while (!(USART1_ISR & (1u << 5))) uart_clear_errors();
return (uint8_t)USART1_RDR; return (uint8_t)USART1_RDR;
} }
static inline void systick_setup(void) { STK_LOAD = 8000 - 1; STK_VAL = 0; STK_CTRL = 5; } static inline void systick_setup(void) { STK_LOAD = 8000 - 1; STK_VAL = 0; STK_CTRL = 5; }
+45 -6
View File
@@ -2,12 +2,14 @@
No BOOT0 wire, no ST-Link, no ROM bootloader. Writes only the app region No BOOT0 wire, no ST-Link, no ROM bootloader. Writes only the app region
(pages 4-15); safeboot itself is never touched. (pages 4-15); safeboot itself is never touched.
usage: safeboot_flash.py app.bin [--port COM16] usage: safeboot_flash.py app.bin [--port COM16] [--knock]
How it enters flash mode: How it enters flash mode:
1) if the app is running, 'b' makes it soft-reset into safeboot flash mode; 1) if the app is running, 'b' makes it soft-reset into safeboot flash mode;
2) otherwise (dead/absent app) replug the dongle and this spams 'S' to catch 2) otherwise (dead/absent app) replug the dongle and this spams 'S' to catch
safeboot's cold-boot knock window. safeboot's cold-boot knock window.
--knock skips 1) and keeps knocking for 2 minutes, reopening the port as it
comes and goes: start it, then replug. Use it when the app doesn't answer.
""" """
import sys, time, serial import sys, time, serial
@@ -54,6 +56,36 @@ def enter_flash(s):
return False return False
def knock_until_caught(port, timeout=120.0):
"""--knock: for an app that doesn't answer 'b' (dead or deaf). Keeps the
port open and spams 'S' for up to `timeout` s, reopening whenever the port
vanishes, so replugging the dongle at any moment lands in safeboot's 1.5 s
cold-boot knock window. Returns the open port in flash mode, or None."""
t = time.time()
s = None
while time.time() - t < timeout:
try:
if s is None:
s = serial.Serial(port, 115200, timeout=0.02)
s.write(b"S")
r = s.read(16)
if b"K" in r or b"SB1" in r or b"SBR" in r:
time.sleep(0.1); s.reset_input_buffer(); s.timeout = 0.3
s.write(b"V"); time.sleep(0.1)
if b"SBV" in s.read(16):
return s
s.timeout = 0.02
except (serial.SerialException, OSError):
try:
if s is not None:
s.close()
except Exception:
pass
s = None
time.sleep(0.02)
return None
def expect(s, ch, what): def expect(s, ch, what):
r = s.read(1) r = s.read(1)
if r != ch: if r != ch:
@@ -68,11 +100,18 @@ def main():
data += b"\xFF" data += b"\xFF"
print("app %s: %d bytes -> 0x%08X" % (args[0], len(data), APP_BASE)) print("app %s: %d bytes -> 0x%08X" % (args[0], len(data), APP_BASE))
s = open_port(port) if "--knock" in sys.argv:
print("entering safeboot flash mode...") print("knock mode: replug the dongle now (waiting up to 2 min)...")
if not enter_flash(s): s = knock_until_caught(port)
print("could not enter flash mode (app not running? replug and retry)") if s is None:
return 1 print("no knock window caught")
return 1
else:
s = open_port(port)
print("entering safeboot flash mode...")
if not enter_flash(s):
print("could not enter flash mode (app not running? replug and retry with --knock)")
return 1
s.reset_input_buffer() s.reset_input_buffer()
s.write(b"V"); time.sleep(0.1) s.write(b"V"); time.sleep(0.1)
print("safeboot:", s.read(16).decode("ascii", "replace").strip()) print("safeboot:", s.read(16).decode("ascii", "replace").strip())
+13 -9
View File
@@ -151,7 +151,7 @@ switch's plate sits on top of the case, body through the slot, and the old
8 x 16 slot with d2 holes 19 mm apart fits it exactly; the UPS board's 8 x 16 slot with d2 holes 19 mm apart fits it exactly; the UPS board's
charge/on LEDs show through two slots in the floor. charge/on LEDs show through two slots in the floor.
- Size 216 x 116 x 32 mm (old remote: 208 x 175 x 45). Sticks at u +-80, - Size 216 x 116 x 42 mm (top shell 10 mm taller than first printed, TOP_GROW: room behind the display) (old remote: 208 x 175 x 45). Sticks at u +-80,
display forward of them, strap eyelet behind the display, UPS board behind display forward of them, strap eyelet behind the display, UPS board behind
that, switch at the rear centre. Main board under the display. that, switch at the rear centre. Main board under the display.
- JH-D300X-R1: dust cover d53.5 on the top face; the 40.4 mm control box - JH-D300X-R1: dust cover d53.5 on the top face; the 40.4 mm control box
@@ -159,9 +159,11 @@ charge/on LEDs show through two slots in the floor.
plate into the box (no nuts). Reaches 28.5 mm down. Pots (d16.5, 9.2 out) plate into the box (no nuts). Reaches 28.5 mm down. Pots (d16.5, 9.2 out)
towards the middle and towards the user. towards the middle and towards the user.
- Display mounted turned 180 deg so its J1 connector is on the right, clear - Display mounted turned 180 deg so its J1 connector is on the right, clear
of the Teensy's USB plug: set display direction 180 in the Nextion Editor. of the Teensy's USB plug. `remote/remote.HMI` is generated for that
Glass 1.5 mm under the top face, board on 4 posts (M2.5 self-tapping); (direction 270 in the Nextion Editor's terms; done 2026-11-17).
the LCD thickness (4.5) is a guess. Glass 1.0 mm under the top face, board on 4 posts tapped M3 (3.66 mm of thread, 1.2 mm under the top face);
LCD 85.7 x 55 x 3.86 plus a 1.3 mm flex cable on one side, 11.21 mm glass to
back of J1 (owner measured).
- Main board clamped at 4 points on its long sides, no holes in the board - Main board clamped at 4 points on its long sides, no holes in the board
(owner): posts beside the edges carry it, M3 x 8 button heads with d7 (owner): posts beside the edges carry it, M3 x 8 button heads with d7
washers in heat-set inserts clamp the edge. 2 mm above the kickstand washers in heat-set inserts clamp the edge. 2 mm above the kickstand
@@ -212,15 +214,17 @@ charge/on LEDs show through two slots in the floor.
for the stall current. The battery must also fit the bay (see open for the stall current. The battery must also fit the bay (see open
question 3) and leave room for the servo plugs. question 3) and leave room for the servo plugs.
- Remote: connect the IMU to the normal pin headers instead of the Teensy - Remote: the IMU is on the normal pin headers (done 2026-11-17: Wire on
4.0's underside pads; see `remote/README.md`, "Planned" (Wire on 18/19, 18/19, the two stick axes that were there moved to A7/A8; display on
the two stick axes there move to A7/A8). Serial2, 7/8). Pinout in `remote/README.md`, "Wiring".
- Remote: measure the 18650's voltage on the Teensy to show how much charge - Remote: measure the 18650's voltage on the Teensy to show how much charge
is left (owner, later). Divider ~100k/100k from the cell's + (holder or the is left (owner, later). Divider ~100k/100k from the cell's + (holder or the
UPS board's B+, not the 5 V output) to A6 (pin 20, free), 100 nF to GND; UPS board's B+, not the 5 V output) to A6 (pin 20, free), 100 nF to GND;
full cell = ~2.1 V at the pin. Firmware: average, Li-ion curve to %, show full cell = ~2.1 V at the pin. Firmware: reading, smoothing and the volts
on the Nextion with a low-battery warning (optionally send it to the robot). on the STATUS page are done (`remote/Battery`, pin still 255 = not wired);
still to do: Li-ion curve to %, and a low-battery warning. The robot
already sends its own battery voltage back in the telemetry.
- Servo wires barely fit on the real robot: the six servo headers hang - Servo wires barely fit on the real robot: the six servo headers hang
above the battery bay, and the front pair sits right over the bay's end above the battery bay, and the front pair sits right over the bay's end
+20 -15
View File
@@ -27,8 +27,9 @@
/* [Shell] */ /* [Shell] */
T = 2.4; // walls and floor (6 perimeters of 0.4) T = 2.4; // walls and floor (6 perimeters of 0.4)
PLATE = 3.0; // top plate PLATE = 3.0; // top plate
Z_BOT = -32; // flat underside (32 mm thick: the D300X sticks reach 28.5 down) TOP_GROW = 10; // extra height of the top shell only (room behind the display); the bottom shell is unchanged
Z_SPLIT = -12; // top shell / bottom shell Z_BOT = -32 - TOP_GROW; // flat underside (32 mm thick before TOP_GROW: the D300X sticks reach 28.5 down)
Z_SPLIT = -12 - TOP_GROW; // top shell / bottom shell
CHAMFER = 4; // 45 deg bottom edge (printable without support) CHAMFER = 4; // 45 deg bottom edge (printable without support)
TOP_CHAMFER = 1.5; // 45 deg top edge (the top shell prints face down) TOP_CHAMFER = 1.5; // 45 deg top edge (the top shell prints face down)
LIP_H = 2.5; // locating lip on the bottom shell, into the top shell LIP_H = 2.5; // locating lip on the bottom shell, into the top shell
@@ -53,7 +54,7 @@ INSERT_D = 4.0;
INSERT_L = 6; INSERT_L = 6;
SCREW_D = 3.4; SCREW_D = 3.4;
HEAD_D = 6.5; HEAD_D = 6.5;
HEAD_Z = -19; // counterbore floor: 7 mm of tower + 5 mm into the insert HEAD_Z = Z_SPLIT - 7; // counterbore floor: 7 mm of tower + 5 mm into the insert
/* [Joysticks] */ /* [Joysticks] */
STICK_HOLE_D = 40; STICK_HOLE_D = 40;
@@ -61,18 +62,21 @@ STICK_SCREW = 16.25; // 4 x M2.5 x 14 on a 32.5 mm square, through cover and
STICK_SCREW_D = 2.8; STICK_SCREW_D = 2.8;
/* [Display: Nextion NX4832T035] */ /* [Display: Nextion NX4832T035] */
NX_BOARD = [100.5, 54.94]; NX_BOARD = [100.6, 55]; // measured by the owner
NX_HOLES = [94.2, 48.5]; // M3 grid, centred on the board NX_HOLES = [94.2, 48.5]; // M3 grid, centred on the board
NX_CENTRE = [0, 20]; // board centre (forward of the sticks, so the strap misses it) NX_CENTRE = [0, 20]; // board centre (forward of the sticks, so the strap misses it)
NX_FLIP = true; // display mounted turned 180 deg (its J1 connector on the right, clear of NX_FLIP = true; // display mounted turned 180 deg (its J1 connector on the right, clear of
// the Teensy's USB plug): set display direction 180 in the Nextion Editor // the Teensy's USB plug): set display direction 180 in the Nextion Editor
NX_WIN_OFF = [NX_FLIP ? 2.15 : -2.15, 0]; // window (visible area) centre from the board centre NX_WIN_OFF = [NX_FLIP ? 2.15 : -2.15, 0]; // window (visible area) centre from the board centre
NX_WINDOW = [75.9, 50.9]; // opening in the plate NX_WINDOW = [75.9, 50.9]; // opening in the plate
NX_LCD = [84, 54]; // LCD module outline NX_LCD = [85.7, 55]; // LCD module outline (owner: 7.45 mm of board beside it on both sides, centred on the board)
NX_LCD_T = 4.5; // LCD thickness: approximate, measure before printing NX_LCD_CABLE = 1.3; // its flex cable sticks out this much on one short side (87 mm overall)
NX_BEZEL = 1.5; // plate left above the glass NX_LCD_T = 3.86; // LCD thickness (owner)
NX_POST_D = 5.5; // clears the LCD module by 0.2 mm NX_BACK = 11.21 - NX_LCD_T - 1.6; // board underside to back of the J1 connector (owner: 11.21 from the glass)
NX_SCREW_D = 2.2; // M2.5 self-tapping through the board NX_BEZEL = 1.0; // plate left above the glass (was 1.5: the display sat on the Teensy)
NX_POST_D = 5.5; // clears the LCD module (with its cable) by 0.2 mm
NX_SCREW_D = 2.5; // M3 tap drill: tap the posts for M3 x 5 machine screws through the board
NX_SKIN = 1.2; // plastic left between the tapped hole and the top face
/* [Switch: slide switch, mounted on top] */ /* [Switch: slide switch, mounted on top] */
SWITCH_POS = [0, -56]; SWITCH_POS = [0, -56];
@@ -128,7 +132,7 @@ HOOK_INSERTS = 7; // +- u
HOOK_BASE = [24, 18, 4]; // u, v, Z HOOK_BASE = [24, 18, 4]; // u, v, Z
// Alternative place: the front face (the edge away from you), 2 inserts in // Alternative place: the front face (the edge away from you), 2 inserts in
// the front wall of the bottom shell; the loop then points forward. // the front wall of the bottom shell; the loop then points forward.
HOOK_FRONT_Z = -19; HOOK_FRONT_Z = Z_SPLIT - 7;
HOOK_MOUNT = "top"; // [top, front] (assembly view only) HOOK_MOUNT = "top"; // [top, front] (assembly view only)
HOOK_HOLE_D = 8; // for the snap hook HOOK_HOLE_D = 8; // for the snap hook
HOOK_H = 16; // top of the loop above the top face HOOK_H = 16; // top of the loop above the top face
@@ -138,7 +142,7 @@ HOOK_H = 16; // top of the loop above the top face
// hands. Folded forward it wraps the front edge; swung back and down its // hands. Folded forward it wraps the front edge; swung back and down its
// crossbar rests against your chest or belly. M3 x 16 button-head screws // crossbar rests against your chest or belly. M3 x 16 button-head screws
// with a washer into heat-set inserts in the side walls; friction holds it. // with a washer into heat-set inserts in the side walls; friction holds it.
BAIL_PIVOT = [-25, -22]; // v, Z on the side faces (u +-SIDE_U) BAIL_PIVOT = [-25, Z_BOT + 10]; // v, Z on the side faces (u +-SIDE_U)
BAIL_L = 82; // pivot to crossbar centre line BAIL_L = 82; // pivot to crossbar centre line
BAIL_BOW = 10; // crossbar bows outwards by this much in the middle BAIL_BOW = 10; // crossbar bows outwards by this much in the middle
BAIL_T = 5; // arm thickness (u) BAIL_T = 5; // arm thickness (u)
@@ -217,8 +221,9 @@ module top_shell() render(convexity = 10) difference() {
translate([0, 0, 0.005]) cube(concat(NX_WINDOW, 0.01), center = true); translate([0, 0, 0.005]) cube(concat(NX_WINDOW, 0.01), center = true);
translate([0, 0, NX_BEZEL + 0.01]) cube(concat(NX_WINDOW + [2, 2] * NX_BEZEL, 0.02), center = true); translate([0, 0, NX_BEZEL + 0.01]) cube(concat(NX_WINDOW + [2, 2] * NX_BEZEL, 0.02), center = true);
} }
translate(concat(NX_WIN - (NX_LCD + [1, 1]) / 2, -PLATE - 1)) cube(concat(NX_LCD + [1, 1], PLATE + 1 - NX_BEZEL)); // LCD pocket: cable allowance on both short sides, so it fits either way round
nx_holes() translate([0, 0, NX_BOARD_TOP - 1]) cylinder(d = NX_SCREW_D, h = 1 + 4.5); translate(concat(NX_CENTRE - (NX_LCD + [2 * NX_LCD_CABLE + 0.4, 1]) / 2, -PLATE - 1)) cube(concat(NX_LCD + [2 * NX_LCD_CABLE + 0.4, 1], PLATE + 1 - NX_BEZEL));
nx_holes() translate([0, 0, NX_BOARD_TOP - 1]) cylinder(d = NX_SCREW_D, h = 1 - NX_BOARD_TOP - NX_SKIN);
// joysticks // joysticks
for (s = STICKS) translate([s[0], s[1], -BIG / 2]) cylinder(d = STICK_HOLE_D, h = BIG); for (s = STICKS) translate([s[0], s[1], -BIG / 2]) cylinder(d = STICK_HOLE_D, h = BIG);
stick_screws() translate([0, 0, -BIG / 2]) cylinder(d = STICK_SCREW_D, h = BIG); stick_screws() translate([0, 0, -BIG / 2]) cylinder(d = STICK_SCREW_D, h = BIG);
@@ -450,9 +455,9 @@ module nextion() {
translate(concat(-NX_BOARD / 2, 0)) cube(concat(NX_BOARD, 1.6)); translate(concat(-NX_BOARD / 2, 0)) cube(concat(NX_BOARD, 1.6));
for (du = [-1, 1], dv = [-1, 1]) translate([du * NX_HOLES[0], dv * NX_HOLES[1], 0] / 2 + [0, 0, -1]) cylinder(d = 3.2, h = 4); for (du = [-1, 1], dv = [-1, 1]) translate([du * NX_HOLES[0], dv * NX_HOLES[1], 0] / 2 + [0, 0, -1]) cylinder(d = 3.2, h = 4);
} }
translate(concat(NX_WIN - NX_LCD / 2, NX_BOARD_TOP)) color("#202020") cube(concat(NX_LCD, NX_LCD_T)); translate(concat(NX_CENTRE - NX_LCD / 2, NX_BOARD_TOP)) color("#202020") cube(concat(NX_LCD, NX_LCD_T));
translate(concat(NX_WIN - [73.44, 48.96] / 2, -NX_BEZEL - 0.2)) color("#3050a0") cube([73.44, 48.96, 0.2]); translate(concat(NX_WIN - [73.44, 48.96] / 2, -NX_BEZEL - 0.2)) color("#3050a0") cube([73.44, 48.96, 0.2]);
translate(concat(NX_CENTRE + [(NX_FLIP ? 1 : -1) * (NX_BOARD[0] / 2 - 7), -5], NX_BOARD_TOP - 1.6 - 6)) color("#eee") cube([6, 10, 6]); // J1 4-pin connector (approx.) translate(concat(NX_CENTRE + [(NX_FLIP ? 1 : -1) * (NX_BOARD[0] / 2 - 7), -5], NX_BOARD_TOP - 1.6 - NX_BACK)) color("#eee") cube([6, 10, NX_BACK]); // J1 4-pin connector (approx.)
} }
module ups_18650() translate(concat(UPS_CENTRE, UPS_Z)) { module ups_18650() translate(concat(UPS_CENTRE, UPS_Z)) {
+11
View File
@@ -0,0 +1,11 @@
#include "Battery.h"
#include "Config.h"
void Battery::update(float dt) {
if (BATTERY_SENSE_PIN == 255) return; // not fitted: stays 0
// Sticks set the ADC to ADC_BITS for every analogRead().
float v = analogRead(BATTERY_SENSE_PIN) * (BATTERY_ADC_REF_V / ((1 << ADC_BITS) - 1)) * BATTERY_DIVIDER;
if (!primed_) { volts_ = v; primed_ = true; return; }
float a = constrain(dt / 2.0f, 0.0f, 1.0f); // ~2 s time constant
volts_ += (v - volts_) * a;
}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <Arduino.h>
// Handset battery voltage through a resistor divider (Config.h BATTERY_*), smoothed.
class Battery {
public:
void update(float dt);
uint16_t millivolts() const { return (uint16_t)(volts_ * 1000.0f + 0.5f); } // 0 = not fitted
private:
float volts_ = 0;
bool primed_ = false;
};
+45 -33
View File
@@ -31,16 +31,18 @@ constexpr uint32_t LINK_LOST_MS = 300;
// Logical axis order used everywhere in the remote code. // Logical axis order used everywhere in the remote code.
enum StickAxis : uint8_t { L_X = 0, L_Y, L_TWIST, R_X, R_Y, R_TWIST, NUM_AXES }; enum StickAxis : uint8_t { L_X = 0, L_Y, L_TWIST, R_X, R_Y, R_TWIST, NUM_AXES };
// A0-A5 in a row, as wired for the old remote (2019-teensy-nrf24/remote/Joysticks.h). // The old remote had A0-A5 in a row (2019-teensy-nrf24/remote/Joysticks.h).
// A4/A5 are also Wire's SDA/SCL - that's why the MPU6050 is on Wire2 below. // The two wires on A4/A5 (pins 18/19) move to A7/A8 (pins 21/22), because
// BENCH: which physical axis is on which pin wasn't recoverable from the old // 18/19 are Wire's SDA/SCL for the MPU6050 (owner's choice 2026-11-17: edge
// code; reorder these so each lands on the right logical axis ('p' dump). // headers only, no pads underneath). A6 (20) stays free for the battery.
constexpr uint8_t STICK_PINS[NUM_AXES] = { A0, A1, A2, A3, A4, A5 }; // Checked on the real remote (2026-11-17): the left stick is on A3/A7/A8, the
// right stick on A0/A1/A2.
constexpr uint8_t STICK_PINS[NUM_AXES] = { A3, A7, A8, A0, A1, A2 };
// Each logical axis must end up: X + = pushed RIGHT, Y + = pushed FORWARD // Each logical axis must end up: X + = pushed RIGHT, Y + = pushed FORWARD
// (away from you), TWIST + = rotated COUNTERCLOCKWISE seen from above. // (away from you), TWIST + = rotated COUNTERCLOCKWISE seen from above.
// BENCH: flip any axis that reads the wrong way on the serial 'p' status dump. // Checked on the real remote (2026-11-17): every axis but the right twist reads inverted.
constexpr bool STICK_INVERT[NUM_AXES] = { false, false, false, false, false, false }; constexpr bool STICK_INVERT[NUM_AXES] = { true, true, true, true, true, false };
constexpr int ADC_BITS = 12; // 0..4095 constexpr int ADC_BITS = 12; // 0..4095
constexpr int ADC_AVERAGING = 8; // hardware averaging per analogRead() constexpr int ADC_AVERAGING = 8; // hardware averaging per analogRead()
@@ -69,17 +71,14 @@ constexpr float STICK_EXPO[NUM_AXES] = { 0.25f, 0.25f, 0.30f, 0.20f, 0.20f,
// One-pole low-pass on raw ADC counts (1 = no filtering). Pots are noisy. // One-pole low-pass on raw ADC counts (1 = no filtering). Pots are noisy.
constexpr float STICK_FILTER_ALPHA = 0.5f; constexpr float STICK_FILTER_ALPHA = 0.5f;
// ---- Remote IMU: MPU6050 on the third I2C bus (Wire2: SDA2 = 25, SCL2 = 24) ---- // ---- Remote IMU: MPU6050 on Wire (SDA = 18, SCL = 19) ----
// On the Teensy 4.0, 24/25 are solder pads on the underside, not edge pins. // Edge-header pins; the stick axes that used to be there moved to A7/A8.
// Not Wire (18/19): those pins are stick axes A4/A5. Not Wire1 (17/16) either: #define IMU_WIRE Wire
// those are stick axes A3/A2.
#define IMU_WIRE Wire2
constexpr uint8_t IMU_ADDR = 0x68; // 0x69 if AD0 is pulled high constexpr uint8_t IMU_ADDR = 0x68; // 0x69 if AD0 is pulled high
// Mounting remap: which chip axis (0=X,1=Y,2=Z) and sign gives each handset // Mounting remap: which chip axis (0=X,1=Y,2=Z) and sign gives each handset
// axis. Handset frame: +X = away from you, +Y = your left, +Z = up. // axis. Handset frame: +X = away from you, +Y = your left, +Z = up.
// BENCH: with the defaults the chip is assumed flat, component side up, its // Checked on the real remote (2026-11-17): the defaults are right - tipping
// X arrow pointing away from you. Verify with the serial 'p' dump: tipping // the far edge down reads +pitch, dipping the right side reads +roll.
// the far edge down must read +pitch, dipping the right side must read +roll.
constexpr uint8_t IMU_AXIS_FROM_CHIP[3] = { 0, 1, 2 }; constexpr uint8_t IMU_AXIS_FROM_CHIP[3] = { 0, 1, 2 };
constexpr int8_t IMU_AXIS_SIGN[3] = { +1, +1, +1 }; constexpr int8_t IMU_AXIS_SIGN[3] = { +1, +1, +1 };
constexpr float IMU_ALPHA = 0.98f; // complementary filter, same as the robot constexpr float IMU_ALPHA = 0.98f; // complementary filter, same as the robot
@@ -109,24 +108,37 @@ constexpr uint32_t WALK_LINGER_MS = 250;
// (post-deadzone, -1000..1000 scale), so the robot never arms mid-command. // (post-deadzone, -1000..1000 scale), so the robot never arms mid-command.
constexpr int16_t ARM_CENTER_TOLERANCE = 50; constexpr int16_t ARM_CENTER_TOLERANCE = 50;
// ---- Nextion touchscreen on Serial1 (RX1 = pin 0, TX1 = pin 1), as in the old remote ---- // ---- Nextion touchscreen on Serial2 (RX2 = pin 7, TX2 = pin 8) ----
#define NEXTION_SERIAL Serial1 // Found on the real remote (2026-11-17): the display answers on Serial2 at 115200. The old
// BENCH: the old sketch used the ITEAD library, whose nexInit() talks at 9600 // sketch's Serial1.begin() was a red herring; its ITEAD Nextion library used Serial2.
// unless it was modified. This firmware expects 115200: add `bauds=115200` #define NEXTION_SERIAL Serial2
// to the HMI's Program.s (see remote/NEXTION.md) or set 9600 here. // The HMI (remote/remote.HMI) sets this with `bauds=115200` in Program.s.
constexpr uint32_t NEXTION_BAUD = 115200; constexpr uint32_t NEXTION_BAUD = 115200;
// Controls live on this page (remote/NEXTION.md). Its components must have #define NEXTION_UPLOAD_PAGE "upload"
// vscope = global, so the firmware can update them whichever page is showing. // The firmware only writes the page that is showing (each page reports itself
#define NEXTION_CONTROL_PAGE "control" // with a 'P' frame), and only what changed since the last write.
// The old HMI's link-status texts, also vscope = global. Its pages are constexpr uint32_t NEXTION_RENDER_MS = 50; // repaint rate of the showing page
// 0 splashsceen (sic), 1 main, 2 servocal, 3 page0, 4 uploadscreen, constexpr uint32_t NEXTION_SERVOS_RENDER_MS = 100; // SERVOS page: 36 values, so a bit slower
// 5 joysticks; the texts are t1 on page 1 (main) and page 3 (page0).
constexpr const char* NEXTION_STATUS_TEXTS[] = { "main.t1", "page0.t1" };
// The old HMI's "upload" button: page 1, component id 5 (b2), sends the
// standard touch event. It puts the remote into Nextion upload passthrough.
constexpr uint8_t NEXTION_UPLOAD_BUTTON_PAGE = 1;
constexpr uint8_t NEXTION_UPLOAD_BUTTON_ID = 5;
#define NEXTION_UPLOAD_PAGE "uploadscreen"
constexpr uint32_t NEXTION_FULL_REFRESH_MS = 2000; // re-push everything periodically (self-heals after a display reset) constexpr uint32_t NEXTION_FULL_REFRESH_MS = 2000; // re-push everything periodically (self-heals after a display reset)
constexpr uint32_t NEXTION_LINK_REFRESH_MS = 250; // link-quality text update rate // A render is skipped while less than this is free in the TX buffer, so the
// TX loop never blocks on the display.
constexpr int NEXTION_TX_MIN_FREE = 400;
constexpr uint32_t STATUS_MESSAGE_MS = 2500; // how long transient status messages stay up constexpr uint32_t STATUS_MESSAGE_MS = 2500; // how long transient status messages stay up
constexpr uint32_t UPLOAD_CONFIRM_MS = 3000; // UPDATE DISPLAY: second tap within this
// ---- Robot telemetry (ack payloads) ----
constexpr uint32_t TELEMETRY_STALE_MS = 500; // older than this -> the display shows "no data"
// ---- Servo centre calibration (CAL page) ----
constexpr int16_t SERVO_TRIM_STEP_SMALL_US = 1;
constexpr int16_t SERVO_TRIM_STEP_BIG_US = 10;
// SAVE / REVERT go out for this long (the robot acts once; repeats are harmless).
constexpr uint32_t SERVO_CAL_OP_MS = 300;
// ---- Battery voltage (STATUS page) ----
// BENCH: not built yet. Planned: the 18650's + through a 100k/100k divider
// into A6 (pin 20) with 100 nF to GND (see README.md "Planned"). Then set
// the pin to A6. 255 = not fitted: the display shows "--".
constexpr uint8_t BATTERY_SENSE_PIN = 255;
constexpr float BATTERY_DIVIDER = 2.0f; // battery V / pin V
constexpr float BATTERY_ADC_REF_V = 3.3f;
+92 -97
View File
@@ -1,112 +1,107 @@
# Nextion HMI build guide # Nextion HMI
Work in `remote.HMI` in this folder (a copy of the old servo monitor, `remote.HMI` in this folder is the touchscreen project (NX4832T035, 480×320),
`../../2019-teensy-nrf24/remote-nextion/remote.HMI`, re-saved by a newer turned 180° (Editor display direction 270) because the display sits upside
Nextion Editor) and **add one page named `control`** with the components below. down in the remote.
It's **generated** by `../scripts/make_remote_hmi.py`: change the layout
there and re-run it, rather than editing the `.HMI` in Nextion Editor (an
Editor edit is lost on the next run). Then open `remote.HMI` in Nextion
Editor, compile, and upload the `.tft`: SETUP › UPDATE DISPLAY (tap twice)
or serial key `U` puts the remote in USB passthrough for the upload. In the
Editor, upload to the Teensy's COM port with the baud rate on auto. When the
Editor is newer than the display's firmware, the upload first updates that
firmware: don't interrupt it. Power-cycle the remote afterwards to leave
upload mode.
The old HMI's pages: The display is on the remote's **Serial2** (Teensy RX2 = pin 7, TX2 = pin 8),
at 115200.
| # | Name | Contents |
|---|------|----------|
| 0 | `splashsceen` (sic) | start page |
| 1 | `main` | `t1` link status, `b2` (id 5) upload mode |
| 2 | `servocal` | servo calibration (not used by this firmware) |
| 3 | `page0` | servo sliders `h0`–`h17`, `t1` link status. Note the name: `page page0` opens this page, `page 0` (a number) opens the splash |
| 4 | `uploadscreen` | shown during upload mode |
| 5 | `joysticks` | not used by this firmware |
Your existing pages keep working:
| Existing | What the firmware does with it |
|----------|--------------------------------|
| page 1 `t1`, page 3 `t1` | writes `connected` / `not connected`, as the old firmware did, as `main.t1` and `page0.t1` (`NEXTION_STATUS_TEXTS` in `Config.h`). Set both to **vscope = global** |
| page 1 `b2` (id 5) | **upload mode**: keep "Send Component ID" ticked on it. The remote shows `uploadscreen` and passes USB straight through to the display, so Nextion Editor can upload over the remote's USB port. Power-cycle to leave. Serial key `U` does the same |
| page 4 `uploadscreen` | shown on entering upload mode |
| page 3 sliders `h0`–`h17` | not driven yet: the robot doesn't send servo positions back (that needs the planned telemetry channel) |
The firmware drives the display by **component name**, and the display
talks back with small custom frames sent from each button's touch event.
Layout, fonts and colors are up to you. The names and event code must
match exactly.
**Set every component on `control` to vscope = global.** The firmware
writes them as `control.<name>` and keeps them current whichever page is
showing. A local component on another page can't be written from outside,
and with `bkcmd=0` the display ignores those writes silently.
The remote is authoritative. Use **plain Button** components (not
Dual-state buttons) and don't toggle anything locally in the HMI. The
remote repaints every label and color from its own state, including a
full redraw every 2 s and whenever the display reboots.
## Program.s / page setup
In **Program.s**, before `page 0`, add:
``` ```
bauds=115200 python scripts\make_remote_hmi.py (from 2026-current)
``` ```
This sets the display to the `NEXTION_BAUD` in `remote/Config.h`. The It needs the `tools/nextion-hmi-tools` submodule, Pillow, DejaVu Sans Mono
display ships at 9600, and `bauds=` persists across power cycles. The old (found in matplotlib, or `--font-dir`), and the old remote HMI
firmware used the ITEAD library at 9600, so your HMI probably runs at 9600 (`../../2019-teensy-nrf24/remote-nextion/remote.HMI`, read only) for the
today. splash picture. To look at a page without the Editor, use the `nxhmi` MCP
server's `render_page`.
Name the new page `control`. The firmware never changes pages, except ## Pages
into `uploadscreen` for upload mode. Add buttons on your other pages to
switch to it (`page control`).
## Components | id | Page | Contents |
|----|------|----------|
| 0 | `splash` | spider picture, 1.5 s, then `drive` |
| 1 | `drive` | ARM, SIT/STAND, gait, mode, right-stick mode, both gyros, speed + height sliders, messages |
| 2 | `status` | remote and robot IMU roll/pitch, the 6 stick axes, both batteries, radio |
| 3 | `servos` | all 18 joint angles (robot telemetry), laid out as a top view of the robot |
| 4 | `cal` | servo centre calibration: START/STOP, leg and joint, trim ±1/±10 µs, ZERO, REVERT, SAVE |
| 5 | `setup` | stick calibration, LEVEL REMOTE, UPDATE DISPLAY, backlight, versions |
| 6 | `upload` | shown during display update mode |
Text components need **txt_maxl** at least as large as the longest string Pages 1–5 share a frame: a top bar (`tLink` link quality, `tState` robot
the firmware writes. Button bounds here allow some slack. state + battery, red `bKill` DISARM) and tab buttons `bTab0`–`bTab4` that
switch pages locally (`page drive`, ...). The page order is the page id, and
must match `UiPage` in `UiTypes.h`.
| Name | Type | txt_maxl | Firmware writes | ## How the firmware talks to it
|----------|---------|----------|----------------------------------------------|
| `bArm` | Button | 10 | `ARMED` / `DISARMED`, bco red / gray |
| `bKill` | Button | – | nothing (static "DISARM" label, make it red) |
| `bStand` | Button | 6 | `STAND` / `SIT`, bco green / gray |
| `bGait` | Button | 8 | `TRIPOD` / `WAVE` |
| `bMode` | Button | 8 | `DIRECT` / `HEADING` |
| `bRs` | Button | 10 | `R: ROTATE` / `R: MOVE` |
| `bRGyro` | Button | – | bco green / gray (label it "REMOTE GYRO") |
| `bBGyro` | Button | – | bco green / gray (label it "ROBOT GYRO") |
| `hSpeed` | Slider | – | `val` 0..255 (set **maxval = 255**) |
| `nSpeed` | Number | – | `val` 0..100 (speed %) |
| `hHeight`| Slider | – | `val` 0..200, 100 = default (set **maxval = 200**) |
| `nHeight`| Number | – | `val` -100..100 (height offset %) |
| `bCal` | Button | 9 | `CAL` / `SAVE CAL`, bco orange while active |
| `bCalX` | Button | – | nothing (static "CANCEL CAL") |
| `bZero` | Button | – | nothing (static "LEVEL") |
| `tLink` | Text | 10 | `LINK 97%` / `NO LINK`, pco green / red |
| `tMsg` | Text | 40 | status / rejection messages |
## Touch events - **Display → remote:** every touch sends a custom frame with `printh`:
`'#'` (0x23), length, command byte, optional value byte. "Send Component
ID" is off everywhere.
- **Page tracking:** each page's Preinitialize event sends `'P'` + its page
id, so the remote always knows which page is showing. After a remote
restart it asks with `sendme`.
- **Remote → display:** the remote writes only the showing page, by local
component name (no `vscope = global`, no display RAM spent), and only
what changed (`NextionUI` hashes every instruction). Everything is
re-sent every 2 s and after the display restarts (0x88), so a dropped
byte heals itself. Render rate is 20 Hz (SERVOS 10 Hz), and a render is
skipped rather than blocking when the TX buffer is full.
- **The remote is authoritative:** plain buttons only, nothing toggles
locally. Exceptions that are purely local: the tabs, and the backlight
slider (`dim` / `dims`).
- `Program.s` sets `bauds=115200` (= `NEXTION_BAUD` in `Config.h`), stored in the display.
Put this in each component's **Touch Release Event** (the Speed slider ## Commands (display → remote)
uses **Touch Move** as well so the value tracks your finger). Frame format:
`'#'` (0x23), length, command byte, optional value byte.
| Component | Event code | Command | | Component | Event code | Command |
|-----------|------------------------------------------|--------------------------------| |-----------|-----------|---------|
| `bArm` | `printh 23 01 41` | `A` toggle arm (needs sticks centered) | | every page | `printh 23 02 50 <id>` (Preinitialize) | `P` page shown |
| `bKill` | `printh 23 01 4B` | `K` disarm, always accepted | | `bKill` | `printh 23 01 4B` | `K` disarm, always accepted |
| `bStand` | `printh 23 01 53` | `S` toggle sit/stand | | `bArm` | `printh 23 01 41` | `A` toggle arm (needs sticks centered) |
| `bGait` | `printh 23 01 47` | `G` tripod ↔ wave | | `bStand` | `printh 23 01 53` | `S` toggle sit/stand |
| `bMode` | `printh 23 01 4D` | `M` direct ↔ heading-hold | | `bGait` | `printh 23 01 47` | `G` tripod ↔ wave |
| `bRs` | `printh 23 01 58` | `X` right stick rotate ↔ translate | | `bMode` | `printh 23 01 4D` | `M` direct ↔ heading-hold |
| `bRGyro` | `printh 23 01 52` | `R` remote-gyro tilt on/off | | `bRs` | `printh 23 01 58` | `X` right stick rotate ↔ translate |
| `bBGyro` | `printh 23 01 42` | `B` robot self-stabilize on/off | | `bRGyro` | `printh 23 01 52` | `R` remote-gyro tilt on/off |
| `hSpeed` | `printh 23 02 56`<br>`prints hSpeed.val,1` | `V` + speed byte | | `bBGyro` | `printh 23 01 42` | `B` robot self-stabilize on/off |
| `hHeight` | `printh 23 02 48`<br>`prints hHeight.val,1` | `H` + height byte (Touch Move + Release) | | `hSpeed` | `printh 23 02 56` + `prints hSpeed.val,1` (move + release) | `V` + speed 0..255 |
| `bZero` | `printh 23 01 5A` | `Z` zero handset level | | `hHeight` | `printh 23 02 48` + `prints hHeight.val,1` (move + release) | `H` + height 0..200, 100 = default |
| `bCal` | `printh 23 01 43` | `C` start / save stick calibration | | `bCal` | `printh 23 01 43` | `C` start / save stick calibration |
| `bCalX` | `printh 23 01 51` | `Q` cancel calibration | | `bCalX` | `printh 23 01 51` | `Q` cancel stick calibration |
| `bZero` | `printh 23 01 5A` | `Z` zero handset level |
| `bUpd` | `printh 23 01 55` | `U` display update mode (second tap within 3 s) |
| `bCalOn` | `printh 23 01 4F` | `O` servo calibration start/stop |
| `bL0`–`bL5` | `printh 23 02 4C 0n` | `L` + leg (0 FR, 1 MR, 2 RR, 3 RL, 4 ML, 5 FL) |
| `bJ0`–`bJ2` | `printh 23 02 4A 0n` | `J` + joint (0 coxa, 1 femur, 2 tibia) |
| `bM10` `bM1` `bP1` `bP10` `bZeroT` | `printh 23 02 54 0n` | `T` + trim step: 0 −10, 1 −1, 2 +1, 3 +10, 4 zero (µs) |
| `bSave` | `printh 23 01 57` | `W` save trims on the robot |
| `bRevert` | `printh 23 01 45` | `E` reload trims from the robot's EEPROM |
**Uncheck "Send Component ID"** on every component on `control`: those To add a control: pick an unused command byte, add it to
standard touch frames only add serial traffic. The one exception is the old `NextionUI::decodeCustom()` and `UiCmd`, handle it in `RemoteState::handle()`,
page 1 `b2` upload button (see the top). add the component in `make_remote_hmi.py`, and a row here.
Protocol details and the parser live in `NextionUI.h/.cpp`. To add a ## What the remote writes (remote → display)
control, pick an unused command byte, add it to `NextionUI::decodeCustom()`
and `UiCmd`, handle it in `RemoteState::handle()`, and add a row here. | Page | Components |
|------|-----------|
| all but splash/upload | `tLink` txt/pco, `tState` txt/pco |
| drive | `bArm` `bStand` txt/bco, `bGait` `bMode` `bRs` txt, `bRGyro` `bBGyro` bco, `hSpeed` `hHeight` val, `tSpeed` `tHeight` `tMsg` txt |
| status | `tRRoll` `tRPitch` `tBRoll` `tBPitch` txt, `hRRoll` `hRPitch` `hBRoll` `hBPitch` val (0..90 = ±45°), `hLX` `hLY` `hLT` `hRX` `hRY` `hRT` val (0..200 = ±1000), `tBatt` `tRadio` txt. The indicator sliders have touch switched off (`tsw` in Preinitialize) |
| servos | `tJ0`–`tJ17` txt (index = leg × 3 + joint), `jJ0`–`jJ17` val (position in the servo's travel), `tSrv` txt/pco |
| cal | `bCalOn` txt/bco, `bL0`–`bL5` `bJ0`–`bJ2` bco (selected = green), `tTrim` txt, `bSave` bco (orange = unsaved), `tMsg` txt |
| setup | `bCal` txt/bco, `bUpd` txt/bco, `tVer` txt, `tMsg` txt |
`txt_maxl` of each text is set in the generator to fit the longest string
the firmware writes. Keep them in step when you change a format string.
+208 -63
View File
@@ -6,27 +6,29 @@ static constexpr uint16_t COL_ON = 2016; // green
static constexpr uint16_t COL_OFF = 50712; // Nextion default light gray static constexpr uint16_t COL_OFF = 50712; // Nextion default light gray
static constexpr uint16_t COL_DANGER = 63488; // red static constexpr uint16_t COL_DANGER = 63488; // red
static constexpr uint16_t COL_WARN = 64512; // orange static constexpr uint16_t COL_WARN = 64512; // orange
static constexpr uint16_t COL_TEXT = 65535; // white (top bar text)
static constexpr uint16_t COL_DIM = 33808; // gray (no data)
// The default 64-byte TX buffer would make a full redraw (~400 bytes at // The default 64-byte TX buffer would make a full redraw (~1 kB at 115200
// 115200 baud) block the TX loop for ~35 ms. Give it room to queue. // baud) block the TX loop for ~90 ms. Give it room to queue.
static uint8_t tx_extra[1024]; static uint8_t tx_extra[2048];
static uint8_t rx_extra[128]; static uint8_t rx_extra[128];
// Every control lives on NEXTION_CONTROL_PAGE with vscope = global, so it's static const char* const LEG_NAMES[6] = { "FR", "MR", "RR", "RL", "ML", "FL" }; // robot leg order
// addressed as page.component and can be updated whichever page is showing. static const char* const JOINT_NAMES[3] = { "coxa", "femur", "tibia" };
#define P NEXTION_CONTROL_PAGE "."
void NextionUI::begin() { void NextionUI::begin() {
NEXTION_SERIAL.begin(NEXTION_BAUD); NEXTION_SERIAL.begin(NEXTION_BAUD);
NEXTION_SERIAL.addMemoryForWrite(tx_extra, sizeof(tx_extra)); NEXTION_SERIAL.addMemoryForWrite(tx_extra, sizeof(tx_extra));
NEXTION_SERIAL.addMemoryForRead(rx_extra, sizeof(rx_extra)); NEXTION_SERIAL.addMemoryForRead(rx_extra, sizeof(rx_extra));
cmd("bkcmd=0"); // no success/fail replies - we never need them (and a cmd("bkcmd=0"); // no success/fail replies - we never need them (and a write
// write to a page the HMI doesn't have is then just ignored) // to a component that isn't on the showing page is ignored)
cmd("sendme"); // which page is showing? (the display may have kept running)
force_full_ = true; force_full_ = true;
} }
void NextionUI::cmd(const char* fmt, ...) { void NextionUI::cmd(const char* fmt, ...) {
char buf[80]; char buf[96];
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap); vsnprintf(buf, sizeof(buf), fmt, ap);
@@ -37,6 +39,30 @@ void NextionUI::cmd(const char* fmt, ...) {
NEXTION_SERIAL.write(0xFF); NEXTION_SERIAL.write(0xFF);
} }
void NextionUI::put(const char* fmt, ...) {
char buf[96];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
uint32_t h = 2166136261u; // FNV-1a
for (const char* c = buf; *c; c++) h = (h ^ (uint8_t)*c) * 16777619u;
h |= 1; // 0 = empty slot
bool cached = slot_ < MAX_SLOTS;
if (cached && !full_ && cache_[slot_] == h) { slot_++; return; }
if (cached) cache_[slot_] = h;
slot_++;
NEXTION_SERIAL.print(buf);
NEXTION_SERIAL.write(0xFF);
NEXTION_SERIAL.write(0xFF);
NEXTION_SERIAL.write(0xFF);
}
void NextionUI::setPage(uint8_t page) {
page_ = page;
force_full_ = true; // a newly shown page has its HMI defaults: write everything
}
// ---- Receive ---- // ---- Receive ----
bool NextionUI::decodeCustom(UiEvent& out) { bool NextionUI::decodeCustom(UiEvent& out) {
@@ -55,26 +81,37 @@ bool NextionUI::decodeCustom(UiEvent& out) {
case 'Z': out.cmd = UiCmd::ZeroGyro; break; case 'Z': out.cmd = UiCmd::ZeroGyro; break;
case 'C': out.cmd = UiCmd::CalStartSave; break; case 'C': out.cmd = UiCmd::CalStartSave; break;
case 'Q': out.cmd = UiCmd::CalCancel; break; case 'Q': out.cmd = UiCmd::CalCancel; break;
case 'U': out.cmd = UiCmd::NextionUpload; break; case 'U': out.cmd = UiCmd::UploadRequest; break;
case 'O': out.cmd = UiCmd::ServoCalToggle; break;
case 'L': out.cmd = UiCmd::ServoCalLeg; break;
case 'J': out.cmd = UiCmd::ServoCalJoint; break;
case 'T': out.cmd = UiCmd::ServoCalTrim; break;
case 'W': out.cmd = UiCmd::ServoCalSave; break;
case 'E': out.cmd = UiCmd::ServoCalRevert; break;
case 'P':
if (out.value == page_) return false; // same page again: nothing changes
setPage(out.value);
out.cmd = UiCmd::PageShown;
break;
default: return false; default: return false;
} }
return true; return true;
} }
// Standard Nextion frames (terminated FF FF FF). Two matter: // Standard Nextion frames (terminated FF FF FF). Two matter:
// 0x88 / 0x00 display (re)started -> redraw everything // 0x88 / 0x00 display (re)started -> redraw everything (its start page
// 0x65 page id event touch event from a component with "Send Component // then reports itself with 'P')
// ID" ticked - how the old HMI's upload button (b2) // 0x66 page reply to `sendme`: the page that is showing
// reports, so it keeps working unchanged.
bool NextionUI::decodeNative(UiEvent& out) { bool NextionUI::decodeNative(UiEvent& out) {
if (native_buf_[0] == 0x88 || native_buf_[0] == 0x00) { if (native_buf_[0] == 0x88 || native_buf_[0] == 0x00) {
force_full_ = true; force_full_ = true;
return false; return false;
} }
if (native_buf_[0] == 0x65 && native_len_ >= 4 && if (native_buf_[0] == 0x66 && native_len_ >= 5) {
native_buf_[1] == NEXTION_UPLOAD_BUTTON_PAGE && native_buf_[2] == NEXTION_UPLOAD_BUTTON_ID) { if (native_buf_[1] == page_) return false;
out.cmd = UiCmd::NextionUpload; setPage(native_buf_[1]);
out.value = 0; out.cmd = UiCmd::PageShown;
out.value = native_buf_[1];
return true; return true;
} }
return false; return false;
@@ -131,62 +168,170 @@ bool NextionUI::poll(UiEvent& out) {
// ---- Render ---- // ---- Render ----
void NextionUI::pushState(const UiView& v, bool full) { static const char* robotStateName(uint8_t s) {
const UiView& s = shown_; switch (s) {
if (full || v.armed != s.armed) { case TSTATE_DISARMED: return "DISARMED";
cmd(P "bArm.txt=\"%s\"", v.armed ? "ARMED" : "DISARMED"); case TSTATE_SIT: return "SIT";
cmd(P "bArm.bco=%u", v.armed ? COL_DANGER : COL_OFF); case TSTATE_STAND: return "STAND";
case TSTATE_WALKING: return "WALKING";
case TSTATE_SERVO_CAL: return "SERVO CAL";
default: return "?";
} }
if (full || v.stand != s.stand) {
cmd(P "bStand.txt=\"%s\"", v.stand ? "STAND" : "SIT");
cmd(P "bStand.bco=%u", v.stand ? COL_ON : COL_OFF);
}
if (full || v.gait_wave != s.gait_wave) cmd(P "bGait.txt=\"%s\"", v.gait_wave ? "WAVE" : "TRIPOD");
if (full || v.mode_b != s.mode_b) cmd(P "bMode.txt=\"%s\"", v.mode_b ? "HEADING" : "DIRECT");
if (full || v.rstick_xlate != s.rstick_xlate) cmd(P "bRs.txt=\"%s\"", v.rstick_xlate ? "R: MOVE" : "R: ROTATE");
if (full || v.remote_gyro != s.remote_gyro) cmd(P "bRGyro.bco=%u", v.remote_gyro ? COL_ON : COL_OFF);
if (full || v.robot_gyro != s.robot_gyro) cmd(P "bBGyro.bco=%u", v.robot_gyro ? COL_ON : COL_OFF);
if (full || v.speed_target != s.speed_target) {
cmd(P "hSpeed.val=%u", v.speed_target);
cmd(P "nSpeed.val=%u", (v.speed_target * 100 + 127) / 255);
}
if (full || v.height != s.height) {
cmd(P "hHeight.val=%d", v.height / 10 + 100); // slider 0..200, 100 = default
cmd(P "nHeight.val=%d", v.height / 10); // -100..100 %
}
if (full || v.calibrating != s.calibrating) {
cmd(P "bCal.txt=\"%s\"", v.calibrating ? "SAVE CAL" : "CAL");
cmd(P "bCal.bco=%u", v.calibrating ? COL_WARN : COL_OFF);
}
if (full || v.message != s.message) cmd(P "tMsg.txt=\"%s\"", v.message);
} }
void NextionUI::pushLink(const UiView& v) { // "7.2V", or "--" when the battery isn't measured.
if (v.link_ok) cmd(P "tLink.txt=\"LINK %u%%\"", v.link_pct); static const char* volts(char* buf, size_t n, uint16_t mv) {
else cmd(P "tLink.txt=\"NO LINK\""); if (mv == 0) snprintf(buf, n, "--");
cmd(P "tLink.pco=%u", v.link_ok ? COL_ON : COL_DANGER); else snprintf(buf, n, "%u.%uV", mv / 1000, (mv % 1000) / 100);
// The old HMI's own status texts, same wording as the old firmware. return buf;
for (const char* t : NEXTION_STATUS_TEXTS) }
cmd("%s.txt=\"%s\"", t, v.link_ok ? "connected" : "not connected");
// Angles are shown to 0.5 deg, so sensor noise doesn't repaint every frame.
static float halfDeg(float d) { return roundf(d * 2.0f) / 2.0f; }
void NextionUI::renderTopBar(const UiView& v) {
if (v.link_ok) put("tLink.txt=\"LINK %u%%\"", v.link_pct);
else put("tLink.txt=\"NO LINK\"");
put("tLink.pco=%u", v.link_ok ? COL_ON : COL_DANGER);
char b[8];
if (v.tele_ok) put("tState.txt=\"ROBOT %s %s\"", robotStateName(v.tele.state), volts(b, sizeof(b), v.tele.battery_mv));
else put("tState.txt=\"ROBOT: NO DATA\"");
put("tState.pco=%u", v.tele_ok ? COL_TEXT : COL_DIM);
}
void NextionUI::renderDrive(const UiView& v) {
put("bArm.txt=\"%s\"", v.armed ? "ARMED" : "DISARMED");
put("bArm.bco=%u", v.armed ? COL_DANGER : COL_OFF);
put("bStand.txt=\"%s\"", v.stand ? "STAND" : "SIT");
put("bStand.bco=%u", v.stand ? COL_ON : COL_OFF);
put("bGait.txt=\"%s\"", v.gait_wave ? "WAVE" : "TRIPOD");
put("bMode.txt=\"%s\"", v.mode_b ? "HEADING" : "DIRECT");
put("bRs.txt=\"%s\"", v.rstick_xlate ? "R: MOVE" : "R: ROTATE");
put("bRGyro.bco=%u", v.remote_gyro ? COL_ON : COL_OFF);
put("bBGyro.bco=%u", v.robot_gyro ? COL_ON : COL_OFF);
put("hSpeed.val=%u", v.speed_target);
put("tSpeed.txt=\"%u%%\"", (v.speed_target * 100 + 127) / 255);
put("hHeight.val=%d", v.height / 10 + 100); // slider 0..200, 100 = default
put("tHeight.txt=\"%+d%%\"", v.height / 10);
put("tMsg.txt=\"%s\"", v.message);
}
void NextionUI::renderStatus(const UiView& v) {
// Handset IMU, sliders 0..90 = -45..+45 deg
if (v.imu_ok) {
put("tRRoll.txt=\"roll %+.1f\"", halfDeg(v.imu_roll));
put("tRPitch.txt=\"pitch %+.1f\"", halfDeg(v.imu_pitch));
} else {
put("tRRoll.txt=\"roll no IMU\"");
put("tRPitch.txt=\"pitch no IMU\"");
}
put("hRRoll.val=%d", (int)constrain(lroundf(v.imu_roll) + 45, 0L, 90L));
put("hRPitch.val=%d", (int)constrain(lroundf(v.imu_pitch) + 45, 0L, 90L));
// Robot IMU, from telemetry
float br = v.tele.roll_ddeg / 10.0f, bp = v.tele.pitch_ddeg / 10.0f;
bool robot_imu = v.tele_ok && (v.tele.status & TSTAT_IMU_OK);
if (robot_imu) {
put("tBRoll.txt=\"roll %+.1f\"", halfDeg(br));
put("tBPitch.txt=\"pitch %+.1f\"", halfDeg(bp));
} else {
put("tBRoll.txt=\"roll %s\"", v.tele_ok ? "no IMU" : "--");
put("tBPitch.txt=\"pitch %s\"", v.tele_ok ? "no IMU" : "--");
}
put("hBRoll.val=%d", robot_imu ? (int)constrain(lroundf(br) + 45, 0L, 90L) : 45);
put("hBPitch.val=%d", robot_imu ? (int)constrain(lroundf(bp) + 45, 0L, 90L) : 45);
// Sticks, sliders 0..200 = -1000..+1000
static const char* const STICKS[NUM_AXES] = { "hLX", "hLY", "hLT", "hRX", "hRY", "hRT" };
for (int i = 0; i < NUM_AXES; i++) put("%s.val=%d", STICKS[i], (v.sticks[i] + 1000) / 10);
char a[8], b[8];
put("tBatt.txt=\"battery remote %s robot %s\"", volts(a, sizeof(a), v.battery_mv),
v.tele_ok ? volts(b, sizeof(b), v.tele.battery_mv) : "--");
if (!v.link_ok) put("tRadio.txt=\"radio no link\"");
else if (v.tele_ok) put("tRadio.txt=\"radio %u%% acked, robot hears %u/s\"", v.link_pct, v.tele.rx_per_sec);
else put("tRadio.txt=\"radio %u%% acked, no telemetry\"", v.link_pct);
}
void NextionUI::renderServos(const UiView& v) {
for (int i = 0; i < 18; i++) {
int joint = i % 3;
if (v.tele_ok) {
int deg = v.tele.joint_deg[i] - (joint == 2 ? TELEMETRY_TIBIA_OFFSET_DEG : 0);
// Bar = position within the servo's travel: coxa/femur -90..90, tibia -180..0.
int pct = (deg + (joint == 2 ? 180 : 90)) * 100 / 180;
put("tJ%d.txt=\"%-5s %+4d\"", i, JOINT_NAMES[joint], deg);
put("jJ%d.val=%d", i, constrain(pct, 0, 100));
} else {
put("tJ%d.txt=\"%-5s --\"", i, JOINT_NAMES[joint]);
put("jJ%d.val=0", i);
}
}
const char* s = !v.tele_ok ? "NO DATA"
: v.tele.state == TSTATE_SERVO_CAL ? "CENTRE"
: (v.tele.status & TSTAT_SERVOS_ON) ? "LIVE"
: "RELAXED";
put("tSrv.txt=\"%s\"", s);
put("tSrv.pco=%u", !v.tele_ok ? COL_DIM : (v.tele.status & TSTAT_SERVOS_ON) ? COL_ON : 0);
}
void NextionUI::renderCal(const UiView& v) {
put("bCalOn.txt=\"%s\"", v.servo_cal ? "STOP" : "START");
put("bCalOn.bco=%u", v.servo_cal ? COL_WARN : COL_OFF);
for (int i = 0; i < 6; i++) put("bL%d.bco=%u", i, v.servo_sel / 3 == i ? COL_ON : COL_OFF);
for (int j = 0; j < 3; j++) put("bJ%d.bco=%u", j, v.servo_sel % 3 == j ? COL_ON : COL_OFF);
const char* leg = LEG_NAMES[v.servo_sel / 3];
const char* joint = JOINT_NAMES[v.servo_sel % 3];
if (!v.servo_cal) put("tTrim.txt=\"%s %s\"", leg, joint);
else if (!v.trim_synced) put("tTrim.txt=\"%s %s ...\"", leg, joint);
else put("tTrim.txt=\"%s %s %+dus\"", leg, joint, v.trim_us);
bool dirty = v.tele_ok && (v.tele.status & TSTAT_CAL_DIRTY);
put("bSave.bco=%u", dirty ? COL_WARN : COL_OFF);
const char* hint = v.message[0] ? v.message
: !v.servo_cal ? "Robot on a stand, disarmed: START"
: !v.tele_ok ? "No telemetry from the robot"
: v.tele.state != TSTATE_SERVO_CAL ? "Waiting for the robot"
: dirty ? "Unsaved trims: SAVE keeps them"
: "Trim until the horn is square";
put("tMsg.txt=\"%s\"", hint);
}
void NextionUI::renderSetup(const UiView& v) {
put("bCal.txt=\"%s\"", v.stick_calibrating ? "SAVE CAL" : "CAL STICKS");
put("bCal.bco=%u", v.stick_calibrating ? COL_WARN : COL_OFF);
put("bUpd.txt=\"%s\"", v.upload_confirm ? "TAP AGAIN" : "UPDATE DISPLAY");
put("bUpd.bco=%u", v.upload_confirm ? COL_WARN : COL_OFF);
put("tVer.txt=\"remote fw %s protocol v%u radio ch %u\"", __DATE__, HXP_PROTOCOL_VERSION, HXP_RADIO_CHANNEL);
put("tMsg.txt=\"%s\"", v.message);
} }
void NextionUI::render(const UiView& v, uint32_t now_ms) { void NextionUI::render(const UiView& v, uint32_t now_ms) {
bool full = force_full_ || (now_ms - last_full_ms_) >= NEXTION_FULL_REFRESH_MS; uint32_t interval = page_ == PAGE_SERVOS ? NEXTION_SERVOS_RENDER_MS : NEXTION_RENDER_MS;
if (full) { if (!force_full_ && (now_ms - last_render_ms_) < interval) return;
// Never block the TX loop on the display: wait for the buffer to drain.
if (NEXTION_SERIAL.availableForWrite() < NEXTION_TX_MIN_FREE) return;
last_render_ms_ = now_ms;
full_ = force_full_ || (now_ms - last_full_ms_) >= NEXTION_FULL_REFRESH_MS;
if (full_) {
force_full_ = false; force_full_ = false;
last_full_ms_ = now_ms; last_full_ms_ = now_ms;
if (page_ == PAGE_UNKNOWN) cmd("sendme"); // still don't know the page: ask again
} }
slot_ = 0;
pushState(v, full); switch (page_) {
case PAGE_DRIVE: renderTopBar(v); renderDrive(v); break;
// Link quality changes nearly every packet; repaint it at a readable rate, case PAGE_STATUS: renderTopBar(v); renderStatus(v); break;
// but immediately when the link comes or goes. case PAGE_SERVOS: renderTopBar(v); renderServos(v); break;
if (full || v.link_ok != shown_.link_ok || (now_ms - last_link_ms_) >= NEXTION_LINK_REFRESH_MS) { case PAGE_CAL: renderTopBar(v); renderCal(v); break;
pushLink(v); case PAGE_SETUP: renderTopBar(v); renderSetup(v); break;
last_link_ms_ = now_ms; default: break; // splash / upload / unknown: nothing to show
} }
shown_ = v;
} }
// ---- Upload passthrough ---- // ---- Upload passthrough ----
+31 -12
View File
@@ -7,17 +7,21 @@
// Nextion -> remote: custom frames the HMI's touch events send with printh: // Nextion -> remote: custom frames the HMI's touch events send with printh:
// '#' <len> <cmd> [value] e.g. printh 23 01 41 (ToggleArm) // '#' <len> <cmd> [value] e.g. printh 23 01 41 (ToggleArm)
// printh 23 02 56 + prints hSpeed.val,1 // printh 23 02 56 + prints hSpeed.val,1
// Command bytes are listed in NEXTION.md and in NextionUI.cpp. // Command bytes are listed in NEXTION.md and in NextionUI.cpp. Every
// Native Nextion return frames (terminated FF FF FF) are also parsed: a // page's Preinitialize event sends 'P' + its page id, so the remote always
// display reset (0x88 "ready") triggers a full redraw, and the old HMI's // knows which page is showing. Native Nextion return frames (terminated
// upload button sends a standard touch event (0x65) that's recognized. // FF FF FF) are parsed too: a display reset (0x88 "ready") triggers a
// full redraw, and the reply to `sendme` (0x66 page) gives the page after
// the remote itself restarted.
// //
// remote -> Nextion: plain instructions ("bArm.txt=\"ARMED\"" + FF FF FF). // remote -> Nextion: plain instructions ("bArm.txt=\"ARMED\"" + FF FF FF).
// //
// The remote is authoritative: buttons are plain buttons (not dual-state), // Only the page that is showing is written (by local component names), and
// they only send requests, and render() repaints whatever the remote state // only what changed: every instruction is hashed into a per-page cache. The
// actually is. A Nextion reboot or a dropped byte self-heals on the next // remote is authoritative: buttons are plain buttons, they only send
// periodic full refresh. // requests, and render() repaints whatever the remote state actually is. A
// Nextion reboot or a dropped byte self-heals on the next periodic full
// refresh.
class NextionUI { class NextionUI {
public: public:
void begin(); void begin();
@@ -35,14 +39,29 @@ private:
uint8_t native_buf_[8]; uint8_t native_buf_[8];
uint8_t native_len_ = 0, ff_run_ = 0; uint8_t native_len_ = 0, ff_run_ = 0;
UiView shown_; uint8_t page_ = PAGE_UNKNOWN;
bool force_full_ = true; bool force_full_ = true;
uint32_t last_full_ms_ = 0; uint32_t last_full_ms_ = 0;
uint32_t last_link_ms_ = 0; uint32_t last_render_ms_ = 0;
// Change cache: one hash per instruction, in the order a page's render
// issues them (the same every time).
static constexpr int MAX_SLOTS = 96;
uint32_t cache_[MAX_SLOTS] = {};
uint8_t slot_ = 0;
bool full_ = false;
void cmd(const char* fmt, ...); void cmd(const char* fmt, ...);
void pushState(const UiView& v, bool full); void put(const char* fmt, ...); // like cmd(), but only if it changed
void pushLink(const UiView& v); void setPage(uint8_t page);
void renderTopBar(const UiView& v);
void renderDrive(const UiView& v);
void renderStatus(const UiView& v);
void renderServos(const UiView& v);
void renderCal(const UiView& v);
void renderSetup(const UiView& v);
bool decodeCustom(UiEvent& out); bool decodeCustom(UiEvent& out);
bool decodeNative(UiEvent& out); bool decodeNative(UiEvent& out);
}; };
+3
View File
@@ -14,6 +14,9 @@ CmdPacket PacketBuilder::build(const StickFrame& s, const RemoteIMU& imu, const
p.seq = seq_++; p.seq = seq_++;
p.speed_scale = st.speedCurrent(); p.speed_scale = st.speedCurrent();
p.body_height = st.height(); // a setting, not motion: sent even while disarmed p.body_height = st.height(); // a setting, not motion: sent even while disarmed
p.cal_cmd = st.servoCalCmd(now_ms); // CAL_NONE unless the CAL page is calibrating (only while disarmed)
p.cal_servo = st.servoSel();
p.cal_value = st.trimTarget();
uint8_t f = 0; uint8_t f = 0;
if (st.armed()) f |= FLAG_ARMED; if (st.armed()) f |= FLAG_ARMED;
+82 -37
View File
@@ -4,44 +4,46 @@ Handheld transmitter for the hexapod. It reads two 3-axis twist-grip
joysticks and an MPU6050, takes operator commands from a Nextion joysticks and an MPU6050, takes operator commands from a Nextion
touchscreen, and sends a `CmdPacket` (defined in touchscreen, and sends a `CmdPacket` (defined in
`../shared/HexapodProtocol/HexapodProtocol.h`) to the robot over nRF24L01 `../shared/HexapodProtocol/HexapodProtocol.h`) to the robot over nRF24L01
at 100 Hz. at 100 Hz. The robot's `Telemetry` comes back in the radio's ack payloads.
Without the robot, the Unity simulation can answer instead, through the
USB nRF24 dongle (`../sim/README.md`).
## Planned ## Planned
- **Battery level** (not built yet): read the 18650's voltage through a - **Battery level** (divider not built yet): read the 18650's voltage through a
~100k/100k divider from the cell's + (not the boost board's 5 V output) ~100k/100k divider from the cell's + (not the boost board's 5 V output)
into A6 (pin 20, free), with 100 nF to GND, and show the charge on the into A6 (pin 20, free), with 100 nF to GND. Details in
Nextion with a low-battery warning. Details in `../hardware/openscad/PLANNING.md` (notes for future designs). The
`../hardware/openscad/PLANNING.md` (notes for future designs). firmware side is done (`Battery`, shown on the STATUS page): set
`BATTERY_SENSE_PIN = A6` in `Config.h` once it's wired. A low-battery
- **IMU on the normal pin headers** (suggestion, not done): with the GY-521 on warning is still to do.
the main board, wire it to Wire (SDA 18 / SCL 19) instead of Wire2 (the
24/25 pads under the Teensy 4.0). 18/19 are A4/A5, used by two stick axes
now, so move those two axes to A7 (pin 21) and A8 (pin 22): all on the
edge headers. A6 (pin 20) stays free for the battery divider, A9 (23) is
spare. Firmware: in `Config.h` `STICK_PINS = { A0, A1, A2, A3, A7, A8 }`
and `#define IMU_WIRE Wire`; `Sticks.cpp` reads through `STICK_PINS`, so
nothing else changes. Redo the stick axis check (`p` dump) and calibration
afterwards. (Wire1 is no way out: its 16/17 are stick pins A2/A3 too.)
## Building ## Building
From the `2026-current` folder: `pio run -e remote`, flash with From the `2026-current` folder: `pio run -e remote`, flash with
`pio run -e remote -t upload`, monitor with `pio device monitor -e remote`. `pio run -e remote -t upload`, monitor with `pio device monitor -e remote`.
The upload opens Teensy Loader; if the Teensy doesn't reboot into it by
itself, press its program button. If flashing works but the USB serial port
then won't open or goes quiet, try another USB port or cable before
suspecting the firmware (a bare Teensy 4.0 showed exactly that on one port).
## Wiring (from the old remote sketch in `../../2019-teensy-nrf24/remote/`; edit `Config.h` if yours differs) ## Wiring (edge headers only; edit `Config.h` if yours differs)
| Part | Signal | Teensy 4.0 pin | | Part | Signal | Teensy 4.0 pin |
|------|--------|----------------| |------|--------|----------------|
| nRF24L01 | MOSI / MISO / SCK | 11 / 12 / 13 (SPI0) | | nRF24L01 | MOSI / MISO / SCK | 11 / 12 / 13 (SPI0) |
| nRF24L01 | CE / CSN | 9 / 10 | | nRF24L01 | CE / CSN | 9 / 10 |
| nRF24L01 | VCC | 3.3 V, with a 10–100 µF cap right at the module | | nRF24L01 | VCC | 3.3 V, with a 10–100 µF cap right at the module |
| MPU6050 | SDA / SCL | **25 / 24 (Wire2)**, solder pads on the underside of the 4.0: not 18/19, those are stick pins A4/A5 | | MPU6050 | SDA / SCL | **18 / 19 (Wire)** |
| Nextion | TX → RX1, RX ← TX1 | 0 / 1 (Serial1), 5 V supply | | MPU6050 | VCC | 3.3 V (a GY-521 runs fine on it). Check the polarity: one supply reversal killed the first board's regulator |
| Sticks | 6 axes | A0–A5. Which axis is on which pin isn't known yet: reorder `STICK_PINS` until the `p` dump reads right | | Nextion | TX → RX2, RX ← TX2 | 7 / 8 (Serial2), 5 V supply (found on the real remote) |
| Sticks | 6 axes | left stick X / Y / twist on **A3 / A7 / A8** (17 / 21 / 22), right stick on **A0 / A1 / A2** (14 / 15 / 16). A7/A8 hold the two wires that were on A4/A5 (18/19). All but the right twist read inverted (`STICK_INVERT`). Checked on the real remote |
| Battery (planned) | divider | A6 (20) |
**MPU6050 rewiring:** the old remote had its MPU code switched off, probably **Rewiring from the old remote:** move the two stick wires from 18/19 to
because A4/A5 double as Wire's pins. Move the MPU's SDA/SCL to pins 25/24 (the pads under the board). 21/22, then put the MPU on 18/19 (Wire). The old remote had its MPU code
switched off, probably because A4/A5 double as Wire's pins. Redo the stick
axis check (`p` dump) and the sweep calibration afterwards.
Stick pots are wired 3.3 V – wiper – GND. **Never feed 5 V into a Teensy Stick pots are wired 3.3 V – wiper – GND. **Never feed 5 V into a Teensy
4.x analog pin.** 4.x analog pin.**
@@ -64,14 +66,44 @@ steers: forward+left or back+left walk while turning left, and left alone
turns on the spot for as long as you hold it. Let go and the robot holds turns on the spot for as long as you hold it. Let go and the robot holds
its heading. its heading.
Touchscreen: ARM / DISARM, SIT/STAND, TRIPOD/WAVE, DIRECT/HEADING, Touchscreen (`NEXTION.md` has the details), with tabs along the bottom and
R: ROTATE/MOVE, REMOTE GYRO, ROBOT GYRO, speed slider, LEVEL (re-zero the a red DISARM on every page:
handset tilt), CAL / CANCEL CAL. `NEXTION.md` has the HMI build guide.
- **DRIVE:** ARM / DISARM, SIT/STAND, TRIPOD/WAVE, DIRECT/HEADING,
R: ROTATE/MOVE, REMOTE GYRO, ROBOT GYRO, speed and height sliders.
- **STATUS:** handset and robot IMU roll/pitch, the six stick axes, both
batteries, radio quality and the robot's received packet rate.
- **SERVOS:** all 18 joint angles the robot is commanding, as a top view.
- **CAL:** servo centre calibration (see below).
- **SETUP:** stick calibration (CAL STICKS / CANCEL), LEVEL REMOTE (re-zero
the handset tilt), UPDATE DISPLAY, backlight.
Everything about the robot comes from its **telemetry**, which rides back on
the radio's ack payloads (`Telemetry` in `HexapodProtocol.h`): `RadioLink`
reads it after every send, and it counts as stale after
`TELEMETRY_STALE_MS`.
## Servo centre calibration (CAL page)
1. Put the robot on a stand, legs free, and disarm.
2. Tap **START**. The robot drives every servo to its centre pose: coxa 0,
femur 0, tibia −90 (legs straight out, shins straight down).
3. Pick a leg (FR MR RR RL ML FL) and a joint. The remote first reads that
servo's trim back from the robot (the trim box shows `...` until then).
4. Step the trim with −10 / −1 / +1 / +10 µs (or ZERO) until the horn is
exactly square. SAVE TO ROBOT turns orange while there are unsaved
trims.
5. **SAVE TO ROBOT** stores all 18 trims in the robot's EEPROM. **REVERT**
drops unsaved changes. **STOP**, leaving the page, or a link loss relaxes
the servos. Arming is refused while calibrating.
### Safety interlocks (in `RemoteState`) ### Safety interlocks (in `RemoteState`)
- **Arming** is refused unless every stick axis is centered, and never - **Arming** is refused unless every stick axis is centered, and never
allowed during calibration. allowed during stick or servo calibration. Servo calibration only starts
while disarmed, and stops when you leave the CAL page or the link drops.
- **UPDATE DISPLAY** needs a second tap within 3 s and is refused while
armed.
- **Disarming** always clears the stand request. The robot arms into SIT, - **Disarming** always clears the stand request. The robot arms into SIT,
so re-arming never stands it up by itself. so re-arming never stands it up by itself.
- **Link loss:** if no ack arrives for `LINK_LOST_MS` (300 ms, matching the - **Link loss:** if no ack arrives for `LINK_LOST_MS` (300 ms, matching the
@@ -97,12 +129,13 @@ handset tilt), CAL / CANCEL CAL. `NEXTION.md` has the HMI build guide.
1. Power on with both sticks released and the remote held still. Each 1. Power on with both sticks released and the remote held still. Each
axis's resting center is captured automatically. axis's resting center is captured automatically.
2. For full calibration, disarm, then tap **CAL** (or press `c` on the 2. For full calibration, disarm, then tap **CAL STICKS** on the SETUP page
serial console). Move every axis of both sticks to both limits, release (or press `c` on the serial console). Move every axis of both sticks to
them, and tap **SAVE CAL** (`c`). The result is saved to EEPROM. both limits, release them, and tap **SAVE CAL** (`c`). The result is
saved to EEPROM, so it survives power cycles and reflashing.
3. If any axis moved less than `CAL_MIN_HALF_SPAN` either side of center, 3. If any axis moved less than `CAL_MIN_HALF_SPAN` either side of center,
the save is refused and you stay in calibration mode. **CANCEL CAL** the save is refused and you stay in calibration mode. **CANCEL** (`x`)
(`x`) aborts. aborts.
4. `p` prints the calibration in a form you can paste into `Config.h` 4. `p` prints the calibration in a form you can paste into `Config.h`
defaults. `R` wipes EEPROM back to the `Config.h` defaults. defaults. `R` wipes EEPROM back to the `Config.h` defaults.
@@ -122,19 +155,31 @@ display attached.
| `c` | start / save calibration | `x` | cancel calibration | | `c` | start / save calibration | `x` | cancel calibration |
| `p` | print status (raw + mapped sticks, IMU, link, state, cal) | `d` | toggle 10 Hz packet dump | | `p` | print status (raw + mapped sticks, IMU, link, state, cal) | `d` | toggle 10 Hz packet dump |
| `R` | reset stick cal to Config defaults | `U` | Nextion upload mode (USB ↔ display; power-cycle to leave) | | `R` | reset stick cal to Config defaults | `U` | Nextion upload mode (USB ↔ display; power-cycle to leave) |
| `o` | servo calibration start/stop | `n` | next servo (leg × 3 + joint) |
| `,` / `.` | trim −1 / +1 µs | `<` / `>` | trim −10 / +10 µs |
| `0` | trim to zero | `w` / `e` | save trims on the robot / revert |
`p` also prints the robot's telemetry (state, IMU, battery, joint angles)
and the servo-calibration state.
## Bench-check checklist ## Bench-check checklist
1. **Stick directions:** with `p`, confirm each logical axis reads 1. **Stick directions:** with `p`, confirm each logical axis reads
positive for right / forward / counterclockwise twist. Flip it in positive for right / forward / counterclockwise twist. Flip it in
`STICK_INVERT[]` if not. `STICK_INVERT[]` if not. Done on the real remote (2026-11-17), then
the sweep calibration.
2. **IMU mounting:** with `p`, dip the right edge down to get +roll, and 2. **IMU mounting:** with `p`, dip the right edge down to get +roll, and
tip the far edge down to get +pitch. If not, fix `IMU_AXIS_FROM_CHIP` / tip the far edge down to get +pitch. If not, fix `IMU_AXIS_FROM_CHIP` /
`IMU_AXIS_SIGN`. `IMU_AXIS_SIGN`. Done (defaults are right). The first GY-521 got its
3. **Nextion baud:** `bauds=115200` must be in Program.s, or the display supply reversed once and its regulator now runs hot: redo this check
shows nothing useful. on the replacement, and see whether it still needs the reset in
4. **Radio:** with the robot powered, `tLink` / `p` should show ~100%. If `RemoteIMU::begin()`.
it reads NO LINK, check that both boards were built from the same 3. **Nextion:** the generated HMI sets `bauds=115200` in Program.s and is
`HexapodProtocol.h`. The static payload size is part of the handshake. on the display (upload through SETUP › UPDATE DISPLAY or serial `U`).
4. **Radio:** with the robot (or the Unity sim behind the USB dongle)
running, `tLink` / `p` should show ~100%, and `p` should print robot
telemetry. If it reads NO LINK, check that both ends were built from
the same `HexapodProtocol.h`: each end drops packets of the wrong size.
Done against the Unity sim through the dongle; not yet with the robot.
5. **End to end with the robot on a stand:** use `d` to dump packets and 5. **End to end with the robot on a stand:** use `d` to dump packets and
confirm each field changes the way the table above says. confirm each field changes the way the table above says.
+16 -1
View File
@@ -11,7 +11,10 @@ static RF24 radio(RADIO_CE_PIN, RADIO_CSN_PIN);
bool RadioLink::begin() { bool RadioLink::begin() {
present_ = radio.begin(); present_ = radio.begin();
if (present_) { if (present_) {
radio.setPayloadSize(HXP_RADIO_PAYLOAD); // must match the robot exactly (static payloads) // The robot answers with Telemetry in its ack payloads, which needs
// dynamic payload lengths on both radios. Each end checks the length of
// what it receives against its own struct instead (see HexapodProtocol.h).
radio.enableAckPayload();
radio.setPALevel((rf24_pa_dbm_e)HXP_RADIO_PA_LEVEL); radio.setPALevel((rf24_pa_dbm_e)HXP_RADIO_PA_LEVEL);
radio.setDataRate((rf24_datarate_e)HXP_RADIO_DATA_RATE); radio.setDataRate((rf24_datarate_e)HXP_RADIO_DATA_RATE);
radio.setChannel(HXP_RADIO_CHANNEL); radio.setChannel(HXP_RADIO_CHANNEL);
@@ -30,6 +33,18 @@ bool RadioLink::send(const CmdPacket& p) {
last_ack_ms_ = millis(); last_ack_ms_ = millis();
ever_acked_ = true; ever_acked_ = true;
} }
// An ack payload lands in the RX FIFO. Drain it every time, so it can't fill up.
while (radio.available()) {
uint8_t len = radio.getDynamicPayloadSize();
if (len == sizeof(Telemetry)) {
radio.read(&telemetry_, sizeof(telemetry_));
has_telemetry_ = true;
telemetry_ms_ = millis();
} else if (len > 0) { // 0 = corrupt length; RF24 has flushed the FIFO already
uint8_t junk[32]; // another protocol version: ignore it
radio.read(junk, len <= sizeof(junk) ? len : sizeof(junk));
}
}
return acked; return acked;
} }
+11
View File
@@ -1,8 +1,10 @@
#pragma once #pragma once
#include <HexapodProtocol.h> #include <HexapodProtocol.h>
#include "Config.h"
// nRF24L01 transmitter. Uses hardware auto-ack to measure the link: the // nRF24L01 transmitter. Uses hardware auto-ack to measure the link: the
// robot's radio acks every packet it receives, so an ack = the robot heard us. // robot's radio acks every packet it receives, so an ack = the robot heard us.
// The robot's Telemetry comes back as the ack's payload.
class RadioLink { class RadioLink {
public: public:
bool begin(); // false if the radio chip didn't respond bool begin(); // false if the radio chip didn't respond
@@ -13,10 +15,19 @@ public:
bool linkOk() const { return link_ok_; } bool linkOk() const { return link_ok_; }
uint8_t qualityPct() const; // acked share of the last 32 packets uint8_t qualityPct() const; // acked share of the last 32 packets
// Latest telemetry from the robot, and whether it's recent enough to show.
const Telemetry& telemetry() const { return telemetry_; }
bool telemetryFresh(uint32_t now_ms) const {
return has_telemetry_ && (now_ms - telemetry_ms_) < TELEMETRY_STALE_MS;
}
private: private:
bool present_ = false; bool present_ = false;
bool link_ok_ = false; bool link_ok_ = false;
uint32_t last_ack_ms_ = 0; uint32_t last_ack_ms_ = 0;
bool ever_acked_ = false; bool ever_acked_ = false;
uint32_t history_ = 0; // 1 bit per packet, newest in bit 0 uint32_t history_ = 0; // 1 bit per packet, newest in bit 0
Telemetry telemetry_;
bool has_telemetry_ = false;
uint32_t telemetry_ms_ = 0;
}; };
+8 -1
View File
@@ -18,8 +18,15 @@ static bool writeReg(uint8_t reg, uint8_t val) {
bool RemoteIMU::begin() { bool RemoteIMU::begin() {
IMU_WIRE.begin(); IMU_WIRE.begin();
IMU_WIRE.setClock(400000); IMU_WIRE.setClock(400000);
ok_ = writeReg(REG_PWR_MGMT_1, 0x00); // wake out of sleep // Full device reset first: the remote's MPU6050 (likely a clone) answers
// and wakes without it, but every data register reads 0 until it has been
// reset (found on the real remote, 2026-11-17).
ok_ = writeReg(REG_PWR_MGMT_1, 0x80);
if (!ok_) return false; if (!ok_) return false;
delay(100);
ok_ = writeReg(REG_PWR_MGMT_1, 0x01); // wake, clocked from the X gyro PLL
if (!ok_) return false;
delay(50);
writeReg(REG_CONFIG, 0x03); // 44 Hz DLPF: a handheld remote doesn't need more bandwidth writeReg(REG_CONFIG, 0x03); // 44 Hz DLPF: a handheld remote doesn't need more bandwidth
delay(50); delay(50);
+111 -6
View File
@@ -17,6 +17,26 @@ void RemoteState::disarm() {
stand_ = false; stand_ = false;
} }
void RemoteState::stopServoCal() {
servo_cal_ = false;
trim_synced_ = false;
cal_op_ = CAL_NONE;
}
// A new selection is only trimmed once the robot has reported that servo's
// current trim (CAL_HOLD until then), so a stale value is never sent.
void RemoteState::selectServo(uint8_t servo) {
if (servo == servo_sel_) return;
servo_sel_ = servo;
trim_synced_ = false;
}
uint8_t RemoteState::servoCalCmd(uint32_t now_ms) const {
if (!servo_cal_ || armed_) return CAL_NONE;
if (cal_op_ != CAL_NONE && now_ms < cal_op_until_ms_) return cal_op_;
return trim_synced_ ? CAL_SET : CAL_HOLD;
}
bool RemoteState::handle(const UiEvent& e, Sticks& stick_hw, RemoteIMU& imu, uint32_t now) { bool RemoteState::handle(const UiEvent& e, Sticks& stick_hw, RemoteIMU& imu, uint32_t now) {
const StickFrame& sticks = stick_hw.frame(); const StickFrame& sticks = stick_hw.frame();
switch (e.cmd) { switch (e.cmd) {
@@ -30,6 +50,7 @@ bool RemoteState::handle(const UiEvent& e, Sticks& stick_hw, RemoteIMU& imu, uin
case UiCmd::ToggleArm: case UiCmd::ToggleArm:
if (armed_) { disarm(); return true; } if (armed_) { disarm(); return true; }
if (calibrating_) { setMessage("Finish calibration first", now); return false; } if (calibrating_) { setMessage("Finish calibration first", now); return false; }
if (servo_cal_) { setMessage("Stop servo calibration first", now); return false; }
if (!sticks.allCentered(ARM_CENTER_TOLERANCE)) { setMessage("Center both sticks to arm", now); return false; } if (!sticks.allCentered(ARM_CENTER_TOLERANCE)) { setMessage("Center both sticks to arm", now); return false; }
armed_ = true; armed_ = true;
return true; return true;
@@ -81,6 +102,66 @@ bool RemoteState::handle(const UiEvent& e, Sticks& stick_hw, RemoteIMU& imu, uin
case UiCmd::NextionUpload: case UiCmd::NextionUpload:
return false; // not operator state - remote.ino handles it return false; // not operator state - remote.ino handles it
case UiCmd::UploadRequest:
if (armed_) { setMessage("Disarm first", now); return false; }
if (now < upload_confirm_until_ms_) { upload_go_ = true; return true; }
upload_confirm_until_ms_ = now + UPLOAD_CONFIRM_MS;
setMessage("Tap again to enter display update mode", now);
return true;
case UiCmd::PageShown:
page_ = e.value;
// Servo calibration only runs while its page is showing.
if (servo_cal_ && page_ != PAGE_CAL) stopServoCal();
upload_confirm_until_ms_ = 0;
return true;
case UiCmd::ServoCalToggle:
if (servo_cal_) { stopServoCal(); setMessage("Servos relaxed", now); return true; }
if (armed_) { setMessage("Disarm to calibrate servos", now); return false; }
servo_cal_ = true;
trim_synced_ = false;
setMessage("Robot holds every servo at centre", now);
return true;
case UiCmd::ServoCalLeg:
if (e.value >= 6) return false;
selectServo(e.value * 3 + servo_sel_ % 3);
return true;
case UiCmd::ServoCalJoint:
if (e.value >= 3) return false;
selectServo(servo_sel_ / 3 * 3 + e.value);
return true;
case UiCmd::ServoCalNext:
selectServo((servo_sel_ + 1) % 18);
return true;
case UiCmd::ServoCalTrim: {
if (!servo_cal_) { setMessage("Tap START first", now); return false; }
if (!trim_synced_) { setMessage("Waiting for the robot", now); return false; }
int t = trim_target_;
switch (e.value) {
case SERVO_TRIM_MINUS_BIG: t -= SERVO_TRIM_STEP_BIG_US; break;
case SERVO_TRIM_MINUS_SMALL: t -= SERVO_TRIM_STEP_SMALL_US; break;
case SERVO_TRIM_PLUS_SMALL: t += SERVO_TRIM_STEP_SMALL_US; break;
case SERVO_TRIM_PLUS_BIG: t += SERVO_TRIM_STEP_BIG_US; break;
case SERVO_TRIM_ZERO: t = 0; break;
default: return false;
}
trim_target_ = (int16_t)constrain(t, -CAL_TRIM_LIMIT_US, CAL_TRIM_LIMIT_US);
return true;
}
case UiCmd::ServoCalSave:
case UiCmd::ServoCalRevert:
if (!servo_cal_) { setMessage("Tap START first", now); return false; }
cal_op_ = e.cmd == UiCmd::ServoCalSave ? CAL_SAVE : CAL_REVERT;
cal_op_until_ms_ = now + SERVO_CAL_OP_MS;
setMessage(e.cmd == UiCmd::ServoCalSave ? "Trims saved on the robot" : "Unsaved trims dropped", now);
return true;
case UiCmd::CalCancel: case UiCmd::CalCancel:
if (!calibrating_) return false; if (!calibrating_) return false;
stick_hw.cancelCalibration(); stick_hw.cancelCalibration();
@@ -91,16 +172,35 @@ bool RemoteState::handle(const UiEvent& e, Sticks& stick_hw, RemoteIMU& imu, uin
return false; return false;
} }
void RemoteState::update(float dt, bool link_ok, uint32_t now_ms) { void RemoteState::update(float dt, bool link_ok, bool tele_fresh, const Telemetry& tele, uint32_t now_ms) {
// Mirror the robot's link failsafe: it disarms (servos relax) when packets // Mirror the robot's link failsafe: it disarms (servos relax) when packets
// stop, so the remote disarms too and the operator must re-arm on purpose // stop, so the remote disarms too and the operator must re-arm on purpose
// once the link is back. // once the link is back. Servo calibration stops the same way, so the
if (!link_ok && link_was_ok_ && armed_) { // servos don't spring back to centre on their own when the link returns.
disarm(); if (!link_ok && link_was_ok_) {
setMessage("Link lost - disarmed", now_ms); if (armed_) {
disarm();
setMessage("Link lost - disarmed", now_ms);
}
if (servo_cal_) {
stopServoCal();
setMessage("Link lost - servo cal stopped", now_ms);
}
} }
link_was_ok_ = link_ok; link_was_ok_ = link_ok;
// SAVE / REVERT done: after a revert the robot's trims changed under us, so
// read the selected one back again.
if (cal_op_ != CAL_NONE && now_ms >= cal_op_until_ms_) {
if (cal_op_ == CAL_REVERT) trim_synced_ = false;
cal_op_ = CAL_NONE;
}
if (servo_cal_ && !trim_synced_ && cal_op_ == CAL_NONE && tele_fresh &&
tele.state == TSTATE_SERVO_CAL && tele.cal_servo == servo_sel_) {
trim_target_ = tele.cal_trim_us;
trim_synced_ = true;
}
speed_.setTarget(speed_target_); speed_.setTarget(speed_target_);
speed_.update(dt); speed_.update(dt);
tilt_blend_.setTarget(remote_gyro_ ? 1.0f : 0.0f); tilt_blend_.setTarget(remote_gyro_ ? 1.0f : 0.0f);
@@ -115,7 +215,12 @@ void RemoteState::fillView(UiView& v, uint32_t now_ms) const {
v.rstick_xlate = rstick_xlate_; v.rstick_xlate = rstick_xlate_;
v.remote_gyro = remote_gyro_; v.remote_gyro = remote_gyro_;
v.robot_gyro = robot_gyro_; v.robot_gyro = robot_gyro_;
v.calibrating = calibrating_; v.stick_calibrating = calibrating_;
v.servo_cal = servo_cal_;
v.servo_sel = servo_sel_;
v.trim_synced = trim_synced_;
v.trim_us = trim_target_;
v.upload_confirm = now_ms < upload_confirm_until_ms_;
v.speed_target = speed_target_; v.speed_target = speed_target_;
v.height = height_; v.height = height_;
v.message = message(now_ms); v.message = message(now_ms);
+28 -2
View File
@@ -17,8 +17,9 @@ public:
// rejections leave an explanation in message(). // rejections leave an explanation in message().
bool handle(const UiEvent& e, Sticks& sticks, RemoteIMU& imu, uint32_t now_ms); bool handle(const UiEvent& e, Sticks& sticks, RemoteIMU& imu, uint32_t now_ms);
// Advances smoothers and link-loss handling. Call once per TX tick. // Advances smoothers and link-loss handling, and reads the servo trim back
void update(float dt, bool link_ok, uint32_t now_ms); // from the robot's telemetry. Call once per TX tick.
void update(float dt, bool link_ok, bool tele_fresh, const Telemetry& tele, uint32_t now_ms);
bool armed() const { return armed_; } bool armed() const { return armed_; }
bool standRequested() const { return stand_; } bool standRequested() const { return stand_; }
@@ -33,6 +34,17 @@ public:
uint8_t speedCurrent() const { return (uint8_t)lroundf(speed_.current); } uint8_t speedCurrent() const { return (uint8_t)lroundf(speed_.current); }
float remoteTiltBlend() const { return tilt_blend_.current; } // 0..1, fades on the gyro toggle float remoteTiltBlend() const { return tilt_blend_.current; } // 0..1, fades on the gyro toggle
// Servo centre calibration (CAL page) -> CmdPacket.cal_*
uint8_t servoCalCmd(uint32_t now_ms) const;
uint8_t servoSel() const { return servo_sel_; } // leg * 3 + joint
int16_t trimTarget() const { return trim_target_; }
bool servoCal() const { return servo_cal_; }
bool trimSynced() const { return trim_synced_; }
uint8_t page() const { return page_; }
// UPDATE DISPLAY was confirmed: remote.ino enters the upload passthrough.
bool takeUploadRequest() { bool r = upload_go_; upload_go_ = false; return r; }
const char* message(uint32_t now_ms) const { return now_ms < message_until_ms_ ? message_ : ""; } const char* message(uint32_t now_ms) const { return now_ms < message_until_ms_ ? message_ : ""; }
void setMessage(const char* msg, uint32_t now_ms); void setMessage(const char* msg, uint32_t now_ms);
@@ -53,9 +65,23 @@ private:
SmoothedValue speed_{SPEED_SCALE_RATE_PER_SEC}; SmoothedValue speed_{SPEED_SCALE_RATE_PER_SEC};
SmoothedValue tilt_blend_{REMOTE_TILT_FADE_PER_SEC}; SmoothedValue tilt_blend_{REMOTE_TILT_FADE_PER_SEC};
uint8_t page_ = PAGE_UNKNOWN;
bool servo_cal_ = false;
uint8_t servo_sel_ = 0;
int16_t trim_target_ = 0;
bool trim_synced_ = false; // trim_target_ was read back from the robot for servo_sel_
uint8_t cal_op_ = CAL_NONE; // CAL_SAVE / CAL_REVERT while it's being sent
uint32_t cal_op_until_ms_ = 0;
uint32_t upload_confirm_until_ms_ = 0;
bool upload_go_ = false;
bool link_was_ok_ = false; bool link_was_ok_ = false;
const char* message_ = ""; const char* message_ = "";
uint32_t message_until_ms_ = 0; uint32_t message_until_ms_ = 0;
void disarm(); void disarm();
void stopServoCal();
void selectServo(uint8_t servo);
}; };
+9
View File
@@ -23,6 +23,15 @@ bool SerialConsole::poll(UiEvent& ui, Local& local) {
case 'c': ui.cmd = UiCmd::CalStartSave; return true; case 'c': ui.cmd = UiCmd::CalStartSave; return true;
case 'x': ui.cmd = UiCmd::CalCancel; return true; case 'x': ui.cmd = UiCmd::CalCancel; return true;
case 'U': ui.cmd = UiCmd::NextionUpload; return true; case 'U': ui.cmd = UiCmd::NextionUpload; return true;
case 'o': ui.cmd = UiCmd::ServoCalToggle; return true;
case 'n': ui.cmd = UiCmd::ServoCalNext; return true;
case ',': ui = UiEvent{ UiCmd::ServoCalTrim, SERVO_TRIM_MINUS_SMALL }; return true;
case '.': ui = UiEvent{ UiCmd::ServoCalTrim, SERVO_TRIM_PLUS_SMALL }; return true;
case '<': ui = UiEvent{ UiCmd::ServoCalTrim, SERVO_TRIM_MINUS_BIG }; return true;
case '>': ui = UiEvent{ UiCmd::ServoCalTrim, SERVO_TRIM_PLUS_BIG }; return true;
case '0': ui = UiEvent{ UiCmd::ServoCalTrim, SERVO_TRIM_ZERO }; return true;
case 'w': ui.cmd = UiCmd::ServoCalSave; return true;
case 'e': ui.cmd = UiCmd::ServoCalRevert; return true;
case 'p': local = Local::PrintStatus; return true; case 'p': local = Local::PrintStatus; return true;
case 'd': local = Local::ToggleDump; return true; case 'd': local = Local::ToggleDump; return true;
case 'R': local = Local::ResetCal; return true; case 'R': local = Local::ResetCal; return true;
+50 -4
View File
@@ -1,5 +1,7 @@
#pragma once #pragma once
#include <Arduino.h> #include <Arduino.h>
#include <HexapodProtocol.h>
#include "Config.h"
// Operator commands. Produced by the Nextion touchscreen (NextionUI) and by // Operator commands. Produced by the Nextion touchscreen (NextionUI) and by
// the USB serial console (SerialConsole) through the same path, so the // the USB serial console (SerialConsole) through the same path, so the
@@ -21,19 +23,43 @@ enum class UiCmd : uint8_t {
HeightUp, // serial console only HeightUp, // serial console only
HeightDown, // serial console only HeightDown, // serial console only
ZeroGyro, // capture the handset's current attitude as "level" ZeroGyro, // capture the handset's current attitude as "level"
CalStartSave, // start sweep calibration, or save it if running CalStartSave, // stick sweep calibration: start, or save it if running
CalCancel, CalCancel,
NextionUpload, // USB <-> display passthrough for Nextion Editor (handled in remote.ino) PageShown, // value = Nextion page id (UiPage); the display just showed it
ServoCalToggle, // servo centre calibration on/off (robot holds the centre pose)
ServoCalLeg, // value = leg 0..5
ServoCalJoint, // value = joint 0..2 (coxa, femur, tibia)
ServoCalNext, // serial console only: next servo
ServoCalTrim, // value = SERVO_TRIM_* step code
ServoCalSave, // store the trims in the robot's EEPROM
ServoCalRevert, // reload the trims from the robot's EEPROM
UploadRequest, // display update mode from the touchscreen: needs a second tap
NextionUpload, // display update mode right away (serial console 'U')
}; };
// ServoCalTrim values.
constexpr uint8_t SERVO_TRIM_MINUS_BIG = 0;
constexpr uint8_t SERVO_TRIM_MINUS_SMALL = 1;
constexpr uint8_t SERVO_TRIM_PLUS_SMALL = 2;
constexpr uint8_t SERVO_TRIM_PLUS_BIG = 3;
constexpr uint8_t SERVO_TRIM_ZERO = 4;
struct UiEvent { struct UiEvent {
UiCmd cmd = UiCmd::None; UiCmd cmd = UiCmd::None;
uint8_t value = 0; uint8_t value = 0;
}; };
// The HMI's pages (remote/remote.HMI, page id = position in the Editor's
// page list). Each page reports itself with a 'P' frame when it opens.
enum UiPage : uint8_t {
PAGE_SPLASH = 0, PAGE_DRIVE, PAGE_STATUS, PAGE_SERVOS, PAGE_CAL, PAGE_SETUP, PAGE_UPLOAD,
PAGE_UNKNOWN = 0xFF,
};
// Everything the display shows. The remote is authoritative: the Nextion // Everything the display shows. The remote is authoritative: the Nextion
// only sends requests, and always renders what's in here. // only sends requests, and always renders what's in here.
struct UiView { struct UiView {
// Operator state (DRIVE page)
bool armed = false; bool armed = false;
bool stand = false; bool stand = false;
bool gait_wave = false; bool gait_wave = false;
@@ -41,10 +67,30 @@ struct UiView {
bool rstick_xlate = false; bool rstick_xlate = false;
bool remote_gyro = false; bool remote_gyro = false;
bool robot_gyro = false; bool robot_gyro = false;
bool calibrating = false;
uint8_t speed_target = 0; uint8_t speed_target = 0;
int16_t height = 0; // -1000..1000, 0 = default int16_t height = 0; // -1000..1000, 0 = default
// Radio + robot telemetry
bool link_ok = false; bool link_ok = false;
uint8_t link_pct = 0; uint8_t link_pct = 0;
const char* message = ""; // always a string literal - NextionUI diffs it by pointer bool tele_ok = false; // fresh telemetry from the robot
Telemetry tele;
// Handset (STATUS page)
bool imu_ok = false;
float imu_roll = 0, imu_pitch = 0; // degrees, vs the zeroed level
int16_t sticks[NUM_AXES] = {};
uint16_t battery_mv = 0; // 0 = not measured
// SETUP page
bool stick_calibrating = false;
bool upload_confirm = false; // UPDATE DISPLAY tapped once, waiting for the second tap
// CAL page (servo centre calibration)
bool servo_cal = false;
uint8_t servo_sel = 0; // leg * 3 + joint
bool trim_synced = false; // trim below is known (read back from the robot)
int16_t trim_us = 0;
const char* message = "";
}; };
Binary file not shown.
+30 -3
View File
@@ -6,6 +6,7 @@
#include "RadioLink.h" #include "RadioLink.h"
#include "NextionUI.h" #include "NextionUI.h"
#include "SerialConsole.h" #include "SerialConsole.h"
#include "Battery.h"
// Hexapod remote (Teensy 4.0): reads two 3-axis sticks and the handset // Hexapod remote (Teensy 4.0): reads two 3-axis sticks and the handset
// MPU6050, takes operator commands from the Nextion touchscreen (and the USB // MPU6050, takes operator commands from the Nextion touchscreen (and the USB
@@ -19,6 +20,7 @@ PacketBuilder builder;
RadioLink radio_link; RadioLink radio_link;
NextionUI nextion; NextionUI nextion;
SerialConsole console; SerialConsole console;
Battery battery;
uint32_t last_tx_us = 0; uint32_t last_tx_us = 0;
bool dump_packets = false; bool dump_packets = false;
@@ -39,6 +41,22 @@ static void printStatus() {
state.modeB() ? "B" : "A", state.rstickXlate() ? "xlate" : "rot", state.modeB() ? "B" : "A", state.rstickXlate() ? "xlate" : "rot",
state.remoteGyro(), state.robotGyro(), state.speedTarget(), state.speedCurrent(), state.height()); state.remoteGyro(), state.robotGyro(), state.speedTarget(), state.speedCurrent(), state.height());
sticks.printCalibration(Serial); sticks.printCalibration(Serial);
if (BATTERY_SENSE_PIN != 255) Serial.printf("battery %u mV\n", battery.millivolts());
const Telemetry& t = radio_link.telemetry();
if (radio_link.telemetryFresh(millis())) {
Serial.printf("robot: state %u status %02X roll %.1f pitch %.1f battery %u mV, hears %u/s\n",
t.state, t.status, t.roll_ddeg / 10.0f, t.pitch_ddeg / 10.0f, t.battery_mv, t.rx_per_sec);
Serial.print("robot joints (deg):");
for (int i = 0; i < 18; i++)
Serial.printf(" %d", t.joint_deg[i] - (i % 3 == 2 ? TELEMETRY_TIBIA_OFFSET_DEG : 0));
Serial.println();
} else {
Serial.println("robot: no telemetry");
}
Serial.printf("servo cal %s, servo %u (leg %u joint %u) trim %d us%s, robot reports servo %u trim %d\n",
state.servoCal() ? "ON" : "off", state.servoSel(), state.servoSel() / 3, state.servoSel() % 3,
state.trimTarget(), state.trimSynced() ? "" : " (not read back yet)", t.cal_servo, t.cal_trim_us);
} }
static void dumpPacket(const CmdPacket& p) { static void dumpPacket(const CmdPacket& p) {
@@ -47,7 +65,7 @@ static void dumpPacket(const CmdPacket& p) {
p.remote_roll, p.remote_pitch, p.body_height, p.speed_scale, p.flags); p.remote_roll, p.remote_pitch, p.body_height, p.speed_scale, p.flags);
} }
// Nextion Editor upload through this USB port (the old remote's b2 button). // Nextion Editor upload through this USB port (SETUP > UPDATE DISPLAY, or 'U').
// Never returns: the TX loop stops, so the robot loses the link and // Never returns: the TX loop stops, so the robot loses the link and
// disarms itself after LINK_TIMEOUT_SEC. Power-cycle the remote to leave. // disarms itself after LINK_TIMEOUT_SEC. Power-cycle the remote to leave.
static void enterNextionUpload() { static void enterNextionUpload() {
@@ -61,8 +79,8 @@ static void enterNextionUpload() {
static void pollInputs(uint32_t now_ms) { static void pollInputs(uint32_t now_ms) {
UiEvent ev; UiEvent ev;
while (nextion.poll(ev)) { while (nextion.poll(ev)) {
if (ev.cmd == UiCmd::NextionUpload) enterNextionUpload();
state.handle(ev, sticks, imu, now_ms); state.handle(ev, sticks, imu, now_ms);
if (state.takeUploadRequest()) enterNextionUpload(); // UPDATE DISPLAY, tapped twice
} }
SerialConsole::Local local; SerialConsole::Local local;
@@ -114,7 +132,9 @@ void loop() {
sticks.update(); sticks.update();
imu.update(dt); imu.update(dt);
radio_link.update(now_ms); radio_link.update(now_ms);
state.update(dt, radio_link.linkOk(), now_ms); battery.update(dt);
bool tele_fresh = radio_link.telemetryFresh(now_ms);
state.update(dt, radio_link.linkOk(), tele_fresh, radio_link.telemetry(), now_ms);
last_packet = builder.build(sticks.frame(), imu, state, now_ms); last_packet = builder.build(sticks.frame(), imu, state, now_ms);
radio_link.send(last_packet); radio_link.send(last_packet);
@@ -123,6 +143,13 @@ void loop() {
state.fillView(view, now_ms); state.fillView(view, now_ms);
view.link_ok = radio_link.linkOk(); view.link_ok = radio_link.linkOk();
view.link_pct = radio_link.qualityPct(); view.link_pct = radio_link.qualityPct();
view.tele_ok = tele_fresh;
view.tele = radio_link.telemetry();
view.imu_ok = imu.ok();
view.imu_roll = imu.rollDeg();
view.imu_pitch = imu.pitchDeg();
for (int i = 0; i < NUM_AXES; i++) view.sticks[i] = sticks.frame().v[i];
view.battery_mv = battery.millivolts();
nextion.render(view, now_ms); nextion.render(view, now_ms);
if (dump_packets && now_ms - last_dump_ms >= 100) { if (dump_packets && now_ms - last_dump_ms >= 100) {
+10
View File
@@ -0,0 +1,10 @@
#include "Battery.h"
#include "Config.h"
void Battery::update(float dt) {
if (BATTERY_SENSE_PIN == 255) return; // not fitted: stays 0
float v = analogRead(BATTERY_SENSE_PIN) * (BATTERY_ADC_REF_V / BATTERY_ADC_MAX) * BATTERY_DIVIDER;
if (!primed_) { volts_ = v; primed_ = true; return; }
float a = constrain(dt / 2.0f, 0.0f, 1.0f); // ~2 s time constant: servo load makes it sag and bounce
volts_ += (v - volts_) * a;
}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <Arduino.h>
// Battery voltage through a resistor divider (Config.h BATTERY_*), smoothed.
class Battery {
public:
void update(float dt);
uint16_t millivolts() const { return (uint16_t)(volts_ * 1000.0f + 0.5f); } // 0 = not fitted
private:
float volts_ = 0;
bool primed_ = false;
};
+29 -3
View File
@@ -12,22 +12,48 @@ bool Comms::begin() {
SPI.setSCK(RADIO_SCK_PIN); // alternate SCK pin (see Config.h); before RF24 starts SPI SPI.setSCK(RADIO_SCK_PIN); // alternate SCK pin (see Config.h); before RF24 starts SPI
radio_present_ = radio.begin(); radio_present_ = radio.begin();
if (radio_present_) { if (radio_present_) {
radio.setPayloadSize(HXP_RADIO_PAYLOAD); // mismatched protocol versions won't be received at all // Telemetry rides back on the auto-ack (ack payloads), which needs dynamic
// payload lengths - update() drops any packet that isn't a CmdPacket.
radio.enableAckPayload();
radio.openReadingPipe(1, HXP_RADIO_ADDRESS); radio.openReadingPipe(1, HXP_RADIO_ADDRESS);
radio.setPALevel((rf24_pa_dbm_e)HXP_RADIO_PA_LEVEL); radio.setPALevel((rf24_pa_dbm_e)HXP_RADIO_PA_LEVEL);
radio.setDataRate((rf24_datarate_e)HXP_RADIO_DATA_RATE); radio.setDataRate((rf24_datarate_e)HXP_RADIO_DATA_RATE);
radio.setChannel(HXP_RADIO_CHANNEL); radio.setChannel(HXP_RADIO_CHANNEL);
radio.startListening(); radio.startListening();
loadAckPayload();
} }
return radio_present_; return radio_present_;
} }
// Replaces whatever ack payload is still queued with the latest telemetry, so
// the remote never gets stale data.
void Comms::loadAckPayload() {
radio.flush_tx();
radio.writeAckPayload(1, &telemetry_, sizeof(telemetry_));
}
void Comms::update() { void Comms::update() {
if (radio_present_) { if (radio_present_) {
bool got = false;
while (radio.available()) { while (radio.available()) {
radio.read(&packet_, sizeof(packet_)); uint8_t len = radio.getDynamicPayloadSize();
last_rx_ms_ = millis(); if (len == sizeof(CmdPacket)) {
radio.read(&packet_, sizeof(packet_));
last_rx_ms_ = millis();
rx_count_++;
got = true;
} else if (len > 0) { // 0 = corrupt length; RF24 has flushed the FIFO already
uint8_t junk[32]; // another protocol version: never act on it
radio.read(junk, len <= sizeof(junk) ? len : sizeof(junk));
}
} }
if (got) loadAckPayload();
}
uint32_t now = millis();
if (now - rate_window_ms_ >= 1000) {
rx_per_sec_ = (uint8_t)min(rx_count_, (uint16_t)255);
rx_count_ = 0;
rate_window_ms_ = now;
} }
link_ok_ = (millis() - last_rx_ms_) < (uint32_t)(LINK_TIMEOUT_SEC * 1000); link_ok_ = (millis() - last_rx_ms_) < (uint32_t)(LINK_TIMEOUT_SEC * 1000);
} }
+11
View File
@@ -12,9 +12,20 @@ public:
// Lets the serial test harness (or, later, real radio) inject a packet directly. // Lets the serial test harness (or, later, real radio) inject a packet directly.
void injectPacket(const CmdPacket& p) { packet_ = p; last_rx_ms_ = millis(); } void injectPacket(const CmdPacket& p) { packet_ = p; last_rx_ms_ = millis(); }
// Telemetry for the remote. Goes out as the ack payload of the next packet
// received, so set it every loop.
void setTelemetry(const Telemetry& t) { telemetry_ = t; }
uint8_t packetsPerSec() const { return rx_per_sec_; }
private: private:
CmdPacket packet_; CmdPacket packet_;
uint32_t last_rx_ms_ = 0; uint32_t last_rx_ms_ = 0;
bool link_ok_ = false; bool link_ok_ = false;
bool radio_present_ = false; bool radio_present_ = false;
Telemetry telemetry_;
uint16_t rx_count_ = 0;
uint8_t rx_per_sec_ = 0;
uint32_t rate_window_ms_ = 0;
void loadAckPayload();
}; };
+9
View File
@@ -140,6 +140,15 @@ constexpr uint8_t RADIO_CSN_PIN = 15;
constexpr uint8_t RADIO_SCK_PIN = 14; constexpr uint8_t RADIO_SCK_PIN = 14;
constexpr float LINK_TIMEOUT_SEC = 0.3f; constexpr float LINK_TIMEOUT_SEC = 0.3f;
// ---- Battery voltage (shown on the remote's STATUS page) ----
// Battery + through a resistor divider into an analog pin. BENCH: no divider
// is wired yet - set the pin and the divider ratio (battery V / pin V) once
// it is. 255 = not fitted: the remote then shows "--".
constexpr uint8_t BATTERY_SENSE_PIN = 255;
constexpr float BATTERY_DIVIDER = 3.0f; // e.g. 20k over 10k
constexpr float BATTERY_ADC_REF_V = 3.3f; // Teensy 3.6 analog reference
constexpr int BATTERY_ADC_MAX = 1023; // default 10-bit analogRead()
// ---- Robot-gyro self-leveling ---- // ---- Robot-gyro self-leveling ----
// Integral gain (1/s): a leftover tilt of 1 deg changes the correction by // Integral gain (1/s): a leftover tilt of 1 deg changes the correction by
// this many deg/s. Higher levels faster but can wobble. BENCH: tune on the robot. // this many deg/s. Higher levels faster but can wobble. BENCH: tune on the robot.
+32 -7
View File
@@ -41,8 +41,9 @@ still a placeholder. Check all of it against the real robot:
needed ±90° offsets there, which left the servos at the end of their needed ±90° offsets there, which left the servos at the end of their
travel. travel.
- `RADIO_CE_PIN` / `RADIO_CSN_PIN` / `RADIO_SCK_PIN`: 39 / 15 / 14, as in - `RADIO_CE_PIN` / `RADIO_CSN_PIN` / `RADIO_SCK_PIN`: 39 / 15 / 14, as in
the old sketch. Address, channel, data rate, PA level and payload size the old sketch. Address, channel, data rate, PA level and the packet
are in `shared/HexapodProtocol` so they can't drift from the remote. structs are in `shared/HexapodProtocol` so they can't drift from the
remote.
## Bench-check checklist (do this before the first stand-up) ## Bench-check checklist (do this before the first stand-up)
@@ -62,7 +63,11 @@ for your build:
down). down).
3. **RobotIMU register map** (`RobotIMU.cpp`) — written for an MPU6050-style 3. **RobotIMU register map** (`RobotIMU.cpp`) — written for an MPU6050-style
chip (I2C addr `0x68`). If your gyro is a different part, its register chip (I2C addr `0x68`). If your gyro is a different part, its register
addresses and scale factors will differ; swap them in. addresses and scale factors will differ; swap them in. Also check that
it gives live readings at all (the robot's roll/pitch on the remote's
STATUS page): the remote's MPU6050 answered and woke up but read all
zeros until it got a full device reset (`PWR_MGMT_1 = 0x80`), which
`RobotIMU::begin()` doesn't do.
4. **Sit-pose assumption** — the built-in sit pose in `robot.ino` assumes all 4. **Sit-pose assumption** — the built-in sit pose in `robot.ino` assumes all
six feet stay grounded and simply lowers the body (a 0.4x height blend). six feet stay grounded and simply lowers the body (a 0.4x height blend).
If your chassis is meant to rest its belly on the ground instead, this If your chassis is meant to rest its belly on the ground instead, this
@@ -83,7 +88,8 @@ for your build:
This exact code also compiles for the PC and runs in the Unity model. See This exact code also compiles for the PC and runs in the Unity model. See
`../sim/README.md`. `sim/build/sim_smoke.exe` is a quick headless check `../sim/README.md`. `sim/build/sim_smoke.exe` is a quick headless check
after every change. after every change. In Unity the simulated robot can also be driven by the
real remote over the radio, through the USB nRF24 dongle.
## Testing without a remote yet ## Testing without a remote yet
@@ -116,9 +122,27 @@ ignore walk commands.
## Link with the remote ## Link with the remote
- `CmdPacket` and the `FLAG_*` bits in `shared/HexapodProtocol` are the - `CmdPacket` and the `FLAG_*` bits in `shared/HexapodProtocol` are the
exact wire format. Both radios set a static payload size of exact wire format. `Comms` drops any packet whose length isn't
`sizeof(CmdPacket)`, so a robot and remote built from different protocol `sizeof(CmdPacket)`, so a robot and remote built from different protocol
versions won't receive each other at all (and the robot fails safe). versions won't receive each other at all (and the robot fails safe).
- **Telemetry back to the remote:** after every packet received, `Comms`
loads a fresh `Telemetry` (robot state, IMU roll/pitch, battery, the 18
commanded joint angles, packets per second, servo-cal echo) as the radio's
ack payload. It goes back on the auto-ack of the remote's next packet:
no extra transmissions. `sendTelemetry()` in `robot.ino` fills it every
loop. The IMU attitude is now estimated whether or not robot gyro is on
(the remote shows it); only the leveling is gated by `FLAG_ROBOT_GYRO`.
- **Servo centre calibration** (remote's CAL page): while disarmed, a
`cal_cmd` other than `CAL_NONE` puts the robot in SERVO_CAL. Every servo
is driven to the centre pose (coxa 0, femur 0, tibia −90: legs straight
out, shins straight down) and `CAL_SET` adjusts one servo's centre trim
(µs, ±200, on top of `Config.h` `SERVOS`; it shifts the whole pulse range
like the old `servoCallibration[]`). `CAL_SAVE` stores the 18 trims in
EEPROM (`ServoDriver`, address 0, loaded at power-on), `CAL_REVERT`
reloads them. `CAL_NONE`, arming or link loss relaxes the servos again.
Put the robot on a stand first.
- **Battery:** `Battery` reads `BATTERY_SENSE_PIN` through a divider
(`Config.h`). Not wired yet (pin 255): the remote shows "--".
- Failsafe: if no packet arrives for `LINK_TIMEOUT_SEC`, `Comms::linkOk()` - Failsafe: if no packet arrives for `LINK_TIMEOUT_SEC`, `Comms::linkOk()`
goes false and the main loop falls back to a zeroed `CmdPacket`, which goes false and the main loop falls back to a zeroed `CmdPacket`, which
disarms the robot. disarms the robot.
@@ -145,6 +169,7 @@ robot/
├── StateMachine.h/.cpp - DISARMED/SIT/STAND/WALKING with smoothed sit-stand blend ├── StateMachine.h/.cpp - DISARMED/SIT/STAND/WALKING with smoothed sit-stand blend
├── InputMapper.h/.cpp - CmdPacket -> twist/pose/mode decoding ├── InputMapper.h/.cpp - CmdPacket -> twist/pose/mode decoding
├── Limits.h/.cpp - workspace clamp, joint rate limit, stance polygon check ├── Limits.h/.cpp - workspace clamp, joint rate limit, stance polygon check
├── Comms.h/.cpp - nRF24L01 receive (packet definition is in shared/HexapodProtocol) ├── Comms.h/.cpp - nRF24L01 receive + telemetry as ack payload (packets in shared/HexapodProtocol)
└── ServoDriver.h/.cpp - servo attach/relax/write ├── ServoDriver.h/.cpp - servo PWM write/relax, per-servo centre trims (EEPROM), SERVO_CAL
└── Battery.h/.cpp - battery voltage through a divider (not wired yet)
``` ```
+1 -1
View File
@@ -38,7 +38,7 @@ bool RobotIMU::readRaw(float& ax, float& ay, float& az, float& gx, float& gy, fl
} }
void RobotIMU::update(float dt) { void RobotIMU::update(float dt) {
if (!ok_ || !enabled) return; if (!ok_) return;
float ax, ay, az, gx, gy, gz; float ax, ay, az, gx, gy, gz;
if (!readRaw(ax, ay, az, gx, gy, gz)) return; if (!readRaw(ax, ay, az, gx, gy, gz)) return;
+5 -2
View File
@@ -4,11 +4,14 @@
class RobotIMU { class RobotIMU {
public: public:
bool begin(); // returns false if the IMU didn't respond bool begin(); // returns false if the IMU didn't respond
void update(float dt); // no-op if disabled or the IMU never came up void update(float dt); // no-op if the IMU never came up
float rollDeg() const { return roll_deg_; } float rollDeg() const { return roll_deg_; }
float pitchDeg() const { return pitch_deg_; } float pitchDeg() const { return pitch_deg_; }
bool ok() const { return ok_; }
bool enabled = true; // robot-gyro toggle from CmdPacket sets this // Robot-gyro toggle from CmdPacket. The attitude is estimated either way
// (the remote shows it); robot.ino only levels the body while it's set.
bool enabled = true;
private: private:
float roll_deg_ = 0, pitch_deg_ = 0; float roll_deg_ = 0, pitch_deg_ = 0;
+71 -2
View File
@@ -1,5 +1,7 @@
#include "ServoDriver.h" #include "ServoDriver.h"
#include "Config.h" #include "Config.h"
#include <HexapodProtocol.h>
#include <EEPROM.h>
// 18 servos on hardware PWM, the way the old robot sketch drove them (the // 18 servos on hardware PWM, the way the old robot sketch drove them (the
// Teensy 3.6 Servo library stops at 12). 16-bit duty at 50 Hz is ~0.3 us per // Teensy 3.6 Servo library stops at 12). 16-bit duty at 50 Hz is ~0.3 us per
@@ -28,10 +30,77 @@ void ServoDriver::relaxAll() {
analogWrite(SERVOS[i][j].pin, 0); // no pulses: the servos go limp analogWrite(SERVOS[i][j].pin, 0); // no pulses: the servos go limp
} }
// ---- Centre trims ----
// EEPROM record at address 0 (nothing else on the robot uses EEPROM). Bump
// TRIM_VERSION if the layout changes - an old record is then ignored.
static constexpr int TRIM_EEPROM_ADDR = 0;
static constexpr uint32_t TRIM_MAGIC = 0x52545848; // "HXTR"
static constexpr uint8_t TRIM_VERSION = 1;
struct TrimRecord {
uint32_t magic;
uint8_t version;
uint8_t checksum; // sum of the trim bytes
int16_t trim_us[NUM_LEGS * 3];
};
static int16_t g_trim[NUM_LEGS * 3] = {};
static bool g_dirty = false;
static bool g_stored = false;
static uint8_t trimChecksum(const int16_t* t) {
uint8_t sum = 0;
const uint8_t* b = reinterpret_cast<const uint8_t*>(t);
for (size_t i = 0; i < sizeof(int16_t) * NUM_LEGS * 3; i++) sum += b[i];
return sum;
}
void ServoDriver::loadTrims() {
TrimRecord r;
EEPROM.get(TRIM_EEPROM_ADDR, r);
g_stored = r.magic == TRIM_MAGIC && r.version == TRIM_VERSION && r.checksum == trimChecksum(r.trim_us);
for (int i = 0; i < NUM_LEGS * 3; i++)
g_trim[i] = g_stored ? constrain(r.trim_us[i], -CAL_TRIM_LIMIT_US, CAL_TRIM_LIMIT_US) : 0;
g_dirty = false;
}
static void saveTrims() {
TrimRecord r;
r.magic = TRIM_MAGIC;
r.version = TRIM_VERSION;
memcpy(r.trim_us, g_trim, sizeof(g_trim));
r.checksum = trimChecksum(r.trim_us);
EEPROM.put(TRIM_EEPROM_ADDR, r);
g_dirty = false;
g_stored = true;
}
int16_t ServoDriver::trim(int servo) { return (servo >= 0 && servo < NUM_LEGS * 3) ? g_trim[servo] : 0; }
bool ServoDriver::trimsDirty() { return g_dirty; }
bool ServoDriver::trimsStored() { return g_stored; }
const JointAngles ServoDriver::CAL_POSE = { 0.0f, 0.0f, -90.0f, true };
void ServoDriver::calibrate(uint8_t cal_cmd, uint8_t servo, int16_t value_us) {
bool valid_servo = servo < NUM_LEGS * 3;
switch (cal_cmd) {
case CAL_SET:
if (valid_servo) {
int16_t v = constrain(value_us, -CAL_TRIM_LIMIT_US, CAL_TRIM_LIMIT_US);
if (v != g_trim[servo]) { g_trim[servo] = v; g_dirty = true; }
}
break;
case CAL_SAVE: if (g_dirty) saveTrims(); break; // the remote repeats it: only write once
case CAL_REVERT: if (g_dirty) loadTrims(); break;
default: break; // CAL_HOLD
}
for (int i = 0; i < NUM_LEGS; i++) writeLeg(i, CAL_POSE);
}
int ServoDriver::degToMicros(int leg, int joint, float deg) { int ServoDriver::degToMicros(int leg, int joint, float deg) {
const ServoCal& c = SERVOS[leg][joint]; const ServoCal& c = SERVOS[leg][joint];
float us = c.us_at_0deg + c.us_per_deg * deg; int16_t t = g_trim[leg * 3 + joint];
return (int)constrain(us, (float)c.us_min, (float)c.us_max); float us = c.us_at_0deg + t + c.us_per_deg * deg;
return (int)constrain(us, (float)(c.us_min + t), (float)(c.us_max + t));
} }
void ServoDriver::writeLeg(int i, const JointAngles& a) { void ServoDriver::writeLeg(int i, const JointAngles& a) {
+15 -1
View File
@@ -7,6 +7,20 @@ public:
void relaxAll(); // stop all pulses - call when disarming void relaxAll(); // stop all pulses - call when disarming
void writeLeg(int leg_index, const JointAngles& angles); void writeLeg(int leg_index, const JointAngles& angles);
// Joint angle -> pulse through that servo's calibration (Config.h SERVOS). // Joint angle -> pulse through that servo's calibration (Config.h SERVOS)
// plus its centre trim.
static int degToMicros(int leg, int joint, float deg); static int degToMicros(int leg, int joint, float deg);
// ---- Servo centre calibration (remote's CAL page, CmdPacket.cal_*) ----
// Each servo has a centre trim in us on top of Config.h SERVOS, kept in
// EEPROM. Trims shift the whole pulse range, like the old sketch's
// servoCallibration[].
static void loadTrims(); // from EEPROM; all 0 if none stored. Call in setup()
static int16_t trim(int servo); // servo = leg * 3 + joint
static bool trimsDirty(); // changed since the last load/save
static bool trimsStored(); // the EEPROM holds a trim record
// Applies one calibration command (CAL_* in HexapodProtocol.h) and holds
// every servo at the centre pose. Call every loop while in SERVO_CAL.
void calibrate(uint8_t cal_cmd, uint8_t servo, int16_t value_us);
static const JointAngles CAL_POSE; // coxa 0, femur 0, tibia -90
}; };
+46
View File
@@ -9,6 +9,7 @@
#include "Comms.h" #include "Comms.h"
#include "ServoDriver.h" #include "ServoDriver.h"
#include "SmoothedValue.h" #include "SmoothedValue.h"
#include "Battery.h"
// Uncomment to drive the robot from the Serial Monitor before a remote exists. // Uncomment to drive the robot from the Serial Monitor before a remote exists.
// See README.md for the key map. // See README.md for the key map.
@@ -21,6 +22,7 @@ StateMachine state_machine;
InputMapper mapper; InputMapper mapper;
Comms comms; Comms comms;
ServoDriver servo_driver; ServoDriver servo_driver;
Battery battery;
float current_heading_deg = 0; // open-loop: accumulates commanded omega. See note in loop(). float current_heading_deg = 0; // open-loop: accumulates commanded omega. See note in loop().
SmoothedValue stance_height(STANCE_HEIGHT_RATE_MM_S); // remote height slider, rate-limited SmoothedValue stance_height(STANCE_HEIGHT_RATE_MM_S); // remote height slider, rate-limited
@@ -28,6 +30,7 @@ float gyro_corr_roll_deg = 0, gyro_corr_pitch_deg = 0; // robot-gyro self-level
float last_joint_deg[NUM_LEGS][3] = {}; // for per-joint rate limiting float last_joint_deg[NUM_LEGS][3] = {}; // for per-joint rate limiting
uint32_t last_loop_us = 0; uint32_t last_loop_us = 0;
RobotState last_state = RobotState::DISARMED; RobotState last_state = RobotState::DISARMED;
bool servo_cal_active = false; // SERVO_CAL: servos held at the centre pose for trimming
#ifdef TEST_SERIAL_INPUT #ifdef TEST_SERIAL_INPUT
CmdPacket test_packet; CmdPacket test_packet;
@@ -63,6 +66,33 @@ void pollSerialTestInput() {
} }
#endif #endif
// Robot state for the remote's display, sent back in the radio's ack payload.
void sendTelemetry(const CmdPacket& cmd, const MapperOutput& mapped, RobotState state) {
Telemetry t;
t.roll_ddeg = (int16_t)lroundf(constrain(imu.rollDeg(), -3000.0f, 3000.0f) * 10);
t.pitch_ddeg = (int16_t)lroundf(constrain(imu.pitchDeg(), -3000.0f, 3000.0f) * 10);
t.battery_mv = battery.millivolts();
t.state = servo_cal_active ? TSTATE_SERVO_CAL : (uint8_t)state;
t.status = (imu.ok() ? TSTAT_IMU_OK : 0) |
(mapped.robot_gyro_enabled ? TSTAT_GYRO_ON : 0) |
(state != RobotState::DISARMED || servo_cal_active ? TSTAT_SERVOS_ON : 0) |
(ServoDriver::trimsDirty() ? TSTAT_CAL_DIRTY : 0) |
(ServoDriver::trimsStored() ? TSTAT_TRIMS_STORED : 0);
t.cal_servo = cmd.cal_servo;
t.cal_trim_us = ServoDriver::trim(cmd.cal_servo);
t.rx_per_sec = comms.packetsPerSec();
for (int i = 0; i < NUM_LEGS; i++) {
const float* j = last_joint_deg[i];
float c = servo_cal_active ? ServoDriver::CAL_POSE.coxa_deg : j[0];
float f = servo_cal_active ? ServoDriver::CAL_POSE.femur_deg : j[1];
float b = servo_cal_active ? ServoDriver::CAL_POSE.tibia_deg : j[2];
t.joint_deg[i * 3] = (int8_t)constrain(lroundf(c), -127L, 127L);
t.joint_deg[i * 3 + 1] = (int8_t)constrain(lroundf(f), -127L, 127L);
t.joint_deg[i * 3 + 2] = (int8_t)constrain(lroundf(b) + TELEMETRY_TIBIA_OFFSET_DEG, -127L, 127L);
}
comms.setTelemetry(t);
}
void setup() { void setup() {
Serial.begin(115200); Serial.begin(115200);
gait.begin(); gait.begin();
@@ -73,6 +103,7 @@ void setup() {
if (!imu.begin()) Serial.println("robot IMU not responding - stabilization disabled"); if (!imu.begin()) Serial.println("robot IMU not responding - stabilization disabled");
if (!comms.begin()) Serial.println("radio not responding - waiting for injected/test commands only"); if (!comms.begin()) Serial.println("radio not responding - waiting for injected/test commands only");
ServoDriver::loadTrims();
servo_driver.begin(); servo_driver.begin();
last_loop_us = micros(); last_loop_us = micros();
} }
@@ -115,6 +146,18 @@ void loop() {
} else if (state != RobotState::DISARMED && last_state == RobotState::DISARMED) { } else if (state != RobotState::DISARMED && last_state == RobotState::DISARMED) {
servo_driver.begin(); servo_driver.begin();
} }
// Servo centre calibration (remote CAL page): only while disarmed. The
// servos hold the centre pose through their trims; leaving it - CAL_NONE,
// arming or link loss (cmd is then a default packet) - relaxes them again.
bool servo_cal = !mapped.armed && cmd.cal_cmd != CAL_NONE;
if (servo_cal) {
if (!servo_cal_active) servo_driver.begin();
servo_driver.calibrate(cmd.cal_cmd, cmd.cal_servo, cmd.cal_value);
} else if (servo_cal_active && state == RobotState::DISARMED) {
servo_driver.relaxAll();
}
servo_cal_active = servo_cal;
// The stand pose holds every foot at neutral, so walking starts from there. // The stand pose holds every foot at neutral, so walking starts from there.
if (state == RobotState::WALKING && last_state != RobotState::WALKING) gait.resetFeet(); if (state == RobotState::WALKING && last_state != RobotState::WALKING) gait.resetFeet();
last_state = state; last_state = state;
@@ -203,4 +246,7 @@ void loop() {
servo_driver.writeLeg(i, angles); servo_driver.writeLeg(i, angles);
} }
} }
battery.update(dt);
sendTelemetry(cmd, mapped, state);
} }
+283
View File
@@ -0,0 +1,283 @@
"""Builds remote/remote.HMI, the remote's Nextion touchscreen project, from code.
The layout below is the single source of truth for the HMI: change it here and
re-run, rather than editing remote.HMI in Nextion Editor (an Editor edit is
lost on the next run). Component names and event code must match the
firmware - remote/NextionUI.cpp and remote/NEXTION.md.
python scripts\\make_remote_hmi.py (from 2026-current, PowerShell 5.1 fine)
Needs:
- the nxhmi package: the tools/nextion-hmi-tools submodule (git submodule update --init)
- Pillow, and the DejaVu Sans Mono fonts (free licence). They ship with
matplotlib; or pass --font-dir with DejaVuSansMono.ttf + DejaVuSansMono-Bold.ttf.
- the old remote HMI (../2019-teensy-nrf24/remote-nextion/remote.HMI), read
only: its splash picture is reused.
Then open remote.HMI in Nextion Editor, compile and upload (SETUP > UPDATE
DISPLAY puts the remote in USB passthrough for that).
"""
import argparse
import os
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE) # 2026-current
sys.path.insert(0, os.path.join(ROOT, "tools", "nextion-hmi-tools", "src"))
from nxhmi import mcp_server as nx # noqa: E402 (the same functions the nxhmi MCP server exposes)
OUT = os.path.join(ROOT, "remote", "remote.HMI")
OLD_HMI = os.path.join(ROOT, "..", "2019-teensy-nrf24", "remote-nextion", "remote.HMI")
W, H = 480, 320
BAR_H = 32 # top bar
TAB_Y, TAB_H = 272, 48
BIG, SMALL = 0, 1 # font ids: 24 px bold, 16 px
# Colours. The firmware repaints the stateful ones (remote/NextionUI.cpp):
# gray #c6c3c6 = off, green #00fc00 = on, red #f80000, orange #f88000.
PAGE_BG = "#182030"
BAR_BG = "#000000"
TEXT = "#ffffff"
LABEL = "#a0b0c8"
BTN = "#c6c3c6"
RED = "#f80000"
TRACK = "#404850"
TAB_ON = "#3060c0"
# Page order = page id; must match UiPage in remote/UiTypes.h.
PAGES = ["splash", "drive", "status", "servos", "cal", "setup", "upload"]
TABS = [("drive", "DRIVE"), ("status", "STATUS"), ("servos", "SERVOS"), ("cal", "CAL"), ("setup", "SETUP")]
LEG_NAMES = ["FR", "MR", "RR", "RL", "ML", "FL"] # robot leg order (robot/Config.h)
LEG_TITLES = ["FRONT RIGHT", "MID RIGHT", "REAR RIGHT", "REAR LEFT", "MID LEFT", "FRONT LEFT"]
def frame(cmd, value=None):
"""printh line for a custom '#' frame (remote/NextionUI.h)."""
body = [ord(cmd)] + ([value] if value is not None else [])
return "printh 23 %02X %s" % (len(body), " ".join("%02X" % b for b in body))
class Builder:
def __init__(self, path):
self.path = path
def add(self, page, kind, name, events=None, **att):
nx.t_add_component(self.path, page, kind, name, att, events or {})
def text(self, page, name, x, y, w, h, txt, font=SMALL, pco=TEXT, bco=PAGE_BG, xcen="left", ycen="center",
maxl=None, **kw):
self.add(page, "text", name, x=x, y=y, w=w, h=h, txt=txt, font=font, pco=pco, bco=bco,
xcen=xcen, ycen=ycen, txt_maxl=maxl or max(len(txt), 10), **kw)
def button(self, page, name, x, y, w, h, txt, up=None, font=BIG, bco=BTN, pco="#000000", maxl=None, **kw):
events = {"codesup": up} if up else {}
self.add(page, "button", name, events, x=x, y=y, w=w, h=h, txt=txt, font=font, bco=bco, bco2=bco,
pco=pco, pco2=pco, txt_maxl=maxl or max(len(txt), 10), **kw)
def slider(self, page, name, x, y, w, h, maxval, val, events=None, cursor=None):
self.add(page, "slider", name, events, x=x, y=y, w=w, h=h, bco=TRACK, bco1=TRACK, pco=TEXT,
wid=cursor or h, hig=h, maxval=maxval, minval=0, val=val)
def bar(self, page, name, x, y, w, h, val=0):
self.add(page, "progress_bar", name, x=x, y=y, w=w, h=h, bco=TRACK, pco="#00c000", val=val)
# ---- shared frame: top bar + tabs on every working page ----
def chrome(self, page):
self.text(page, "tLink", 0, 0, 112, BAR_H, "NO LINK", font=SMALL, pco=RED, bco=BAR_BG, xcen="center", maxl=12)
self.text(page, "tState", 112, 0, 256, BAR_H, "ROBOT: NO DATA", font=SMALL, pco=TEXT, bco=BAR_BG, maxl=30)
self.button(page, "bKill", 368, 0, 112, BAR_H, "DISARM", [frame("K")], font=BIG, bco=RED, pco=TEXT)
tw = W // len(TABS)
for i, (target, label) in enumerate(TABS):
on = target == page
self.button(page, "bTab%d" % i, i * tw, TAB_Y, tw, TAB_H, label, ["page %s" % target], font=SMALL,
bco=TAB_ON if on else "#283040", pco=TEXT, borderw=1)
def page(self, name, preinit=()):
"""Every page reports itself to the remote when it opens ('P' + page id)."""
if name != PAGES[0]:
nx.t_add_page(self.path, name, {"bco": PAGE_BG, "sta": "solid color"})
else:
nx.t_set_attributes(self.path, name, name, {"bco": PAGE_BG})
nx.t_set_event(self.path, name, name, "codesload", [frame("P", PAGES.index(name))] + list(preinit))
def splash_png(tmp):
"""The old remote's splash picture (a jumping spider), rendered from the old HMI."""
from nxhmi.render import Renderer
from nxhmi.container import HMIFile
img = Renderer(HMIFile.load(OLD_HMI)).render("splashsceen")
path = os.path.join(tmp, "splash.png")
img.save(path)
return path
def font_dir(arg):
if arg:
return arg
import matplotlib
return os.path.join(os.path.dirname(matplotlib.__file__), "mpl-data", "fonts", "ttf")
MODEL = "NX4832T035_011"
def new_project_flipped(path, program):
"""Like nxhmi's project.new_project, but landscape turned 180 degrees (Editor: Setting >
Display direction 270): the display sits upside down in the remote (owner, 2026-11-17).
Must come first: pictures and fonts added afterwards are stored for this direction."""
from nxhmi import models, project
from nxhmi.components import new_page
direction = models.direction_byte(MODEL, landscape=True, flipped=True)
w, h = models.page_size(MODEL, direction)
items = [("main.HMI", project.make_main(MODEL, [("pa", "0.pa")], "iso-8859-1", direction)),
("Program.s", program.encode("latin-1")),
("0.pa", new_page(PAGES[0], w=w, h=h).pack())]
project.build(items).save(path)
def build(path, fonts):
b = Builder(path)
program = ("//Runs once at power-on, before the first page.\r\n"
"bauds=115200 //the remote's NEXTION_BAUD; stored in the display\r\n"
"page 0\r\n")
new_project_flipped(path, program)
nx.t_add_font(path, 24, os.path.join(fonts, "DejaVuSansMono-Bold.ttf"), "iso-8859-1") # font 0
nx.t_add_font(path, 16, os.path.join(fonts, "DejaVuSansMono.ttf"), "iso-8859-1") # font 1
with tempfile.TemporaryDirectory() as tmp:
pic = nx.t_add_picture(path, splash_png(tmp))["picture_id"]
# ---------------------------------------------------------------- 0 splash
p = "splash"
b.page(p)
nx.t_set_attributes(path, p, p, {"sta": "image", "pic": pic})
b.text(p, "t0", 0, 0, 480, 40, "HEXAPOD REMOTE", font=BIG, pco=TEXT, bco="#000000", xcen="center", sta="crop image", picc=pic)
b.add(p, "timer", "tm0", {"codestimer": ["page drive"]}, tim=1500, en="enable")
for name in PAGES[1:]:
b.page(name, preinit=PREINIT.get(name, ()))
for name, _ in TABS:
b.chrome(name)
# ---------------------------------------------------------------- 1 drive
p = "drive"
y = 40
for i, (n, t, c) in enumerate([("bArm", "DISARMED", "A"), ("bStand", "SIT", "S"),
("bGait", "TRIPOD", "G"), ("bMode", "DIRECT", "M")]):
b.button(p, n, 4 + i * 119, y, 115, 48, t, [frame(c)], maxl=10)
y = 94
for i, (n, t, c) in enumerate([("bRs", "R: ROTATE", "X"), ("bRGyro", "REMOTE GYRO", "R"), ("bBGyro", "ROBOT GYRO", "B")]):
b.button(p, n, 4 + i * 159, y, 154, 44, t, [frame(c)], font=SMALL, maxl=12)
b.text(p, "tSpL", 4, 146, 80, 36, "SPEED", font=SMALL, pco=LABEL)
send_speed = ["printh 23 02 56", "prints hSpeed.val,1"] # 'V' + value byte
b.slider(p, "hSpeed", 86, 150, 300, 28, 255, 128, {"codesslide": send_speed, "codesup": send_speed}, cursor=20)
b.text(p, "tSpeed", 394, 146, 82, 36, "50%", font=BIG, xcen="right", maxl=6)
b.text(p, "tHtL", 4, 190, 80, 36, "HEIGHT", font=SMALL, pco=LABEL)
send_height = ["printh 23 02 48", "prints hHeight.val,1"] # 'H' + value byte
b.slider(p, "hHeight", 86, 194, 300, 28, 200, 100, {"codesslide": send_height, "codesup": send_height}, cursor=20)
b.text(p, "tHeight", 394, 190, 82, 36, "+0%", font=BIG, xcen="right", maxl=6)
b.text(p, "tMsg", 4, 234, 472, 34, "", font=SMALL, pco="#ffd040", maxl=40)
# ---------------------------------------------------------------- 2 status
p = "status"
for side, x, prefix in (("REMOTE (deg)", 4, "R"), ("ROBOT (deg)", 248, "B")):
b.text(p, "tHdr" + prefix, x, 36, 228, 22, side, font=SMALL, pco=LABEL)
b.text(p, "t%sRoll" % prefix, x, 58, 228, 22, "roll --", maxl=16)
b.slider(p, "h%sRoll" % prefix, x, 80, 228, 16, 90, 45, cursor=10)
b.text(p, "t%sPitch" % prefix, x, 100, 228, 22, "pitch --", maxl=16)
b.slider(p, "h%sPitch" % prefix, x, 122, 228, 16, 90, 45, cursor=10)
b.text(p, "tHdrS", 4, 144, 60, 22, "STICKS", pco=LABEL)
for i, axis in enumerate(("X", "Y", "TWIST")): # centred over the slider columns below
x = 32 + i * 150
if i == 0:
x, w = 67, 70 # same centre (102), clear of "STICKS"
else:
w = 140
b.text(p, "tAx%d" % i, x, 144, w, 22, axis, pco=LABEL, xcen="center")
for row, (label, y) in enumerate((("L", 168), ("R", 192))):
b.text(p, "tSt" + label, 4, y, 24, 20, label, pco=LABEL)
for i, axis in enumerate("XYT"):
b.slider(p, "h%s%s" % (label, axis), 32 + i * 150, y + 2, 140, 16, 200, 100, cursor=10)
b.text(p, "tBatt", 4, 220, 472, 24, "battery remote -- robot --", maxl=40)
b.text(p, "tRadio", 4, 244, 472, 24, "radio no link", maxl=44)
# ---------------------------------------------------------------- 3 servos
p = "servos"
# Top view of the robot, front up: right legs on the right.
slots = {5: (4, 36), 4: (4, 114), 3: (4, 192), 0: (304, 36), 1: (304, 114), 2: (304, 192)}
for leg, (x, y) in slots.items():
b.text(p, "tLeg%d" % leg, x, y, 172, 18, LEG_TITLES[leg], pco=LABEL, maxl=12)
for j in range(3):
i = leg * 3 + j
b.text(p, "tJ%d" % i, x, y + 19 + j * 19, 108, 18, ["coxa", "femur", "tibia"][j] + " --", maxl=12)
b.bar(p, "jJ%d" % i, x + 110, y + 22 + j * 19, 62, 13)
b.text(p, "tBody", 196, 40, 88, 200, "FRONT", font=SMALL, pco=TEXT, bco="#303848", xcen="center",
ycen="up", style="border", borderc="#8090a8", borderw=2)
b.text(p, "tSrv", 196, 246, 88, 22, "NO DATA", font=SMALL, pco="#808080", xcen="center", maxl=10)
# ---------------------------------------------------------------- 4 cal
p = "cal"
b.button(p, "bCalOn", 4, 38, 130, 44, "START", [frame("O")], maxl=6)
b.text(p, "tMsg", 140, 38, 336, 44, "Robot on a stand, disarmed: START", font=SMALL, pco="#ffd040", maxl=40, isbr="true")
for i in range(6):
b.button(p, "bL%d" % i, 4 + i * 79, 88, 75, 40, LEG_NAMES[i], [frame("L", i)], maxl=4)
for j, n in enumerate(["COXA", "FEMUR", "TIBIA"]):
b.button(p, "bJ%d" % j, 4 + j * 158, 134, 154, 40, n, [frame("J", j)], maxl=6)
for n, x, t, code in (("bM10", 4, "-10", 0), ("bM1", 78, "-1", 1), ("bP1", 332, "+1", 2), ("bP10", 406, "+10", 3)):
b.button(p, n, x, 180, 70, 44, t, [frame("T", code)], maxl=4)
b.text(p, "tTrim", 152, 180, 176, 44, "FR coxa", font=SMALL, xcen="center", maxl=20, bco="#303848")
b.button(p, "bZeroT", 4, 228, 110, 40, "ZERO", [frame("T", 4)], font=SMALL, maxl=6)
b.button(p, "bRevert", 118, 228, 140, 40, "REVERT", [frame("E")], font=SMALL, maxl=8)
b.button(p, "bSave", 262, 228, 214, 40, "SAVE TO ROBOT", [frame("W")], font=SMALL, maxl=14)
# ---------------------------------------------------------------- 5 setup
p = "setup"
b.text(p, "tHdr1", 4, 36, 472, 22, "STICKS AND HANDSET", pco=LABEL, maxl=20)
b.button(p, "bCal", 4, 60, 170, 44, "CAL STICKS", [frame("C")], font=SMALL, maxl=12)
b.button(p, "bCalX", 180, 60, 120, 44, "CANCEL", [frame("Q")], font=SMALL, maxl=8)
b.button(p, "bZero", 306, 60, 170, 44, "LEVEL REMOTE", [frame("Z")], font=SMALL, maxl=14)
b.text(p, "tHdr2", 4, 110, 472, 22, "DISPLAY", pco=LABEL, maxl=20)
b.button(p, "bUpd", 4, 134, 230, 44, "UPDATE DISPLAY", [frame("U")], font=SMALL, maxl=16)
b.text(p, "tDim", 244, 134, 70, 44, "LIGHT", pco=LABEL)
b.slider(p, "hDim", 314, 142, 162, 28, 100, 100, {"codesslide": ["dim=hDim.val"], "codesup": ["dims=hDim.val"]},
cursor=20)
b.text(p, "tVer", 4, 186, 472, 22, "remote fw --", pco=LABEL, maxl=50)
b.text(p, "tMsg", 4, 212, 472, 54, "", pco="#ffd040", maxl=40, isbr="true")
# ---------------------------------------------------------------- 6 upload
p = "upload"
b.text(p, "t0", 20, 40, 440, 50, "DISPLAY UPDATE MODE", font=BIG, xcen="center", maxl=20)
for i, line in enumerate(("Upload the .tft from Nextion Editor", "over the remote's USB port.", "",
"Power-cycle the remote when done.")):
b.text(p, "t%d" % (i + 1), 20, 110 + i * 26, 440, 24, line, xcen="center", maxl=40)
return path
# Page pre-initialize code after the 'P' frame.
PREINIT = {
# Indicator sliders: no touch, so a finger can't drag them.
"status": ["tsw hRRoll,0", "tsw hRPitch,0", "tsw hBRoll,0", "tsw hBPitch,0",
"tsw hLX,0", "tsw hLY,0", "tsw hLT,0", "tsw hRX,0", "tsw hRY,0", "tsw hRT,0"],
"setup": ["hDim.val=dim"],
}
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--out", default=OUT)
ap.add_argument("--font-dir", help="folder with DejaVuSansMono.ttf and DejaVuSansMono-Bold.ttf")
a = ap.parse_args()
tmp = a.out + ".new"
if os.path.exists(tmp):
os.remove(tmp)
build(tmp, font_dir(a.font_dir))
problems = nx.t_verify(tmp)
if not problems["ok"]:
sys.exit("verify failed: %s" % problems["problems"])
os.replace(tmp, a.out)
print("wrote", a.out)
if __name__ == "__main__":
main()
@@ -2,14 +2,15 @@
#include <Arduino.h> #include <Arduino.h>
// ===================================================================== // =====================================================================
// Remote -> robot wire protocol. SINGLE SOURCE OF TRUTH. // Remote <-> robot wire protocol. SINGLE SOURCE OF TRUTH.
// //
// Both robot/ and remote/ compile against this exact header (PlatformIO // Both robot/ and remote/ compile against this exact header (PlatformIO
// lib_dir = shared). Any change here changes the over-the-air format: // lib_dir = shared). Any change here changes the over-the-air format:
// rebuild and reflash BOTH boards together. The static payload size is set // rebuild and reflash BOTH boards together. Each end drops any packet whose
// to sizeof(CmdPacket) on both radios, so a remote and robot running // length isn't sizeof() of what it expects, so a remote and robot running
// mismatched versions simply won't hear each other (the robot then fails // mismatched versions simply won't hear each other (the robot then fails
// safe on link timeout) instead of misinterpreting fields. // safe on link timeout) instead of misinterpreting fields.
// Telemetry (below) comes back from the robot in the radio's ack payloads.
// //
// Axis convention (right-handed body frame, viewed from above, like ROS // Axis convention (right-handed body frame, viewed from above, like ROS
// REP-103): +X forward, +Y left, +Z up. Positive rotations follow the // REP-103): +X forward, +Y left, +Z up. Positive rotations follow the
@@ -21,6 +22,10 @@
// remote never needs to know robot geometry. // remote never needs to know robot geometry.
// ===================================================================== // =====================================================================
// Protocol version: bump on any change to CmdPacket, Telemetry or the radio
// settings below (the payload sizes are checked on both ends as well).
constexpr uint8_t HXP_PROTOCOL_VERSION = 4;
struct CmdPacket { struct CmdPacket {
int16_t vx = 0; // left stick: + forward / - backward int16_t vx = 0; // left stick: + forward / - backward
int16_t vy = 0; // left stick: + strafe left / - strafe right int16_t vy = 0; // left stick: + strafe left / - strafe right
@@ -29,15 +34,18 @@ struct CmdPacket {
int16_t remote_roll = 0; // remote handset tilt (feedforward), only honored with FLAG_REMOTE_GYRO int16_t remote_roll = 0; // remote handset tilt (feedforward), only honored with FLAG_REMOTE_GYRO
int16_t remote_pitch = 0; int16_t remote_pitch = 0;
int16_t body_height = 0; // standing height setting: -1000 lowest, 0 = default, +1000 highest int16_t body_height = 0; // standing height setting: -1000 lowest, 0 = default, +1000 highest
int16_t cal_value = 0; // servo calibration: centre trim in us for cal_servo (CAL_SET only)
uint8_t speed_scale = 128; // 0-255, multiplies vx/vy uint8_t speed_scale = 128; // 0-255, multiplies vx/vy
uint8_t flags = 0; // bit-packed, see FLAG_* below uint8_t flags = 0; // bit-packed, see FLAG_* below
uint8_t seq = 0; // increments every transmitted packet uint8_t seq = 0; // increments every transmitted packet
uint8_t cal_cmd = 0; // servo calibration command, CAL_* below. 0 = normal operation
uint8_t cal_servo = 0xFF; // servo calibration: selected servo, leg * 3 + joint (0..17)
}; };
// Both ends are Teensy (Cortex-M7, little-endian, 2-byte int16 alignment): // Both ends are Teensy (Cortex-M, little-endian, 2-byte int16 alignment):
// 9 x int16 + 3 x uint8 = 21 bytes, padded to 22. If a different MCU family // 10 x int16 + 5 x uint8 = 25 bytes, padded to 26. If a different MCU family
// ever joins, pack the struct explicitly rather than trusting this. // ever joins, pack the struct explicitly rather than trusting this.
static_assert(sizeof(CmdPacket) == 22, "CmdPacket layout changed - reflash both boards"); static_assert(sizeof(CmdPacket) == 26, "CmdPacket layout changed - reflash both boards");
static_assert(sizeof(CmdPacket) <= 32, "nRF24L01 payloads are limited to 32 bytes"); static_assert(sizeof(CmdPacket) <= 32, "nRF24L01 payloads are limited to 32 bytes");
constexpr uint8_t FLAG_ARMED = 1 << 0; constexpr uint8_t FLAG_ARMED = 1 << 0;
@@ -53,10 +61,63 @@ constexpr uint8_t FLAG_GAIT_WAVE = 1 << 5; // 0 = tripod requested, 1 = wav
constexpr uint8_t FLAG_REMOTE_GYRO = 1 << 6; // remote tilt feedforward enabled constexpr uint8_t FLAG_REMOTE_GYRO = 1 << 6; // remote tilt feedforward enabled
constexpr uint8_t FLAG_ROBOT_GYRO = 1 << 7; // robot stabilization feedback enabled constexpr uint8_t FLAG_ROBOT_GYRO = 1 << 7; // robot stabilization feedback enabled
// ---- Servo centre calibration (CmdPacket.cal_cmd) ----
// Only honoured while FLAG_ARMED is clear. Any CAL_* other than CAL_NONE puts
// the robot in its SERVO_CAL state: every servo is driven to its centre pose
// (coxa 0, femur 0, tibia -90 = legs straight out, shins straight down) through
// the per-servo trims, so a mis-centred horn shows. Every command is a state,
// not an event, so a repeated or lost packet does no harm. Leaving SERVO_CAL
// (CAL_NONE, arming, or link loss) relaxes the servos again.
constexpr uint8_t CAL_NONE = 0; // normal operation
constexpr uint8_t CAL_HOLD = 1; // hold the centre pose; select cal_servo, report its trim
constexpr uint8_t CAL_SET = 2; // ... and set cal_servo's trim to cal_value (us)
constexpr uint8_t CAL_SAVE = 3; // ... and store all trims in the robot's EEPROM (if changed)
constexpr uint8_t CAL_REVERT = 4; // ... and reload all trims from the EEPROM (drop unsaved changes)
constexpr int16_t CAL_TRIM_LIMIT_US = 200; // trims are clamped to +-this
constexpr uint8_t CAL_NO_SERVO = 0xFF;
// =====================================================================
// Robot -> remote telemetry. The robot preloads this as the nRF24 ACK
// PAYLOAD, so it rides back on the auto-ack of the remote's next packet:
// no extra transmissions, and nothing changes for the remote -> robot
// direction. Ack payloads need dynamic payload lengths on both radios, so
// each end checks the received length against sizeof() itself and drops
// anything else - a remote and robot on different protocol versions still
// don't understand each other's packets.
// =====================================================================
struct Telemetry {
int16_t roll_ddeg = 0; // robot IMU roll, 0.1 deg (+ = right side down)
int16_t pitch_ddeg = 0; // robot IMU pitch, 0.1 deg (+ = nose down)
uint16_t battery_mv = 0; // robot battery, mV. 0 = not measured
int16_t cal_trim_us = 0; // centre trim of cal_servo, us
uint8_t state = 0; // TSTATE_* below
uint8_t status = 0; // TSTAT_* bits below
uint8_t cal_servo = CAL_NO_SERVO; // echo of CmdPacket.cal_servo (the trim above belongs to it)
uint8_t rx_per_sec = 0; // remote packets the robot received in the last second
int8_t joint_deg[18] = {}; // commanded joint angles, leg * 3 + joint, degrees.
// Tibia is stored + 90 (its range -150..-20 doesn't fit an int8):
// tibia = joint_deg[i * 3 + 2] - 90.
};
static_assert(sizeof(Telemetry) == 30, "Telemetry layout changed - reflash both boards");
static_assert(sizeof(Telemetry) <= 32, "nRF24L01 ack payloads are limited to 32 bytes");
constexpr int TELEMETRY_TIBIA_OFFSET_DEG = 90;
constexpr uint8_t TSTATE_DISARMED = 0; // same numbering as the robot's RobotState
constexpr uint8_t TSTATE_SIT = 1;
constexpr uint8_t TSTATE_STAND = 2;
constexpr uint8_t TSTATE_WALKING = 3;
constexpr uint8_t TSTATE_SERVO_CAL = 4;
constexpr uint8_t TSTAT_IMU_OK = 1 << 0; // robot IMU responded at power-on
constexpr uint8_t TSTAT_GYRO_ON = 1 << 1; // robot-gyro self-leveling active
constexpr uint8_t TSTAT_SERVOS_ON = 1 << 2; // servos are being driven (not relaxed)
constexpr uint8_t TSTAT_CAL_DIRTY = 1 << 3; // servo trims changed since the last save
constexpr uint8_t TSTAT_TRIMS_STORED = 1 << 4; // the EEPROM holds a trim record
// ---- Radio link settings (must be identical on both ends) ---- // ---- Radio link settings (must be identical on both ends) ----
constexpr uint8_t HXP_RADIO_ADDRESS[6] = "HXPD1"; // 5-byte pipe address + NUL constexpr uint8_t HXP_RADIO_ADDRESS[6] = "HXPD1"; // 5-byte pipe address + NUL
constexpr uint8_t HXP_RADIO_CHANNEL = 96; // 2400+96 MHz; pick one clear of your local Wi-Fi constexpr uint8_t HXP_RADIO_CHANNEL = 96; // 2400+96 MHz; pick one clear of your local Wi-Fi
constexpr uint8_t HXP_RADIO_PAYLOAD = sizeof(CmdPacket); constexpr uint8_t HXP_RADIO_PAYLOAD = sizeof(CmdPacket); // remote -> robot (checked per packet, see Telemetry)
// Data rate / PA level are RF24 enums; kept as plain ints here so this header // Data rate / PA level are RF24 enums; kept as plain ints here so this header
// doesn't depend on RF24.h. 2 == RF24_250KBPS, 1 == RF24_PA_LOW in RF24 1.x; // doesn't depend on RF24.h. 2 == RF24_250KBPS, 1 == RF24_PA_LOW in RF24 1.x;
// both Comms.cpp (robot) and RadioLink.cpp (remote) static_assert this. // both Comms.cpp (robot) and RadioLink.cpp (remote) static_assert this.
+1
View File
@@ -83,6 +83,7 @@ HXSIM_API void hxsim_step(uint32_t dt_us) {
} }
HXSIM_API void hxsim_radio_send(const uint8_t* bytes, int32_t len) { simhw::radioSend(bytes, len); } HXSIM_API void hxsim_radio_send(const uint8_t* bytes, int32_t len) { simhw::radioSend(bytes, len); }
HXSIM_API int32_t hxsim_get_ack_payload(uint8_t* out, int32_t cap) { return simhw::radioLastAckPayload(out, cap); }
HXSIM_API void hxsim_set_imu(float ax, float ay, float az, float gx, float gy, float gz) { HXSIM_API void hxsim_set_imu(float ax, float ay, float az, float gx, float gy, float gz) {
g_manual_imu = true; g_manual_imu = true;
+5 -1
View File
@@ -18,7 +18,7 @@
#endif #endif
// Bump whenever a signature or struct below changes; the C# side checks it. // Bump whenever a signature or struct below changes; the C# side checks it.
#define HXSIM_API_VERSION 7 #define HXSIM_API_VERSION 8
#define HXSIM_NUM_LEGS 6 #define HXSIM_NUM_LEGS 6
@@ -83,6 +83,10 @@ HXSIM_API void hxsim_get_servos(int32_t* us_18, int32_t* attached_18, uint32_
HXSIM_API void hxsim_get_joints_deg(float* deg_18); // servo pulses decoded through Config.h's per-servo SERVOS table HXSIM_API void hxsim_get_joints_deg(float* deg_18); // servo pulses decoded through Config.h's per-servo SERVOS table
HXSIM_API void hxsim_get_feet_mm(float* xyz_18); // forward kinematics of those angles, body frame HXSIM_API void hxsim_get_feet_mm(float* xyz_18); // forward kinematics of those angles, body frame
HXSIM_API void hxsim_get_status(HxStatus* out); HXSIM_API void hxsim_get_status(HxStatus* out);
// The robot's telemetry (shared/HexapodProtocol Telemetry) as it came back in
// the ack payload of the last packet received. Returns its length in bytes
// (sizeof(Telemetry)), 0 before the first one.
HXSIM_API int32_t hxsim_get_ack_payload(uint8_t* out, int32_t cap);
// Kinematic body (SimBody.cpp): the body rests on the support plane of its // Kinematic body (SimBody.cpp): the body rests on the support plane of its
// feet and grounded feet don't slide. World frame = robot frame at power-on, // feet and grounded feet don't slide. World frame = robot frame at power-on,
// ground at z = 0. Any pointer may be null. // ground at z = 0. Any pointer may be null.
+31 -18
View File
@@ -19,7 +19,7 @@ robot/ (unchanged) ──► PlatformIO + Teensy core ──► Teensy 3.6 firmw
|---|---| |---|---|
| `analogWrite()` hardware PWM (how `ServoDriver` drives the servos) | the pulse width per pin, worked out from duty, resolution and frequency, then decoded back to angles through `Config.h`'s per-servo `SERVOS` table | | `analogWrite()` hardware PWM (how `ServoDriver` drives the servos) | the pulse width per pin, worked out from duty, resolution and frequency, then decoded back to angles through `Config.h`'s per-servo `SERVOS` table |
| `Wire` + MPU6050 registers | a register-level fake MPU6050 at 0x68, fed from the simulated body's tilt and rotation | | `Wire` + MPU6050 registers | a register-level fake MPU6050 at 0x68, fed from the simulated body's tilt and rotation |
| `RF24` | a simulated radio: packets are received only if channel, address, data rate and **payload size** match, and the RX FIFO holds 3 | | `RF24` | a simulated radio: packets are received only if channel, address, data rate and **payload size** match (any length up to 32 once `enableAckPayload()` turns on dynamic payloads, as on the chip), and the RX FIFO holds 3. `writeAckPayload()` goes back with the next packet received: `hxsim_get_ack_payload` returns it (the robot's `Telemetry`) |
| `millis()` / `micros()` / `Serial` | a simulated clock that Unity advances, and captured serial I/O | | `millis()` / `micros()` / `Serial` | a simulated clock that Unity advances, and captured serial I/O |
`robot_ino.cpp` compiles `robot.ino` itself and exposes read-only views of `robot_ino.cpp` compiles `robot.ino` itself and exposes read-only views of
@@ -65,31 +65,43 @@ It drives the firmware the way the remote would and checks:
- **`+vx` moves the body forward**, - **`+vx` moves the body forward**,
- link loss disarms, - link loss disarms,
- a wrong-size packet is ignored, - a wrong-size packet is ignored,
- the serial harness still works. - the robot's telemetry comes back in the ack payload, and every servo
calibration command (HOLD / SET / SAVE / REVERT, arming refused) works,
- the serial harness still works,
- plus the body-pose, leg-clearance, heading and robot-gyro checks listed
in the file.
## Using it in Unity ## Using it in Unity
Open `Hexapod_Simulation_Unity` and press Play in `Main.unity`. No scene Open `Hexapod_Simulation_Unity` and press Play in `Main.unity`. No scene
edits are needed: `HexapodSimBootstrap` adds a `HexapodSimulation` object, edits are needed: `HexapodSimBootstrap` adds a `HexapodSimulation` object,
disables the old movement scripts (`Walk`, `RotationControl`, `Leg`, disables the old movement scripts (`Walk`, `RotationControl`, `Leg`), and
`HandleHoystick`), and binds the existing leg rig by name (`Leg` → `hip1` binds the existing leg rig by name (`Leg` → `hip1` / `Hip2` / `Knie`). By
/ `Hip2` / `Knie`). The on-screen panel (F1 toggles it) offers three input default `OpenScadModel` swaps the old scene's robot for the OpenSCAD model
sources: of the real one (`HexapodSimulation.useOpenScadModel`). The on-screen panel
(F1 toggles it) offers two input sources:
- **Joystick:** the real remote as a USB controller, on input axes
`"1"`–`"6"` like the old `HandleHoystick`. Axis assignment and inversion
are set on the `SimRemote` component. The panel shows the raw axes so you
can fix them.
- **Keyboard:** test without a remote. WASD walks, Q/E turns, IJKL + U/O - **Keyboard:** test without a remote. WASD walks, Q/E turns, IJKL + U/O
drive the right stick, 1–7 flip the toggles, Backspace disarms, +/- drive the right stick, 1–7 flip the toggles, Backspace disarms, +/-
change speed. change speed. The panel has every remote toggle, the speed slider and
- **Robot serial:** no radio at all. Keystrokes go to `robot.ino`'s own simulated handset tilt (remote gyro).
`TEST_SERIAL_INPUT` harness. - **Real remote (radio):** the real handheld remote, over the air. The USB
nRF24 dongle (`../dongle/`, bridge mode) receives its packets, they go
into the firmware byte for byte, and the robot's `Telemetry` goes back as
the radio's ack payload, exactly like the real robot's `Comms`. The
remote's display then shows the simulated robot (state, IMU, joint
angles, servo calibration). `DongleLink.cs` finds the dongle's CH340 port
by itself (or set `SimRemote.donglePort`, e.g. `COM7`); quit SignalRGB
first, it grabs CH340 ports. Don't run the real robot at the same time:
both would answer the remote.
The panel also has every remote toggle, the speed slider, simulated There's no USB link to the remote or the robot any more (the old joystick
handset tilt (remote gyro), a **ground tilt** slider (to test the robot and serial-harness inputs and the `Serial*` / `HandleHoystick` scripts are
gyro), and live firmware state, joint angles, foot contact, the packet on gone): everything goes over the radio.
air and robot serial output.
The panel also has a **ground tilt** slider (to test the robot gyro), and
live firmware state, joint angles, foot contact, the packet on air and the
robot's debug prints.
The body moves **kinematically**, computed in the DLL (`SimBody.cpp`), so The body moves **kinematically**, computed in the DLL (`SimBody.cpp`), so
Unity shows what the smoke test checks: Unity shows what the smoke test checks:
@@ -119,4 +131,5 @@ component to the scene yourself.
firmware *intends*, including pulse-limit clamping (which is how it firmware *intends*, including pulse-limit clamping (which is how it
caught the old ±90° coxa offsets). Whether a real servo turns that way is caught the old ±90° coxa offsets). Whether a real servo turns that way is
a bench check. a bench check.
- The remote firmware. `SimRemote.cs` mirrors its packet rules instead. - The remote firmware, in Keyboard mode: `SimRemote.cs` mirrors its packet
rules instead. With the real remote over the radio, its own firmware runs.
+26 -1
View File
@@ -213,6 +213,9 @@ struct AirPacket {
static bool g_radio_present = true; static bool g_radio_present = true;
static std::deque<AirPacket> g_air; // packets waiting at the receiver static std::deque<AirPacket> g_air; // packets waiting at the receiver
static constexpr size_t RX_FIFO_DEPTH = 3; static constexpr size_t RX_FIFO_DEPTH = 3;
static std::vector<uint8_t> g_ack_queued; // robot's writeAckPayload(), not sent yet
static bool g_ack_has_queued = false;
static std::vector<uint8_t> g_ack_delivered; // came back with the last packet received
namespace simhw { namespace simhw {
void radioSetPresent(bool present) { g_radio_present = present; } void radioSetPresent(bool present) { g_radio_present = present; }
@@ -225,6 +228,16 @@ void radioSend(const uint8_t* bytes, int len) {
memcpy(p.address, HXP_RADIO_ADDRESS, 5); memcpy(p.address, HXP_RADIO_ADDRESS, 5);
p.payload.assign(bytes, bytes + len); p.payload.assign(bytes, bytes + len);
g_air.push_back(p); g_air.push_back(p);
// The chip acks on reception, carrying whatever ack payload is queued.
if (g_ack_has_queued) {
g_ack_delivered = g_ack_queued;
g_ack_has_queued = false;
}
}
int radioLastAckPayload(uint8_t* out, int cap) {
int n = (int)g_ack_delivered.size() < cap ? (int)g_ack_delivered.size() : cap;
if (n > 0) memcpy(out, g_ack_delivered.data(), n);
return n;
} }
} // namespace simhw } // namespace simhw
@@ -240,7 +253,7 @@ bool RF24::available() {
while (!g_air.empty()) { while (!g_air.empty()) {
const AirPacket& p = g_air.front(); const AirPacket& p = g_air.front();
bool match = p.channel == channel_ && p.rate == data_rate_ && bool match = p.channel == channel_ && p.rate == data_rate_ &&
memcmp(p.address, address_, 5) == 0 && p.payload.size() == payload_size_; memcmp(p.address, address_, 5) == 0 && (dynamic_ || p.payload.size() == payload_size_);
if (match) return true; if (match) return true;
g_air.pop_front(); g_air.pop_front();
} }
@@ -252,3 +265,15 @@ void RF24::read(void* buf, uint8_t len) {
memcpy(buf, p.payload.data(), len < p.payload.size() ? len : p.payload.size()); memcpy(buf, p.payload.data(), len < p.payload.size() ? len : p.payload.size());
g_air.pop_front(); g_air.pop_front();
} }
uint8_t RF24::getDynamicPayloadSize() { return g_air.empty() ? 0 : (uint8_t)g_air.front().payload.size(); }
bool RF24::writeAckPayload(uint8_t, const void* buf, uint8_t len) {
if (!dynamic_ || len > 32) return false;
const uint8_t* b = static_cast<const uint8_t*>(buf);
g_ack_queued.assign(b, b + len);
g_ack_has_queued = true;
return true;
}
uint8_t RF24::flush_tx() {
g_ack_has_queued = false;
return 0;
}
+3
View File
@@ -32,5 +32,8 @@ void imuSet(float ax, float ay, float az, float gx, float gy, float gz);
void radioSetPresent(bool present); void radioSetPresent(bool present);
// Puts one packet "on air" using the protocol's channel/address/data rate. // Puts one packet "on air" using the protocol's channel/address/data rate.
void radioSend(const uint8_t* bytes, int len); void radioSend(const uint8_t* bytes, int len);
// The ack payload that came back with the last packet received (what the
// remote would read after write()). Returns its length, 0 if none yet.
int radioLastAckPayload(uint8_t* out, int cap);
} // namespace simhw } // namespace simhw
+1
View File
@@ -37,6 +37,7 @@ inline double degrees(double rad) { return rad * (180.0 / PI); }
void pinMode(uint8_t pin, uint8_t mode); void pinMode(uint8_t pin, uint8_t mode);
void digitalWrite(uint8_t pin, uint8_t value); void digitalWrite(uint8_t pin, uint8_t value);
void analogWrite(uint8_t pin, int value); void analogWrite(uint8_t pin, int value);
inline int analogRead(uint8_t) { return 0; } // nothing analog is simulated
uint32_t analogWriteResolution(uint32_t bits); // returns the previous resolution, like Teensyduino uint32_t analogWriteResolution(uint32_t bits); // returns the previous resolution, like Teensyduino
void analogWriteFrequency(uint8_t pin, float hz); void analogWriteFrequency(uint8_t pin, float hz);
+2 -2
View File
@@ -1,6 +1,6 @@
#pragma once #pragma once
// Not used by robot/ today; here so a future robot-side EEPROM use doesn't // ServoDriver keeps its servo centre trims here. Backed by RAM, starts erased (0xFF),
// break the simulation build silently. Backed by RAM, starts erased (0xFF). // so every simulated power-on starts with no trims stored.
#include <Arduino.h> #include <Arduino.h>
class SimEEPROM { class SimEEPROM {
+11 -2
View File
@@ -8,8 +8,11 @@ enum rf24_datarate_e { RF24_1MBPS = 0, RF24_2MBPS, RF24_250KBPS };
// A simulated radio. Packets the simulation puts "on air" (hxsim_radio_send) // A simulated radio. Packets the simulation puts "on air" (hxsim_radio_send)
// are only received if this radio's channel, data rate, address and static // are only received if this radio's channel, data rate, address and static
// payload size match the sender's, just like the real nRF24L01. The RX FIFO // payload size match the sender's, just like the real nRF24L01 (with dynamic
// holds 3 packets; extra packets are dropped. // payloads - enableAckPayload() - any length up to 32 is received). The RX
// FIFO holds 3 packets; extra packets are dropped. An ack payload queued with
// writeAckPayload() goes back with the next packet received, like the chip's
// auto-ack (hxsim_get_ack_payload shows it).
class RF24 { class RF24 {
public: public:
RF24(uint16_t ce_pin, uint16_t csn_pin) { (void)ce_pin; (void)csn_pin; } RF24(uint16_t ce_pin, uint16_t csn_pin) { (void)ce_pin; (void)csn_pin; }
@@ -27,6 +30,11 @@ public:
bool available(); bool available();
void read(void* buf, uint8_t len); void read(void* buf, uint8_t len);
bool write(const void*, uint8_t) { return false; } // the robot never transmits bool write(const void*, uint8_t) { return false; } // the robot never transmits
void enableDynamicPayloads() { dynamic_ = true; }
void enableAckPayload() { dynamic_ = true; }
uint8_t getDynamicPayloadSize();
bool writeAckPayload(uint8_t pipe, const void* buf, uint8_t len);
uint8_t flush_tx();
private: private:
uint8_t payload_size_ = 32; uint8_t payload_size_ = 32;
@@ -35,4 +43,5 @@ private:
uint8_t address_[5] = {}; uint8_t address_[5] = {};
bool pipe_open_ = false; bool pipe_open_ = false;
bool listening_ = false; bool listening_ = false;
bool dynamic_ = false;
}; };
+77
View File
@@ -227,6 +227,21 @@ int main() {
snprintf(buf, sizeof(buf), "%u servo writes in 1.5 s (0 = every IK solution was rejected as invalid)", writes); snprintf(buf, sizeof(buf), "%u servo writes in 1.5 s (0 = every IK solution was rejected as invalid)", writes);
check(writes > 0, "IK produces valid joint solutions at the stance pose", buf); check(writes > 0, "IK produces valid joint solutions at the stance pose", buf);
printLegs("standing:"); printLegs("standing:");
{
Telemetry t;
int len = hxsim_get_ack_payload(reinterpret_cast<uint8_t*>(&t), sizeof(t));
float deg[18]; hxsim_get_joints_deg(deg);
float worst = 0;
for (int i = 0; i < 18; i++) {
float tj = t.joint_deg[i] - (i % 3 == 2 ? TELEMETRY_TIBIA_OFFSET_DEG : 0);
worst = fmaxf(worst, fabsf(tj - deg[i]));
}
snprintf(buf, sizeof(buf), "%d bytes, state %u, status %02X, joints off by up to %.1f deg, %u packets/s",
len, t.state, t.status, worst, t.rx_per_sec);
check(len == (int)sizeof(Telemetry) && t.state == TSTATE_STAND && (t.status & TSTAT_SERVOS_ON) &&
worst < 1.5f && t.rx_per_sec >= 90,
"telemetry comes back in the ack payload (state, servo angles, packet rate)", buf);
}
float feet[18]; hxsim_get_feet_mm(feet); float feet[18]; hxsim_get_feet_mm(feet);
float worst = 0; float worst = 0;
@@ -553,6 +568,68 @@ int main() {
s = status(); s = status();
check(!s.link_ok && s.robot_state == 0, "link loss (>0.3 s silence) disarms the robot"); check(!s.link_ok && s.robot_state == 0, "link loss (>0.3 s silence) disarms the robot");
// ---- Servo centre calibration (CAL_* commands, only while disarmed) ----
{
auto tele = []() { Telemetry t; hxsim_get_ack_payload(reinterpret_cast<uint8_t*>(&t), sizeof(t)); return t; };
int us[18], att[18]; uint32_t wr[18];
CmdPacket c; // disarmed
c.cal_cmd = CAL_HOLD;
c.cal_servo = 4; // leg 1 (mid-right) femur
run(c, 0.3f);
float deg[18]; hxsim_get_joints_deg(deg);
hxsim_get_servos(us, att, wr);
float worst = 0; int relaxed = 0;
for (int i = 0; i < 18; i++) {
worst = fmaxf(worst, fabsf(deg[i] - (i % 3 == 2 ? -90.0f : 0.0f)));
if (!att[i]) relaxed++;
}
Telemetry t = tele();
snprintf(buf, sizeof(buf), "state %u, %d relaxed, pose off by up to %.1f deg", t.state, relaxed, worst);
check(t.state == TSTATE_SERVO_CAL && relaxed == 0 && worst < 1.0f,
"CAL_HOLD holds every servo at the centre pose (coxa 0, femur 0, tibia -90)", buf);
int us0 = us[4];
c.cal_cmd = CAL_SET; c.cal_value = 50;
run(c, 0.2f);
hxsim_get_servos(us, att, wr);
t = tele();
snprintf(buf, sizeof(buf), "pulse %d -> %d us, echo servo %u trim %d, status %02X", us0, us[4], t.cal_servo, t.cal_trim_us, t.status);
check(abs(us[4] - us0 - 50) <= 1 && t.cal_servo == 4 && t.cal_trim_us == 50 && (t.status & TSTAT_CAL_DIRTY),
"CAL_SET trims the selected servo and the telemetry echoes it", buf);
c.cal_cmd = CAL_SAVE;
run(c, 0.2f);
t = tele();
check((t.status & TSTAT_TRIMS_STORED) && !(t.status & TSTAT_CAL_DIRTY), "CAL_SAVE stores the trims");
c.cal_cmd = CAL_SET; c.cal_value = -120;
run(c, 0.2f);
c.cal_cmd = CAL_REVERT;
run(c, 0.2f);
t = tele();
snprintf(buf, sizeof(buf), "trim %d after revert", t.cal_trim_us);
check(t.cal_trim_us == 50 && !(t.status & TSTAT_CAL_DIRTY), "CAL_REVERT drops unsaved trims", buf);
c.flags = FLAG_ARMED; // arming wins over calibration
run(c, 0.3f);
t = tele();
check(t.state == TSTATE_SIT, "arming while CAL_* is sent leaves SERVO_CAL (robot arms into SIT)");
c.flags = 0; c.cal_cmd = CAL_SET; c.cal_value = 0; // put the trim back for the checks below
run(c, 0.2f);
c.cal_cmd = CAL_SAVE;
run(c, 0.2f);
c.cal_cmd = CAL_NONE;
run(c, 0.2f);
hxsim_get_servos(us, att, wr);
relaxed = 0;
for (int i = 0; i < 18; i++) if (!att[i]) relaxed++;
t = tele();
snprintf(buf, sizeof(buf), "state %u, %d of 18 relaxed, trim %d", t.state, relaxed, t.cal_trim_us);
check(t.state == TSTATE_DISARMED && relaxed == 18 && t.cal_trim_us == 0, "CAL_NONE relaxes the servos again", buf);
runSilent(0.5f);
}
// ---- Protocol mismatch fails closed ---- // ---- Protocol mismatch fails closed ----
uint8_t short_payload[16] = {}; uint8_t short_payload[16] = {};
short_payload[10] = FLAG_ARMED; short_payload[10] = FLAG_ARMED;