Unix:如何清除串口 I/O 缓冲区? [英] Unix: How to clear the serial port I/O buffer?

查看:17
本文介绍了Unix:如何清除串口 I/O 缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为标准 PC 串行端口开发高级"C++ 接口.当我打开端口时,我想清除输入和输出缓冲区,以免接收或发送以前使用端口的数据.为此,我使用了 tcflush 函数.但是,它不起作用.怎么可能?我的端口开放"代码如下所示.是的,我使用 C++ 异常,但没有抛出异常.这表示 tcflush 返回 0 但不清除缓冲区.

I am working on a "high level" C++ interface for the standard PC serial port. When I open the port, I would like to clear the input and output buffers in order not to receive or send data from previous usage of the port. To do that, I use the tcflush function. However, it does not work. How can that be? My "port opening" code can be seen below. Yes I use C++ exceptions but none are getting thrown. That indicates that tcflush returns 0 but it does not clear the buffer.

我可以清除输入缓冲区的唯一方法是从中读取字节,直到没有剩余为止.这通常需要几秒钟,我不认为这是一个解决方案.

The only way I can clear the input buffer is to read bytes from it until there is none left. This usually takes a couple of seconds and I do not think of it as a solution.

提前致谢:-)

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();
}

推荐答案

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

This is the correct way (as below):

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

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

User can choose both of the first 2 lines OR last line alone based on requirement. Please check if sleep may be required.

这篇关于Unix:如何清除串口 I/O 缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