[英]Reading Serial Port Data
我試圖在Mac OS上的C中讀取串行端口數據。 串行端口的配置在單獨的Arduino IDE中完成。
我能夠讀取部分數據,但隨后打印的數據會重復自身並開始讀取零,如下所示。 如果刪除O_NONBLOCK,該程序將掛起。 我該怎么做才能解決此問題? 其次,假設我正在for循環中讀取數據,如何確定讀取速率與波特率相對應?
看到的數據:296310 0
320295311
320295311
9296311
320295311
320295311
9296311
...
0 0 0
0 0 0
0 0 0等
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int buffer[300];
int main(int argc, const char* argv[])
{
// open serial port
int port;
port = open("/dev/tty.usbmodem1411", O_RDONLY | O_NONBLOCK);
if (port == -1)
{
printf("Unable to open serial port.\n");
return 1;
}
// instantiate file
FILE* file = fdopen(port, "r");
if (file == NULL)
{
printf("Unable to instantiate file.\n");
close(port);
return 2;
}
for (int j = 0; j < 200; j++)
{
fscanf(file, "%d %d %d", &buffer[3*i], &buffer[3*i+1], &buffer[3*i+2]);
printf("%d %d %d\n", buffer[3*i], buffer[3*i+1], buffer[3*i+2]);
i = (i + 1) % 100;
usleep(10000);
}
fclose(file);
close(port);
return 0;
}
對於克里斯·斯特拉頓:
if (fgets(temp, sizeof(temp), file) != NULL)
{
sscanf(temp, "%d %d %d\n", &buffer[3*i], &buffer[3*i+1], &buffer[3*i+2]);
printf("%d %d %d\n", buffer[3*i], buffer[3*i+1], buffer[3*i+2]);
}
但是,回到我原來的問題,即使我使用fscanf和printf,我也會獲取數據,然后我只會無限期地讀取零。 我認為這可能更多是串行端口通信問題?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.