C++:如果没有来自串口的新数据,如何忽略 ReadFile()?
C++: How to ignore ReadFile() if there is no new data from the serial port?
我正在开发一个可以从串行端口读取和写入串行端口的 C++ 程序。我在读取数据时遇到问题。如果没有新数据,ReadFile()
等待接收新数据。
我读取数据的代码:
while (!_kbhit())
{
if (!_kbhit())
{
if (ReadFile(hSerial, &c, 1, &dwBytesRead, NULL))
{
cout << c;
}
}
}
如何检查是否没有新数据并跳过ReadFile()
行?
编辑:
我终于能够修复它。
我将我的 ReadFunction 更改为:
do
{
if (ReadFile(hSerial, &c, 1, &dwBytesRead, NULL))
{
if (isascii(c))
{
cout << c;
}
}
if (_kbhit())
{
key = _getch();
}
} while (key != 27);
我添加了这样的超时:
serialHandle = CreateFile(LcomPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 1;
timeouts.ReadTotalTimeoutMultiplier = 1;
timeouts.ReadTotalTimeoutConstant = 1;
timeouts.WriteTotalTimeoutMultiplier = 1;
timeouts.WriteTotalTimeoutConstant = 1;
SetCommTimeouts(serialHandle, &timeouts);
// Call function to Read
...
尝试 ReadFileEx 而不是
是异步函数
If there is no new data, ReadFile()
is waiting until it receive new data.
您可以使用SetCommTimeouts()
配置读取超时,如果在超时间隔内没有数据到达,ReadFile()
将退出。
我正在开发一个可以从串行端口读取和写入串行端口的 C++ 程序。我在读取数据时遇到问题。如果没有新数据,ReadFile()
等待接收新数据。
我读取数据的代码:
while (!_kbhit())
{
if (!_kbhit())
{
if (ReadFile(hSerial, &c, 1, &dwBytesRead, NULL))
{
cout << c;
}
}
}
如何检查是否没有新数据并跳过ReadFile()
行?
编辑:
我终于能够修复它。 我将我的 ReadFunction 更改为:
do
{
if (ReadFile(hSerial, &c, 1, &dwBytesRead, NULL))
{
if (isascii(c))
{
cout << c;
}
}
if (_kbhit())
{
key = _getch();
}
} while (key != 27);
我添加了这样的超时:
serialHandle = CreateFile(LcomPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 1;
timeouts.ReadTotalTimeoutMultiplier = 1;
timeouts.ReadTotalTimeoutConstant = 1;
timeouts.WriteTotalTimeoutMultiplier = 1;
timeouts.WriteTotalTimeoutConstant = 1;
SetCommTimeouts(serialHandle, &timeouts);
// Call function to Read
...
尝试 ReadFileEx 而不是
是异步函数
If there is no new data,
ReadFile()
is waiting until it receive new data.
您可以使用SetCommTimeouts()
配置读取超时,如果在超时间隔内没有数据到达,ReadFile()
将退出。