简体   繁体   中英

How do I read the output of an AT command in Arduino?

How do I capture the output from an AT command on an Arduino?

I'm using the Arduino Uno R3 with a GSM shield. I have all the AT commands ( they can be seen here ) and I can enter them just fine if I use the terminal and get output. However how can I capture the resulting output via code? The code below shows what I've tried but it does not work. In particular where I attempt to get the analog input and then print out the result.

#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());  
    */
}

I get the outputs:

AT+CMGF=1

AT+CADC? 21 13

or

AT+CMGF=1

AT+CADC? 18 65

Regardless of changes in my analog source

Take a look at the documentation of the SoftwareSerial read function here .

When you read from the GSM device serial interface, you cannot take for granted that there are bytes to be read on the buffer.

It's very likely that mySerial.read() returns -1 (no bytes available), as Arduino runs that code before the GSM device can provide something on the serial port.

You should use the available function (documentation here ) to test the serial interface for incoming bytes. You could use it with a timeout to avoid infinite waiting.

The best thing you could try is to write a separate class to handle serial operations (read, write, timeouts, delays, etc).

Also, I wrote a GPRS driver for Arduino once. I had a problem with the power supply that required me to install an extra capacitor on the GPRS device and use a power supply with more than 2A of output current.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM