2011-04-23 7 views
1

以下は、Windows XPでarduinoと通信するために使用しているコードです。私が抱えている問題は、ポートに同時にアクセスしようとしている2つのコマンド、つまりUnauthroizedAccessException catchステートメントがあり、errormessageが出力され、コマンドの1つが実行されない場合です。 catch文の代わりにエラーをキャッチしたり、プログラムは最初のコマンドを終了し、他の1、キューのような何かを実行するためにエラーにそれを作るように....C++/CLIはキャッチ処理を試します

#include "stdafx.h" 
#include <iostream> 

using namespace System; 
using namespace System::IO::Ports; 

int main(int argc, char* argv[]) 
{ 
    using namespace std; 

    String^ portName; 
    int baudRate=9600; 

    portName="COM4"; 
    // arduino settings 
    SerialPort^ arduino; 

    arduino = gcnew SerialPort(portName, baudRate); 
    // open port 
    try 
    { 
     arduino->Open(); 
     { 
      if(strcmp(argv[1],"-send")==0){ 
       String^ command = gcnew String(reinterpret_cast<const char*>(argv[2])); 

       if(String::Compare(command,"int6")==0){ 
        arduino->Write("^"); 
       }else 
        arduino->Write(command); 
      } 
      if(strcmp(argv[1],"-get")==0){ 
       String^ command = gcnew String(reinterpret_cast<const char*>(argv[2])); 
       arduino->ReadTimeout = 1000;   
       arduino->WriteLine(command); 

       String^ result = arduino->ReadLine(); 

       Console::Write(result); 
      } 
     } 
     // close port to arduino 
     arduino->Close(); 
    } 
    catch (IO::IOException^ e){ 
     Console::Write("errormessagedisconnected"); 
    } 
    catch (TimeoutException^ e){ 
     Console::Write("errormessage"); 
    } 
    catch (UnauthorizedAccessException^ e){ 
     Console::Write("errormessage"); 
    } 
    catch (ArgumentException^ e){ 
     Console::WriteLine(e->GetType()->Name+": incorrect port name syntax, must start with COM/com"); 
    } 
    // end program 

    return 0; 
} 
+0

スムースを明確にすることはできますか?私たちは[this(http://www.arduino.cc/)arduinoについて話していますか?どの関数が例外をスローするのか知っていますか?これらの関数のソースコードにアクセスできますか? – beduin

答えて

1

最善の解決策だろう可能であれば、ここでは例外を使用しないでください。私はまた、最初に例外を避けるために、同じシリアルポートにアクセスする2つのプログラムを同時に実行しないことをお勧めします。ただし、例外は次のようにすることができます。

void f() 
{ 
    bool bFinished = FALSE; 
    while(!bFinished) { 
     try { 
      ThisFunctionThrows(); 
      bFinished = TRUE; 
     } 
     catch(UnauthorizedAccessException^ e) { 
      Console::Write("retrying in 1 sec"); 
      sleep(1); 
     } 
    } 
} 

無期限に待機したくない場合は、カウンタを追加することもできます。

関連する問題