串口读取未完成

Serial port read is not complete

下面的函数用于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;
}

来自the man

read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

Return Value

On success, the number of bytes read is returned (zero indicates end of file),

也就是说count参数是你要读取的最大字节数,但是读取可以return不同的字节数。

返回值是从 FD 读取的字节数。

要简单地解决它,您可以循环接收字节,直到达到预期长度,一次读取 1 个字节。

可以使用 Read Timeouts

实施其他解决方案