无法从串行端口读取.WaitCommEvent() 永远不会返回

Unable to read from serial port. WaitCommEvent() never returns

本文关键字:永远 返回 WaitCommEvent 串行端口 读取      更新时间:2023-10-16

我必须使用 win32 api 从串行端口读取字节,但尚未连接任何设备 到端口进行测试,所以我在端口中写入一个字节并尝试读取,但WaitCommEvent()永远不会 返回和程序保持等待状态。当我检查是否完成写作时,我看到已经完成,但问题出在WaitCommEvent()上。

HANDLE hPort;
TCHAR *pcCommPort = TEXT("COM1");
hPort = CreateFile( pcCommPort,GENERIC_READ | GENERIC_WRITE, 0,NULL,OPEN_EXISTING,0,NULL);        
if (hPort == INVALID_HANDLE_VALUE)
MessageBox( hwnd , L"Error in opening serial port" , L"error" , MB_OK );
else
MessageBox( hwnd , L"Port opened" , L"successful" , MB_OK ); //This is displayed

//Configuration
DCB conf={0};
conf.DCBlength = sizeof(conf);
if(GetCommState(hPort, &conf))
{
conf.ByteSize = 8;
conf.Parity = NOPARITY;
conf.StopBits = ONESTOPBIT;
conf.fBinary = TRUE;
conf.fParity = TRUE;
}
else
MessageBox( hwnd , L"Cannot get comm state" , L"Oops" , MB_OK );
if(!SetCommState(hPort, &conf))
{
MessageBox( hwnd , L"cannot set comm state" , L"Oops" , MB_OK );
}

//Timeout
COMMTIMEOUTS commTimeout;
if(GetCommTimeouts(hPort, &commTimeout))
{
COMMTIMEOUTS timeouts = { 0 };
timeouts.ReadIntervalTimeout         = 50; 
timeouts.ReadTotalTimeoutConstant    = 50; 
timeouts.ReadTotalTimeoutMultiplier  = 10; 
}
else
MessageBox( hwnd , L"cannot get timeout" , L"Oops" , MB_OK );
if(!SetCommTimeouts(hPort, &commTimeout))
MessageBox( hwnd , L"cannot set timeout" , L"Oops" , MB_OK );

//Writing
char lpBuffer[] = "a";
DWORD dNoOFBytestoWrite;       
DWORD dNoOfBytesWritten = 0;     
dNoOFBytestoWrite = sizeof(lpBuffer);
WriteFile(hPort,lpBuffer,dNoOFBytestoWrite,&dNoOfBytesWritten,NULL);
if(dNoOfBytesWritten == 1){
MessageBox(NULL , L"Writing happened" , L"Attention" , MB_OK); //This is displayed
}

//Reading
DWORD dwEventMask; 
SetCommMask(hPort, EV_RXCHAR);
WaitCommEvent(hPort, &dwEventMask, NULL); 
char TempChar; 
DWORD NoBytesRead;

ReadFile( hPort,&TempChar,sizeof(TempChar),&NoBytesRead, NULL);
CloseHandle(hPort);//Closing the Serial Port

怎么了?为什么我看不懂?

谢谢

我 [...] 没有将任何设备连接到端口

串行端口"读取"来自连接设备的字节。 您没有连接的设备。 因此,不会有角色来。

仅当存在环回连接(使计算机成为自己的连接设备(时,您才能读回您自己编写的字节。 某些串行端口将支持软件配置的环回,但 C# 不提供任何方法来控制此1。 否则,您将需要一个硬件环回连接(如果禁用硬件握手,可以像单线一样简单(

最后一个选项是虚拟串行端口驱动程序,它连接到另一个应用程序,根本不涉及任何硬件。


1Win32 API 可以启用和禁用内部环回,但不幸的是,它仍然不是标准的,也不是普遍支持的。 请参阅IOCTL_SERIAL_SET_MODEM_CONTROL