Вопрос

I am writing a code for modbus protocol, that runs on a MSP430 controller. The response buffer(global) is an array of 8bit data, through which the response to the processed request is to be sent on serial UART. Now, my problem is that the response generated is having a combination of different data types. i.e uint8, uint32, float. How to send this data by using the global response buffer?

For float, i have tried using memcpy and this seems to be working fine. Is there any better and efficient way? Cuz the frame size is large (say 20-30 bytes). Here is a demo of what i've tried to do

int main() 
{ unsigned char buff[8]; //Global buffer 

float temp[2]; //temp buffer to store response values 

temp[0] = 0x00ef2212; 

memcpy(buff, temp, 8); 

printf("buff[0]= %u \n buff[1]= %u\n buff[2] = %u\n buff[3]= %u\n", buff[0],buff[1],buff
[2],buff[3]); 

return 0; 
} 
Это было полезно?

Решение

With casting and assignment. E.g.

uint8 *globalbuf;
uint32 myval;
*(uint32*)globalbuf = myval;

copies myval into the first 4 bytes of globalbuf.

Beware of alignment issues: it may be illegal or expensive on your platform to assign or read values to/from addresses that aren't whole multiples of that type size. For example address 0,4,8 etc. are OK places to put a uint32.

This assumes your globalbuf starts on a nice round address..

Другие советы

a simple implementation would be to create a response structure and memcpy the response structure to the buffer

struct response {
   uint8 bytedata;
   uint32 intdata;
   float  floatdata;
};
memcpy((void *)uartbuffer,(void *)&response,sizeof(response));

Note: since it looks like your working on a protocol the endianess may be already specified and you may need to pack items according to the particular endian type and simple memcpy would not work and you may need to pack the datatypes.

How about considering using a union to represent a same range of memory into different data types?

typedef union {
    unsigned char buff[8];
    float temp[2];
} un;

un global_buffer;
// give global_buffer.buff some data.
un local_buffer;

local_buffer = global_buffer; 
// handle local_buffer.temp
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top