我正在努力通过串口COM端口与设备通信。
起初,我设法通过一个非常简单的非重叠设置来读取和写入端口。但现在我意识到我在WRITE和READ函数之间有一个约100ms的延迟。
问题:我需要在大约15ms后检查答案才能立即回复。
我不知道如何实现这一点,所以我尝试设置重叠的通信并遇到了这个Microsoft文档:Serial Communications
现在我甚至无法让READ部分工作。
这是我现在的代码
int main() {
LPCWSTR port = L"COM3:";
HANDLE hComm = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if (hComm == INVALID_HANDLE_VALUE) cout << "ERROR " << GetLastError() << endl;
else {
DWORD dwRead;
DWORD dwRes;
BOOL fWaitingOnRead = FALSE;
OVERLAPPED osReader = { 0 };
//Create overlapped event
osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osReader.hEvent == NULL) cout << "ERROR " << GetLastError() << endl;
else {
BYTE Byte[2];
while (true) {
if (!fWaitingOnRead) {
//Issue read operation
if (!ReadFile(hComm, &Byte, sizeof(Byte), &dwRead, &osReader)); cout << "ERROR " << GetLastError() << endl;
else {
cout << std::hex << (int)Byte[0] << " " << std::hex << (int)Byte[1] << endl;
fWaitingOnRead = TRUE;
}
}
else {
dwRes = WaitForSingleObject(osReader.hEvent, 500);
switch (dwRes) {
// Read completed.
case WAIT_OBJECT_0:
if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) cout << "ERROR " << GetLastError() << endl;
else {
cout << std::hex << (int)Byte[0] << " " << std::hex << (int)Byte[1] << endl;
}
// Reset flag so that another opertion can be issued.
fWaitingOnRead = FALSE;
break;
default:
break;
}
}
Sleep(100);
}
}
}
return 0;
}
此代码应将READ函数的结果输出到控制台。但它每次都失败,GetLastError()给我 997
我希望有人可以指出我的错误,或者给我一个提示如何解决这个重叠的结构,我还不太清楚。