串行端口通信 - PuTTY 仿真

Serial Port communication - PuTTY emulation

本文关键字:仿真 PuTTY 通信 串行端口      更新时间:2023-10-16

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

我可以找到正确的COM端口并成功打开它。我可以发送数据,但响应只相当于"未知命令"。

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

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

if (!WriteFile(hSerial, "r rc.allrn", 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

这是>rn.我尝试减慢字符的发送速度以模拟它们被键入,但这会调用 ICSP 的相同响应:

bool serialSend(LPCSTR MESSAGE, PHANDLE hSERIAL)
{
    DWORD   bytesWritten;
    char    writeBuff[2];    
    writeBuff[1] = '';
    for (UINT x = 0; x <= strnlen(MESSAGE, 64); x++)
    {
        cout << MESSAGE[x];
        writeBuff[0] = MESSAGE[x];
        if (!WriteFile(*hSERIAL, writeBuff, 1, &bytesWritten, NULL))
            cout << "ttERROR! (character '" << MESSAGE[x] << "', error " << GetLastError() << ")" << endl;
        Sleep(100);
    }
    writeBuff[0] = 'n';
    if (!WriteFile(*hSERIAL, writeBuff, 1, &bytesWritten, NULL))
        cout << "ttERROR! (character 'LF', error " << GetLastError() << ")" << endl;
    Sleep(100);
    writeBuff[0] = 'r';
    if (!WriteFile(*hSERIAL, writeBuff, 1, &bytesWritten, NULL))
        cout << "ttERROR! (character 'CR', error " << GetLastError() << ")" << endl;
    cout << endl;
    return true;
}

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

怎么了?

问题原来是消息末尾发送的rn组合。

仅发送r或仅发送n不起作用。但是,发送(char) 13确实如此 - 即使这应该与r相同。

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