WaitCommEvent 在启动时不会返回(当通过 MatLAB 初始化 COMPort 时有效)
WaitCommEvent does not return on startup (works when COMPort is initialized via MatLAB)
我遇到了一个关于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确实有效。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 从 Matlab Coder 初始化主函数
- WaitCommEvent 在启动时不会返回(当通过 MatLAB 初始化 COMPort 时有效)
- 是否可以像在 Matlab 中那样在C++中初始化向量
- 从c++调用matlab dll:初始化库失败
- Matlab无法正确初始化c++共享库
- 如何避免重复初始化.mex (matlab编译代码)
- 无法在c++中初始化Matlab dll