c++程序在读取COM端口时冻结
C++ program freezes during COM port read
我正试图编写一个简单的程序,通过COM端口将单个字符发送到程序,并读取我得到的答案。我想我有工作脚本,我至少可以通过com端口发送命令,但当ReadFile
函数开始冻结。我有通信超时设置为100ms,所以我不认为它是锁定端口,但我可能是错的。我没有得到任何错误,也没有警告,当我编译。我对c++非常陌生(通常使用python),所以请尽可能清楚地回答您的问题。
// comtest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
#include <dos.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <windows.h>
int main(int argc, char **argv)
{
std::cout << "TOP! n";
char buffer[1];
HANDLE file;
COMMTIMEOUTS timeouts;
DWORD read, written;
DCB port;
char init[] = ""; // e.g., "ATZ" to completely reset a modem.
// open the comm port.
file = CreateFile(L"COM1",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
std::cout << "file made n";
// get the current DCB, and adjust a few bits to our liking.
memset(&port, 0, sizeof(port));
port.DCBlength = sizeof(port);
// set short timeouts on the comm port.
timeouts.ReadIntervalTimeout = 100;
timeouts.ReadTotalTimeoutMultiplier = 1;
timeouts.ReadTotalTimeoutConstant = 100;
timeouts.WriteTotalTimeoutMultiplier = 1;
timeouts.WriteTotalTimeoutConstant = 100;
int N = 10;
while (N > 1)
{
std::cout << "i'm in the loop!" << N << " loops left n";
char command [1];
char * commandbuff;
std::cin >> command;
commandbuff = &command[1];
WriteFile(file, commandbuff, sizeof(commandbuff),&written, NULL);
Sleep(1000);
std::cout << "I just slept n";
ReadFile(file, buffer, sizeof(buffer), &read, NULL);
N--;
}
// close up and go home.
CloseHandle(file);
return 0;
您的代码似乎并没有实际调用SetCommTimeouts
,因此您定义的超时将无法应用
从com端口接收数据,除非先发送命令或得到响应,否则不要开始读取。然后,最好一次只读取一个字节,但是如果你像我这样发送modbus/at命令,并且知道你期望8个字节,那么使用readfile读取8个字节是可以的。在你读取单个字节之前,大多数c++ com端口示例都有SetCommState, SetCommTimeouts, SetCommMask和WaitCommEvent。
在ReadFile的第二个参数上有一个"&"。不过是MS Visual c++。Status = ReadFile(fileusb, &ReadData, sizeof(ReadData), &NoBytesRead, NULL);
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- WIN32:C++,为什么在WM_CLOSE上调用Messagebox函数程序正在冻结
- 两个 COM 组件中 ENUM 的重复条目
- COM 接口 c# 封送数组数组
- COM :是否可以查看是否存在对我的某个 COM 对象的进程外引用?我可以释放它吗?
- Win32 发送输入鼠标移动滞后并冻结
- ImGui 在单击按钮后冻结
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 进程外 EXE 的免注册 COM
- 使用 Outlook 2016 Microsoft Store 连接到 Outlook COM
- 如何从COM模块中的函数返回字符串数组?
- QWidget UI 在使用 QQuickWidget 时冻结
- 如何防止 std::thread 在 QT 中冻结 GUI?
- Adafruit 羽毛RFM69HCW在使用过程中会冻结,需要硬重置
- 如何在C++非托管/本机 DLL 中从注册免费 COM C# 托管 DLL 创建 COM 对象
- Windows (COM) API 的行为不同,没有特定的库
- MFC/C++ ComboBox:禁用下拉列表关闭和打开(UI 冻结)的绘制
- 我是否可以使用 win32 句柄以编程方式记录发送到/接收到 USB/COM 的内容
- 在传递 com 变体时运行 excel 宏崩溃
- c++程序在读取COM端口时冻结