21 KiB
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):
- UART OFF → CAN disabled
- CAN Toggle ON → CAN starts → UART auto-starts
- UART transmits real-time CAN data at 5 Hz
- 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:
- Initialize checksum to 0x00
- XOR with version byte
- XOR with length byte
- XOR with all 18 payload bytes in sequence
- 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:
- Start Marker Check: First byte == 0xAA
- End Marker Check: Last byte (offset 22) == 0x55
- Version Check: Protocol version == 0x01
- Length Check: Payload length == 0x12 (18 bytes)
- Checksum Validation: Calculated checksum matches received checksum
Error Recovery
On Validation Failure:
- Discard the corrupted packet
- Increment error counter (for diagnostics)
- Continue listening for next valid start marker (0xAA)
- 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:
- Search for start marker (0xAA) in incoming byte stream
- Read next 22 bytes as potential packet
- Validate end marker (0x55) at expected offset
- Verify version and length fields
- Calculate and compare checksum
- 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):
- CAN toggle ON in Settings screen?
- CAN messages being received? (check serial: "✓ Parsed CAN ID=...")
- UART auto-started? (check serial: "UART STARTED (triggered by CAN state)")
- Packets being sent? (check serial: "TX Packet #N (...)")
Controller B (Receiver):
- UART initialized on correct GPIO (RX = GPIO 1)?
- Baud rate set to 115200?
- Start marker (0xAA) being detected?
- Checksum validation passing?
- 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 instructionsCAN_BUS_INTEGRATION.md- CAN bus configuration and BMW message IDssrc/protocol/automotive_data.h- C structure definitionssrc/modules/uart_manager.cpp- Transmitter implementationsrc/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