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>
This commit is contained in:
mangavalkandClaude Opus 5.5 committed 2026-11-17 14:42:37 +01:00
1 parent 481610c9fd
commit 0b836af8de
40 files changed
+1463 -281

No files matched your search

+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;
};
+31 -18
View File
@@ -109,24 +109,37 @@ constexpr uint32_t WALK_LINGER_MS = 250;
// (post-deadzone, -1000..1000 scale), so the robot never arms mid-command.
constexpr int16_t ARM_CENTER_TOLERANCE = 50;
// ---- Nextion touchscreen on Serial1 (RX1 = pin 0, TX1 = pin 1), as in the old remote ----
#define NEXTION_SERIAL Serial1
// BENCH: the old sketch used the ITEAD library, whose nexInit() talks at 9600
// unless it was modified. This firmware expects 115200: add `bauds=115200`
// to the HMI's Program.s (see remote/NEXTION.md) or set 9600 here.
// ---- Nextion touchscreen on Serial2 (RX2 = pin 7, TX2 = pin 8) ----
// Found on the real remote (2026-11-17): the display answers on Serial2 at 115200. The old
// sketch's Serial1.begin() was a red herring; its ITEAD Nextion library used Serial2.
#define NEXTION_SERIAL Serial2
// The HMI (remote/remote.HMI) sets this with `bauds=115200` in Program.s.
constexpr uint32_t NEXTION_BAUD = 115200;
// Controls live on this page (remote/NEXTION.md). Its components must have
// vscope = global, so the firmware can update them whichever page is showing.
#define NEXTION_CONTROL_PAGE "control"
// The old HMI's link-status texts, also vscope = global. Its pages are
// 0 splashsceen (sic), 1 main, 2 servocal, 3 page0, 4 uploadscreen,
// 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"
#define NEXTION_UPLOAD_PAGE "upload"
// The firmware only writes the page that is showing (each page reports itself
// with a 'P' frame), and only what changed since the last write.
constexpr uint32_t NEXTION_RENDER_MS = 50; // repaint rate of the showing page
constexpr uint32_t NEXTION_SERVOS_RENDER_MS = 100; // SERVOS page: 36 values, so a bit slower
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 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;
+84 -98
View File
@@ -1,112 +1,98 @@
# Nextion HMI build guide
# Nextion HMI
Work in `remote.HMI` in this folder (a copy of the old servo monitor,
`../../2019-teensy-nrf24/remote-nextion/remote.HMI`, re-saved by a newer
Nextion Editor) and **add one page named `control`** with the components below.
The old HMI's pages:
| # | 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:
`remote.HMI` in this folder is the touchscreen project (NX4832T035, 480×320).
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.
```
bauds=115200
python scripts\make_remote_hmi.py (from 2026-current)
```
This sets the display to the `NEXTION_BAUD` in `remote/Config.h`. The
display ships at 9600, and `bauds=` persists across power cycles. The old
firmware used the ITEAD library at 9600, so your HMI probably runs at 9600
today.
It needs the `tools/nextion-hmi-tools` submodule, Pillow, DejaVu Sans Mono
(found in matplotlib, or `--font-dir`), and the old remote HMI
(`../../2019-teensy-nrf24/remote-nextion/remote.HMI`, read only) for the
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
into `uploadscreen` for upload mode. Add buttons on your other pages to
switch to it (`page control`).
## Pages
## 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
the firmware writes. Button bounds here allow some slack.
Pages 1–5 share a frame: a top bar (`tLink` link quality, `tState` robot
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 |
|----------|---------|----------|----------------------------------------------|
| `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 |
## How the firmware talks to it
## 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
uses **Touch Move** as well so the value tracks your finger). Frame format:
`'#'` (0x23), length, command byte, optional value byte.
## Commands (display → remote)
| Component | Event code | Command |
|-----------|------------------------------------------|--------------------------------|
| `bArm` | `printh 23 01 41` | `A` toggle arm (needs sticks centered) |
| `bKill` | `printh 23 01 4B` | `K` disarm, always accepted |
| `bStand` | `printh 23 01 53` | `S` toggle sit/stand |
| `bGait` | `printh 23 01 47` | `G` tripod ↔ wave |
| `bMode` | `printh 23 01 4D` | `M` direct ↔ heading-hold |
| `bRs` | `printh 23 01 58` | `X` right stick rotate ↔ translate |
| `bRGyro` | `printh 23 01 52` | `R` remote-gyro tilt on/off |
| `bBGyro` | `printh 23 01 42` | `B` robot self-stabilize on/off |
| `hSpeed` | `printh 23 02 56`<br>`prints hSpeed.val,1` | `V` + speed byte |
| `hHeight` | `printh 23 02 48`<br>`prints hHeight.val,1` | `H` + height byte (Touch Move + Release) |
| `bZero` | `printh 23 01 5A` | `Z` zero handset level |
| `bCal` | `printh 23 01 43` | `C` start / save stick calibration |
| `bCalX` | `printh 23 01 51` | `Q` cancel calibration |
| Component | Event code | Command |
|-----------|-----------|---------|
| every page | `printh 23 02 50 <id>` (Preinitialize) | `P` page shown |
| `bKill` | `printh 23 01 4B` | `K` disarm, always accepted |
| `bArm` | `printh 23 01 41` | `A` toggle arm (needs sticks centered) |
| `bStand` | `printh 23 01 53` | `S` toggle sit/stand |
| `bGait` | `printh 23 01 47` | `G` tripod ↔ wave |
| `bMode` | `printh 23 01 4D` | `M` direct ↔ heading-hold |
| `bRs` | `printh 23 01 58` | `X` right stick rotate ↔ translate |
| `bRGyro` | `printh 23 01 52` | `R` remote-gyro tilt on/off |
| `bBGyro` | `printh 23 01 42` | `B` robot self-stabilize on/off |
| `hSpeed` | `printh 23 02 56` + `prints hSpeed.val,1` (move + release) | `V` + speed 0..255 |
| `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 |
| `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
standard touch frames only add serial traffic. The one exception is the old
page 1 `b2` upload button (see the top).
To add a control: pick an unused command byte, add it to
`NextionUI::decodeCustom()` and `UiCmd`, handle it in `RemoteState::handle()`,
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
control, pick an unused command byte, add it to `NextionUI::decodeCustom()`
and `UiCmd`, handle it in `RemoteState::handle()`, and add a row here.
## What the remote writes (remote → display)
| 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_DANGER = 63488; // red
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
// 115200 baud) block the TX loop for ~35 ms. Give it room to queue.
static uint8_t tx_extra[1024];
// The default 64-byte TX buffer would make a full redraw (~1 kB at 115200
// baud) block the TX loop for ~90 ms. Give it room to queue.
static uint8_t tx_extra[2048];
static uint8_t rx_extra[128];
// Every control lives on NEXTION_CONTROL_PAGE with vscope = global, so it's
// addressed as page.component and can be updated whichever page is showing.
#define P NEXTION_CONTROL_PAGE "."
static const char* const LEG_NAMES[6] = { "FR", "MR", "RR", "RL", "ML", "FL" }; // robot leg order
static const char* const JOINT_NAMES[3] = { "coxa", "femur", "tibia" };
void NextionUI::begin() {
NEXTION_SERIAL.begin(NEXTION_BAUD);
NEXTION_SERIAL.addMemoryForWrite(tx_extra, sizeof(tx_extra));
NEXTION_SERIAL.addMemoryForRead(rx_extra, sizeof(rx_extra));
cmd("bkcmd=0"); // no success/fail replies - we never need them (and a
// write to a page the HMI doesn't have is then just ignored)
cmd("bkcmd=0"); // no success/fail replies - we never need them (and a write
// 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;
}
void NextionUI::cmd(const char* fmt, ...) {
char buf[80];
char buf[96];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
@@ -37,6 +39,30 @@ void NextionUI::cmd(const char* fmt, ...) {
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 ----
bool NextionUI::decodeCustom(UiEvent& out) {
@@ -55,26 +81,37 @@ bool NextionUI::decodeCustom(UiEvent& out) {
case 'Z': out.cmd = UiCmd::ZeroGyro; break;
case 'C': out.cmd = UiCmd::CalStartSave; 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;
}
return true;
}
// Standard Nextion frames (terminated FF FF FF). Two matter:
// 0x88 / 0x00 display (re)started -> redraw everything
// 0x65 page id event touch event from a component with "Send Component
// ID" ticked - how the old HMI's upload button (b2)
// reports, so it keeps working unchanged.
// 0x88 / 0x00 display (re)started -> redraw everything (its start page
// then reports itself with 'P')
// 0x66 page reply to `sendme`: the page that is showing
bool NextionUI::decodeNative(UiEvent& out) {
if (native_buf_[0] == 0x88 || native_buf_[0] == 0x00) {
force_full_ = true;
return false;
}
if (native_buf_[0] == 0x65 && native_len_ >= 4 &&
native_buf_[1] == NEXTION_UPLOAD_BUTTON_PAGE && native_buf_[2] == NEXTION_UPLOAD_BUTTON_ID) {
out.cmd = UiCmd::NextionUpload;
out.value = 0;
if (native_buf_[0] == 0x66 && native_len_ >= 5) {
if (native_buf_[1] == page_) return false;
setPage(native_buf_[1]);
out.cmd = UiCmd::PageShown;
out.value = native_buf_[1];
return true;
}
return false;
@@ -131,62 +168,170 @@ bool NextionUI::poll(UiEvent& out) {
// ---- Render ----
void NextionUI::pushState(const UiView& v, bool full) {
const UiView& s = shown_;
if (full || v.armed != s.armed) {
cmd(P "bArm.txt=\"%s\"", v.armed ? "ARMED" : "DISARMED");
cmd(P "bArm.bco=%u", v.armed ? COL_DANGER : COL_OFF);
static const char* robotStateName(uint8_t s) {
switch (s) {
case TSTATE_DISARMED: return "DISARMED";
case TSTATE_SIT: return "SIT";
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) {
if (v.link_ok) cmd(P "tLink.txt=\"LINK %u%%\"", v.link_pct);
else cmd(P "tLink.txt=\"NO LINK\"");
cmd(P "tLink.pco=%u", v.link_ok ? COL_ON : COL_DANGER);
// The old HMI's own status texts, same wording as the old firmware.
for (const char* t : NEXTION_STATUS_TEXTS)
cmd("%s.txt=\"%s\"", t, v.link_ok ? "connected" : "not connected");
// "7.2V", or "--" when the battery isn't measured.
static const char* volts(char* buf, size_t n, uint16_t mv) {
if (mv == 0) snprintf(buf, n, "--");
else snprintf(buf, n, "%u.%uV", mv / 1000, (mv % 1000) / 100);
return buf;
}
// 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) {
bool full = force_full_ || (now_ms - last_full_ms_) >= NEXTION_FULL_REFRESH_MS;
if (full) {
uint32_t interval = page_ == PAGE_SERVOS ? NEXTION_SERVOS_RENDER_MS : NEXTION_RENDER_MS;
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;
last_full_ms_ = now_ms;
if (page_ == PAGE_UNKNOWN) cmd("sendme"); // still don't know the page: ask again
}
slot_ = 0;
pushState(v, full);
// Link quality changes nearly every packet; repaint it at a readable rate,
// but immediately when the link comes or goes.
if (full || v.link_ok != shown_.link_ok || (now_ms - last_link_ms_) >= NEXTION_LINK_REFRESH_MS) {
pushLink(v);
last_link_ms_ = now_ms;
switch (page_) {
case PAGE_DRIVE: renderTopBar(v); renderDrive(v); break;
case PAGE_STATUS: renderTopBar(v); renderStatus(v); break;
case PAGE_SERVOS: renderTopBar(v); renderServos(v); break;
case PAGE_CAL: renderTopBar(v); renderCal(v); break;
case PAGE_SETUP: renderTopBar(v); renderSetup(v); break;
default: break; // splash / upload / unknown: nothing to show
}
shown_ = v;
}
// ---- Upload passthrough ----
+31 -12
View File
@@ -7,17 +7,21 @@
// Nextion -> remote: custom frames the HMI's touch events send with printh:
// '#' <len> <cmd> [value] e.g. printh 23 01 41 (ToggleArm)
// printh 23 02 56 + prints hSpeed.val,1
// Command bytes are listed in NEXTION.md and in NextionUI.cpp.
// Native Nextion return frames (terminated FF FF FF) are also parsed: a
// display reset (0x88 "ready") triggers a full redraw, and the old HMI's
// upload button sends a standard touch event (0x65) that's recognized.
// Command bytes are listed in NEXTION.md and in NextionUI.cpp. Every
// page's Preinitialize event sends 'P' + its page id, so the remote always
// knows which page is showing. Native Nextion return frames (terminated
// 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).
//
// The remote is authoritative: buttons are plain buttons (not dual-state),
// they only send 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.
// Only the page that is showing is written (by local component names), and
// only what changed: every instruction is hashed into a per-page cache. The
// remote is authoritative: buttons are plain buttons, they only send
// 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 {
public:
void begin();
@@ -35,14 +39,29 @@ private:
uint8_t native_buf_[8];
uint8_t native_len_ = 0, ff_run_ = 0;
UiView shown_;
uint8_t page_ = PAGE_UNKNOWN;
bool force_full_ = true;
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 pushState(const UiView& v, bool full);
void pushLink(const UiView& v);
void put(const char* fmt, ...); // like cmd(), but only if it changed
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 decodeNative(UiEvent& out);
};
+3
View File
@@ -14,6 +14,9 @@ CmdPacket PacketBuilder::build(const StickFrame& s, const RemoteIMU& imu, const
p.seq = seq_++;
p.speed_scale = st.speedCurrent();
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;
if (st.armed()) f |= FLAG_ARMED;
+56 -14
View File
@@ -8,11 +8,13 @@ at 100 Hz.
## 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)
into A6 (pin 20, free), with 100 nF to GND, and show the charge on the
Nextion with a low-battery warning. Details in
`../hardware/openscad/PLANNING.md` (notes for future designs).
into A6 (pin 20, free), with 100 nF to GND. Details in
`../hardware/openscad/PLANNING.md` (notes for future designs). The
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
warning is still to do.
- **IMU on the normal pin headers** (suggestion, not done): with the GY-521 on
the main board, wire it to Wire (SDA 18 / SCL 19) instead of Wire2 (the
@@ -37,7 +39,7 @@ From the `2026-current` folder: `pio run -e remote`, flash with
| nRF24L01 | CE / CSN | 9 / 10 |
| 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 |
| Nextion | TX → RX1, RX ← TX1 | 0 / 1 (Serial1), 5 V supply |
| Nextion | TX → RX2, RX ← TX2 | 7 / 8 (Serial2), 5 V supply (found on the real remote) |
| Sticks | 6 axes | A0–A5. Which axis is on which pin isn't known yet: reorder `STICK_PINS` until the `p` dump reads right |
**MPU6050 rewiring:** the old remote had its MPU code switched off, probably
@@ -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
its heading.
Touchscreen: ARM / DISARM, SIT/STAND, TRIPOD/WAVE, DIRECT/HEADING,
R: ROTATE/MOVE, REMOTE GYRO, ROBOT GYRO, speed slider, LEVEL (re-zero the
handset tilt), CAL / CANCEL CAL. `NEXTION.md` has the HMI build guide.
Touchscreen (`NEXTION.md` has the details), with tabs along the bottom and
a red DISARM on every page:
- **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`)
- **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,
so re-arming never stands it up by itself.
- **Link loss:** if no ack arrives for `LINK_LOST_MS` (300 ms, matching the
@@ -122,6 +154,12 @@ display attached.
| `c` | start / save calibration | `x` | cancel calibration |
| `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) |
| `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
@@ -131,10 +169,14 @@ display attached.
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` /
`IMU_AXIS_SIGN`.
3. **Nextion baud:** `bauds=115200` must be in Program.s, or the display
shows nothing useful.
4. **Radio:** with the robot powered, `tLink` / `p` should show ~100%. If
it reads NO LINK, check that both boards were built from the same
`HexapodProtocol.h`. The static payload size is part of the handshake.
3. **Nextion baud:** the generated HMI sets `bauds=115200` in Program.s.
The display still runs the old HMI (probably 9600) until you upload
the new one; Nextion Editor finds the baud rate by itself. For that
first upload use serial key `U`: the old HMI's UPLOAD button isn't
recognised any more.
4. **Radio:** with the robot powered, `tLink` / `p` should show ~100%, and
`p` should print robot telemetry. If it reads NO LINK, check that both
boards were built from the same `HexapodProtocol.h`: each end drops
packets of the wrong size.
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.
+16 -1
View File
@@ -11,7 +11,10 @@ static RF24 radio(RADIO_CE_PIN, RADIO_CSN_PIN);
bool RadioLink::begin() {
present_ = radio.begin();
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.setDataRate((rf24_datarate_e)HXP_RADIO_DATA_RATE);
radio.setChannel(HXP_RADIO_CHANNEL);
@@ -30,6 +33,18 @@ bool RadioLink::send(const CmdPacket& p) {
last_ack_ms_ = millis();
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;
}
+11
View File
@@ -1,8 +1,10 @@
#pragma once
#include <HexapodProtocol.h>
#include "Config.h"
// 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.
// The robot's Telemetry comes back as the ack's payload.
class RadioLink {
public:
bool begin(); // false if the radio chip didn't respond
@@ -13,10 +15,19 @@ public:
bool linkOk() const { return link_ok_; }
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:
bool present_ = false;
bool link_ok_ = false;
uint32_t last_ack_ms_ = 0;
bool ever_acked_ = false;
uint32_t history_ = 0; // 1 bit per packet, newest in bit 0
Telemetry telemetry_;
bool has_telemetry_ = false;
uint32_t telemetry_ms_ = 0;
};
+111 -6
View File
@@ -17,6 +17,26 @@ void RemoteState::disarm() {
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) {
const StickFrame& sticks = stick_hw.frame();
switch (e.cmd) {
@@ -30,6 +50,7 @@ bool RemoteState::handle(const UiEvent& e, Sticks& stick_hw, RemoteIMU& imu, uin
case UiCmd::ToggleArm:
if (armed_) { disarm(); return true; }
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; }
armed_ = true;
return true;
@@ -81,6 +102,66 @@ bool RemoteState::handle(const UiEvent& e, Sticks& stick_hw, RemoteIMU& imu, uin
case UiCmd::NextionUpload:
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:
if (!calibrating_) return false;
stick_hw.cancelCalibration();
@@ -91,16 +172,35 @@ bool RemoteState::handle(const UiEvent& e, Sticks& stick_hw, RemoteIMU& imu, uin
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
// stop, so the remote disarms too and the operator must re-arm on purpose
// once the link is back.
if (!link_ok && link_was_ok_ && armed_) {
disarm();
setMessage("Link lost - disarmed", now_ms);
// once the link is back. Servo calibration stops the same way, so the
// servos don't spring back to centre on their own when the link returns.
if (!link_ok && link_was_ok_) {
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;
// 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_.update(dt);
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.remote_gyro = remote_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.height = height_;
v.message = message(now_ms);
+28 -2
View File
@@ -17,8 +17,9 @@ public:
// rejections leave an explanation in message().
bool handle(const UiEvent& e, Sticks& sticks, RemoteIMU& imu, uint32_t now_ms);
// Advances smoothers and link-loss handling. Call once per TX tick.
void update(float dt, bool link_ok, uint32_t now_ms);
// Advances smoothers and link-loss handling, and reads the servo trim back
// 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 standRequested() const { return stand_; }
@@ -33,6 +34,17 @@ public:
uint8_t speedCurrent() const { return (uint8_t)lroundf(speed_.current); }
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_ : ""; }
void setMessage(const char* msg, uint32_t now_ms);
@@ -53,9 +65,23 @@ private:
SmoothedValue speed_{SPEED_SCALE_RATE_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;
const char* message_ = "";
uint32_t message_until_ms_ = 0;
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 'x': ui.cmd = UiCmd::CalCancel; 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 'd': local = Local::ToggleDump; return true;
case 'R': local = Local::ResetCal; return true;
+50 -4
View File
@@ -1,5 +1,7 @@
#pragma once
#include <Arduino.h>
#include <HexapodProtocol.h>
#include "Config.h"
// Operator commands. Produced by the Nextion touchscreen (NextionUI) and by
// the USB serial console (SerialConsole) through the same path, so the
@@ -21,19 +23,43 @@ enum class UiCmd : uint8_t {
HeightUp, // serial console only
HeightDown, // serial console only
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,
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 {
UiCmd cmd = UiCmd::None;
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
// only sends requests, and always renders what's in here.
struct UiView {
// Operator state (DRIVE page)
bool armed = false;
bool stand = false;
bool gait_wave = false;
@@ -41,10 +67,30 @@ struct UiView {
bool rstick_xlate = false;
bool remote_gyro = false;
bool robot_gyro = false;
bool calibrating = false;
uint8_t speed_target = 0;
int16_t height = 0; // -1000..1000, 0 = default
// Radio + robot telemetry
bool link_ok = false;
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 "NextionUI.h"
#include "SerialConsole.h"
#include "Battery.h"
// Hexapod remote (Teensy 4.0): reads two 3-axis sticks and the handset
// MPU6050, takes operator commands from the Nextion touchscreen (and the USB
@@ -19,6 +20,7 @@ PacketBuilder builder;
RadioLink radio_link;
NextionUI nextion;
SerialConsole console;
Battery battery;
uint32_t last_tx_us = 0;
bool dump_packets = false;
@@ -39,6 +41,22 @@ static void printStatus() {
state.modeB() ? "B" : "A", state.rstickXlate() ? "xlate" : "rot",
state.remoteGyro(), state.robotGyro(), state.speedTarget(), state.speedCurrent(), state.height());
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) {
@@ -47,7 +65,7 @@ static void dumpPacket(const CmdPacket& p) {
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
// disarms itself after LINK_TIMEOUT_SEC. Power-cycle the remote to leave.
static void enterNextionUpload() {
@@ -61,8 +79,8 @@ static void enterNextionUpload() {
static void pollInputs(uint32_t now_ms) {
UiEvent ev;
while (nextion.poll(ev)) {
if (ev.cmd == UiCmd::NextionUpload) enterNextionUpload();
state.handle(ev, sticks, imu, now_ms);
if (state.takeUploadRequest()) enterNextionUpload(); // UPDATE DISPLAY, tapped twice
}
SerialConsole::Local local;
@@ -114,7 +132,9 @@ void loop() {
sticks.update();
imu.update(dt);
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);
radio_link.send(last_packet);
@@ -123,6 +143,13 @@ void loop() {
state.fillView(view, now_ms);
view.link_ok = radio_link.linkOk();
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);
if (dump_packets && now_ms - last_dump_ms >= 100) {