2011-04-23 2 views
1

아래는 Windows XP에서 내 arduino와 통신하는 데 사용하는 코드입니다. 내가 가지고있는 문제는 포트에 동시에 액세스하려고하는 두 개의 명령, 즉 UnauthroizedAccessException catch 문이 있으며 errormessage를 출력하고 명령 중 하나를 실행하지 않을 때 발생합니다. 어떻게 코딩 할 수 있습니까? 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

명료성을 명확히 할 수 있습니까? 우리는 [이] (http://www.arduino.cc/) arduino에 대해 이야기하고 있습니까? 어떤 함수가 예외를 throw하는지 알고 있습니까? 이 함수의 소스 코드에 액세스 할 수 있습니까? – beduin

답변

1

가장 좋은 해결책 것 .... 첫 번째 명령을 완료 한 후 다른 하나는, 큐 같은으로 실행하는 프로그램의 오류에 그것을 만들기도 오류를 잡는 또는 가능한 경우 여기서 예외를 사용하지 마십시오. 또한 처음에는 예외를 피하기 위해 동일한 직렬 포트에 액세스하는 두 개의 프로그램을 동시에 실행하지 말 것을 권합니다. 그러나 예외는 다음과 같이 그것을 할 수 있습니다 : 당신은 무한정 기다리지 않으려면

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

또한 카운터를 추가 할 수 있습니다.