Diff-lock inputs: DI0 rear / DI1 front via CH422G EXIO0/EXIO5 (bank flipped to input per read), Settings > System switch default OFF, DIFF LOCK pills on the Driveline, 'difflock' console; wiki diff-lock-inputs
Firmware / build (push) Successful in 7m26s

This commit is contained in:
2026-09-29 09:48:57 +02:00
parent f07590bbc5
commit 31ca44187e
13 changed files with 362 additions and 10 deletions
+7 -2
View File
@@ -88,6 +88,7 @@ src/
ota_update.cpp # Manual firmware updates from Gitea releases ('ota' console)
link_peer.cpp # Inst. Cluster over the link: its STATUS frames, 'link pair' (key over the wire), encrypted credential handoff, B's updates ('link' console)
status_overlay.cpp # lv_layer_top() on EVERY screen: Wi-Fi chip top-right, blinking red / steady amber alert banner top-centre
diff_locks.cpp # Diff-lock inputs DI0 rear / DI1 front via CH422G EXIO0/EXIO5 ('difflock' console, Settings switch, default OFF)
settings_manager.cpp # NVS persistent storage
ui_state_manager.cpp # Debug flag (performance overlay, sent to B)
display_init.cpp # Display initialization; boots into DrivelineScreen
@@ -143,7 +144,7 @@ include/
Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
- Namespace: "settings"
- Keys: `wifi_en`, `uart_en`, `can_en`, `debug_en` (boolean values)
- Keys: `wifi_en`, `uart_en`, `can_en`, `debug_en`, `difflock_en` (boolean values)
- Functions: `saveWiFiState()`, `loadWiFiState()`, `saveUARTState()`, `loadUARTState()`, `saveCANState()`, `loadCANState()`, `saveDebugState()`, `loadDebugState()`
- Namespace "wifi": `ssid`, `pass` - the one remembered network (`WiFiManager`); the password is never printed
@@ -231,12 +232,16 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
`src/modules/link_peer.cpp` keeps B's last `STATUS` frame (version, update phase, progress, flags; "not heard" after 15 s), owns the pairing key (NVS `linkpeer`) and drives B's updater. `link pair` generates a 32-byte key and sends it **three times over UART1 only** (`UARTManager::sendWire()`, never ESP-NOW - both repos are public, this is the one secret); B confirms with `key_fp` in its next STATUS. `tick()` pushes the remembered Wi-Fi network to B in an encrypted `SECURE` frame whenever B lacks it or it changed (hash-compared, ≥ 15 s apart; `WiFiManager::getSavedCredentials()` exists for this alone - never print the password), and a FORGET when A forgets its network. `requestCheck()` / `requestInstall()` (Settings → Updates, Inst. Cluster card) require: B heard, paired with *this* key, B has credentials, B not busy, A on Wi-Fi (same AP as B ⇒ same channel ⇒ progress frames arrive), and for install `Ota::isParked()`. Console: `link status | pair | unpair | creds | ota check | ota install [force] | ota rollback`. Design + procedure: B's wiki `controller-b-ota`.
### Diff-lock inputs (`difflock` console)
`src/modules/diff_locks.cpp` reads the Patrol's two diff-lock signals (+12 V = locked) on the isolated inputs: DI0 = rear, DI1 = front, `DI_COM` to vehicle ground. The PC814 outputs reach the ESP32 only through the CH422G (DI0 = EXIO0, DI1 = EXIO5, active LOW), and the CH422G's IO0-7 are one bank, all in or all out - the same bank drives touch reset (EXIO1), backlight (EXIO2) and LCD reset (EXIO3). Each poll (4 Hz, under the LVGL lock so no touch read shares the bus) writes WR_SET input (0x24 <- 0x00), reads 0x26, and writes output back (0x01), restore retried; the chip keeps its output latch. Raw I2C on host 0 (legacy driver, as the panel library), never the library's `enableAllIO_Input()` (it sleeps 2 ms with the bank floating). A state counts after two equal reads. Behind the Settings → System switch, default OFF, so a board without the wiring never flips the bank. Driveline shows `DIFF LOCK [REAR] [FRONT]` top-right (amber = locked, FRONT red if it reads locked without REAR, hidden when off); the System row's sub-line shows the live state for testing. Wiring and evidence: wiki `diff-lock-inputs`.
### Screens
All hand-coded in `src/modules`, built once and kept (never deleted - the old generated screens were deleted on leave, which left dangling pointers and caused the 2026-09-27 freezes). Shared look in `ui_kit.cpp` (20/24 px text, >= 56 px touch targets, no shadows/animations, `UiKit::confirm()` modal dialog). Each screen has a `tick()` called from `loop()` that refreshes values under the LVGL lock, only while it is shown, and only re-sets label text that changed.
- **Driveline** (boot) - swipe left: Settings, swipe right: Gauge Tuning
- **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (two cards: Main CTRL -> `Ota::requestCheck/requestInstall`, Inst. Cluster -> `LinkPeer::requestCheck/requestInstall`; each Installed / Latest / status line / Check / Install behind a confirm dialog; must fit 484 px, pages don't scroll), **System** (CAN / link to B / performance overlay switches, live ESP-NOW, CAN, memory, uptime). Swipe right or the Driveline button goes back
- **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (two cards: Main CTRL -> `Ota::requestCheck/requestInstall`, Inst. Cluster -> `LinkPeer::requestCheck/requestInstall`; each Installed / Latest / status line / Check / Install behind a confirm dialog; must fit 484 px, pages don't scroll), **System** (CAN / link to B / performance overlay / diff-lock input switches, live ESP-NOW, CAN, memory, uptime on the firmware line - the page is full at four rows). Swipe right or the Driveline button goes back
- **Gauge Tuning** (`tuning_screen.cpp`) - tabs Tachometer / Coolant gauge / Alerts / Simulation; -/+ rows with hints (hold to repeat, speeds up), per-tab Reset with confirm, "Saving... / All changes saved" footer, SIMULATION ON chip while an override is active. Swipe left or the Driveline button goes back
- Screen switches are instant (`LV_SCR_LOAD_ANIM_NONE`): full-screen fades are software-blended every frame and stutter at 1024x600. The firmware version is a label on `lv_layer_top()` (bottom-right, every screen, `DisplayInit`)
- **StatusOverlay** (2026-09-27, `status_overlay.cpp`, also on `lv_layer_top()`): a 150 px Wi-Fi chip top-right (off / not connected / joining / network name) and an alert banner top-centre that blinks red at 2 Hz while any red alert bit is set (coolant hot, gearbox oil hot, gear mismatch, battery low - text names the value) and is steady amber for gearbox cooling; hidden with CAN or ignition off. The top ~56 px of every screen belong to it: `UiKit::header()` puts the back button at x -176, the Driveline chips start at y 60. On the Driveline the crossed value AND its title go red (amber for cooling) and a gear mismatch turns the hero ring + letter red (the old top-right mismatch label is gone). Blinking is a colour toggle from `tick()` every 500 ms, not an lv_anim (a 1024-wide banner animated per frame would cost real render time)
+7
View File
@@ -132,6 +132,13 @@ diag raw on | off CANRAW frame logging
diag status
```
### `difflock` — diff-lock inputs (DI0 = rear, DI1 = front; Settings → System switch, default OFF)
```
difflock status rear / front LOCKED or open, raw CH422G IO byte, read counters
difflock on | off same as the switch (saved)
```
Wiring: lock wire (+12 V when locked) → DI0 / DI1, `DI_COM` → vehicle ground. Details: wiki `diff-lock-inputs`.
### Diagnostics
```
mem internal heap, PSRAM, LVGL pool
+6 -2
View File
@@ -19,6 +19,7 @@
#include "modules/ota_update.h" // Manual firmware updates from Gitea releases (`ota` console)
#include "modules/link_peer.h" // Inst. Cluster status, pairing, credential handoff, B updates (`link` console)
#include "modules/status_overlay.h" // Every screen: Wi-Fi chip top-right, blinking alert banner top-centre
#include "modules/diff_locks.h" // Diff-lock inputs DI0 rear / DI1 front via the CH422G (`difflock` console)
// ============================================================================
// MINIMAL LVGL + UI SETTINGS + WIFI + UART
@@ -57,11 +58,12 @@ static bool memCommand(const char* line) {
return true;
}
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi, mem.
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi, mem, link, difflock.
static bool consoleExtraCommand(const char* line) {
return DiagProbe::handleCommand(line) || Ota::handleCommand(line) ||
WiFiManager::handleCommand(line) || memCommand(line) ||
PerfMon::handleCommand(line) || LinkPeer::handleCommand(line);
PerfMon::handleCommand(line) || LinkPeer::handleCommand(line) ||
DiffLocks::handleCommand(line);
}
// ============================================================================
@@ -107,6 +109,7 @@ void setup()
bool saved_uart_state = SettingsManager::loadUARTState();
bool saved_can_state = SettingsManager::loadCANState();
bool saved_debug_state = SettingsManager::loadDebugState();
DiffLocks::init(SettingsManager::loadDiffLockState()); // CH422G bus is up since DisplayInit
ESP_LOGI("MAIN", "Saved states loaded (UI will be updated when Settings screen opens)");
// Initialize UI State Manager
@@ -165,6 +168,7 @@ void loop()
DiagProbe::tick();
Ota::tick(); // confirms a freshly installed image after healthy uptime
LinkPeer::tick(); // Inst. Cluster heard/lost, credential sync
DiffLocks::tick(); // DI0/DI1 at 4 Hz, only when the Settings switch is on
DrivelineScreen::tick();
TuningScreen::tick();
+149
View File
@@ -0,0 +1,149 @@
/*
* Differential lock inputs - see diff_locks.h
*
* Schematic (V1.2, sheet 1): DINx -> PC814 LED -> 3.6 kOhm -> DI_COM. The
* optocoupler's transistor pulls DIx (4.7 kOhm to 3V3) LOW while current flows,
* so a LOCKED diff reads 0 on its EXIO bit. The PC814 LED is bidirectional:
* +12 V on DINx with DI_COM on ground is the "PNP / high-level" wiring.
*/
#include "diff_locks.h"
#include "settings_manager.h"
#include "serial_lock.h"
#include "display/lvgl_v8_port.h"
#include <driver/i2c.h>
#include <stdarg.h>
namespace DiffLocks {
// CH422G on the panel library's I2C host 0. Its "registers" are I2C addresses.
static const i2c_port_t CH422G_PORT = I2C_NUM_0;
static const uint8_t ADDR_WR_SET = 0x24; // system parameter byte
static const uint8_t ADDR_RD_IO = 0x26; // IO0-7 pin levels
// WR_SET as the board config leaves it (ESP_PANEL_BOARD_EXPANDER_POST_BEGIN_FUNCTION:
// enableAllIO_Output -> IO_OE only; OC push-pull, no sleep). Input = IO_OE cleared.
static const uint8_t WR_SET_OUTPUT = 0x01;
static const uint8_t WR_SET_INPUT = 0x00;
static const uint8_t BIT_REAR = 1 << 0; // DI0 = EXIO0
static const uint8_t BIT_FRONT = 1 << 5; // DI1 = EXIO5
static const uint32_t POLL_MS = 250;
static const uint8_t FAULT_AFTER = 3; // failed reads in a row
static bool g_enabled = false;
static bool g_rear = false, g_front = false; // debounced
static bool g_have_state = false;
static uint8_t g_last_raw = 0xFF;
static bool g_have_raw = false;
static uint8_t g_fail_run = 0;
static uint32_t g_reads = 0, g_fails = 0;
static uint32_t g_last_poll = 0;
static void print(const char* fmt, ...) {
char buf[160];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
static esp_err_t writeSet(uint8_t v) {
return i2c_master_write_to_device(CH422G_PORT, ADDR_WR_SET, &v, 1, pdMS_TO_TICKS(10));
}
/**
* One raw read of IO0-7. The bank is an input only between the two WR_SET
* writes (three short I2C transactions); the output is restored even when the
* read fails, and retried, because touch reset, backlight and LCD reset live on
* the same bank. The caller holds the LVGL lock, so no touch read (same bus)
* can land in the middle.
*/
static bool readBank(uint8_t* out) {
if (writeSet(WR_SET_INPUT) != ESP_OK) {
writeSet(WR_SET_OUTPUT); // a half-done write: make sure we are back
return false;
}
esp_err_t r = i2c_master_read_from_device(CH422G_PORT, ADDR_RD_IO, out, 1, pdMS_TO_TICKS(10));
for (int i = 0; i < 3 && writeSet(WR_SET_OUTPUT) != ESP_OK; i++) {}
return r == ESP_OK;
}
void init(bool enabled) {
g_enabled = enabled;
print("[difflock] %s (DI0 = rear, DI1 = front)", enabled ? "ON" : "OFF - Settings > System to enable");
}
void setEnabled(bool enabled) {
if (enabled == g_enabled) return;
g_enabled = enabled;
g_have_state = g_have_raw = false;
g_rear = g_front = false;
g_fail_run = 0;
SettingsManager::saveDiffLockState(enabled);
}
bool isEnabled() { return g_enabled; }
bool isValid() { return g_enabled && g_have_state && g_fail_run < FAULT_AFTER; }
bool rearLocked() { return isValid() && g_rear; }
bool frontLocked() { return isValid() && g_front; }
void tick() {
if (!g_enabled || millis() - g_last_poll < POLL_MS) return;
g_last_poll = millis();
if (!lvgl_port_lock(100)) return; // UI busy: try again next poll
uint8_t raw = 0xFF;
bool ok = readBank(&raw);
lvgl_port_unlock();
g_reads++;
if (!ok) {
g_fails++;
if (g_fail_run < 255) g_fail_run++;
if (g_fail_run == FAULT_AFTER) print("[difflock] CH422G read failing - lock states unknown");
return;
}
g_fail_run = 0;
// Accept a state only when two reads in a row agree (<= 0.5 s latency).
uint8_t bits = raw & (BIT_REAR | BIT_FRONT);
if (g_have_raw && bits == (g_last_raw & (BIT_REAR | BIT_FRONT))) {
bool rear = !(bits & BIT_REAR); // opto conducting = pin low = locked
bool front = !(bits & BIT_FRONT);
if (!g_have_state || rear != g_rear || front != g_front) {
g_rear = rear;
g_front = front;
g_have_state = true;
print("[difflock] rear %s, front %s%s", rear ? "LOCKED" : "open", front ? "LOCKED" : "open",
(front && !rear) ? " (front without rear - check the DI0 wiring)" : "");
}
}
g_last_raw = raw;
g_have_raw = true;
}
bool handleCommand(const char* line) {
if (strncmp(line, "difflock", 8) != 0 || (line[8] != 0 && line[8] != ' ')) return false;
const char* a = line + 8;
while (*a == ' ') a++;
if (!strcmp(a, "on")) { setEnabled(true); print("[difflock] ON (saved)"); return true; }
if (!strcmp(a, "off")) { setEnabled(false); print("[difflock] OFF (saved)"); return true; }
if (!*a || !strcmp(a, "status")) {
if (!g_enabled) { print("[difflock] OFF - inputs not read ('difflock on' or Settings > System)"); return true; }
print("[difflock] rear %s, front %s | raw IO0-7 0x%02X | %lu reads, %lu failed%s",
!isValid() ? "?" : g_rear ? "LOCKED" : "open",
!isValid() ? "?" : g_front ? "LOCKED" : "open",
g_last_raw, (unsigned long)g_reads, (unsigned long)g_fails,
g_fail_run >= FAULT_AFTER ? " | READ FAULT" : "");
return true;
}
print("[difflock] usage: difflock status | on | off (DI0 = rear, DI1 = front, 12 V = locked)");
return true;
}
} // namespace DiffLocks
+38
View File
@@ -0,0 +1,38 @@
/*
* Differential lock inputs - DI0 = rear, DI1 = front
*
* The Patrol's lock switches put +12 V on a wire while a diff is locked. Those
* wires go to the board's isolated inputs (PC814 optocouplers, 5-36 V, DI_COM to
* vehicle ground). The inputs reach the ESP32 only through the CH422G expander
* (DI0 = EXIO0, DI1 = EXIO5), whose IO0-7 are all-in or all-out as ONE bank - and
* the same bank drives touch reset, backlight enable and LCD reset. So each read
* switches the bank to input for ~0.1 ms and straight back (output latches are
* kept by the chip). That is why the whole feature sits behind a Settings switch,
* default OFF: a board without diff-lock wiring never touches the bank.
*/
#pragma once
#include <Arduino.h>
namespace DiffLocks {
/** Call once after DisplayInit (the CH422G's I2C bus is installed by the panel library). */
void init(bool enabled);
/** Settings switch / `difflock on|off`. Saved to NVS (SettingsManager). */
void setEnabled(bool enabled);
bool isEnabled();
/** Poll the inputs (4 Hz, debounced over two reads). Call from loop(). */
void tick();
/** Enabled AND the last reads succeeded - otherwise the lock states mean nothing. */
bool isValid();
bool rearLocked();
bool frontLocked();
/** `difflock status | on | off`. Returns true if the line was ours. */
bool handleCommand(const char* line);
} // namespace DiffLocks
+60
View File
@@ -9,6 +9,7 @@
#include "drivers/can_driver.h"
#include "tuning_screen.h"
#include "settings_screen.h"
#include "diff_locks.h"
#include "esp_log.h"
namespace DrivelineScreen {
@@ -49,6 +50,9 @@ static lv_obj_t* g_ign_chip = NULL;
static lv_obj_t* g_eng_chip = NULL;
static lv_obj_t* g_clutch_chip = NULL;
static lv_obj_t* g_cool_chip = NULL;
static lv_obj_t* g_diff_box = NULL; // top-right: DIFF LOCK [REAR] [FRONT]
static lv_obj_t* g_rear_pill = NULL;
static lv_obj_t* g_front_pill = NULL;
// ============================================================================
// PRIVATE HELPERS
@@ -111,6 +115,38 @@ static void setChip(lv_obj_t* chip, const char* text, lv_color_t colour) {
}
}
/** A diff-lock pill: text, fill and text colour, each written only on change. */
static void setPill(lv_obj_t* pill, const char* text, lv_color_t bg, lv_color_t fg) {
setText(pill, text);
if (lv_color_to32(lv_obj_get_style_bg_color(pill, 0)) != lv_color_to32(bg)) {
lv_obj_set_style_bg_color(pill, bg, 0);
}
setColour(pill, fg);
}
/**
* @brief Diff locks, from the isolated inputs (not CAN - shown with CAN off too).
* Locked = amber tell-tale. The front can only lock after the rear, so
* FRONT without REAR is a wiring/switch fault and shows red.
*/
static void refreshDiffLocks() {
bool on = DiffLocks::isEnabled();
if (lv_obj_has_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN) == on) {
if (on) lv_obj_clear_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN);
}
if (!on) return;
if (!DiffLocks::isValid()) {
setPill(g_rear_pill, "REAR ?", COL_PANEL, COL_MUTED);
setPill(g_front_pill, "FRONT ?", COL_PANEL, COL_MUTED);
return;
}
bool rear = DiffLocks::rearLocked(), front = DiffLocks::frontLocked();
setPill(g_rear_pill, "REAR", rear ? COL_AMBER : COL_PANEL, rear ? COL_BG : COL_MUTED);
if (front && !rear) setPill(g_front_pill, "FRONT", COL_ALERT, COL_TEXT);
else setPill(g_front_pill, "FRONT", front ? COL_AMBER : COL_PANEL, front ? COL_BG : COL_MUTED);
}
/**
* @brief Compose the hero gear label from the 0x1D2 pieces.
*
@@ -212,6 +248,28 @@ static void build() {
g_cool_chip = makeChip(bar, "COOLING --");
// Gear mismatch: the ring and the gear letter turn red, and the overlay banner says so.
// ---- diff locks, top-right under the overlay's Wi-Fi chip (hidden until enabled)
g_diff_box = lv_obj_create(g_screen);
lv_obj_remove_style_all(g_diff_box);
lv_obj_set_size(g_diff_box, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_flow(g_diff_box, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(g_diff_box, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(g_diff_box, 8, 0);
lv_obj_align(g_diff_box, LV_ALIGN_TOP_RIGHT, -24, 60);
lv_obj_clear_flag(g_diff_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_t* diff_title = lv_label_create(g_diff_box);
lv_label_set_text(diff_title, "DIFF LOCK");
lv_obj_set_style_text_font(diff_title, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(diff_title, COL_MUTED, 0);
g_rear_pill = makeChip(g_diff_box, "REAR");
g_front_pill = makeChip(g_diff_box, "FRONT");
for (lv_obj_t* p : {g_rear_pill, g_front_pill}) {
lv_obj_set_style_text_font(p, &lv_font_montserrat_20, 0); // a tell-tale, bigger than the status chips
lv_obj_set_style_pad_hor(p, 14, 0);
}
// ---- gear hero -------------------------------------------------------
g_gear_ring = lv_obj_create(g_screen);
lv_obj_set_size(g_gear_ring, 220, 220);
@@ -322,6 +380,8 @@ void tick() {
(void)gear; // gear now comes from the driveline pieces, not the UART enum
lvgl_port_lock(-1);
refreshDiffLocks(); // hard-wired inputs: live even with CAN or the key off
// Blank every readout when there's nothing live to show: CAN off, or the key
// is off. The user asked for a full reset on ignition-off so the screen goes
// quiet with the car rather than freezing the last frame. 0x3B4 sends its
+15
View File
@@ -19,6 +19,7 @@ static const char* NVS_KEY_WIFI_ENABLED = "wifi_en";
static const char* NVS_KEY_UART_ENABLED = "uart_en";
static const char* NVS_KEY_DEBUG_ENABLED = "debug_en";
static const char* NVS_KEY_CAN_ENABLED = "can_en";
static const char* NVS_KEY_DIFFLOCK_ENABLED = "difflock_en";
// ============================================================================
// PUBLIC API IMPLEMENTATION
@@ -89,4 +90,18 @@ bool loadCANState() {
return enabled;
}
void saveDiffLockState(bool enabled) {
preferences.begin(NVS_NAMESPACE, false); // read-write mode
preferences.putBool(NVS_KEY_DIFFLOCK_ENABLED, enabled);
preferences.end();
Serial.printf("[SettingsManager] Saved DiffLock state = %s\n", enabled ? "ON" : "OFF");
}
bool loadDiffLockState() {
preferences.begin(NVS_NAMESPACE, true); // read-only mode
bool enabled = preferences.getBool(NVS_KEY_DIFFLOCK_ENABLED, false); // default: OFF
preferences.end();
return enabled;
}
} // namespace SettingsManager
+4
View File
@@ -66,4 +66,8 @@ void saveCANState(bool enabled);
*/
bool loadCANState();
/** Diff-lock inputs DI0/DI1 read (DiffLocks). Default OFF. */
void saveDiffLockState(bool enabled);
bool loadDiffLockState();
} // namespace SettingsManager
+24 -6
View File
@@ -8,6 +8,7 @@
#include "wifi_manager.h"
#include "ota_update.h"
#include "link_peer.h"
#include "diff_locks.h"
#include "uart_manager.h"
#include "espnow_link.h"
#include "settings_manager.h"
@@ -82,6 +83,8 @@ static Ota::phase_t g_upd_refusal_phase = Ota::PHASE_IDLE;
static lv_obj_t* g_sys_can = NULL;
static lv_obj_t* g_sys_link = NULL;
static lv_obj_t* g_sys_dbg = NULL;
static lv_obj_t* g_sys_diff = NULL;
static lv_obj_t* g_sys_diff_sub = NULL; // sub-line of the diff-lock row: live state
static lv_obj_t* g_sys_info = NULL; // values column; keys are static
static void refresh(bool force);
@@ -768,10 +771,22 @@ static void onDebugSwitch(lv_event_t* e) {
UIStateManager::setDebugEnabled(on);
}
static void onDiffSwitch(lv_event_t* e) {
if (g_refreshing) return;
DiffLocks::setEnabled(lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED));
}
static void refreshSystem(bool force) {
setChecked(g_sys_can, CANDriver::isActive());
setChecked(g_sys_link, UARTManager::getState() != UARTManager::UART_STATE_OFF);
setChecked(g_sys_dbg, UIStateManager::isDebugEnabled());
setChecked(g_sys_diff, DiffLocks::isEnabled());
// live state in the sub-line, so the wiring can be tested from this page
if (!DiffLocks::isEnabled()) setText(g_sys_diff_sub, "DI0 rear, DI1 front - 12 V = locked");
else if (!DiffLocks::isValid()) setText(g_sys_diff_sub, "Now: reading...");
else setText(g_sys_diff_sub, DiffLocks::frontLocked()
? (DiffLocks::rearLocked() ? "Now: rear LOCKED, front LOCKED" : "Now: FRONT only - check DI0 wiring")
: (DiffLocks::rearLocked() ? "Now: rear LOCKED, front open" : "Now: both open"));
static uint32_t last = 0; // the figures below change slowly; 1 Hz is plenty
if (!force && millis() - last < 1000) return;
@@ -782,18 +797,17 @@ static void refreshSystem(bool force) {
uint32_t up = millis() / 1000;
char buf[400];
snprintf(buf, sizeof(buf),
"%s (slot %s)\n"
"%s (slot %s), up %lu h %02lu min\n"
"ESP-NOW %s, %lu frames sent, %lu failed\n"
"%lu frames received\n"
"%u KB internal free, %u KB PSRAM free\n"
"%lu h %02lu min",
"%u KB internal free, %u KB PSRAM free",
FW_VERSION, run ? run->label : "?",
(unsigned long)(up / 3600), (unsigned long)((up / 60) % 60),
EspNowLink::isReady() ? "up" : "DOWN",
(unsigned long)EspNowLink::sentCount(), (unsigned long)EspNowLink::failCount(),
(unsigned long)cs.messages_received,
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) / 1024),
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024),
(unsigned long)(up / 3600), (unsigned long)((up / 60) % 60));
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024));
setText(g_sys_info, buf);
}
@@ -810,13 +824,17 @@ static void buildSystemPage(lv_obj_t* page) {
g_sys_link = toggle(right, onLinkSwitch, NULL);
makeSettingRow(c, "Performance overlay", "Frame rate and CPU load in the corner", &right);
g_sys_dbg = toggle(right, onDebugSwitch, NULL);
lv_obj_t* diff_row = makeSettingRow(c, "Diff lock inputs", "DI0 rear, DI1 front - 12 V = locked", &right);
g_sys_diff_sub = lv_obj_get_child(lv_obj_get_child(diff_row, 0), 1);
g_sys_diff = toggle(right, onDiffSwitch, NULL);
// two labels side by side, same line spacing, so keys and values line up
lv_obj_t* info = card(page);
lv_obj_set_size(info, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(info, LV_FLEX_FLOW_ROW);
lv_obj_set_style_pad_column(info, 24, 0);
lv_obj_t* keys = label(info, "Firmware\nLink to B\nCAN bus\nMemory\nUptime", &lv_font_montserrat_20, UI_COL_MUTED);
// Uptime shares the firmware line: a fourth switch row leaves no room for a fifth line (484 px page)
lv_obj_t* keys = label(info, "Firmware\nLink to B\nCAN bus\nMemory", &lv_font_montserrat_20, UI_COL_MUTED);
lv_obj_set_style_text_line_space(keys, 6, 0);
g_sys_info = label(info, "", &lv_font_montserrat_20, UI_COL_TEXT);
lv_obj_set_style_text_line_space(g_sys_info, 6, 0);
+1
View File
@@ -13,6 +13,7 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee
- [[bmw-m57n-engine]] — the 3.0L BMW diesel whose CAN bus we read; E60/E65 donor (confirmed), DDE ECU, auto box with EGS on bus
- [[nissan-patrol-swap]] — the target vehicle: Patrol receiving the M57N + BMW auto; the tapped bus is a BMW island in a Nissan
- [[esp32-s3-touch-lcd-5b]] — Waveshare 5" display board (Main CTRL); onboard TJA1051 CAN transceiver, 7–36 V input, pinout, PSRAM/LCD gotchas — **flash writes flicker the RGB panel, full-screen fades stutter, internal RAM nearly full, opening the serial port resets the board unless DTR/RTS are low; Wi-Fi scans caused the flickering dots; all screens hand-coded since 2026-09-27**
- [[diff-lock-inputs]] — **2026-09-29**: Patrol diff locks (+12 V = locked) on DI0 rear / DI1 front, `DI_COM` to ground; PC814 → CH422G EXIO0/EXIO5 (active low); the bank flip per read is unverified for panel flicker, so it is behind a Settings switch, default OFF
## Concepts
+4
View File
@@ -218,3 +218,7 @@ User renamed Controller A → **Main CTRL** and Controller B → **Inst. Cluster
## [2026-09-28] update | Deep-sleep feature REMOVED (user decision) - and the lesson it left
The "Sleep when the car is off" switch and both power managers are gone: code, Settings row, NVS key, the `CFG_SLEEP_WHEN_SILENT` bit in the shared header, the wiki page and the cheat-sheet entries. Reason: on the bench the Main CTRL's panel showed flickering white edges after a sleep, and it stayed that way through resets and even a USB flash of release v0.1.8. Cause, understood too late: `gpio_hold_en()` on the 20 RGB panel lines (added to blank the panel in sleep) lives in the RTC domain and **survives every reset except a power cycle** - no firmware without a matching `gpio_hold_dis()` at boot can drive the panel again. Only pulling the power clears it. **Rule for the future: never use GPIO hold / deep-sleep hold on this board's panel lines, and never send a board to deep sleep from the console without the user's go-ahead** (the USB port vanishes and only reset or power brings it back). The boards stay awake whenever powered; if power saving is ever wanted again, do it in hardware (ignition-switched supply).
## [2026-09-29] update | Diff-lock inputs on DI0 / DI1
The user wants the two Patrol diff locks (+12 V while locked; the front only locks after the rear) shown on the Main CTRL. From the schematic: DI0 = CH422G EXIO0, DI1 = EXIO5, active low behind PC814. The CH422G's IO0-7 are one all-in/all-out bank shared with touch reset, backlight and LCD reset, so the firmware flips the bank to input for about 0.1 ms per read, 4 Hz. It is behind a Settings switch, default OFF, until tried on the bench for flicker. New page [[diff-lock-inputs]]; the schematic source page now carries the input circuit and the EXIO net table.
+46
View File
@@ -0,0 +1,46 @@
---
type: concept
tags: [hardware, patrol, inputs, ch422g, wiring]
updated: 2026-09-29
---
# Diff-lock inputs (DI0 rear, DI1 front)
The Patrol has two differential locks. Their switches put **+12 V on a wire while a diff is locked** (source: user, 2026-09-29). The front can only be locked after the rear, so the valid states are: none, rear only, rear + front (source: user). The Main CTRL shows them on the Driveline screen from its two isolated inputs.
## Wiring
| Terminal (16-way block) | Connect to |
|---|---|
| `DI0` | rear diff-lock wire (+12 V = locked) |
| `DI1` | front diff-lock wire (+12 V = locked) |
| `DI_COM` | vehicle ground (chassis, same ground as the board's `GND`) |
This is Waveshare's "PNP wet input / high-level trigger" wiring: `DI_COM` to the negative pole, 5–36 V DC on the input (source: [[esp32-s3-touch-lcd-5b-waveshare-wiki]]). Tap the wires in parallel with whatever the Patrol already drives with them (dash lamp); each input draws only ~3 mA.
## Circuit (source: [[esp32-s3-touch-lcd-5-schematic]], sheet 1, "DI/DO")
- `DINx` → PC814 LED (bidirectional, so polarity does not matter) → 3.6 kΩ (R78 / R73, 1206) → `DI_COM`. At 12 V: (12 − 1.2) / 3.6 k ≈ **3.0 mA**; at 14.4 V charging ≈ 3.7 mA.
- 100 nF across each input (C100 / C101) filters spikes.
- `DI_COM` is also fed from 5 V through D4 (1N5822) + R79 220 Ω. That is what makes the "dry contact" mode work (`DI_COM` left open, the input switched to ground). With `DI_COM` on ground, as here, that path draws ~20 mA from the board's 5 V rail `(unverified: read from the schematic, not measured)`.
- Output side: the phototransistor pulls `DI0` / `DI1` (4.7 kΩ to 3V3) **low** while current flows. `DI0` = CH422G **EXIO0**, `DI1` = **EXIO5** (net table on the same sheet). So **locked = bit reads 0**.
## How the firmware reads them `(repo)`
The CH422G's IO0–7 are **one bank, all inputs or all outputs**, and the same bank drives touch reset (EXIO1), backlight (EXIO2) and LCD reset (EXIO3). The firmware switches the bank to input for about 0.1 ms per read (three I2C transactions: WR_SET 0x00, read, WR_SET 0x01), 4 times a second, under the LVGL lock. The chip keeps its output latch, so the outputs return to their previous levels. Another project does the same on a running display (source: github.com/VaAndCob/waveshare-esp32-s3-5inch-ch422g-driver, `EX_Read()`).
> [!warning] Not yet verified on this board
> Whether the 0.1 ms float disturbs the panel (flicker) or touch is **unknown** until tried. That is why the feature sits behind **Settings → System → Diff lock inputs**, default OFF. A board without the wiring never flips the bank. If the panel flickers with the switch on, turn it off. The fallback is to move the inputs to spare GPIOs on the Inst. Cluster.
A state counts after two equal reads, so it can lag the real switch by up to 0.5 s. Front-locked-without-rear is shown red on the Driveline, as a wiring or switch fault.
## Test on the bench
1. Settings → System → Diff lock inputs ON. The row's sub-line shows "Now: both open".
2. Put 12 V (the board's own VIN supply) on `DI0`, with `DI_COM` on `GND`. It should show "rear LOCKED", and the Driveline REAR pill turns amber. Then do the same on `DI1`.
3. Console: `difflock status` prints the raw IO byte: bit 0x01 (rear) and bit 0x20 (front) are SET while open, clear while locked.
4. Watch the panel for flicker while the switch is on (see the warning above).
## Related
[[esp32-s3-touch-lcd-5b]] · [[esp32-s3-touch-lcd-5-schematic]] · [[patrol-instrument-cluster]]
@@ -28,6 +28,7 @@ Raw: `raw/ESP32-S3-Touch-LCD-5-Sch.pdf` (3 sheets, V1.2), re-downloaded 2026-09-
- CAN: `CANTX` = IO15, `CANRX` = IO16 (matches `(repo)`); RS485: `RS485_TXD` = IO44, `RS485_RXD` = IO43 (matches [[esp32-s3-touch-lcd-5-intro-photo]]).
- SD card on `MOSI` IO11 / `SCK` IO12 / `MISO` IO13, `SDCS` on CH422G `EXIO4` — the pin facts needed for the SD "black box" idea in [[obd-diagnostic-polling]].
- Isolated outputs `DO0`/`DO1` via PC817 optocouplers driven from `OD0`/`OD1` (CH422G), inputs `DI0`/`DI1` via PC814.
- Input detail (read 2026-09-29 for [[diff-lock-inputs]]): `DINx` → PC814 LED → 3.6 kΩ 1206 → `DI_COM`, 100 nF across. `DI_COM` is also fed from 5 V via D4 1N5822 + R79 220 Ω, for dry contacts. The phototransistor pulls `DI0`/`DI1` (4.7 kΩ to 3V3) low. The net table maps `DI0` = **EXIO0** and `DI1` = **EXIO5**. The rest of the bank: EXIO1 `CTP_RST`, EXIO2 `DISP`, EXIO3 `LCD_RST`, EXIO4 `SDCS`.
- Strapping pads `R87–R94` (IO0/IO3/IO45/IO46).
## Related