Install DCB when trying to configure COM port

I am trying to write a C ++ MFC application that uses a serial port (e.g. COM8). Every time I try to install DCB, it fails. If someone can point out what I'm doing wrong, I would really appreciate it.

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();
}

Thank.

Additional information: Generated error code: 87: "The parameter is incorrect." Microsoft is probably the most useful error code. J / c

+3
source share
4 answers

I managed to solve the problem using 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();
}
+1
source

My money for this:

dcb.StopBits = 1; 

MSDN StopBits:

, . .

ONESTOPBIT    0    1 stop bit.
ONE5STOPBITS  1    1.5 stop bits.
TWOSTOPBITS   2    2 stop bits.

, 1,5 , , , . Teleprinters, .

, / , , slim, , .

, dcb.StopBits = ONESTOPBIT;

+8

.

  • GetCommState , . .
  • , , , - .
  • StopBits - , . 1 ONE5STOPBITS, .
+2
source

Look at the parameters that you pass to the function. They are probably wrong, as the error code says. A Google search for "SetCommState 87" shows several examples where parameters (such as baud rate) were not compatible with the serial port.

0
source

Source: https://habr.com/ru/post/1775041/


All Articles