【发布时间】:2020-07-06 20:19:33
【问题描述】:
我正在编写一个 c 库来帮助读取 linux 上的 arduino 控制器。我的 arduino 代码每 1/3 秒将其每个输入(一个操纵杆和两个按钮)的值以逗号分隔一次写入 /dev/ttyACM0。我的 C 代码应该打印出倒数第二行,也就是最后完成的行,但它只是打印出一个空行。这是我的代码:
char* getLastFullLine() {
FILE* fd = fopen("/dev/ttyACM0", "r");
/* max length including newline */
static const long max_len = 55 + 1;
/* space for all of that plus a nul terminator */
char buf[max_len + 1];
/* now read that many bytes from the end of the file */
fseek(fd, -max_len, SEEK_END);
fread(buf, max_len, 1, fd);
/* don't forget the nul terminator */
buf[max_len - 1] = '\0';
char *last_newline;
/* and find the last newline character (there must be one, right?) */
last_newline = strrchr(buf, '\n');
return last_newline;
}
int main() {
printf("%s \n", getLastFullLine());
}
【问题讨论】:
-
文件名
/dev/ttyACM0代表一个串行终端设备,而不是一个“串行文件”。它不是一个流,应该使用 open() 和 read() 系统调用访问(并正确配置)。 “我的 C 代码应该打印出倒数第二行” -- 试图将程序执行与数据接收同步是愚蠢的。现代 Linux 不会为未打开的串行终端缓冲数据。 IOW 当您打开/打开串行终端 在 数据已接收(并丢弃)之后,您的程序没有要读取的数据(直到接收到新数据)。
标签: c linux arduino serial-port