Language: EN

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

How to connect an ESP8266 or ESP32 to a WiFi network (STA mode)

We start with the entries dedicated to programming the ESP8266 and ESP32. As it could not be otherwise, we start with the simplest case, how to connect the ESP8266 or ESP32 to an existing WiFi network.

In previous entries, we have seen how to program the ESP8266 with the Arduino environment, and the ESP8266 programming guide, emphasizing the differences between programming an Arduino and an ESP8266.

We have also seen two of the most popular development boards based on the ESP8266, the NodeMCU and the Wemos D1 Mini. There are many more to see, but for now it is more than enough to get into programming.

So (finally!) we can start playing with this fun device, connecting our ESP8266 to a WiFi. In this case the ESP8266 will act in station mode (STA), that is, as a device that connects to an access point (AP). In the next entry we will see how to make the ESP8266 generate its own WiFi by acting as an AP.

We will refer to the ESP8266, but the same code is compatible for the ESP32, adjusting the name of the libraries. At the end, you have the code for both the ESP8266 and the ESP32.

Connect to WiFi network

Connecting to a WiFi network with the ESP8266 is very simple thanks to the functions of the ESP8266WiFi library, which is part of the ESP8266 definition that we downloaded with the board manager when setting up the Arduino IDE.

In the case of the ESP32, the library is simply called ‘WiFi’.

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

WiFi.begin(ssid, password = null, channel = 0, bssid = null, connect = true)

Where:

  • ssid, name of the WiFi network to which we want to connect (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 of code to connect to an existing WiFi network with the ESP8266 would look like this.

#include <ESP8266WiFi.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() 
{
}

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

WiFi.begin()

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

WL_CONNECTEDConnection established
WL_NO_SSID_AVAILThe SSID is not found
WL_CONNECT_FAILEDIncorrect password
WL_IDLE_STATUSWi-Fi is changing between states
WL_DISCONNECTEDThe ESP8266 is not configured in STA mode

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

WIFI_OFFOff
WIFI_STAStation
WIFI_APAccess point
WIFI_AP_STAStation+Access Point

We will see the last two in the next entry when we see how to generate our own WiFi with the ESP8266.

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 <ESP8266WiFi.h>
 
#include "config.h"  // Replace with your network data
#include "ESP8266_Utils.hpp"
 
void setup()
{
  Serial.begin(115200);
  
  ConnectWiFi_STA();
}
 
void loop() 
{
}

An additional file that we will call ‘ESP8266_Utils.hpp’ that contains 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());
}

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

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

Organizing our projects in this way is a good habit, which allows us to have cleaner, maintainable, and reusable code.

Connect to Multiple WiFi Networks

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 ‘ESP8266WiFiMulti’ library.

In the configuration, we will use wifiMulti.addAP(…) to add several WiFi networks providing their respective SSID and password. When starting up, the ESP8266 will connect to the network with the best reception.

This mode is less common than the previous one, since normally we are not going to have several available WiFi networks (it is 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 a multiple WiFi also implies an additional workload for the ESP8266, although not too large. So use this function only when it is really necessary and do not get used to using it “just because”.

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

ESP8266WiFiMulti 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() 
{
}

Other ESP8266 WiFi Functions

Here is a summary of some of the additional functions available in ESP8266 WiFi. The names are self-descriptive of their function, but if you have doubts, you can consult the ESP8266 documentation.

// Connection management
WiFi.reconnect();
WiFi.disconnect(true);
WiFi.isConnected();
WiFi.setAutoConnect(autoConnect);
WiFi.status();

// Return the indicated value (cannot be used to rewrite the value)
WiFi.SSID();
WiFi.hostname();
WiFi.localIP();
WiFi.subnetMask()
WiFi.gatewayIP();
WiFi.dnsIP(dns_no);
WiFi.macAddress();

It’s that simple! Isn’t it impressive what this little device can do? In the next entry we will see something even more impressive, like configuring the ESP8266 to act as an AP, that is, generate its own WiFi for other devices to connect to. See you soon!

Download the code

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

github-full

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

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