这是我用Ubuntu 12.04打开串口的函数代码:
int open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
// Could not open the port.
perror("open_port: Unable to open /dev/ttyUSB0 - ");
}
else
fcntl(fd, F_SETFL, 0);
struct termios options;
tcgetattr(fd, &options);
//setting baud rates and stuff
cfsetispeed(&options, B19200);
cfsetospeed(&options, B19200);
options.c_cflag |= (CLOCAL | CREAD);
tcsetattr(fd, TCSANOW, &options);
tcsetattr(fd, TCSAFLUSH, &options);
options.c_cflag &= ~PARENB;//next 4 lines setting 8N1
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
//options.c_cflag &= ~CNEW_RTSCTS;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //raw input
options.c_iflag &= ~(IXON | IXOFF | IXANY); //disable software flow control
return (fd);
}
我的问题是,当我运行这个程序时,如果我的串行设备已经插入,则缓冲区中会有内容。我需要一种在开始读取之前清除缓冲区的方法。我认为使用 tcsetattr(fd, TCSAFLUSH, &options);
可以解决这个问题,通过初始化端口之前刷新IO缓冲区,但没有这样的运气。有什么见解吗?
usleep(10000);
。两秒钟太长了,但是@areslagae建议的1000us太短了。在我的情况下,10毫秒刚刚好。 - Dmitry