2012-05-29 22 views
0

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

代码示例:

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

如何配置我的端口:

int configure_port(int fd) // configure the port 
{ 
    struct termios port_settings; // structure to store the port settings in 

    cfsetispeed(&port_settings, B9600); // set baud rates 
    cfsetospeed(&port_settings, B9600); 

    port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits 
    port_settings.c_cflag &= ~CSTOPB; 
    port_settings.c_cflag &= ~CSIZE; 
    port_settings.c_cflag |= CS8; 

    tcsetattr(fd, TCSANOW, &port_settings); // apply the settings to the port 
    return (fd); 
} 

问题是什么?回声如何混合2次10次?

+0

您怎样沟通?它是如何配置的? –

+0

也许你应该修正以下几点: char c; ... res = read(fd,&c,200);它可能会导致溢出。这可能会导致令人讨厌的问题。 – SKi

+4

'res = read(fd,&c,200);'您试图将200个字节读入单字节字符? – wildplasser

回答

1

也许你应该尝试的功能bzero()当您配置连接。

bzero(&port_settings, sizeof (port_settings)); 

这清除了新的端口设置,这可能有助于阻止你获得通过串口不规则的答案结构。

+0

谢谢,我现在就试试这个 – NeViXa

+0

这实际上似乎工作!谢谢! – NeViXa