como-conectar-un-esp8266-a-una-red-wifi-modo-sta

How to Connect ESP32 to a WiFi Network (STA Mode)

  • 6 min

STA mode allows an ESP32 or ESP8266 to connect to an existing WiFi as just another device on the network.

One of the main strengths of the ESP family, and something we will use a lot, is its full WiFi connectivity. This lets us send data, receive commands, set up web servers, or communicate with other services without adding extra hardware.

In this case the board will work in station mode (STA, Station), meaning it connects to an access point (AP, Access Point) like any other client device. This is the mode you will use in most projects connected to the home, workshop, or office network.

The example is oriented to ESP32. In many cases it can also be adapted to ESP8266 by changing libraries and a few pin details.

Connect to WiFi Network

Connecting to a WiFi network with the ESP32 is very easy thanks to the functions of the WiFi library, which is part of the ESP32 core for the Arduino environment.

To connect we simply use the method ‘Wifi.begin(…)’, which has the following definition,

WiFi.begin(ssid, password = null, channel = 0, bssid = null, connect = true)
Copied!
  • ssid, name of the WiFi network we want to connect to (max 32 char)
  • password, optional, password (minimum 8 char and maximum 64)
  • channel, optional, the WiFi channel to use
  • bssid, optional, MAC address of the access point
  • connect, indicates if we want to connect immediately (if false, it only saves the parameters)

An example code to connect to an existing WiFi network with the ESP32 would look like this.

#include <WiFi.h>

// Replace with your network data
const char* ssid = "ssid";
const char* password = "password";

void setup()
{
  Serial.begin(115200);
  delay(10);
  
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to:\t");
  Serial.println(ssid); 

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(200);
  Serial.print('.');
  }

  // Show success message and assigned IP address
  Serial.println();
  Serial.print("Connected to:\t");
  Serial.println(WiFi.SSID()); 
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());
}

void loop() 
{
}
Copied!

The WiFi.begin(…) function saves the indicated credentials in non-volatile flash memory (which persists even if we load another program). In case of a connection failure, the device will automatically connect to the last access point when available. Furthermore, once configured once, we can reconnect by calling the overload without parameters.

WiFi.begin()
Copied!

The WiFi.begin(…) functions return the connection status to determine when we have established the connection with the network. We can also obtain it at another point in our program with the WiFi.status() function. This status variable can be:

WL_CONNECTEDConnection established
WL_NO_SSID_AVAILSSID not found
WL_CONNECT_FAILEDIncorrect password
WL_IDLE_STATUSWi-Fi is changing between states
WL_DISCONNECTEDThe device is not configured in STA mode

The WiFi.mode(WIFI_STA) function is optional in this example. It serves to leave only the STA mode and deactivate the AP in case we had configured it previously since, as we said, the WiFi configuration is saved even if we reprogram it. The mode options are:

WIFI_OFFOff
WIFI_STAStation
WIFI_APAccess point
WIFI_AP_STAStation+Access Point

The last two modes allow the board to generate its own WiFi network, or to combine AP and STA at the same time.

Summarized Example

The connection code may seem a bit long, but if we clean and organize the code, the code is reduced to a few lines to connect to a WiFi network.

#include <WiFi.h>
 
#include "config.h"  // Replace with your network data
#include "ESP32_Utils.hpp"
 
void setup()
{
  Serial.begin(115200);
  
  ConnectWiFi_STA();
}
 
void loop() 
{
}
Copied!

An additional file we’ll call ‘ESP32_Utils.hpp’ containing the usual functions.

void ConnectWiFi_STA()
{
   Serial.println("");
   WiFi.mode(WIFI_STA);
   WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED) 
   { 
     delay(100);  
     Serial.print('.'); 
   }
 
   Serial.println("");
   Serial.print("Started STA:\t");
   Serial.println(ssid);
   Serial.print("IP address:\t");
   Serial.println(WiFi.localIP());
}
Copied!

A configuration file called ‘config.h’ containing the SSID and password.

const char* ssid = "ssid";
const char* password = "password";
Copied!

Organizing our projects in this way is a good habit, allowing for cleaner, more maintainable, and reusable code.

Connect to Multiple WiFi Network

There is another way to connect to a WiFi network, or rather, to the one with the best signal among available WiFi networks. For this we will use the ‘WiFiMulti’ library.

In the configuration we will use wifiMulti.addAP(…) to add several WiFi networks providing their respective SSIDs and passwords. On startup, the board will connect to the network with the best reception.

This mode is less common than the previous one, since normally we won’t have several WiFi networks available (it’s more common to have several APs with the same SSID and password). But it is interesting in some mesh network projects, sniffers, etc.

However, managing multiple WiFi also means additional workload for the device, although not too large. So use this function only when it is really necessary and don’t get used to using it “just because”.

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

WiFiMulti wifiMulti;

void setup() 
{
  Serial.begin(115200);
  delay(10);
  
  WiFi.mode(WIFI_STA);
  wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
  wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
  wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

  Serial.println("Connecting");
  while (wifiMulti.run() != WL_CONNECTED) 
  {
    delay(250);
    Serial.print('.');
  }

  // Show success message, connected WiFI, and assigned IP address
  Serial.println();
  Serial.print("Connected to:\t");
  Serial.println(WiFi.SSID());
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());
}

void loop() 
{
}
Copied!

That easy! Isn’t it impressive what this little device can do? With this we already have our board connected to a WiFi network, ready to start sending data, making requests, or exposing network services.

Download the Code

All the code from this post is available for download on Github.

github-full

Version for ESP8266: https://github.com/luisllamasbinaburo/ESP8266-Examples

Version for ESP32: https://github.com/luisllamasbinaburo/ESP32-Examples