【发布时间】:2016-12-22 18:43:15
【问题描述】:
我有以下程序尝试使用串行端口从 arduino 读取数据,问题是它几乎不读取任何内容,除了有时它会读取我发送的一部分内容。 arduino 代码只是在循环中写一个字母。
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int main() {
int serialfd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if (serialfd == -1)
perror("Error opening the serial port");
else
fcntl(serialfd, F_SETFL, 0);
fprintf(stdout, "Device is open, attempting read \n");
fcntl(serialfd, F_SETFL, 0);
char buf[11] = {0};
read(serialfd, buf, 10);
fprintf(stdout, "Buffer: %s", buf);
close(serialfd);
return 0;
}
例如输出是这样的
Device is open, attempting read
Buffer: AAAAAAAAAAA⏎
如果我尝试再次运行它(多次),我只会得到 0'd 缓冲区
Device is open, attempting read
Buffer: ⏎
【问题讨论】:
-
您没有说您重复发送的哪个单个字符。假设您确实具有匹配的波特率(未提及)并且您正在发送
'A'然后在接收到其中的 11 个之后,输入缓冲区已满并且没有'\0'的零终止,因此您正在传递一个 not_string到fprintf,因此不可避免地会输出一些废话。但是请read thisF_SETFL。 -
@WeatherVane 我正在从 arduino 写“A”,我不知道如何使用文件描述符设置波特率。
-
@WeatherVane F_SETFL 也是从串行编程指南中获取的,我希望阻止调用。就是它?还是我错过了什么-
标签: c serial-port