# CAN-BUS message conversion

Hi, total beginner here.

I’ve connected the arduino to my car’s can-bus system using autowp/arduino-mcp2515 library.
My goal is to read RPM frames and update the rpm value of the program.

I’ve found an excell formula online for calculating the rpm value:

``````ARBID: 0x316 (DME1)
-B0
-B1
-B2 RPM LSB
-B3 RPM MSB [RPM=(hex2dec("byte3"&"byte2"))/6.4]
-B4
-B5
-B6
-B7
``````
``````void handleCanFrames() {
Serial.print(canMsg.can_id, HEX); Serial.print(" "); Serial.print(canMsg.can_dlc, HEX); Serial.print(" ");
for (int i = 0; i<canMsg.can_dlc; i++)  {  // print the data
Serial.print(canMsg.data[i],HEX); Serial.print(" ");
}

if(canMsg.can_id == CAN_BUS_RPM_FRAME_ID) {
float rpm = strtol(canMsg.data + canMsg.data, NULL, 16) / 6.4;
rpm_current = rpm;
}
}
}
``````

The problem is my coding knowledge is not sufficient to do it. In the code above I am getting 0.00.
If I calculate the value manually by taking what serial print is showing me, for example third data byte: 12, second is: 3F and add them as strings 123F (4671 in decimal) and divide the number by 6.4 I am getting the correct value 729.84.

Any tips and tutorials are welcome.

You need to do the same calculations with the Arduino. I do not believe you need to use float, I know of no vehicle that sends RPM as a floating point number.

gilshultz:
You need to do the same calculations with the Arduino. I do not believe you need to use float, I know of no vehicle that sends RPM as a floating point number.

Well yes, this is exactly where I am failing. Should I somehow convert byte to HEX string and then add them? (any tips on that? I’ve tried googling but all cases were too difficult to understand)
Of course I don’t receive it as float, I thought the result after the division would be though.

I would have a look at the examples that come with a number of these shields - there are examples translating the PID code returns , how they are made up etc .

In case anyone will have same issue this is how I’ve solved it:
String(canMsg.data, HEX) converts in to the hex string, all that was remaining was to convert hex string back strtoul(hexString.c_str(), NULL, 16)

``````void handleCanFrames() {
Serial.print(canMsg.can_id, HEX); Serial.print(" "); Serial.print(canMsg.can_dlc, HEX); Serial.print(" ");
for (int i = 0; i<canMsg.can_dlc; i++)  {  // print the data
Serial.print(canMsg.data[i],HEX); Serial.print(" ");
}

if(canMsg.can_id == CAN_BUS_RPM_FRAME_ID) {
String hexString = String(canMsg.data, HEX) + String(canMsg.data, HEX);
float rpm = strtoul(hexString.c_str(), NULL, 16) / 6.4;

Serial.print("RPM: "); Serial.println(rpm);
}
}
}
``````

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