Skip to content
Get started

CAN Bus

The Controller Area Network (CAN) bus is a serial bus protocol to connect individual systems and sensors as an alternative to conventional multi-wire looms. It allows automotive components to communicate on a single or dual-wire data bus at speeds up to 1Mbps.

CAN is an International Standardization Organization (ISO) defined serial communications bus originally developed for the automotive industry to replace the complex wiring harness with a two-wire bus. The specification calls for high immunity to electrical interference and the ability to self-diagnose and repair data errors. These features have led to CAN’s popularity in a variety of industries including building automation, medical, and manufacturing.

ESPHome supports single frame data transfer: up to 8 bytes per frame for classic CAN, and up to 64 bytes for CAN FD on a platform that supports it, such as the MCP251xFD. With this you can transmit the press of a button or the feedback from a sensor on the bus. All other devices on the bus will be able to get this data to switch on/off a light or display the transmitted data.

The CAN bus itself has only two wires named Can High and Can Low or CanH and CanL. For the ESPHome CAN bus to work, you need to select the device that has the physical CAN bus implemented. You can configure multiple buses.

Any CAN bus node can transmit data at any time; any node can both send and/or receive any can_id value. You must determine how to organize the can_id values; for example, you can set up a CAN bus network where each node has a can_id it will use to broadcast data about itself. If a given node should (for example) turn on a light, it can listen to the CAN bus for messages containing its specific can_id and react accordingly. With this architecture, you can have multiple nodes able to control a light connected to a single, specific node.

Each canbus platform extends the following configuration schema:

# Example configuration entry
canbus:
- platform: ...
can_id: 4
on_frame:
- can_id: 500
use_extended_id: false
then:
- lambda: |-
std::string b(x.begin(), x.end());
ESP_LOGD("can id 500", "%s", &b[0] );

Configuration variables:

  • platform (Required, platform): One of the supported CAN bus Platforms.

  • id (Optional, ID): Manually specify the ID used for code generation.

  • can_id (Required, int): default CAN ID used for transmitting frames.

  • use_extended_id (Optional, boolean): Identifies the type of can_id :

    • false : Standard 11-bit IDs (default)
    • true : Extended 29-bit IDs
  • bit_rate (Optional, enum): One of the supported bit rates. See this table for a list of supported bit rates by the internal CAN (TWAI) controllers of different ESP32 variants. Defaults to 125KBPS.

    • 1KBPS - Support by esp32_can depends on ESP32 variant
    • 5KBPS - Support by esp32_can depends on ESP32 variant
    • 10KBPS - Support by esp32_can depends on ESP32 variant
    • 12K5BPS - Support by esp32_can depends on ESP32 variant
    • 16KBPS - Support by esp32_can depends on ESP32 variant
    • 20KBPS - Support by esp32_can depends on ESP32 variant and chip revision
    • 25KBPS
    • 31K25BPS - Not supported by esp32_can
    • 33KBPS - Not supported by esp32_can
    • 40KBPS - Not supported by esp32_can
    • 50KBPS
    • 80KBPS - Not supported by esp32_can
    • 83K3BPS - Not supported by esp32_can
    • 95KBPS - Not supported by esp32_can
    • 100KBPS
    • 125KBPS - Default
    • 200KBPS - Not supported by esp32_can
    • 250KBPS
    • 500KBPS
    • 800KBPS
    • 1000KBPS
  • max_frames_per_loop (Optional, int): Maximum number of received CAN frames processed in one pass of the main loop. Frames still queued after that are handled on the next pass, so one burst cannot stall the rest of the firmware. A warning is logged each time the limit is reached, since the receive queue may overflow and drop frames if it keeps happening. Must be at least 1. Defaults to 50.

The next three options exist only on platforms that support CAN FD, such as the MCP251xFD. Other platforms reject them, even when set to false:

  • default_fd (Optional, boolean): Default frame format for canbus.send actions. Defaults to false, unless the platform specifies otherwise.

  • default_bit_rate_switch (Optional, boolean): Default bit rate switch setting for CAN FD send actions. Defaults to false.

  • default_pad_data (Optional, boolean): Default padding behavior for canbus.send actions. Defaults to false. See pad_data.

  • on_frame (Optional, Automation): An automation to perform when a CAN frame is received. See on_frame Trigger.

This automation will be triggered when a CAN frame is received. The variables x (of type canbus::CanPayload) containing the frame data, can_id (of type uint32_t) containing the actual received CAN ID and remote_transmission_request (of type bool) containing the corresponding field from the CAN frame are passed to the automation for use in lambdas. On a platform that supports CAN FD, x holds up to 64 bytes when a CAN FD frame is received.

x holds the data without using the heap. It offers size(), empty(), x[i], data(), begin() and end() like a std::vector<uint8_t>, and converts to one where a function needs it, for example std::vector<uint8_t> data = x;. That conversion allocates, so prefer reading x directly.

NOTE

Messages this node sends to the same ID will not show up as received messages.

