/* You should type your messages as IDH,IDH,LEN,D0,D1,D2,D3,D4,D5,D6,D7\n, where: IDH,IDL are the high and low parts of the CAN ID, in hexadecimal. LEN is the data length (0 to 8). D0 to D7 are the data bytes, in hexadecimal. If you type 123,456,3,12,34,56, this will send a CAN message with ID 0x123456, length 3, and data bytes 0x12, 0x34, 0x56. This code listens for user input. Once a newline is received, it parses the input and sends it as a CAN message. Note that this code does not handle errors in the input format, you should ensure you enter the data correctly. */ #include #include MCP_CAN CAN(10); // Set CS to pin 10 String inputString = ""; void setup() { Serial.begin(115200); while (CAN_OK != CAN.begin(CAN_500KBPS)) { // init can bus : baudrate = 500k Serial.println("CAN BUS Shield init fail"); Serial.println(" Init CAN BUS Shield again"); delay(100); } Serial.println("CAN BUS Shield init ok!"); } void loop() { unsigned char len = 0; unsigned char buf[8]; if (CAN_MSGAVAIL == CAN.checkReceive()) { // check if data coming CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf unsigned long canId = CAN.getCanId(); Serial.println("-----------------------------"); Serial.println("Get data from CAN BUS"); Serial.print("CAN ID: "); Serial.println(canId, HEX); // Prints ID in HEX format Serial.print("CAN Data: "); for(int i = 0; i 8 || parts[2] < 0) { Serial.println("Invalid length"); return; } // prepare id and data unsigned long canId = (parts[0] << 8) + parts[1]; unsigned char len = parts[2]; unsigned char data[8]; for (int i = 0; i < len; i++) { data[i] = parts[3 + i]; } // send the message CAN.sendMsgBuf(canId, 0, len, data); Serial.println("Sent CAN message"); }