我正在为标准 PC 串行端口开发“高级”C++ 接口。当我打开端口时,我想清除输入和输出缓冲区,以便不接收或发送以前使用该端口的数据。为此,我使用 tcflush 函数。然而,它不起作用。怎么可能?我的“端口开放”代码如下所示。是的,我使用 C++ 异常,但没有抛出任何异常。这表明 tcflush 返回 0 但它不会清除缓冲区。
我清除输入缓冲区的唯一方法是从中读取字节,直到没有剩余字节为止。这通常需要几秒钟,我不认为这是一个解决方案。
提前致谢 :-)
fd = ::open(port.c_str(), O_RDWR | O_NOCTTY);
if (fd < 0)
{
throw OpenPortException(port);
return;
}
// Get options
tcgetattr(fd, &options);
// Set default baud rate 9600, 1 stop bit, 8 bit data length, no parity
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
// Default timeout (1000 ms)
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
// Additional options
options.c_cflag |= (CLOCAL | CREAD);
this->port = port;
// Apply the settings now
if (tcsetattr(fd, TCSANOW, &options) != 0)
{
throw PortSettingsException();
}
// Flush the port
if (tcflush(fd, TCIOFLUSH) != 0)
{
throw IOException();
}
这是正确的方法(如下):
usleep(1000);
ioctl(fd, TCFLSH, 0); // flush receive
ioctl(fd, TCFLSH, 1); // flush transmit
ioctl(fd, TCFLSH, 2); // flush both
用户可以根据需要选择前两行或单独选择最后一行。请检查是否需要睡眠。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)