我有下面的程序试图用串口读取arduino中的数据,事情大部分是不读取任何东西,除了有时它读取我发送的一块。 arduino代码只是在循环中写一个字母。从串口读取arduino C
#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',因此不可避免地会输出一些废话。但请[阅读此](http://stackoverflow.com/questions/34943745/why-fcntlfd-f-setfl-0-use-in-serial-port-programming)关于'F_SETFL'。 –
@WeatherVane我在写arduino的'A',我不知道如何用文件描述符设置波特率。 – Aram
打开串行终端设备后,您必须先配置终端属性,然后才能读取或写入。研究[设置终端模式来适当地(http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_12.html#SEC237) 和[串行编程指南POSIX操作系统(HTTP: //www.cmrr.umn.edu/~strupp/serial.html)有关示例代码,请参阅http://stackoverflow.com/questions/6947413/how-to-open-read-and-write-from-serial-port -in-C/38318768#38318768和http://stackoverflow.com/questions/12437593/how-to-read-a-binary-data-over-serial-terminal-in-c-program/12457195#12457195 – sawdust