首页 > 解决方案 > 如何立即从串行端口读取字节而不是等待换行符?

问题描述

我有串行到 USB 连接。C打开/dev/ttyS0,python打开/dev/ttyUSB0。C read(),来自 python 的 24 个字节。请参阅下面的 C 代码。

python将24个字节发送到C

ser.write(b'123456789012345678901234'.encode())

C面没有打印。如果我在字符串末尾添加 \n 。

ser.write(b'123456789012345678901234\n'.encode())

然后在 C 面打印

 get 24 bytes
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
 get 24 bytes
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
 get 1 bytes

似乎 read() 必须等待 '\n' 才能从函数 read() 返回。

我的问题是如何让 read() 在获取 24 个字节后返回?

#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

typedef unsigned char uint8_t;
typedef unsigned int  uint32_t;

int fd = 0;

int main()
{
    int ret = 0;

    fd = open( "/dev/ttyS0", O_RDWR );

    if ( fd == -1 )
    {
        printf("open communication port fail");
        ret = 1;
    }

    while(1)
    {
        uint8_t buf[100]={0};
        int cnt = 0;

        cnt = read(fd, buf, 24);   

        printf(" get %d bytes\n", cnt);

        for ( int i = 0; i < cnt; i++ )
        {
            printf( "%c ", buf[i]);

        }
        printf("\n");

     }


    close(fd);

    return 0;

}

标签: pythonclinux

解决方案


除了注释中的建议外,通常在循环中放置变量退出条件会很有用: 例如, from :while(some_variable < some_value)

while(1)

int cnt = 0;//declare and initialize before loop
while(cnt < 24 )

break;一旦满足退出条件,您也可以在循环中添加一条语句。例如类似于:

    ...
    cnt = read(fd, buf, 24);
    if(cnt == 24)
    {   
        printf(" get %d bytes\n", cnt);

        for ( int i = 0; i < cnt; i++ )
        {
            printf( "%c ", buf[i]);
        }
        printf("\n");
        break;
    }
    ....

推荐阅读