Advertisement
Guest User

Arduino ReadCan

a guest
Feb 19th, 2016
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. #include <SPI.h>
  2. #include "mcp_can.h"
  3.  
  4. #define CAN_CS_PIN 10
  5.  
  6. MCP_CAN CAN(CAN_CS_PIN);
  7.  
  8. void setup() {
  9.   Serial.begin(115200);
  10.   Serial.println("Booting up");
  11.  
  12.  
  13. //  uint8_t can_speed = 0;
  14.   uint8_t can_speed = CAN_1000KBPS;
  15.  
  16.   uint8_t can_status = CAN.begin(can_speed);
  17.  
  18.   while(can_status != CAN_OK)
  19.   {
  20.     Serial.println("Could not init CAN, retrying...");
  21.     delay(250);
  22.     can_status = CAN.begin(can_speed);
  23.   }
  24.  
  25.   Serial.println("CAN MCP2515 init ok!");
  26.   //CAN.init_Mask(0, 0, 0x3ff);                         // there are 2 mask in mcp2515, you need to set both of them
  27.   //CAN.init_Mask(1, 0, 0x3ff);
  28.  
  29. }
  30.  
  31. void ReadCan()
  32. {
  33.  
  34.   uint8_t len = 0;
  35.   uint8_t buf[8];
  36.   uint8_t st = CAN.checkReceive();
  37.  
  38.   //Serial.print("S: "); Serial.println(st);
  39.   if(st != CAN_MSGAVAIL)
  40.   {
  41.     return;
  42.   }
  43.  
  44.   //Must read message before checking ID and other flags.
  45.  
  46.   CAN.readMsgBuf(&len, buf);
  47.  
  48.   Serial.print("ID "); Serial.print(CAN.getCanId(), HEX);
  49.   Serial.print(CAN.isExtendedFrame()?" E L":" s L");
  50.  
  51.  
  52.   Serial.print(len); Serial.print(" ");
  53.  
  54.   for(int i = 0; i<len; i++)
  55.   {
  56.     if(buf[i]<0x10)
  57.     {
  58.       Serial.print("0");
  59.     }
  60.     Serial.print(buf[i], HEX);
  61.     if(i<len-1)
  62.     {
  63.       Serial.print(":");
  64.     }
  65.   }
  66.   Serial.println();
  67. }
  68.  
  69. void loop() {
  70.   ReadCan();
  71.   delay(500);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement