【问题标题】:How can I read bytes immediately from a serial port instead of waiting for a newline?如何立即从串行端口读取字节而不是等待换行符?
【发布时间】:2020-10-17 06:38:57
【问题描述】:

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

python 向 C 发送 24 个字节

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;

}

【问题讨论】:

  • 我认为这也适用于串行端口:stackoverflow.com/questions/54358053/… - 告诉我它是否适合您,我会投票将这个问题与那个问题联系起来
  • @user253751 这不会使终端脱离线路模式。终端需要输入raw mode
  • 您缺少设置终端波特率、模式和其他选项的代码。所以终端处于其默认模式,即线路模式。
  • 谢谢大家的意见。似乎我需要将串口配置为原始模式。我会努力回来的。

标签: python c linux


【解决方案1】:

除了 cmets 中的建议外,通常在 while(some_variable &lt; 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;
    }
    ....

【讨论】:

    【解决方案2】:

    灵感来自所有朋友的意见。我通过设置串口解决了问题

    stty -F /dev/ttyS0 115200 min 1 -icanon -echo
    

    在运行 C 代码之前,如上设置串口。然后 read() 将读取串行端口上可用的任何内容。然后返回。

    我不太明白min 1 -icanon -echo 的意思,但它解决了换行问题。

    谢谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 2010-09-17
      • 2021-12-16
      • 2015-07-30
      相关资源
      最近更新 更多