[英]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.