我想在 115200,n,8,1 从 COM1 读取(最好是阻塞调用,但我可以添加它。而且我不需要线程)。
我能找到的唯一代码是这个问题的 Stack Overflow 上(微软也有一些有用的信息)。
作者说他的代码有效,我不怀疑他,但是当我运行代码时,即使端口正确打开,我也没有收到任何字符(如果我用终端程序检查,数据正在发送) .
有人可以发布一些示例 C 代码的 URL 吗?谢谢。
FWIW,这是我的代码:
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
E_boolean OpenCom1(void)
{
COMMTIMEOUTS timeouts;
comPorthandle = CreateFile("COM1", // Specify port device: default "COM1"
GENERIC_READ | GENERIC_WRITE, // Specify mode that open device.
0, // the device isn't shared.
NULL, // the object gets a default security.
OPEN_EXISTING, // Specify which action to take on file.
0, // default (not overlapped i/o).
NULL); // default (hTemplate must be NULL for COM devices).
if (comPorthandle == INVALID_HANDLE_VALUE)
return False;
deviceControlBlock.DCBlength = sizeof(deviceControlBlock);
if((GetCommState(comPorthandle, &deviceControlBlock) == 0))
{
// CodeMe: do what?
return False;
}
deviceControlBlock.BaudRate = CBR_115200;
deviceControlBlock.StopBits = ONESTOPBIT;
deviceControlBlock.Parity = NOPARITY;
deviceControlBlock.ByteSize = DATABITS_8;
deviceControlBlock.fRtsControl = 0;
if (!SetCommState(comPorthandle, &deviceControlBlock))
{
// CodeMe: do what?
return False;
}
#if 0
// alternative to GetCommState() and SetCommState()
// both versions succeed
if (!BuildCommDCB("115200,n,8,1", &deviceControlBlock))
{
// CodeMe: do what?
return False;
}
#endif
// set short timeouts on the comm port.
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 1;
timeouts.ReadTotalTimeoutConstant = 1;
timeouts.WriteTotalTimeoutMultiplier = 1;
timeouts.WriteTotalTimeoutConstant = 1;
if (!SetCommTimeouts(comPorthandle, &timeouts))
{
// CodeMe: do what?
return False;
}
return True;
}//OpenCom1()
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
void ReadCharacterFromCom1(INPUT char *theCharacter)
{
DWORD numBytesRead;
numBytesRead = 0;
while (numBytesRead == 0)
{
ReadFile(comPorthandle, // handle of file to read
theCharacter, // store read data here
sizeof(theCharacter), // number of bytes to read
&numBytesRead, // pointer to number of bytes actually read
NULL);
}
return;
}//ReadCharacterFromCom1()