设置DCB尝试配置COM端口时会失败
-
10-10-2019 - |
题
我正在尝试编写使用串行端口(例如COM8)的C ++ MFC应用程序。每当我尝试设置DCB时,都会失败。如果有人可以指出我做错了什么,我将非常感谢。
DCB dcb = {0};
dcb.DCBlength = sizeof(DCB);
port.Insert( 0, L"\\\\.\\" );
m_hComm = CreateFile(
port, // Virtual COM port
GENERIC_READ | GENERIC_WRITE, // Access: Read and write
0, // Share: No sharing
NULL, // Security: None
OPEN_EXISTING, // The COM port already exists.
FILE_FLAG_OVERLAPPED, // Asynchronous I/O.
NULL // No template file for COM port.
);
if ( m_hComm == INVALID_HANDLE_VALUE )
{
TRACE(_T("Unable to open COM port."));
ThrowException();
}
if ( !::GetCommState( m_hComm, &dcb ) )
{
TRACE(_T("CSerialPort : Failed to get the comm state - Error: %d"), GetLastError());
ThrowException();
}
dcb.BaudRate = 38400; // Setup the baud rate.
dcb.Parity = NOPARITY; // Setup the parity.
dcb.ByteSize = 8; // Setup the data bits.
dcb.StopBits = 1; // Setup the stop bits.
if ( !::SetCommState( m_hComm, &dcb ) ) // <- Fails here.
{
TRACE(_T("CSerialPort : Failed to set the comm state - Error: %d"), GetLastError());
ThrowException();
}
谢谢。
附加信息: 生成的错误代码为87:“参数不正确。”可能是微软的 最多 有用的错误代码。 j/k
解决方案 3
我能够使用 BuildCommDCB
:
DCB dcb = {0};
if ( !::BuildCommDCB( _T("baud=38400 parity=N data=8 stop=1"), &dcb ) )
{
TRACE(_T("CSerialPort : Failed to build the DCB structure - Error: %d"), GetLastError());
ThrowException();
}
其他提示
我的钱就是这样:
dcb.StopBits = 1;
MSDN文档 关于停工的说法:
要使用的停止位数。该成员可以是以下值之一。
ONESTOPBIT 0 1 stop bit. ONE5STOPBITS 1 1.5 stop bits. TWOSTOPBITS 2 2 stop bits.
因此,您要要求1.5停止钻头,这是一件非常古老的事情,我什至不记得它来自哪里。电信器可能。
我猜想支持此模式的驱动程序/硬件的机会很小,因此错误。
因此,将其更改为 dcb.StopBits = ONESTOPBIT;
这是没有特定顺序的一些可能性。
GetCommState
由于端口尚未初始化,因此正在用垃圾填充结构。您可能会跳过此步骤。- 有两个参数可以控制奇偶校验设置,目前尚不清楚是否有任何无效组合。
- 停止物的值不是位数,而是一个神奇的数字常数。值1等于
ONE5STOPBITS
与其他参数结合使用时可能无效。
这是我的代码,它的运行良好。
/* Try to open the port */
hCom = CreateFile(szPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if (hCom != INVALID_HANDLE_VALUE) {
printf("Handle success\n");
}
dcb = { 0 };
dcb.DCBlength = sizeof(dcb);
fSuccess = GetCommState(hCom, &dcb);
if (!fSuccess) {
// Handle the error.
printf("GetCommState failed with error %d.\n", GetLastError());
CloseHandle(hCom);
return APP_ERROR;
}
// Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit.
dcb = { 0 };
dcb.DCBlength = sizeof(dcb);
dcb.BaudRate = CBR_115200; // Set the baud rate
dcb.ByteSize = 8; // Data size, xmit, and rcv
dcb.Parity = NOPARITY; // No parity bit
dcb.StopBits = ONESTOPBIT; // One stop bit
fSuccess = SetCommState(hCom, &dcb);
if (!fSuccess) {
// Handle the error.
printf("SetCommState failed with error %d.\n", GetLastError());
CloseHandle(hCom);
return APP_ERROR;
}
}
printf("Serial port successfully reconfigured.\n");
查看您给该功能的参数。正如错误代码所说,它们可能不正确。 Google搜索“ setCommstate 87”显示了几个实例,其中参数(例如波特率)与串行端口不兼容。
不隶属于 StackOverflow