Hi everyone!
I am working on a project where I need to format raw bytes received via serial into float or double value. I am using Arduino mega for this project. I am able to convert into signed and unsigned integer but somehow conversion to float does not work. I am explaining my requirement below with an example :
Example :: 0x41CC28F6 should give 25.52
Below is the function I use for data conversion in my code.
void Format_Data(struct MB_RESP *input, unsigned char fmt, char *data)
{
char arr[30];
float real;
unsigned long int temp;
strcat(data, ",");
switch (fmt)
{
case INT16:
*((char*)(&temp) + 0) = input->data[1];
*((char*)(&temp) + 1) = input->data[0];
*((char*)(&temp) + 2) = 0;
*((char*)(&temp) + 3) = 0;
sprintf(arr, "%d", temp);
arr[5] = '\0';
strcat(data, arr);
break;
case UINT16:
*((char*)(&temp) + 0) = input->data[1];
*((char*)(&temp) + 1) = input->data[0];
*((char*)(&temp) + 2) = 0;
*((char*)(&temp) + 3) = 0;
sprintf(arr, "%u", temp);
arr[5] = '\0';
strcat(data, arr);
break;
case INT32:
*((char*)(&temp) + 0) = input->data[3];
*((char*)(&temp) + 1) = input->data[2];
*((char*)(&temp) + 2) = input->data[1];
*((char*)(&temp) + 3) = input->data[0];
sprintf(arr, "%ld", temp);
arr[10] = '\0';
strcat(data, arr);
break;
case UINT32:
*((char*)(&temp) + 0) = input->data[3];
*((char*)(&temp) + 1) = input->data[2];
*((char*)(&temp) + 2) = input->data[1];
*((char*)(&temp) + 3) = input->data[0];
sprintf(arr, "%lu", temp);
arr[10] = '\0';
strcat(data, arr);
break;
case IEEE754FP:
*((char*)(&temp) + 0) = input->data[1];
*((char*)(&temp) + 1) = input->data[0];
*((char*)(&temp) + 2) = input->data[3];
*((char*)(&temp) + 3) = input->data[2];
sprintf(arr, "%lu", temp); //temporarily converting into unsigned long long int
// sprintf(arr, "%lf", (double)temp); //gives '?' on serial
arr[10] = '\0';
strcat(data, arr);
break;
}
}
I have included all header files and there is no compilation error.