Kalreg
Kalreg

Reputation: 1012

arduino and esp8266 - how to get AT command response into variable

So i have my arduino and esp8266 wifi module. Everything is connected correctly and sending data to arduino lets me control connection via AT commands. My skletch looks like this:

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop()
{

  if (Serial.available() > 0) {
    char ch = Serial.read();
    Serial1.print(ch);
  }
  if (Serial1.available() > 0) {
    char ch = Serial1.read();
    Serial.print(ch);
}

The code above lets me send commands and see response from esp. In spite of different response time and different answers I need to store response in variable when wifi module such a response creates. Unfortunatelly I cant do this because of Serial1.read() grabing only one char from Serial1.available() buffer instead of full buffer.

I tried approach like this:

  if (Serial1.available() > 0) {
      while (Serial1.available() > 0) {
        char ch = Serial1.read();
        Serial.print(ch);
        response = response.concat(ch);
       }
    } else {
      String response = "";
    }

So as long ther eis something in a buffer it is sent to response variable that concatens last char with itself. And later it can be searched via indefOf command for "OK" marker or "ERROR". But that doesnt work as intended :( It for example may print my variable 8 times (dont know why). I need full response from wifi module to analaze it for example to make the led on in my arduino board if proper command comes from wifi network, but also send some data if i press button on arduino to the network. Any ideas would be appreciated.

Kalreg.

Upvotes: 0

Views: 2598

Answers (1)

Blurry Sterk
Blurry Sterk

Reputation: 1607

Try this rather:

String response = ""; // No need to recreate the String each time no data is available
char ch; // No need to recreate the variable in a loop

while (Serial1.available() > 0) {
  ch = Serial1.read();
  response = response.concat(ch);
}

// Now do whatever you want with the string by first checking if it is empty or not. Then do something with it

Also remember to clear the buffer before you send a command like I suggested in your previous question: how to get AT response from ESP8266 connected to arduino

Upvotes: 1

Related Questions