在C语言中从一个框架中提取错误的数据?[英] Extract wrong data from a frame in C?

本文是小编为大家收集整理的关于在C语言中从一个框架中提取错误的数据?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在编写一个程序,该程序从Linux上的串行端口读取数据.数据由其他设备以下框架格式发送:


|start | Command | Data               | CRC  | End |
|0x02  | 0x41    | (0-127 octets)     |      | 0x03|
----------------------------------------------------

数据字段包含127个八位字节,如图所示,八位字节1,2包含一种类型的数据. Octet 3,4包含另一个数据.我需要获取这些数据.

因为在 c 中,一个字节只能保留一个字符,在框架的开始字段中,它是0x02,这意味着STX为3个字符.

因此,为了测试我的程序,

在发件人侧,我构造了一个阵列,就像上面格式的框架一样:


char frame[254];
frame[0] = 0x02; // starting field
frame[1] = 0x41; // command field which is character 'A'
..so on..

,然后,在接收方的一侧,我取出了:


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'.

我认为,这是因为帧的第一个字段值为0x02(STX),在数组框架中占据了3个第一名,并在接收器侧导致错误的结果.

我该如何纠正问题或在发件人方面做错了什么?

相关问题:
parse and parse and parse and读取数据框架?
c?

推荐答案

如果您的程序实际包含

read(result);

然后您需要添加

#include <unistd.h>

在顶部获得read的功能原型.然后,您需要open串行端口,然后将结果文件描述符和缓冲区一起传递给read,因此它知道该阅读内容.参见man 2 read和man 2 open.

本文地址:https://www.itbaoku.cn/post/2091183.html

问题描述

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|
----------------------------------------------------

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.

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

the command field value (result[1]) is not character 'A'.

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?

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);

then you need to add

#include <unistd.h>

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.