Project: How Do You Build an ESP32 CAN Bus?

Give each ESP32 a CAN controller and a transceiver, join the two transceivers with a twisted pair terminated by 120 Ω at each end, and agree on one bit rate. The ESP32 talks to an MCP2515 CAN controller over SPI; the MCP2515 builds and checks the frames; a transceiver turns its logic-level TX and RX into the differential CANH and CANL signals. In this project node A sends a potentiometer reading as frame 0x100 ten times a second, and node B sets an LED's brightness from it and replies with frame 0x200.

How this was checked

Honestly stated: both sketches were compile-checked with arduino-cli for the ESP32 (esp32:esp32 core 3.3.12, autowp-mcp2515 library 1.3.1, all warnings on, none reported), and the wiring and bit timing follow the MCP2515 and ESP32 datasheets and the library's documentation. The project has not been built and run on a bench. If you build it and something doesn't behave as described, please tell us through the contact page and we'll correct the post.

What you'll learn

  • What the controller, the transceiver and the termination each do
  • How a CAN frame is laid out, and why the lower ID wins the bus
  • How the MCP2515 makes 500 kbit/s from an 8 MHz crystal
  • Wiring an MCP2515 module to an ESP32 safely at 3.3 V
  • Sending, receiving with an interrupt, and replying

Parts

PartQuantityNotes
ESP32 development board2Any ESP32 (not S2, S3 or C3: their default SPI pins differ)
MCP2515 CAN module2Check the crystal: most are 8 MHz, some 16 MHz
CAN transceiver2On the module (often TJA1050, a 5 V part) or a separate 3.3 V SN65HVD230
120 Ω resistor2One at each end of the bus; many modules have a jumper for it
10 kΩ potentiometer1On node A
LED and 330 Ω resistor1On node B, or use the on-board LED
Twisted pair wire1CANH and CANL twisted together

Step 1: the pieces, and why there are three

The ESP32 runs your code. The MCP2515 is a stand-alone CAN controller: it adds the start bit, CRC and acknowledge slot, does bit stuffing, arbitration and error counting, and holds two receive buffers and three transmit buffers, all reached over SPI. The transceiver drives the bus: for a dominant bit (a logic 0) it pulls CANH up and CANL down, and for a recessive bit (a logic 1) it lets both float to the same level. Because the receiver looks only at the difference CANH minus CANL, noise that lands on both wires cancels. The 120 Ω terminators match the cable's characteristic impedance at each end so edges don't reflect.

Two CAN nodes on one busEach ESP32 talks SPI to an MCP2515 controller, which drives a transceiver; the two transceivers share the CANH and CANL twisted pair, terminated at each end.ESP32node AMCP2515controllerTransceiverESP32node BMCP2515controllerTransceiverCANH and CANLtwisted pair, 120 ohm at each endSPITX, RXSPITX, RX
Node A and node B: microcontroller, controller and transceiver, joined by one terminated twisted pair.

Step 2: the frame, and arbitration

A standard data frame is a start bit, an 11-bit identifier, the RTR, IDE and r0 bits, a 4-bit length (DLC), 0 to 8 data bytes, a 15-bit CRC and its delimiter, a 2-bit acknowledge field and 7 end-of-frame bits: 44 bits plus 8 per data byte, before stuff bits. There are no addresses: the ID names the message, and every node sees every frame. When two nodes start together, each compares the bus with what it sent, bit by bit. A dominant 0 overwrites a recessive 1, so the node sending a 1 where the bus shows a 0 backs off and tries later. The lower ID always wins, without a single bit being lost.

