串行通讯RX大小限制

时间:2019-01-15 17:07:24

标签: c serial-communication

我不能收到我发送的所有字节。 (Raspberry Pi 3B + / Raspbian)

我试图以9600bit / s的速度发送4000字节并仅接收960字节。当我提高速度时,增加了接收的字节数。我尝试在c_cc数组中设置VTIME和VMIN值,但不会更改所有内容。

如何接收所有字节?

a

输出:

transmitter:

char write_buffer[4000];    /* Buffer containing characters to write into port       */

        for(uint32_t i=0;i<4000;i++)
        {
            write_buffer[i] = i;
        }

        int  bytes_written  = 0;    /* Value for storing the number of bytes written to the port */ 

        bytes_written = write(fd,write_buffer,sizeof(write_buffer));/* use write() to send data to port                                            */
                                         /* "fd"                   - file descriptor pointing to the opened serial port */
                                         /* "write_buffer"         - address of the buffer containing data              */
                                         /* "sizeof(write_buffer)" - No of bytes to write                               */  
        printf("\n  %s written to ttyUSB0",write_buffer);
        printf("\n  %d Bytes written to ttyUSB0", bytes_written);
        printf("\n +----------------------------------+\n\n");

receiver:

/*------------------------------- Read data from serial port -----------------------------*/

        char read_buffer[4000];   /* Buffer to store the data received              */
        uint32_t  bytes_read = 0;    /* Number of bytes read by the read() system call */
        int i = 0;

        bytes_read = read(fd,&read_buffer,4000); /* Read the data                   */

        printf("\n\n  Bytes Rxed: %d", bytes_read); /* Print the number of bytes read */
        printf("\n\n  ");

        for(i=0;i<bytes_read;i++)    /*printing only the received characters*/
            printf("%c",read_buffer[i]);

        printf("\n +----------------------------------+\n\n\n");

1 个答案:

答案 0 :(得分:0)

不能保证read系统调用返回请求的字节数。请参阅this链接以获取完整参考。

如果read返回一个非负值,则该值表示读取的字节数,在您的情况下为960字节。

为确保成功读取所有字节,您需要将对read的调用置于某种形式的循环内。也许与此类似:

char buffer[4000 + 1]; /* +1 to leave space for null-terminator */

memset(buffer, 0, sizeof(buffer)); /* Clear buffer */

size_t bytesToRead = 4000;
size_t bytesRead = 0;
while (bytesToRead > 0)
{
    const ssize_t retVal = read(fd, buffer + bytesRead, bytesToRead);
    if (retVal < 0)
    {
        /* Handle error */
    }

    const size_t bytes = (size_t) retVal;
    bytesRead += bytes;
    bytesToRead -= bytes;
}