c - 串口通讯中换行字符的意义

标签 c linux serial-port rs485

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

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

传输代码

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

我没有通过上述调用接收数据,但是当我在写入调用中添加 '\n 时,我在读取 block 调用中获得了数据。

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

最佳答案

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

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

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).

关于c - 串口通讯中换行字符的意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53220735/

相关文章:

linux - 使 MahApp 需要 : No rule to make target 'part2.d' ,

c# - 如何与USB 3G调制解调器通信?

c - 如何删除 char 数组转换为无符号 char 数组的警告

c - 将大型 (~4MB) 文件上传到 boa 网络服务器时出现不可预测的行为

linux - 使用 CSS 使 Gnome 顶部栏字体粗细加粗?

c++ - 使用 GetOverlappedResult 丢失数据?

c - linux设置串口中断

c - 如何在 linux 内核中实现 clone(2) 系统调用的另一种变体?

C、写系统调用,写int

c++ - OpenCV - 从图像网格中拼接图像