【发布时间】:2014-02-25 15:11:05
【问题描述】:
我正在为标准 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();
}
【问题讨论】:
-
您正在做什么测试以查看它是否正常工作?
-
我希望看到
cfsetispeed(&options, B9600); cfsetospeed(&options, B9600);,如果代码按照注释暗示'// 设置默认波特率 9600..." -
我在另一个函数中使用上述命令设置了速度。我已经使用将字符发送到串行端口的微控制器进行了测试。如果我在退出程序后停止传输,输入缓冲区将在下一次运行时包含字符。这就是我要清除缓冲区的原因。
标签: c++ c unix serial-port