Files
ESP32-S3-LCD-1.3/.docs/ESP32-S3-LCD-1.3-Implementation-Guide.md
T
2026-09-21 10:28:35 +02:00

26 KiB
Raw Blame History

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:

// 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

    cp ../ESP32-S3-Touch-LCD-5B/include/protocol/automotive_data.h include/protocol/
    
  2. Implement UART Receiver Module

    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

    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

[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

#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)

#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:

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:

#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):

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:

// 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:

// 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


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)