Skip to content

Instantly share code, notes, and snippets.

@recyclerobot
Last active March 8, 2021 00:02
Show Gist options
  • Save recyclerobot/0a11aeea8f0a84a4e992 to your computer and use it in GitHub Desktop.
Save recyclerobot/0a11aeea8f0a84a4e992 to your computer and use it in GitHub Desktop.
int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout){
uint8_t x=0, answer=0;
char response[100];
unsigned long previous;
memset(response, '\0', 100); // Clean response buffer
delay(100); // Delay to be sure no passed commands interfere
while( Serial.available() > 0) Serial.read(); // Wait for clean input buffer
Serial.println(ATcommand); // Send the AT command
previous = millis();
// this loop waits for the answer
do{
// if there are data in the UART input buffer, reads it and checks for the asnwer
if(Serial.available() != 0){
response[x] = Serial.read();
x++;
// check if the desired answer is in the response of the module
if (strstr(response, expected_answer) != NULL){
answer = 1;
}
}
// Waits for the answer with time out
} while((answer == 0) && ((millis() - previous) < timeout));
return answer;
}
@ingloriousbstrd
Copy link

The function is only receiving an inverted question mark as a response? Any advise on how to fix this please?

@tk5ep
Copy link

tk5ep commented Dec 16, 2017

I use this function in one of my projects since years and it works just fine for me and many others.
Your problem is somewhere else... Have you checked your serial speed ?

@peterwliu
Copy link

hello, when i see your code also i think this will work but, when i implement the code for example:
answer = sendATcommand("AT", "OK", 2000);

at serial monitor only AT and keep repeating , there's no "expected_answer" what am i doing wrong?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment