2017-10-18 19 views
1

私はシリアルポートに読み書きするマルチスレッドプログラムで作業しています。私がパテを使ってアプリケーションをテストすると、すべてが正常です。しかし、作成した.exeファイルでテストすると、動作しません。 (私はVS2017でプログラムを起動し、次に.exeファイルを起動します)シリアルポートReadFileは繰り返しデータを受信します

例:私の入力: "Test"、他のウィンドウの出力: "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ファイルでテストするとどうしてですか?

+7

あなたはどちらかReadFile'または '' bytesRead'の戻り値をチェックしません。 –

+2

とDavisが言っていたのは、あなたが戻り値を得ることができるため、何も読まれていない**(受信バッファが空で新しいデータを待たずに)通知とそれは前と同じデータを持っていると仮定すると、ゆっくりと返されます。 – 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

関連する問題