gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:49 27 4
gpt4 key购买 nike

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

谢谢。

附加信息:生成的错误代码为 87:“参数不正确。”可能是微软有用的错误代码。 j/k

最佳答案

我的钱花在这里:

dcb.StopBits = 1; 

The MSDN docs这是关于 StopBits 的:

The number of stop bits to be used. This member can be one of the following values.

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

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

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

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

关于c++ - 尝试配置 COM 端口时设置 DCB 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4188782/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com