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

Содержание

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.

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.

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

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

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 ()

  • 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

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.

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)

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

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.

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

We open a connection with the run() class.

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()

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

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

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

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

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.

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.

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.

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

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.

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.


Источник: diyprojects.io