ESP8266 Software Serial

#include "SoftwareSerial.h"

SoftwareSerial esp8266(2, 3); // RX, TX

void setup()
{
  Serial.begin(115200); // serial port used for debugging
  esp8266.begin(115200);  // your ESP's baud rate might be different
}

void loop()
{
  
  if(esp8266.available())  // check if the ESP is sending a message
  {
    int i=0;
    char cmd[5];
    while(esp8266.available())
    {
      char c = esp8266.read();  // read the next character.

      cmd[i]=c;
      i++;
      Serial.write(c);  // writes data to the serial monitor
    }
    Serial.print("Serial1 aval");\
    Serial.print(cmd);
    if(cmd[0]=='o'&&cmd[1]=='n')
    {
    Serial.print("On is typed");
    digitalWrite(9, HIGH);
    }
  }

  if(Serial.available())
  {
    delay(10);  // wait to let all the input command in the serial buffer

    // read the input command in a string
    String cmd = "";
    while(Serial.available())
    {
      cmd += (char)Serial.read();
    }
    // send to the esp8266
    esp8266.println(cmd); 
  }
}

when i type AT in console it is not detected ,also sometimes it displays random characters.
I want a code to receive serial which i will send by connecting to wifi through android app

ie. if i type "on" from mobile an led will turn on.
is the above code wrong ??

Software serial will NOT work at 115200. The fastest that I have been able to use the Software Serial library, reliably, is 38400. There are other libraries (Neosoftware serial) that may go faster, but probably not 115200. Your choices are to lower the ESP baud rate or use hardware serial to talk to the ESP and software serial (through a USB to TTL converter) to talk to the PC for trouble shooting ( you need to switch around to program the Arduino). Another way is to program the ESP using the Arduino IDE and the ESP Arduino core instead of using the AT commands.

What are you doing? It may be possible to do the whole project with just the ESP. The processor on the ESP is much faster than most Arduinos and has more flash and SRAM. The lack of pins can be overcome with external chips like I2C expanders and shift registers.

if i keep baud as 38400 random text is comming on console

rushic24:
if i keep baud as 38400 random text is comming on console

Did you reconfigure the ESP to communicate at that speed?