我尝试使用 WIN32 API 在 C++ 中写入串行端口,WriteFile 不返回 ERROR_IO_PENDING 但没有任何反应,但是在我使用另一个程序(在 C# 中)写入端口后,c++ 程序可以工作,直到我重新启动 Windows 7,在这里是写代码:
static DCB dcb = {0};
static HANDLE hComm;
static int _tmain(int argc, _TCHAR* argv[])
{
hComm = CreateFile(
L"\\\\.\\COM3",
GENERIC_WRITE | GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
NULL,
NULL
);
if (hComm == INVALID_HANDLE_VALUE) // error opening port; abort
printf_s("INVALID_HANDLE_VALUE\n");
if (GetCommState(hComm, &dcb))// DCB is ready for use.
{
dcb.BaudRate = CBR_19200; //19200 Baud
dcb.ByteSize = 8; //8 data bits
dcb.Parity = NOPARITY; //no parity
dcb.StopBits = ONESTOPBIT; //1 stop
printf_s("set UP DCB\n");
}
else // Error getting current DCB settings
printf_s("ERROR getting \n"+GetLastError());
osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
WriteABuffer("!serialCMDtoSend\r",sizeof("!serialCMDtoSend\r");
}
static BOOL WriteABuffer(char * lpBuf, DWORD dwToWrite)
{
// Issue write.
if (!WriteFile(hComm, lpBuf, dwToWrite, &dwWritten, &osWrite))
{
if (GetLastError() != ERROR_IO_PENDING) { // WriteFile failed, but it isn't delayed. Report error and abort.
fRes = FALSE;
}
else {
// Write is pending.
if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE))
fRes = FALSE;
else
fRes = TRUE;// Write operation completed successfully.
}
}
else
fRes = TRUE; // WriteFile completed immediately.
return fRes;
}
任何人都可以看到我的错误吗?