美文网首页
Case. Arduino 与 STM32 进行 CAN 通讯

Case. Arduino 与 STM32 进行 CAN 通讯

作者: T_K_233 | 来源:发表于2020-07-23 11:55 被阅读0次

    接线

    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);
    
    }
    

    相关文章

      网友评论

          本文标题:Case. Arduino 与 STM32 进行 CAN 通讯

          本文链接:https://www.haomeiwen.com/subject/qawclktx.html