C 单线串行通信,回音错误

C 单线串行通信,回音错误,c,ubuntu,serial-port,termios,C,Ubuntu,Serial Port,Termios,我有一个单线串行通信接口,问题是我发送01010101,我收到的回波是10次01010101中的8次,但10次中的2次我收到01110101 代码示例: void checkVersion(int fd) { tcflush(fd, TCIFLUSH); unsigned char checkVersion[] = {0x55, 0x02, 0x00, 0x02}; int n = write(fd, &checkVersion, 4); //Send data

我有一个单线串行通信接口,问题是我发送01010101,我收到的回波是10次01010101中的8次,但10次中的2次我收到01110101

代码示例:

void checkVersion(int fd) {
    tcflush(fd, TCIFLUSH);
    unsigned char checkVersion[] = {0x55, 0x02, 0x00, 0x02};
    int n = write(fd, &checkVersion, 4); //Send data
    if (n < 0) cout << "BM: WRITE FAILED" << endl;

    char read_bytes[10] = {0};
    char c;
    int aantalBytes = 0;
    bool foundU = false;
    int res;
    while (aantalBytes < 7) {
        res = read(fd, &c, 200);
        if (res != 0) {
            cout << "Byte received: " << bitset < 8 > (c) << endl;
            if (c == 'U')foundU = true;
            if (foundU)
                read_bytes[aantalBytes++] = c;
        }
        if (aantalBytes > 2 && !foundU) break;
    }
    if (!foundU) checkVersionSucceeded = false;
    if (read_bytes[aantalBytes - 3] == 0x02 && read_bytes[aantalBytes - 2] == 0x04 && read_bytes[aantalBytes - 1] == 0x06)
       cout << "BM Version 4" << endl;
}

有什么问题?回声怎么可能被混淆了10次中的2次呢?

也许在配置连接时,您应该尝试使用bzero()函数

bzero(&port_settings, sizeof (port_settings));

这将清除新端口设置的结构,这可能有助于停止通过串行端口接收的不规则应答。

您在与什么通信?它是如何配置的?也许你应该修复以下问题:char c。。。res=读取(fd和c,200);它可能会导致溢出。这可能会导致严重的问题。
res=read(fd,&c,200)您试图将200字节读入一个单字节字符?正如@wildplasser已经说明的,您的代码有一些怪癖。例如,看起来您还想查找前7个字节中的“U”字符,但只有在找到“U”时,
aantalBytes
才会递增。
if(!foundU){}
语句是无用的,因为如果
foundU
true
,循环就不会退出。也许先尝试做一些非常简单的事情,比如
tcflush();写入(1个字符);读取(1个字符)
并查看问题是否仍然存在。感谢您的回答,但尚未解决。我确实在“搜索”U,因为这是我作为第一个字节(0x55=U)发送的,因此应该作为第一个字节接收,U之前的所有内容(如果有)都是垃圾。如果确实失败,循环将不会退出,在实际函数中,我有一个“循环杀手计数器”。谢谢,我现在就试试这个
bzero(&port_settings, sizeof (port_settings));