我有下面的程序試圖用串口讀取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