Environment setup: Refer to Arduino IDE Quick Start to complete IDE installation, and install the corresponding board package for the development board in use along with the required driver libraries.
Required libraries:
Required hardware products:


CAN (Controller Area Network) is a multi-master, high-reliability serial communication protocol widely used in automotive electronics, industrial automation, and other applications that demand high real-time performance and reliability. A CAN network supports equal access for multiple nodes and features excellent error detection and arbitration mechanisms.
1. Core Definition:
2. Key Features:
3. Working Principle:
A 120Ω termination resistor must be connected in parallel at both ends of the bus to ensure signal integrity.G5 (RX) and G6 (TX).
#include <M5Unified.h>
#include <M5GFX.h>
#include "driver/twai.h"
const gpio_num_t MCU_CAN_TXD = GPIO_NUM_5;
const gpio_num_t MCU_CAN_RXD = GPIO_NUM_6;
void setup() {
M5.begin();
M5.Display.clear();
M5.Display.setFont(&fonts::FreeMonoBold12pt7b);
Serial.begin(115200);
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(MCU_CAN_TXD, MCU_CAN_RXD, TWAI_MODE_NORMAL);
twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK && twai_start() == ESP_OK) {
Serial.println("\nCAN ready. ");
} else {
Serial.println("\nCAN init failed. ");
while (1) delay(1000);
}
M5.Display.drawCenterString("CAN", 64, 50);
}
void loop() {
// transmit
twai_message_t tx_msg = {};
tx_msg.extd = 0; // 0 = standard frame, 1 = extended frame
tx_msg.identifier = 0x123; // 11-bit standard ID, change it on another device
tx_msg.data_length_code = 2;
tx_msg.data[0] = 0xAA; // change it on another device
tx_msg.data[1] = 0xBB; // change it on another device
if (twai_transmit(&tx_msg, pdMS_TO_TICKS(100)) == ESP_OK) {
Serial.println("TX OK");
} else {
Serial.println("TX failed");
}
// receive (non-blocking)
twai_message_t rx_msg;
if (twai_receive(&rx_msg, pdMS_TO_TICKS(10)) == ESP_OK) {
Serial.print("RX: ");
for (int i = 0; i < rx_msg.data_length_code; i++) Serial.printf("%02X ", rx_msg.data[i]);
Serial.printf("(ext=%d, id=0x%X, dlc=%d)", rx_msg.extd, rx_msg.identifier, rx_msg.data_length_code);
Serial.println();
}
delay(2000);
}
TX OKRX: AA BB (ext=0, id=0x123, dlc=2)