2012-04-26 228 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