Files
ESP32-S3-Touch-LCD-5B/.docs/CAN_BUS_INTEGRATION.md
T

18 KiB

CAN Bus Integration Guide

Complete guide for BMW CAN Bus integration with ESP32-S3-Touch-LCD-5B (Controller A).

Table of Contents


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:

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:

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:

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:

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:

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:

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:

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

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

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

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