SetCommState 函数失败(错误 87)

Rom*_*nzo 5 c embedded usb winapi serial-port

我正在研究一些基本的串行通信内容,并且遇到了这个我似乎无法解决的问题。我正在尝试将通信状态设置为特定的波特率、停止位、奇偶校验位和数据大小。如下面的示例代码所示,我从 getComState 获取当前 COM 状态并修改一些值。

    DCB dcb = { 0 };
    // for set timeout for readfile function
    COMMTIMEOUTS timeouts = {   0,  // interval timeout. 0 = not used
                                0,  // read multiplier
                                500, // read constant (milliseconds)
                                0,  // Write multiplier
                                500 // Write Constant
                            };

    if (SetCommTimeouts(usb_device, &timeouts) == FALSE) {
        "ERROR: SetCommTimeouts failed with error %d.\n", GetLastError();

        add_log_trace("ERROR: SetCommTimeouts failed with error %d.\n", GetLastError());
    }

    BOOL fSuccess;
    //  Initialize the DCB structure.
    SecureZeroMemory(&dcb, sizeof(DCB));
    dcb.DCBlength = sizeof(DCB);

    //  Build on the current configuration by first retrieving all current
    //  settings.
    fSuccess = GetCommState(usb_device, &dcb);

    //  Fill in some DCB values and set the com state: 
    //  115,200 bps, 8 data bits, no parity, and 1 stop bit.
    dcb.BaudRate    =   CBR_115200;     //  baud rate
    dcb.ByteSize    =   8;             //  data size, xmit and rcv
    dcb.Parity      =   NOPARITY;      //  parity bit
    dcb.StopBits    =   ONESTOPBIT;    //  stop bit

    fSuccess = SetCommState(usb_device, &dcb);
Run Code Online (Sandbox Code Playgroud)

然而,无论我做什么,这个功能都会让我失败。该错误非常简单(错误代码 87),这表示存在无效参数。经过一些研究后,解决方案似乎非常明显。但是,我已经尝试了下面列出的解决方案,包括一些健全性测试,但似乎没有任何效果。

我还考虑了 MSDN 开发人员留下的有关使用 SetComState 函数的评论,但是函数调用仍然失败。

我尝试在 Linux 机器上运行类似的代码,并且设置 com 端口工作正常。我看到一些文章,其中指出 Windows 弄乱了处理操作系统和设备之间通信的 usbser.sys 文件。

我很想尝试用旧文件替换 usbser.sys 文件,但我想就这个问题得到第二个意见。这是一个常见问题吗?有更直接的解决方案吗?如果有人能指出我正确的方向或纠正我的一些假设和方法,我将不胜感激。希望这篇文章的范围不会太宽泛。我只是想使用 SetCommState 设置正确的波特率。哈哈。

谢谢

小智 1

在 SetCommState 之前调用 GetCommState