当前位置:  开发笔记 > 编程语言 > 正文

Linux串行读取()无关数据

如何解决《Linux串行读取()无关数据》经验,为你挑选了1个好方法。

我有两个应用程序串行通信.目标有一个它导航的状态机.它将接收并丢弃数据,直到它获得消息字节(0xE3)的开始,然后处理数据直到消息字节(0x3E)结束.我遇到了一些数据问题.我认为这是一个处理问题而不是通信问题.我也知道这很简单,但很难看到问题.

主机正在向目标发送数据.bfr数据是:{0xAA, 0xFF, 0x05, 'H', 'e', 'l', 'l', 'o'};

byte = MSG_START_BYTE; // 0xE3
if (write(fd, &byte, 1) < 0)
    return -1;

if (write(fd, bfr, bfr_len) < 0)
    return -1;

if (write(fd, &crc, sizeof(crc)) < 0)
    return -1;

byte = MSG_END_BYTE;  // 0x3E
if (write(fd, &byte, 1) < 0)
    return -1;

目标是使用select()和read()来接收数据.

char rx_bfr[128];
uint8_t max_bytes_to_read = 1;

memset(rx_bfr, 0, strlen(rx_bfr));
...
printf("\tactivity...");
bytes_read = read(fd, rx_bfr, max_bytes_to_read);
if (bytes_read < 0)
    return -1;
else if (bytes_read == 0)
    return -1;

printf(" %d bytes to process...\n", bytes_read);
for (i = 0; i < bytes_read; i++)
{
    printf("byte[%d] = 0x%x\n", i, rx_bfr[i]);
    switch (state)
    {
        case SOM:
            if (rx_bfr[i] == 0xE3)
 ...

目标控制台输出是:

Waiting for message...
    activity... 1 bytes to process...
byte[0] = 0xffffffe3
    activity... 1 bytes to process...
byte[0] = 0xffffffaa
    activity... 1 bytes to process...
byte[0] = 0xffffffff
    activity... 1 bytes to process...
byte[0] = 0x5
    activity... 1 bytes to process...
byte[0] = 0x48
    activity... 1 bytes to process...
byte[0] = 0x65
    activity... 1 bytes to process...
byte[0] = 0x6c
    activity... 1 bytes to process...
byte[0] = 0x6c
    activity... 1 bytes to process...
byte[0] = 0x6f
    activity... 1 bytes to process...
byte[0] = 0xffffffd4
    activity... 1 bytes to process...
byte[0] = 0xffffff81
    activity... 1 bytes to process...
byte[0] = 0x1a
    activity... 1 bytes to process...
byte[0] = 0x3c
    activity... 1 bytes to process...
byte[0] = 0x3b
    activity... 1 bytes to process...
byte[0] = 0x3e

所以在我的状态机中,if条件是寻找0xE3SOM,但是从printf看到的缓冲区中的第一个"字节"是0xFFFF_FFE3.



1> David Schwar..:
char rx_bfr[128];

在您的平台char上签名.值为0xE3的带符号的char为负,但值为0xE3的整数为正,因此它们不会相等.请unsigned char改用.

推荐阅读
和谐啄木鸟
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有