串行端口通信 - PuTTY 仿真

Serial Port communication - PuTTY emulation

我正在编写一个简单的用户界面来与在线串行编程器进行通信。目的是消除最终用户通过 PuTTY 键入十几个神秘命令的需要,实际上完全消除了键入的需要,因为用户不可避免地戴着键盘不友好的手套。该过程需要与用户交互,因此简单的批处理脚本不可行。

我可以找到正确的COM端口并成功打开它。我可以发送数据,但响应永远只相当于 "unknown command".

我将避免发布整个代码,因为没有人能够重现我的情况。但是,如有必要,我随时可以添加所有内容。

我使用 CreateFile() 打开通信并使用 WriteFile()ReadFile() 进行通信。例如:

if (!WriteFile(hSerial, "r rc.all\r\n", 10, &bytesRead, NULL))
    cout << "Error sending message (" << GetLastError() << ")" << endl;
if (!ReadFile(hSerial, msgBuffer, 15, &bytesRead, NULL))
    cout << "No message received" << endl
else
{
    cout << "Bytes rcvd = " << bytesRead << endl;
    for (int x=0; x<bytesRead; x++)
        cout << (unsigned int) msgBuffer[x] << "  ";
}

无论我发送什么消息("r rc.all" 或 "foobar"),我总是得到相同的回复:

Bytes rcvd = 3
62  13  10

>\r\n。我曾尝试放慢字符的发送速度以模拟它们被键入的速度,但这会调用来自 ICSP 的相同响应:

bool serialSend(LPCSTR MESSAGE, PHANDLE hSERIAL)
{
    DWORD   bytesWritten;
    char    writeBuff[2];    

    writeBuff[1] = '[=12=]';

    for (UINT x = 0; x <= strnlen(MESSAGE, 64); x++)
    {
        cout << MESSAGE[x];
        writeBuff[0] = MESSAGE[x];
        if (!WriteFile(*hSERIAL, writeBuff, 1, &bytesWritten, NULL))
            cout << "\t\tERROR! (character '" << MESSAGE[x] << "', error " << GetLastError() << ")" << endl;
        Sleep(100);
    }

    writeBuff[0] = '\n';
    if (!WriteFile(*hSERIAL, writeBuff, 1, &bytesWritten, NULL))
        cout << "\t\tERROR! (character 'LF', error " << GetLastError() << ")" << endl;
    Sleep(100);
    writeBuff[0] = '\r';
    if (!WriteFile(*hSERIAL, writeBuff, 1, &bytesWritten, NULL))
        cout << "\t\tERROR! (character 'CR', error " << GetLastError() << ")" << endl;

    cout << endl;

    return true;
}

我已经设置了串行连接的参数以匹配 PuTTY 中的设置 - 字节长度、停止位、奇偶校验、流量控制等。我得到响应的事实表明连接没有问题.

怎么了?

原来是消息末尾发送的 \r\n 组合出现问题。

仅发送 \r\n 无效。然而,发送 (char) 13 确实如此——尽管这应该与 \r.

相同

每个字符的发送之间也需要有一个停顿; 1ms就够了。