ESP8266. How to connect to the WiFi network (ESP8266WiFi and ESP8266WiFiMulti)

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on email
Share on whatsapp

The ESP8266WiFi library is an adaptation of the Arduino standard library for ESP8266 modules made by Espressif. It is super simple to use and a few lines of code are enough to establish a WiFi connection from the microcontroller. The difficulty lies more in the multitude of existing libraries. ESP8266WiFi, ESP8266wifi, ESP8266WiFiMulti, ESP8266HTTPClient … Difficult to navigate when you start.

 

In this tutorial, we will learn how to simply connect to a WiFi network with an ESP8266 using the standard library. We will also see what the other libraries mentioned above are used for.

ESP8266WiFi / ESP8266wifi, the confusion!

If you are new to ESP8266 modules, you have undoubtedly encountered these two libraries which have a very similar name in the many tutorials offered on the internet. The difference is subtle – wifi in lower case – but can quickly cause problems, especially when starting out.

ESP8266WiFi

ESP8266WiFi is the “official” development kit library for ESP8266. The library is installed at the same time as the ESP8266 SDK from the board manager.

The library comes with many examples. The GitHub repository can be found here .

The library is very well documented by Espressif.

This is the standard library for ESP8266 modules developed by Espressif, the SoC manufacturers. It is preferable to use this library in priority because it is updated regularly.

ESP8266wifi

ESP8266wifi is an equivalent library developed by Jonas Ekstrand available on GitHub . It is not available from the library manager. It will have to be installed manually by unzipping the repository in the libraries directory of the Arduino IDE. Jonas Ekstrand’s library is much more complete than the original library.

This library combines several functions. It allows you to manage the ESP8266 as an access point, to monitor the arrival of messages, to manage the automatic re-connection … The last update dates from 2017. It is preferable to avoid it.

Here, we will use the adaptation of the Arduino ESP8266WiFi library .

Different WiFi connection modes available

ESP8266 is a very complete library that offers several modes of Wi-Fi connection

Station Station mode (STA) is used to connect the ESP module to a Wi-Fi access point. This is the default mode.

Access Point transforms the ESP8266 into an access point (AP), i.e. other devices can connect to the ESP8266. This operating mode is also called a software access point (soft-AP).

Be careful, in this mode the ESP8266 is not connected to the internet. In this mode, we create an HTML page that will allow you to enter parameters for connection to a WiFi network or whatever else you want. This is for example the mode used by ESP Easy Mega (or ESP Easy).

espeasy mega esp32 wifi configuration ap mode

We can use this mode in different cases

  • To develop home automation accessories or connected objects without “hard” compiling the connection parameters to the WiFi network. To do this, I advise you instead to use the WiFiManager library which is the specialty.
  • Exchange data between two (or more) ESP8266 modules without the need for a WiFi router.

Other modes: client, server, UDP

Client is not a connection mode in the strict sense. Clients are created which can access the services provided by a server in order to send, receive and process data.

Server allows to start a small web server on the ESP8266

UDP is used to send and receive UDP (User Datagram Protocol) messages. UDP uses a simple “send and forget” transmission model with no guaranteed delivery, ordering, or duplicate protection. On the other hand, the data transmission is ultra-fast. We could for example use UDP to develop a WiFi remote control to control a drone, robotic arm, RC car.

Install the ESP8266 SDK

If you are new to ESP8266 development boards, you must first install the ESP8266 SDK on the Arduino IDE.

How to connect to a WiFi network with the ESP8266WiFi library

Here is an example of code that allows you to connect to the local WiFi network.

Before uploading the code, replace the Wi-Fi network identifier enter_your_ssid and the password enter_your_password in the code

#include <ESP8266WiFi.h> 

void setup()
{
  Serial.begin(115200);
  Serial.println();

  WiFi.begin("enter_your_ssid", "enter_your_password");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {}

How does the code work?

Using the ESP8266WiFi library is very simple. You just need to know the identifier of the WiFi network to which you want to connect the NodeMCU module as well as the password. The WiFi.begin () method takes two parameters which are the network ID and the password

WiFi.begin("enter_your_ssid", "enter_your_password");

The WiFi.status method allows you to know the connection status at any time. The method returns a code between 0 and 6 to which corresponds a constant whose meaning here is

  • 0: WL_IDLE_STATUS when Wi-Fi is changing state
  • 1: WL_NO_SSID_AVAIL if the configured SSID cannot be reached
  • 3: WL_CONNECTED after connection is established
  • 4: WL_CONNECT_FAILED if the password is incorrect
  • 6: WL_DISCONNECTED if the module is not configured in station mode

In most, it is sufficient to connect to power on in the setup ()

while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
}

