环境配置: 参考 Arduino IDE 上手教程完成 IDE 安装,并根据实际使用的开发板安装对应的板管理,与需要的驱动库。
使用到的驱动库:
使用到的硬件产品:


CAN(Controller Area Network)是一种多主机、高可靠性的串行通信协议,广泛应用于汽车电子、工业自动化等对实时性和可靠性要求较高的场合。CAN 网络支持多节点平等接入,具备优异的错误检测和仲裁机制。
1. 核心定义:
2. 关键特性:
3. 工作原理:
总线两端需并联 120Ω 终端匹配电阻以确保信号完整性。本教程中使用的主控设备为 AtomS3R ,搭配 Atomic CAN Base。本模块采用串口方式通讯,根据实际的电路连接修改程序中的引脚定义,设备连接后对应的串口引脚为G5 (RX)、G6 (TX)。
本模块内部没有集成 120Ω 终端电阻,可参考下图位置在 CAN 总线两端并联 120Ω 电阻。
#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);
} 1. 下载模式:不同设备进行程序烧录前需要下载模式,不同的主控设备该步骤可能有所不同。详情可参考Arduino IDE上手教程页面底部的设备程序下载教程列表,查看具体的操作方式。
AtomS3R 长按复位按键 (大约 2 秒) 直到内部绿色 LED 灯亮起,便可松开,此时设备已进入下载模式,等待烧录。
TX OKRX: AA BB (ext=0, id=0x123, dlc=2)