Building a J1939 CAN bus display using an ESP32 and an MCP2515 module is a fantastic project! It involves multiple layers of hardware and software, from low-level SPI communication to high-level J1939 protocol parsing and display rendering.
Here's a comprehensive guide to help you get started:
Project Overview
Goal: Create a display that reads J1939 messages from a CAN bus (e.g., from a truck, tractor, or industrial equipment) and shows relevant data like engine RPM, coolant temperature, fuel level, etc., on a screen.
Key Components:
- ESP32 Development Board: The main microcontroller, providing Wi-Fi, Bluetooth (optional), and plenty of processing power.
- MCP2515 CAN Bus Module (with TJA1050/SN65HVD230 Transceiver): The CAN controller chip that handles the physical layer communication with the CAN bus. It communicates with the ESP32 via SPI. Most readily available modules include the transceiver.
- Display:
- OLED (e.g., SSD1306 0.96"/1.3"): Simple, low power, good for basic text/numbers. Connects via I2C or SPI.
- TFT LCD (e.g., ST7735 1.8", ILI9341 2.4"/2.8"): Color, larger, good for graphics and multiple data points. Connects via SPI.
- Touchscreen LCD (e.g., ILI9341 with XPT2046): Adds user interaction.
- CAN Bus Connection:
- OBD-II Connector: If connecting to a vehicle with an OBD-II port (pins 6 and 14 for CAN High/Low).
- DB9 Connector: Common for industrial/heavy-duty applications.
- Bare Wires: If connecting directly to a CAN bus.
- Power Supply: A 5V power supply for the ESP32 (e.g., USB charger).
Hardware Setup
1. Components & Wiring Diagram
ESP32 Dev Board (e.g., ESP32-WROOM-32)
| ESP32 Pin Name | ESP32 GPIO Pin (Example) | Function |
|---|
| VSPI_SCK | GPIO18 | SPI Clock |
| VSPI_MISO | GPIO19 | SPI MISO |
| VSPI_MOSI | GPIO23 | SPI MOSI |
| GND | GND | Ground |
| 3V3 | 3V3 | Power (for display, if needed) |
| Any Digital Pin | GPIO5 (Recommended) | CS (Chip Select for MCP2515) |
| Any Digital Pin | GPIO2 (Recommended) | INT (Interrupt for MCP2515) |
Note: The default SPI pins for ESP32 are GPIO18, GPIO19, GPIO23. You can use other pins by explicitly defining them in your code if your ESP32 board has different defaults or you prefer other pins.
MCP2515 Module
| MCP2515 Pin Name | Connection to ESP32 | Function |
|---|
| SCK | ESP32 GPIO18 (VSPI_SCK) | SPI Clock |
| SI (MOSI) | ESP32 GPIO23 (VSPI_MOSI) | SPI Master Out Slave In |
| SO (MISO) | ESP32 GPIO19 (VSPI_MISO) | SPI Master In Slave Out |
| CS | ESP32 GPIO5 (or custom) | Chip Select |
| INT | ESP32 GPIO2 (or custom) | Interrupt (optional but recommended) |
| VCC | ESP32 5V (or external 5V) | Power (MCP2515 usually prefers 5V) |
| GND | ESP32 GND | Ground |
| CANH | CAN Bus High (e.g., OBD-II Pin 6) | CAN High Line |
| CANL | CAN Bus Low (e.g., OBD-II Pin 14) | CAN Low Line |
Display (Example: ILI9341 TFT LCD)
| Display Pin Name | Connection to ESP32 | Function |
|---|
| SCK | ESP32 GPIO18 (VSPI_SCK) | SPI Clock |
| MOSI | ESP32 GPIO23 (VSPI_MOSI) | SPI Master Out Slave In |
| MISO | ESP32 GPIO19 (VSPI_MISO) | SPI Master In Slave Out |
| CS | ESP32 GPIO15 (or custom) | Chip Select |
| DC (Data/Command) | ESP32 GPIO4 (or custom) | Data/Command Select |
| RST (Reset) | ESP32 GPIO16 (or custom) | Reset |
| VCC | ESP32 3V3 or 5V (check display spec) | Power (usually 3.3V) |
| GND | ESP32 GND | Ground |
Note: For OLED displays, the wiring will differ (often I2C: SDA, SCL, VCC, GND).
2. Physical Connection Tips
- Breadboard: Use a breadboard for initial prototyping.
- Power: Ensure your ESP32 can provide enough current for both the MCP2515 and the display. An external 5V power supply connected directly to the ESP32's 5V pin or USB port is usually sufficient.
- CAN Bus Termination: If your project is the only device on a small CAN bus segment, ensure there are 120-ohm resistors at both ends of the bus. Most vehicles/machinery already have proper termination.
- Shielded Cables: For CAN bus connections, use twisted-pair shielded cables to minimize noise.
Software Setup
1. Arduino IDE Setup
- Install Arduino IDE: Download from arduino.cc.
- Add ESP32 Board Manager:
- Go to
File > Preferences.
- In "Additional Boards Manager URLs," add:
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
- Go to
Tools > Board > Boards Manager...
- Search for "esp32" and install "esp32 by Espressif Systems".
- Select Your Board: Go to
Tools > Board > ESP32 Arduino and choose your specific ESP32 board (e.g., "ESP32 Dev Module").
2. Install Libraries
You'll need the following libraries. Go to Sketch > Include Library > Manage Libraries... and search for them:
- For MCP2515:
mcp_can_lib by Seeed Studio (or CAN_BUS_Shield if that's what you find first and it works with MCP2515). This library handles the SPI communication with the MCP2515 chip.
- For Display (choose one based on your display type):
- OLED (SSD1306):
Adafruit SSD1306 and Adafruit GFX Library.
- TFT (ILI9341, ST7735, etc.):
Adafruit ILI9341 (or specific display library) and Adafruit GFX Library. A powerful alternative is TFT_eSPI by Bodmer, which is highly optimized for ESP32 and supports many drivers.
J1939 Protocol Basics (Crucial for Parsing)
J1939 is an application layer protocol that runs over CAN. It defines how data is structured, communicated, and interpreted. Unlike raw CAN, where IDs are arbitrary, J1939 IDs have a specific format.
A J1939 CAN ID (29-bit extended ID) typically contains:
Priority (3 bits) | Reserved (1 bit) | Data Page (1 bit) | PDU Format (8 bits) | PDU Specific (8 bits) | Source Address (8 bits)
- Priority (P): 0-7, lower value means higher priority.
- Data Page (DP): 0 or 1, extends the PGN range.
- PDU Format (PF): If PF < 240, PDU Specific (PS) is the Destination Address (DA). This is a P2P message.
- PDU Format (PF): If PF >= 240, PDU Specific (PS) is a Group Extension. This is a Broadcast message.
- Parameter Group Number (PGN): The core identifier for the type of data being sent (e.g., Engine Speed, Coolant Temperature). Calculated from
DP, PF, and PS.
- If PF < 240: PGN =
(DP << 16) | (PF << 8) | PS
- If PF >= 240: PGN =
(DP << 16) | (PF << 8)
- Source Address (SA): The address of the ECU sending the message (0-255).
- Suspect Parameter Number (SPN): Specific data points within a PGN. A PGN can contain multiple SPNs. For example, PGN 61444 ("Engine Speed, Torque") contains SPN 190 (Engine Speed) and SPN 513 (Engine Torque).
Common PGNs you might encounter:
- 61444 (0xF004): Electronic Engine Controller 1 (EEC1) - Engine Speed (SPN 190), Engine Torque.
- 65262 (0xFEE4): Engine Temperature 1 (ET1) - Engine Coolant Temperature (SPN 110), Engine Oil Temperature (SPN 175).
- 65276 (0xFEEC): Fuel Economy (LFE) - Fuel Rate (SPN 183), Instantaneous Fuel Economy (SPN 184).
- 65247 (0xFEDF): Vehicle Distance (VD) - Total Vehicle Distance (SPN 245).
- 65253 (0xFEE5): Vehicle Id (VI) - VIN.
Challenges:
- No Universal J1939 Arduino Library: While there are CAN libraries, a full-fledged J1939 library that handles all claims, requests, and comprehensive SPN decoding is rare in the Arduino ecosystem. You'll primarily be decoding PGNs and SPNs manually.
- J1939-71 Document: The official J1939-71 document defines all PGNs, SPNs, data types, scaling factors, and offsets. It's expensive and crucial for definitive decoding. Without it, you'll rely on common knowledge or reverse engineering specific devices.
Software Implementation (Example Code)
This example focuses on a TFT display (ILI9341) and the mcp_can_lib.
#include <SPI.h>
#include "mcp_can.h" // https://github.com/Seeed-Studio/mcp_can_lib
// Display specific includes (choose one)
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
// Or for TFT_eSPI (more advanced, highly recommended for ESP32)
// #include <TFT_eSPI.h> // You'll need to configure User_Setup.h for your specific display
// --- MCP2515 SPI Pins (Adjust as needed) ---
#define SPI_CS_PIN 5 // ESP32 GPIO pin for MCP2515 CS
#define SPI_INT_PIN 2 // ESP32 GPIO pin for MCP2515 INT (Interrupt)
// ESP32 default VSPI pins:
// SCK: GPIO18
// MISO: GPIO19
// MOSI: GPIO23
MCP_CAN CAN(SPI_CS_PIN); // Set CS pin for MCP2515
// --- Display Pins (Adjust as needed) ---
// For Adafruit_ILI9341
#define TFT_CS 15 // ESP32 GPIO pin for TFT CS
#define TFT_DC 4 // ESP32 GPIO pin for TFT Data/Command
#define TFT_RST 16 // ESP32 GPIO pin for TFT Reset (can be -1 if not connected)
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
// Or for TFT_eSPI:
// TFT_eSPI tft = TFT_eSPI();
// --- J1939 Variables ---
uint32_t currentRPM = 0;
float currentCoolantTempC = 0.0;
float currentFuelLevelPct = 0.0; // In %
uint32_t currentTotalVehicleDistanceKM = 0; // In km
// --- Display Update Interval ---
unsigned long lastDisplayUpdate = 0;
const long displayUpdateInterval = 200; // milliseconds
void setup() {
Serial.begin(115200);
// Initialize SPI for MCP2515
SPI.begin(); // Uses default VSPI pins (GPIO18, 19, 23)
// Initialize CAN
// Set CAN baud rate to 250kbps. Common rates are 250kbps or 500kbps for J1939.
// Make sure this matches your CAN bus!
while (CAN_OK != CAN.begin(MCP_ANY, CAN_250KBPS, MCP_8MHZ)) {
Serial.println("CAN BUS Shield init fail");
Serial.println("Init CAN BUS Shield again");
delay(100);
}
Serial.println("CAN BUS Shield init ok!");
// Set interrupt pin for receiving CAN messages (optional but good practice)
pinMode(SPI_INT_PIN, INPUT);
//attachInterrupt(digitalPinToInterrupt(SPI_INT_PIN), CAN_ISR, FALLING); // For advanced interrupt-driven approach
// Initialize Display
tft.begin();
tft.setRotation(3); // Adjust rotation as needed (0, 1, 2, 3)
tft.fillScreen(ILI9341_BLACK);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.setCursor(0, 0);
tft.println("J1939 Display");
tft.println("Waiting for data...");
}
void loop() {
// Check for CAN messages
unsigned char len = 0;
unsigned char buf[8];
uint32_t canId;
// Check if there's a message waiting (using polling for simplicity, interrupt is better)
if (CAN_MSGAVAIL == CAN.checkReceive()) {
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
canId = CAN.get-->read_ID(); // Get the 29-bit extended ID
// Check if it's an extended ID (J1939 uses 29-bit extended IDs)
if (!(canId & 0x80000000)) { // 0x80000000 indicates a standard ID in mcp_can_lib
//Serial.println("Standard CAN ID, skipping...");
return;
}
// Extract J1939 components from 29-bit CAN ID
// J1939 ID format: Priority (3) | Reserved (1) | Data Page (1) | PDU Format (8) | PDU Specific (8) | Source Address (8)
uint8_t priority = (canId >> 26) & 0x7;
uint8_t dataPage = (canId >> 24) & 0x1;
uint8_t pduFormat = (canId >> 16) & 0xFF;
uint8_t pduSpecific = (canId >> 8) & 0xFF;
uint8_t sourceAddress = canId & 0xFF;
uint32_t pgn;
if (pduFormat < 0xF0) { // PDU Format < 240 (PDU1 format - specific destination)
pgn = (dataPage << 16) | (pduFormat << 8) | pduSpecific;
} else { // PDU Format >= 240 (PDU2 format - broadcast)
pgn = (dataPage << 16) | (pduFormat << 8);
}
// Serial.print("CAN ID: 0x"); Serial.print(canId, HEX);
// Serial.print(", PGN: 0x"); Serial.print(pgn, HEX);
// Serial.print(", SA: "); Serial.print(sourceAddress);
// Serial.print(", Data: ");
// for (int i = 0; i < len; i++) {
// Serial.print("0x"); Serial.print(buf[i], HEX); Serial.print(" ");
// }
// Serial.println();
// --- J1939 PGN Decoding ---
switch (pgn) {
case 0x00F004: // PGN 61444 - EEC1 (Electronic Engine Controller 1)
// SPN 190: Engine Speed (RPM) - Bytes 3-4, 2 bytes, 0.125 resolution, offset 0
if (len >= 4) {
currentRPM = (buf[3] << 8 | buf[2]) * 0.125;
//Serial.print("Engine RPM: "); Serial.println(currentRPM);
}
break;
case 0x00FEE4: // PGN 65262 - ET1 (Engine Temperature 1)
// SPN 110: Engine Coolant Temperature - Byte 1, 1 byte, 1 resolution, offset -40 C
if (len >= 1) {
currentCoolantTempC = buf[0] - 40;
//Serial.print("Coolant Temp: "); Serial.print(currentCoolantTempC); Serial.println(" C");
}
break;
case 0x00FEEA: // PGN 65258 - LFC (Liquid Fuel Consumed) - Often contains fuel level
// SPN 96: Fuel Level 1 - Byte 2, 1 byte, 0.4 resolution, offset 0
if (len >= 2) {
currentFuelLevelPct = buf[1] * 0.4;
//Serial.print("Fuel Level: "); Serial.print(currentFuelLevelPct); Serial.println(" %");
}
break;
case 0x00F001: // PGN 61441 - Cruise Control/Vehicle Speed
// SPN 84: Wheel-Based Vehicle Speed - Bytes 1-2, 2 bytes, 1/256 km/h resolution, offset 0
if (len >= 2) {
uint16_t speedRaw = (buf[1] << 8 | buf[0]);
float vehicleSpeedKPH = speedRaw * (1.0 / 256.0);
// Serial.print("Vehicle Speed: "); Serial.print(vehicleSpeedKPH); Serial.println(" km/h");
}
break;
case 0x00FEDF: // PGN 65247 - VD (Vehicle Distance)
// SPN 245: Total Vehicle Distance - Bytes 1-4, 4 bytes, 1/8 km/pixel resolution, offset 0
if (len >= 4) {
currentTotalVehicleDistanceKM = ((uint32_t)buf[3] << 24 | (uint32_t)buf[2] << 16 | (uint32_t)buf[1] << 8 | buf[0]) / 8;
// Serial.print("Total Distance: "); Serial.print(currentTotalVehicleDistanceKM); Serial.println(" km");
}
break;
// Add more PGN cases as needed based on your J1939 documentation or observations
}
}
// Update display periodically
if (millis() - lastDisplayUpdate >= displayUpdateInterval) {
lastDisplayUpdate = millis();
updateDisplay();
}
}
void updateDisplay() {
tft.fillScreen(ILI9341_BLACK); // Clear screen
tft.setTextSize(2);
tft.setTextColor(ILI9341_WHITE);
tft.setCursor(10, 10);
tft.print("RPM: ");
tft.setTextColor(ILI9341_CYAN);
tft.println(currentRPM);
tft.setTextColor(ILI9341_WHITE);
tft.setCursor(10, 40);
tft.print("Temp C: ");
tft.setTextColor(ILI9341_ORANGE);
tft.print(currentCoolantTempC, 1); // 1 decimal place
tft.println(" C");
tft.setTextColor(ILI9341_WHITE);
tft.setCursor(10, 70);
tft.print("Fuel: ");
tft.setTextColor(ILI9341_GREEN);
tft.print(currentFuelLevelPct, 1);
tft.println(" %");
tft.setTextColor(ILI9341_WHITE);
tft.setCursor(10, 100);
tft.print("Dist: ");
tft.setTextColor(ILI9341_YELLOW);
tft.print(currentTotalVehicleDistanceKM);
tft.println(" km");
// Add more data points as you decode them
}
// Optional: Interrupt Service Routine for more efficient CAN reception
// volatile bool CAN_RX_Flag = false;
// void IRAM_ATTR CAN_ISR() {
// CAN_RX_Flag = true;
// }
Explanation of the Code:
- Includes: Necessary libraries for SPI, MCP2515, and your chosen display.
- Pin Definitions: Define the ESP32 GPIO pins connected to MCP2515 CS, INT, and your display's pins.
- MCP_CAN Object: Instantiates the CAN controller object.
- Display Object: Instantiates your display.
- J1939 Variables: Global variables to store the decoded data.
setup():
- Initializes
Serial for debugging.
- Initializes
SPI communication for both MCP2515 and the display (they can share the same SPI bus, but need separate CS pins).
- Initializes the MCP2515
CAN module with the correct baud rate (CAN_250KBPS or CAN_500KBPS). This is crucial for successful communication.
- Initializes the display (e.g.,
tft.begin(), tft.setRotation(), tft.fillScreen()).
loop():
- CAN Message Check:
CAN.checkReceive() polls for incoming messages. An interrupt-driven approach (using attachInterrupt) is more efficient for high bus loads but adds complexity.
- Read Message:
CAN.readMsgBuf() reads the message ID and data.
- J1939 ID Parsing: This is the most critical part. The 29-bit extended CAN ID is bit-shifted and masked to extract the
priority, dataPage, pduFormat, pduSpecific, and sourceAddress.
- PGN Calculation: Based on
pduFormat, the PGN is calculated.
- PGN
switch Statement: This is where you implement your J1939 decoding logic.
- For each
case pgn, you inspect the buf (data payload) according to the SPN definitions for that PGN.
- SPN Decoding: You'll use bitwise operations and arithmetic to extract the specific SPN value, applying scaling factors and offsets as defined in the J1939-71 standard. The examples provided are common but always verify with actual documentation if possible.
- Display Update:
updateDisplay() is called periodically to refresh the screen with the latest data.
- Clears the display, sets text properties (size, color, cursor position), and prints the decoded J1939 data.
Further Enhancements & Considerations
- Error Handling: Implement robust error checking for CAN bus status (e.g.,
CAN.checkError() or handling CAN_BUS_OFF errors).
- Persistent Storage: Use ESP32's preferences (EEPROM emulation) or SPIFFS/LittleFS to save user settings or calibration data.
- User Interface: Add buttons or integrate a touchscreen for navigating menus, changing display modes, or viewing different PGNs.
- Data Logging: Log CAN messages to a file on an SD card or send them over Wi-Fi to a server.
- Web Interface: Leverage ESP32's Wi-Fi capabilities to create a web server for monitoring data or configuring the device remotely.
- OTA Updates: Implement Over-The-Air updates for easier firmware upgrades.
- Power Management: Optimize code for lower power consumption if running on battery.
- More PGNs/SPNs: Extend the
switch statement in loop() to decode more J1939 messages relevant to your application. This often requires consulting J1939 documentation or observing your target device's CAN traffic.
- Multi-Page Display: If you have many data points, design a multi-page display that can be switched using buttons.
Troubleshooting Tips
- Wiring: Double-check all your connections, especially SPI (MOSI, MISO, SCK, CS) and CANH/CANL.
- CAN Baud Rate: The most common issue. Ensure the
CAN.begin() baud rate matches your vehicle/machine's CAN bus. Common J1939 rates are 250kbps or 500kbps.
- CAN Termination: Ensure the CAN bus has 120-ohm termination resistors at its two furthest points. Your MCP2515 module might have a jumper for this.
- SPI Communication: If the MCP2515 isn't initializing (
CAN BUS Shield init fail), check your CS pin and SPI connections. Try swapping MOSI/MISO if you're unsure (though standard connections are usually reliable).
- J1939 ID/Data: Use a CAN analyzer (like a USBtin or a logic analyzer with CAN decoding) to observe raw CAN messages on your bus. This lets you verify if messages are indeed flowing, what their IDs are, and what data they contain, allowing you to debug your parsing logic.
- Display Issues: If the display isn't working, check its power, ground, and SPI/I2C connections. Ensure you've selected the correct display type and pins in your code.
- Power Supply: Ensure your ESP32 and peripherals are getting sufficient and stable power.
This project is very rewarding once you see the data flowing! Good luck!