Notes:

  • This code also works very well in the code where the ESP8266 module is put into deep sleep.
  • This code does not provide for the module to be put on standby if the WiFi network is not available, which risks draining the battery.

To correctly manage the automatic re-connection in case of loss of WiFi signal, I advise you to turn to the WiFiManager library which automatically manages the re-connections.

Put the ESP8266 to sleep (deep-sleep) if the WiFi network is not available

Rather than remaining in an infinite loop while waiting for the WiFi network to be available, it is preferable to put the ESP8266 module to sleep for a certain period of time and start again later.

Create a new sketch and paste the code below

#include <ESP8266WiFi.h>  

const char* ssid      = "enter_your_ssid"; 
const char* password  = "enter_your_network_password"; 
#define wifi_max_try  10 // Nombre de tentative de connexion
#define duration_deep_sleep 10   // mettre en veille 10 secondes si le reseau wifi n est pas disponible

void setup()
{
  Serial.begin(115200);
  Serial.println();

  WiFi.begin(ssid, password);

  Serial.print("Connecting");
  int count_try = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    count_try++;
    if ( count_try >= wifi_max_try ) {
      Serial.println("\n");
      Serial.println("Impossible to establish WiFi connexion, sleep a little !");
      ESP.deepSleep(duration_deep_sleep * 1000000);
    }
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
}

To activate the deep sleep mode of the NodeMCU, you must connect the RST pin to the D0 pin with a jumper or a wire.

Warning, disconnect the RST and D0 pins before you can upload the code.

 

wemos d1 mini activate deep-sleep mode esp8266

We activate the deep-sleep mode of the ESP8266 by connecting the RST and D0 pins

How does this code work

We add a counter which is incremented at each passage in the while (here every 500ms)

int count_try = 0;

As soon as the counter equals (or exceeds) the number of attempts, we activate standby by calling the ESP.deepsleep () method. The sleep time is shown in microseconds. 1 second = 1,000,000 microseconds

if ( count_try >= wifi_max_try ) {
  ESP.deepSleep(duration_deep_sleep * 1000000);

}

ESP8266WiFiMulti library

Finally, the last interesting library to know, the ESP8266WiFiMulti library . It allows you to define several WiFi networks and leaves the choice to the ESP8266 to connect to the network depending on its availability and signal strength. It is a component of the ESP8266WiFi standard library .

It is very easy to use. We start by creating a wifiMulti object.

ESP8266WiFiMulti wifiMulti;

The different access points are added in a list using the class wifiMulti.addAP()

wifiMulti.addAP("ssid1","psk1");
wifiMulti.addAP("ssid2","psk2");

We open a connection with the run() class.

wifiMulti.run()

Several keys are available to test the correct operation of the connection:

  • WL_CONNECTED: Connection is established
  • WL_NO_SSID_AVAIL: no access point specified in the list is available
  • WL_CONNECT_FAILED: Connection failed. Probably the password is bad or a filtering by MAC address has been set up on the router.

To see what happens, you can add this option in the setup()

Serial.setDebugOutput(true);

Assign a fixed IP address to an ESP8266 or ESP01 board

When developing an object connected to WiFi with an ESP32, ESP8266 or ESP-01 (or any other microcontroller for that matter), it is much more practical to assign a fixed IP address. We can thus always connect to the object on the local network even in the event of a change of router or internet box.

Everything is explained in detail in this tutorial.

ESP8266HTTPClient library

As you saw in the previous example, you send a message to the server using the function client.print () where you pass a string containing the HTTP command. It is effective but not necessarily super friendly to use especially if one is not a pro of the Web. To do something “cleaner” and more advanced, there is the ESP8266HTTPClient library. It is also an adaptation of an Arduino library (ArduinoHTTPClient) for the ESP8266. It is available from the Arduino IDE library manager.

We will therefore create an http object at the beginning of the sketch

HTTPClient http;

The url is constructed in exactly the same way as before.

String url = "/watchdog?command=watchdog&uptime=";
    url += String(millis());
    url += "&ip=";
    url += WiFi.localIP().toString();

Before sending the query we pass the parameters to the http object like this

http.begin(host,port,url);

We now have three distinct classes that correspond to the most traditional HTTP requests: GET (data request), POST (data sending) and PUT (file sending). Here we will make a GET request to simulate the reception of a response from the server

int httpCode = http.GET();

Each class returns a code to find out if the query was successful. The code complies with RFC7231 (source).

