从C中的帧中提取错误的数据? [英] Extract wrong data from a 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.
因为在 C 中,一个字节只能容纳一个字符,并且在帧的开始字段中,它是0x02,表示STX是3个字符.
Because in C, one byte can only holds one character and in the start field of the frame, it is 0x02 which means STX which is 3 characters.
所以,为了测试我的程序,
So, in order to test my program,
在发送方,我按照上面的格式构造一个数组,如下所示:
On the sender side, I construct an array as the frame formatted above like:
char frame[254];
frame[0] = 0x02; // starting field
frame[1] = 0x41; // command field which is character 'A'
..so on..
然后,在接收器端,我取出像这样的字段:
And, then On the receiver side, I take out the fields like:
char result[254];
// read data
read(result);
printf("command = %c", result[1]); // get the command field of the frame
// get other field's values
命令字段值(结果[1])不是字符'A'.
the command field value (result[1]) is not character 'A'.
我认为,这是因为帧的第一个字段值为0x02(STX),在数组帧中占据3个首位,并导致接收器端出现错误的结果.
I think, this because the first field value of the frame is 0x02 (STX) occupying 3 first places in the array frame and leading to the wrong results on the receiver side.
我该如何解决此问题,或者我在发件人一方做错了什么?
How can I correct the issue or am I doing something wrong at the sender side?
相关问题:
在C语言中解析和读取数据帧?
在Linux中使用C语言清除串行端口上的数据吗?
related questions:
Parse and read data frame in C?
Clear data at serial port in Linux in C?
推荐答案
如果您的程序实际上包含
If your program actually contains
read(result);
然后您需要添加
#include <unistd.h>
在顶部,以获取read
的函数原型.然后,您需要open
串行端口,并将生成的文件描述符与缓冲区一起传递给read
,以便它知道要读取的内容.参见man 2 read
和man 2 open
.
at the top, to get the function prototype for read
. Then you need to open
the serial port and pass the resulting file descriptor to read
along with your buffer, so it knows what to read. See man 2 read
and man 2 open
.
这篇关于从C中的帧中提取错误的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!