3

This is the code I uploaded in Arduino UNO:

#include<SoftwareSerial.h>
SoftwareSerial ESP(2,3); // RX, TX
//ESP RX-->3(UNO) TX-->2(UNO)

void setup() {
// Open serial communications and wait for port to open:

    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }

    Serial.println("Goodnight moon!");

    // set the data rate for the SoftwareSerial port
    ESP.begin(9600);

}

void loop() {
    if (ESP.available()) {
        char inData = ESP.read();
        Serial.println("Got reponse from ESP8266: ");
        Serial.write(inData);
    }

    ESP.write("AT\r\n"); //Normally ESP responds to AT command with "OK"
}

But ESP is not able to receive the AT command properly...sometimes it recieves A, sometime T. It then responds with garbage value. Though we are able to give command to ESP through Serial Monitor and it responds pretty well. But when trying to communicate through code, the communication is not OK.

sa_leinad
  • 3,218
  • 2
  • 23
  • 51

1 Answers1

4

The problem is in your loop() function. On each iteration, you will receive at most one character from the SoftwareSerial, while writing the same AT command again and again. As a result, your slave device (ie. ESP8266) will overflow its UART buffers, resulting in garbage being sent and received.

You should keep receiving data from the slave for as long as it has data:

while (ESP.available()) {
    char inData = ESP.read();
    Serial.println("Got response from ESP8266: ");
    Serial.write(inData);
}
sa_leinad
  • 3,218
  • 2
  • 23
  • 51
Dmitry Grigoryev
  • 1,288
  • 11
  • 31