WaitCommEvent 在启动时不会返回(当通过 MatLAB 初始化 COMPort 时有效)

WaitCommEvent does not return on startup (works when COMPort is initialized via MatLAB)

本文关键字:MatLAB 初始化 COMPort 有效 启动 WaitCommEvent 返回      更新时间:2023-10-16

我遇到了一个关于WaitCommEvent的奇怪问题。我使用创建文件通过C++打开串行端口。当我想从它接收 sth 时,WaitCommEvent 没有回复,程序崩溃。但是:如果我使用 MatLAB 初始化相同的端口,然后尝试使用我的 C++ 文件打开它,它工作得很好。不幸的是,我无法在其他帖子中找到解决方案。非常感谢任何建议。提前谢谢。

这是我C++代码(comport 和波特率的值是正确的,与 matlab 代码中的值相同):

m_hLaunchpad = CreateFile(COMPORT_LAUNCHPAD, GENERIC_READ | GENERIC_WRITE, 0, 0,
    OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL);
unsigned char buffer[64];
DCB dcb;
DWORD dwBytesTransferred;
DWORD dwCommModemStatus;
if (m_hLaunchpad == INVALID_HANDLE_VALUE)
{
    return (C_ERROR);
}
if (!GetCommState(m_hLaunchpad, &dcb))
    return (C_ERROR);
dcb.BaudRate = BAUD_LAUNCHPAD; //baudrate; 
dcb.ByteSize = 8; //8 data bits
dcb.Parity = NOPARITY; //no parity
dcb.StopBits = ONESTOPBIT; //1 stop
if (!SetCommState(m_hLaunchpad, &dcb))
    return (C_ERROR);
SetCommMask(m_hLaunchpad, EV_RXCHAR | EV_ERR); //receive character event
WaitCommEvent(m_hLaunchpad, &dwCommModemStatus, NULL); //wait for character
if (dwCommModemStatus & EV_RXCHAR)
    ReadFile(m_hLaunchpad, &buffer, sizeof(buffer), &dwBytesTransferred, 0); // read and save in buffer
else if (dwCommModemStatus & EV_ERR)
    return (C_ERROR);

以下是通过 MatLab 初始化 Comport 的方式:

% LaunchPad for potentiometers
handles.ser2 = serial(handles.COMPort2, 'BaudRate', 115200);
handles.ser2.BytesAvailableFcnCount = 64;
handles.ser2.BytesAvailableFcnMode = 'byte';
handles.ser2.BytesAvailableFcn = {@instrcallback, hObject};

更多信息:我使用 Maestro 和 Launchpad。打开端口并将数据发送到 Maestro 端口在启动时和执行 matlab 代码后工作正常,因此仅从 Launchpad 接收会导致麻烦。

所以我终于找到了解决方案。它与异步或手器握手无关。

为了设置波特率,我使用了BAUD_115200(来自WinBase.h),这似乎是错误的。我将波特率作为 int (115200) 而不是使用该变量,现在它可以工作了。我在代码中没有更改任何其他内容。对于迷你大师来说,变量BAUD_9600确实有效。