2011-04-19 4 views
0

아래 코드는 내 Arduino에서 정보를주고받는 데 사용하는 코드입니다. 내 문제는 Arduino가 처음으로 연결될 때입니다. 명령이 아무것도 반환하지 않기 때문에 명령을 읽는 것이 멈 춥니 다. 아직 전체 프로그램이 충돌하지 않기 때문입니다. 문제를 일으키는 arduino->ReadLine(); 인 읽기 기능에 시간 제한을 어떻게 추가 할 수 있습니까? 그렇게하면 잠시 후에 계속 될 것입니까?Arduino가있는 C++의 직렬 통신 시간 초과

#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->WriteLine(command); 
       String^ result = arduino->ReadLine(); 
       Console::Write(result); 
      } 
     } 

답변

2

설정 arduino->ReadTimeout = duration_in_ms 다음 TimeoutException을 잡을 수있어. 시간 제한 외에

+0

완벽하게 작동했습니다. 감사! – user541597

0

코드해야 루프하여 SerialPort의 BytesToRead 속성이 될 때까지 제로보다 큰

while (arduino->BytesToRead==0) {} 

당신은 정상적으로 사용자 메시지 만약 당신이 루프 얼마나 오래 추적하고 종료를 유지할 수있다 예상 한 시간 내에 arduino에서받은 것은 아무것도 없습니다.