我正在開發一個多線程程序來讀寫串口。如果我用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進行測試時纔會發生這種情況?
你不檢查或者ReadFile'或'bytesRead'的'的返回值。 –
和Davis說**是非常重要的**,因爲你可以得到一個返回值,告訴你**沒有讀取任何內容**(接收緩衝區爲空,我們沒有等待新數據),你的代碼不會通知,並會假設它得到了與以前相同的數據,因此eeeeeeeeeeeeeeeeee.... – quetzalcoatl
@DavidSchwartz如何檢查返回值? – User987123