2012-04-26 78 views
2

如何在Arduino上捕獲AT命令的輸出?如何在Arduino中讀取AT命令的輸出?

我使用帶GSM屏蔽的Arduino Uno R3。我有所有的AT命令(they can be seen here),如果我使用終端並獲得輸出,我可以很好地輸入它們。但是,如何通過代碼捕獲結果輸出?下面的代碼顯示了我嘗試過的,但它不起作用。特別是在我嘗試獲取模擬輸入並打印出結果的地方。

#include <SoftwareSerial.h> 

SoftwareSerial mySerial(7, 8); 

void setup() 
{ 
    char sensorValue[32] =""; 
    Serial.begin(9600); 
    mySerial.begin(9600); 
    Serial.println("\r"); 

    //Wait for a second while the modem sends an "OK" 
    delay(1000);      

    //Because we want to send the SMS in text mode 
    Serial.println("AT+CMGF=1\r");  
    delay(1000); 

    mySerial.println("AT+CADC?");  //Query the analog input for data 
    Serial.println(Serial.available());  
    Serial.println(Serial.read()); //Print out result??? 

    //Start accepting the text for the message 
    //to be sent to the number specified. 
    //Replace this number with the target mobile number. 
    Serial.println("AT+CMGS=\"+MSISDN\"\r");  


    delay(1000); 
    Serial.println("!"); //The text for the message 
    delay(1000); 
    Serial.write(26); //Equivalent to sending Ctrl+Z 
} 

void loop() 
{ 
    /* 
    if (mySerial.available()) 
    Serial.write(mySerial.read()); 
    if (Serial.available()) 
    mySerial.write(Serial.read()); 
    */ 
} 

我得到的輸出:

AT + CMGF = 1

AT + CADC? 21 13

AT + CMGF = 1

AT + CADC?不管我的模擬信號源的變化18 65

回答

2

看看在SoftwareSerial read功能here的文檔。

當您從GSM設備串行接口讀取時,您不能理所當然地認爲緩衝區上有字節需要讀取。

很有可能mySerial.read()返回-1(無字節可用),因爲Arduino在GSM設備可以在串口上提供某些東西之前運行該代碼。

您應該使用available函數(文檔here)來測試傳入字節的串行接口。你可以在超時使用它,以避免無限的等待。

你可以嘗試的最好的事情是編寫一個單獨的class來處理串行操作(讀,寫,超時,延遲等)。

另外,我爲Arduino寫了一次GPRS驅動程序。 我的電源有問題,需要我在GPRS設備上安裝額外的電容器,並使用輸出電流超過2A的電源。

+0

好的,我已經構建了一些代碼來檢查available()然後讀取,但是我只是返回我剛纔輸入的命令,如何獲取命令發回的結果? – BOMEz 2012-04-26 21:48:47

+0

您可以測試可用性並從myserial中讀取。 – 2012-04-27 17:06:41