2011-04-23 63 views
1

以下是我用于在Windows XP上与我的arduino进行通信的代码。我遇到的问题是当我有两个命令试图同时访问端口,这是UnauthroizedAccessException catch语句,它输出错误消息,并且不执行其中一个命令,我该如何去编码catch语句,这样,而不是捕捉错误甚至能够进入错误的程序来完成的第一个命令,然后用另外一个,像一个队列执行....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 2011-04-23 06:22:18

回答

1

最好的解决办法如果可能的话,在这里不要使用例外。我还建议你不要同时运行两个访问同一串口的程序,以避免首先出现异常。然而,有例外,你可以做这样的:

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

您还可以添加一个计数器,如果你不想无限期地等待。