canbus:
- platform: ...
on_frame:
- can_id: 43 # the received can_id
then:
- if:
condition:
lambda: 'return (x.size() > 0) ? x[0] == 0x11 : false;'
then:
light.toggle: light1
- can_id: 0b00000000000000000000001000000
can_id_mask: 0b11111000000000011111111000000
use_extended_id: true
remote_transmission_request: false
then:
- lambda: |-
auto pdo_id = can_id >> 14;
switch (pdo_id)
{
case 117:
ESP_LOGD("canbus", "exhaust_fan_duty");
break;
case 118:
ESP_LOGD("canbus", "supply_fan_duty");
break;
case 119:
ESP_LOGD("canbus", "supply_fan_flow");
break;
// to be continued...
}

Configuration variables:

  • can_id (Required, int): The CAN ID which, when received, will trigger this automation.

  • can_id_mask (Optional, int): The bit mask to apply to the received CAN ID before trying to match it with can_id. Defaults to 0x1fffffff (all bits of received CAN ID are compared with can_id).

  • use_extended_id (Optional, boolean): Identifies the type of can_id to match on. Defaults to false.

  • remote_transmission_request (Optional, boolean): Whether to run for CAN frames with the “remote transmission request” bit set or not set. Defaults to not checking (the automation will run for both cases).

The CAN bus can transmit frames by means of the canbus.send action. There are several ways to use it:

on_...:
- canbus.send:
data: [ 0x10, 0x20, 0x30 ]
canbus_id: my_mcp2515 # optional if you only have 1 canbus device
can_id: 23 # override the can_id configured in the can bus
on_...:
- canbus.send: [ 0x11, 0x22, 0x33 ]
- canbus.send: 'hello'
# Templated; return a list of bytes, a std::vector<uint8_t>, or x from on_frame
- canbus.send: !lambda return {0x00, 0x20, 0x42};
# CAN FD, on a platform that supports it: 12 bytes with the faster data phase
- canbus.send:
data: [ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C ]
fd: true
bit_rate_switch: true

Configuration variables:

  • data (Required, binary data, templatable): Data to transmit. Classic CAN sends at most 8 bytes. Longer fixed payloads are rejected when the frame format is known during configuration validation. Otherwise, longer payloads are truncated to the first 8 bytes at runtime and a warning is logged. CAN FD supports up to 64 bytes. CAN FD payload lengths above 8 must be 12, 16, 20, 24, 32, 48, or 64 bytes, unless pad_data is enabled. Non-templated data is limited to 64 bytes during configuration validation.

  • canbus_id (Optional): Sets the CAN bus ID to use for transmitting the frame. Required if you are have multiple CAN bus platforms defined in your configuration.

  • can_id (Optional, int): Allows overriding the can_id configured for the CAN bus device.

  • use_extended_id (Optional, boolean): Identifies the type of can_id :

    • false : Standard 11-bit IDs (default)
    • true : Extended 29-bit IDs
  • remote_transmission_request (Optional, boolean): Set to send CAN bus frame to request data from another node. If a certain data length code needs to be sent, include the necessary (dummy) bytes in data. Defaults to false. Remote transmission requests cannot be used with CAN FD.

The fd, bit_rate_switch and pad_data options need a platform that supports CAN FD. On any other CAN bus they are rejected during configuration validation, even when set to false, so leave them out there.

  • fd (Optional, boolean, templatable): Send a CAN FD frame. Defaults to default_fd on the CAN bus.

  • bit_rate_switch (Optional, boolean, templatable): Use the faster data phase bit rate for a CAN FD frame. Defaults to default_bit_rate_switch for FD frames and false for classic frames. This option requires fd: true.

  • pad_data (Optional, boolean, templatable): Pad a CAN FD payload with zero bytes to the next supported length. Defaults to default_pad_data on the CAN bus.

Invalid frames are rejected and not sent. This includes CAN FD payloads exceeding 64 bytes, unsupported CAN FD frames, and CAN FD payload lengths that require padding when padding is disabled. Invalid fixed values can also be rejected during configuration validation, including when fd or pad_data uses the CAN bus default.

CAN FD frames can carry up to 64 bytes, even with bit rate switching (BRS) disabled. With BRS disabled, the data phase uses the nominal bit rate. This allows larger payloads without switching to a faster data rate.

Enabling BRS allows a faster data phase, but higher rates place greater demands on the transceiver, wiring, and termination. They can also require compensation for transceiver delays to sample the data phase correctly. Choose a data bit rate supported by the whole bus and check the platform documentation for timing constraints.

All nodes on the bus must be able to tolerate CAN FD frames, even when BRS is disabled. Use classic CAN frames when communicating on a bus with nodes that do not support CAN FD.

Standard IDs and Extended IDs can coexist on the same segment.

NOTE

It is important to know that “standard” and “extended” addresses denote different addresses. For example, Standard 0x123 and Extended 0x123 are, in fact, different addresses.

