【问题标题】:Unix: How to clear the serial port I/O buffer?Unix:如何清除串口 I/O 缓冲区?
【发布时间】: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(&amp;options, B9600); cfsetospeed(&amp;options, B9600);,如果代码按照注释暗示'// 设置默认波特率 9600..."
  • 我在另一个函数中使用上述命令设置了速度。我已经使用将字符发送到串行端口的微控制器进行了测试。如果我在退出程序后停止传输,输入缓冲区将在下一次运行时包含字符。这就是我要清除缓冲区的原因。

标签: c++ c unix serial-port


【解决方案1】:

这是正确的方法(如下):

usleep(1000);
ioctl(fd, TCFLSH, 0); // flush receive
ioctl(fd, TCFLSH, 1); // flush transmit
ioctl(fd, TCFLSH, 2); // flush both

用户可以根据需要选择前两行或最后一行。请检查是否需要睡眠。

【讨论】:

    【解决方案2】:

    试试

    ioctl(fd, TCFLUSH, 目录)

    dir 等于 0 表示接收,1 表示发送,2 表示两者。

    【讨论】:

    • 本次通话前后是否需要睡眠。似乎对我不起作用(或者很难确定它是否有效)。使用 Linux x86,64 位。
    • 您的回答不完整。在帖子中更正您的答案@user3485419。它的 TCFLSH 不是 TCFLUSH
    猜你喜欢
    • 2012-01-14
    • 2012-10-12
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 2016-06-04
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多