Link protocol v2 receiver, ESP-NOW leg, Patrol gauge outputs, gear pulse

- protocol header v2 copied byte-identical from the 5B repo
- uart_receiver: processFrame() shared by the UART framing task and ESP-NOW,
  version check, dedupe on packet_id+timestamp, per-transport liveness,
  CONFIG cache with sequence number
- espnow_receiver: STA mode, channel hopping while silent, locks on frames
- gauge_outputs: tach on IO7 (LEDC ch2, 14-bit), coolant PWM on IO8 (LEDC
  ch4, 8-bit), config cached in NVS, overrides applied but not saved
- main: gear label from lever + engaged/target (pulses while shifting, red on
  mismatch), icons driven by A's alert bits, gauge update at 5 Hz, link stats
- wiki: temp_stage.cfd (user's old CANNY program) decoded as prior art;
  controller-link, link-redundancy, patrol-gauge-outputs, open-questions
  updated with the bench-verified v2 results and calibration procedure

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-21 19:12:38 +02:00
parent 3613387d41
commit 5fe313b7fa
18 changed files with 1658 additions and 514 deletions
+4 -4
View File
@@ -197,8 +197,11 @@
"bases:Create new base": false
}
},
"active": "414d380b45e2466d",
"active": "d1e54c160baeb57c",
"lastOpenFiles": [
"sources/temp-stage-cfd.md",
"sources/temp-stage-cfd.md.tmp.8664.e5d183fc2b73",
"raw/temp_stage.cfd",
"pages/sedyhRU0S",
"pages/sedIT5Pq3",
"sources/sedWvixlJ",
@@ -211,11 +214,8 @@
"index.md",
"index.md.tmp.8664.f6325122b3bb",
"sources/pinout-photo-details-7.md",
"sources/pinout-photo-details-7.md.tmp.8664.84fea9960617",
"sources/waveshare-wiki-esp32-s3-lcd-1-3.md",
"sources/waveshare-wiki-esp32-s3-lcd-1-3.md.tmp.8664.230b4837adb6",
"pages/open-questions.md",
"pages/open-questions.md.tmp.8664.fdfb3a9afb71",
"pages/patrol-gauge-outputs.md",
"pages/link-redundancy.md",
"pages/controller-link.md",
+5 -4
View File
@@ -13,15 +13,16 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee
## Concepts
- [[controller-link]] — the A → B link: 23-byte UART packet @ 5 Hz, what each field really carries (oil temp is dead, RPM missing), pins (A TX = GPIO 44, B RX = IO1), the **RS485-vs-TTL physical-layer question**, and the **gear-enum drift** between the two repos
- [[link-redundancy]] — design space for wired + wireless redundancy: RS485 vs TTL, BLE GATT vs ESP-NOW, failover policy on B, and why A must always transmit on both paths
- [[patrol-gauge-outputs]] — driving the Patrol cluster's tachometer (variable frequency) and coolant gauge (variable duty) from B's LEDC on IO7/IO8; the external driver stage; what must be measured on the cluster first
- [[controller-link]] — the A → B link, **protocol v2 (verified 2026-09-21)**: typed DATA/CONFIG frames on UART1 **and** ESP-NOW with dedupe, split gear fields, rpm, A-side alerts; pins (A TX = GPIO 44 → 485_A → B IO1 on the bench); the RS485-in-the-car question; v1 and the old enum drift kept for the record
- [[link-redundancy]] — wired + wireless redundancy: **ESP-NOW leg built and bench-verified** (both paths carry every frame, B dedupes and hops channels); RS485 for the car and BLE still open; failover policy notes
- [[patrol-gauge-outputs]] — Patrol tachometer (IO7, 14-bit LEDC, 4 ppr) and coolant gauge (IO8, 8-bit PWM, CANNY duty law) **outputs implemented and bench-verified**; tunables on A via `cfg` console; prior art from the CANNY program; driver stage and needle calibration still to do
## Synthesis
- [[open-questions]] — the research frontier: how the wire is really connected, which gear enum is right, which Patrol cluster, RPM field, BLE vs ESP-NOW, gauge behaviour on link loss, vehicle power, missing environmental specs
- [[open-questions]] — the research frontier: will the bare A-line wire survive the car, which Patrol cluster / tach pull-up, temp needle calibration + CANNY PWM clock, gauge behaviour on link loss, pull-the-wire failover test, BLE or not, vehicle power, environmental specs
## Sources
- [[waveshare-wiki-esp32-s3-lcd-1-3]] — Waveshare product wiki (condensed fetch 2026-09-21, not a verbatim clip); core spec, CH343, PL4054/ME6217 power, BLE 5; silent on pins and environmental limits
- [[pinout-photo-details-7]] — Waveshare annotated header photo (`raw/ESP32-S3-LCD-1.3-details-7.jpg`); the authoritative pinout, contradicts the repo's wiring guide
- [[temp-stage-cfd]] — **the user's earlier CannyLab program** for the same temp gauge (`raw/temp_stage.cfd`, decoded 2026-09-21): CAN 0x1D0 byte 0 − 48, **duty = 1.5·T + 50 on 0–255**, enable gate; PWM frequency and external circuit not in the file
+36
View File
@@ -17,3 +17,39 @@ Findings recorded during setup:
## [2026-09-21] update | .docs folder retired; root CLAUDE.md created
The repo's `.docs/` folder (14 files) was deleted (user decision). Its still-true content — verified display pins, brightness API, SquareLine export rules, CH343 serial notes, link facts — was distilled into a new root `CLAUDE.md`; the stale parts (backlight on GPIO 2/15, SPI on 10/11, native USB-CDC, the IO35–IO42 header table, the phase roadmap, the pin-hunting guides) were dropped. `UART_PROTOCOL.md` now exists only in the 5B repo at `docs/UART_PROTOCOL.md`. `README.md` repointed to `CLAUDE.md` and `wiki/`. Wiki citations that named `.docs/` files were reworded to "former … (deleted 2026-09-21)"; [[open-questions]] wishlist gained the Waveshare schematic and demo-zip URLs recovered from the old troubleshooting doc. No page content changed otherwise.
## [2026-09-21] update | Tach = 4 pulses/rev (user); coolant gauge characterisation procedure
User states the Patrol cluster's tachometer expects **4 pulses per revolution** (recorded as user-stated, not bench-verified). Clarified that the coolant gauge is a current/resistance meter with no pulse count; added a bench procedure (pot sweep for the resistance → needle curve, sender-wire voltage to tell bimetal/regulated from series coil, series current for MOSFET sizing, PWM 500 Hz–2 kHz clear of any instrument-voltage-regulator chopper, empirical °C → duty lookup, tach pull-up check and two-frequency verification) to [[patrol-gauge-outputs]]. [[open-questions]] #3 and #7 reworded accordingly.
## [2026-09-21] ingest | temp_stage.cfd — the user's old CANNY 5.3 pico temp-gauge program decoded
`raw/temp_stage.cfd` (CannyLab, proprietary binary) walked as 165 `[type][len][payload]` records; block names, constants, wiring and an Albanian comment recovered → [[temp-stage-cfd]]. Result: CAN 500k, filter 0x1D0, low byte of D1:D0 minus 48 = °C (matches the 5B's verified decode), **duty = ((T − 40)·15 + 1100)/10 = 1.5·T + 50 on a 0–255 PWM period**, output enabled above a minimum temperature, push-pull pin with PWM pull-up. Not in the file: PWM base clock and the external drive circuit. [[patrol-gauge-outputs]] gained a prior-art section and a starting LEDC law; [[open-questions]] #7 partly answered, #13 added; index updated.
## [2026-09-21] update | Calibration parameters to live on A; ESP32 as frequency meter for the CANNY
User has the CANNY unit but no scope, and wants tunable variables on the 5B for both gauges. Recorded on [[patrol-gauge-outputs]]: the proposed `gauge_calibration_t` (tach ppr/trim/clamps; temp PWM Hz, slope/offset, min-temp gate, clamp; enables; calibration override) pushed A → B in a v2 config packet, and the plan to measure the CANNY's PWM frequency/duty with a 1.3 header GPIO + pulse counter instead of a scope. Suggested order: counter sketch → v2 header → A NVS/config TX/serial tuning → B RX + LEDC → A settings UI.
## [2026-09-21] update | Frequency-counter sketch demoted to fallback
User decision: do not measure the CANNY's PWM first; implement the v2 protocol and B's LEDC outputs directly, and only feed the CANNY's PWM pin into a free 1.3 header GPIO for troubleshooting if the gauges misbehave. Coolant PWM frequency will default to 1 kHz (tunable from A) in the absence of a measurement. Proposed implementation defaults awaiting the user's go: split gear bytes (lever + target/engaged nibbles), A-side alert bitmap (coolant ≥ 100 °C, gearbox ≥ 130 °C, gearbox cooling demand, battery < 11.0 V, gear mismatch), 16-bit rpm, config packet from A's NVS via serial console first, B outputs tach IO7 / temp IO8 on separate LEDC timers, off when link down or value invalid.
## [2026-09-21] update | Bench wiring for the A→B link specified
Added a bench-wiring section to [[controller-link]]: 3.3 V RS485→TTL module on B (MAX3485/SP3485), 5B `485_A`/`485_B`/GND → module → RO to IO1, VCC from 3V3, DE/RE low; termination note (shared CAN/RS485 switch, OFF before the car); the bare-A-line shortcut flagged as unreliable; a v1 baseline check (CAN toggle ON → default packets at 5 Hz → B reports established, zero errors) to run before the v2 protocol work. Running this check answers open question #1.
## [2026-09-21] update | No RS485 module on hand — zero-parts bench options
User has no RS485→TTL module. Re-assessed the bare `485_A` → IO1 shortcut against the 5B schematic: SP3485 at 3.3 V, auto-direction drives only zeros, 4.7 kΩ bias holds A high → effectively a 3.3 V UART signal when unterminated; recorded on [[controller-link]] as the bench-only first try (unverified). Wireless leg (ESP-NOW first, BLE later) to be built alongside the v2 protocol regardless; B-as-I2C-slave noted and not pursued.
## [2026-09-21] update | Bench link VERIFIED on the bare A line; both boards reflashed
Both boards flashed from current sources (5B → COM11, 1.3 → COM10). Bench check with `485_A` → IO1 + GND, no transceiver on B, 120 Ω OFF: B reports connection established, 38 packets / 10 s, 0 checksum / 0 framing errors, valid flags 0x3F, debug flag mirrored; A logs 23-byte packets on GPIO 44 every 200 ms (UART auto-started from NVS). Open question #1 answered for the bench and re-scoped to "will it survive the car". [[controller-link]] updated. Note: opening the 5B's USB-CDC port from the PC resets the board.
## [2026-09-21] update | Protocol v2 + ESP-NOW + gauge outputs implemented and bench-verified
Implemented in both repos (not yet committed): shared header v2 (typed DATA/CONFIG frames, `gear_lever` + target/engaged nibbles, `engine_rpm`, `alerts` bitmap, `link_config_t`); A: `Tunables` (NVS + `cfg` serial console), `EspNowLink` (broadcast leg, radio held in STA), UART manager sends every frame on both paths, CAN driver publishes gear pieces + evaluates alerts; B: `UARTReceiver::processFrame()` shared by the UART framing task and the new `EspNowReceiver` (channel hopping), dedupe on packet_id, CONFIG cache in NVS, `GaugeOutputs` (tach IO7 14-bit LEDC, coolant IO8 8-bit PWM), gear label pulses while target != engaged and turns red on mismatch, icons driven by A's alert bits. Bench: 42/42/42 frames applied/uart/espnow with 42 duplicates and 0 errors; ESP-NOW locked on ch 1; CONFIG on both paths; `cfg override rpm 2000` -> 133.3 Hz on IO7; coolant 89 C -> duty 183. Two bench-found fixes: tach needs 14-bit LEDC resolution (8-bit cannot reach 100 Hz) and the shared temperature formatter must not emit a degree sign (B's font lacks the glyph). Pages updated: [[controller-link]], [[link-redundancy]], [[patrol-gauge-outputs]], [[open-questions]] (#2, #4, BLE-vs-ESP-NOW and tunables-location moved to Answered; #5/#5b reworded); index updated.
## [2026-09-21] update | Gauge Tuning touchscreen page on A; calibration procedure filed
A gained a hand-coded LVGL Gauge Tuning screen (Home → right → Driveline → right): −/+ rows for every `link_config_t` field, enable switches, and an override panel with RPM/duty sliders; changes go through `Tunables` (saved + pushed), overrides never persisted (A's NVS save strips them). Built and flashed. Step-by-step needle calibration procedure added to [[patrol-gauge-outputs]].
+42 -11
View File
@@ -15,12 +15,20 @@ BMW PT-CAN ──▶ Controller A (5B) ──UART 5 Hz──▶ Controller B (1.
Architecture rule: **B never touches CAN.** Anything B needs must be put into the packet by A. See `(sibling: 5B wiki → dual-controller-architecture)` for A's view of the same link.
## Wire-level contract (repo, both repos' `include/protocol/automotive_data.h` and `docs/UART_PROTOCOL.md` (5B repo))
## Wire-level contract — protocol v2 `(repo, 2026-09-21; spec: 5B repo docs/UART_PROTOCOL.md)`
- 115200 8N1, 3.3 V TTL, one direction A → B, 5 Hz (every 200 ms)
- Frame: `0xAA` · version `0x01` · length `0x12` · 18-byte payload · XOR checksum · `0x55` = **23 bytes**
- Payload (little-endian): `packet_id` u8 · `timestamp_ms` u32 · `gear_position` u8 · `gearbox_oil_temp` i16 (0.1 °C) · `engine_oil_temp` i16 (0.1 °C) · `coolant_temp` i16 (0.1 °C) · `battery_voltage` u16 (0.01 V) · `fault_codes` u16 bitmap · `valid_flags` u8 · `debug_enabled` u8
- B declares the link **lost after 1000 ms** without a valid packet and shows a no-data state `(repo)`; A only transmits while its CAN task is running (CAN toggle ON → UART auto-starts) `(repo)`
- One direction A → B, on **two transports at once**: UART1 115200 8N1 and **ESP-NOW broadcast** (channel 1; B hops 1–13 while silent and locks when frames arrive). B dedupes DATA frames on `packet_id` + `timestamp_ms`.
- Frame: `0xAA | version 0x02 | type | length | payload | XOR | 0x55`. Types: **DATA** (21-byte payload, every 200 ms) and **CONFIG** (27-byte payload, on start, on every tunables change, and every 5 s).
- DATA payload: `packet_id` · `timestamp_ms` · `gear_lever` (P/R/N/D/S/M) · `gear_nibbles` (target ≪ 4 | engaged) · `engine_rpm` · gearbox / engine-oil / coolant temps (0.1 °C) · `battery_voltage` (0.01 V) · `alerts` bitmap · `valid_flags` · `debug_enabled`.
- CONFIG payload = `link_config_t`: tach ppr/trim/clamps, coolant PWM Hz + duty law + min temp, enables, bench override, alert thresholds — edited on A (`cfg` serial console, NVS), executed on B ([[patrol-gauge-outputs]]).
- Alerts are decided on A from its thresholds; B only renders the bits (icons red, gear label red on mismatch).
- B declares the link **lost after 1000 ms** without an applied DATA frame on any transport and drops both gauge outputs; A transmits while its CAN task runs `(repo)`.
**Bench-verified 2026-09-21** `(verified)`: 42 frames / 10 s applied, 42 seen on UART, 42 on ESP-NOW, 42 duplicates dropped, 0 checksum / framing / version errors; ESP-NOW locked on channel 1; CONFIG frames received on both paths; `cfg override rpm 2000` typed on A's console reached B and produced a 133.3 Hz tach output within a second, and clearing it dropped the output.
### v1 for reference
23-byte single-type frame with one `gear_position` byte and a `fault_codes` word. Retired 2026-09-21; B counts any non-v2 frame as a version error.
### What each field actually carries today (sibling: 5B wiki → can-id-candidates)
@@ -29,10 +37,10 @@ Architecture rule: **B never touches CAN.** Anything B needs must be put into th
| `coolant_temp` | CAN 0x1D0 byte 0, raw − 48 | verified live |
| `gearbox_oil_temp` | CAN 0x0B5 byte 7, raw − 40 | verified live |
| `engine_oil_temp` | CAN 0x1D0 byte 1 | **dead — sensor not fitted on this M57N, reads 0xFF**; B will never get a real value |
| `gear_position` | CAN 0x1D2 lever/mode + 0x0BA target gear | verified live |
| `gear_lever` + `gear_nibbles` | CAN 0x1D2 lever/mode + byte 1 engaged gear; 0x0BA target gear | verified live; `target != engaged` = shift in progress (B pulses the digit) |
| `battery_voltage` | CAN 0x3B4, 12-bit × 0.015 V | verified live |
| `fault_codes` | A's own derived faults (bit 0 = lever vs gearbox mismatch), **not** DDE DTCs | `(repo)` |
| RPM | **not in the packet** — A has it verified from CAN 0x0AA but the protocol has no field | needed by [[patrol-gauge-outputs]] |
| `engine_rpm` | CAN 0x0AA | verified live on A; on the wire since v2 (2026-09-21) |
| `alerts` | A's thresholds (`link_config_t`) + CAN status bits | v2 |
## Pins
@@ -43,11 +51,34 @@ Architecture rule: **B never touches CAN.** Anything B needs must be put into th
> The 5B repo's root `CLAUDE.md` (corrected 2026-09-21) and this repo's former `.docs/UART_WIRING_GUIDE.md` (deleted 2026-09-21) both said "GPIO 43 TX". The 5B firmware and `docs/UART_PROTOCOL.md` (5B repo) say **44**. The code wins `(repo)`.
> [!warning] GPIO 44 on the 5B is not a bare pin — it feeds an RS485 transceiver
> On the 5B schematic, IO44 is the `RS485_TXD` net into an SP3485 with automatic direction control, and only the differential **A/B pair** reaches the terminal block `(sibling: 5B wiki → esp32-s3-touch-lcd-5b)`. Both wiring guides describe a direct "GPIO 44 → IO1 + GND" TTL wire, which the 5B does not physically expose. So either (a) the RS485 A line is being fed straight into B's TTL input and happens to work, (b) there is an RS485→TTL module on the B side that the docs don't mention, or (c) the wire is soldered to the module pin. **Which one is true is unknown** `(unverified)` and it decides how robust the wired link is in the car → [[open-questions]] #1, [[link-redundancy]].
> On the 5B schematic, IO44 is the `RS485_TXD` net into an SP3485 with automatic direction control, and only the differential **A/B pair** reaches the terminal block `(sibling: 5B wiki → esp32-s3-touch-lcd-5b)`. Both wiring guides describe a direct "GPIO 44 → IO1 + GND" TTL wire, which the 5B does not physically expose. So either (a) the RS485 A line is being fed straight into B's TTL input and happens to work, (b) there is an RS485→TTL module on the B side that the docs don't mention, or (c) the wire is soldered to the module pin. **Answered 2026-09-21: it is (a)** — the bare A line into IO1 works on the bench (verified, see bench wiring below). Whether it survives a car-length run is a separate question → [[open-questions]] #1, [[link-redundancy]].
## Protocol drift between the two repos
## Bench wiring (recommended, 2026-09-21 — unverified until run)
> [!warning] The `gear_position_t` enums differ `(repo, 2026-09-21)`
The 5B exposes UART1 only as the RS485 pair on its terminal block (`485_A`, `485_B`), so B needs a **3.3 V RS485→TTL module** (MAX3485 / SP3485; not a 5 V MAX485 without a divider on RO — ESP32 inputs are not 5 V tolerant).
| 5B terminal | → | Module | → | 1.3 left header |
|---|---|---|---|---|
| `485_A` | | A | | |
| `485_B` | | B | | |
| `GND` | | GND | | pin 2 GND |
| | | VCC | | pin 3 3V3 |
| | | RO | | pin 4 IO1 (UART1 RX) |
| | | DI / DE / RE | | unconnected, or DE+RE tied low (receive-only) |
Termination: the 5B's single 120 Ω switch serves CAN *and* RS485 — may be ON on the bench with no vehicle bus, **must be OFF before the 5B meets the car's CAN**. Desk-length runs don't care.
**Zero-parts bench alternative (no RS485 module available, 2026-09-21):** `485_A` → IO1 plus GND → GND. On the 5B schematic the SP3485 runs from 3.3 V (A can never exceed 3.3 V), the auto-direction circuit enables the driver only while sending a 0, and 4.7 kΩ bias resistors hold A high at idle — so with no 120 Ω load, A carries a plain 3.3 V UART signal with GPIO 44's polarity. **(verified on the bench 2026-09-21: 38 packets / 10 s, 0 checksum, 0 framing errors, all valid flags set; both boards on USB, 120 Ω switch OFF.)** This is almost certainly what the old wiring guide's "GPIO 44 → IO1" line described. **Bench only**: the bias pull-up will not hold up over a car-length run; the car gets a transceiver or the wireless leg. Keep the 5B's 120 Ω switch OFF for this.
Other zero-parts paths considered: ESP-NOW / BLE (the planned wireless leg, → [[link-redundancy]]) and B as an I2C slave on the 5B's I2C terminal (fiddly — A's bus is owned by the display library and shared with touch + RTC; not pursued).
Bench check before any protocol work: both boards on USB, monitors at 115200; CAN toggle ON on the 5B (its UART starts with the CAN task, no bus needed, default values at 5 Hz); B should report the connection established and packet counts rising with zero checksum/framing errors. Framing errors = A/B swapped; nothing at all = module not in receive or no common ground.
## Protocol drift between the two repos — resolved by v2
> [!note] Resolved 2026-09-21: the wire no longer carries `gear_position_t`. v2 sends `gear_lever` plus target/engaged nibbles, and the header is copied byte-identical to B (`cmp`-checked). The history below is kept for the record.
> [!warning] The `gear_position_t` enums differed `(repo, before v2)`
> - **B's header** (matches `docs/UART_PROTOCOL.md` (5B repo)): 0 P · 1 R · 2 N · 3 D · **4 Sport · 5 Manual** · 6–13 M1–M8 · 14 Error
> - **A's header** (rewritten during CAN decoding): 0 P · 1 R · 2 N · 3 D · **4–9 M1–M6** · 0xFF Unknown
>
+8 -1
View File
@@ -6,7 +6,7 @@ updated: 2026-09-21
# Link Redundancy: wired + wireless
Stated goal (user, 2026-09-21): connect B to A "through some serial or BLE, or maybe a combination of both as redundant in case the wired connection is lost." This page is the design space. **Nothing here is decided or verified** — every item is `(unverified)` unless labelled otherwise.
Stated goal (user, 2026-09-21): connect B to A "through some serial or BLE, or maybe a combination of both as redundant in case the wired connection is lost." This page is the design space. **Status 2026-09-21: ESP-NOW is implemented and bench-verified as the second transport** (see below); the RS485 question and BLE remain open. Items are `(unverified)` unless labelled otherwise.
## Why redundancy matters more once B drives gauges
@@ -21,6 +21,13 @@ Today a lost link only blanks a secondary display. Once B drives the cluster's t
| **BLE 5 GATT** (A = peripheral notifying, B = central) | both boards have BLE 5 `(source: waveshare-wiki-esp32-s3-lcd-1-3)`; connection-oriented, so B gets an explicit disconnect event; notify payload of 23 bytes fits one packet | connection setup/reconnect takes hundreds of ms to seconds; BLE stack costs RAM on both ends (NimBLE is the lighter choice on Arduino-ESP32); A's Core 0 already runs Wi-Fi scanning + CAN + UART, and Wi-Fi/BLE coexistence on one radio can add jitter | The user's stated candidate |
| **ESP-NOW** | connectionless, ~ms latency, no pairing state, trivially broadcast the same 23-byte frame; both are ESP32-S3 so it is a one-call API | Wi-Fi-based, so it shares the radio with A's Wi-Fi scanning; no link-layer "disconnected" event — liveness must come from the existing 1 s timeout | Worth benchmarking against BLE before committing; simpler failover semantics |
## What was built (2026-09-21, verified on the bench)
- A broadcasts every frame on **both** UART1 and ESP-NOW (channel 1, broadcast peer, radio held in STA mode; the WiFi manager's "off" no longer powers the radio down).
- B receives on both, hands every frame to one `processFrame()`, dedupes DATA on `packet_id` + `timestamp_ms`, and tracks per-transport liveness (`uart alive, espnow alive`). While ESP-NOW is silent B hops channels 1–13 every 400 ms and locks when frames arrive.
- Result on the desk: every frame seen on both paths, all duplicates dropped, zero errors. Pulling either path should leave the other carrying the link — **not yet tested by physically pulling the wire** `(unverified)`.
- Not built: B talking back, BLE, an on-screen indicator of which path is live (the serial stats line shows it).
## Failover design sketch
1. B keeps **one** packet consumer. Every transport (UART, BLE/ESP-NOW) feeds validated `automotive_data_t` frames into the same queue, tagged with a source id.
+14 -6
View File
@@ -10,16 +10,16 @@ The research frontier for Controller B. Answering any of these should trigger up
## Blocking
1. **How is the wired link physically connected today?** The 5B's GPIO 44 only leaves the board as an RS485 A/B pair through an SP3485, yet both wiring guides describe a direct TTL wire into IO1. Is the RS485 A line going straight into IO1, is there an RS485→TTL module on B, or is it soldered to the module? Decides whether the wired leg is trustworthy in the car and what [[link-redundancy]] has to cover. → [[controller-link]]
2. **Which `gear_position_t` enum is correct?** A's and B's protocol headers disagree on values 4–13 (Sport/Manual vs M1–M6). Check what A's CAN parser emits, fix the other side, bump `PACKET_VERSION`. → [[controller-link]]
3. **Which Nissan Patrol cluster, and what does its tach input expect** (signal source, pulses per rev, pull-up voltage)? Fixes the frequency range for the tachometer output. → [[patrol-gauge-outputs]]
1. **Will the bare `485_A` → IO1 link survive the car?** On the bench it works (verified 2026-09-21) because the SP3485's 4.7 kΩ bias holds A high when unterminated. Over a car-length harness with noise and possible termination it may not. Decide: RS485 module on B, or rely on the wireless leg → [[link-redundancy]], [[controller-link]]
3. **Which Nissan Patrol cluster, and what does its tach input expect** (signal source, pull-up voltage)? Pulses per rev stated by the user as **4** (2026-09-21), unverified on the bench. Fixes the frequency range for the tachometer output. → [[patrol-gauge-outputs]]
## Active
4. **Add `engine_rpm` to the packet.** A has RPM verified from CAN 0x0AA `(sibling: 5B wiki → can-id-candidates)` but the protocol carries no RPM field. Needed before the tachometer can be driven. → [[controller-link]]
5. **BLE GATT or ESP-NOW for the wireless leg?** Benchmark reconnect time, latency and RAM cost on A (whose Core 0 already runs Wi-Fi + CAN + UART). → [[link-redundancy]]
5. **Is ESP-NOW enough, or is BLE still wanted?** ESP-NOW is built and works on the bench. Open: behaviour when A joins a Wi-Fi AP (channel follows the AP; B hops — untested), range in the car, and whether BLE's disconnect event is worth its RAM. → [[link-redundancy]]
5b. **Pull-the-wire test.** Both transports carry every frame on the desk; physically removing the UART wire (and separately blocking the radio) to confirm seamless failover has not been done. → [[link-redundancy]]
6. **Gauge behaviour on link loss** — zero, hold + warn, or sweep to a "no data" mark? A safety/UX decision the user must make. → [[link-redundancy]]
7. **Temp sender resistance curve** as seen by the gauge, for the °C → duty lookup. → [[patrol-gauge-outputs]]
7. **Temp gauge °C → duty curve — partly answered.** The user's old CANNY program gives `duty = 1.5·T + 50` on 0–255 ([[temp-stage-cfd]]). Still needed: the old circuit's series resistor / driver and PWM frequency, and a needle check with the new MOSFET stage. Measurement procedure is on [[patrol-gauge-outputs]].
13. **CANNY 5.3 pico details**: what is the HR PWM base clock (period 255 = what frequency), and what sat between the CANNY pin and the gauge wire? The user may still have the unit and harness. → [[temp-stage-cfd]]
8. **Does `engine_oil_temp` stay in the packet?** Its CAN source reads 0xFF on this engine (sensor not fitted). B currently reserves screen space and a warning threshold for it `(repo)`. Drop it, or repurpose the slot.
## Hardware
@@ -31,6 +31,13 @@ The research frontier for Controller B. Answering any of these should trigger up
## Answered
- ~~Which `gear_position_t` enum is correct?~~ → **Moot**: protocol v2 (2026-09-21) sends lever + target/engaged nibbles; header copied byte-identical to B. → [[controller-link]]
- ~~Add `engine_rpm` to the packet.~~ → **Done in v2** (2026-09-21), `valid_flags` bit 6. → [[controller-link]]
- ~~BLE GATT or ESP-NOW for the wireless leg?~~ → **ESP-NOW first**, implemented and bench-verified 2026-09-21; BLE stays optional (#5). → [[link-redundancy]]
- ~~Where do the gauge tunables live?~~ → **On A** (`Tunables`, NVS, `cfg` console), pushed to B in CONFIG frames, cached on B (verified 2026-09-21). → [[patrol-gauge-outputs]]
- ~~How is the wired link physically connected today?~~ → **Bare `485_A` straight into IO1, common GND, no transceiver on B.** Bench-verified 2026-09-21: 0 errors at 5 Hz. Works because of the 5B's SP3485 bias resistors; bench-only until proven in the car (now #1). → [[controller-link]]
- ~~Does the 1.3 have free PWM-capable GPIO?~~ → **Yes, 13 on the headers** (IO1–5, IO7–14), 10 fully free today. (verified from pinout photo, 2026-09-21) → [[esp32-s3-lcd-1-3]]
- ~~Could the 5B drive the gauges itself?~~ → **No.** All native GPIO consumed; its DO terminals go through an I2C expander + optocoupler and cannot carry hardware PWM. (schematic reviewed 2026-09-21) → [[patrol-gauge-outputs]]
- ~~Which GPIO does A transmit on?~~ → **GPIO 44** per A's firmware; the "43" in two docs is stale. `(repo)` → [[controller-link]]
@@ -43,3 +50,4 @@ The research frontier for Controller B. Answering any of these should trigger up
- Nissan Patrol **cluster wiring diagram** for the target generation — tach input and temp sender pins
- Scope capture of the original Patrol tach signal at idle and a known RPM, if the original engine's cluster wiring still exists
- Datasheet or Waveshare note on the board's operating temperature range
- CANNY 5.3 pico datasheet / CannyLab HR PWM documentation (PWM clock, output stage), or a scope trace of the old unit's output
+71 -6
View File
@@ -16,15 +16,18 @@ Controller A (5B) has no free native GPIO on any header: the RGB LCD, I2C, CAN,
| Gauge | What the cluster expects | What B must generate | Status |
|---|---|---|---|
| Tachometer | a pulse train whose **frequency** tracks engine speed; the source and pulses-per-revolution depend on the cluster variant | variable-frequency square wave at ~50 % duty, on one LEDC channel with its **own timer** | source data (RPM from CAN 0x0AA) verified on A `(sibling: 5B wiki → can-id-candidates)`; **not yet in the packet** |
| Tachometer | a pulse train whose **frequency** tracks engine speed — **4 pulses per revolution** on this cluster (user, 2026-09-21; not yet bench-verified) | variable-frequency square wave at ~50 % duty, on one LEDC channel with its **own timer** | source data (RPM from CAN 0x0AA) verified on A `(sibling: 5B wiki → can-id-candidates)`; **not yet in the packet** |
| Coolant temp | a moving-coil/bimetal gauge that reads the **resistance to ground** of the sender | fixed-frequency PWM with variable **duty** into a low-side switch, so the gauge integrates it as an average resistance | coolant already in the packet as 0.1 °C |
The two need separate LEDC timers because one varies frequency and the other varies duty. ESP32-S3 LEDC has 8 channels on 4 timers `(unverified — datasheet figure from memory, confirm)`.
## Proposed pin assignment (unverified — proposal only)
## Pin assignment (implemented 2026-09-21)
- **IO7** → tachometer pulse output
- **IO8** → coolant gauge PWM output
- **IO7** → tachometer pulse output — LEDC channel 2 (timer 1), **14-bit** resolution so the divider reaches low frequencies (~4.8 Hz .. ~4.9 kHz; 8-bit could not even do 100 Hz), 50 % duty
- **IO8** → coolant gauge PWM output — LEDC channel 4 (timer 2), 8-bit duty at `temp_pwm_hz` (default 1 kHz)
- LEDC channels 0/1 (timer 0) belong to the display backlight; never reuse them `(repo)`
**Bench-verified 2026-09-21** `(verified)`: with A's default 89 °C coolant, B drives IO8 at duty 183/255 (1.5·89 + 50); `cfg override rpm 2000` on A's console produced 133.3 Hz on IO7 (2000 × 4 / 60), and clearing it dropped the output. Both outputs stay low with no link or no valid value. Still unverified: the **needle** — nothing is connected to the cluster yet and the external driver stage does not exist.
Both on the right header, adjacent to GND-free pins, so add a ground wire from the left header. IO3 deliberately avoided (strapping pin). IO1 stays the UART RX.
@@ -36,11 +39,73 @@ Both on the right header, adjacent to GND-free pins, so add a ground wire from t
- **Temp gauge**: sender wire goes to ground through the sender's thermistor. Emulate it with a logic-level N-MOSFET (or NPN) pulling the sender wire to ground under PWM, plus a series resistor sized so 100 % duty corresponds to the hottest resistance you want to show. The gauge's thermal/mechanical lag averages the PWM; use a few hundred Hz to 1 kHz so nothing flickers. Calibration is a lookup table from °C → duty, built empirically against the needle.
- Optocouplers between B and the 12 V cluster side are cheap insurance; the 5B's own DO stage (PC817 → transistor) is a reasonable pattern to copy.
## Characterising the gauges (procedure, unverified until run)
The coolant gauge is a **current meter, not a pulse input** — there is no pulse count to find. The sender is a thermistor to ground; the needle follows the current through the gauge coil, which follows the sender's resistance. What has to be measured is the resistance → needle curve.
Coolant gauge, ignition on, engine off, sender disconnected:
1. 1 kΩ linear pot (or decade box, or fixed 47/100/220/470 Ω) from the sender wire to chassis ground. Sweep; record the resistance at the cold mark, middle, hot mark and start of the red zone (read the pot disconnected).
2. At each point also record the sender-wire voltage. Constant regardless of resistance → regulated supply, bimetal gauge. Proportional drop → plain series coil.
3. Needle lag of seconds → bimetal; near-instant → air core. Both average PWM; bimetal is more forgiving.
4. Series current at the hot-mark resistance = the peak the MOSFET stage must sink (expect tens of mA).
PWM drive from the curve:
- Logic-level N-MOSFET low side, drain to the sender wire through a fixed resistor equal to the hottest resistance ever to be shown; 100 % duty = hottest reading, the gauge integrates lower duties.
- 500 Hz – 2 kHz. Older Nissan clusters feed gauges from a chopped instrument voltage regulator at a few Hz `(unverified)`; PWM near that rate beats against it. Scope the sender wire once to see whether the chopper exists.
- Build the °C → duty lookup from where the needle actually lands at each duty step, not from any sender datasheet.
Tachometer, 4 ppr: f = rpm × 4 / 60 → ~47 Hz at 700 rpm, ~267 Hz at 4000 rpm. Before wiring: measure the tach input's open-circuit voltage with ignition on — battery voltage means the cluster has its own pull-up (open-collector output suffices); near zero means add a pull-up to 12 V. Verify the needle at two known LEDC frequencies before trusting the scaling.
## Prior art: the user's CANNY 5.3 pico program (source: temp-stage-cfd)
The user drove this gauge before, from the BMW CAN bus, with a CannyLab program → [[temp-stage-cfd]]. Recovered from the file:
- Same decode the 5B later verified: CAN 0x1D0 byte 0, raw − 48 °C.
- **Duty = 1.5 × T + 50 on a 0–255 scale**, i.e. 110/255 at 40 °C, 200/255 at 100 °C, saturating near 137 °C. Duty *rises* with temperature (NTC sender emulation).
- Output only enabled above a minimum temperature (constant 0 in the file, 40 °C in the comment).
- Output was the controller's own push-pull pin with PWM pull-up enabled; the external circuit and the PWM frequency are **not** in the file.
Starting point for the LEDC implementation: 8-bit duty, `duty = clamp(1.5·T + 50, 0, 255)`, output disabled while the coolant value is invalid or the link is down. Verify against the needle before trusting it — the old drive circuit may differ from the new MOSFET stage, which shifts the whole curve.
## Tuning parameters — declared on A, executed on B (implemented 2026-09-21)
Calibration lives on Controller A (NVS; the **Gauge Tuning touchscreen page** — Home → right → Driveline → right — or the `cfg` serial console) and is pushed to B in CONFIG frames; B executes and caches the last config in its own NVS. `link_config_t` in the shared protocol header:
| Group | Parameter | Default | Note |
|---|---|---|---|
| Tach | pulses per rev | 4 | user figure |
| Tach | fine trim % | 0 | needle reads N % off at a known rpm |
| Tach | min / max output Hz | tbd | clamp against bad rpm values |
| Temp | PWM frequency Hz | **unknown** | from the CANNY measurement ([[temp-stage-cfd]]) |
| Temp | duty slope, offset (fixed-point) | 1.5, 50 | from the CANNY law |
| Temp | min temperature gate °C | 40 | output off below |
| Temp | duty clamp | 255 | |
| Both | output enable | on | per gauge |
| Both | **calibration override** | off | force a fixed rpm / fixed duty from A's screen and watch the needle |
Transport: CONFIG frames in protocol v2, sent on start, on every change (`cfg_version` bump) and every 5 s; overrides are pushed but never saved on either side. Console: `cfg show`, `cfg set <name> <value>`, `cfg override rpm <n> | duty <n> | both <rpm> <duty> | off`, `cfg reset` → [[controller-link]].
Measuring the CANNY's PWM without a scope: use a free 1.3 header GPIO with the ESP32 pulse-counter peripheral as a frequency/duty meter (resistor divider if the CANNY output exceeds 3.3 V). Same sketch later verifies B's own outputs. Planned as a separate PlatformIO environment in this repo.
## Calibration procedure (touchscreen or console)
Tachometer, with the driver stage on the tach wire:
1. Force 1000 rpm (override). The needle should read 1000.
2. A constant-factor error means the wrong pulses/rev — change it until 1000 reads 1000.
3. Force 3000 rpm; a small residual is the trim (%).
4. Override off.
Coolant gauge, with the MOSFET stage on the sender wire:
1. Force duty 110 (the CANNY program's 40 °C point) and note the needle; sweep 140 / 170 / 200 / 230.
2. From two marks (Tc at duty A, Th at duty B): slope = (B − A)/(Th − Tc), offset = A − slope × Tc; enter slope × 100 and offset.
3. Needle flicker or wander → raise PWM frequency. No response at all → driver stage / pull-up, not the numbers.
4. Override off. Values are saved on A and pushed to B at once.
## What must be established before any of this is wired
1. **Which Patrol cluster** (Y60/Y61, petrol vs diesel). Diesel clusters were fed from the alternator W-terminal at a much higher frequency and often have a calibration trimmer; petrol clusters expect ~3 pulses/rev for a 6-cylinder from the ignition system `(unverified)`. This fixes the frequency range and therefore the LEDC resolution/prescaler. → [[open-questions]]
1. **Which Patrol cluster** (Y60/Y61, petrol vs diesel). User states **4 pulses/rev** (2026-09-21); confirm on the bench with the procedure above, since diesel clusters fed from an alternator W-terminal and petrol clusters fed from ignition differ `(unverified)`. This fixes the frequency range and therefore the LEDC resolution/prescaler. → [[open-questions]]
2. Whether the cluster's tach input has an internal pull-up, and to what voltage (meter it).
3. The temp sender's resistance-vs-temperature curve as the gauge sees it (meter the original sender at cold/hot, or sweep a pot until the needle sits at known marks).
3. The temp sender's resistance-vs-temperature curve as the gauge sees it (meter the original sender at cold/hot, or sweep a pot until the needle sits at known marks). The CANNY-era duty law in [[temp-stage-cfd]] is the starting table; it still needs a needle check with the new driver stage, plus the old circuit's series resistor and PWM frequency.
4. Protocol change: add `engine_rpm` (u16, 1/min) and a `valid_flags` bit to the packet; bump the version on both repos → [[controller-link]].
5. The outage policy: what the needles do when the link is lost → [[link-redundancy]].
Binary file not shown.
+76
View File
@@ -0,0 +1,76 @@
---
type: source
tags: [gauges, cannylab, canny, pwm, calibration, prior-art]
updated: 2026-09-21
raw: raw/temp_stage.cfd
---
# `temp_stage.cfd` — the user's earlier CannyLab program for the Patrol temp gauge
CannyLab project ("CANNY FUNCTIONAL DIAGRAM FILE", file-format version fields 12 / 2) written by the user some years ago for a **CANNY 5.3 pico** controller, to drive the Nissan Patrol coolant gauge from the BMW engine's CAN bus. Dropped into `raw/` 2026-09-21; file dated 2026-06-04. **This is direct prior art for [[patrol-gauge-outputs]]**: the same job the 1.3 board is about to take over.
## How it was read
The format is a proprietary binary, not documented anywhere I know of. It walks as a flat list of `[u32 type][u32 length][payload]` records — 165 of them, ending exactly at a 16-byte trailer (hash). Block names, port names, constants and a free-text comment are stored in clear. Function-block opcodes are numeric; their meaning below is **inferred** from the wiring, the constants and the comment, which agree with each other everywhere. Two diagram pages: page 1 = hardware configuration, page 2 = "Temperatura Gauge" (the logic).
## Page 1 — hardware configuration (read verbatim from the file)
| Block | Setting |
|---|---|
| CAN Mode | `CAN 500k` |
| CAN RX IDL (receive ID filter) | constant **0x1D0** |
| CAN RX data | `CAN RX D1:D0` (16-bit word, bytes 1:0) |
| DIO Mode IO Channel 1 | `OUTPUT; VDD/gnd` (push-pull) |
| HR PWM Period | constant **255** |
| HR PWM 1 | Duty / Enable / Pull-up driven from page 2 |
| UART1, UART2 Mode | `UART RX/TX 9600-8-N-1-PU`, TX LEN 1 — not used by the logic |
## Page 2 — the logic (inferred; every constant and the comment match)
```
CAN Data Received ─┐
AND ──▶ latch(D1:D0) ──▶ take low byte (D0) ──▶ − 48 ──▶ T ("tmp aktuale")
CAN RX IDL == 0x1D0 ┘
Duty = ((T − 40) × 15 + 1100) / 10 (integer arithmetic, constants 40, 15, 1100, 10)
Enable = Pull-up = (T > tmp_min) tmp_min constant = 0 in this file
HR PWM 1 Duty = Enable ? Duty : 0
```
The comment box (Albanian, translated): *"Calculation: D = ((T − RT) × 15 + 1100) / 10. a: D = Duty. b: T = temperature coming from the ECU. c: RT = reference temperature (40 °C). d: 15 → 1.5 (coefficient per degree) × 10. e: 1100 → 110 (duty at 40 °C) × 10. f: everything divided by 10. Note: if temp is not 40, do not activate any function."*
Simplified: **Duty = 1.5 × T + 50**, on a **0–255** period. Points:
| T °C | Duty /255 | % |
|---|---|---|
| 40 | 110 | 43 |
| 60 | 140 | 55 |
| 80 | 170 | 67 |
| 90 | 185 | 73 |
| 100 | 200 | 78 |
| 110 | 215 | 84 |
| 120 | 230 | 90 |
| ≈137 | 255 | 100 (saturates) |
## What this establishes
- The **CAN decode is the same one the 5B verified** in 2026: ID 0x1D0, byte 0, raw − 48 °C `(sibling: 5B wiki → can-id-candidates)`. Independent confirmation from a working installation years earlier.
- The gauge was driven by **PWM duty rising with temperature**, linearly, with a non-zero floor at 40 °C. Consistent with emulating an NTC sender (resistance falls as temperature rises) through a switch and series resistor.
- The output was the CANNY's own IO channel 1 in push-pull mode with the PWM pull-up enabled — i.e. the gauge line was driven (or a driver stage was fed) directly from the controller pin `(source: file; external circuit unknown)`.
- The linear duty law means the gauge + drive circuit behaved close to linear in duty over 40–120 °C, or the user accepted a linear approximation. Either way this is the °C → duty table to start from.
## What it does NOT tell us
- The **PWM frequency**: "HR PWM Period = 255" is in CANNY timer ticks of an unknown base clock `(unverified)`. Look up the CANNY 5.3 pico HR PWM clock, or scope the old unit.
- The **external circuit** between the CANNY pin and the gauge sender wire (series resistor value, any transistor). Ask the user / inspect the old harness.
- Whether the cluster is the same one the 1.3 board will drive (assumed yes).
- Why `tmp_min` is 0 while the comment says 40: either edited later or the gate was relaxed. With 0 the output is enabled for any positive temperature.
## Relevance
- Answers most of [[open-questions]] #7 (temp gauge curve) — as a starting table, pending a bench check on the actual needle.
- Sets the initial LEDC design for [[patrol-gauge-outputs]]: 8-bit duty, `duty = 1.5·T + 50` clamped to 0–255, output enabled only with a valid temperature.
## Related
[[patrol-gauge-outputs]] · [[controller-link]] · [[open-questions]]