I have this code to read a SMS:
String read_SMS(int index)
{
Serial.println("--START READ SMS POSITION" + String(index) + "--");
delay(400);
sendATcommand("AT+CMGF=1", "OK", 1000); // sets the SMS mode to text
delay(2000);
String tmp;
tmp = readATcommand("AT+CMGR=1", 4000);
Serial.println("Content: " + tmp);
Serial.println("--END READ SMS POSITION" + String(index) + "--");
}
String readATcommand(String ATcommand, unsigned int timeout)
{
char response[800];
unsigned long previous;
memset(response, '\0', 800); // Initialice the string
int x = 0;
GSMSerial.println(ATcommand);
delay(3000);
previous = millis();
do {
if (GSMSerial.available() > 0) {
response[x] = GSMSerial.read();
x++;
}
} while ((millis() - previous) < timeout); // Waits for the asnwer with time out
return (String) response;
}
// sending AT commands to the Sim808 module
int8_t sendATcommand(String ATcommand, char* expected_answer, unsigned int timeout) {
uint8_t x = 0, answer = 0;
char response[200];
unsigned long previous;
memset(response, '\0', 200); // Initialice the string
delay(100);
// Clean the input buffer
while (GSMSerial.available() > 0 ) GSMSerial.read();
if (ATcommand[0] != '\0') {
// Send the AT command
GSMSerial.println(ATcommand);
//Serial.print(F("AT Command: "));
//Serial.println(ATcommand);
}
// Waiting for the answer
x = 0;
previous = millis();
do {
// if there are data in the UART input buffer, reads it and checks for the asnwer
if (GSMSerial.available() > 0) {
response[x] = GSMSerial.read();
x++;
// check if the desired answer (OK) is in the response of the module
if (strstr(response, expected_answer) != NULL) {
answer = 1;
}
}
} while ((answer == 0) && ((millis() - previous) < timeout)); // Waits for the asnwer with time out
//Serial.println(F("START RESPONSE:"));
//Serial.println(response);
//Serial.println(F("END RESPONSE"));
//if (answer == 0) {
// Serial.println("Could not get the expected answer!");
//}
//else {
// Serial.println("Found expected answer!");
//}
return answer;
}
What can be wrong in the readATcommand function as it replies with an incomplete response:
--START READ SMS POSITION1--
Content:
AT+CMGR=1
+CMGR: "REC READ","+407245402XX","","17/06/29,10:
--END READ SMS POSITION1--
But, when I run it from a terminal, the AT+CMGR=1 replies with:
AT+CMGR=1
+CMGR: "REC READ","+40724540234","","17/06/29,10:03:06+12"
Salut
OK
As you can see the message body is not there + the time of the SMS is also incomplete.
Thank you!
GSMSerial
?delay()
function is making the serial buffer overflow. There is never any call to usedelay()
when reading from serial. The AT protocol has proper handshaking signals that you should use, such as looking for "OK". There is no need todelay()
while waiting for them, that's just silly.