When sending the esp a cmd it's important to allow it to complete before sending it another. I call a routine that looks for a string returned by the esp to indicate it is in a state ready for the next cmd. It times out if it doesn't see the expected string. See waitcmd().
Here is the code i'm using to setup an AP and also to connect to wifi and setup as a server:
int waitcmd(char *s, unsigned short timeout) {
unsigned long tm=millis();
while( 1 ) {
if( millis() - tm >= timeout ) {
Serial.println(F("Timed Out"));
return 0;
}
if (espSerial.find(s)) {
Serial.println(s);
return 1;
}
}
}
void access_point() {
Serial.println(F("SETUP ACCESS POINT"));
Serial.println(F("AT+RST"));
espSerial.println(F("AT+RST"));
waitcmd("thinker.com",10000);
Serial.println(F("AT+CWMODE=2"));
espSerial.println(F("AT+CWMODE=2"));
waitcmd("OK",1000);
Serial.println(F("AT+CIPMUX=1"));
espSerial.println(F("AT+CIPMUX=1"));
waitcmd("OK",1000);
Serial.println(F("AT+CWSAP=\"esp826605\",\"12345678\",1,0"));
espSerial.println(F("AT+CWSAP=\"esp826605\",\"12346785\",1,0"));
waitcmd("OK",1000);
Serial.println(F("AT+CIFSR"));
espSerial.println(F("AT+CIFSR"));
}
int server() {
int cnt=0;
Serial.println(F("SETUP SERVER"));
Serial.println(F("AT+RST"));
espSerial.println(F("AT+RST"));
cnt+=waitcmd("thinker.com",10000);
Serial.println(F("AT+CWMODE=1"));
espSerial.println(F("AT+CWMODE=1"));
cnt+=waitcmd("OK",500);
Serial.println(F("AT+CWJAP=\"xxxxx\",\"xxxxxx\""));
espSerial.println(F("AT+CWJAP=\"xxxxx\",\"xxxxxx\""));
cnt+=waitcmd("OK",10000);
Serial.println(F("AT+CIPMUX=1"));
espSerial.println(F("AT+CIPMUX=1"));
cnt+=waitcmd("OK",500);
Serial.println(F("AT+CIPSERVER=1,8000"));
espSerial.println(F("AT+CIPSERVER=1,8000"));
cnt+=waitcmd("OK",500);
Serial.println(F("AT+CIPSTO=15"));
espSerial.println(F("AT+CIPSTO=15"));
cnt+=waitcmd("OK",500);
Serial.println(F("AT+CIFSR"));
espSerial.println(F("AT+CIFSR"));
return cnt;
}