串口ReadFile接收重复数据

时间:2017-10-18 07:12:15

标签: c++ windows winapi serial-port

我正在研究一个多线程程序来读写串口。如果我用Putty测试我的应用程序一切都很好。但是当我用创建的.exe文件测试它时,它不起作用。 (我在VS2017中启动程序,然后启动.exe文件)

例如:我的输入:“测试”,其他窗口的输出:“Teeeeeeeeeeeesssssssssssttttttt”。

我发送数据的代码:

void SendDataToPort()
{
for (size_t i = 0; i <= strlen(line); i++) // loop through the array until 
 every letter has been sent
{
    try
    {
        if (i == strlen(line))  // If ever letter has been sent                 
        {                       // end it with a new line
            c = '\n';           // a new line
        }
        else
        {
            c = line[i];
        }
        WriteFile(serialHandle, &c, 1, &dwBytesWrite, NULL); // Send letter to serial port
    }
    catch (const exception&)
    {
        cout << "Error while writing.";
    }
}
cout << endl << "Sent." << endl;
}

在数组“line”中,我有来自用户的输入。

我的代码来读取数据:

int newLineCounter = 0;
unsigned char tmp;
while (!endCurrentRead)
{
    ReadFile(hSerial, &tmp, 1, &bytesRead, NULL); // Get new letter

    if (tmp != '\n')
    {
        newLineCounter = 0;
        if (tmp >= 32 && tmp <= 126)
        {
            output += tmp; // Add current letter to the output
        }
    }
    else
    {
        newLineCounter++;
        if (newLineCounter < 2) // If there are more than 2 '\n' it doesn't write it down
        {
            output += tmp;
        }
        else if (newLineCounter == 2)
        {
            Print(output);
            output = receiverName;
            endCurrentRead = true;
        }
    }
}

之后我用Print(输出)函数写下数据:

cout << output << endl;

我如何创建句柄文件:

serialHandle = CreateFile(LcomPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

为什么会发生这种情况?为什么只有在我使用.exe文件而不是使用Putty进行测试时才会发生这种情况?

1 个答案:

答案 0 :(得分:1)

感谢 @quetzalcoatl 的帮助,我能够解决问题。我必须检查bytesRead是否大于0。

解决方案:

int newLineCounter = 0;
DWORD dwCommModemStatus;
unsigned char tmp;
while (!endCurrentRead)
{
    ReadFile(hSerial, &tmp, 1, &bytesRead, NULL); // Get new letter
    if (bytesRead > 0)
    {
        if (tmp != '\n')
        {
            newLineCounter = 0;
            if (tmp >= 32 && tmp <= 126)
            {
                output += tmp; // Add current letter to the output
            }
        }
        else
        {
            output += tmp;
            Print(output);
            output = receiverName;
            endCurrentRead = true;
        }
    }
}