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?