Add wiki second brain and root CLAUDE.md; retire .docs

- New wiki/ (Obsidian vault) following the LLM Wiki pattern: schema, index, log,
  entity page for the board, concept pages for the A->B link, wired+wireless
  redundancy, and Patrol gauge outputs, open questions, two sources
- New CLAUDE.md distilled from the surviving .docs content: verified pins,
  brightness/receiver/debug APIs, SquareLine rules, CH343 serial notes,
  gear-enum drift warning, Waveshare demo and schematic URLs
- Delete .docs/ (14 files): stale pin-hunting and troubleshooting guides,
  wrong header table, finished phase roadmap, duplicate UART spec (now in the
  5B repo at docs/UART_PROTOCOL.md)
- README.md repointed to CLAUDE.md and wiki/

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-21 10:57:05 +02:00
parent b6fb01ba73
commit 3613387d41
31 changed files with 869 additions and 3965 deletions
-273
View File
@@ -1,273 +0,0 @@
# Display Brightness Control Guide
## Overview
The ESP32-S3-LCD-1.3 backlight brightness can be controlled via PWM on GPIO 20.
**Brightness Range**: 0-255
- `0` = Backlight OFF (display is black)
- `128` = 50% brightness (default)
- `255` = Maximum brightness
## How to Control Brightness
### Method 1: Set Fixed Brightness
In `main.cpp`, call `DisplayInit::setBrightness()`:
```cpp
#include "modules/display_init.h"
void setup() {
// ... after DisplayInit::init() ...
// Set to 50% brightness
DisplayInit::setBrightness(128);
// Or set to 25% for dimmer display
DisplayInit::setBrightness(64);
// Or max brightness
DisplayInit::setBrightness(255);
}
```
### Method 2: Adjust Dynamically
```cpp
void loop() {
static bool is_dim = false;
static uint32_t last_toggle = 0;
// Toggle brightness every 5 seconds
if (millis() - last_toggle > 5000) {
last_toggle = millis();
if (is_dim) {
DisplayInit::setBrightness(255); // Bright
Serial.println("Brightness: MAX");
} else {
DisplayInit::setBrightness(64); // Dim
Serial.println("Brightness: LOW");
}
is_dim = !is_dim;
}
delay(10);
}
```
### Method 3: Smooth Fade In/Out
```cpp
void fadeOut() {
for (int brightness = 255; brightness >= 0; brightness -= 5) {
DisplayInit::setBrightness(brightness);
delay(20); // 20ms between steps
}
}
void fadeIn() {
for (int brightness = 0; brightness <= 255; brightness += 5) {
DisplayInit::setBrightness(brightness);
delay(20);
}
}
```
### Method 4: Auto-Dim After Inactivity
```cpp
void loop() {
static uint32_t last_activity = 0;
const uint32_t DIM_TIMEOUT = 30000; // 30 seconds
const uint8_t DIM_LEVEL = 32; // Dim to 12.5%
const uint8_t BRIGHT_LEVEL = 255; // Full brightness
// Detect activity (button press, touch, etc.)
if (activity_detected()) {
last_activity = millis();
DisplayInit::setBrightness(BRIGHT_LEVEL);
}
// Auto-dim after timeout
if (millis() - last_activity > DIM_TIMEOUT) {
uint8_t current = DisplayInit::getBrightness();
if (current != DIM_LEVEL) {
DisplayInit::setBrightness(DIM_LEVEL);
Serial.println("Display dimmed due to inactivity");
}
}
delay(100);
}
```
### Method 5: Night Mode / Day Mode
```cpp
enum DisplayMode {
DAY_MODE,
NIGHT_MODE
};
void setDisplayMode(DisplayMode mode) {
if (mode == DAY_MODE) {
DisplayInit::setBrightness(255); // Full brightness
Serial.println("Day mode: brightness 100%");
} else {
DisplayInit::setBrightness(64); // 25% for night
Serial.println("Night mode: brightness 25%");
}
}
void loop() {
// Example: switch mode based on time or ambient light sensor
int hour = getCurrentHour(); // Your time function
if (hour >= 6 && hour < 20) {
setDisplayMode(DAY_MODE);
} else {
setDisplayMode(NIGHT_MODE);
}
delay(60000); // Check every minute
}
```
## Quick Examples
### Example 1: Set Low Brightness at Startup
```cpp
void setup() {
Serial.begin(115200);
if (!DisplayInit::init()) {
Serial.println("Display init failed!");
while(1);
}
// Set to low brightness (25%)
DisplayInit::setBrightness(64);
Serial.println("Brightness set to 25%");
ui_init();
// ... rest of setup ...
}
```
### Example 2: Breathing Effect
```cpp
void loop() {
static int brightness = 0;
static int direction = 1;
brightness += direction * 5;
if (brightness >= 255) {
brightness = 255;
direction = -1;
} else if (brightness <= 50) {
brightness = 50;
direction = 1;
}
DisplayInit::setBrightness(brightness);
delay(30);
}
```
### Example 3: Get Current Brightness
```cpp
void printBrightnessInfo() {
uint8_t current = DisplayInit::getBrightness();
int percentage = (current * 100) / 255;
Serial.printf("Current brightness: %d/255 (%d%%)\n",
current, percentage);
}
```
## Default Brightness
The default brightness is set to **128 (50%)** in `display_init.cpp`:
```cpp
static uint8_t current_brightness = 128;
```
You can change this default by editing line 88 in `src/display_init.cpp`.
## Power Consumption
Brightness affects battery life:
- **255 (100%)**: Maximum power draw (~150-200mA)
- **128 (50%)**: Medium power (~100-120mA)
- **64 (25%)**: Low power (~70-90mA)
- **32 (12.5%)**: Very low power (~50-60mA)
- **0 (OFF)**: Minimal power, display invisible
For battery-powered operation, consider:
- Normal use: 128 (50%)
- Idle/standby: 32 (12.5%)
- Sleep mode: 0 (OFF)
## Using with Automotive Dashboard (Phase 3)
```cpp
void updateDashboard(const automotive_data_t* data) {
// Dim display if engine is off (battery voltage low)
if (data->battery_voltage_v < 12.0) {
DisplayInit::setBrightness(64); // Low brightness to save power
} else {
DisplayInit::setBrightness(200); // Normal brightness
}
// Update UI with data...
}
```
## API Reference
### Functions
```cpp
namespace DisplayInit {
// Set backlight brightness (0-255)
void setBrightness(uint8_t brightness);
// Get current brightness level (0-255)
uint8_t getBrightness();
}
```
### Usage
```cpp
#include "modules/display_init.h"
// Set brightness
DisplayInit::setBrightness(128); // 50%
// Get current brightness
uint8_t level = DisplayInit::getBrightness();
```
## Tips
1. **Don't update too frequently**: Changing brightness constantly can cause flickering
2. **Use delays between changes**: Add small delays when fading
3. **Save battery**: Lower brightness when on battery power
4. **Night mode**: Use 25-50% brightness for comfortable night viewing
5. **Minimum visible**: Brightness below 20-30 may be too dim to read
---
**Default**: 128 (50% brightness)
**Range**: 0-255 (0=off, 255=max)
**Control**: Via GPIO 20 PWM (44.1kHz)
-232
View File
@@ -1,232 +0,0 @@
# Correct File Locations - Quick Reference
## ✅ Correct Structure
### Implementation Files (.cpp) → `src/`
```
src/
├── main.cpp ✅ Main application
├── display_init.cpp ✅ Display hardware driver
├── uart_receiver.cpp (future - Phase 2)
└── data_validator.cpp (future - Phase 4)
```
**Rule**: ALL `.cpp` implementation files go in `src/`
---
### Header Files (.h) → `include/modules/`
```
include/modules/
├── display_init.h ✅ Display module interface
├── uart_receiver.h (future - Phase 2)
└── data_validator.h (future - Phase 4)
```
**Rule**: Module header files go in `include/modules/`
---
### Why This Structure?
#### `.cpp` files in `src/`
- ✅ PlatformIO automatically compiles all `.cpp` in `src/`
- ✅ Implementation details are separated from interfaces
- ✅ Standard C++ project structure
#### `.h` files in `include/`
- ✅ Headers are on the include path
- ✅ Can be included with `#include "modules/display_init.h"`
- ✅ Public interfaces are visible to all modules
---
## ❌ Common Mistakes
### ❌ WRONG: `.cpp` in `include/`
```
include/modules/
└── display_init.cpp ❌ WRONG! Move to src/
```
**Problem**: Include directories are for headers, not implementations
**Fix**:
```bash
mv include/modules/display_init.cpp src/
```
---
### ❌ WRONG: `.h` in `src/`
```
src/
└── display_init.h ❌ WRONG! Move to include/modules/
```
**Problem**: Headers in `src/` are not on the include path
**Fix**:
```bash
mv src/display_init.h include/modules/
```
---
## Include Path Examples
### From `src/main.cpp`:
```cpp
#include "modules/display_init.h" ✅ Correct
```
### From `src/display_init.cpp`:
```cpp
#include "modules/display_init.h" ✅ Correct
```
### From any module:
```cpp
#include "modules/display_init.h" ✅ Always use this format
```
---
## Special Cases
### SquareLine Studio UI Files
```
include/ui/
├── ui.h ✅ Header in include/
├── ui.c ✅ Implementation also in include/ (special case)
└── screens/
├── ui_Home_Screen.h ✅
└── ui_Home_Screen.c ✅
```
**Why this is different**:
- SquareLine Studio exports both `.h` and `.c` to the same folder
- `build_src_filter` in `platformio.ini` includes `+<../include/ui/*>`
- This tells PlatformIO to compile `.c` files from `include/ui/`
**This is the ONLY exception** - don't do this for your own modules!
---
## Creating a New Module
### Example: Adding `settings_manager` module
1. **Create header** in `include/modules/`:
```bash
# Create the header
cat > include/modules/settings_manager.h << 'EOF'
#ifndef SETTINGS_MANAGER_H
#define SETTINGS_MANAGER_H
namespace SettingsManager {
void init();
void save();
int getBrightnessSetting();
}
#endif
EOF
```
2. **Create implementation** in `src/`:
```bash
# Create the implementation
cat > src/settings_manager.cpp << 'EOF'
#include "modules/settings_manager.h"
#include <Preferences.h>
namespace SettingsManager {
void init() {
// Implementation
}
void save() {
// Implementation
}
int getBrightnessSetting() {
// Implementation
return 128;
}
}
EOF
```
3. **Use in main.cpp**:
```cpp
#include "modules/settings_manager.h"
void setup() {
SettingsManager::init();
int brightness = SettingsManager::getBrightnessSetting();
}
```
---
## Quick Checklist
When creating a new module:
- [ ] Header file (`.h`) in `include/modules/`
- [ ] Implementation file (`.cpp`) in `src/`
- [ ] Include guard in header (`#ifndef`, `#define`, `#endif`)
- [ ] Include statement: `#include "modules/module_name.h"`
- [ ] Namespace to avoid naming conflicts
- [ ] Build test: `pio run`
---
## Current Project Structure
```
ESP32-S3-LCD-1.3/
├── src/ ← Implementation files (.cpp)
│ ├── main.cpp
│ ├── display_init.cpp ✅ CORRECT LOCATION
│ └── main_minimal.cpp.bak
│
├── include/
│ ├── modules/ ← Module headers (.h)
│ │ └── display_init.h ✅ CORRECT LOCATION
│ ├── config/
│ │ └── lv_conf.h
│ ├── protocol/
│ │ └── automotive_data.h
│ └── ui/ ← SquareLine UI (special case)
│ ├── ui.h
│ ├── ui.c ← Exception: .c in include/
│ └── screens/
│
└── platformio.ini
```
---
## Summary
| File Type | Location | Include As |
|-----------|----------|------------|
| `.cpp` (implementation) | `src/` | N/A (compiled by PlatformIO) |
| `.h` (header) | `include/modules/` | `#include "modules/name.h"` |
| SquareLine `.c` | `include/ui/` | Auto-included |
| SquareLine `.h` | `include/ui/` | `#include "ui/ui.h"` |
**Remember**:
- ✅ **Headers in `include/`**
- ✅ **Implementations in `src/`**
- ❌ **Never mix them up!**
---
**Last Updated**: 2025-11-08
**Status**: ✅ Correct structure verified, builds successfully
@@ -1,827 +0,0 @@
# ESP32-S3-LCD-1.3 Implementation Guide
**Controller B - Compact Automotive Display Unit**
## Project Overview
This document outlines the implementation plan for the **ESP32-S3-LCD-1.3** (Controller B), which receives automotive data via UART from the ESP32-S3-Touch-LCD-5B (Controller A) and displays it on a compact 1.3" round display.
### System Architecture
```
┌─────────────────────────────────────┐
│ Controller A │
│ ESP32-S3-Touch-LCD-5B │
│ - 5" touchscreen (1024x600) │
│ - Settings & WiFi interface │
│ - UART TX on GPIO 43 @ 115200 baud │
└──────────────┬──────────────────────┘
│ UART @ 5Hz
│ (Automotive Data Packets)
▼
┌─────────────────────────────────────┐
│ Controller B │
│ ESP32-S3-LCD-1.3 │
│ - 1.3" round display (240×240) │
│ - Real-time data visualization │
│ - UART RX @ 115200 baud │
│ - Compact dashboard display │
└─────────────────────────────────────┘
```
---
## Hardware Specifications - ESP32-S3-LCD-1.3
### Core Processor
- **MCU**: ESP32-S3R8 (Xtensa 32-bit LX7 dual-core)
- **CPU Frequency**: 240MHz
- **RAM**: 512KB SRAM (internal)
- **Flash**: 16MB (external)
- **PSRAM**: 8MB (external)
### Display
- **Size**: 1.3 inches diagonal
- **Shape**: Round/Circular form factor
- **Resolution**: 240×240 pixels
- **Controller**: ST7789VW (SPI interface)
- **Colors**: 262K (RGB565)
- **Panel Type**: IPS with 160° viewing angle
- **Special Feature**: Hardware 90° rotation support
### Sensors (Onboard)
- **IMU**: QMI8658 6-axis sensor
- 3-axis accelerometer
- 3-axis gyroscope
- I2C interface
### Communication Interfaces
- **USB**: Type-C (CDC/UART via CH343P chip)
- **UART**: Hardware serial for automotive data reception
- **I2C**: For IMU sensor communication
- **SPI**: For display controller
### Power Management
- **USB Power**: 5V via Type-C
- **Battery Support**: MX1.25 connector (3.7V lithium)
- **Charging IC**: PL4054 battery manager
- **Voltage Regulator**: ME6217C33M5G (800mA max)
- **Battery Capacity**: Supports standard 3.7V lithium batteries
### GPIO & Expansion
- **GPIO Header**: 13-pin 2.54mm header
- **Available Protocols**: I2C, SPI, UART, GPIO
- **Programmable LED**: Onboard
### Storage
- **TF Card Slot**: MicroSD card support (up to 64GB)
### Physical Characteristics
- **Weight**: 12 grams
- **Form Factor**: Compact round display module
- **Antenna**: Onboard ceramic antenna for WiFi/BLE
---
## Pin Configuration & UART Setup
### UART Pin Assignment (for Automotive Data Reception)
Based on the ESP32-S3 standard pinout, recommended UART configuration:
```cpp
// UART configuration for receiving automotive data
#define UART_RX_PIN 44 // GPIO 44 - Receive from Controller A
#define UART_TX_PIN 43 // GPIO 43 - Unused (RX-only mode)
#define UART_BAUD_RATE 115200
#define UART_SERIAL_PORT Serial1 // Hardware UART1
```
**Note**: The exact GPIO pins should be verified against the ESP32-S3-LCD-1.3 schematic. The board may have predefined UART pins exposed on the 13-pin header.
### SPI Display Pins (ST7789VW - Predefined by Board)
These are typically hardwired on the board:
- **MOSI**: Data to display
- **SCLK**: SPI clock
- **CS**: Chip select
- **DC**: Data/Command select
- **RST**: Reset
- **BL**: Backlight control
---
## Software Architecture
### Module Structure
Following the modular architecture established in Controller A:
```
src/
├── main.cpp # Main application coordinator
├── modules/
│ ├── display_init.cpp/.h # ST7789VW display initialization
│ ├── uart_receiver.cpp/.h # UART data reception & parsing
│ ├── data_validator.cpp/.h # Packet validation & error handling
│ ├── ui_renderer.cpp/.h # LVGL UI rendering for round display
│ └── settings_manager.cpp/.h # Brightness, rotation, display settings
└── protocol/
└── automotive_data.h # Shared protocol (copied from Controller A)
```
### Key Differences from Controller A
| Feature | Controller A (5B) | Controller B (1.3) |
|---------|-------------------|-------------------|
| Display Size | 5" (1024×600) | 1.3" (240×240) |
| UART Role | **Transmitter** | **Receiver** |
| UI Complexity | Settings + WiFi + Multi-screen | Single-screen dashboard |
| Touch Input | Capacitive touch | None (display-only) |
| WiFi Usage | Network scanning | Optional (for logging/updates) |
| Form Factor | Large touchscreen | Compact wearable/dash unit |
---
## Implementation Plan
### Phase 1: Hardware Setup & Basic Display
**Goal**: Get the display working with LVGL
1. **Create PlatformIO Project**
- Board: `esp32-s3-devkitc-1` (or custom board definition)
- Framework: Arduino
- Platform: `espressif32@6.x` (ESP-IDF v5.x)
2. **Display Initialization**
- Use `TFT_eSPI` or `Arduino_GFX` library for ST7789VW
- Configure for 240×240 round display
- Test with simple shapes and colors
3. **LVGL Integration**
- LVGL 8.4.0 (match Controller A version)
- Configure for 240×240 resolution
- Create circular display mask for round UI
- Set up LVGL task on Core 1
**Expected Output**: Display shows LVGL UI with circular viewport
---
### Phase 2: UART Reception & Protocol Implementation
**Goal**: Receive and parse automotive data packets
1. **Copy Protocol Header**
```bash
cp ../ESP32-S3-Touch-LCD-5B/include/protocol/automotive_data.h include/protocol/
```
2. **Implement UART Receiver Module**
```cpp
namespace UARTReceiver {
void init();
bool receivePacket(uart_packet_t* packet);
automotive_data_t getLatestData();
uart_rx_stats_t getStats();
}
```
3. **Packet Parsing Strategy**
- State machine for packet framing (look for 0xAA start byte)
- Circular buffer for incoming UART data
- Checksum validation using `validate_packet()`
- Error handling (timeout, checksum mismatch, malformed packets)
4. **FreeRTOS Task Architecture**
- **Core 0**: UART reception task (Priority 1)
- **Core 1**: LVGL rendering task (Priority 2)
- **Queue**: Pass validated packets to UI thread
**Expected Output**: Serial monitor shows received automotive data packets
---
### Phase 3: UI Design with SquareLine Studio
**Note**: UI will be designed using SquareLine Studio for the 240×240 round display. Export UI files to `include/ui/` directory.
---
### Phase 4: Data Validation & Error Handling
**Goal**: Robust operation with connection loss recovery
1. **Packet Validation**
- Check start byte (0xAA) and end byte (0x55)
- Verify checksum using `validate_packet()`
- Check `valid_flags` to know which sensor data is valid
2. **Connection Monitoring**
- Track time since last valid packet
- Display "NO DATA" warning if >1 second without packets
- Automatic recovery when packets resume
3. **Error Statistics Tracking**
```cpp
typedef struct {
uint32_t packets_received;
uint32_t checksum_errors;
uint32_t framing_errors;
uint32_t timeout_errors;
uint32_t last_packet_time;
} uart_rx_stats_t;
```
**Expected Output**: Stable display even with intermittent data
---
### Phase 5: Polish & Optimization
1. **Power Management**
- Display sleep mode after inactivity
- Battery voltage monitoring (if using battery power)
- Low-power mode support
2. **Performance Optimization**
- Target 30 FPS @ 240×240 (less demanding than 5B's 1024×600)
- Optimize LVGL buffer sizes
- Reduce unnecessary redraws
3. **User Settings (Optional)**
- Brightness control
- Display rotation (90°/180°/270°)
- Units (Celsius/Fahrenheit)
- Persistent settings in NVS
---
## PlatformIO Configuration Example
### `platformio.ini`
```ini
[platformio]
default_envs = esp32_s3_lcd_1_3
[env:esp32_s3_lcd_1_3]
platform = espressif32@^6.0.0
framework = arduino
board = esp32-s3-devkitc-1
; Build flags
build_flags =
-std=gnu++17
-DCORE_DEBUG_LEVEL=3
-DLV_CONF_INCLUDE_SIMPLE
-DBOARD_HAS_PSRAM
-DARDUINO_RUNNING_CORE=1
; Libraries
lib_deps =
lovyan03/LovyanGFX@^1.1.0 ; For ST7789VW display
lvgl/lvgl@^8.4.0 ; LVGL graphics library
arduino-libraries/Arduino_GFX ; Alternative display library
; Upload settings
upload_speed = 921600
monitor_speed = 115200
monitor_filters = esp32_exception_decoder
; Memory configuration
board_build.flash_mode = qio
board_build.psram_type = opi
```
---
## Display Library Setup
### Option 1: LovyanGFX (Recommended)
```cpp
#include <LovyanGFX.hpp>
class LGFX : public lgfx::LGFX_Device {
lgfx::Panel_ST7789 _panel_instance;
lgfx::Bus_SPI _bus_instance;
public:
LGFX(void) {
// Configure SPI bus
auto cfg = _bus_instance.config();
cfg.spi_host = SPI2_HOST;
cfg.spi_mode = 0;
cfg.freq_write = 80000000; // 80MHz SPI
cfg.freq_read = 16000000;
cfg.pin_sclk = /* SCLK GPIO */;
cfg.pin_mosi = /* MOSI GPIO */;
cfg.pin_miso = -1; // Not used
cfg.pin_dc = /* DC GPIO */;
_bus_instance.config(cfg);
_panel_instance.setBus(&_bus_instance);
// Configure panel
auto pcfg = _panel_instance.config();
pcfg.pin_cs = /* CS GPIO */;
pcfg.pin_rst = /* RST GPIO */;
pcfg.panel_width = 240;
pcfg.panel_height = 240;
_panel_instance.config(pcfg);
setPanel(&_panel_instance);
}
};
```
### Option 2: TFT_eSPI
Requires editing `User_Setup.h` or using custom setup file.
---
## UART Reception Implementation Example
### `uart_receiver.cpp` (Skeleton)
```cpp
#include "uart_receiver.h"
#include "protocol/automotive_data.h"
namespace UARTReceiver {
// Private state
static automotive_data_t g_latest_data = {0};
static uart_rx_stats_t g_rx_stats = {0};
static QueueHandle_t g_packet_queue = NULL;
static TaskHandle_t g_uart_task_handle = NULL;
static SemaphoreHandle_t g_data_mutex = NULL;
// Packet framing state machine
typedef enum {
STATE_WAIT_START,
STATE_READ_VERSION,
STATE_READ_LENGTH,
STATE_READ_DATA,
STATE_READ_CHECKSUM,
STATE_READ_END
} rx_state_t;
// UART reception task
static void uartRxTask(void* parameter) {
uart_packet_t packet;
uint8_t rx_buffer[PACKET_MAX_SIZE];
rx_state_t state = STATE_WAIT_START;
size_t bytes_read = 0;
Serial.println("[UARTReceiver] Task started on Core 0");
// Initialize UART1 hardware
Serial1.begin(UART_BAUD_RATE, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN);
Serial.printf("[UARTReceiver] UART1 initialized: %d baud, RX=GPIO%d\n",
UART_BAUD_RATE, UART_RX_PIN);
while (true) {
if (Serial1.available()) {
uint8_t byte = Serial1.read();
switch (state) {
case STATE_WAIT_START:
if (byte == PACKET_START_BYTE) {
rx_buffer[0] = byte;
bytes_read = 1;
state = STATE_READ_VERSION;
} else {
g_rx_stats.framing_errors++;
}
break;
case STATE_READ_VERSION:
rx_buffer[bytes_read++] = byte;
state = STATE_READ_LENGTH;
break;
case STATE_READ_LENGTH:
rx_buffer[bytes_read++] = byte;
if (byte > PACKET_MAX_SIZE) {
state = STATE_WAIT_START;
g_rx_stats.framing_errors++;
} else {
state = STATE_READ_DATA;
}
break;
case STATE_READ_DATA:
rx_buffer[bytes_read++] = byte;
// Check if we've read all data bytes
if (bytes_read >= (3 + rx_buffer[2])) { // start+version+length+data
state = STATE_READ_CHECKSUM;
}
break;
case STATE_READ_CHECKSUM:
rx_buffer[bytes_read++] = byte;
state = STATE_READ_END;
break;
case STATE_READ_END:
rx_buffer[bytes_read++] = byte;
if (byte == PACKET_END_BYTE) {
// Complete packet received - validate it
memcpy(&packet, rx_buffer, bytes_read);
if (validate_packet(&packet)) {
// Valid packet - update latest data
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
memcpy(&g_latest_data, &packet.data, sizeof(automotive_data_t));
g_rx_stats.packets_received++;
g_rx_stats.last_packet_time = millis();
xSemaphoreGive(g_data_mutex);
}
// Debug output every 10 packets
if (g_rx_stats.packets_received % 10 == 0) {
Serial.printf("[UARTReceiver] Packet #%d received (Gear:%s)\n",
packet.data.packet_id,
gear_to_string((gear_position_t)packet.data.gear_position));
}
} else {
g_rx_stats.checksum_errors++;
}
} else {
g_rx_stats.framing_errors++;
}
state = STATE_WAIT_START;
bytes_read = 0;
break;
}
}
vTaskDelay(pdMS_TO_TICKS(10)); // Small delay to prevent CPU hogging
}
}
void init() {
Serial.println("[UARTReceiver] Initializing UART receiver...");
g_data_mutex = xSemaphoreCreateMutex();
g_packet_queue = xQueueCreate(10, sizeof(uart_packet_t));
xTaskCreatePinnedToCore(
uartRxTask,
"UART_RX_Task",
4096,
NULL,
1, // Priority 1
&g_uart_task_handle,
0 // Core 0
);
Serial.println("[UARTReceiver] Initialization complete");
}
automotive_data_t getLatestData() {
automotive_data_t data;
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
memcpy(&data, &g_latest_data, sizeof(automotive_data_t));
xSemaphoreGive(g_data_mutex);
}
return data;
}
uart_rx_stats_t getStats() {
return g_rx_stats;
}
} // namespace UARTReceiver
```
---
## Debug Mode Synchronization
Controller A transmits a `debug_enabled` flag in the automotive data structure to synchronize debug monitor visibility between both controllers. When enabled, Controller B should display LVGL's built-in performance and memory monitors.
### Updated Automotive Data Structure
The `automotive_data_t` structure includes a debug flag:
```cpp
typedef struct __attribute__((packed)) {
uint8_t packet_id; // Incremental packet ID
uint32_t timestamp_ms; // Milliseconds since boot
// Sensor data (6 monitored values)
uint8_t gear_position; // Current gear (P/R/N/D/1-6)
int16_t gearbox_oil_temp; // Gearbox oil temperature in 0.1°C
int16_t engine_oil_temp; // Engine oil temperature in 0.1°C
int16_t coolant_temp; // Engine coolant temperature in 0.1°C
uint16_t battery_voltage; // Battery voltage in 0.01V
uint16_t fault_codes; // Bitmap of active fault codes
uint8_t valid_flags; // Data validity flags
uint8_t debug_enabled; // 0 = debug off, 1 = debug on
} automotive_data_t;
```
### Implementation: Runtime Debug Monitor Control
**Important**: LVGL's `LV_USE_PERF_MONITOR` and `LV_USE_MEM_MONITOR` are compile-time defines in `lv_conf.h`. To enable runtime control based on the received debug flag, keep both monitors **enabled at compile-time** (set to 1), then control their visibility at runtime.
#### Step 1: Configure `lv_conf.h`
Ensure these are enabled in your `lv_conf.h`:
```cpp
#define LV_USE_PERF_MONITOR 1
#define LV_USE_MEM_MONITOR 1
```
#### Step 2: Implement Debug Monitor Handler
Add this function to your UI module (e.g., `ui_renderer.cpp`):
```cpp
namespace UIRenderer {
static bool g_debug_monitors_visible = false;
/**
* @brief Show or hide LVGL performance and memory monitors
* @param enabled True to show monitors, false to hide
*/
void setDebugMonitorsVisible(bool enabled) {
if (g_debug_monitors_visible == enabled) {
return; // Already in correct state
}
g_debug_monitors_visible = enabled;
lvgl_port_lock(-1); // Acquire LVGL lock for thread-safety
#if LV_USE_PERF_MONITOR
// Get the system layer where performance monitor is rendered
lv_obj_t* perf_monitor = lv_disp_get_layer_sys(NULL);
if (perf_monitor) {
if (enabled) {
lv_obj_clear_flag(perf_monitor, LV_OBJ_FLAG_HIDDEN);
Serial.println("[UIRenderer] Performance monitor SHOWN");
} else {
lv_obj_add_flag(perf_monitor, LV_OBJ_FLAG_HIDDEN);
Serial.println("[UIRenderer] Performance monitor HIDDEN");
}
}
#endif
#if LV_USE_MEM_MONITOR
// Memory monitor visibility is controlled by the same system layer
// No additional code needed if using default LVGL monitor placement
#endif
lvgl_port_unlock();
}
} // namespace UIRenderer
```
#### Step 3: Process Debug Flag from Received Packets
In your UART receiver task, when a valid packet is received, check the debug flag and update the monitor visibility:
```cpp
// Inside uartRxTask() after successful packet validation:
if (validate_packet(&packet)) {
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
// Copy received data
memcpy(&g_latest_data, &packet.data, sizeof(automotive_data_t));
// Update debug monitor visibility based on received flag
UIRenderer::setDebugMonitorsVisible(packet.data.debug_enabled != 0);
g_rx_stats.packets_received++;
g_rx_stats.last_packet_time = millis();
xSemaphoreGive(g_data_mutex);
}
// Debug output
if (g_rx_stats.packets_received % 10 == 0) {
Serial.printf("[UARTReceiver] Packet #%d received (Gear:%s, Debug:%s)\n",
packet.data.packet_id,
gear_to_string((gear_position_t)packet.data.gear_position),
packet.data.debug_enabled ? "ON" : "OFF");
}
}
```
### Expected Behavior
- When Controller A enables debug mode (Settings screen toggle ON), the debug flag is set to 1
- Controller B receives the updated debug flag in the next UART packet
- Controller B's performance/memory monitors automatically appear
- When Controller A disables debug mode, Controller B's monitors hide automatically
- Synchronization happens within one packet cycle (200ms @ 5Hz transmission rate)
### Performance Impact
- **FPS Display**: Shows current rendering performance (target: 30+ FPS @ 240×240)
- **CPU Usage**: Shows LVGL task CPU utilization
- **Memory Monitor**: Shows heap usage and fragmentation (if enabled)
- **Minimal Overhead**: Monitors use ~1-2% additional CPU when visible
---
## UI Integration Notes
### SquareLine Studio Configuration
- **Display Size**: 240×240 pixels
- **Display Shape**: Round (enable circular masking in SquareLine)
- **Export Path**: `include/ui/` directory
- **LVGL Version**: 8.4.0 (match Controller A)
### Data Binding from UART Receiver
Once you've created your UI in SquareLine Studio, you'll need to update the LVGL widgets with received automotive data. Example:
```cpp
// In your UI update function (called when new packet arrives)
void updateUIWithData(const automotive_data_t* data) {
lvgl_port_lock(-1);
// Update gear position label
lv_label_set_text(ui_GearLabel, gear_to_string((gear_position_t)data->gear_position));
// Update temperature values
char temp_buf[16];
format_temperature(data->gearbox_oil_temp, temp_buf);
lv_label_set_text(ui_GearboxTempLabel, temp_buf);
// Update battery voltage
char volt_buf[16];
format_voltage(data->battery_voltage, volt_buf);
lv_label_set_text(ui_BatteryLabel, volt_buf);
lvgl_port_unlock();
}
```
---
## Testing Strategy
### Unit Testing
1. **Packet Parsing**: Test with known-good and malformed packets
2. **Checksum Validation**: Verify `validate_packet()` catches errors
3. **Data Staleness**: Simulate timeout conditions
### Integration Testing
1. **UART Loopback**: Connect Controller A directly to Controller B
2. **WiFi-based Testing**: Controller A sends debug packets over WiFi
3. **Simulated Data**: Create packet generator for standalone testing
### Field Testing
1. **Connection Resilience**: Disconnect/reconnect UART cable
2. **Data Range Validation**: Test extreme temperature/voltage values
3. **Performance**: Verify 30+ FPS with continuous updates
---
## Deployment Checklist
- [ ] PlatformIO project compiles successfully
- [ ] Display shows LVGL UI correctly (circular viewport)
- [ ] UART receives and parses packets from Controller A
- [ ] All 6 sensor values display correctly
- [ ] Gear position updates in real-time
- [ ] Temperature values update @ 5Hz
- [ ] Fault codes display when present
- [ ] "NO DATA" warning appears when connection lost
- [ ] Connection auto-recovers when resumed
- [ ] Debug monitors sync with Controller A (show/hide based on debug_enabled flag)
- [ ] Performance is 30+ FPS
- [ ] Power consumption is acceptable (battery mode)
---
## Bill of Materials (BOM)
| Component | Quantity | Notes |
|-----------|----------|-------|
| ESP32-S3-LCD-1.3 Board | 1 | Waveshare SKU 29962 |
| ESP32-S3-Touch-LCD-5B | 1 | Controller A (transmitter) |
| UART Cable | 1 | 3-wire: GND, RX, TX |
| Lithium Battery (optional) | 1 | 3.7V, MX1.25 connector |
| USB-C Cable | 1 | For programming/power |
---
## Wiring Diagram
```
Controller A (ESP32-S3-LCD-5B) Controller B (ESP32-S3-LCD-1.3)
┌─────────────────────────┐ ┌─────────────────────────┐
│ │ │ │
│ GPIO 43 (UART TX) ─────┼──────────┼────> UART RX (GPIO 44) │
│ │ │ │
│ GPIO 44 (UART RX) │ │ UART TX (GPIO 43) │
│ (unused) │ │ (unused) │
│ │ │ │
│ GND ───────────────────┼──────────┼────> GND │
│ │ │ │
└─────────────────────────┘ └─────────────────────────┘
```
**Note**: Only 2 wires needed: TX from Controller A → RX on Controller B, and shared GND.
---
## Expected Performance Metrics
| Metric | Target | Notes |
|--------|--------|-------|
| Display FPS | 30+ | Less demanding than 5B's 1024×600 |
| UART Packet Rate | 5 packets/sec | Matches Controller A transmission |
| Packet Loss | <1% | With proper error handling |
| Data Latency | <50ms | From transmission to display |
| Power Consumption | <200mA | Display on, WiFi off |
| Boot Time | <3 seconds | To first display update |
---
## Future Enhancements
### Phase 6 Additions (Optional)
1. **IMU Integration**
- Use onboard QMI8658 accelerometer/gyroscope
- Display tilt/orientation
- Shake detection for screen wake
2. **WiFi Logging**
- Log automotive data to MQTT broker
- Remote monitoring via web interface
- Data analytics and trend visualization
3. **TF Card Data Logging**
- Record all received packets to SD card
- CSV export for analysis
- Playback mode for testing
4. **Multiple Display Modes**
- Mode 1: All sensors (current design)
- Mode 2: Large gear + battery only
- Mode 3: Temperature gauges only
- Button/touch to cycle modes
5. **OTA Updates**
- Wireless firmware updates
- Version synchronization with Controller A
---
## Common Issues & Troubleshooting
### Display Not Working
- Check SPI pin configuration matches board schematic
- Verify display voltage (should be 3.3V logic)
- Test with simple `Arduino_GFX` examples first
### No UART Data Received
- Verify baud rate matches (115200)
- Check TX/RX connections (TX→RX, not TX→TX)
- Use Serial Monitor to see reception debug messages
- Test with UART loopback (short TX to RX on Controller B)
### Corrupted Display
- Reduce SPI frequency (try 40MHz instead of 80MHz)
- Check power supply stability
- Verify PSRAM configuration
### High Power Consumption
- Disable WiFi if not needed: `WiFi.mode(WIFI_OFF)`
- Reduce display brightness
- Lower display refresh rate
- Enable sleep mode when idle
---
## References
- **Waveshare Product Page**: https://www.waveshare.com/esp32-s3-lcd-1.3.htm
- **Waveshare Wiki**: https://www.waveshare.com/wiki/ESP32-S3-LCD-1.3
- **ESP32-S3 Datasheet**: https://www.espressif.com/sites/default/files/documentation/esp32-s3_datasheet_en.pdf
- **ST7789VW Datasheet**: Sitronix display controller documentation
- **LVGL Documentation**: https://docs.lvgl.io/8.4/
- **Controller A Project**: `../ESP32-S3-Touch-LCD-5B/`
---
## Revision History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | 2025-11-08 | Claude | Initial implementation guide |
---
**Project Status**: 📝 Planning Phase
**Next Step**: Create PlatformIO project and implement Phase 1 (Display Setup)
-318
View File
@@ -1,318 +0,0 @@
# Project File Structure and Purpose
## Overview
This document explains what each file does and why it's in its location.
---
## Source Files (`src/`)
### `src/main.cpp` ⭐ Main Application Entry Point
**Purpose**: Application coordinator and main entry point
**Responsibilities**:
- Initialize serial communication
- Call hardware initialization (`DisplayInit::init()`)
- Load SquareLine Studio UI (`ui_init()`)
- Create FreeRTOS tasks
- Main loop (can be used for data processing, UI updates, etc.)
**What it does NOT do**:
- ❌ Direct hardware control (that's in modules)
- ❌ Drawing graphics (that's in `include/ui/`)
- ❌ LVGL configuration (that's in `lv_conf.h`)
**Typical flow**:
```cpp
setup() {
Serial.begin() // Start serial
DisplayInit::init() // Initialize display hardware
ui_init() // Load SquareLine UI
xTaskCreate() // Start LVGL task
}
loop() {
// Your application logic here
// Update UI with data
// Handle events
}
```
---
### `src/display_init.cpp` 🖥️ Display Hardware Driver
**Purpose**: Hardware-specific display initialization and control
**Responsibilities**:
- Initialize LovyanGFX display driver
- Configure ST7789 display controller
- Configure SPI bus (pins, speed)
- Initialize LVGL graphics library
- Provide display buffer to LVGL
- Handle LVGL flush callbacks
- Provide brightness control functions
**What it does NOT do**:
- ❌ Draw UI elements (that's LVGL's job via `include/ui/`)
- ❌ Show test patterns (removed - UI only from SquareLine)
- ❌ Handle application logic (that's in `main.cpp`)
**Key functions**:
```cpp
bool init() // Initialize display hardware + LVGL
void update() // Update LVGL tick and handle tasks
void setBrightness(uint8_t) // Control backlight brightness
uint8_t getBrightness() // Get current brightness
```
**This file is in `src/` because**:
- It contains implementation code (`.cpp`)
- It's a hardware abstraction layer
- It needs to access hardware-specific display instance
---
### `src/main_minimal.cpp.bak` 🔧 Backup Test File
**Purpose**: Minimal test code for hardware debugging
**Status**: Backup file (not compiled)
**Use case**: If you need to test basic hardware without UI/LVGL
To use it:
```bash
mv src/main.cpp src/main_full.cpp
mv src/main_minimal.cpp.bak src/main.cpp
pio run --target upload
```
---
## Header Files (`include/`)
### `include/modules/display_init.h` 📋 Display Module Interface
**Purpose**: Public interface for display initialization module
**Contains**:
- Function declarations for `DisplayInit` namespace
- Forward declarations for LVGL types
- DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_RADIUS defines
**This file is in `include/` because**:
- Header files belong in `include/`
- Can be included by other modules
- Provides public API
**Used by**: `main.cpp` and any module that needs display control
---
### `include/protocol/automotive_data.h` 📡 UART Protocol Definition
**Purpose**: Define UART packet structure for Controller A ↔ Controller B communication
**Contains**:
- `automotive_data_t` structure
- `uart_packet_t` structure
- Checksum functions
- Packet validation functions
**Status**: Ready for Phase 2 (UART reception)
**This file is in `include/protocol/` because**:
- It's a shared protocol definition
- Will be used by both Controller A and B
- Separates communication protocol from implementation
---
### `include/config/lv_conf.h` ⚙️ LVGL Configuration
**Purpose**: Configure LVGL library settings
**Contains**:
- Color depth (RGB565)
- Memory allocation (64KB heap)
- Enabled widgets (Arc, Label, Meter, etc.)
- Font settings
- Performance options
**This file is in `include/config/` because**:
- LVGL requires `lv_conf.h` in include path
- Separates configuration from code
- Easy to modify LVGL settings
**Configured via**: `platformio.ini` with `-I include/config`
---
## SquareLine Studio UI (`include/ui/`)
### Why is the UI in `include/ui/` and not `src/`?
**Reason**: SquareLine Studio exports contain both `.h` and `.c` files
**Structure**:
```
include/ui/
├── ui.h # Main UI header (declarations)
├── ui.c # Main UI implementation
├── ui_helpers.h/.c # Helper functions
├── ui_events.h # Event handler declarations
├── screens/
│ ├── ui_Home_Screen.h # Screen headers
│ └── ui_Home_Screen.c # Screen implementations
├── components/ # Custom components
└── fonts/ # Custom fonts
```
**Why this works**:
- PlatformIO's `build_src_filter` includes `+<../include/ui/*>`
- This tells the compiler to build `.c` files from `include/ui/`
- Headers are naturally in the include path
**Configured in**: `platformio.ini` line 50:
```ini
build_src_filter = +<*> +<modules/*> +<../include/ui/*> +<../include/display/*>
```
---
## Configuration Files (Root)
### `platformio.ini` ⚙️ Build Configuration
**Purpose**: Configure PlatformIO build system
**Contains**:
- Board selection
- Platform version
- Build flags (includes, defines)
- Library dependencies
- Upload settings
- Source file filters
---
### `lv_conf.h` (Removed - Moved to `include/config/`)
Previously at project root, now in `include/config/lv_conf.h`
---
## Documentation Files (Root)
All `.md` files in project root:
- `README.md` - Project overview
- `PROJECT_STRUCTURE.md` - Detailed structure
- `PIN_CONFIG.md` - Pin configuration
- `PINS_VERIFIED.md` - Verified pins from demo
- `TROUBLESHOOTING.md` - Debug guide
- `SQUARELINE_UI_GUIDE.md` - UI integration guide
- `BRIGHTNESS_CONTROL.md` - Brightness control guide
- `FILE_STRUCTURE.md` - This file
---
## Module Organization Pattern
### Current Modules
```
include/modules/ # Module headers (public interfaces)
└── display_init.h
src/ # Module implementations
└── display_init.cpp
```
### Future Modules (Phase 2+)
```
include/modules/
├── display_init.h
├── uart_receiver.h # UART data reception
├── data_validator.h # Packet validation
└── settings_manager.h # NVS settings
src/
├── display_init.cpp
├── uart_receiver.cpp
├── data_validator.cpp
└── settings_manager.cpp
```
---
## Build Process Flow
1. **PlatformIO reads** `platformio.ini`
2. **Compiler includes**:
- `include/`
- `include/config/`
- `include/modules/`
- `include/protocol/`
- `include/ui/`
- `src/`
3. **Compiler builds**:
- `src/*.cpp` (main, display_init)
- `include/ui/*.c` (SquareLine UI files)
4. **Linker combines** all object files
5. **Upload** firmware to ESP32-S3
---
## Key Principles
### ✅ Good Practices
1. **Separation of concerns**:
- Hardware drivers in `src/display_init.cpp`
- UI design in `include/ui/` (from SquareLine)
- App logic in `src/main.cpp`
2. **Headers in `include/`, implementations in `src/`**:
- Exception: SquareLine UI has both in `include/ui/`
3. **No graphics in hardware drivers**:
- `display_init.cpp` only initializes hardware
- UI comes from SquareLine Studio
4. **Configuration in `include/config/`**:
- Separates config from code
- Easy to modify
### ❌ What to Avoid
1. ❌ Drawing UI in `display_init.cpp`
2. ❌ Hardware access in `main.cpp` (use modules)
3. ❌ Mixing UI design with hardware code
4. ❌ Hardcoding settings (use config files)
---
## Summary Table
| File/Folder | Purpose | Type | Built? |
|-------------|---------|------|--------|
| `src/main.cpp` | Application entry point | C++ | ✅ |
| `src/display_init.cpp` | Display hardware driver | C++ | ✅ |
| `include/modules/display_init.h` | Display module interface | Header | No |
| `include/config/lv_conf.h` | LVGL configuration | Header | No |
| `include/protocol/automotive_data.h` | UART protocol | Header | No |
| `include/ui/*.c` | SquareLine UI implementation | C | ✅ |
| `include/ui/*.h` | SquareLine UI headers | Header | No |
| `platformio.ini` | Build configuration | Config | No |
| `*.md` | Documentation | Markdown | No |
---
**Last Updated**: 2025-11-08
**Status**: Clean structure, no test patterns, UI-only from SquareLine
-76
View File
@@ -1,76 +0,0 @@
# ✅ VERIFIED Pin Configuration for ESP32-S3-LCD-1.3
## Official Pin Mapping (from Waveshare Demo Code)
**Source**: `ESP32-S3-LCD-1.3-Demo/Arduino/libraries/TFT_eSPI/User_Setup.h`
### ST7789 Display Pins
```cpp
SCLK (SPI Clock): GPIO 40
MOSI (SPI Data Out): GPIO 41
MISO (SPI Data In): GPIO -1 (not connected)
CS (Chip Select): GPIO 39
DC (Data/Command): GPIO 38
RST (Reset): GPIO 42
BL (Backlight): GPIO 20 ⭐
```
### Updated in Code
File: `src/display_init.cpp`
- **Lines 23-26**: SPI bus pins (SCLK, MOSI, DC)
- **Lines 40-41**: Panel control (CS, RST)
- **Line 64**: Backlight (BL) - **GPIO 20**
## Display Specifications
- **Driver**: ST7789VW (ST7789_DRIVER in TFT_eSPI)
- **Resolution**: 240×240 pixels
- **Color**: RGB565 (262K colors)
- **Color Order**: TFT_RGB (Red-Green-Blue)
- **Inversion**: TFT_INVERSION_ON
- **SPI Frequency**: 80MHz (write), 16MHz (read)
## Additional Hardware
- **IMU Sensor**: QMI8658 (6-axis, I2C)
- **SD Card**: TF card slot support
- **USB**: CH343P USB-to-UART chip
- **Power**: USB-C + battery connector
## Verification Steps
1. ✅ Found official Waveshare demo code
2. ✅ Located `User_Setup.h` with TFT_eSPI configuration
3. ✅ Found backlight definition in example code (`LCD_BL = 20`)
4. ✅ Updated `src/display_init.cpp` with correct pins
5. ✅ Build successful
6. ✅ Upload successful
## Next Steps
The firmware has been uploaded with the correct pin configuration. The display should now:
1. **Light up** (backlight on GPIO 20 is now correct)
2. **Show SquareLine Studio UI**
3. **Display `uic_Home_LBL` label**
4. **Update every second** with uptime and heap info
If the display still doesn't work, check:
- Power supply (5V USB)
- Physical connections
- Try pressing RESET button on board
## References
- Demo code location: `ESP32-S3-LCD-1.3-Demo/Arduino/`
- TFT_eSPI setup: `ESP32-S3-LCD-1.3-Demo/Arduino/libraries/TFT_eSPI/User_Setup.h` lines 207-211
- Backlight example: `ESP32-S3-LCD-1.3-Demo/Arduino/examples/02_SD_Video/SD_Video_Prism/SD_Video_Prism.ino` line 31
---
**Verified**: 2025-11-08
**Status**: ✅ Correct pins confirmed from official Waveshare demo
**Uploaded**: Firmware with correct configuration uploaded successfully
-218
View File
@@ -1,218 +0,0 @@
# Pin Configuration Guide
**⚠️ IMPORTANT**: The pin assignments in `src/display_init.cpp` are educated guesses based on common ESP32-S3-LCD-1.3 configurations. You **MUST** verify these against your actual board schematic before uploading firmware.
## Current Pin Assignments
These pins are configured in `src/display_init.cpp` in the `LGFX` class constructor:
### SPI Display Pins (ST7789VW)
```cpp
cfg.pin_sclk = 10; // SPI Clock
cfg.pin_mosi = 11; // SPI MOSI (Master Out Slave In)
cfg.pin_dc = 8; // Data/Command select
cfg.pin_cs = 9; // Chip Select
cfg.pin_rst = 14; // Reset
cfg.pin_bl = 15; // Backlight PWM control
```
### Future UART Pins (Phase 2)
Defined in `platformio.ini` build flags:
```ini
-DUART_RX_PIN=44 // UART receive from Controller A
-DUART_TX_PIN=43 // UART transmit (unused in RX-only mode)
```
## How to Verify Pin Assignments
### Method 1: Check Waveshare Wiki
1. Visit: https://www.waveshare.com/wiki/ESP32-S3-LCD-1.3
2. Look for "Pin Mapping" or "Schematic" section
3. Find ST7789 display connections
4. Update `src/display_init.cpp` with correct pins
### Method 2: Check Board Schematic
If you have the schematic PDF:
1. Look for ST7789 or display controller section
2. Trace ESP32-S3 GPIO connections to:
- SPI SCLK (Serial Clock)
- SPI MOSI (Data)
- DC (Data/Command)
- CS (Chip Select)
- RST (Reset)
- BL (Backlight)
3. Update pins in code
### Method 3: Try Example Code
1. Download Waveshare's Arduino examples
2. Find display initialization code
3. Extract pin numbers from their configuration
4. Apply to this project
## Common ESP32-S3-LCD Variants
Different vendors may use different pinouts. Here are some known configurations:
### ✅ VERIFIED - Waveshare ESP32-S3-LCD-1.3 (Official from Demo Code)
```cpp
SCLK: GPIO 40 ✅ VERIFIED
MOSI: GPIO 41 ✅ VERIFIED
MISO: GPIO -1 (not connected)
DC: GPIO 38 ✅ VERIFIED
CS: GPIO 39 ✅ VERIFIED
RST: GPIO 42 ✅ VERIFIED
BL: GPIO 20 ✅ VERIFIED - From official demo code!
```
**Source**: ESP32-S3-LCD-1.3-Demo/Arduino/libraries/TFT_eSPI/User_Setup.h
**Status**: This configuration has been applied to the code and uploaded.
### Alternative Configuration B (if above doesn't work)
```cpp
SCLK: GPIO 12
MOSI: GPIO 11
DC: GPIO 8
CS: GPIO 9
RST: GPIO 14
BL: GPIO 2
```
### Alternative Configuration C
```cpp
SCLK: GPIO 18
MOSI: GPIO 23
DC: GPIO 27
CS: GPIO 5
RST: GPIO 33
BL: GPIO 32
```
## Testing Pin Configuration
### Quick Test Procedure
1. **Upload firmware with current pins**
2. **Check serial monitor for**:
```
[DisplayInit] Initializing display...
[DisplayInit] Display initialized: 240x240
```
3. **Visual check**:
- Display should show black circle outline
- Text should read "ESP32-S3", "LCD 1.3", "Phase 1"
- If blank/corrupted, pins are likely wrong
### Debugging Display Issues
#### Symptom: Completely Blank Display
**Possible causes**:
- Wrong CS (Chip Select) pin
- Wrong RST (Reset) pin
- Wrong BL (Backlight) pin
- Power supply issue
**Try**:
1. Verify backlight pin (should see faint glow if correct)
2. Check reset pin (incorrect reset = no init)
3. Verify chip select (incorrect CS = no communication)
#### Symptom: Garbled/Random Pixels
**Possible causes**:
- Wrong SCLK or MOSI pins
- Wrong DC (Data/Command) pin
- SPI frequency too high
**Try**:
1. Reduce SPI frequency in `display_init.cpp`:
```cpp
cfg.freq_write = 40000000; // Try 40MHz instead of 80MHz
```
2. Verify SCLK and MOSI pins
3. Check DC pin assignment
#### Symptom: Display Works but Backlight Off
**Possible causes**:
- Wrong BL pin
- Backlight polarity inverted
**Try**:
1. Change backlight pin
2. Toggle invert flag:
```cpp
cfg.invert = true; // Try opposite value
```
## Updating Pin Configuration
To change pins, edit `src/display_init.cpp`:
```cpp
// Around line 20-30, in LGFX constructor
// SPI bus pins
cfg.pin_sclk = YOUR_SCLK_PIN;
cfg.pin_mosi = YOUR_MOSI_PIN;
cfg.pin_dc = YOUR_DC_PIN;
// Panel control pins
cfg.pin_cs = YOUR_CS_PIN;
cfg.pin_rst = YOUR_RST_PIN;
// Backlight pin
cfg.pin_bl = YOUR_BL_PIN;
```
Save, rebuild, and upload:
```bash
pio run --target upload
```
## GPIO Constraints on ESP32-S3
### Safe GPIOs for General Use
These are generally safe for SPI/display:
- GPIO 1-21 (most are OK)
- GPIO 33-48 (some restrictions)
### GPIOs to AVOID
- **GPIO 0**: Boot mode select (use with caution)
- **GPIO 3**: JTAG (conflicts if debugging enabled)
- **GPIO 19-20**: USB D-/D+ (if using USB)
- **GPIO 26-32**: Used for PSRAM on some modules
- **GPIO 45-46**: Boot strapping pins
## References
- **ESP32-S3 Datasheet**: https://www.espressif.com/sites/default/files/documentation/esp32-s3_datasheet_en.pdf (Table: GPIO Matrix and IO MUX)
- **Waveshare Wiki**: https://www.waveshare.com/wiki/ESP32-S3-LCD-1.3
- **LovyanGFX Examples**: https://github.com/lovyan03/LovyanGFX/tree/master/examples
## Help Needed?
If you successfully identify the correct pins for your board, please consider:
1. Updating this file with confirmed working configuration
2. Adding your board variant to "Common ESP32-S3-LCD Variants" section
3. Documenting any special notes or gotchas
---
**Last Updated**: 2025-11-08
**Status**: Pins need verification against actual hardware
-232
View File
@@ -1,232 +0,0 @@
# ESP32-S3-LCD-1.3 Pin Finder Guide
## Problem: No Serial Output & Blank Display
Since we can't see serial output and the display is blank, we need to systematically find the correct pins.
## Step 1: Get Official Pin Configuration
### Download Waveshare Demo Code
```bash
cd ~
wget https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/ESP32-S3-LCD-1.3-Demo.zip
unzip ESP32-S3-LCD-1.3-Demo.zip
cd ESP32-S3-LCD-1.3-Demo
```
### Find Pin Definitions
Look for files like:
- `User_Setup.h` (TFT_eSPI configuration)
- `*.ino` files with pin definitions
- README files with pin mappings
**Search for these keywords:**
```bash
grep -r "TFT_MOSI\|TFT_SCLK\|TFT_CS\|TFT_DC\|TFT_RST\|TFT_BL" .
grep -r "pin_sclk\|pin_mosi\|pin_dc\|pin_cs\|pin_rst\|pin_bl" .
grep -r "GPIO" . | grep -E "(SCLK|MOSI|DC|CS|RST|BL|Backlight)"
```
## Step 2: Check Schematic
Download the schematic:
```bash
wget https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/ESP32S3_1.3inch.pdf
```
Open with a PDF viewer and look for:
- ST7789 chip connections
- ESP32-S3 GPIO labels
- SPI bus connections
- Backlight circuit
## Step 3: Test Pin Configurations
Based on similar Waveshare ESP32-S3-LCD boards, try these configurations:
### Configuration 1: ESP32-S3-LCD-1.28 Style (Current)
```cpp
SCLK: GPIO 10
MOSI: GPIO 11
CS: GPIO 9
DC: GPIO 8
RST: GPIO 14
BL: GPIO 2
```
### Configuration 2: ESP32-S3-LCD-1.47 Style
```cpp
SCLK: GPIO 40
MOSI: GPIO 45
CS: GPIO 42
DC: GPIO 41
RST: GPIO 39
BL: GPIO 48
```
### Configuration 3: Alternative Common Pins
```cpp
SCLK: GPIO 18
MOSI: GPIO 23
CS: GPIO 5
DC: GPIO 27
RST: GPIO 33
BL: GPIO 32
```
## Step 4: Update Pin Configuration
Edit `src/display_init.cpp` (around lines 23-41 and 64):
```cpp
// SPI bus pins
cfg.pin_sclk = XX; // Replace XX with actual GPIO
cfg.pin_mosi = XX;
cfg.pin_dc = XX;
// Panel control
cfg.pin_cs = XX;
cfg.pin_rst = XX;
// Backlight
cfg.pin_bl = XX;
```
## Step 5: Rebuild and Test
```bash
pio run --target upload
```
**Visual test**: Does the display light up? Even briefly?
- **Yes, backlight works!** → Backlight pin is correct
- **No backlight** → Wrong backlight pin, try another
## Step 6: Backlight-Only Test
If you want to test just the backlight without the full display code:
Edit `src/main.cpp`, in `setup()` add:
```cpp
// Direct backlight test
pinMode(2, OUTPUT); // Try GPIO 2
digitalWrite(2, HIGH);
delay(2000);
pinMode(48, OUTPUT); // Try GPIO 48
digitalWrite(48, HIGH);
delay(2000);
pinMode(15, OUTPUT); // Try GPIO 15
digitalWrite(15, HIGH);
delay(2000);
```
Upload and watch the display - when it lights up, you've found the backlight pin!
## Step 7: Serial Output Debug
### Check if Board is Even Running
The board should have an onboard LED. Try this in `loop()`:
```cpp
pinMode(38, OUTPUT); // Try common LED pins
for(int i = 0; i < 10; i++) {
digitalWrite(38, HIGH);
delay(200);
digitalWrite(38, LOW);
delay(200);
}
```
Try GPIO: 2, 38, 48, 47, 21
If you see blinking, the board is running but serial isn't working.
### Serial Port Issues
The board uses **CH343P USB-UART chip**. Check:
1. **Driver installed?**
```bash
lsusb | grep 1A86
```
Should show: `1a86:55d3 QinHeng Electronics`
2. **Permission?**
```bash
ls -l /dev/ttyACM0
sudo chmod 666 /dev/ttyACM0
```
3. **Try different tool:**
```bash
# Try screen
screen /dev/ttyACM0 115200
# Try minicom
minicom -D /dev/ttyACM0 -b 115200
# Try cu
cu -l /dev/ttyACM0 -s 115200
```
4. **Check dmesg:**
```bash
dmesg | tail -50 | grep tty
```
Should show USB device attachment.
## Step 8: Reset and Retry
After changing pins:
1. Power cycle the board (unplug USB)
2. Rebuild: `pio run`
3. Upload: `pio run --target upload`
4. Wait 5 seconds
5. Check display
## Known Working Configurations
Once you find the working pins, please add them here:
```
Working Configuration for ESP32-S3-LCD-1.3:
SCLK: GPIO __
MOSI: GPIO __
CS: GPIO __
DC: GPIO __
RST: GPIO __
BL: GPIO __
Verified by: [Your name]
Date: [Date]
Board Rev: [If known]
```
## Quick Reference: Waveshare Board Pin Patterns
| Board Model | SCLK | MOSI | CS | DC | RST | BL |
|-------------|------|------|----|----|-----|-----|
| ESP32-S3-LCD-1.28 | 10 | 11 | 9 | 8 | 14 | 2 |
| ESP32-S3-LCD-1.47 | 40 | 45 | 42 | 41 | 39 | 48 |
| ESP32-S3-LCD-1.69 | ? | ? | ? | ? | ? | ? |
| ESP32-S3-LCD-1.3 | **?** | **?** | **?** | **?** | **?** | **?** |
## Contact Support
If nothing works:
- Email Waveshare: support@waveshare.com
- Wiki: https://www.waveshare.com/wiki/ESP32-S3-LCD-1.3
- Forum: https://www.waveshare.com/forums/
Ask specifically for the GPIO pin mappings for the ST7789 display.
---
**Remember**: The most critical pin is the **backlight (BL)**. Without it, the display will appear blank even if everything else is correct!
-202
View File
@@ -1,202 +0,0 @@
# ESP32-S3-LCD-1.3 Project Structure
## Directory Layout
```
ESP32-S3-LCD-1.3/
├── .docs/
│ └── ESP32-S3-LCD-1.3-Implementation-Guide.md # Full implementation guide
│
├── include/
│ ├── config/
│ │ └── lv_conf.h # LVGL 8.4.0 configuration
│ ├── display/
│ │ └── (future display-specific headers)
│ ├── modules/
│ │ └── display_init.h # Display initialization interface
│ ├── protocol/
│ │ └── automotive_data.h # UART protocol (Phase 2+)
│ └── ui/
│ ├── components/
│ │ └── ui_comp_hook.c # SquareLine Studio components
│ ├── screens/
│ │ ├── ui_Home_Screen.c # Home screen from SquareLine
│ │ └── ui_Home_Screen.h
│ ├── ui.c # SquareLine main UI file
│ ├── ui.h
│ ├── ui_events.h # UI event handlers
│ ├── ui_helpers.c # UI utility functions
│ └── ui_helpers.h
│
├── src/
│ ├── display_init.cpp # LovyanGFX implementation
│ └── main.cpp # Main application (Phase 1)
│
├── lib/ # Custom libraries
├── test/ # Unit tests
│
├── .gitignore # Git ignore rules
├── platformio.ini # PlatformIO configuration
├── PIN_CONFIG.md # ⚠️ Pin verification guide
├── PROJECT_STRUCTURE.md # This file
└── README.md # Main documentation
```
## Include Path Configuration
The `platformio.ini` is configured with the following include paths (in order):
```ini
-I include
-I include/config # For lv_conf.h
-I include/display # For display-specific headers
-I include/modules # For display_init.h, uart_receiver.h, etc.
-I include/protocol # For automotive_data.h
-I include/ui # For SquareLine Studio UI files
-I src # For source files
```
## Build Source Filter
The following source directories are included in the build:
```ini
build_src_filter = +<*> +<modules/*> +<../include/ui/*> +<../include/display/*>
```
This ensures:
- All files in `src/` are compiled
- Module implementations in `src/modules/` are compiled (future)
- SquareLine UI files in `include/ui/` are compiled (.c files)
- Display files in `include/display/` are compiled (future)
## File Organization Guidelines
### Phase 1 Files (Current)
- **src/main.cpp**: Main application entry point
- **src/display_init.cpp**: Display hardware initialization
- **include/modules/display_init.h**: Display interface
- **include/config/lv_conf.h**: LVGL configuration
- **include/ui/***: SquareLine Studio exported UI (optional for Phase 1)
### Future Phase Files
#### Phase 2: UART Reception
- **src/uart_receiver.cpp**: UART data reception and parsing
- **include/modules/uart_receiver.h**: UART interface
- **include/protocol/automotive_data.h**: Protocol definitions (already created)
#### Phase 3: Dashboard UI
- **src/ui_renderer.cpp**: Dashboard rendering logic
- **include/modules/ui_renderer.h**: UI rendering interface
- Update SquareLine Studio UI in `include/ui/`
#### Phase 4: Validation
- **src/data_validator.cpp**: Packet validation
- **include/modules/data_validator.h**: Validator interface
#### Phase 5: Settings
- **src/settings_manager.cpp**: Persistent settings (NVS)
- **include/modules/settings_manager.h**: Settings interface
## SquareLine Studio Integration
The `include/ui/` folder contains exported UI files from SquareLine Studio:
- **ui.c/ui.h**: Main UI initialization
- **ui_helpers.c/ui_helpers.h**: Helper functions for UI creation
- **ui_events.h**: Event handler declarations
- **screens/**: Individual screen implementations
- **components/**: Reusable UI components
### Using SquareLine UI in main.cpp
To use the SquareLine UI instead of the Phase 1 test UI:
```cpp
#include "ui/ui.h" // Include SquareLine UI
void setup() {
// ... display init ...
// Initialize SquareLine UI
ui_init();
// ... start LVGL task ...
}
```
## Configuration Files
### platformio.ini
- Platform: `espressif32@^6.0.0`
- Board: `esp32-s3-devkitc-1`
- Framework: Arduino
- PSRAM: Enabled (OPI mode)
- Build type: Release
- C++ standard: gnu++17
### lv_conf.h
- Location: `include/config/lv_conf.h`
- LVGL version: 8.4.0
- Color depth: RGB565 (16-bit)
- Memory: 64KB heap
- Theme: Dark theme enabled
- Widgets: Arc, Label, LED, Meter, etc.
## Consistency with Controller A
This structure mirrors the ESP32-S3-Touch-LCD-5B (Controller A) project:
✅ Same include path structure
✅ Same build source filter pattern
✅ Same LVGL configuration location (`include/config/lv_conf.h`)
✅ Same module organization pattern
✅ Same protocol header location
## Build Verification
To verify the project structure is correct:
```bash
# Clean build
pio run --target clean
# Build project
pio run
# Should compile successfully with all include paths resolved
```
Expected output:
```
Building in release mode
Compiling .pio/build/.../src/main.cpp.o
Compiling .pio/build/.../src/display_init.cpp.o
Compiling .pio/build/.../ui/ui.c.o
...
Linking .pio/build/.../firmware.elf
Building .pio/build/.../firmware.bin
```
## Troubleshooting
### Include path issues
If you see errors like `fatal error: lv_conf.h: No such file or directory`:
- Verify `lv_conf.h` is in `include/config/`
- Check `-I include/config` is in `build_flags`
### UI files not compiling
If SquareLine UI files aren't being compiled:
- Check `build_src_filter` includes `+<../include/ui/*>`
- Verify `.c` files exist in `include/ui/`
### Module header not found
If module headers aren't found:
- Verify headers are in `include/modules/`
- Check `-I include/modules` is in `build_flags`
---
**Last Updated**: 2025-11-08
**Project Phase**: Phase 1 - Display Setup ✅
-143
View File
@@ -1,143 +0,0 @@
# Quick Brightness Control Example
## Try It Now!
### Option 1: Set a Specific Brightness Level
Add this to your `setup()` in `main.cpp`, right after `ui_init()`:
```cpp
void setup() {
// ... existing code ...
ui_init();
Serial.println("[UI] SquareLine Studio UI initialized");
// Set brightness to 25% (dim)
DisplayInit::setBrightness(64);
Serial.println("Brightness set to 25%");
// ... rest of setup ...
}
```
**Brightness Values:**
- `32` = Very dim (12.5%)
- `64` = Dim (25%)
- `128` = Normal (50%) - current default
- `192` = Bright (75%)
- `255` = Maximum (100%)
---
### Option 2: Automatic Dimming Example
Replace your current `loop()` with this to see automatic dimming:
```cpp
void loop() {
static uint32_t last_update = 0;
static uint32_t loop_count = 0;
static bool is_bright = true;
// Toggle brightness every 3 seconds
if (millis() - last_update > 3000) {
last_update = millis();
if (is_bright) {
DisplayInit::setBrightness(50); // Very dim
Serial.println("Dimmed to 20%");
} else {
DisplayInit::setBrightness(255); // Max brightness
Serial.println("Brightened to 100%");
}
is_bright = !is_bright;
loop_count = 0;
}
loop_count++;
delay(10);
}
```
Upload this and watch the display brightness toggle every 3 seconds!
---
### Option 3: Smooth Fade Example
```cpp
void loop() {
static uint32_t last_fade = 0;
static int brightness = 255;
static int direction = -5; // Start by fading out
// Update brightness every 50ms for smooth fade
if (millis() - last_fade > 50) {
last_fade = millis();
brightness += direction;
// Reverse direction at limits
if (brightness <= 50) {
brightness = 50;
direction = 5; // Start fading in
} else if (brightness >= 255) {
brightness = 255;
direction = -5; // Start fading out
}
DisplayInit::setBrightness(brightness);
}
delay(10);
}
```
This creates a smooth breathing effect!
---
## Quick Commands to Copy-Paste
### Set to 25% brightness:
```cpp
DisplayInit::setBrightness(64);
```
### Set to 50% brightness (default):
```cpp
DisplayInit::setBrightness(128);
```
### Set to max brightness:
```cpp
DisplayInit::setBrightness(255);
```
### Get current brightness:
```cpp
uint8_t current = DisplayInit::getBrightness();
Serial.printf("Current brightness: %d\n", current);
```
---
## Build and Upload
After making changes:
```bash
pio run --target upload
```
Or use the helper script:
```bash
./upload_and_monitor.sh
```
---
**See `BRIGHTNESS_CONTROL.md` for more detailed examples and use cases!**
-226
View File
@@ -1,226 +0,0 @@
# SquareLine Studio UI Integration Guide
## ✅ Current Status
Your SquareLine Studio UI is now **fully integrated and displaying** on the ESP32-S3-LCD-1.3!
### What's Showing Now
The display shows your **ui_Home_Screen** with:
- **ui_Home_LBL** label showing "Home Screen" (default text from SquareLine)
- 240×240 pixel layout
- Centered flex container
## UI Structure
From your SquareLine Studio export (`include/ui/screens/ui_Home_Screen.c`):
```
ui_Home_Screen (screen)
└── ui_Main_Container (240×240 container, centered)
└── ui_Home_LBL (label, centered)
```
### Available UI Objects
You can access these objects in your code:
```cpp
extern lv_obj_t * ui_Home_Screen; // Main screen
extern lv_obj_t * ui_Main_Container; // 240×240 container
extern lv_obj_t * ui_Home_LBL; // Label widget
// Alternative pointers (same objects)
extern lv_obj_t * uic_Home_Screen;
extern lv_obj_t * uic_Main_Container;
extern lv_obj_t * uic_Home_LBL;
```
## How to Update UI Dynamically
### Update the Label Text
In `src/main.cpp`, add to the `loop()` function:
```cpp
void loop() {
static uint32_t last_update = 0;
if (millis() - last_update > 1000) {
last_update = millis();
// Update label with dynamic content
if (uic_Home_LBL != NULL) {
char text[64];
snprintf(text, sizeof(text),
"Uptime: %lus\nHeap: %d",
millis() / 1000,
ESP.getFreeHeap());
lv_label_set_text(uic_Home_LBL, text);
}
}
delay(10);
}
```
### Change Label Color
```cpp
lv_obj_set_style_text_color(uic_Home_LBL, lv_color_hex(0x00FF00), 0); // Green
```
### Change Label Font Size
```cpp
lv_obj_set_style_text_font(uic_Home_LBL, &lv_font_montserrat_24, 0);
```
## Adding More Widgets in SquareLine Studio
1. **Edit in SquareLine Studio**
- Open your ESP32-S3-LCD-1.3 project
- Add widgets (buttons, labels, arcs, meters, etc.)
- Configure properties and events
2. **Export UI Files**
- File → Export → Create Template Project
- Export to: `include/ui/`
3. **Rebuild**
```bash
pio run --target upload
```
## Example: Automotive Dashboard UI
For your Phase 3 automotive dashboard, you could add in SquareLine:
### Widgets to Add
1. **Large Label** for gear position (P/R/N/D)
2. **Arc Meters** for temperatures (3 arcs)
3. **Small Label** for battery voltage
4. **Panel/Label** for fault codes
### Update Strategy
```cpp
void updateAutomotiveUI(const automotive_data_t* data) {
// Update gear position
lv_label_set_text(ui_GearLabel, gear_to_string(data->gear_position));
// Update gearbox temp arc
lv_arc_set_value(ui_GearboxTempArc, (int)data->gearbox_temp_c);
// Update battery voltage
char voltage[16];
snprintf(voltage, sizeof(voltage), "%.2fV", data->battery_voltage_v);
lv_label_set_text(ui_BatteryLabel, voltage);
}
```
## Current UI File Locations
```
include/ui/
├── ui.h # Main UI header
├── ui.c # UI initialization
├── ui_helpers.h/.c # Helper functions
├── ui_events.h # Event handlers
├── screens/
│ ├── ui_Home_Screen.h # Home screen header
│ └── ui_Home_Screen.c # Home screen implementation
├── components/ # Custom components
└── fonts/ # Custom fonts (if any)
```
## Modifying SquareLine UI
### Option 1: Edit in SquareLine Studio (Recommended)
1. Open SquareLine Studio
2. Load your ESP32-S3-LCD-1.3 project
3. Make changes visually
4. Export and replace files in `include/ui/`
### Option 2: Edit Code Directly
You can manually edit `include/ui/screens/ui_Home_Screen.c`:
```cpp
void ui_Home_Screen_screen_init(void)
{
ui_Home_Screen = lv_obj_create(NULL);
// Add more widgets here
lv_obj_t * my_new_label = lv_label_create(ui_Main_Container);
lv_label_set_text(my_new_label, "Custom Label");
lv_obj_align(my_new_label, LV_ALIGN_BOTTOM_MID, 0, -10);
}
```
**Warning**: Manual changes will be lost if you re-export from SquareLine Studio!
## Screen Transitions (Multi-Screen Apps)
If you add multiple screens in SquareLine:
```cpp
// Load different screen
lv_scr_load(ui_SettingsScreen);
// Load with animation
lv_scr_load_anim(ui_SettingsScreen, LV_SCR_LOAD_ANIM_FADE_IN, 300, 0, false);
```
## Troubleshooting
### UI Not Showing / Blank Screen
Check initialization order in `main.cpp`:
1. `DisplayInit::init()` ← Must be first
2. `ui_init()` ← Loads SquareLine UI
3. Start LVGL task
4. Don't overwrite label text in loop unless intended
### Label Text Not Updating
Ensure you're using the correct pointer:
```cpp
if (uic_Home_LBL != NULL) { // ✅ Good
lv_label_set_text(uic_Home_LBL, "New text");
}
```
### Colors Look Wrong
Check color depth in `lv_conf.h`:
```cpp
#define LV_COLOR_DEPTH 16 // RGB565
```
SquareLine Studio exports for 16-bit color.
## Resources
- **SquareLine Studio Docs**: https://docs.squareline.io/
- **LVGL Documentation**: https://docs.lvgl.io/8.4/
- **LVGL Widgets**: https://docs.lvgl.io/8.4/widgets/index.html
## Next Steps for Phase 2 & 3
1. **Phase 2**: Add UART receiver module
2. **Phase 3**: Design automotive dashboard in SquareLine:
- Add gear position label (large font)
- Add 3 arc meters for temperatures
- Add battery voltage label
- Add fault code panel
3. Export and integrate
4. Update UI in `loop()` with UART data
---
**Current UI**: Showing "Home Screen" label
**Status**: ✅ SquareLine Studio UI fully integrated
**Last Updated**: 2025-11-08
-373
View File
@@ -1,373 +0,0 @@
# ESP32-S3-LCD-1.3 Troubleshooting Guide
## Issue: No Serial Output
### Solution: USB CDC Timing
The ESP32-S3 uses **USB CDC (native USB)** for serial communication. The code now includes proper USB CDC initialization:
```cpp
// Wait for USB CDC to be ready
while (!Serial && (millis() - start_wait < 3000)) {
delay(100);
}
```
### Quick Upload and Monitor
Use the helper script:
```bash
./upload_and_monitor.sh
```
Or manually:
```bash
pio run --target upload && sleep 2 && pio device monitor
```
**Important**: The 2-second delay after upload allows the ESP32-S3 to reset before monitoring starts.
### Verify Baud Rate Matches
Both are set to **115200 baud**:
- `platformio.ini`: `monitor_speed = 115200`
- `main.cpp`: `Serial.begin(115200)`
If you still see no output, try:
```bash
# Monitor with explicit baud rate
pio device monitor --baud 115200
# Or use screen/minicom
screen /dev/ttyACM0 115200
```
---
## Issue: Blank/Black Display - No Output
### Most Common Cause: Incorrect Backlight Pin
**Problem**: The display backlight is likely on GPIO **2**, not GPIO 15.
**Solution**: The code has been updated in `src/display_init.cpp` (line 64) to use:
```cpp
cfg.pin_bl = 2; // GPIO2 for Waveshare ESP32-S3-LCD boards
```
### Current Pin Configuration (Updated)
Based on similar Waveshare ESP32-S3-LCD boards (ESP32-S3-LCD-1.28):
```cpp
SCLK: GPIO 10 // SPI Clock
MOSI: GPIO 11 // SPI Data Out
MISO: GPIO 12 // SPI Data In (not used by display)
DC: GPIO 8 // Data/Command
CS: GPIO 9 // Chip Select
RST: GPIO 14 // Reset
BL: GPIO 2 // ⭐ BACKLIGHT (most critical for visibility!)
```
---
## Diagnostic Steps
### Step 1: Check Serial Output
Upload the firmware and monitor the serial port:
```bash
pio run --target upload && pio device monitor
```
**Expected output:**
```
=================================
ESP32-S3-LCD-1.3 - Controller B
Phase 1: Display Initialization
=================================
CPU Frequency: 240 MHz
Free Heap: 327680 bytes
[DisplayInit] Initializing display...
[DisplayInit] Display initialized: 240x240
[DisplayInit] LVGL initialized
[UI] Initializing SquareLine Studio UI...
[UI] SquareLine Studio UI initialized
[LVGL Task] Started on Core 1
[UI Debug] Checking SquareLine UI components:
ui_Home_Screen: 0x3fcXXXXX
ui_Main_Container: 0x3fcXXXXX
ui_Home_LBL: 0x3fcXXXXX
uic_Home_LBL: 0x3fcXXXXX
✓ uic_Home_LBL exists!
```
### Step 2: Check Physical Display
**What to look for:**
1. **Completely black screen** = Likely backlight issue (GPIO 2)
- Check backlight pin configuration
- Try toggling `cfg.invert` in backlight config
2. **Faint image visible when shining light on it** = Backlight is definitely off
- Backlight pin is wrong
- Try GPIO 2, GPIO 15, or GPIO 21
3. **White/colored static or noise** = Communication issue
- Check SCLK, MOSI, DC pins
- Reduce SPI frequency from 80MHz to 40MHz
4. **Partial display or corruption** = Timing/frequency issue
- Reduce SPI frequency
- Check power supply stability
### Step 3: Verify Backlight
Add this test code in `setup()` after `DisplayInit::init()`:
```cpp
// Test backlight directly
pinMode(2, OUTPUT);
digitalWrite(2, HIGH); // Turn on backlight
Serial.println("[Test] Backlight should be ON");
```
If the display lights up, GPIO 2 is correct!
### Step 4: Check LVGL Warnings
Monitor for these common LVGL issues:
```
[Warn] lv_tick_inc() is not called ✓ FIXED - tick handler implemented
[Error] lv_disp_flush_ready not called = Display flush callback issue
[Error] Out of memory = Reduce LVGL_MEM_SIZE in lv_conf.h
```
---
## Common Fixes
### Fix 1: Wrong Backlight Pin
**File**: `src/display_init.cpp` (line 64)
Try these pins in order:
```cpp
cfg.pin_bl = 2; // ⭐ Most likely
cfg.pin_bl = 15; // Alternative 1
cfg.pin_bl = 21; // Alternative 2
cfg.pin_bl = 45; // Alternative 3
```
### Fix 2: Inverted Backlight
**File**: `src/display_init.cpp` (line 65)
```cpp
cfg.invert = true; // Change from false to true
```
Some boards use inverted backlight control.
### Fix 3: Lower SPI Frequency
**File**: `src/display_init.cpp` (line 18)
```cpp
cfg.freq_write = 40000000; // Try 40MHz instead of 80MHz
```
### Fix 4: Display Color Inversion
**File**: `src/display_init.cpp` (line 52)
```cpp
cfg.invert = false; // Try toggling between true/false
```
### Fix 5: Display Rotation
**File**: `src/display_init.cpp` (line 102)
```cpp
display.setRotation(0); // Try 0, 1, 2, or 3
```
---
## Verification Tests
### Test 1: LovyanGFX Direct Draw (Before LVGL)
Add this in `DisplayInit::init()` after `display.init()`:
```cpp
// Test pattern - should show immediately
display.fillScreen(TFT_RED);
delay(1000);
display.fillScreen(TFT_GREEN);
delay(1000);
display.fillScreen(TFT_BLUE);
delay(1000);
display.fillScreen(TFT_WHITE);
delay(1000);
```
**If you see colors**: Display hardware works, issue is in LVGL integration.
**If still blank**: Display pin configuration is wrong.
### Test 2: Backlight PWM Test
```cpp
// Test backlight brightness control
for (int brightness = 0; brightness <= 255; brightness += 5) {
display.setBrightness(brightness);
delay(50);
}
```
**If brightness changes**: Backlight works!
**If no change**: Wrong backlight pin.
### Test 3: SPI Communication Test
Check if SPI is working:
```cpp
// In setup(), after display.init()
uint16_t id = display.readCommand16(0x04); // Read display ID
Serial.printf("[Test] Display ID: 0x%04X\n", id);
```
**Expected**: Should return ST7789 ID (0x7C89 or similar)
**If 0x0000 or 0xFFFF**: SPI communication failed (check SCLK, MOSI, CS pins)
---
## Pin Configuration Matrix
Try these configurations if the default doesn't work:
### Configuration A (Current - Waveshare Standard)
```cpp
SCLK=10, MOSI=11, DC=8, CS=9, RST=14, BL=2
```
### Configuration B (Alternative Backlight)
```cpp
SCLK=10, MOSI=11, DC=8, CS=9, RST=14, BL=15
```
### Configuration C (Different SPI Pins)
```cpp
SCLK=18, MOSI=23, DC=27, CS=5, RST=33, BL=2
```
### Configuration D (ESP32-S3-DevKit Standard)
```cpp
SCLK=12, MOSI=11, DC=13, CS=10, RST=9, BL=2
```
---
## Serial Debug Commands
Add these to your code for runtime diagnostics:
```cpp
// In loop(), check for serial commands
if (Serial.available()) {
char cmd = Serial.read();
switch (cmd) {
case '1':
display.fillScreen(TFT_RED);
Serial.println("Red screen");
break;
case '2':
display.fillScreen(TFT_GREEN);
Serial.println("Green screen");
break;
case '3':
display.fillScreen(TFT_BLUE);
Serial.println("Blue screen");
break;
case 'b':
display.setBrightness(255);
Serial.println("Backlight MAX");
break;
case 'd':
display.setBrightness(0);
Serial.println("Backlight OFF");
break;
}
}
```
---
## Hardware Checks
### 1. Power Supply
- Verify 5V USB power is stable
- Check if board LED is lit
- Measure voltage on 3.3V pin (should be 3.2-3.4V)
### 2. Display Connection
- Ensure display is seated properly (if removable)
- Check for physical damage
- Look for broken solder joints
### 3. ESP32-S3 Status
- Verify boot messages on serial (if using USB CDC)
- Check if board boots normally
- Confirm PSRAM is detected
---
## If Nothing Works
### Last Resort: Factory Test Mode
1. Download Waveshare official demo code:
```bash
wget https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/ESP32-S3-LCD-1.3-Demo.zip
unzip ESP32-S3-LCD-1.3-Demo.zip
```
2. Check their pin configuration in the demo code
3. Test with their demo to confirm hardware works
4. Compare their pins to our configuration
### Get Help
If the display still doesn't work:
1. **Schematic**: Download from https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/ESP32S3_1.3inch.pdf
2. **Datasheet**: https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/1.3inch_LCD_Module_ESP32S3.pdf
3. **Waveshare Support**: support@waveshare.com
4. **Community**: https://www.waveshare.com/wiki/ESP32-S3-LCD-1.3#Resources
---
## Success Checklist
Once display is working, you should see:
- ✅ SquareLine Studio UI appears
- ✅ `uic_Home_LBL` label is visible
- ✅ Text updates every second
- ✅ No LVGL warnings in serial monitor
- ✅ Smooth rendering (30+ FPS)
---
**Last Updated**: 2025-11-08
**Status**: Backlight pin updated to GPIO 2 (most likely correct)
-656
View File
@@ -1,656 +0,0 @@
# UART Protocol Specification
**Version:** 1.0
**Last Updated:** 2025-11-09
**Author:** BMW Patrol Project
**Target Hardware:** ESP32-S3-Touch-LCD-5B → ESP32-S3-Touch-LCD-1.3
---
## Overview
This document describes the UART communication protocol used to transmit automotive sensor data from **Controller A** (ESP32-S3-Touch-LCD-5B, 5-inch display) to **Controller B** (ESP32-S3-Touch-LCD-1.3, 1.3-inch display).
Controller A receives BMW CAN bus messages, parses the vehicle sensor data, and forwards it via UART to Controller B for display on the smaller dashboard screen.
---
## Physical Layer
### Hardware Configuration
| Parameter | Value | Notes |
|-----------|-------|-------|
| **Baud Rate** | 115200 bps | Standard UART speed |
| **Data Bits** | 8 | No parity |
| **Stop Bits** | 1 | Standard framing |
| **Flow Control** | None | Simple 2-wire TX/RX |
| **Voltage Level** | 3.3V TTL | ESP32 GPIO levels |
| **Connector** | GPIO Headers | Direct GPIO-to-GPIO connection |
### Pin Mapping
**Controller A (Transmitter - 5B):**
- TX: GPIO 44
- RX: GPIO 43 (unused - transmit-only mode)
**Controller B (Receiver - 1.3):**
- RX: GPIO 1 (IO1)
- TX: Not used (receive-only mode)
### Wiring
Simple 3-wire connection:
- Controller A GPIO 44 → Controller B GPIO 1 (data line)
- GND → GND (common ground required)
- VCC: Both powered independently (no power sharing)
---
## Protocol Layer
### Transmission Characteristics
| Parameter | Value | Notes |
|-----------|-------|-------|
| **Transmission Rate** | 5 Hz (200ms intervals) | Periodic updates |
| **Packet Format** | Binary framed packet | Fixed-length structure |
| **Error Detection** | XOR checksum | Single-byte validation |
| **Start Marker** | 0xAA | Packet synchronization |
| **End Marker** | 0x55 | Packet boundary detection |
| **Total Packet Size** | 23 bytes | Fixed length |
### State Machine
**Controller A (Transmitter):**
1. UART OFF → CAN disabled
2. CAN Toggle ON → CAN starts → UART auto-starts
3. UART transmits real-time CAN data at 5 Hz
4. CAN Toggle OFF → CAN stops → UART auto-stops
**Controller B (Receiver):**
- Continuously listens on UART RX
- Validates packet markers and checksum
- Parses automotive data structure
- Updates display with latest values
---
## Packet Structure
### Binary Frame Format
Total packet size: **23 bytes**
```
┌─────────┬─────────┬────────┬──────────────────┬──────────┬─────────┐
│ START │ VERSION │ LENGTH │ PAYLOAD (DATA) │ CHECKSUM │ END │
├─────────┼─────────┼────────┼──────────────────┼──────────┼─────────┤
│ 0xAA │ 0x01 │ 0x12 │ 18 bytes │ 1 byte │ 0x55 │
│ 1 byte │ 1 byte │ 1 byte │ │ (XOR) │ 1 byte │
└─────────┴─────────┴────────┴──────────────────┴──────────┴─────────┘
```
### Field Descriptions
#### Header (3 bytes)
| Offset | Size | Name | Value | Description |
|--------|------|------|-------|-------------|
| 0 | 1 | Start Marker | 0xAA | Fixed synchronization byte |
| 1 | 1 | Protocol Version | 0x01 | Current protocol version |
| 2 | 1 | Payload Length | 0x12 (18 decimal) | Data section size in bytes |
#### Payload - Automotive Data (18 bytes)
| Offset | Size | Name | Data Type | Unit | Range | Description |
|--------|------|------|-----------|------|-------|-------------|
| 3 | 4 | Timestamp | uint32_t (LE) | milliseconds | 0 - 4,294,967,295 | System uptime when packet created |
| 7 | 1 | Packet ID | uint8_t | counter | 0 - 255 | Rolling packet counter (wraps at 255) |
| 8 | 1 | Gear Position | uint8_t | enum | 0 - 14 | Current transmission gear/mode |
| 9 | 2 | Coolant Temp | int16_t (LE) | 0.1°C | -400 to 2150 | Engine coolant temperature × 10 |
| 11 | 2 | Engine Oil Temp | int16_t (LE) | 0.1°C | -400 to 2150 | Engine oil temperature × 10 |
| 13 | 2 | Gearbox Temp | int16_t (LE) | 0.1°C | -400 to 2150 | Transmission fluid temperature × 10 |
| 15 | 2 | Battery Voltage | uint16_t (LE) | 0.01V | 0 - 655.35 | Battery voltage × 100 |
| 17 | 2 | Fault Codes | uint16_t (LE) | bitfield | 0 - 65535 | Active diagnostic fault codes |
| 19 | 1 | Valid Flags | uint8_t | bitfield | 0 - 255 | Data validity indicators |
| 20 | 1 | Debug Enabled | uint8_t | boolean | 0 or 1 | Debug mode flag (0=OFF, 1=ON) |
**Note:** LE = Little-Endian byte order (least significant byte first)
#### Trailer (2 bytes)
| Offset | Size | Name | Description |
|--------|------|------|-------------|
| 21 | 1 | Checksum | XOR of all bytes from offset 1 to 20 (inclusive) |
| 22 | 1 | End Marker | Fixed value 0x55 for packet boundary |
---
## Data Encoding Details
### Temperature Fields
**Format:** Signed 16-bit integer (int16_t), little-endian
**Units:** Tenths of degrees Celsius (0.1°C precision)
**Encoding:** `raw_value = actual_temperature × 10`
**Examples:**
- 85.0°C → Transmitted as: 850 (0x52 0x03 in little-endian)
- 104.7°C → Transmitted as: 1047 (0x17 0x04 in little-endian)
- -12.5°C → Transmitted as: -125 (0x83 0xFF in little-endian, two's complement)
**Typical Range:**
- Coolant: 60°C to 110°C (600 to 1100)
- Engine Oil: 80°C to 140°C (800 to 1400)
- Gearbox: 60°C to 120°C (600 to 1200)
**Special Values:**
- -400 (0xFF70): Sensor error or not available
- 2150 (0x086E): Over-temperature fault
### Battery Voltage
**Format:** Unsigned 16-bit integer (uint16_t), little-endian
**Units:** Hundredths of volts (0.01V precision)
**Encoding:** `raw_value = actual_voltage × 100`
**Examples:**
- 12.45V → Transmitted as: 1245 (0xDD 0x04 in little-endian)
- 14.23V → Transmitted as: 1423 (0x8F 0x05 in little-endian)
- 11.80V → Transmitted as: 1180 (0x9C 0x04 in little-endian)
**Typical Range:**
- Normal operation: 12.0V to 14.5V (1200 to 1450)
- Engine off: 12.3V to 12.8V (1230 to 1280)
- Charging: 13.8V to 14.4V (1380 to 1440)
**Warning Thresholds:**
- Low voltage: < 12.0V (1200)
- High voltage: > 15.0V (1500)
### Gear Position Enumeration
**Format:** Unsigned 8-bit integer (uint8_t)
**Encoding:** Single byte representing transmission state
| Value | Name | Display | Description |
|-------|------|---------|-------------|
| 0 | GEAR_PARK | P | Park - transmission locked |
| 1 | GEAR_REVERSE | R | Reverse gear |
| 2 | GEAR_NEUTRAL | N | Neutral - no gear engaged |
| 3 | GEAR_DRIVE | D | Drive - automatic mode |
| 4 | GEAR_SPORT | S | Sport mode |
| 5 | GEAR_MANUAL | M | Manual/Sequential mode |
| 6 | GEAR_MANUAL_1 | 1 | Manual 1st gear |
| 7 | GEAR_MANUAL_2 | 2 | Manual 2nd gear |
| 8 | GEAR_MANUAL_3 | 3 | Manual 3rd gear |
| 9 | GEAR_MANUAL_4 | 4 | Manual 4th gear |
| 10 | GEAR_MANUAL_5 | 5 | Manual 5th gear |
| 11 | GEAR_MANUAL_6 | 6 | Manual 6th gear |
| 12 | GEAR_MANUAL_7 | 7 | Manual 7th gear |
| 13 | GEAR_MANUAL_8 | 8 | Manual 8th gear |
| 14 | GEAR_ERROR | ? | Transmission fault/unknown |
**Note:** BMW automatic transmissions typically use P/R/N/D/S modes. Manual mode (M) with sequential shifting shows the current selected gear (1-8).
### Fault Codes Bitfield
**Format:** Unsigned 16-bit integer (uint16_t), little-endian
**Encoding:** Each bit represents a specific fault condition
| Bit | Mask | Fault Name | Description |
|-----|------|------------|-------------|
| 0 | 0x0001 | ENGINE_FAULT | Check engine light / MIL |
| 1 | 0x0002 | TRANSMISSION_FAULT | Transmission system error |
| 2 | 0x0004 | ABS_FAULT | Anti-lock braking system fault |
| 3 | 0x0008 | AIRBAG_FAULT | SRS airbag system fault |
| 4 | 0x0010 | BATTERY_FAULT | Charging system fault |
| 5 | 0x0020 | COOLANT_FAULT | Coolant temperature warning |
| 6 | 0x0040 | OIL_PRESSURE_FAULT | Low oil pressure warning |
| 7 | 0x0080 | BRAKE_FAULT | Brake system warning |
| 8-15 | 0xFF00 | RESERVED | Reserved for future use |
**Examples:**
- 0x0000: No faults
- 0x0001: Engine fault only
- 0x0003: Engine + Transmission faults (bits 0 and 1 set)
- 0x0021: Engine + Coolant faults (bits 0 and 5 set)
**Note:** Multiple faults can be active simultaneously. Check each bit independently.
### Valid Flags Bitfield
**Format:** Unsigned 8-bit integer (uint8_t)
**Encoding:** Each bit indicates if corresponding data field is valid
| Bit | Mask | Field Name | Description |
|-----|------|------------|-------------|
| 0 | 0x01 | VALID_GEAR_POS | Gear position data is valid |
| 1 | 0x02 | VALID_GEARBOX_TEMP | Gearbox temperature is valid |
| 2 | 0x04 | VALID_ENGINE_TEMP | Engine oil temperature is valid |
| 3 | 0x08 | VALID_COOLANT_TEMP | Coolant temperature is valid |
| 4 | 0x10 | VALID_BATTERY_VOLT | Battery voltage is valid |
| 5 | 0x20 | VALID_FAULT_CODES | Fault codes are valid |
| 6-7 | 0xC0 | RESERVED | Reserved for future use |
**Usage:**
- **All bits set (0x3F):** All data fields contain valid readings from CAN bus
- **Bit cleared (0):** Corresponding field may contain stale/default/invalid data
- **Example (0x1F):** All fields valid except fault codes (bit 5 cleared)
**Important:** Receivers should check validity flags before using sensor data. Invalid data should be ignored or displayed with a warning indicator.
### Debug Flag
**Format:** Unsigned 8-bit integer (uint8_t)
**Values:**
- 0x00: Debug mode OFF (normal operation)
- 0x01: Debug mode ON (verbose logging enabled on Controller B)
**Purpose:** Controls diagnostic logging and performance monitoring on the receiver. When enabled, Controller B may display:
- FPS (frames per second)
- CPU usage statistics
- Packet reception statistics
- Parse error counts
---
## Checksum Algorithm
### XOR Checksum Calculation
**Algorithm:** Simple XOR of all bytes in the packet (excluding start marker and checksum itself)
**Range:** Bytes from offset 1 to 20 (inclusive)
**Fields included:**
- Protocol version (offset 1)
- Length (offset 2)
- All payload data (offsets 3-20)
**Fields excluded:**
- Start marker (offset 0) - not included
- Checksum itself (offset 21) - calculated result
- End marker (offset 22) - not included
**Process:**
1. Initialize checksum to 0x00
2. XOR with version byte
3. XOR with length byte
4. XOR with all 18 payload bytes in sequence
5. Result is the checksum value
**Validation:**
Receiver must recalculate checksum using the same algorithm and compare with received checksum byte. If mismatch occurs, the packet is corrupted and must be discarded.
---
## Error Handling
### Packet Validation Rules
A valid packet MUST satisfy ALL of the following conditions:
1. **Start Marker Check:** First byte == 0xAA
2. **End Marker Check:** Last byte (offset 22) == 0x55
3. **Version Check:** Protocol version == 0x01
4. **Length Check:** Payload length == 0x12 (18 bytes)
5. **Checksum Validation:** Calculated checksum matches received checksum
### Error Recovery
**On Validation Failure:**
1. Discard the corrupted packet
2. Increment error counter (for diagnostics)
3. Continue listening for next valid start marker (0xAA)
4. Do NOT update display with invalid data
**On Missing Packets:**
- If no valid packet received within 1 second:
- Display last known valid data
- Show "STALE DATA" warning indicator
- Continue using cached values
**On Checksum Error:**
- Common cause: Noise on UART line or baud rate mismatch
- Check physical wiring (crosstalk, EMI)
- Verify both devices configured for 115200 baud
**On Continuous Errors (>10 consecutive failures):**
- Display "UART FAULT" error
- Consider communication link broken
- May indicate hardware failure or disconnection
---
## Data Source
### CAN Bus Origin
All automotive sensor data originates from BMW CAN bus messages received by Controller A:
| Data Field | CAN Message ID | Byte Position | Notes |
|------------|----------------|---------------|-------|
| Coolant Temperature | 0x4F | Byte 0 | Standard 11-bit ID |
| Engine Oil Temperature | 0x55 | Byte 7 | Standard 11-bit ID |
| Gearbox Temperature | 0x201 | Byte 3 | Standard 11-bit ID |
| Gear Position | 0x1001 | Byte 0 | Extended 29-bit ID |
| Current Gear (1-8) | 0x1001 | Byte 1 | Same message as position |
| Battery Voltage | 0x101F | Bytes 0-1 (16-bit) | Extended 29-bit ID |
**CAN Bus Configuration:**
- Speed: 500 Kbps (BMW K-CAN standard)
- Mode: NORMAL (can send ACK bits)
- GPIOs: TX=GPIO15, RX=GPIO16
- Reception rate: ~25 messages/second (5 unique IDs at 5 Hz)
**Data Flow:**
```
BMW Vehicle CAN Bus
↓
Controller A (ESP32-S3-LCD-5B)
- CAN driver receives messages
- Parses BMW protocol
- Updates shared data structure
↓
UART Transmitter (5 Hz)
- Reads shared data (mutex protected)
- Builds binary packet
- Transmits via GPIO 44
↓
Controller B (ESP32-S3-LCD-1.3)
- Receives on GPIO 1
- Validates packet
- Updates 1.3-inch display
```
### Data Freshness
**Timestamp Field:**
- Represents Controller A system uptime when packet was created
- Updates every 200ms (5 Hz rate)
- Used to detect communication delays or stale data
- Wraps around every ~49.7 days (uint32_t milliseconds)
**Receiver Freshness Check:**
Compare consecutive packet timestamps. If delta != ~200ms, possible issues:
- Delta < 150ms: Duplicate packet or clock skew
- Delta > 300ms: Missed packet(s) or transmission delay
- Delta > 1000ms: Communication interrupted
---
## Timing Specifications
### Transmission Schedule
| Parameter | Value | Tolerance | Notes |
|-----------|-------|-----------|-------|
| **Update Rate** | 200ms (5 Hz) | ±10ms | Periodic transmission |
| **Packet Duration** | ~2ms | - | At 115200 baud, 23 bytes |
| **Inter-Packet Gap** | ~198ms | - | Time between end and next start |
| **Startup Delay** | < 100ms | - | From CAN toggle to first packet |
### Receiver Requirements
**Minimum Buffer Size:** 32 bytes recommended
- Allows buffering of 1 complete packet plus margin
- Prevents overflow during processing
**Processing Time:** < 50ms per packet
- Parse and validate packet
- Update display data
- Must complete before next packet arrives
**Synchronization:**
- Listen for 0xAA start marker continuously
- No strict timing requirement (asynchronous)
- Packet boundaries defined by markers, not timing
---
## Interoperability
### Protocol Versioning
**Current Version:** 0x01 (version byte at offset 1)
**Future Version Changes:**
If protocol structure changes, version byte will increment:
- Version 0x02: May add new fields or change packet size
- Receivers MUST check version byte
- Unknown versions should be rejected
**Backward Compatibility:**
This specification (v1.0) guarantees:
- Packet structure fixed at 23 bytes
- Field offsets will not change
- New versions will use different version byte
### Multi-Language Support
This protocol is binary and language-agnostic. Compatible with:
- C/C++ (native on ESP32)
- Python (struct module for packing/unpacking)
- Rust (byteorder crate)
- Any language with binary I/O support
**Endianness Requirement:**
All multi-byte fields use **little-endian** byte order to match ESP32 native format. Non-ESP32 receivers must handle endianness conversion if needed.
---
## Security Considerations
### Protocol Limitations
**This protocol does NOT provide:**
- Encryption (data transmitted in plaintext)
- Authentication (no sender verification)
- Integrity protection beyond simple checksum
- Replay attack prevention
**Assumptions:**
- Physical security: Direct wired connection between trusted devices
- Closed system: No external access to UART lines
- Point-to-point: Single transmitter → single receiver
### Checksum Strength
**XOR checksum provides:**
- Detection of single-bit errors: ✓
- Detection of burst errors: Partial
- Detection of intentional tampering: ✗
**Known Weaknesses:**
- Two identical errors cancel out (XOR property)
- Does not detect byte reordering
- Cryptographically insecure
**Recommendation:** For safety-critical applications requiring higher integrity, consider upgrading to CRC-16 or CRC-32 checksums in future protocol versions.
---
## Example Packet Analysis
### Sample Packet (Hexadecimal)
```
AA 01 12 | E8 03 00 00 | 1A | 04 | 4E 03 | 17 04 | 7F 03 | DD 04 | 00 00 | 3F | 01 | 9C | 55
```
### Field-by-Field Breakdown
| Offset | Hex Bytes | Field | Decoded Value | Notes |
|--------|-----------|-------|---------------|-------|
| 0 | AA | Start Marker | 0xAA | Valid sync byte |
| 1 | 01 | Version | 1 | Protocol v1.0 |
| 2 | 12 | Length | 18 bytes | Payload size |
| **PAYLOAD START** |
| 3-6 | E8 03 00 00 | Timestamp | 1000ms | Little-endian uint32 |
| 7 | 1A | Packet ID | 26 | Rolling counter |
| 8 | 04 | Gear Position | 4 (GEAR_SPORT) | Sport mode |
| 9-10 | 4E 03 | Coolant Temp | 846 = 84.6°C | int16_t LE |
| 11-12 | 17 04 | Engine Oil Temp | 1047 = 104.7°C | int16_t LE |
| 13-14 | 7F 03 | Gearbox Temp | 895 = 89.5°C | int16_t LE |
| 15-16 | DD 04 | Battery Voltage | 1245 = 12.45V | uint16_t LE |
| 17-18 | 00 00 | Fault Codes | 0x0000 | No faults |
| 19 | 3F | Valid Flags | 0x3F (0b00111111) | All fields valid |
| 20 | 01 | Debug Enabled | 1 (ON) | Debug mode active |
| **PAYLOAD END** |
| 21 | 9C | Checksum | 0x9C | XOR validation |
| 22 | 55 | End Marker | 0x55 | Valid packet boundary |
### Interpretation
**System Status:**
- Uptime: 1.0 seconds since boot
- Transmission in Sport mode
- Engine warmed up (coolant 84.6°C, oil 104.7°C)
- Normal battery voltage (12.45V)
- No fault codes active
- All sensor data valid
- Debug logging enabled
**Validity Check:**
- Start marker: ✓ (0xAA found)
- End marker: ✓ (0x55 found)
- Version: ✓ (0x01 matches)
- Length: ✓ (0x12 = 18 bytes)
- Checksum: ✓ (recalculate to verify 0x9C)
**Display Output:**
```
Gear: S
Temps: 84.6 / 104.7 / 89.5 °C
Battery: 12.45V
Faults: None
Debug: ON
```
---
## Implementation Guidelines
### Receiver Best Practices
**Synchronization Strategy:**
1. Search for start marker (0xAA) in incoming byte stream
2. Read next 22 bytes as potential packet
3. Validate end marker (0x55) at expected offset
4. Verify version and length fields
5. Calculate and compare checksum
6. Parse payload only if all checks pass
**Buffer Management:**
- Use circular/ring buffer for incoming bytes
- Handle partial packets gracefully
- Clear buffer on validation failure to resync
**Data Extraction:**
- Use bitwise operations for multi-byte fields
- Handle little-endian conversion if needed
- Apply scaling factors (×10 for temps, ×100 for voltage)
- Check valid flags before using each field
**Display Updates:**
- Update display only on valid packet
- Maintain last known good values for each field
- Show warning if packet age > 1 second
- Indicate invalid fields with "---" or similar
### Transmitter Considerations
**Timing Accuracy:**
- Use hardware timer for 200ms interval
- Avoid blocking operations in transmission loop
- Keep packet assembly time < 10ms
**Data Consistency:**
- Use mutex when reading shared CAN data
- Snapshot all values atomically
- Update timestamp last (after data read)
**Error Handling:**
- If UART transmit fails, log error but continue
- Don't block CAN reception on UART errors
- Auto-restart UART if failures exceed threshold
---
## Troubleshooting
### Common Issues
**No Packets Received:**
- Check physical wiring (TX→RX connection, common ground)
- Verify baud rate match (115200 on both sides)
- Confirm Controller A CAN bus is active and receiving data
- Check GPIO pin assignments match specification
**Checksum Errors:**
- Intermittent errors: Likely EMI/noise on wire
- Consistent errors: Baud rate mismatch or endianness issue
- Add shielding to UART wires if noise suspected
**Stale Data (Timestamp Not Updating):**
- Controller A may have crashed (check serial log)
- CAN bus disconnected (no vehicle data)
- UART transmitter disabled (check CAN toggle state)
**Invalid Temperature Readings:**
- Value -400: CAN message not received or sensor fault
- Value > 2000: Overflow or parsing error
- Check CAN bus connection and message IDs
**Gear Position Shows Error (14):**
- Transmission CAN message (0x1001) not received
- Check CAN wiring and bus termination
- Verify vehicle is in accessory mode (CAN active)
### Debug Checklist
**Controller A (Transmitter):**
1. CAN toggle ON in Settings screen?
2. CAN messages being received? (check serial: "✓ Parsed CAN ID=...")
3. UART auto-started? (check serial: "UART STARTED (triggered by CAN state)")
4. Packets being sent? (check serial: "TX Packet #N (...)")
**Controller B (Receiver):**
1. UART initialized on correct GPIO (RX = GPIO 1)?
2. Baud rate set to 115200?
3. Start marker (0xAA) being detected?
4. Checksum validation passing?
5. Valid flags checked before using data?
---
## Revision History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | 2025-11-09 | BMW Patrol Team | Initial release - CAN-to-UART integration complete |
---
## References
**Related Documentation:**
- `CLAUDE.md` - Project architecture and build instructions
- `CAN_BUS_INTEGRATION.md` - CAN bus configuration and BMW message IDs
- `src/protocol/automotive_data.h` - C structure definitions
- `src/modules/uart_manager.cpp` - Transmitter implementation
- `src/drivers/can_driver.cpp` - CAN receiver implementation
**Hardware Specifications:**
- ESP32-S3-Touch-LCD-5B: https://www.waveshare.com/esp32-s3-touch-lcd-5.htm
- ESP32-S3-Touch-LCD-1.3: https://www.waveshare.com/esp32-s3-touch-lcd-1.3.htm
- ESP32-S3 Technical Reference Manual: https://www.espressif.com/en/products/socs/esp32-s3
**Standards:**
- BMW K-CAN Bus: 500 Kbps, ISO 11898 compliant
- UART: RS-232 compatible (TTL voltage levels)
---
**End of Document**
-182
View File
@@ -1,182 +0,0 @@
# UART Wiring Guide - Controller A ↔ Controller B
## Physical Connection
### Required: 2 Wires
```
Controller A Controller B
ESP32-S3-Touch-LCD-5B ESP32-S3-LCD-1.3
┌─────────────────────────┐ ┌─────────────────────────┐
│ │ │ │
│ GPIO 43 (UART TX) ─────┼──────────┼────> GPIO 1 (RX) │
│ [RS485 Terminal] │ Wire 1 │ [Pin 4 on header] │
│ │ │ │
│ GND ───────────────────┼──────────┼────> GND │
│ [Any GND pin] │ Wire 2 │ [Pin 2 on header] │
│ │ │ │
└─────────────────────────┘ └─────────────────────────┘
```
---
## Pin Details
### Controller A (ESP32-S3-Touch-LCD-5B)
- **TX Pin**: GPIO 43 (on RS485 terminal block)
- **GND**: Any GND pin on board
### Controller B (ESP32-S3-LCD-1.3)
- **RX Pin**: GPIO 1 (Pin 4 on 13-pin header)
- **GND**: Pin 2 on 13-pin header
---
## 13-Pin Header Pinout (Controller B)
Based on Waveshare documentation:
```
┌─────────────────┐
│ 1. 5V │
│ 2. GND │ ← Connect GND here
│ 3. 3V3 │
│ 4. GPIO 1 │ ← Connect UART RX here
│ 5. GPIO 2 │
│ 6. GPIO 42 │
│ 7. GPIO 41 │
│ 8. GPIO 40 │
│ 9. GPIO 39 │
│ 10. GPIO 38 │
│ 11. GPIO 37 │
│ 12. GPIO 36 │
│ 13. GPIO 35 │
└─────────────────┘
```
**Reference Image**: https://www.waveshare.com/img/devkit/ESP32-S3-LCD-1.3/ESP32-S3-LCD-1.3-details-7.jpg
---
## UART Configuration
| Parameter | Value |
|-----------|-------|
| Baud Rate | 115200 |
| Data Bits | 8 |
| Parity | None |
| Stop Bits | 1 |
| Format | 8N1 |
| Direction | One-way (A → B) |
| Update Rate | 5 Hz (200ms) |
---
## Testing Steps
### 1. Power Off Both Controllers
### 2. Make Physical Connections
- Wire 1: Controller A GPIO 43 → Controller B GPIO 1 (Pin 4)
- Wire 2: Controller A GND → Controller B GND (Pin 2)
### 3. Power On Controller A
- Ensure UART transmission is enabled
- Check Controller A serial monitor for "UART packets sent" messages
### 4. Power On Controller B
- Monitor serial output:
```bash
cd /home/julian/projects/esp/pio/bmw-patrol/ESP32-S3-LCD-1.3
pio device monitor
```
### 5. Expected Output on Controller B
**On Boot**:
```
[BOOT] ESP32-S3-LCD-1.3 starting...
[UART] Initializing UART receiver...
[UARTReceiver] Task started on Core 0
[UARTReceiver] UART1 initialized: 115200 baud, RX=GPIO1, TX=GPIO2
[UARTReceiver] Waiting for packets from Controller A...
```
**When Connected** (within 1-2 seconds):
```
[UART] Connection ESTABLISHED with Controller A
[Data] Gear:P | Gearbox:85.0°C | Engine:92.0°C | Battery:12.45V
```
**Every 5 seconds**:
```
[UART Stats] Packets: 25 | Checksum Errors: 0 | Framing Errors: 0 | Bytes RX: 650
[UART Stats] Last packet: 198 ms ago
```
**Every 20 packets**:
```
[UARTReceiver] Packet #20 | Gear:P | Gearbox:85.0°C | Engine:92.0°C | Coolant:89.0°C | Battery:12.45V
```
---
## Troubleshooting
### No Data Received
**Check**:
1. ✅ Wiring correct? (TX → RX, not TX → TX)
2. ✅ GND connected?
3. ✅ Controller A transmitting? (check its serial monitor)
4. ✅ Baud rates match? (both should be 115200)
**Serial Monitor Shows**:
```
[UART Stats] Packets: 0 | Checksum Errors: 0 | Framing Errors: 0 | Bytes RX: 0
```
→ No data arriving at all - check wiring
### Framing Errors
**Serial Monitor Shows**:
```
[UART Stats] Packets: 0 | Checksum Errors: 0 | Framing Errors: 127 | Bytes RX: 127
[UARTReceiver] Framing error! Expected 0x55, got 0x3C
```
→ Data arriving but corrupted - check:
- Loose connection
- Baud rate mismatch
- Electrical interference
### Checksum Errors
**Serial Monitor Shows**:
```
[UART Stats] Packets: 0 | Checksum Errors: 15 | Framing Errors: 0 | Bytes RX: 390
[UARTReceiver] Checksum error!
```
→ Packets arriving but validation failing - possible:
- Protocol version mismatch between A and B
- Electrical noise
- Timing issues
---
## Pin Configuration in Code
**File**: `src/modules/uart_receiver.cpp` (lines 16-21)
```cpp
// UART Configuration
#define UART_RX_PIN 1 // GPIO 1 - Receive from Controller A (Pin 4 on header)
#define UART_TX_PIN 2 // GPIO 2 - Unused (RX-only mode)
#define UART_BAUD_RATE 115200 // Match Controller A
#define UART_SERIAL_PORT Serial1 // Hardware UART1
#define UART_RX_BUFFER_SIZE 256 // Receive buffer size
```
---
**Last Updated**: 2025-11-08
**Status**: ✅ GPIO 1 configured and tested
**Firmware Version**: Phase 2 - UART Reception
+111
View File
@@ -0,0 +1,111 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
**Controller B** of the BMW M57N → Nissan Patrol swap display system, running on a **Waveshare ESP32-S3-LCD-1.3** (1.3" 240×240 ST7789VW, shown with a circular mask). It is a slave/extension of Controller A (ESP32-S3-Touch-LCD-5B, sibling repo `../ESP32-S3-Touch-LCD-5B`): it receives a 23-byte sensor packet over UART at 5 Hz, shows it, and is the planned driver for the Patrol cluster's tachometer and coolant gauges.
**Hardware**: ESP32-S3R8 dual-core @ 240 MHz, 16 MB flash, 8 MB OPI PSRAM, CH343 USB-serial bridge (not native USB-CDC), Wi-Fi + BLE 5, 13 free-function GPIOs on two 8-pin headers.
**Domain knowledge lives in `wiki/`** (an Obsidian vault maintained by the LLM). Read `wiki/CLAUDE.md` before editing anything there. `wiki/index.md` is the catalog; `wiki/pages/open-questions.md` is the roadmap. CAN decoding and vehicle facts live in the sibling repo's wiki, not here.
## Build & Development Commands
```bash
pio run # build
pio run --target upload # upload
pio device monitor # serial monitor, 115200 baud
./upload_and_monitor.sh # upload, wait 2 s for reset, then monitor
pio run --target clean # clean build
pio pkg update # update libraries
pio device list # find the port
pio run --target upload --upload-port COMx # explicit port
```
Serial goes through the onboard **CH343 USB-UART chip on UART0**, so the port appears as a normal COM/ttyUSB device and there is no USB-CDC enumeration delay. If the monitor shows nothing, check `monitor_speed = 115200` matches `Serial.begin(115200)` and start the monitor after the board has reset (the helper script's 2 s delay exists for this).
## Architecture
### Tasks and cores
- **Core 1**: `lvglTask()` calls `DisplayInit::update()` every 5 ms (LVGL tick + handler). The Arduino `loop()` also runs on Core 1 (`ARDUINO_RUNNING_CORE=1`) and is where all UI updates happen: it polls `UARTReceiver` and writes labels/icons.
- **Core 0**: the UART receiver task (byte-level packet state machine). It never touches LVGL. Shared data is guarded by `g_data_mutex` inside `uart_receiver.cpp`.
There is **no LVGL port lock** in this project (unlike Controller A). Keep every LVGL call in `loop()` or `lvglTask()`; if you add a task that must update the UI, add a mutex around `lv_*` calls first.
### Modules
```
src/
main.cpp # setup(), loop(): UI update from received data, warning thresholds
modules/
display_init.cpp/.h # LovyanGFX LGFX class (ST7789VW), LVGL init, circular mask, backlight PWM
uart_receiver.cpp # UART1 RX task, framing state machine, checksum, stats, link timeout
debug_monitor.cpp # shows/hides LVGL perf+mem monitors, mirrors A's debug_enabled flag
include/
config/lv_conf.h # LVGL 8.4.0 config (RGB565, dark theme, arc/label/led/meter widgets)
modules/uart_receiver.h, debug_monitor.h
protocol/automotive_data.h # SHARED packet contract — copied from Controller A, must match its version
ui/ # SquareLine Studio exports (ui.c/h, screens/, components/, fonts/)
```
**DisplayInit** — `init()`, `update()`, `setBrightness(0–255)`, `getBrightness()`. Default brightness 128. `DISPLAY_RADIUS 120` defines the circular mask.
**UARTReceiver** — `init()`, `getStats()` (packets, checksum errors, framing errors, timeouts, bytes, last packet time), `isConnected(timeout_ms = 1000)`, `getTimeSinceLastPacket()`, `resetStats()`. The link is considered lost after 1000 ms without a valid packet; `loop()` shows a no-data state and hides sensor icons.
**DebugMonitor** — `init()`, `setVisible(bool)`, `isVisible()`. Driven by the `debug_enabled` byte in each packet, so Controller A's debug toggle controls B's overlays.
### UART packet (shared with Controller A)
`0xAA` · version `0x01` · length `0x12` · 18-byte `automotive_data_t` · XOR checksum · `0x55` = 23 bytes, 115200 8N1, 5 Hz, one direction A → B. The spec lives in the sibling repo at `docs/UART_PROTOCOL.md`; the struct in `include/protocol/automotive_data.h` must stay byte-identical to A's. When A changes the packet it bumps `PACKET_VERSION`; copy the header here and reject unexpected versions.
> **Known drift (2026-09-21)**: A's and B's `gear_position_t` enums disagree above value 3 (B: 4 = Sport, 5 = Manual, 6–13 = M1–M8; A: 4–9 = M1–M6). Value 4 on the wire means different things on each end. Resolve before trusting the gear display. See `wiki/pages/controller-link.md`.
Warning thresholds in `main.cpp`: coolant 110 °C, engine oil 130 °C, gearbox oil 130 °C, battery below 11.0 V. Note `engine_oil_temp` has no real source on this engine (A reads 0xFF from CAN); expect it to stay invalid.
## Hardware-Specific Details
### GPIO assignments (verified against the Waveshare demo and the pinout photo)
| GPIO | Function |
|---|---|
| 40 / 41 | LCD SCLK / MOSI (80 MHz write) |
| 38 / 39 / 42 | LCD DC / CS / RST |
| 20 | LCD backlight, LEDC PWM |
| 43 / 44 | UART0 → CH343 USB bridge (debug console) — not available for the link |
| IO1 | UART1 RX from Controller A (left header, pin 4) |
| IO2 | UART1 TX — unused, link is receive-only |
**Header pinout** (USB-C at top): left 5V · GND · 3V3 · IO1 · IO2 · IO3 · IO4 · IO5; right IO14 · IO13 · IO12 · IO11 · IO10 · IO9 · IO8 · IO7. Free for new features: IO4, IO5, IO7–IO14 (IO3 is a strapping pin, avoid). IO7/IO8 are earmarked for the gauge outputs — see `wiki/pages/patrol-gauge-outputs.md`.
Pins are set in `src/modules/display_init.cpp` and `platformio.ini` (`-DUART_RX_PIN=1 -DUART_TX_PIN=2`). Older notes claiming backlight on GPIO 2 or 15, SPI on 10/11, or a header carrying IO35–IO42 were wrong and have been removed.
### platformio.ini
- `espressif32@^6.0.0`, Arduino framework, board `esp32-s3-devkitc-1` with `board_build.arduino.memory_type = qio_opi`, `psram_type = opi`
- `-DARDUINO_RUNNING_CORE=1`, `-DBOARD_HAS_PSRAM`, `-DDISPLAY_WIDTH=240 -DDISPLAY_HEIGHT=240`
- `build_src_filter` pulls `include/ui/*` and `include/display/*` into the build
- Libraries: `lovyan03/LovyanGFX@^1.1.0`, `lvgl/lvgl@^8.4.0`
## SquareLine Studio
- Export to **`include/ui/`**, never to `src/` (it would overwrite `main.cpp`).
- Access widgets through the exported `ui_*` / `uic_*` pointers; always NULL-check before use.
- Manual edits inside `include/ui/` are lost on the next export — put logic in `main.cpp`.
- Init order: `DisplayInit::init()` → `ui_init()` → create `lvglTask`. Do not overwrite label text in `loop()` unless intended.
- Colour depth must stay `LV_COLOR_DEPTH 16` (SquareLine exports RGB565).
## Troubleshooting
- **Blank display**: confirm the pin table above (backlight GPIO 20 is the usual culprit), try `cfg.freq_write = 40000000`, toggle `cfg.invert`. A direct LovyanGFX `fillScreen()` before LVGL init separates hardware from LVGL problems.
- **`lv_tick_inc() is not called`**: the tick handler lives in `DisplayInit::update()`; make sure `lvglTask` is running.
- **Out of memory**: raise `LV_MEM_SIZE` in `include/config/lv_conf.h` or move buffers to PSRAM.
- **No packets** (`Packets: 0`): TX→RX crossed? common ground? A's CAN toggle must be ON (its UART auto-starts with CAN). Framing errors with bytes arriving = baud or wiring; checksum errors = version/struct mismatch between the repos.
- **Last resort**: Waveshare demo `https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/ESP32-S3-LCD-1.3-Demo.zip` and schematic `https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/ESP32S3_1.3inch.pdf`.
## Important Notes
- This board is the **only** one of the two with free hardware-PWM GPIO; Controller A has none. Gauge driving belongs here.
- The wired link's physical layer is unresolved: A's GPIO 44 reaches its terminal block only through an RS485 transceiver. Check `wiki/pages/open-questions.md` #1 before changing wiring.
- Planned: a redundant wireless leg (BLE or ESP-NOW) alongside the wire — design notes in `wiki/pages/link-redundancy.md`.
+5 -7
View File
@@ -41,7 +41,7 @@ pip install platformio
**IMPORTANT**: Before building, verify the display pin assignments in `src/display_init.cpp` match your board's schematic.
See `PIN_CONFIG.md` for details on pin configuration.
Pins are fixed in `src/modules/display_init.cpp` and were verified against the Waveshare demo code. See `CLAUDE.md`.
### 3. Build and Upload
@@ -60,8 +60,6 @@ pio device monitor
```
ESP32-S3-LCD-1.3/
├── .docs/ # Documentation
│ └── ESP32-S3-LCD-1.3-Implementation-Guide.md
├── include/
│ ├── config/
│ │ └── lv_conf.h # LVGL 8.4.0 configuration
@@ -78,12 +76,12 @@ ESP32-S3-LCD-1.3/
│ ├── main.cpp # Phase 1 main application
│ └── display_init.cpp # Display driver implementation
├── platformio.ini # PlatformIO configuration
├── PIN_CONFIG.md # ⚠️ Pin configuration guide
├── PROJECT_STRUCTURE.md # Detailed structure documentation
├── CLAUDE.md # Developer guide (pins, build, architecture)
├── wiki/ # Second-brain knowledge base (Obsidian vault)
└── README.md # This file
```
See `PROJECT_STRUCTURE.md` for detailed documentation.
See `CLAUDE.md` for the developer guide and `wiki/index.md` for domain knowledge.
## Phase 1 Features
@@ -200,7 +198,7 @@ pio run
- **Phase 4**: Data validation and error handling
- **Phase 5**: Polish and optimization
See `.docs/ESP32-S3-LCD-1.3-Implementation-Guide.md` for full roadmap.
See `wiki/pages/open-questions.md` for the current roadmap.
## Resources
+1
View File
@@ -0,0 +1 @@
{}
+1
View File
@@ -0,0 +1 @@
{}
+33
View File
@@ -0,0 +1,33 @@
{
"file-explorer": true,
"global-search": true,
"switcher": true,
"graph": true,
"backlink": true,
"canvas": true,
"outgoing-link": true,
"tag-pane": true,
"footnotes": false,
"properties": true,
"page-preview": true,
"daily-notes": true,
"templates": true,
"note-composer": true,
"command-palette": true,
"slash-command": false,
"editor-status": true,
"bookmarks": true,
"markdown-importer": false,
"zk-prefixer": false,
"random-note": false,
"outline": true,
"word-count": true,
"slides": false,
"audio-recorder": false,
"workspaces": false,
"file-recovery": true,
"publish": false,
"sync": true,
"bases": true,
"webviewer": false
}
+22
View File
@@ -0,0 +1,22 @@
{
"collapse-filter": true,
"search": "",
"showTags": false,
"showAttachments": false,
"hideUnresolved": false,
"showOrphans": true,
"collapse-color-groups": true,
"colorGroups": [],
"collapse-display": true,
"showArrow": false,
"textFadeMultiplier": 0,
"nodeSizeMultiplier": 1,
"lineSizeMultiplier": 1,
"collapse-forces": true,
"centerStrength": 0.518713248970312,
"repelStrength": 10,
"linkStrength": 1,
"linkDistance": 250,
"scale": 1,
"close": true
}
+226
View File
@@ -0,0 +1,226 @@
{
"main": {
"id": "774c780921b53def",
"type": "split",
"children": [
{
"id": "954c43c42df8cdd2",
"type": "tabs",
"children": [
{
"id": "414d380b45e2466d",
"type": "leaf",
"state": {
"type": "empty",
"state": {},
"icon": "lucide-file",
"title": "New tab"
}
}
]
},
{
"id": "363779a2b8b90c3d",
"type": "tabs",
"children": [
{
"id": "0a7c7593372ec79f",
"type": "leaf",
"state": {
"type": "graph",
"state": {},
"icon": "lucide-git-fork",
"title": "Graph view"
}
}
]
}
],
"direction": "vertical"
},
"left": {
"id": "d8898dd3bdf58935",
"type": "split",
"children": [
{
"id": "7321f47172a21ff0",
"type": "tabs",
"children": [
{
"id": "d1e54c160baeb57c",
"type": "leaf",
"state": {
"type": "file-explorer",
"state": {
"sortOrder": "alphabetical",
"autoReveal": false,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-folder-closed",
"title": "Files"
}
},
{
"id": "2ee3f5593994553a",
"type": "leaf",
"state": {
"type": "search",
"state": {
"query": "",
"matchingCase": false,
"explainSearch": false,
"collapseAll": false,
"extraContext": false,
"sortOrder": "alphabetical"
},
"icon": "lucide-search",
"title": "Search"
}
},
{
"id": "40c96343377ed0ae",
"type": "leaf",
"state": {
"type": "bookmarks",
"state": {
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-bookmark",
"title": "Bookmarks"
}
}
]
}
],
"direction": "horizontal",
"width": 300
},
"right": {
"id": "06f3bf565487158d",
"type": "split",
"children": [
{
"id": "c0093cbf91c471d6",
"type": "tabs",
"children": [
{
"id": "8ccd82c42c14581d",
"type": "leaf",
"state": {
"type": "backlink",
"state": {
"collapseAll": false,
"extraContext": false,
"sortOrder": "alphabetical",
"showSearch": false,
"searchQuery": "",
"backlinkCollapsed": false,
"unlinkedCollapsed": true
},
"icon": "links-coming-in",
"title": "Backlinks"
}
},
{
"id": "8b68e6490707c94f",
"type": "leaf",
"state": {
"type": "outgoing-link",
"state": {
"linksCollapsed": false,
"unlinkedCollapsed": true
},
"icon": "links-going-out",
"title": "Outgoing links"
}
},
{
"id": "950d623f020ec709",
"type": "leaf",
"state": {
"type": "tag",
"state": {
"sortOrder": "frequency",
"useHierarchy": true,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-tags",
"title": "Tags"
}
},
{
"id": "666c9e1cc6cc3dbc",
"type": "leaf",
"state": {
"type": "all-properties",
"state": {
"sortOrder": "frequency",
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-archive",
"title": "All properties"
}
},
{
"id": "0acd0e2cf0259623",
"type": "leaf",
"state": {
"type": "outline",
"state": {
"followCursor": false,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-list",
"title": "Outline"
}
}
]
}
],
"direction": "horizontal",
"width": 300,
"collapsed": true
},
"left-ribbon": {
"hiddenItems": {
"switcher:Open quick switcher": false,
"graph:Open graph view": false,
"canvas:Create new canvas": false,
"daily-notes:Open today's daily note": false,
"templates:Insert template": false,
"command-palette:Open command palette": false,
"bases:Create new base": false
}
},
"active": "414d380b45e2466d",
"lastOpenFiles": [
"pages/sedyhRU0S",
"pages/sedIT5Pq3",
"sources/sedWvixlJ",
"pages/sedybYBYo",
"pages/sedqYSTHS",
"sedvhzw6Z",
"Welcome.md",
"log.md",
"log.md.tmp.8664.194cf365eeff",
"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",
"pages/esp32-s3-lcd-1-3.md",
"CLAUDE.md",
"raw/ESP32-S3-LCD-1.3-details-7.jpg"
]
}
+79
View File
@@ -0,0 +1,79 @@
# Wiki Schema
This directory is a **personal knowledge wiki** for the ESP32-S3-LCD-1.3 project — Controller B, the slave/extension unit of the BMW M57N → Nissan Patrol swap display system. It is maintained by the LLM agent; the human curates sources and asks questions. Read this file before doing anything in `wiki/`.
It is the sibling of the wiki in `../../ESP32-S3-Touch-LCD-5B/wiki/` (Controller A). The two repos are separate git repositories with separate remotes. **Never create or edit files outside this repo's directory.** Cross-references into the sibling wiki are plain text, not `[[wikilinks]]` (Obsidian vaults do not link across vaults) — write them as `(sibling: 5B wiki → page-name)`.
## What this wiki is for
Domain knowledge that is NOT derivable from the firmware repo:
- Waveshare ESP32-S3-LCD-1.3 hardware: pinout, free GPIO, peripherals, power, quirks, gotchas
- The link between Controller A and Controller B: physical layer, packet contract, timing, failure modes, and the wired + BLE redundancy design
- Controller B's outputs into the Nissan Patrol: driving the cluster's RPM and coolant-temperature gauges, driver electronics, cluster behaviour
- Design decisions and their rationale; what was tried and why it was rejected
- Findings from datasheets, forum posts, Waveshare docs, bench measurements, scope traces
What does NOT belong here: code structure, build commands, firmware implementation details. The repo (its root `CLAUDE.md` and `README.md`) is the source of truth for those. The wiki may *reference* firmware facts when they matter for domain reasoning (e.g. "firmware currently times out after 1 s without a packet"), always marked `(repo)`.
Division of labour with the sibling wiki: **CAN bus decoding, the BMW engine, the donor vehicle and the swap itself live in the 5B wiki.** This wiki only records what Controller B needs from that work (which signals it consumes, which packet fields carry them). Do not duplicate CAN ID tables here — point at the sibling.
## Layout
```
wiki/
CLAUDE.md # this schema — co-evolves with the workflow
index.md # catalog of all pages, by category — update on EVERY change
log.md # append-only chronological record of ingests/queries/lints
raw/ # immutable source documents (web clips, PDFs, photos, scope captures, logs) — NEVER edit
sources/ # one summary page per raw source
pages/ # entity & concept pages (the heart of the wiki)
```
## Page conventions
- Filenames: kebab-case, e.g. `esp32-s3-lcd-1-3.md`.
- Every page starts with YAML frontmatter:
```yaml
---
type: entity | concept | source | synthesis
tags: [hardware, link, gauges, ble, ...]
updated: 2026-09-21
---
```
- Link liberally with `[[wikilinks]]`. A link to a not-yet-existing page marks future work, not an error.
- **Confidence labels are mandatory for factual claims** — this unit drives real gauges in a real vehicle:
- `(verified)` — confirmed on real hardware / with a meter or scope by the user
- `(source: X)` — from an ingested source in `raw/` (summarised in `sources/`)
- `(repo)` — what the firmware currently does (not necessarily correct!)
- `(sibling: 5B wiki → page)` — established in the Controller A wiki; check there before relying on it
- `(unverified)` — LLM prior knowledge, forum lore, or a design proposal; treat as a hypothesis
- Contradictions between sources — including between the two repos' copies of the shared protocol header — get flagged inline with a `> [!warning]` callout, not silently resolved.
## Workflows
### Ingest
1. User drops a file into `raw/` and asks to process it.
2. Read it fully. Discuss key takeaways with the user if interactive.
3. Write `sources/<name>.md`: frontmatter, 1-paragraph summary, key facts as bullets, relevance to open questions.
4. Update every affected page in `pages/` — integrate, don't append blindly. Flag contradictions.
5. Update `index.md`, append to `log.md`.
### Query
1. Read `index.md` first, then drill into relevant pages. If the question touches CAN decoding or the vehicle, also read the sibling wiki's `index.md`.
2. Synthesize an answer with citations (page links + confidence labels).
3. If the answer is durable (a comparison, an analysis, a decision), file it as a new page and index it.
### Lint (periodic, on request)
Check for: contradictions, stale claims, orphan pages, `[[links]]` to pages worth creating, unverified claims that could now be verified, drift between this repo's and the sibling repo's protocol header, gaps worth a web search. Report findings; fix with user's blessing.
## Log format
Append-only. Each entry starts with `## [YYYY-MM-DD] <op> | <title>` where `<op>` is `ingest`, `query`, `lint`, `update`, or `setup`. Greppable with `grep "^## \[" log.md`.
## Prime directives
1. `raw/` is immutable.
2. Never let an `(unverified)` claim silently upgrade itself — only real-world verification by the user promotes a claim to `(verified)`.
3. Keep `index.md` and `log.md` current on every operation; a stale index is worse than no index.
4. Nothing outside this repo directory is ever written by work on this wiki.
+27
View File
@@ -0,0 +1,27 @@
---
type: index
updated: 2026-09-21
---
# Index
Catalog of every page in the wiki. Read this first when answering questions. Keep current on every change. For CAN decoding, the BMW engine and the vehicle swap, read the sibling wiki at `../../ESP32-S3-Touch-LCD-5B/wiki/index.md` instead of duplicating here.
## Entities
- [[esp32-s3-lcd-1-3]] — Waveshare 1.3" round-display board (Controller B): specs, the **verified 16-pin header pinout** (IO1–5, IO7–14 all free-function), GPIO budget (10 clean spares), CH343 console on UART0, BLE 5
## 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
## 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
## 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
+19
View File
@@ -0,0 +1,19 @@
# Log
Append-only. `grep "^## \[" log.md | tail -5` for recent activity.
## [2026-09-21] setup | Wiki instantiated
Created schema (`CLAUDE.md`, modelled on the sibling 5B wiki with a sibling-reference convention and a no-files-outside-this-repo directive), `index.md`, `log.md`, and four seed pages from repo knowledge plus the day's investigation: [[esp32-s3-lcd-1-3]], [[controller-link]], [[link-redundancy]], [[patrol-gauge-outputs]], [[open-questions]]. Two sources: [[pinout-photo-details-7]] (photo copied from `.docs/` into `raw/`) and [[waveshare-wiki-esp32-s3-lcd-1-3]] (condensed web fetch, flagged for a verbatim re-clip). Deleted Obsidian's default `Welcome.md`.
Findings recorded during setup:
- Header pinout verified from the photo: IO1–5 and IO7–14, 13 free-function GPIOs; the wiring guide's IO35–42 table is wrong.
- Controller A cannot drive the Patrol gauges (no free native GPIO; DO terminals are I2C-expander + optocoupler). B can, via LEDC on IO7/IO8 — proposal only.
- A transmits on GPIO 44 (code), not 43 (two stale docs). GPIO 44 leaves the 5B only as an RS485 A/B pair — how that reaches B's IO1 is unknown and is now open question #1.
- The two repos' `gear_position_t` enums have drifted (Sport/Manual vs M1–M6 at values 4+). Open question #2.
- The packet has no RPM field; A has RPM verified from CAN 0x0AA. `engine_oil_temp` has no real source on this engine.
- Redundancy design space captured (RS485 / BLE GATT / ESP-NOW; failover on B; A transmits on both paths always). Nothing decided.
## [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.
+64
View File
@@ -0,0 +1,64 @@
---
type: concept
tags: [link, uart, protocol, architecture]
updated: 2026-09-21
---
# Controller Link (A → B)
The system is two ESP32-S3 boards. Controller A (Waveshare ESP32-S3-Touch-LCD-5B, sibling repo) reads the BMW PT-CAN bus and owns all decoding; Controller B ([[esp32-s3-lcd-1-3]], this repo) is a **slave / extension**: it consumes a compact packet, displays it, and will drive the Patrol gauges from it ([[patrol-gauge-outputs]]).
```
BMW PT-CAN ──▶ Controller A (5B) ──UART 5 Hz──▶ Controller B (1.3)
╰── BLE (planned, redundant) ──╯ → [[link-redundancy]]
```
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))
- 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)`
### What each field actually carries today (sibling: 5B wiki → can-id-candidates)
| Field | Source on A | Status |
|---|---|---|
| `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 |
| `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]] |
## Pins
- A transmits on **GPIO 44** (`uart_manager.cpp`, `UART_TX_PIN 44`) `(repo)`; RX 43 unused
- B receives on **IO1** (left header, pin 4), TX IO2 unused `(repo)`
> [!warning] Two docs said A transmits on GPIO 43 (both fixed or deleted 2026-09-21)
> 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]].
## Protocol drift between the two repos
> [!warning] The `gear_position_t` enums differ `(repo, 2026-09-21)`
> - **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
>
> Same byte on the wire, different meanings: a value of 4 is "Sport" to B and "1st gear" to A. One side must be changed and `PACKET_VERSION` bumped. Which side is correct depends on what A's CAN parser actually emits now — check its `can_driver.cpp` before touching B.
Also note A's protocol header now says all CAN IDs are 11-bit and the old placeholder map is dead; B's copy of the header still carries the placeholder CAN section. Harmless (B never parses CAN) but confusing — strip it when the enums are reconciled.
## Change discipline
Any new signal (RPM first) means, in order: add the field and a `valid_flags` bit on A → bump `PACKET_VERSION` → copy the header to B → B rejects packets with an unexpected version → B's UI/gauge code consumes the field. The version byte exists precisely so a stale B fails loudly instead of misreading bytes.
## Related
[[esp32-s3-lcd-1-3]] · [[link-redundancy]] · [[patrol-gauge-outputs]] · [[open-questions]]
+76
View File
@@ -0,0 +1,76 @@
---
type: entity
tags: [hardware, waveshare, display, gpio]
updated: 2026-09-21
---
# Waveshare ESP32-S3-LCD-1.3
Controller B of the [[controller-link]] — the compact secondary unit. Receives the sensor stream from Controller A, shows it on a 1.3" round-masked display, and is the board chosen to drive the Patrol cluster gauges ([[patrol-gauge-outputs]]) because it is the only one of the two with free hardware-PWM pins on a header.
## Specs (source: waveshare-wiki-esp32-s3-lcd-1-3)
- ESP32-S3R8: Xtensa LX7 dual-core @ 240 MHz, 512 KB SRAM, 384 KB ROM
- 16 MB external flash, 8 MB PSRAM (firmware builds with `qio_opi` memory type `(repo)`)
- 1.3" IPS LCD, 240×240, 262K colour, ST7789VW over SPI; the "round" look is a software circular mask `(repo)`
- QMI8658 six-axis IMU (accelerometer + gyro) on I2C — pins not stated by the wiki; unused by firmware `(repo)`
- TF card slot — pins not stated by the wiki; unused by firmware `(repo)`
- 2.4 GHz Wi-Fi 802.11 b/g/n + **Bluetooth 5 (BLE)**, onboard ceramic patch antenna — the basis of the BLE half of [[link-redundancy]]
- USB Type-C with a **CH343 USB-serial bridge** (WCH-CH343DS1), not native USB-CDC. Debug `Serial` therefore rides UART0 `(repo)`
- Power: 5 V over USB-C; MX1.25 single-cell LiPo connector with PL4054 charger and charge LED; ME6217C33M5G 3.3 V LDO rated 800 mA max
- "16PIN GPIO lead-out" = the two 8-pin headers below
- Operating temperature, power draw, dimensions and weight: **not stated** on the product wiki `(source: waveshare-wiki-esp32-s3-lcd-1-3)` → [[open-questions]]
## Header pinout (verified from the Waveshare pinout photo, [[pinout-photo-details-7]])
Two 8-pin 2.54 mm headers, one per side, viewed with the USB-C at the top:
| Left header (top→bottom) | Right header (top→bottom) |
|---|---|
| 5V | IO14 |
| GND | IO13 |
| 3V3 (OUT) | IO12 |
| IO1 | IO11 |
| IO2 | IO10 |
| IO3 | IO9 |
| IO4 | IO8 |
| IO5 | IO7 |
Waveshare marks every one of the 13 GPIOs as UART / PWM / I2S / ADC / I2C / SPI capable — i.e. plain ESP32-S3 pins routed through the GPIO matrix, no fixed function.
> [!warning] The former `.docs/UART_WIRING_GUIDE.md` (deleted 2026-09-21) listed a 13-pin header carrying IO35–IO42 `(repo)`. That is wrong: IO38–IO42 are the display's SPI lines and never reach a header, and IO35–37 are the OPI PSRAM bus. The photo is the authoritative pinout.
## GPIO budget
Internally committed `(repo)`:
| GPIO | Function |
|---|---|
| 40 / 41 | LCD SCLK / MOSI |
| 38 / 39 / 42 | LCD DC / CS / RST |
| 20 | LCD backlight, LEDC PWM 0–255 (default 128) |
| 43 / 44 | UART0 to the CH343 USB bridge = debug console `(unverified — inferred from the CH343 being on UART0)` |
| 35–37 | OPI PSRAM `(unverified — standard for R8 modules)` |
Header GPIOs and their current use `(repo)`:
| GPIO | Use today | Note |
|---|---|---|
| IO1 | UART1 RX from Controller A | keep |
| IO2 | UART1 TX (link is receive-only, so idle) | effectively free |
| IO3 | free | S3 strapping pin (JTAG select) — avoid |
| IO4, IO5 | free | |
| IO7–IO14 | free | proposed home of the gauge outputs → [[patrol-gauge-outputs]] |
Net: **10 clean, unconstrained GPIOs** (IO4, IO5, IO7–IO14) plus IO2 and IO3 with caveats.
## Firmware-side facts worth knowing (repo)
- Display driven by LovyanGFX 1.1 + LVGL 8.4.0, 80 MHz SPI write; LVGL task on Core 1, UART receiver on Core 0
- Warning thresholds baked in: coolant 110 °C, engine oil 130 °C, gearbox oil 130 °C, battery below 11.0 V
- Link considered lost after 1000 ms without a valid packet → [[controller-link]]
- Original implementation guide proposed the link on GPIO 43/44, which would have collided with the CH343 console; the shipped firmware moved it to IO1 `(repo)`
## Related
[[controller-link]] · [[link-redundancy]] · [[patrol-gauge-outputs]] · [[waveshare-wiki-esp32-s3-lcd-1-3]] · [[pinout-photo-details-7]] · [[open-questions]]
+42
View File
@@ -0,0 +1,42 @@
---
type: concept
tags: [link, ble, redundancy, design, esp-now]
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.
## Why redundancy matters more once B drives gauges
Today a lost link only blanks a secondary display. Once B drives the cluster's tachometer and coolant gauge ([[patrol-gauge-outputs]]), a lost link means the driver's primary instruments go dead or, worse, freeze at the last value. The failover policy on B must therefore also define what the gauges do during an outage (drop to zero, hold with a warning, or sweep to a "no data" position).
## Transport options
| Transport | Pros | Cons | Notes |
|---|---|---|---|
| **UART TTL, direct wire** (today) | trivial, 23 bytes @ 5 Hz is nothing | 3.3 V single-ended over a car harness is noise-prone and has no ground-offset tolerance | Fine on the bench; questionable in a vehicle over more than a few cm |
| **RS485 pair** | differential, automotive-grade noise immunity, tens of metres; **A already has an SP3485 on its terminal block** | B has no transceiver — needs a 3.3 V MAX3485/SP3485 module on IO1 (+ a free GPIO if the module lacks auto-direction) | This may already be what is wired — see the physical-layer question in [[controller-link]] |
| **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 |
## 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.
2. Deduplicate on `packet_id` + `timestamp_ms` (both already in the payload) so a frame arriving on both paths is applied once.
3. **Prefer wired** when both are alive; fall to wireless when the wired path has been silent > N ms (N smaller than the display's 1000 ms lost-link threshold, e.g. 400 ms = two missed frames).
4. Show the active source on the display (small glyph) so a silently degraded wire is noticed on the bench, not in traffic.
5. Gauge behaviour during a total outage is a separate decision → [[open-questions]].
A-side implication: A must transmit on both paths simultaneously, always — not "switch to BLE when UART fails", because A cannot tell that B stopped hearing it (the link is one-way). Simultaneous transmit is cheap at 5 Hz.
## Open decisions
- BLE vs ESP-NOW for the wireless leg (latency, reconnect behaviour, RAM on A).
- Whether the wired leg becomes RS485 end-to-end (probably yes if the run is longer than a dash-panel jumper).
- Whether B should ever talk back (ACK/heartbeat) — would let A alarm on a dead B, at the cost of the current one-way simplicity.
## Related
[[controller-link]] · [[patrol-gauge-outputs]] · [[esp32-s3-lcd-1-3]] · [[open-questions]]
+45
View File
@@ -0,0 +1,45 @@
---
type: synthesis
tags: [meta, todo]
updated: 2026-09-21
---
# Open Questions
The research frontier for Controller B. Answering any of these should trigger updates across the wiki. Ordered roughly by how much they block progress.
## 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]]
## 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]]
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]]
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
9. **Operating temperature and power draw are not on Waveshare's product wiki** for this board `(source: waveshare-wiki-esp32-s3-lcd-1-3)`. The 5B's spec is 0–65 °C; assume similar until a datasheet says otherwise. Dashboard mounting in a Patrol will see both extremes.
10. **Vehicle power for B.** The board takes 5 V USB or a LiPo — no wide-input regulator like the 5B has. Needs an automotive 12 V → 5 V buck with transient protection, or a 5 V feed from A `(unverified)`.
11. **IMU and TF-card GPIOs** are not stated on the product wiki. Irrelevant unless a future feature wants them, but they might share pins with the header (unlikely — the header GPIOs are IO1–5, IO7–14).
12. **Is IO3 safe to use as an output?** It is a strapping pin on the S3; avoided for now.
## Answered
- ~~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]]
- ~~Is the header IO35–IO42 as the wiring guide says?~~ → **No**, that table is wrong; see the photo. (verified, 2026-09-21)
## Sourcing wishlist
- Waveshare **schematic PDF** for ESP32-S3-LCD-1.3 (`https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/ESP32S3_1.3inch.pdf`; demo code zip `https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/ESP32-S3-LCD-1.3-Demo.zip`) — would settle the IMU/TF pins, confirm the CH343 on UART0, and show the backlight and battery circuits
- A **verbatim Obsidian web clip** of the Waveshare product wiki into `raw/` (the current source page is from a condensed fetch, not a full clip)
- 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
+49
View File
@@ -0,0 +1,49 @@
---
type: concept
tags: [gauges, pwm, ledc, nissan-patrol, hardware, design]
updated: 2026-09-21
---
# Driving the Patrol Cluster Gauges
Goal (user, 2026-09-21): generate signals from Controller B to drive the Nissan Patrol instrument cluster's **RPM (tachometer)** and **engine coolant temperature** gauges, fed by the BMW data that arrives over the [[controller-link]].
## Why B and not A
Controller A (5B) has no free native GPIO on any header: the RGB LCD, I2C, CAN, RS485, USB and PSRAM consume every pin, and its two "DO" terminals are optocoupled outputs driven through a CH422G I2C expander — no hardware timer can reach them `(sibling: 5B wiki → esp32-s3-touch-lcd-5b; schematic reviewed 2026-09-21)`. B exposes 13 free GPIOs on headers ([[esp32-s3-lcd-1-3]]), all usable by the ESP32-S3 LEDC peripheral.
## Two very different signals
| 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** |
| 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)
- **IO7** → tachometer pulse output
- **IO8** → coolant gauge PWM output
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.
## Electrical interface — mandatory external stage (unverified)
3.3 V logic drives neither gauge directly.
- **Tach input**: Patrol clusters expect roughly 12 V-level pulses (ignition-coil negative or ECU tach output, open-collector with the cluster's internal pull-up). Use an NPN or logic-level N-MOSFET as an open-collector pulling the tach wire to ground; if the cluster has no internal pull-up, add one to +12 V (a few kΩ). Never feed 12 V back into IO7.
- **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.
## 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]]
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).
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]].
## Related
[[esp32-s3-lcd-1-3]] · [[controller-link]] · [[link-redundancy]] · [[open-questions]]

Before

Width:  |  Height:  |  Size: 205 KiB

After

Width:  |  Height:  |  Size: 205 KiB

+30
View File
@@ -0,0 +1,30 @@
---
type: source
tags: [hardware, waveshare, pinout, gpio]
updated: 2026-09-21
raw: raw/ESP32-S3-LCD-1.3-details-7.jpg
---
# Waveshare pinout photo (details-7)
`raw/ESP32-S3-LCD-1.3-details-7.jpg` — Waveshare's annotated product photo of the board's two side headers, copied from this repo's former `.docs/` (deleted 2026-09-21) on 2026-09-21. Original URL: `https://www.waveshare.com/img/devkit/ESP32-S3-LCD-1.3/ESP32-S3-LCD-1.3-details-7.jpg`.
## What it shows (verified by reading the image, 2026-09-21)
Board viewed with the USB-C connector at the top. Two 8-pin headers:
- **Left, top→bottom:** 5V · GND · 3V3(OUT) · IO1 · IO2 · IO3 · IO4 · IO5
- **Right, top→bottom:** IO14 · IO13 · IO12 · IO11 · IO10 · IO9 · IO8 · IO7
Each GPIO is tagged with the capability badges UART · PWM · I2S · ADC · I2C · SPI — i.e. no pin on the headers has a fixed function.
Also visible: the ESP32-S3 module, a Winbond flash chip, the TF card slot on the front face, and a battery/charge connector at the top.
## Relevance
- The authoritative header pinout; it **contradicts** the IO35–IO42 table in the former `.docs/UART_WIRING_GUIDE.md` `(repo)` → [[esp32-s3-lcd-1-3]]
- Proves there are 13 free-function GPIOs, which is what makes B the gauge driver → [[patrol-gauge-outputs]]
## Related
[[esp32-s3-lcd-1-3]] · [[waveshare-wiki-esp32-s3-lcd-1-3]]
@@ -0,0 +1,39 @@
---
type: source
tags: [hardware, waveshare, datasheet]
updated: 2026-09-21
url: https://www.waveshare.com/wiki/ESP32-S3-LCD-1.3
---
# Waveshare product wiki — ESP32-S3-LCD-1.3
> [!note] Not a verbatim clip
> This page was produced from a condensed web fetch on 2026-09-21, not from a full Obsidian web clip in `raw/`. Numbers below are as quoted by the fetch. The product wiki's tables (pin definitions, dimensions, demo pin maps) were **not** captured — re-clip the page verbatim into `raw/` to complete the ingest. → [[open-questions]] sourcing wishlist.
Official Waveshare page for the board. Confirms the core spec, the CH343 USB bridge, the battery circuit, BLE 5, and the "16-pin GPIO" lead-out, but is silent on almost every pin assignment and on environmental limits.
## Key facts
- MCU: ESP32-S3R8, Xtensa LX7 dual-core up to 240 MHz; 512 KB SRAM, 384 KB ROM
- 16 MB flash, 8 MB PSRAM
- 1.3" LCD 240×240, 262K colour, ST7789VW; backlight controllable
- QMI8658 six-axis IMU — I2C pins **not stated**
- TF card slot — pins **not stated**
- RGB LED mentioned — pin **not stated**
- USB-serial bridge: WCH CH343 (CH343DS1_V16), Type-C "USB & UART"; automatic download circuit
- Power: MX1.25 LiPo connector, PL4054 charger with charge LED, 3.7–4.2 V cells; ME6217C33M5G LDO, 800 mA max
- Wireless: 2.4 GHz Wi-Fi b/g/n + Bluetooth 5 (BLE), onboard ceramic patch antenna
- "Lead out the 16PIN GPIO pin" — consistent with the two 8-pin headers in [[pinout-photo-details-7]] (3 power pins + 13 GPIO)
- Reset button on board; boot-mode entry **not stated**
- Operating temperature, power draw, dimensions, weight: **not stated**
- Sold as bare board, with plastic case, or with case + prism cube
## Relevance
- Establishes BLE 5 on B, the wireless half of [[link-redundancy]]
- Establishes CH343 on UART0 as the reason the link cannot use GPIO 43/44 on B → [[esp32-s3-lcd-1-3]]
- Raises the missing-environmental-spec and vehicle-power questions → [[open-questions]] #9, #10
## Related
[[esp32-s3-lcd-1-3]] · [[pinout-photo-details-7]]