Files
hexapod-robot/2026-current/sim/README.md
T
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

130 lines
5.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Firmware simulation (software-in-the-loop)
This folder compiles the **unchanged** robot firmware (`robot/*.cpp` plus
`robot.ino`) into a Windows DLL. The Unity project
(`Hexapod_Simulation_Unity/`) runs that DLL, so the code you test in the
simulation is exactly the code you flash to the Teensy. `robot/` has no
`#ifdef SIM` anywhere.
```
robot/ (unchanged) ──► PlatformIO + Teensy core ──► Teensy 3.6 firmware
└─► CMake + g++ + sim/shim/ ──► sim/build/hexapod_sim.dll ──► Unity
```
## How it works
`shim/` provides PC stand-ins for the only hardware the firmware touches:
| Firmware uses | Simulated as |
|---|---|
| `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 |
| `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 |
`robot_ino.cpp` compiles `robot.ino` itself and exposes read-only views of
its globals (state machine, heading, IMU filter, gait phase) for status
display. `HexapodSimApi.h` is the C API. Its forward kinematics is written
separately from `robot/Kinematics.cpp` on purpose, so it can catch IK
mistakes.
## Build
Needs a 64-bit g++ and CMake. Strawberry Perl's `C:\Strawberry\c\bin` has
g++, cmake and ninja, and the script falls back to it automatically. From
the `2026-current` folder in PowerShell:
```
.\sim\build.ps1 # configure (first time) + build + smoke test
.\sim\build.ps1 -NoTest # build only
.\sim\build.ps1 -Clean # rebuild from scratch
```
To run the steps by hand, use separate lines. Windows PowerShell 5.1 has
no `&&`:
```
cmake -S sim -B sim\build -G Ninja
cmake --build sim\build
.\sim\build\sim_smoke.exe
```
Rebuild after any change in `robot/` or `shared/`. In Unity, press **Play**
(or **Reload firmware** in the panel) to pick up the new DLL. Unity copies
the DLL before loading it, so it never locks the build output and you
don't need to restart the editor.
## Headless smoke test (`tests/sim_smoke.cpp`)
It drives the firmware the way the remote would and checks:
- disarmed at power-on,
- arm lands in SIT,
- stand reaches STAND,
- **IK gives valid solutions and the feet end up at `STANCE_HEIGHT`**,
- `FLAG_WALK` leads to WALKING,
- **`+vx` moves the body forward**,
- link loss disarms,
- a wrong-size packet is ignored,
- the serial harness still works.
## Using it in Unity
Open `Hexapod_Simulation_Unity` and press Play in `Main.unity`. No scene
edits are needed: `HexapodSimBootstrap` adds a `HexapodSimulation` object,
disables the old movement scripts (`Walk`, `RotationControl`, `Leg`), and
binds the existing leg rig by name (`Leg` → `hip1` / `Hip2` / `Knie`). The
on-screen panel (F1 toggles it) offers two input sources:
- **Keyboard:** test without a remote. WASD walks, Q/E turns, IJKL + U/O
drive the right stick, 1–7 flip the toggles, Backspace disarms, +/-
change speed. The panel has every remote toggle, the speed slider and
simulated handset tilt (remote gyro).
- **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.
There's no USB link to the remote or the robot any more (the old joystick
and serial-harness inputs and the `Serial*` / `HandleHoystick` scripts are
gone): everything goes over the radio.
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
Unity shows what the smoke test checks:
- The body rests on the support plane of its feet, the plane all feet are
on or above.
- Grounded feet don't slide.
- The simulated MPU6050 reads that body's tilt and rotation rate.
The sphere at each foot (`Point`) is placed by the DLL's forward
kinematics. If it doesn't sit on the tibia tip, the rig and `Config.h`
disagree.
Setup that lives in the Inspector on `HexapodSimulation`:
- `forwardAxis`: robot forward = Unity −X by default, taken from the old
scene's `invertForLeftLeg` naming.
- `unitsPerMm`: 0.1, since the model is in cm.
- `kneeRestDeg`: −90, the rig's knee pose at rotation 0.
For a custom setup instead of the bootstrap, add a `HexapodSimulation`
component to the scene yourself.
## What is not simulated
- Physics (mass, falling, slipping, servo torque and speed).
- Whether the calibration matches the real servos. The sim decodes pulses
through the same `SERVOS` table the firmware uses, so it shows what the
firmware *intends*, including pulse-limit clamping (which is how it
caught the old ±90° coxa offsets). Whether a real servo turns that way is
a bench check.
- The remote firmware, in Keyboard mode: `SimRemote.cs` mirrors its packet
rules instead. With the real remote over the radio, its own firmware runs.