我正在尝试编写一个使用串行端口(例如 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();
}
Thanks.
附加信息:生成的错误代码为87:“参数不正确。”
应该是微软的most有用的错误代码。焦/克
我的钱都花在这个上了:
dcb.StopBits = 1;
MSDN 文档关于 StopBits 是这样说的:
要使用的停止位的数量。该成员可以是其中之一
以下值。
ONESTOPBIT 0 1 stop bit.
ONE5STOPBITS 1 1.5 stop bits.
TWOSTOPBITS 2 2 stop bits.
所以,你要求 1.5 个停止位,这是一个非常古老的东西,我什至不记得它来自哪里。电传打字机,可能。
我猜你的驱动程序/硬件支持这种模式的机会很小,因此会出现错误。
所以,将其更改为dcb.StopBits = ONESTOPBIT;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)