Decimal or hexadecimal notation may be used for IDs:

  • Standard IDs use 0x000 to 0x7ff (hexadecimal) or 0 to 2047 (decimal)
  • Extended IDs use 0x00000000 to 0x1fffffff (hexadecimal) or 0 to 536870911 (decimal)

This example illustrates how different ID types may be used in your configuration for both transmitting and receiving.

# Transmission of extended and standard ID 0x100 every second
time:
- platform: sntp
on_time:
- seconds: /1
then:
- canbus.send:
# Extended ID explicit
use_extended_id: true
can_id: 0x100
data: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]
- canbus.send:
# Standard ID by default
can_id: 0x100
data: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]
canbus:
- platform: ...
can_id: 0x1fff
use_extended_id: true
bit_rate: 125kbps
on_frame:
- can_id: 0x123
use_extended_id: true
then:
- lambda: |-
std::string b(x.begin(), x.end());
ESP_LOGD("CAN extended ID 0x123", "%s", &b[0]);
- can_id: 0x123
then:
- lambda: |-
std::string b(x.begin(), x.end());
ESP_LOGD("CAN standard ID 0x123", "%s", &b[0]);

Given that we have a button connected to a remote CAN node which will send a message to ID 0x100 with the payload 0x1 for contact closed and 0x0 for contact open, this example will look for this message and update the state of its binary_sensor accordingly.

binary_sensor:
- platform: template
name: CAN Bus Button
id: can_bus_button
canbus:
- platform: ...
can_id: 4
bit_rate: 125kbps
on_frame:
- can_id: ${0x100}
then:
- lambda: |-
if(x.size() > 0) {
switch(x[0]) {
case 0x0: // button release
id(can_bus_button).publish_state(false);
break;
case 0x1: // button press
id(can_bus_button).publish_state(true);
break;
}
}

In this example, three nodes are connected to the CAN bus:

  • Node 1 sends a one-byte payload to ID 0x50B

  • Node 2 sends a one-byte payload to ID 0x50C

    These nodes send the following one-byte payload which is based on the state of a button connected to each of them:

    • 0: Button release
    • 1: Button press
    • 2: Long press
    • 3: Long release
    • 4: Double-click
  • Node 3 controls a motor connected to it. It expects a message to ID 0x51A where the one-byte payload is:

    • 0: Off
    • 1: Open
    • 2: Close
canbus:
- platform: ...
id: my_canbus
can_id: 4
bit_rate: 125kbps
on_frame:
- can_id: 0x50c
then:
- lambda: |-
if(x.size() > 0) {
auto call = id(TestCover).make_call();
switch(x[0]) {
case 0x2: call.set_command_open(); call.perform(); break; // long press
case 0x1: // button press
case 0x3: call.set_command_stop(); call.perform(); break; // long release
case 0x4: call.set_position(1.0); call.perform(); break; // double-click
}
}
- can_id: 0x50b
then:
- lambda: |-
if(x.size() > 0) {
auto call = id(TestCover).make_call();
switch(x[0]) {
case 0x2: call.set_command_close(); call.perform(); break; // long press
case 0x1: // button press
case 0x3: call.set_command_stop(); call.perform(); break; // long release
case 0x4: call.set_position(0.0); call.perform(); break; // double-click
}
}
cover:
- platform: time_based
name: Canbus Test Cover
id: TestCover
device_class: shutter
has_built_in_endstop: true
open_action:
- canbus.send:
data: [ 0x01 ]
canbus_id: my_canbus
can_id: 0x51A
open_duration: 2min
close_action:
- canbus.send:
data: [ 0x02 ]
canbus_id: my_canbus
can_id: 0x51A
close_duration: 2min
stop_action:
- canbus.send:
data: [ 0x00 ]
canbus_id: my_canbus
can_id: 0x51A

High logging levels and slow on_frame handlers can delay reading received frames. Frames continue to arrive while the main loop is busy, and the receive queue can overflow if it is not drained fast enough.

The CAN bus component logs each received frame at DEBUG level and its payload as a hexadecimal message at VERBOSE level. Reducing the canbus log level can help on a busy bus. For example:

logger:
logs:
canbus: INFO

With ESP32 hardware UART logging, messages are written to the ESP-IDF UART driver’s transmit buffer. When the buffer fills, logging waits for space and delays the main loop. At 115200 baud with 8N1 framing, a 100-byte message takes about 8.7 ms to transmit, during which several CAN frames can arrive. Increasing logger.tx_buffer_size can absorb short bursts, but sustained logging must stay within the UART’s output capacity. Reducing logging or increasing the UART baud rate can reduce the bottleneck. See Logger for configuration options.

The receive loop starts matching on_frame automations before reading the next frame. Synchronous actions run until they finish or yield, so keep handlers brief and avoid blocking waits, long computations, and excessive per-frame logging. If several handlers match a frame, their combined execution time delays the next read.

For longer operations, capture the necessary values quickly and process them in small, nonblocking steps. The YAML delay action schedules a continuation and allows reception to continue. Calling C++ delay() in a lambda blocks the receive loop. Deferred work still shares the main loop and must remain short enough to avoid receive queue overflow.