improving code for ESP8266

Hi, Learning to work with ESP8266, I feel that code I use from tutorials online are not to guarantee a stable connection. Many places in the tutorial codes (I made a post based on them in this forum here) have a pattern that makes me first priority question. The pattern is this:

  1. issue an AT command with Serial.println()
  2. issue a delaty(1000) or any other time constant
  3. check for a Serial.find(), like this:
  sser.println("AT+CWMODE=1");
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";

  Serial.println(cmd);
    sser.println(cmd);
  delay(2000);
  
  if(sser.find("OK")){
    Serial.println("OK, Connected to WiFi.");
    return true;
  }else{
    Serial.println("Can not connect to the WiFi.");
    return false;
  }

I would like to ask if there is a better waiting strategy, so that if the time delay is less or more than needed and if we missed the serial chars in search, the command sending could be repeated.

Is a while(1) with repeatedly calling another method is the best practices please?

The .find() method uses the timeout set by .setTimeout() (default is 1000 milliseconds). Rather than delaying two seconds before looking for input you can speed things up by setting a two second timeout:

    sser.println(cmd);
  sser.setTimeout(2000);
  if(sser.find("OK")) {

would like to ask if there is a better waiting strategy, so that if the time delay is less or more than needed and if we missed the serial chars in search, the command sending could be repeated.

Do the returned data packets have an end of data packet marker?

zoomkat: Do the returned data packets have an end of data packet marker?

The other end point of communication is standard HTTP protocol, i.e. I did not program anything with special protocol.

The "OK" being searched in the code is an effort to get the "SEND OK" that must be returned if a successfull TCP connection has been made.

I still don't know how I can make Arduino aware of: 1. need to retry in case the connection is not established by ESP8266 2. lost ESP8266 wifi connection that was previously established in the "proper" way.

Perhaps this is the worst problem that could ever be: the disability of collecting correct knowledge of the state of the system!

Please give ideas.

ardutry: I still don't know how I can make Arduino aware of: 1. need to retry in case the connection is not established by ESP8266 2. lost ESP8266 wifi connection that was previously established in the "proper" way.

  • Error when trying to establish the connection to WiFi or when trying to connect to the server.
  • Error when trying to write to the server or timeout when waiting for response from the server.

You will have to decide if you want to re-try forever or go back to some previous step such as all the way back to establishing a WiFi connection. If there is some way to reset the ESP8266 hardware you may want to do that, too.