【发布时间】:2014-06-20 09:08:33
【问题描述】:
我正在编写一个简单的 C 程序,它可以从连接到我的 Arduino 设备的 USB 端口读取数据。 Arduino 以 9600 的波特率以 4 字节为单位输出数据。
我希望从 Arduino 到我的计算机的输入看起来像这样:
136.134.132.130.129.127.126.124.121.119.117.115.113.111.
但是,我得到的是这样的:
271.274.281..2.4062.4022.40225.4021
问题:如何让我的 C 程序中的输入整齐地同步而不会丢失数据/重新读取数据?当端口有新数据时,是否有某种标志可以告诉我的程序?
代码:
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <sys/types.h>
int open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/tty.usbmodemfd121", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/tty");
}
else
fcntl(fd, F_SETFL, 0);
struct termios options;
tcgetattr(fd,&options);
cfsetospeed(&options,B9600);
options.c_cflag |=(CLOCAL | CREAD);
tcsetattr(fd, TCSANOW, &options);
return (fd);
}
int main (){
int i;
for(i=0; i<50; i++){
fcntl(open_port(), F_SETFL, FNDELAY);
char buf[5];
size_t nbytes;
ssize_t bytes_read;
nbytes = sizeof(buf);
bytes_read = read(open_port(), buf, nbytes);
printf("%s ", buf);
buf[0]=0;
}
return 0;
}
【问题讨论】:
标签: c serial-port arduino