Init new era, with wiki integrated.

This commit is contained in:
2026-07-15 12:17:06 +02:00
commit 37f98a241f
67 changed files with 10396 additions and 0 deletions
+604
View File
@@ -0,0 +1,604 @@
# CAN Bus Integration Guide
Complete guide for BMW CAN Bus integration with ESP32-S3-Touch-LCD-5B (Controller A).
## Table of Contents
- [Overview](#overview)
- [Hardware Setup](#hardware-setup)
- [BMW CAN Message Specifications](#bmw-can-message-specifications)
- [Testing with CAN Simulators](#testing-with-can-simulators)
- [Connecting to Real BMW CAN Bus](#connecting-to-real-bmw-can-bus)
- [Troubleshooting](#troubleshooting)
---
## Overview
Controller A (ESP32-S3-Touch-LCD-5B) receives BMW vehicle data via CAN Bus and transmits it to Controller B (ESP32-S3-LCD-1.3) via UART at 5Hz.
**Key Features:**
- **LISTEN_ONLY mode** - Safe, non-intrusive monitoring (no transmission)
- **500 Kbps baud rate** - Standard BMW CAN speed
- **Real-time parsing** - Extracts temperature, gear, and voltage data
- **Thread-safe** - Mutex-protected shared data structure
- **Automatic fallback** - Uses dummy data when CAN is disabled
---
## Hardware Setup
### GPIO Pin Connections
```
ESP32-S3-Touch-LCD-5B (Controller A)
┌─────────────────────────────────┐
│ │
│ GPIO 15 (CAN_TX) ──────────┐ │
│ GPIO 16 (CAN_RX) ──────────┼──► To CAN Transceiver
│ GND ───────────────────────┘ │
│ │
└─────────────────────────────────┘
```
### CAN Transceiver Requirements
The ESP32-S3 TWAI peripheral requires an **external CAN transceiver** (e.g., TJA1050, MCP2551, SN65HVD230).
**Recommended Transceiver: SN65HVD230**
- 3.3V compatible (ESP32-S3 logic level)
- ISO 11898-2 compliant
- Low power consumption
**Wiring Diagram:**
```
ESP32-S3 SN65HVD230 BMW OBD-II / CAN Bus
GPIO 15 (TX) ───► D (TXD)
GPIO 16 (RX) ◄─── R (RXD)
3.3V ────────────► VCC
GND ─────────────► GND
CANH ───────────────► CAN High (Pin 6)
CANL ───────────────► CAN Low (Pin 14)
120Ω termination (only if at end of bus)
```
**Important Notes:**
- **Do NOT connect ESP32 GPIO pins directly to CAN bus** - you will damage the ESP32!
- Use proper CAN transceiver rated for 12V automotive systems
- Only add 120Ω termination resistor if you're at the physical end of the CAN bus
- BMW OBD-II CAN is on pins 6 (CAN-H) and 14 (CAN-L)
---
## BMW CAN Message Specifications
These are the configured CAN message IDs and data formats for BMW vehicles.
### Message ID: 0x4F - Engine Coolant Temperature
**Format:** Standard 11-bit CAN ID
**DLC:** 8 bytes
**Update Rate:** ~100ms
| Byte | Description | Format | Example |
|------|-------------|--------|---------|
| 0 | Coolant Temp | Raw + 40°C offset | 0x55 = 85°C (0x55 - 40 = 45°C actual) |
| 1-7 | Reserved | - | - |
**Parsing:**
```cpp
int16_t coolant_temp = can_to_temperature(data[0]); // Converts to 0.1°C units
// Example: data[0] = 0x55 (85 raw) → (85 - 40) * 10 = 450 (45.0°C)
```
---
### Message ID: 0x55 - Engine Oil Temperature
**Format:** Standard 11-bit CAN ID
**DLC:** 8 bytes
**Update Rate:** ~200ms
| Byte | Description | Format | Example |
|------|-------------|--------|---------|
| 0-6 | Reserved | - | - |
| 7 | Oil Temp | Raw + 40°C offset | 0x84 = 132°C (92°C actual) |
**Parsing:**
```cpp
int16_t engine_oil_temp = can_to_temperature(data[7]);
// Example: data[7] = 0x84 (132 raw) → (132 - 40) * 10 = 920 (92.0°C)
```
---
### Message ID: 0x201 - Gearbox Oil Temperature
**Format:** Standard 11-bit CAN ID
**DLC:** 8 bytes
**Update Rate:** ~200ms
| Byte | Description | Format | Example |
|------|-------------|--------|---------|
| 0-2 | Reserved | - | - |
| 3 | Gearbox Oil Temp | Raw + 40°C offset | 0x7D = 125°C (85°C actual) |
| 4-7 | Reserved | - | - |
**Parsing:**
```cpp
int16_t gearbox_oil_temp = can_to_temperature(data[3]);
// Example: data[3] = 0x7D (125 raw) → (125 - 40) * 10 = 850 (85.0°C)
```
---
### Message ID: 0x1001 - Gearbox Data (Extended)
**Format:** Extended 29-bit CAN ID
**DLC:** 8 bytes
**Update Rate:** ~50ms
| Byte | Description | Values | Notes |
|------|-------------|--------|-------|
| 0 | Gear Position | 0=P, 1=R, 2=N, 3=D, 4-9=M1-M6 | Current selector position |
| 1 | Current Gear | 1-8 | Actual engaged gear (0 if neutral) |
| 2-7 | Reserved | - | - |
**Parsing:**
```cpp
uint8_t gear_position = data[0]; // P/R/N/D/M selector
uint8_t current_gear = data[1]; // 1-8 for manual mode
```
**Gear Position Enum:**
```cpp
typedef enum {
GEAR_PARK = 0,
GEAR_REVERSE = 1,
GEAR_NEUTRAL = 2,
GEAR_DRIVE = 3,
GEAR_MANUAL_1 = 4,
GEAR_MANUAL_2 = 5,
GEAR_MANUAL_3 = 6,
GEAR_MANUAL_4 = 7,
GEAR_MANUAL_5 = 8,
GEAR_MANUAL_6 = 9
} gear_position_t;
```
---
### Message ID: 0x101F - Battery Voltage (Extended)
**Format:** Extended 29-bit CAN ID
**DLC:** 8 bytes
**Update Rate:** ~1000ms
| Byte | Description | Format | Example |
|------|-------------|--------|---------|
| 0 | Voltage High Byte | MSB of 16-bit value | 0x04 |
| 1 | Voltage Low Byte | LSB of 16-bit value | 0xD2 |
| 2-7 | Reserved | - | - |
**Parsing:**
```cpp
uint16_t raw_voltage = (data[0] << 8) | data[1]; // Big-endian
uint16_t battery_voltage = raw_voltage * 10; // Convert to 0.01V units
// Example: data = [0x04, 0xD2] → 0x04D2 = 1234 raw → 12340 (12.34V)
```
---
## Testing with CAN Simulators
Before connecting to a real vehicle, test the CAN Bus receiver using simulation tools.
### Option 1: Python-CAN with Virtual CAN (Linux)
**Setup Virtual CAN Interface:**
```bash
# Load virtual CAN kernel module
sudo modprobe vcan
# Create virtual CAN interface
sudo ip link add dev vcan0 type vcan
sudo ip link set up vcan0
# Verify interface
ip link show vcan0
```
**Python Test Script:**
Save as `bmw_can_simulator.py`:
```python
#!/usr/bin/env python3
"""
BMW CAN Bus Simulator for ESP32-S3-Touch-LCD-5B Testing
Sends realistic BMW CAN messages to test the receiver
"""
import can
import time
import random
# Create virtual CAN bus
bus = can.interface.Bus(channel='vcan0', bustype='socketcan')
def send_coolant_temp(temp_celsius=85):
"""Send engine coolant temperature (CAN ID 0x4F)"""
raw_value = int(temp_celsius + 40) # Add 40°C offset
msg = can.Message(
arbitration_id=0x4F,
data=[raw_value, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
is_extended_id=False
)
bus.send(msg)
print(f"[0x4F] Coolant Temp: {temp_celsius}°C (raw: 0x{raw_value:02X})")
def send_engine_oil_temp(temp_celsius=92):
"""Send engine oil temperature (CAN ID 0x55)"""
raw_value = int(temp_celsius + 40)
msg = can.Message(
arbitration_id=0x55,
data=[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, raw_value],
is_extended_id=False
)
bus.send(msg)
print(f"[0x55] Oil Temp: {temp_celsius}°C (raw: 0x{raw_value:02X})")
def send_gearbox_temp(temp_celsius=85):
"""Send gearbox oil temperature (CAN ID 0x201)"""
raw_value = int(temp_celsius + 40)
msg = can.Message(
arbitration_id=0x201,
data=[0x00, 0x00, 0x00, raw_value, 0x00, 0x00, 0x00, 0x00],
is_extended_id=False
)
bus.send(msg)
print(f"[0x201] Gearbox Temp: {temp_celsius}°C (raw: 0x{raw_value:02X})")
def send_gear_position(position=3, current_gear=4):
"""Send gearbox position and current gear (CAN ID 0x1001)"""
msg = can.Message(
arbitration_id=0x1001,
data=[position, current_gear, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
is_extended_id=True # Extended 29-bit ID
)
gear_names = ['P', 'R', 'N', 'D', '1', '2', '3', '4', '5', '6']
print(f"[0x1001] Gear: {gear_names[position]}, Current: {current_gear}")
bus.send(msg)
def send_battery_voltage(voltage_v=12.45):
"""Send battery voltage (CAN ID 0x101F)"""
raw_value = int(voltage_v * 100) # Convert to 0.01V units
high_byte = (raw_value >> 8) & 0xFF
low_byte = raw_value & 0xFF
msg = can.Message(
arbitration_id=0x101F,
data=[high_byte, low_byte, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
is_extended_id=True # Extended 29-bit ID
)
bus.send(msg)
print(f"[0x101F] Battery: {voltage_v}V (raw: 0x{raw_value:04X})")
def main():
"""Main simulation loop"""
print("BMW CAN Simulator Started - Press Ctrl+C to stop")
print("Configure ESP32 CAN interface to connect to vcan0 via USB-CAN adapter")
print("-" * 60)
try:
iteration = 0
while True:
iteration += 1
print(f"\n[Iteration {iteration}]")
# Simulate realistic temperature variations
coolant = 85 + random.randint(-3, 3)
oil = 92 + random.randint(-2, 2)
gearbox = 85 + random.randint(-2, 2)
voltage = 12.45 + random.uniform(-0.2, 0.2)
# Send all messages
send_coolant_temp(coolant)
time.sleep(0.01)
send_engine_oil_temp(oil)
time.sleep(0.01)
send_gearbox_temp(gearbox)
time.sleep(0.01)
send_gear_position(3, 4) # Drive, 4th gear
time.sleep(0.01)
send_battery_voltage(voltage)
# Update every 200ms (5Hz like UART transmission)
time.sleep(0.2)
except KeyboardInterrupt:
print("\n\nSimulator stopped")
bus.shutdown()
if __name__ == "__main__":
main()
```
**Run Simulator:**
```bash
# Install python-can
pip3 install python-can
# Run simulator
python3 bmw_can_simulator.py
```
**Connect ESP32 to Virtual CAN:**
You'll need a USB-CAN adapter (e.g., CANable, PCAN-USB) to bridge the virtual CAN to the ESP32's physical CAN pins.
---
### Option 2: Arduino CAN Transmitter
Use a second ESP32 or Arduino with CAN shield as a transmitter:
```cpp
#include <driver/twai.h>
#define TX_PIN GPIO_NUM_5
#define RX_PIN GPIO_NUM_4
void setup() {
Serial.begin(115200);
// Configure TWAI for transmission
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(TX_PIN, RX_PIN, TWAI_MODE_NORMAL);
twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
twai_driver_install(&g_config, &t_config, &f_config);
twai_start();
Serial.println("CAN Transmitter Ready");
}
void loop() {
// Send coolant temperature (85°C)
twai_message_t msg1;
msg1.identifier = 0x4F;
msg1.data_length_code = 8;
msg1.data[0] = 125; // 85 + 40 offset
twai_transmit(&msg1, pdMS_TO_TICKS(100));
// Send engine oil temp (92°C)
twai_message_t msg2;
msg2.identifier = 0x55;
msg2.data_length_code = 8;
msg2.data[7] = 132; // 92 + 40 offset
twai_transmit(&msg2, pdMS_TO_TICKS(100));
// Send gearbox temp (85°C)
twai_message_t msg3;
msg3.identifier = 0x201;
msg3.data_length_code = 8;
msg3.data[3] = 125; // 85 + 40 offset
twai_transmit(&msg3, pdMS_TO_TICKS(100));
// Send gear position (Drive, 4th gear)
twai_message_t msg4;
msg4.identifier = 0x1001;
msg4.extd = 1; // Extended ID
msg4.data_length_code = 8;
msg4.data[0] = 3; // Drive
msg4.data[1] = 4; // 4th gear
twai_transmit(&msg4, pdMS_TO_TICKS(100));
// Send battery voltage (12.45V)
twai_message_t msg5;
msg5.identifier = 0x101F;
msg5.extd = 1; // Extended ID
msg5.data_length_code = 8;
msg5.data[0] = 0x04; // High byte
msg5.data[1] = 0xD2; // Low byte (1234 = 12.34V)
twai_transmit(&msg5, pdMS_TO_TICKS(100));
Serial.println("Sent CAN test messages");
delay(200); // 5Hz update rate
}
```
---
## Connecting to Real BMW CAN Bus
### OBD-II Port Connection
**BMW OBD-II Pinout:**
```
┌─────────────┐
│ 1 2 3 4 │ Top Row
└─────────────┘
┌─────────────────┐
│ 5 6 7 8 9 │ Bottom Row
└─────────────────┘
```
| Pin | Signal | Description |
|-----|--------|-------------|
| 6 | CAN-H | CAN Bus High (connect to transceiver CANH) |
| 14 | CAN-L | CAN Bus Low (connect to transceiver CANL) |
| 4, 5 | GND | Ground (connect to transceiver GND) |
| 16 | +12V | Battery voltage (optional, can power CAN transceiver) |
**Connection Diagram:**
```
BMW OBD-II Port CAN Transceiver ESP32-S3
┌──────────────┐ ┌──────────────┐ ┌──────────┐
│ │ │ │ │ │
│ Pin 6 (CAN-H)│────────►│ CANH │ │ │
│ │ │ │ │ │
│ Pin 14(CAN-L)│────────►│ CANL │ │ │
│ │ │ │ │ │
│ Pin 4/5 (GND)│────────►│ GND ─────────┼────────►│ GND │
│ │ │ │ │ │
│ │ │ TXD ◄────────┼────────►│ GPIO 15 │
│ │ │ │ │ │
│ │ │ RXD ─────────┼────────►│ GPIO 16 │
│ │ │ │ │ │
│ │ │ VCC ◄────────┼────────►│ 3.3V │
└──────────────┘ └──────────────┘ └──────────┘
```
**Safety Checklist:**
- [ ] Use proper CAN transceiver (SN65HVD230 or TJA1050)
- [ ] Verify 500 Kbps baud rate setting
- [ ] Ensure LISTEN_ONLY mode is active (code already configured)
- [ ] Double-check wiring before connecting to vehicle
- [ ] Test with CAN simulator first
- [ ] Monitor serial output for errors during initial connection
**Enabling CAN on ESP32:**
1. Power on ESP32-S3-Touch-LCD-5B
2. Navigate to Settings screen
3. Toggle **"Enable CAN Bus"** switch to ON
4. Monitor serial output (115200 baud):
```
[CANDrv] Initializing CAN subsystem...
[CANDrv] CAN task created successfully on Core 0
[CANTask] CAN task started on Core 0
[CANTask] Starting CAN reception...
[CANDrv] TWAI driver installed (GPIO15/GPIO16, 500Kbps, LISTEN_ONLY)
[CANDrv] TWAI driver started
[CANDrv] CAN alerts configured
[CANTask] CAN reception active
[CANDrv] ✓ Parsed CAN ID=0x4F (Standard format) [1/1 msgs parsed]
```
---
## Troubleshooting
### No CAN Messages Received
**Symptoms:** CAN toggle is ON, but no messages appear in serial monitor.
**Solutions:**
1. **Check Wiring:**
- Verify CAN-H and CAN-L are not swapped
- Check transceiver power (3.3V to VCC)
- Ensure ground connection
2. **Verify Baud Rate:**
- Confirm BMW CAN is 500 Kbps (most common)
- Some older BMWs use 125 Kbps - try changing in `can_driver.h`:
```cpp
#define CAN_BAUD_RATE TWAI_TIMING_CONFIG_125KBITS()
```
3. **Check Transceiver:**
- Measure voltages: CAN-H ~3.5V, CAN-L ~1.5V (recessive state)
- During activity: CAN-H/CAN-L should oscillate
4. **Serial Monitor Filtering:**
- Only BMW-specific IDs are logged
- Use `output_mode: content` in serial monitor to see all TWAI alerts
---
### CAN Bus Errors
**Symptoms:** Log shows bus errors or passive errors.
```
[CANTask] Bus error detected (count: 128)
[CANTask] TWAI controller has become error passive
```
**Solutions:**
1. **Check Termination:**
- Remove 120Ω resistor if you're NOT at the end of the CAN bus
- BMW CAN bus should already have termination
2. **Verify Logic Levels:**
- ESP32 GPIO is 3.3V - ensure transceiver is 3.3V compatible
- Do NOT use 5V transceiver without level shifters
3. **Inspect Physical Layer:**
- Check for loose connections
- Ensure twisted pair for CAN-H/CAN-L if using long wires
- Keep wiring away from high-current circuits
---
### Wrong Data Values
**Symptoms:** Temperatures or voltages are incorrect.
**Solutions:**
1. **Verify Message Format:**
- BMW CAN data may use different scaling factors
- Use CAN logger to inspect raw hex values
- Compare with known good values from OBD-II scanner
2. **Check Endianness:**
- Current implementation assumes big-endian for voltage
- If values are way off, try little-endian:
```cpp
uint16_t raw_voltage = data[1] << 8 | data[0]; // Little-endian
```
3. **Update Offsets:**
- Temperature offset may vary by vehicle year
- If temps are consistently off by a fixed amount, adjust in `automotive_data.h`:
```cpp
static inline int16_t can_to_temperature(uint8_t can_value, int16_t offset = -48) {
```
---
### Memory Issues
**Symptoms:** ESP32 crashes, resets, or CAN stops working after some time.
**Solutions:**
1. **Check Heap:**
- Monitor free heap: `ESP.getFreeHeap()`
- Reduce CAN RX queue size if needed (currently unlimited)
2. **Stack Overflow:**
- Increase CAN task stack size in `can_driver.h`:
```cpp
#define CAN_TASK_STACK_SIZE 8192 // Increase from 4096
```
---
## Next Steps
1. **Test with Simulator** - Verify CAN reception works before connecting to vehicle
2. **Connect to OBD-II** - Use proper transceiver and safety precautions
3. **Verify Data** - Compare readings with OBD-II scanner or instrument cluster
4. **Tune Scaling** - Adjust temperature offsets and voltage scaling if needed
5. **Document IDs** - Record any additional BMW CAN IDs you discover
---
## References
- ESP32 TWAI Driver: [Espressif Documentation](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/twai.html)
- ISO 11898-2: CAN Bus Physical Layer Standard
- BMW CAN Bus: Check BMW TIS (Technical Information System) for your specific model year
---
**Last Updated:** 2025-01-09
**Tested On:** ESP32-S3-Touch-LCD-5B with SN65HVD230 transceiver
Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

+656
View File
@@ -0,0 +1,656 @@
# 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**