Standard CAN data frame fieldsThe fields of a standard data frame in order, with their lengths in bits: start of frame 1, identifier 11, control bits RTR, IDE and r0 3, length code 4, data 0 to 64, CRC with delimiter 16, acknowledge 2, end of frame 7.SOF1ID11Ctrl3DLC4Data0-64CRC15 + 1ACK2EOF7
A standard data frame: 44 bits plus 8 per data byte, before stuff bits. The identifier is sent first, which is what makes arbitration work.
FrameData bytesBits (no stuffing)Time at 500 kbit/s
0x100 from node A344 + 24 = 68136 µs
0x200 reply from node B244 + 16 = 60120 µs
Both, every 100 ms128 per 100 msabout 0.26% of the bus

Step 3: bit timing, 500 kbit/s from 8 MHz

The MCP2515 divides each bit into time quanta (TQ). From the datasheet, TQ = 2 × (BRP + 1) / F_OSC, and a bit is the sync segment (always 1 TQ) plus the propagation segment, phase segment 1 and phase segment 2. The library's 8 MHz, 500 kbit/s setting writes CNF1 = 0x00, CNF2 = 0x90 and CNF3 = 0x82. Decoded:

FieldRegister bitsValue
BRP (prescaler)CNF1[5:0] = 0TQ = 2 × 1 / 8 MHz = 250 ns
SJWCNF1[7:6] = 01 TQ
Propagation segmentCNF2[2:0] = 01 TQ
Phase segment 1CNF2[5:3] = 23 TQ
Phase segment 2CNF3[2:0] = 23 TQ
Bit time1 + 1 + 3 + 38 TQ = 2 µs, so 500 kbit/s
Sample point(1 + 1 + 3) / 862.5% of the bit

If your module has a 16 MHz crystal, change MCP_8MHZ to MCP_16MHZ in both sketches: with the wrong setting, every bit is twice or half as long as the other node expects and nothing is acknowledged. Both nodes must use the same bit rate.

Step 4: wiring

The ESP32's default SPI pins (VSPI) are SCK 18, MISO 19, MOSI 23 and CS 5. The ESP32's I/O pins run at 3.3 V and are not 5 V tolerant, so the MCP2515's SO output, which swings to the MCP2515's own supply, must not reach GPIO 19 at 5 V. The MCP2515 itself runs from 2.7 to 5.5 V, so the safe arrangement is the MCP2515 at 3.3 V with a 3.3 V transceiver such as the SN65HVD230. Many cheap modules power the MCP2515 and a TJA1050 (which needs 5 V) from one VCC pin; with those, either separate the two supplies or put a level shifter on SO before GPIO 19.

MCP2515 module pinESP32 pinNotes
VCC3V3See the 5 V note above
GNDGNDCommon ground for both nodes too
CSGPIO 5Chip select, active low
SOGPIO 19 (MISO)Must be 3.3 V logic
SIGPIO 23 (MOSI)
SCKGPIO 18
INTGPIO 4Node B only; active low
CANH, CANLTo the other node's CANH, CANLTwisted pair, 120 Ω at each end

On node A, wire the potentiometer between 3V3 and GND with its wiper to GPIO 34 (an input-only ADC1 pin). On node B, wire the LED and 330 Ω resistor from GPIO 2 to GND. With power off, the resistance between CANH and CANL should read about 60 Ω: two 120 Ω terminators in parallel. 120 Ω means one is missing; about 40 Ω means a third one is fitted.

Step 5: node A, the sender

Every 100 ms it reads the potentiometer (12 bits, 0 to 4095), packs it into two bytes with a counter in the third, and sends frame 0x100. It also prints any reply it receives, so you can see both directions on one serial monitor.

can_sender.ino
// CAN bus with ESP32 and MCP2515: node A, the sender.
// Reads a potentiometer and sends its value, with a counter, every 100 ms
// as standard frame 0x100 at 500 kbit/s. Compile-checked with arduino-cli
// (esp32:esp32, autowp-mcp2515 1.3.1); not bench-tested.
//
// Wiring (ESP32 VSPI to MCP2515): SCK 18, MISO 19, MOSI 23, CS 5.
// The MCP2515 must run at 3.3 V, or its SO pin needs a level shifter before
// GPIO 19: the ESP32's inputs are not 5 V tolerant.
#include <SPI.h>
#include <mcp2515.h>

