尝试配置COM端口时设置DCB失败

Jim*_*ell 4 c++ mfc serial-port serial-communication visual-studio-2008

我正在尝试编写一个使用串行端口的C++ MFC应用程序(例如COM8).每次我尝试设置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();
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

附加信息:生成的错误代码为87:"参数不正确." 可能是微软有用的错误代码.J/K

Rod*_*ddy 11

我的钱是这样的:

dcb.StopBits = 1; 
Run Code Online (Sandbox Code Playgroud)

MSDN文档说这个关于StopBits:

要使用的停止位数.该成员可以是以下值之一.

ONESTOPBIT    0    1 stop bit.
ONE5STOPBITS  1    1.5 stop bits.
TWOSTOPBITS   2    2 stop bits.
Run Code Online (Sandbox Code Playgroud)

所以,你要求1.5个停止位,这是一个非常古老的东西,我甚至不记得它来自哪里.可能是电传打字机.

我猜你的驱动程序/硬件支持这种模式的机会很小,因此错误.

所以,改成它 dcb.StopBits = ONESTOPBIT;


Jim*_*ell 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();
}
Run Code Online (Sandbox Code Playgroud)