簡體   English   中英

從C語言的串口讀取arduino

[英]Read arduino from serial in C

我有以下程序嘗試使用串行端口從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: ⏎                

聽起來像是配置問題,很可能波特率設置不正確。 同樣,如問題注釋中所述,您可能會得到一個完整的緩沖區,結尾沒有'\\0'字符,因此fprintf不能正常運行。

在這里,我將解釋如何設置波特率,但是您可以使用我將答案放在更下方的Wikibooks鏈接來設置其他設置,還請確保檢查緩沖區。

簡單地說,我喜歡使用arduino 115200作為波特率。 其他設備通常支持更多功能,但是這個值很好用,因此在我的示例中將使用它。

在arduino上,這很可能是您必須配置的唯一內容(並且,實際上,這是我要使用串行端口與計算機進行通訊時設置的唯一內容)。

Serial.begin(115200);

然后根據該Wikibook,您可以通過termios結構中的設置來設置波特率,就像在Wikibook示例中將其稱為attribs

struct termios attribs;

/* get the current settings */
tcgetattr(serialfd, &attribs);

/* set the baudrate */
cfsetospeed(&attribs, B115200); /* outut baudrate */
cfsetispeed(&attribs, B115200); /* input baudrate */

/* if there is need for it, set other settings here */

/* eventually apply everything for your serialfd descriptor */
tcsetattr(serialfd, TCSANOW, &attribs);

因此,從技術上講,是的,您輸入的速度可能不同於輸出的速度,但是arduino的UART僅具有一種這樣的設置, 並且不支持輸入/輸出的不同速度 ,因此您需要在計算機上將兩者設置為相同的值。

如果您只需要在PC端接收二進制數據,並且可能會對某些特定值做出反應,然后將某些內容發送回Arduino並記錄數據,例如,

那么您可以使用一些更高級的RS232終端程序,例如http://docklight.de/

它確實具有更多的選項和腳本來基本上進行螞蟻數據處理,但是我還沒有在其上使用腳本。

但是幾分鍾后,您就可以讀取和回答ASCII或二進制格式的數據了。

當然,對於某些數據庫連接或更多而言,您將需要自定義程序,但是在調試階段進行測試操作,docklight是一個很好的工具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM