解析并读取C中的数据帧? [英] Parse and read data frame in C?
问题描述
我正在编写一个程序,该程序从Linux上的串行端口读取数据. 数据是由另一台设备以以下帧格式发送的:
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 | Command | Data | CRC | End |
|0x02 | 0x41 | (0-127 octets) | | 0x03|
----------------------------------------------------
数据字段包含127个八位位组,如图所示,八位位组1,2包含一种类型的数据;字节3,4包含另一个数据.我需要获取这些数据
The Data field contains 127 octets as shown and octet 1,2 contains one type of data; octet 3,4 contains another data. I need to get these data
我知道如何在Linux的串行端口中读写数据,但这只是在读写一个简单的字符串(如"ABD")
I know how to write and read data to and from a serial port in Linux, but it is just to write and read a simple string (like "ABD")
我的问题是我不知道如何解析如上所述格式的数据帧,以便可以:
My issue is that I do not know how to parse the data frame formatted as above so that I can:
- 在数据"字段中获取八位字节1,2中的数据
- 在数据"字段中获取3,4字节的数据
- 在CRC字段中获取值以检查数据的一致性
以下示例代码片段可在Linux中的串行端口之间读写简单的字符串:
Here the sample snip code that read and write a simple string from and to a serial port in Linux:
int writeport(int fd, char *chars) {
int len = strlen(chars);
chars[len] = 0x0d; // stick a <CR> after the command
chars[len+1] = 0x00; // terminate the string properly
int n = write(fd, chars, strlen(chars));
if (n < 0) {
fputs("write failed!\n", stderr);
return 0;
}
return 1;
}
int readport(int fd, char *result) {
int iIn = read(fd, result, 254);
result[iIn-1] = 0x00;
if (iIn < 0) {
if (errno == EAGAIN) {
printf("SERIAL EAGAIN ERROR\n");
return 0;
} else {
printf("SERIAL read error %d %s\n", errno, strerror(errno));
return 0;
}
}
return 1;
}
有人请问一些想法吗?
推荐答案
result
是由char
s组成的数组,其宽度为1个八位位组.
result
is an array of char
s, which are 1 octet wide.
要读取八位位组 n ,请使用:
to read octet n use:
char octet_n = result[n];
要做你想做的事
// skip the start and command fields
char *data_field = result + 2;
int octet_1_2 = data_field[1] | (data_field[2] << 8);
int octet_3_4 = data_field[3] | (data_field[4] << 8);
// crc is at byte 128 + 2 = 130
int crc = result[130];
修改:此行的说明:
int octet_1_2 = data_field[1] | (data_field[2] << 8);
您想将两个连续的八位位组读取为一个16位字:
You want to read two consecutive octets into one 16-bit word:
1
bits 5 8 7 0
--------------------
octet_1_2 = | octet 2 | octet 1|
--------------------
因此,您想获取八位位组1的7:0位,并将它们放入octet_1_2
的7:0位:
So you want to take bits 7:0 of octet 1 and put them in bits 7:0 of octet_1_2
:
octet_1_2 = data_field[1];
然后,您要获取八位位组2的7:0位,并将它们放入octet_1_2
的15:8位.您可以通过将八位位组2向左移动8位,并将结果OR
'放入octet_1_2
:
Then you want to take bits 7:0 of octet 2 and put them in bits 15:8 of octet_1_2
. You do this by shifting octet 2 8 bits to the left, and OR
'ing the result into octet_1_2
:
octet_1_2 |= data_field[2] << 8;
这两行可以像我上面那样合并为一.
These two lines can be merged into one as I did above.
这篇关于解析并读取C中的数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!