串口通信 - PuTTY仿真

时间:2016-03-01 09:35:44

标签: c++ windows serial-port

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

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

我将不会发布整个代码,因为没有人能够重新创建我的情况。但是,如果有必要,我总是可以添加所有内容。

我使用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] = '\0';

    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中的设置 - 字节长度,停止位,奇偶校验,流量控制等。我得到响应的事实表明连接没有错。< / p>

有什么问题?

1 个答案:

答案 0 :(得分:0)

问题原来是在邮件末尾发送的Hello, playground string int float64 Ab 组合。

仅发送\r\n或仅发送\r不起作用。但是,发送\n即可 - 即使它应与(char) 13相同。

每个角色的发送之间也需要暂停; 1毫秒就足够了。