Arduino 使用MCP2515模块进行CANBUS通讯

实验效果

凌顺实验室(lingshunlab.com)分享使用Arduino Uno + MCP2515 模块和 Arduino Nano + MCP2515 模块 进行CANBUS通讯。

WX20230810-1522572x

元件说明

o7j6k2436j5u43h6h54

WX20230810-1441312x

模块特性:

1、支持CAN V2.0B技术规范,通讯速率1Mb/S
2、0~8字节长的数据字段
3、标准帧、拓展帧和远程帧
4、模块5V DC电源供电,SPI接口 协议控制
5、120欧姆终端电阻。阻抗匹配,保证驱动能力,长距离数据传输防止信号放射
6、模块尺寸:4.4cm x 2.8cm 定位螺丝孔中心间距23mm x 38mm
7、工作电流:典型值5mA,待机电流1微安。电源指示灯除外。
8、工作温度:工业级-40℃ 至 85℃

引脚说明

VCC: 5V供电
GND: 接地
CS: SPI接口的片选输入引脚
SO: SPI接口的数据输出引脚
Sl: SPI接口的数据输入引脚
SCK: SPI接口的时钟输入引脚
INT: 中断输出引脚

BOM表

Arduino Uno x1

Arduino Nano x1

MCP2515 x2

面包板 若干

跳线 若干

接线图

完整接线图

a61bda7ea69d0927d32fc2bce608ccd74cd039e12

Arduino Uno接线图(部分放大)

ca3f21ea49f6ca4242c1168779d26aa42d888ba0456

Arduino Nano接线图(部分放大)

WX20230810-1500542x

安装库

arduino-mcp2515

https://github.com/autowp/arduino-mcp2515

程序代码

无论Uno还是Nano做发送端或者接收端都可以的

上传程序的时候请注意选择好对应的开发板和端口

CANBUS发送代码(CAN_write)

// welcome to lingshunlab.com

#include <SPI.h>
#include <mcp2515.h>

struct can_frame canMsg1;
struct can_frame canMsg2;
MCP2515 mcp2515(10);

void setup() {
  canMsg1.can_id  = 0x0F6;
  canMsg1.can_dlc = 8;
  canMsg1.data[0] = 0x8E;
  canMsg1.data[1] = 0x87;
  canMsg1.data[2] = 0x32;
  canMsg1.data[3] = 0xFA;
  canMsg1.data[4] = 0x26;
  canMsg1.data[5] = 0x8E;
  canMsg1.data[6] = 0xBE;
  canMsg1.data[7] = 0x86;

  canMsg2.can_id  = 0x036;
  canMsg2.can_dlc = 8;
  canMsg2.data[0] = 0x0E;
  canMsg2.data[1] = 0x00;
  canMsg2.data[2] = 0x00;
  canMsg2.data[3] = 0x08;
  canMsg2.data[4] = 0x01;
  canMsg2.data[5] = 0x00;
  canMsg2.data[6] = 0x00;
  canMsg2.data[7] = 0xA0;

  while (!Serial);
  Serial.begin(115200);

  mcp2515.reset();
  mcp2515.setBitrate(CAN_125KBPS);
  mcp2515.setNormalMode();

  Serial.println("Example: Write to CAN");
}

void loop() {
  mcp2515.sendMessage(&canMsg1);
  mcp2515.sendMessage(&canMsg2);

  Serial.println("Messages sent");

  delay(100);
}

CANBUS接收代码(CAN_read)

// welcome to lingshunlab.com

#include <SPI.h>
#include <mcp2515.h>

struct can_frame canMsg;
MCP2515 mcp2515(10);

void setup() {
  Serial.begin(115200);

  mcp2515.reset();
  mcp2515.setBitrate(CAN_125KBPS);
  mcp2515.setNormalMode();

  Serial.println("------- CAN Read ----------");
  Serial.println("ID  DLC   DATA");
}

void loop() {
  if (mcp2515.readMessage(&canMsg) == MCP2515::ERROR_OK) {
    Serial.print(canMsg.can_id, HEX); // print ID
    Serial.print(" "); 
    Serial.print(canMsg.can_dlc, HEX); // print DLC
    Serial.print(" ");

    for (int i = 0; i<canMsg.can_dlc; i++)  {  // print the data
      Serial.print(canMsg.data[i],HEX);
      Serial.print(" ");
    }

    Serial.println();      
  }
}