Connect ESP32 to WiFi

Connect ESP32 to WiFi

Connecting to WiFi with your ESP32 board is a basic feature in many projects, yet the code is lengthy, repetitive and prone to errors. Unless you install the esptoolkit library.

To connect to a WiFi network you've probably used the code below in the past:

WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

// this can get stuck!
while (WiFi.status() != WL_CONNECTED) {
  Serial.print('.');
  delay(1000);
}

As innocent as it looks, this code have several drawbacks:

  1. it is lengthy (6 lines of code)
  2. it is repetitive (you copy-paste from one project to another)
  3. it can remain stuck in a endless loop if the connection never succeeds

While 1) and 2) may be of little interest for you, the stuck problem is a real problem that you must take into account in every project. Copy-pasting from random websites on the web will instead leave you uncovered.

Using the esptoolkit library

If you installed the esptoolkit library from the Arduino Library Manager (if you didn't already, do it now!), you have your back covered out of the box. The bare minimum code to connect your board to a WiFi network (apart from the includes) is a single line:

#include <esptoolkit.h>
#include <esptoolkit/wifi.h>

wifiConn(ssid, pass);

This single line has a built-in timeout of 8 seconds: if the connection can't be established, your program can handle it gracefully. Below there are listed a few configurations and advanced uses of the wifiConn utility.

Custom timeout

By default, if the connection doesn't succeed in 8 seconds, the function will return a falsy value. You can customize the timeout with the code below.

// increase the timeout to 10 seconds
wifiConn(ssid, pass, wifiConn.Timeout("10s"));

Retries

Sometimes the ESP32 needs to retry a couple times before establishing the connection if the WiFi signal is not really strong or the board has a weak antenna. You can set the number of retries with the code below.

// retry 2 more times to connect (3 in total)
wifiConn(ssid, pass, wifiConn.Retry(2));

// you can mix with timeout, too
wifiConn(ssid, pass, wifiConn.Timeout("10s"), wifiConn.Retry(2));

Check success

To check if the connection succeeded, you can test the wifiConn object directly.

// try to connect
wifiConn(ssid, pass);

if (wifiConn) {
    Serial.print("WiFi is connected. IP: ");
    Serial.println(wifiConn.ip);
}
else {
    Serial.print("Can't connect to WiFi. Reason: ");
    Serial.println(wifiConn.reason());
}

Abort on fail

In the early steps of development, you may not be interested in continuing the program execution if a connection can't be established. You can try to connect to WiFi and abort the program (loop endlessly with an error message) with the following code.

// try to connect
// endlessly print the error message on failure
wifiConn(ssid, pass).raise();

// here the connection succeeded

Complete example

/**
 * Utilities to connect to a WiFi network
 *
 * Set Tools > Core Debug Level > Info
 */
#include <esptoolkit.h>
#include <esptoolkit/wifi.h>


void setup() {
    Serial.begin(115200);
    ESP_LOGI("APP", "Connect to WiFi example");

    // try to connect
    // default timeout is 8 seconds
    // default retries is 0
    wifiConn("SSID", "PASSWORD");

    if (wifiConn) {
        // we are connected to WiFi, print IP address
        ESP_LOGI("APP", "Connected to WiFi with IP %s", wifiConn.ip.c_str());
    } else {
        // connection didn't succeded
        ESP_LOGE("APP", "Can't connect to WiFi");
    }

    // you can configure the connection timeout and retries
    // since these arguments are optional, you use
    // named arguments (you can re-order them as you like).
    // I vastly prefer this style instead of wifiConn("SSID", "PASS", "8s", 2)
    // "What's 8s? What does 2 stand for?"
    // if only C++ had named arguments like Python...
    wifiConn("SSID", "PASSWORD", wifiConn.Timeout("8s"), wifiConn.Retry(2));

    // you can abort if connection was not successful
    wifiConn("BAD SSID", "BAD PASSWORD").raise();
}

void loop() {
}