用户工具

站点工具


ocrobot:alpha:canbus:main

ALPHA CANBUS总线模块

简介

特点

参数

参考图片

例程

发送端代码(主控板为D21G18A):

#include <SPI.h>
#include <mcp2515.h>
 
struct can_frame canMsg1;
struct can_frame canMsg2;
MCP2515 mcp2515(A5);
 
 
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 (!SerialUSB);
  SerialUSB.begin(115200);
  SPI.begin();
 
  mcp2515.reset();
  mcp2515.setBitrate(CAN_125KBPS);
  mcp2515.setNormalMode();
 
  SerialUSB.println("Example: Write to CAN");
}
 
void loop() {
 
  mcp2515.sendMessage(&canMsg1);
  mcp2515.sendMessage(&canMsg2);
 
  SerialUSB.println("Messages sent");
 
  delay(100);
 
}

接收端代码

#include <SPI.h>
#include <mcp2515.h>
 
struct can_frame canMsg;
MCP2515 mcp2515(A5);
 
 
void setup() {
  SerialUSB.begin(115200);
  SPI.begin();
 
  mcp2515.reset();
  mcp2515.setBitrate(CAN_125KBPS);
  mcp2515.setNormalMode();
 
  SerialUSB.println("------- CAN Read ----------");
  SerialUSB.println("ID  DLC   DATA");
}
 
void loop() {
 
  if (mcp2515.readMessage(&canMsg) == MCP2515::ERROR_OK) {
 
    SerialUSB.print(canMsg.can_id, HEX); // print ID
    SerialUSB.print(" "); 
    SerialUSB.print(canMsg.can_dlc, HEX); // print DLC
    SerialUSB.print(" ");
 
    for (int i = 0; i<canMsg.can_dlc; i++)  {  // print the data
 
      SerialUSB.print(canMsg.data[i],HEX);
      SerialUSB.print(" ");
 
    }
 
    SerialUSB.println();      
  }
 
}

下载

库文件:mcp2515.zip

原理图:

ocrobot/alpha/canbus/main.txt · 最后更改: 2019/07/04 04:02 由 董凯萍