Domanda

Sto cercando di scrivere un'applicazione C ++ MFC che utilizza la porta seriale (per esempio COM8). Ogni volta che tenta di impostare la DCB fallisce. Se qualcuno può indicare quello che sto facendo male, sarei davvero grato.

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

Grazie.

Altre Informazioni: Il codice di errore generato è 87: "Il parametro non è corretto." Probabilmente Microsoft di più utile codice di errore. j / k

È stato utile?

Soluzione 3

sono stato in grado di risolvere il problema utilizzando 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();
}

Altri suggerimenti

Il mio denaro è su questo:

dcb.StopBits = 1; 

documentazione MSDN dice questo circa StopBits:

Il numero di bit di stop da utilizzare. Il membro può essere uno dei i seguenti valori.

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

Quindi, si sta chiedendo per i bit di stop 1.5, che è tale un orribilmente cosa arcaica non riesco nemmeno a ricordare da dove proviene. Telescriventi, possibilmente.

Direi le possibilità che il driver / hardware che supportano questa modalità sono sottili, da qui l'errore.

Quindi, modificarlo a dcb.StopBits = ONESTOPBIT;

Ecco alcune possibilità in nessun ordine particolare.

  • GetCommState è il riempimento della struttura con immondizia poiché la porta non è stata ancora inizializzata. Si potrebbe semplicemente saltare questo passaggio.
  • Ci sono due parametri che controllano le impostazioni di parità, e non è chiaro se ci sono delle combinazioni non valide.
  • Il valore per StopBits non è il numero di bit, si tratta di un costante numero magico. Il valore 1 è assimilato a ONE5STOPBITS che potrebbe essere valida in combinazione con gli altri parametri.

Questo è il mio codice e il suo lavoro bene.

/* 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");

Guardate i parametri si danno alla funzione. Sono probabilmente non corretta, come il codice di errore dice. Una ricerca su Google per "SetCommState 87" mostra diversi casi in cui i parametri (ad esempio baud rate) non erano compatibili con la porta seriale.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top