2017-05-09 109 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