2017-05-09 108 views
1

以下功能用於在Linux下從串口讀取數據。我可以在調試時讀取完整的數據,但是當我啓動程序時,read_buffer似乎並不完整。我正確接收了小部分數據,但緩衝區的其餘部分完全是。可能是什麼問題呢?串口讀取未完成

int8_t __serial_port_open(uint8_t *port) 
{ 
    mode_t perms = S_IRWXU; 
    fd = open(port, O_RDWR | O_NOCTTY | O_SYNC, perms); 
    if (fd < 0) 
    { 
     return -1; 
    } 

    if (__serial_port_configure() != 0) 
     return -1; 

    return 0; 
} 

static int8_t __serial_port_configure(void) 
{ 
    struct termios attr; 

    if (tcgetattr(fd, &attr) == -1) 
    { 
     return -1; 
    } 
    if (cfsetispeed(&attr, B115200) == -1) 
    { 
     return -1; 
    } 
    if (cfsetospeed(&attr, B115200) == -1) 
    { 
     return -1; 
    } 
    attr.c_cflag |= (CLOCAL | CREAD); 
    attr.c_cflag &= ~PARENB; 
    attr.c_cflag &= ~CSTOPB; 
    attr.c_cflag &= ~CSIZE; 
    attr.c_cflag |= (CS8); 
    attr.c_cflag |= CRTSCTS; 
    attr.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); 
    attr.c_iflag &= ~(IXON | IXOFF | IXANY); 
    attr.c_oflag &= ~OPOST; 
    if (tcsetattr(fd, TCSANOW, &attr) == -1) 
    { 
     return -1; 
    } 
    return 0; 
} 

int8_t __serial_port_read(uint8_t *read_buffer, uint32_t nbytes_to_read, uint32_t *nbytes_read) 
{ 
    do 
    { 
     *nbytes_read = read(fd, read_buffer, nbytes_to_read); 
     if (*nbytes_read == -1) 
     { 
      return -1; 
     } 
    } while (*nbytes_read == 0); 

    return 0; 
} 

回答

2

the man

讀()嘗試讀向上計數從文件描述符fd字節到開始BUF緩衝區。

返回值

成功時,讀取的字節返回的數量(零表示文件的結尾),

換句話說count參數是你想讀的最大字節數,但讀取可以返回不同數量的字節。

返回值爲您提供從FD讀取的字節數。

要簡單地解決它,你可以做一個循環接收字節,直到達到預期的長度,每次讀取1個字節。

其他解決方案可以使用Read Timeouts