typedef enum {
    HTTP_CODE_CONTINUE = 100,
    HTTP_CODE_SWITCHING_PROTOCOLS = 101,
    HTTP_CODE_PROCESSING = 102,
    HTTP_CODE_OK = 200,
    HTTP_CODE_CREATED = 201,
    HTTP_CODE_ACCEPTED = 202,
    HTTP_CODE_NON_AUTHORITATIVE_INFORMATION = 203,
    HTTP_CODE_NO_CONTENT = 204,
    HTTP_CODE_RESET_CONTENT = 205,
    HTTP_CODE_PARTIAL_CONTENT = 206,
    HTTP_CODE_MULTI_STATUS = 207,
    HTTP_CODE_ALREADY_REPORTED = 208,
    HTTP_CODE_IM_USED = 226,
    HTTP_CODE_MULTIPLE_CHOICES = 300,
    HTTP_CODE_MOVED_PERMANENTLY = 301,
    HTTP_CODE_FOUND = 302,
    HTTP_CODE_SEE_OTHER = 303,
    HTTP_CODE_NOT_MODIFIED = 304,
    HTTP_CODE_USE_PROXY = 305,
    HTTP_CODE_TEMPORARY_REDIRECT = 307,
    HTTP_CODE_PERMANENT_REDIRECT = 308,
    HTTP_CODE_BAD_REQUEST = 400,
    HTTP_CODE_UNAUTHORIZED = 401,
    HTTP_CODE_PAYMENT_REQUIRED = 402,
    HTTP_CODE_FORBIDDEN = 403,
    HTTP_CODE_NOT_FOUND = 404,
    HTTP_CODE_METHOD_NOT_ALLOWED = 405,
    HTTP_CODE_NOT_ACCEPTABLE = 406,
    HTTP_CODE_PROXY_AUTHENTICATION_REQUIRED = 407,
    HTTP_CODE_REQUEST_TIMEOUT = 408,
    HTTP_CODE_CONFLICT = 409,
    HTTP_CODE_GONE = 410,
    HTTP_CODE_LENGTH_REQUIRED = 411,
    HTTP_CODE_PRECONDITION_FAILED = 412,
    HTTP_CODE_PAYLOAD_TOO_LARGE = 413,
    HTTP_CODE_URI_TOO_LONG = 414,
    HTTP_CODE_UNSUPPORTED_MEDIA_TYPE = 415,
    HTTP_CODE_RANGE_NOT_SATISFIABLE = 416,
    HTTP_CODE_EXPECTATION_FAILED = 417,
    HTTP_CODE_MISDIRECTED_REQUEST = 421,
    HTTP_CODE_UNPROCESSABLE_ENTITY = 422,
    HTTP_CODE_LOCKED = 423,
    HTTP_CODE_FAILED_DEPENDENCY = 424,
    HTTP_CODE_UPGRADE_REQUIRED = 426,
    HTTP_CODE_PRECONDITION_REQUIRED = 428,
    HTTP_CODE_TOO_MANY_REQUESTS = 429,
    HTTP_CODE_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
    HTTP_CODE_INTERNAL_SERVER_ERROR = 500,
    HTTP_CODE_NOT_IMPLEMENTED = 501,
    HTTP_CODE_BAD_GATEWAY = 502,
    HTTP_CODE_SERVICE_UNAVAILABLE = 503,
    HTTP_CODE_GATEWAY_TIMEOUT = 504,
    HTTP_CODE_HTTP_VERSION_NOT_SUPPORTED = 505,
    HTTP_CODE_VARIANT_ALSO_NEGOTIATES = 506,
    HTTP_CODE_INSUFFICIENT_STORAGE = 507,
    HTTP_CODE_LOOP_DETECTED = 508,
    HTTP_CODE_NOT_EXTENDED = 510,
    HTTP_CODE_NETWORK_AUTHENTICATION_REQUIRED = 511
}

It is therefore very easy to know if the message has been received by the server. The content of the message (payload) is retrieved using the http.getString() class.

if (httpCode) {
  if (httpCode == 200) {
    String payload = http.getString();
    Serial.println(payload);
  }
}

Here is the modified code based. The ESP8266 will look for the best WiFi network to connect to. During the idle phase, WiFi is switched off using the WiFi.disconnect() class.

