我ReadFile()
在 Windows 上使用从串行端口读取数据。这段代码在某个时间点运行良好,但现在失败了,我正在尝试追查问题的根源,所以我怀疑这是串行配置或超时的问题,因为这些都没有改变。
ReadFile()
返回 false,表示发生了错误。但是,当我立即检查 的值时GetLastError()
,它返回 0,即ERROR_SUCCESS
。读取的字节数为 0,所以我倾向于认为确实出了点问题,但错误代码完全没用。
有任何想法吗?谢谢。
编辑:以下是一些相关的代码片段:
#define GPS_COM_PORT L"COM3"
// for reference, the device communicates at 115200 baud,
// no parity, 1 stop bit, no flow control
// open gps com port
hGpsUart = CreateFile(GPS_COM_PORT, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hGpsUart == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
msg.setText("GPS COM port does not exist!");
msg.exec();
QApplication::quit();
}
msg.setText("Error occurred while trying to open GPS COM port!");
msg.exec();
QApplication::quit();
}
// set gps com port settings
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(hGpsUart, &dcbSerialParams))
{
msg.setText("Could not get GPS COM port settings!");
msg.exec();
QApplication::quit();
}
dcbSerialParams.BaudRate = CBR_115200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if (!SetCommState(hGpsUart, &dcbSerialParams))
{
msg.setText("Could not set GPS COM port settings!");
msg.exec();
QApplication::quit();
}
// set gps com port timeouts
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(hGpsUart, &timeouts))
{
msg.setText("Could not set GPS COM port timeouts!");
msg.exec();
QApplication::quit();
}
// ... later in the code ...
char buf[161] = {0};
DWORD bytes_read = 0;
// This returns false...
if (!ReadFile(hGpsUart, buf, 160, &bytes_read, NULL))
{
// Yet in here, GetLastError() returns ERROR_SUCCESS (0)
QMessageBox msg;
msg.setText("Error reading from GPS UART!");
msg.exec();
}