2011-04-19 108 views
0

下面的代碼是我用來從我的Arduino發送和接收信息的代碼。我的問題是當Arduino第一次插入時,從中讀取數據會掛起,因爲命令沒有返回任何內容,因爲這裏沒有任何內容,所以我的整個程序崩潰了。如何將讀取功能添加到arduino->ReadLine();,導致此問題?這種方式會在一秒之後繼續下去嗎?C++與Arduino的串行通信超時

#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 2011-04-19 23:46:29

0

除了超時您的代碼應該循環,直到一個串口的BytesToRead屬性大於零

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

你可以跟蹤你已經循環了多久,退出優雅與用戶的消息,如果有在預期的時間內沒有收到任何arduino的信息。