清除串口缓冲区

这是我的function看起来像打开串口(使用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缓冲区来解决这个问题,但没有这样的运气。 任何见解?

我想我明白了。 出于某种原因,我需要在冲洗之前添加一个延迟。 在返回fd之前添加的这两行似乎已经做到了:

  sleep(2); //required to make flush work, for some reason tcflush(fd,TCIOFLUSH); 

这个问题的原因在于使用USB串行端口。 如果你使用普通的串口,你不会有这个问题。

大多数USB串口驱动程序不支持正常刷新,可能是因为无法知道内部移位寄存器,FIFO或USB子系统中是否还有数据。

另请参阅格雷格(Greg)对前面报告的类似问题的回复。

你的sleep可以治愈这个问题,但这只是一个解决方法。 不幸的是除了使用普通的串口之外,没有其他解决方案。

Arduino Uno板在open()上复位时,我遇到了类似的症状。 在open()调用之后,我是在Arduino板被重置之前生成的,因此在调用open()之前收到数据。

使用ioctl()调用来追踪问题我了解到,在调用tcflush()的时候,数据还没有到达输入缓冲区。 所以tcflush()确实工作,但没有数据刷新。 在open()调用之后,我们睡了1000个人似乎解决了这个问题。 这是因为延迟允许数据在调用tcflush()之前到达,因此tcflush()确实会刷新输入缓冲区。

您可能遇到同样的问题。

我有一个类似的问题。 我正在通过Raspberry Pi 3等待串行数据,并且在USB串口上有垃圾,但在UART串口(gpio pins)上没有。