/*
 * TCP/IP communication ESP8266HTTPClient
 * Copyright (C) 2017 http://www.projetsdiy.fr - https://www.diyprojects.io
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFiMulti.h>

const char* host = "192.168.1.33";
const int  port = 8080;
const int   watchdog = 5000;
unsigned long previousMillis = millis(); 

ESP8266WiFiMulti wifiMulti;
HTTPClient http;

void setup() {
  Serial.begin(115200);
  delay(10);

  // We start by connecting to a WiFi network
  wifiMulti.addAP("ssid1", "psk1");
  wifiMulti.addAP("ssid2", "psk2");

  Serial.println("Connecting Wifi...");
  if(wifiMulti.run() == WL_CONNECTED) {
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.print(WiFi.localIP());
  }
  Serial.setDebugOutput(true);
  
}

int value = 0;

void loop() {
  unsigned long currentMillis = millis();

  if ( currentMillis - previousMillis > watchdog ) {
    previousMillis = currentMillis;

    if(wifiMulti.run() != WL_CONNECTED) {
      Serial.println("!!");
    } else {  
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    
      String url = "/watchdog?command=watchdog&uptime=";
      url += String(millis());
      url += "&ip=";
      url += WiFi.localIP().toString();
      
      Serial.print("connecting to ");
      Serial.println(host);
      Serial.print("Requesting URL: ");
      Serial.println(url);
     
      http.begin(host,port,url);
      int httpCode = http.GET();
      if (httpCode) {
        if (httpCode == 200) {
          String payload = http.getString();
          Serial.println(payload);
        }
      }
      Serial.println("closing connection");
      http.end();
      WiFi.disconnect();
    }
  }
}

You can wait for a response from the server. If you are transmitting to a home automation server, there is a big change that it returns you a status: OK, minimum, you should receive a code reply 200 meaning that the message was correctly received by the server. You can imagine other treatments according to the answer: to put in a stack and to start again later, to delete the measure or to store it in a log, to add in a log the event and the error message (to facilitate the Focus), control the GPIO (flash a LED) …

Node.js test server to communicate with ESP8266

To test the different libraries, I propose you to quickly develop a small server Node.js. In the next tutorials, we will go further by setting up a complete communication with some domotic servers (Jeedom, Domoticz, Home Assistant). If you’re new to Node.js, follow this tutorial to install and discover Node.js

For this server, you will need to install the moment, express packages.

sudo npm moment express

Open a text editor and create a new file called server.js by pasting this code

/*
*   Serveur de test pour librairies ESP8266WiFi et ESP8266HTTPClient
*   Test server for ESP8266WiFi and ESP8266HTTPClient libraries
*   http://www.projetsdiy.fr - 2017
*/
var express = require('express');
var moment = require('moment');
var app = express();

app.get('/', function(req, res) {
  res.send('HTTP ESP8266 Test Server')
});

app.use('/watchdog', function (req, res, next) {
  var t = moment.duration(parseInt(req.param('uptime')), 'milliseconds')
  var _message = req.param('ip') + " uptime " + t.hours() + "h " + t.minutes() + "m " + t.seconds() +"s";
  console.log("watchdog from " + _message);
  res.send("You are alive!");
});

app.listen(8080);

Open the Terminal (or PowerShell on Windows). Move to the directory where you saved the server.js file and start the server with node server.js  or nodemon server.js  (nodemon restarts the server every time the files are changed).

For each message received, the server retrieves the data passed in parameters and constructs an information message which is then sent to the terminal.

serveur test communication tcp ip http esp8266wifi

SocketTest: a test server for

If you do not have the courage to get started with Node.js, you can opt for SocketTest which is a small program that starts a test server on your machine. You can retrieve it from Sourceforge here. SocketTest runs on macOS (start SocketTest.jar), Windows (SocketTest.exe), and Linux (SocketTest.sh).

 sockettest sourceforge test esp8266wifi

Go to the Server tab and enter the ip address of your machine. It is absolutely necessary to indicate the ip address of the machine on which SocketTest works so that it works.

Then start the server by clicking Start Listening. You will receive your first messages (depending on the send frequency set by the watchdog variable).

sockettest watchdog esp8266wifi

You can send a response to the ESP8266 by entering it in the message field and then clicking Send. For example here, I answered OK which appears in the console under S: OK. If you have opened the serial monitor on the Arduino IDE, you will see the received message. If you do not respond within the time specified in the program (here 5 seconds), you will get an error message (>>> Client Timeout!) Before the client disconnects.

Note. Replies sent by SocketTest are not received with the ESP8266HTTPClient library. To dig…

sockettst watchdog send response esp8266wifi client

You now know the 3 main libraries allowing to communicate an Arduino / ESP8266 program in TCP / IP using HTTP requests. We now have to put all this into practice on concrete cases. We will see in the next tutorials how to simply send temperature measurements (or anything else for that matter) to Jeedom, Domoticz and Home Assistant.

Version française

Click to rate this post!
[Total: 1 Average: 5]

Are you having a problem with this topic?

Maybe someone has already found the solution, visit the forum before asking your question
Ask your question

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on email
Share on whatsapp

Did you like this project ? Don't miss any more projects by subscribing to our weekly newsletter!

1 Comment
  1. Hi there, I’m new to the field, can you tell me where to start as I didn’t understand most of what you wrote ?

    Leave a Reply

    DIY Projects
    %d bloggers like this: