I need help to send a double value using a CAN Bus.
I am working on a eletronic traction control and i need to send, by a CAN bus, the calculated values of speed of wheels. The problem start when the calculated value is a double type and i need to send it as a short int or int.
Example:
double speed_calculated;
short value_to_send;
char can_data_to_send[8]; //the function CANWrite sends a vector of char;
speed_calculated = function_to_calculate_correction();
value_to_send = (short)speed_calculated * 10;
can_data_to_send[0] = value_to_send;
can_data_to_send[1] = value_to_send >> 8;
My intention to do is:
If the "speed_calculated" is 10.5, so multiply by 10 and storage 105 in "value_to_send".
As "value_to_send" is a short type, theoretically, i can send 2 bytes.
But, as i am using arduino to test and debug the CAN communication, i am not receiving the correct values.
If i remove the multiplier "*10" of "value_to_send = (short)speed_calculated" i receive only the value of 98 instead 198 that is the correct.
I don't know what i am doing wrong, i've been spending much time searching and testing differents ideas but no one works.
I appreciate the help
Best Answer
To avoid side-effects, a better way would be to use this statement
Refer -> PromotionRules
As to the second part of your question, you say 198 is the expected value. Which means, function_to_calculate_correction() must return 198(0xC6) .
I see no way how short to char conversion would lead 198 to be loaded as 98 in can_data_to_send[0] as 198 can be easily accommodated in a byte.
Also, if your scaling factor is 10, is double really required?