const uint8_t PIN_CS = 5;
const uint8_t PIN_POT = 34;          // ADC1 input, 0 to 4095
const uint32_t SEND_ID = 0x100;      // 11-bit standard ID
const unsigned long PERIOD_MS = 100;

MCP2515 can(PIN_CS);
uint8_t counter = 0;
unsigned long lastSend = 0;

void setup() {
  Serial.begin(115200);
  SPI.begin();                        // VSPI default pins on ESP32
  can.reset();
  // Set to the crystal on your module: most blue boards use 8 MHz.
  if (can.setBitrate(CAN_500KBPS, MCP_8MHZ) != MCP2515::ERROR_OK) {
    Serial.println("setBitrate failed: check wiring and the crystal setting");
  }
  can.setNormalMode();
  Serial.println("Sender ready");
}

void loop() {
  // Print node B's replies (frame 0x200), so both directions are visible.
  struct can_frame rx;
  while (can.readMessage(&rx) == MCP2515::ERROR_OK) {
    if (rx.can_dlc >= 2) {
      Serial.printf("reply id=0x%03X value=%u\n", (unsigned)(rx.can_id & CAN_SFF_MASK), (rx.data[0] << 8) | rx.data[1]);
    }
  }

  if (millis() - lastSend < PERIOD_MS) return;
  lastSend = millis();

  uint16_t pot = analogRead(PIN_POT);
  struct can_frame frame;
  frame.can_id = SEND_ID;
  frame.can_dlc = 3;
  frame.data[0] = pot >> 8;           // big-endian 12-bit reading
  frame.data[1] = pot & 0xFF;
  frame.data[2] = counter++;

  MCP2515::ERROR err = can.sendMessage(&frame);
  if (err == MCP2515::ERROR_OK) {
    Serial.printf("sent id=0x%03X pot=%u count=%u\n", (unsigned)SEND_ID, pot, frame.data[2]);
  } else {
    // ERROR_ALLTXBUSY usually means no other node is acknowledging frames:
    // check the second node, CANH/CANL and the two 120 ohm terminators.
    Serial.printf("send error %d\n", (int)err);
  }
}

Step 6: node B, the receiver

The MCP2515 pulls INT low when a frame is in a receive buffer. The interrupt handler only sets a flag; the loop then reads frames until both buffers are empty, prints each one, sets the LED duty cycle from frame 0x100 (12 bits down to 8 by shifting right 4) and replies with frame 0x200.

can_receiver.ino
// CAN bus with ESP32 and MCP2515: node B, the receiver.
// Prints every frame it receives, and for frame 0x100 sets the LED's
// brightness from the potentiometer value node A sends. It also replies
// with frame 0x200 (the reading halved) so you can watch two IDs share
// the bus. Compile-checked with arduino-cli (esp32:esp32, autowp-mcp2515
// 1.3.1); not bench-tested.
//
// Wiring: SCK 18, MISO 19, MOSI 23, CS 5, MCP2515 INT to GPIO 4, LED on
// GPIO 2 (the on-board LED on many dev boards) through a resistor.
#include <SPI.h>
#include <mcp2515.h>

const uint8_t PIN_CS = 5;
const uint8_t PIN_INT = 4;           // MCP2515 INT is active low
const uint8_t PIN_LED = 2;
const uint32_t POT_ID = 0x100;
const uint32_t REPLY_ID = 0x200;

MCP2515 can(PIN_CS);
volatile bool frameWaiting = false;

void IRAM_ATTR onCanInterrupt() { frameWaiting = true; }

