2017-10-18 100 views
1

我正在開發一個多線程程序來讀寫串口。如果我用Putty測試我的應用程序,一切都很好。但是,當我用創建的.exe文件測試它時,它不起作用。 (我在VS2017中啓動程序,然後是.exe文件)串口ReadFile接收重複數據

例如:我的輸入:「測試」,輸出在另一個窗口中:「Teeeeeeeeeeeessssssssssttttttt」。

我的代碼發送數據:

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; 
} 

在陣列「線」我有來自用戶的輸入。

我的代碼讀取數據:

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; 
     } 
    } 
} 

之後,我寫了數據打倒打印(輸出)功能:

cout << output << endl; 

如何創建處理文件:

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

爲什麼會發生這種情況,爲什麼只有在使用.exe文件而不是使用Putty進行測試時纔會發生這種情況?

+7

你不檢查或者ReadFile'或'bytesRead'的'的返回值。 –

+2

和Davis說**是非常重要的**,因爲你可以得到一個返回值,告訴你**沒有讀取任何內容**(接收緩衝區爲空,我們沒有等待新數據),你的代碼不會通知,並會假設它得到了與以前相同的數據,因此eeeeeeeeeeeeeeeeee.... – quetzalcoatl

+0

@DavidSchwartz如何檢查返回值? – User987123

回答

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; 
     } 
    } 
} 
+0

你應該更加關注ReadFile()失敗的原因。在我看來,超時設置過低,請查看您的SetCommTimeouts()調用。或者如果您忘記使用它,請添加它。 –

+0

@HansPassant我在我的代碼中有超時,但我沒有將它添加到我的問題/答案中。但是,謝謝你的建議。 – User987123