在 C 中与 windows 10 的虚拟端口通信

Virtual comport communication with windows 10 in C

我正在尝试通过 Win10 上的虚拟端口(端口到 USB 适配器,PL2303)与设备通信。该设备是 Eltek RC250 数据记录器。

我已经安装了旧的 PL2303 驱动程序。设备管理器正确识别了该设备。设备与官方软件收发数据正常

我的问题是在执行 ReadFile 后程序什么都不做。我认为 ReadFile 正在等待来自设备的更多输入,因此停留在这个函数中。 在 win7 系统上试过同样的问题。

我写入设备的消息是有效消息。

以下代码显示通信。

hComm = CreateFile("COM3",                       //port name
    GENERIC_READ | GENERIC_WRITE, //Read/Write
    0,                            // No Sharing
    NULL,                         // No Security
    OPEN_EXISTING,// Open existing port only
    0,            // Non Overlapped I/O
    NULL);        // Null for Comm Devices                                                  /* establish connection to serial port */

if (hComm == INVALID_HANDLE_VALUE)
    printf("Error in opening serial port");
else
    printf("opening serial port successfully");


nNumberOfBytesToWrite = sizeof(message);

resW = WriteFile(
    hComm,
    message,
    nNumberOfBytesToWrite,
    &lpNumberOfBytesWritten,
    NULL);

do
    {
    printf("\nread");
    resR = ReadFile(
        hComm,
        &answer,
        sizeof(lpNumberOfBytesRead),
        &lpNumberOfBytesRead,
        NULL);
        SerialBuffer[i] = answer;
        i++;
    }
while (lpNumberOfBytesRead > 0);

return 0;

请帮助我,我不知道可能是什么问题。 托马斯

ReadFile() 调用中,第三个参数应该是 sizeof(answer)(或者可能只是 1,因为它看起来是一个字节),但肯定不是 sizeof(lpNumberOfBytesRead)。当大概 answer 是单个字节时,它正在等待 4 个字节(DWORD 的大小)?

此外,如果您没有明确设置 Comm timeout,您将不知道 ReadFile() 在返回 0 退出循环之前要等待多长时间。如果超时是不确定的,那么它永远不会存在循环。

这个调用还有其他潜在的问题,但是没有看到参数是如何声明的,就不好说了。