Advertisement
Guest User

CAN Bus message send arduino example

a guest
Feb 17th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // demo: CAN-BUS Shield, send data
  2. #include <mcp_can.h>
  3. #include <SPI.h>
  4.  
  5. //Pot for adjusting value
  6. int sensorPin = A0;
  7. int sensorValue = 0;
  8. int cantxValue = 0;
  9.  
  10. void setup()
  11. {
  12.   Serial.begin(115200);
  13.   // init can bus, baudrate: 100k
  14.   if(CAN.begin(CAN_100KBPS) ==CAN_OK) Serial.print("can init ok!!\r\n");
  15.   else Serial.print("Can init fail!!\r\n");
  16. }
  17.  
  18. //Some sample CAN messages
  19. unsigned char msg1[8] = {0, 1, 2, 3, 4, 5, 6, 7};
  20. unsigned char msg2[8] = {0xFF, 0x01, 0x10, 0x0A, 0x00, 0x00, 0x00, 0x00};
  21. unsigned char msg3[4] = {0xFF, 0x01, 0x10, 0x0A};
  22.  
  23.  
  24. void loop()
  25. {
  26.   //Read the value of the pot
  27.   sensorValue = analogRead(sensorPin);
  28.   //Each CAN bus byte can store a value between 0-255.
  29.   //Dividing sensorValue by 4 puts us in that range.
  30.   cantxValue = sensorValue / 4;
  31.   Serial.print("cantxValue: ");
  32.   Serial.print(cantxValue);
  33.   Serial.println();
  34.   //Create data packet for CAN message
  35.   unsigned char canMsg[8] = {cantxValue, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  36.   // send data:  id = 0x123, standrad flame, data len = 8, stmp: data buf
  37.   CAN.sendMsgBuf(0x07B, 0, 8, canMsg);  
  38.   delay(100);
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement