This seems like a topic that has a lot of cover on the internet, and many sites have code snippets for connecting ESP8266 to WiFi networks, however, after using a lot of ESP8266 in my projects I want to recommend my own take on how to achieve this.

As I wrote before, I’ve used many ESP8266 microcontrollers in my home automation projects: they are cheap, reliable, and are Arduino compatible, which makes them perfect for any project, even if it’s not a network centered one.

The method I used to connect those microcontrollers to WiFi was pretty much as seen on every code snippet available on the internet.
For instance, the wide speared solution is to set up WiFi.begin ( "SSID", "PASSWORD");  the void setup()  function of every sketch in Arduino.
While this code certainly works, I discovered that sometimes it can be not reliable: the connection might drop and not return, power outages can disconnect it and sometimes if you want to connect to another network, or change the password, it will fail.

So here are my best practices to connect ESP8266 to WiFi networks.

Move WiFi.Begin to void loop()

ESP8266 has a mechanism that automatically reconnects if the connection is dropped, and while this is probably a good solution for some projects, I think it’s better to control this process instead of being controlled by it.
As I mentioned in the paragraph before, this mechanism can sometimes cause problems.
The way I see things, connecting to a WiFi network is not a single task to be done only when the microcontroller boots up, but an ongoing process of making sure you are connected all time.
That’s why I think that connecting should be done in the main loop of the Arduino sketch.

In the code below, I demonstrate how I connect to WiFi networks, and over the time I’ve used it with various types of microcontroller it worked perfectly.

Use WiFi Events to detect the WiFi State

Another important factor is knowing the state of your connection in your sketch’s code. Your code should take into consideration if your chip is connected, connecting or disconnected and do actions accordingly. That way, you can control what to do if a connection drops: maybe try to reconnect, order your chip to sleep for a while in order to save energy or perhaps try to login to a backup WiFi network.

Adding handlers to WiFi events is done in the setup portion of your sketch like so:

This, for example, fires up the “onConnected” method when the chip has passed the password check of the connection process.
Please note: this event only detects the beginning of the association process, and at this point, the microcontroller still has no ability to send and receive data and it is without an IP address.
“onConnected” method is a function that you need to implement in your sketch (example below).

This, on the other hand, fires “onGotIP” method, when the chip gets its final step of the connection, getting is network IP address.

Use WiFi.disconnect()

ESP8266 sometimes remembers its last connected network, which as mentioned can cause problems, such as trying to connect to a new network, or if you changed your password.
I think it’s best practice to clear the chip’s WiFi cache, and that’s exactly what this command does.

Connect in a Non-Blocking way

Another thing that I recommend while programming a sketch is to avoid using Sleep() commands. These can hang the device and cause a lot of problems. Always try using non-blocking technics when possible.
In our case, we wait for a connection in a loop that executes only if a predetermined time has passed, and thus avoiding the sleep command.

In the example above, the code waits for a connection, and if it doesn’t achieve it in a predetermined time, it tries to reconnect.

 

Full code of connecting ESP8266 to WiFi – my best practice

Hope you enjoyed this tutorial post.
Let me know in the comments below your thoughts and suggestions.

 

 

4 comments

  1. Pingback: ESP8266 WiFi events list with Arduino | Roei's Tips Stream

  2. robin

    You forgot a few declarations in the full code, insert at line 18 or so:
    WiFiEventHandler mConnectHandler, mDisConnectHandler, mGotIpHandler;
    unsigned long previousMillis;

    Otherwise, thanks for the intro!

    cheers,
    Robin.

  3. Pingback: HTTP connection refused on Arduino ESP8266 | Roei's Tips Stream

  4. mist.weg

    Hi Roei,
    thank-you for sharing your expierence. Using the example I didn’t manage to change the hostname. What is wrong in my code, how can I change hostname from default to a more meanigfull one?
    regards Joschen
    ————————————————–
    /*
    https://roei.stream/2018/01/21/connecting-esp8266-microcontroller-to-a-wifi-network/
    */
    #include
    #include
    #include

    const char *ssid2 = “xxx”;
    const char *password = “yyy”;
    String newHostname = “waterPump_Jens”; // set to identify on WLAN

    WiFiEventHandler mConnectHandler, mDisConnectHandler, mGotIpHandler;
    unsigned long previousMillis;
    unsigned long currentMillis;

    const int led = 2;
    int leds = 0 ;
    int reqConnect = 0 ;
    int isConnected = 0 ;
    const long interval = 500;
    const long reqConnectNum = 15; // number of intervals to wait for connection

    void onConnected(const WiFiEventStationModeConnected& event){
    Serial.println ( “Connected to AP.” );
    isConnected = 1;
    }

    void onDisconnect(const WiFiEventStationModeDisconnected& event){
    Serial.println ( “WiFi On Disconnect.” );
    isConnected = 0;
    digitalWrite ( led, 1 );
    }

    void onGotIP(const WiFiEventStationModeGotIP& event){
    Serial.print ( “Got Ip: ” );
    isConnected = 2;
    digitalWrite ( led, 0 );
    Serial.println(WiFi.localIP());
    }

    void setup() {
    Serial.begin(115200);
    delay(200);
    Serial.printf(“\n\nCompiled from: %s at: %s %s”, __FILE__, __DATE__, __TIME__);
    Serial.println(“\nRoai_example”);

    WiFi.disconnect() ;
    WiFi.persistent(false);

    pinMode ( led, OUTPUT );
    digitalWrite ( led, 0 );
    mConnectHandler = WiFi.onStationModeConnected(onConnected);
    mDisConnectHandler = WiFi.onStationModeDisconnected(onDisconnect);
    mGotIpHandler = WiFi.onStationModeGotIP(onGotIP);
    }

    void loop() {
    if (WiFi.status() != WL_CONNECTED && reqConnect > reqConnectNum && isConnected = interval) {
    previousMillis = currentMillis;
    reqConnect++ ;
    if (isConnected < 2){
    digitalWrite ( led, leds );
    leds = (leds + 1) % 2 ;
    }
    }

    if (isConnected == 2) {
    //Do here what is needed when the ESP8266 is connected
    }

    }

Leave a comment