2
votes

The functions below are used consequently to read data from serial port under Linux. I can read the complete data when I debug, but when I launch the program, read_buffer seems not to be complete. I receive the small part of the data correctly but the rest of the buffer is completely zero. What could be the problem?

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

1 Answers

2
votes

From 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),

In other words count parameter is the maximum bytes you want to read, but read can return a different number of bytes.

Returned value gives you the number of read bytes from FD.

To simply solve it you can do a loop receiving bytes until the expected length is reached, reading 1 byte a time.

Other solution can be implemented using Read Timeouts