2012-05-29 20 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