void setup() {
  Serial.begin(115200);
  SPI.begin();
  can.reset();
  if (can.setBitrate(CAN_500KBPS, MCP_8MHZ) != MCP2515::ERROR_OK) {
    Serial.println("setBitrate failed: check wiring and the crystal setting");
  }
  can.setNormalMode();
  pinMode(PIN_INT, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_INT), onCanInterrupt, FALLING);
  ledcAttach(PIN_LED, 5000, 8);       // 5 kHz PWM, 8-bit duty (ESP32 core 3.x)
  Serial.println("Receiver ready");
}

void loop() {
  if (!frameWaiting && digitalRead(PIN_INT) == HIGH) return;
  frameWaiting = false;

  struct can_frame frame;
  // Drain both receive buffers; INT stays low while either holds a frame.
  while (can.readMessage(&frame) == MCP2515::ERROR_OK) {
    Serial.printf("got id=0x%03X dlc=%u data=", (unsigned)(frame.can_id & CAN_SFF_MASK), frame.can_dlc);
    for (uint8_t i = 0; i < frame.can_dlc; i++) Serial.printf("%02X ", frame.data[i]);
    Serial.println();

    if ((frame.can_id & CAN_SFF_MASK) == POT_ID && frame.can_dlc >= 2) {
      uint16_t pot = (frame.data[0] << 8) | frame.data[1];
      ledcWrite(PIN_LED, pot >> 4);   // 12-bit reading to 8-bit duty

      struct can_frame reply;
      reply.can_id = REPLY_ID;
      reply.can_dlc = 2;
      uint16_t half = pot / 2;
      reply.data[0] = half >> 8;
      reply.data[1] = half & 0xFF;
      can.sendMessage(&reply);
    }
  }
}

Step 7: build and run

  • Install the board support: arduino-cli core install esp32:esp32 (or Boards Manager in the Arduino IDE), and the library: arduino-cli lib install autowp-mcp2515.
  • Compile and upload each sketch to its own board, for example: arduino-cli compile --fqbn esp32:esp32:esp32 can_sender, then upload with -p and your port.
  • Open both serial monitors at 115200 baud. Node A should print sent lines and, once node B is running, reply lines; node B should print got lines, and the LED should follow the potentiometer.
  • If node A prints send error 2 (ERROR_ALLTXBUSY) with node B off, that is expected: a CAN frame needs at least one other node to acknowledge it, and an unacknowledged frame is retransmitted until the transmit buffers fill.

Common mistakes

  • Setting MCP_8MHZ on a board with a 16 MHz crystal, or the reverse. Read the marking on the crystal.
  • Leaving out a terminator, or fitting one on every module. Measure 60 Ω between CANH and CANL with power off.
  • Feeding 5 V SO into the ESP32. Run the MCP2515 at 3.3 V or level shift.
  • Testing with one node and expecting frames to go out. Without an acknowledge they are retried forever.
  • Doing SPI work inside the interrupt handler. Set a flag and read in the loop.
  • Reading only one frame per interrupt. INT stays low while either buffer holds a frame, so drain both.

Check your understanding

  • Q1. Nodes send IDs 0x100 and 0x0F0 at the same instant. Which wins? Answer: 0x0F0, because at the first bit where they differ it sends a dominant 0 where 0x100 sends a recessive 1.
  • Q2. How many bits, before stuffing, is a standard frame with 8 data bytes? Answer: 44 + 64 = 108 bits, 216 µs at 500 kbit/s.
  • Q3. With a 16 MHz crystal and BRP = 1, how long is one TQ? Answer: 2 × 2 / 16 MHz = 250 ns, the same as BRP = 0 at 8 MHz.
  • Q4. Why does CAN use two wires instead of one? Answer: the receiver reads the difference CANH minus CANL, so noise coupled equally onto both wires cancels.

Related

Sources

Last verified

Both sketches compile-checked with arduino-cli 1.6.0, ESP32 core 3.3.12 and autowp-mcp2515 1.3.1 on 16 November 2026, with no warnings; not bench-tested. The frame lengths and bit timing are computed in the site's tests (lib/projectNumbers.test.js). The sketches are in the site's repository under scripts/projects/can.