ESP32. How to connect to local WiFi network with Arduino code

How to connect an ESP32 to the local WiFi network with Arduino code
Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on email
Share on whatsapp

The ESP-IDF Development Kit for ESP32 contains the WiFi class which provides all the tools needed to connect to the WiFi network. Unlike the ESP8266, the library has the same name as the original Arduino library. 

 

Operation is identical to the ESP8266WiFi library dedicated to ESP8266

Install the ESP-IDF SDK for ESP32 on IDE Arduino and PlatformIO

The WiFi library is installed at the same time as the kit for ESP32 development boards called ESP-IDF.

If you are new to ESP32 development boards you must first install the ESP-IDF development kit. Here are two tutorials to get started depending on your code editor

Follow the instructions in this tutorial for the Arduino IDE

And this one for PlatformIO (ideally with VSCode)

Different WiFi connection modes available

The WiFi library for ESP32 offers several modes of Wi-Fi connection. The source code is available on GitHub .

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

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

Be careful, in this mode the ESP32 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) ESP32 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 ESP32

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.

Arduino code to connect an ESP32 to the WiFi network

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 <WiFi.h> 

const char* ssid = "enter_your_ssid";           
const char* password = "enter_your_password"; 

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

  WiFi.begin(ssid, 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 WiFi library is very simple. You just need to know the identifier of the WiFi network to which you want to connect the ESP32 module as well as the password. The WiFi.begin() method takes two parameters which are the network ID and the password

WiFi.begin(ssid, 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 when exiting standby.
  • 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.

Assign a fixed IP address to an ESP32

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.

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

If your project absolutely needs to be connected to the WiFi network in order to function, it is not preferable to put the ESP32 on standby and to regularly try to reconnect. This way we will not drain the battery unnecessarily.

Create a new sketch and paste the code below.

#include <Arduino.h>  
#include <WiFi.h>

const char* ssid = "enter_your_ssid";           
const char* password = "enter_your_password";  
#define wifi_max_try 10             // Number of try
#define duration_deep_sleep 10      // Sleep until next try

void print_wakeup_reason(){
  esp_sleep_wakeup_cause_t wakeup_reason;

  wakeup_reason = esp_sleep_get_wakeup_cause();

  switch(wakeup_reason)
  {
    case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
    case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
    case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
    case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
    case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
    default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
  }
}

void print_wifi_error(){
  switch(WiFi.status()) 
  {
    case WL_IDLE_STATUS : Serial.println("WL_IDLE_STATUS"); break;
    case WL_NO_SSID_AVAIL : Serial.println("WL_NO_SSID_AVAIL"); break;
    case WL_CONNECT_FAILED : Serial.println("WL_CONNECT_FAILED"); break;
    case WL_DISCONNECTED : Serial.println("WL_DISCONNECTED"); break;
    default : Serial.printf("No know WiFi error"); break;
  }
}

void setup()
{
  Serial.begin(115200);
  Serial.println();
  
  //Explain ESP2 wakeup reason
  print_wakeup_reason();
  
  // Try connect WiFi network
  WiFi.begin(ssid, password);

  Serial.print("Connecting");
  int count_try = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    count_try++;    // Increase try counter
    if ( count_try >= wifi_max_try ) {
      // Sorry but wifi is not available 
      Serial.println("\n");
      Serial.println("Impossible to establish WiFi connexion");
      
      print_wifi_error();
      Serial.println("Sleep a little and retry later, bye");
      
      // Set the wakeup 
      esp_sleep_enable_timer_wakeup(duration_deep_sleep * 1000000);
      // And ask processor to sleep now 
      esp_deep_sleep_start();
    }
  }
  Serial.println();

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

void loop() {
   
}

Unlike the ESP8266, there is no special circuit required to put the processor to sleep. Different standby modes are available. Everything is explained in detail in this article

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 is equal to (or exceeds) the number of attempts, a wakeup is programmed using the esp_sleep_enable_timer_wakeup(duration) method .

esp_sleep_enable_timer_wakeup(duration_deep_sleep * 1000000);

The sleep time is specified in microseconds. 1 second = 1,000,000 microseconds

And we ask the processor to fall asleep (Zzzz)

esp_deep_sleep_start();

The WiFi.status() method of the ESP-IDF SDK allows you to know the status of the WiFi connection at any time

  • WL_IDLE_STATUS during connection
  • WL_CONNECTED the connection is established
  • WL_NO_SSID_AVAIL no access point specified in the list is available
  • WL_CONNECT_FAILED connection failure. Probably the password is wrong or MAC address filtering has been set up on the router.
  • WL_DISCONNECTED disconnected

Finally, the esp_sleep_get_wakeup_cause() method allows you to find out the last cause of wakeup using the following constants:

  • ESP_SLEEP_WAKEUP_TIMER Timer, timer
  • ESP_SLEEP_WAKEUP_TOUCHPAD touch key
  • ESP_SLEEP_WAKEUP_EXT0 ou ESP_SLEEP_WAKEUP_EXT1
  • ESP_SLEEP_WAKEUP_ULP awakened by the ULP co-processor
  • ESP_SLEEP_WAKEUP_GPIO awakened by GPIO
  • ESP_SLEEP_WAKEUP_UART woken up by serial port

To do this, you just need to call the print_wakeup_reason() method when necessary to find out the origin of the wake-up call.

WiFiMulti library, let the ESP32 choose its WiFi network

To end the tutorial, the WiFiMulti library allows you to define several WiFi networks and leaves the choice to the ESP32 to connect to the network according to the availability and the strength of the signal.

Here is an example of code to test the WiFiMulti library. The operation is identical to that of the ESP8266.

#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>

WiFiMulti wifiMulti;

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

    wifiMulti.addAP("network1", "pwd1");
    wifiMulti.addAP("network2", "pwd2");

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

void loop()
{
    if(wifiMulti.run() != WL_CONNECTED) {
        Serial.println("WiFi not connected!");
        delay(1000);
    }
}

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

WiFiMulti wifiMulti;

We add the different access points in a list using the wifiMulti.addAP() class

wifiMulti.addAP("network1", "pwd1");
wifiMulti.addAP("network2", "pwd2");

Finally, we open the connection with the wifiMulti.run() method.

wifiMulti.run()

We have the same keys to test the correct functioning of the connection:

  • WL_CONNECTED the connection is established
  • WL_NO_SSID_AVAIL no access point specified in the list is available
  • WL_CONNECT_FAILED connection failure. Probably the password is wrong or MAC address filtering has been set up on the router.
  • WL_DISCONNECTED disconnected

Projects and tutorials

Other projects and tutorials on connected objects that use a WiFi connection

Updates

22/09/2020 Publication of the article

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!

We will be happy to hear your thoughts

      Leave a Reply

      DIY Projects