c - 串口通讯中换行符的意义
问题描述
我们正在测试串口通信。设备上有两个 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 时,我在读取块调用中获取数据。
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()
. 像这样的东西:
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).
推荐阅读
- django - 用 django 为餐厅菜单建模
- android - 我开发的 APK 以前可以正常工作,但突然停止工作并出现“未安装应用程序”错误
- android - Ionic 4-cordova-admob-pro 上传后不会显示广告
- html - 在 html 网站上添加了不需要的具有大高度值的 full_body_spacer
- python - 在 Python 中从 csv 文件生成字符串集
- r - 如何在 DT 标头中显示 HTML?
- c# - MultiSelectList 显示给定给它的 IEnumerable 中的一个值和多个值
- angularjs - AngularJS日期输入未在Firefox中的指令内显示初始值
- vue.js - 如何处理来自数据库的路由权限?
- haskell - Haskell 错误:变量不在范围内:myEven