1

I am interfacing a GSM modem via Arduino at Serial port 2.

I have seen that responses fron GSM modem are subject to time. Sometime its response are fast and sometime it are slow. I have a code like below which checks for response from GSM modem based upon a user configurable timeout value:

sendATcommand(str_at_cmd, str_ok, 500);


int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout)
{
    uint8_t x=0;
    char response[100];
    unsigned long previous;
    int answer = 0;
    memset(response, '\0', 100);
    answer = 0;;
    delay(100);
    ClearSerialData(); // read and flush all data
    debug_println(ATcommand);
    Serial2.println(ATcommand);
    delay(200);
    x = 0;
    previous = millis();
    do {
       if(Serial2.available() > 0){    
       response[x] = Serial2.read();
       delay(100);
       debug_print(response[x]);
       response[++x] = '\0';
       if (strstr(response, expected_answer) != NULL)    
       {
           debug_print("\nAnswer Mathced");
           answer = 1;
       }
       }
    }while((answer == 0) && ((millis() - previous) < timeout));   
    debug_println("\nReturning from AT Command");
    return answer;
}

I was never able to set the correct timeout value - as at random test it failed once or twice and not received 100% success.

My question if I change the code like below

while(Serial2.available() > 0){    
   response[x] = Serial2.read();
   delay(100);
   debug_print(response[x]);
   response[++x] = '\0';
   if (strstr(response, expected_answer) != NULL)    
   {
       debug_print("\nAnswer Mathced");
       answer = 1;
   }
}

So when does Serial2.available() method returns <= 0 value. Is my above code correct - this way I overcome the timeout issue and all my GSM responses are being read - are there scenarios that I will end up in infinite loop?

  • You will end up in an infinite loop if you never receive the expected response. If you are receiving other responses, or noise, you could easily overflow your array, so you should put a hard limit on the growth of x. – Chris Stratton Feb 13 '15 at 16:42
1

Your code is flawed in that you are waiting a fixed time, and then hoping that the entire response will arrive quickly. Personally I would send the query, and then exit the function. Test for incoming data in your main loop, and process it when it is all received. Techniques described here: http://www.gammon.com.au/serial

The whole thing should be able to be written without delay().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.