Case. Arduino 与 STM32 进行 CAN 通讯

2020-07-23  本文已影响0人  T_K_233

接线

image.png

Arduino 部分使用 MCP2515 模块

MCP 2515 Arduino
VCC 5V
GND GND
CS D10
SO (MISO) D12
SI (MOSI) D11
SCK D13
INT 不使用

Arduino 程序

/** CAN_test.ino */
#include <SPI.h>
#include <mcp2515.h>

struct can_frame canMsg1;
struct can_frame canMsg2;

struct can_frame recv_frame;

MCP2515 mcp2515(10);


void setup() {
  canMsg1.can_id  = 0x000;
  canMsg1.can_dlc = 1;
  canMsg1.data[0] = 0x00;
  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  = 0x00;
  canMsg2.can_dlc = 4;
  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);
  SPI.begin();
  
  mcp2515.reset();
  mcp2515.setBitrate(CAN_500KBPS, MCP_20MHZ);
  //mcp2515.setListenOnlyMode();
  mcp2515.setNormalMode();
  
  Serial.println("Example: Write to CAN");
}

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

  Serial.println("polling");
  if (mcp2515.readMessage(&recv_frame) == MCP2515::ERROR_OK) {
    Serial.print("recv id:");
    Serial.print(recv_frame.can_id);
    Serial.print(" dlc:");
    Serial.print(recv_frame.can_dlc);
    Serial.print(" data:");
    Serial.print(recv_frame.data[0]);
    Serial.println("");
  }
  
  delay(100);

}
上一篇下一篇

猜你喜欢

热点阅读