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 espx library.

Using the ESPx library

This project makes use of the espx library. The espx library for Arduino defines a set of abstractions that make the ESP32 features easily accessible with few lines of code. Some of the features are:

  • WiFi connection (wifix)
  • HTTP client (httpx)
  • JSON generator (jsonx)
  • Camera manipulation (camx)

Installation

Install the latest version of espx from the Arduino Library Manager.

The code examples on this page have been tested with version 1.0.2: if you get weird errors about missing variables or method, double check that you have the correct version.

If the error persists, please open an issue on GitHub.

The bad way to connect to WiFi

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.

The ESPx way

If you installed the espx 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 <espx.h>
#include <espx/wifix.h>

wifix(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 wifix 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
wifix(ssid, pass, wifix.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)
wifix(ssid, pass, wifix.Retry(2));

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

Check success

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

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

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

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
wifix(ssid, pass).raise();

// here the connection succeeded

Complete example

/**
 * Utilities to connect to a WiFi network
 */
#include <espx.h>
#include <espx/wifix.h>


void setup() {
    delay(1000);
    Serial.begin(115200);
    Serial.println("Wifix example: connect to WiFi");

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

    if (wifix) {
        // we are connected to WiFi, print IP address
        Serial.println("Connected!");
        Serial.print("IP: ");
        Serial.println(wifix.ip);
    } else {
        // connection didn't succeed
        Serial.println("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 wifix("SSID", "PASS", "8s", 2)
    // "What's 8s? What does 2 stand for?"
    // if only C++ had named arguments like Python...
    wifix("SSID", "PASSWORD", wifix.Timeout("8s"), wifix.Retry(2));

    // while in dev mode,
    // you can abort if connection was not successful:
    // raise() will enter an endless loop
    wifix("BAD SSID", "BAD PASSWORD").raise();
}

void loop() {
}
Next: ESP32 Multi - threading