I am writing a program that reads the data from the serial port on Linux. The data are sent by another device with the following frame format:
|start | Comm
The best thing to read formatted data in C is to read a structure. Given the frame format you have I would do the following.
typedef struct special_data
{
char first_data[2];
char second data[2];
} special_data_t;
union data_u
{
special_data_t my_special_data;
char whole_data[128];
};
typedef struct data_frame
{
unsigned char start;
unsigned char cmd;
union data_u data;
unsigned char crc;
unsigned char end;
} data_frame_t;
void func_read(int fd)
{
data_frame_t my_data;
if (read(fd, &my_data, sizeof(my_data)) != -1)
{
// Do something
}
return;
}
This way you may access the data you need through the structure fields. The first structure and the union are just helpers to access the bytes you need in the data field of the frame.