这是我打开串口的功能(使用 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);
}
问题是,当我运行这个程序并且我的串行设备已经插入时,缓冲区中有内容。在开始读取缓冲区之前,我需要一种清除缓冲区的方法。我认为 usingtcsetattr(fd, TCSAFLUSH, &options);
可以通过在初始化端口之前刷新 IO 缓冲区来解决这个问题,但没有这样的运气。有什么见解吗?