Advertisement
Nusa_Techno

can

Jul 8th, 2024
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | Source Code | 0 0
  1. #include <SPI.h>
  2. #include <mcp_can.h>
  3.  
  4. #define CAN0_INT 2   // Set INT to pin 2
  5. MCP_CAN CAN0(10);    // Set CS to pin 53
  6.  
  7. void setup() {
  8.  
  9.     Serial.begin(115200);
  10.    
  11.     // Initialize MCP2515 CAN controller at the specified baud rate
  12.     if (CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_8MHZ) == CAN_OK) {
  13.         Serial.println("CAN BUS Shield init ok!");
  14.     } else {
  15.         Serial.println("CAN BUS Shield init fail");
  16.         Serial.println(" Init CAN BUS Shield again");
  17.         delay(100);
  18.         while (1);
  19.     }
  20.    
  21.     // Set receive interrupt
  22.     CAN0.setMode(MCP_NORMAL);
  23.     pinMode(CAN0_INT, INPUT);
  24.    
  25.     Serial.println("Starting to Receive CAN BUS Message...");
  26. }
  27.  
  28. void loop() {
  29.     long unsigned int rxId;
  30.     unsigned char len = 0;
  31.     unsigned char rxBuf[8];
  32.  
  33.     // Check if data is coming
  34.     if (!digitalRead(CAN0_INT)) {
  35.         CAN0.readMsgBuf(&rxId, &len, rxBuf);
  36.        
  37.         Serial.print("CAN ID: ");
  38.         Serial.print(rxId, HEX);
  39.         Serial.print(" Data: ");
  40.        
  41.         for (int i = 0; i < len; i++) {
  42.             Serial.print(rxBuf[i], HEX);
  43.             Serial.print("\t");
  44.         }
  45.         Serial.println();
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement