CAN Message Data

I am at a loss as to why this is happening. I am reading in the 3rd and 4th data values sent over CAN into a char array and from there will manipulate it as needed to execute commands. Its working just fine with the first two data sets received, but when reading the 3rd and 4th values into an array it is adding two extra characters. I'm sure its something simple I'm not seeing but I'm at a loss right now.

Here is the reading sketch:

#include <SPI.h>
#include <mcp2515.h>

struct can_frame canMsg;
MCP2515 mcp2515(53);
char combine[8];
char test;
char lcommand[8] = "";
String linput = "";

char ninput[2];
String ncommand = "";
int nninput;


void setup() {
  Serial.begin(115200);
  
  mcp2515.reset();
  mcp2515.setBitrate(CAN_125KBPS);
  mcp2515.setNormalMode();
  
  Serial.println("------- CAN Read ----------");
  Serial.println("ID  DLC   DATA");
}

void loop() {
  if (mcp2515.readMessage(&canMsg) == MCP2515::ERROR_OK) {
    Serial.print(canMsg.can_id, HEX); // print ID
    Serial.print(" "); 
    Serial.print(canMsg.can_dlc, HEX); // print DLC
    Serial.print(" ");
    
    for (int i = 0; i<canMsg.can_dlc; i++)  {  // print the data
      Serial.print(canMsg.data[i], HEX);
      Serial.print(" ");
      //combine = combine + canMsg.data[i],HEX;
    }

    for (int i = 0; i < 2; i++){
      lcommand[i] = canMsg.data[i];
    }
    for (int i = 2; i < 4; i++){
      ninput[i-2] = canMsg.data[i];
    }
    
    Serial.println();
    ncommand = ninput;
    nninput = ninput;
    Serial.print("Number (Char): "); Serial.println(ninput);
    Serial.print("Number (String): "); Serial.println(ncommand);
    
    Serial.print("Letter Command: "); Serial.println(lcommand);
    Serial.println(combine);
    linput = lcommand;

    if (linput == "EE"){
      Serial.println("Letter Success!");
    }


    if (ninput == "25"){
      Serial.println("Number Success!");
    }

    Serial.println();      
  }
}

Here are the results from Serial Monitor:

F6 4 45 45 32 35
Number (Char): 25EE
Number (String): 25EE
Letter Command: EE
Letter Success!

The F6 is the message identifier, the #4 is how long the message is, and the next four numbers are the HEX values being sent.

The number char and string should be just 25.

Need to use strcmp() and atoi() when dealing with C char arrays.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.