代码之家  ›  专栏  ›  技术社区  ›  md.jamal

串行口通信中新线字符的意义

  •  0
  • md.jamal  · 技术社区  · 6 年前

    我们正在测试串口通讯。设备上有两个tty节点/dev/ttyUSB8和/dev/ttyUSB9。

    当我将缓冲区从/dev/ttyUSB8传输到/dev/ttyUSB9时,如果缓冲区不包含新行,我就不会在/dev/ttyUSB9 read调用上接收数据。

    传输代码

    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <termios.h>
    #include <unistd.h>
    
    void write_func()
    {
        int fdw;
        int i;
        fdw = open("/dev/ttyUSB8", O_RDWR);
        printf("fdw : %d\n",fdw);
    
        printf("%ld\n", write(fdw, "Hello", 6));
        close(fdw);
    }
    
    int main()
    {
        int i;
        write_func();
        return 0;
    }
    

    接收代码

    void read_thread()
    {
    
        int fdr;
        char buf[] = "NoData";
    
        fdr = open("/dev/ttyUSB9", O_RDWR);
        printf("fdr : %d\n",fdr);
    
        printf("%s: %ld\n", __func__, read(fdr, buf, 6));
    
        printf("%s\n", buf);
        close(fdr);
    }
    
    int main()
    {
        int i;
        read_thread();
        return 0;
    }
    

    我不通过上述调用接收数据,但是当我在write调用中添加'\n时,我在read块调用中获得数据。

     printf("%ld\n", write(fdw, "Hello\n", 7));
    

    新线字在这方面有什么意义。。

    更新:

    我添加了重置规范模式的代码,但仍然不起作用:

    void write_thread()
    {
    
        int fdw;
        int i;
        struct termios config;
        fdw = open("/dev/ttymib24", O_RDWR);
        printf("fdw : %d\n",fdw);
        tcgetattr(fdw, &config);
        config.c_lflag &= ~ICANON;
        tcsetattr(fdw, TCSANOW, &config);    
        printf("%ld\n", write(fdw, "Hello", 6));
        close(fdw);
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   SKi    6 年前

    你的tty可能处于规范模式。

    尝试使用重置 tcsetattr() . 像这样:

    struct termios termiosv;
    tcgetattr(fd, &termiosv);
    termiosv.c_lflag &= ~ICANON;
    tcsetattr(fd, TCSANOW, &termiosv);
    

    更多信息请参见的手册页 termios :

       In canonical mode:
    
       * Input is made available line by line.  An input line is available
         when one of the line delimiters is typed (NL, EOL, EOL2; or EOF at
         the start of line).  Except in the case of EOF, the line delimiter
         is included in the buffer returned by read(2).
    
    推荐文章