c++程序在读取COM端口时冻结

C++ program freezes during COM port read

本文关键字:冻结 COM 程序 读取 c++      更新时间:2023-10-16

我正试图编写一个简单的程序,通过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);