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

时间:2010-11-15 21:01:04

标签: c++ visual-studio-2008 mfc serial-port serial-communication

我正在尝试编写使用串行端口的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();
}

感谢。

其他信息:生成的错误代码为87:“参数不正确。” 可能是Microsoft的大多数有用的错误代码。 J / K

5 个答案:

答案 0 :(得分:11)

我的钱就是这个:

dcb.StopBits = 1; 

The MSDN docs说这个关于StopBits:

  

要使用的停止位数。这个成员可以是其中之一   以下数值。

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

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

我猜你的驱动程序/硬件支持这种模式的可能性很小,因此错误。

因此,请将其更改为dcb.StopBits = ONESTOPBIT;

答案 1 :(得分:3)

以下是一些没有特定顺序的可能性。

  • GetCommState正在用垃圾填充结构,因为端口尚未初始化。你可能只是跳过这一步。
  • 有两个控制奇偶校验设置的参数,并且不清楚是否存在任何无效组合。
  • StopBits的值不是位数,它是一个幻数常量。值1等于ONE5STOPBITS,与其他参数组合时可能无效。

答案 2 :(得分:2)

我能够使用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();
}

答案 3 :(得分:1)

这是我的代码,而且效果很好。

C:\Users\Documents\SymbolicLinks\Folder\SubDirectorio
   ....SymbolicApuntandoADirectorioLink.txt -->SymbolicLink pointing to parent directory SubDirectorio

答案 4 :(得分:0)

查看您为该功能提供的参数。它们可能不正确,正如错误代码所说。谷歌搜索“SetCommState 87”显示了几个参数(例如波特率)与串口不兼容的情况。