How to Configure ESP8266 WiFi in Station (STA), Access Point (AP) and MultiWiFi Mode

ESP8266 WiFi

Sharing is Caring!

Do you want to set up a WiFi connection of ESP8266 WiFi module with your home router, and access the web pages on the internet?

Or, do you intend to advertise a WiFi hotspot via ESP8266 and allow other smart devices to establish wireless communication with it?

Such tasks may seem complex at first, but you just need to program the WiFi chip embedded within the NodeMCU ESP8266 using the insanely popular Arduino IDE.

To get started with the NodeMCU ESP8266 and Arduino IDE, you can refer to the following article:

Once you are able to program the NodeMCU ESP8266 with Arduino IDE, you can upload the WiFi related sketches into ESP8266 and enjoy the WiFi services.

In this article, I will explain how you can prepare sketches for the ESP8266 WiFi Module to connect to an existing WiFi (the one advertised by your router), or to advertise its WiFi hotspot.

Moreover, I will explain how you can configure the ESP8266 to try and connect with the most stable WiFi among the multiple WiFi channels available in a specific area.

Before moving onto the programming part, let’s first explore different configuration modes of the ESP8266 WiFi Module.

ESP8266 WiFi Modes: STA or AP

To play around with the ESP8266 WiFi module, you can program it in two modes: Station (STA) or Access Point (AP).

Station (STA) Mode

In station mode, ESP8266 will act just like your smartphone or laptop. It will connect to an existing WiFi channel, or in most cases, the WiFi advertised by your router.

Once you have programmed ESP8266 in STA mode and you are successfully connected to stable WiFi, you can access any web page on the internet.

ESP8266 WiFi Station (STA) Mode

Access Point (AP) Mode

In this mode, ESP8266 will advertise its WiFi hotspot with a custom SSID and Password. Other smart devices will be able to connect, and consequently establish communication with the ESP8266 WiFi module.

In this case, ESP8266 won’t be able to access the internet as it is merely advertising a WiFi hotspot. Besides, the devices connected to the WiFi advertised by ESP8266 will only be able to communicate with ESP8266 and not with any web server.

ESP8266 WiFi Access Point (AP) Mode

You can program ESP8266 in Station Mode, or AP Mode, or both depending upon the application at hand.

Let’s now explore how to program ESP8266 in both modes…

Programming the ESP8266 Station Mode (STA)

To program the ESP8266 in station mode, upload the following sketch in your NodeMCU ESP8266. Make sure to replace the SSID and password with that of your router WiFi:

  1. const char* ssid = “your_wifi_ssid”
  2. const char* password = “your_wifi_password”
/*
 * This code will configure ESP8266 in station mode which will then connect with a WiFi network. 
 */

#include <ESP8266WiFi.h>

//Specifying the SSID and Password of the Local WiFi Network

const char* ssid = "PTCL_BB"; //“your_wifi_ssid”
const char* password = "F4D22ABF"; //"your_wifi_password"

uint8_t retries=0;

void setup()
{
  //Start the serial communication with the computer
  Serial.begin(115200);
  delay(100);
  Serial.println();

  //Try and Connect to the Network
  WiFi.begin(ssid,password);
  Serial.print("Connecting to ");
  Serial.print(ssid);
  Serial.println("...");

  //Wait for WiFi to connect for a maximum timeout of 20 seconds
  while(WiFi.status()!=WL_CONNECTED && retries<20)
  {
    Serial.print(".");
    retries++;
    delay(1000);
  }

  Serial.println();
  //Inform the user whether the timeout has occured, or the ESP8266 is connected to the internet
  if(retries==20)//Timeout has occured
  {
    Serial.print("Unable to Connect to ");
    Serial.println(ssid);
  }
  
  if(WiFi.status()==WL_CONNECTED)//WiFi has succesfully Connected
  {
    Serial.print("Successfully connected to ");
    Serial.println(ssid);
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
  }
}

void loop() {
  // Maintain your WiFi connection by checking its status before performing any internet related task
  if (WiFi.status()==WL_CONNECTED)
  {
    //EP8266 is connected to WiFi Access Point. You can access Internet or any Web Server
    Serial.println("Connected...");
    delay(1000);
  }
  else
  {
    //ESP8266 is not connected to any WiFi network. You need to wait for the internet connection before you start interacting with any web server
    Serial.print("Trying to connect with ");
    Serial.print(ssid);
    while(WiFi.status()!=WL_CONNECTED)
    {
      Serial.print(".");
      delay(1000);
    }
    Serial.println();
    Serial.print("Sucessfully Connected to ");
    Serial.println(ssid);
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
  }
}

Now, let’s understand what each line of code does to configure the ESP8266 in Station Mode…

Firstly, include the WiFi library for ESP8266 i.e., ESP8266WiFi.h. Then, specify the ssid and password of the WiFi you want to connect with i.e., your router’s WiFi. Finally, initialize the variable which will keep a track of the number of times you want ESP8266 to try and connect with the advertised WiFi i.e., retries:

#include <ESP8266WiFi.h>

//Specifying the SSID and Password of the Local WiFi Network

const char* ssid = "PTCL_BB"; //“your_wifi_ssid”
const char* password = "F4D22ABF"; //"your_wifi_password"
uint8_t retries=0;

In the setup loop (only runs for one time), configure the Arduino Serial Monitor to print the intermittent messages on a console with a baud rate of 115200:

void setup()
{
  //Start the serial communication with the computer
  Serial.begin(115200);
  delay(100);
  Serial.println();

Try and connect with the WiFi using the specified ssid and password and print the relevant messages on the serial console:

  WiFi.begin(ssid,password);
  Serial.print("Connecting to ");
  Serial.print(ssid);
  Serial.println("...");

Wait for the ESP8266 to connect with the WiFi for a maximum of 20 seconds. If the timeout has occurred inform the user via console, else print the IP address assigned to ESP8266. You can now use the assigned IP to check the connection status of ESP8266 by running the ping < ESP8266_IP> command from the Windows/Linux terminal console. This also encloses the setup() loop:

  while(WiFi.status()!=WL_CONNECTED && retries<20)
  {
    Serial.print(".");
    retries++;
    delay(1000);
  }
  Serial.println();
  //Inform the user whether the timeout has occured, or the ESP8266 is connected to the internet
  if(retries==20)//Timeout has occured
  {
    Serial.print("Unable to Connect to ");
    Serial.println(ssid);
  }
  if(WiFi.status()==WL_CONNECTED)//WiFi has succesfully Connected
  {
    Serial.print("Successfully connected to ");
    Serial.println(ssid);
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
  }

In the loop() function (the one which runs endlessly), continuously check the status of the ESP8266 WiFi connection. If the ESP8266 is connected to WiFi, you can go on to access any webpage on the internet. For this example code, I have printed the connection status on the console after every second:

void loop() {
  // Maintain your WiFi connection by checking its status before performing any internet-related task
  if (WiFi.status()==WL_CONNECTED)
  {
    //EP8266 is connected to WiFi Access Point. You can access Internet or any Web Server
    Serial.println("Connected...");
    delay(1000);
  }

If the ESP8266 has lost connection to WiFi, make sure that the connection is established again before you can do any internet-related task or access any server:

else
  {
    //ESP8266 is not connected to any WiFi network. You need to wait for the internet connection before you start interacting with any web server
    Serial.print("Trying to connect with ");
    Serial.print(ssid);
    while(WiFi.status()!=WL_CONNECTED)
    {
      Serial.print(".");
      delay(1000);
    }
    Serial.println();
    Serial.print("Sucessfully Connected to ");
    Serial.println(ssid);
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
  }

Well, that’s it for the configuration of ESP8266 in station mode and subsequent connection with the router’s Wi-Fi.

Here is the output of my serial console and the implementation of the ping command with the assigned IP to evaluate the connection status of ESP8266:

ESP8266 WiFi Configuration in Station (STA) Mode
ESP8266 WiFi Connection Status in Station (STA) Mode

Programming the ESP8266 Multi WiFi

You may have configured ESP8266 in station mode and successfully connected it with the available WiFi, but what if multiple WiFi connections were available and you wanted ESP8266 to connect with the most stable one while switching back and forth between them depending upon the intensity of the WiFi signal?

Turns out, there is an easy way to do that in Arduino using ESP8266WiFiMulti.h library. So, let’s get to operate the ESP8266 in Multi WiFi mode.

For this tutorial, an example case of 3 WiFi connections is considered, however, you can update the code to match your requirements.

Upload the following sketch to your ESP8266, but most importantly, do not forget to update the ssid and password of the WiFi channels:

/*
 * This code will configure ESP8266 in station mode which will then connect with the strongest WiFi network available within the area. 
 */

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

//Defining the instance of ESP8266MultiWifi
ESP8266WiFiMulti wifi_multi;

//Specifying the SSIDs and Passwords of the Local WiFi Networks in your area

//WiFi 1
const char* ssid1 = "PTCL_BB";
const char* password1 = "F4D22ABF";

//WiFi 2
const char* ssid2 = "Netnonik";
const char* password2 = "hey_there";

//WiFi 3
const char* ssid3 = "basal";
const char* password3 = "go_there";

uint16_t connectTimeOutPerAP=5000;//Defines the TimeOut(ms) which will be used to try and connect with any specific Access Point

void setup()
{
  //Start the serial communication with the computer
  Serial.begin(115200);
  delay(100);
  Serial.println();

  //Adding the WiFi networks to the MultiWiFi instance
  wifi_multi.addAP(ssid1,password1);
  wifi_multi.addAP(ssid2,password2);
  wifi_multi.addAP(ssid3,password3);  

  //Wait for ESP8266 to scan the local area and connect with the strongest of the networks defined above
  Serial.print("Connecting to Wi-Fi...");
  while(wifi_multi.run(connectTimeOutPerAP)!=WL_CONNECTED)
  {
    Serial.print(".");
    delay(1000);
  }
  Serial.println();
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop()
{
  //Monitor the WiFi connection before performing any operation
  if(wifi_multi.run()==WL_CONNECTED)
  {
    //ESP8266 is connected to an Access Point
    Serial.print("Connected to ");
    Serial.print(WiFi.SSID());
    Serial.println("...");
    delay(1000);
  }
  else
  {
    //Wait till ESP8266 connects with an AP
    Serial.print("WiFi Disconnected!!!");
    Serial.print("Establishing a connection with a nearby Wi-Fi...");
    while(wifi_multi.run(connectTimeOutPerAP)!=WL_CONNECTED)
    {
      Serial.print(".");
      delay(1000);
    }
    Serial.println();
    Serial.print("Connected to ");
    Serial.println(WiFi.SSID());
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
  }
}

Now let’s understand this code line-by-line…

Firstly load the ESP8266Wifi.h and ESP8266WiFiMulti.h libraries and declare the multi WiFi instance i.e., wifi_multi. Then, specify the ssid and password of all the available WiFi channels. Finally, connectTimeOutPerAP defines the time out (in milliseconds) which will be used to try and connect with each WiFi channel:

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
//Defining the instance of ESP8266MultiWifi
ESP8266WiFiMulti wifi_multi;
//Specifying the SSIDs and Passwords of the Local WiFi Networks in your area
//WiFi 1
const char* ssid1 = "PTCL_BB";
const char* password1 = "F4D22ABF";
//WiFi 2
const char* ssid2 = "Netnonik";
const char* password2 = "hey_there";
//WiFi 3
const char* ssid3 = "basal";
const char* password3 = "go_there";
uint16_t connectTimeOutPerAP=5000;

In the setup() function, configure the serial communication parameters and register the ssid/password of each WiFi channel you wish ESP8266 to scan:

void setup()
{
  //Start the serial communication with the computer
  Serial.begin(115200);
  delay(100);
  Serial.println();
  //Adding the WiFi networks to the MultiWiFi instance
  wifi_multi.addAP(ssid1,password1);
  wifi_multi.addAP(ssid2,password2);
  wifi_multi.addAP(ssid3,password3); 

Now, wait for ESP8266 to scan the registered WiFi networks in the local area and connect with the one having the most stable WiFi signal.

Once the connection is established, print the SSID of the relevant WiFi network and the IP address assigned to ESP8266. 

Serial.print("Connecting to Wi-Fi...");
  while(wifi_multi.run(connectTimeOutPerAP)!=WL_CONNECTED)
  {
    Serial.print(".");
    delay(1000);
  }
  Serial.println();
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

In the loop() function, continuously monitor the status of the ESP8266 WiFi connection. If the connection is established, you can access any web page on the internet. For this example, I have just printed the SSID of the connected WiFi network on the serial console:

void loop()
{
  //Monitor the WiFi connection before performing any operation
  if(wifi_multi.run()==WL_CONNECTED)
  {
    //ESP8266 is connected to an Access Point
    Serial.print("Connected to ");
    Serial.print(WiFi.SSID());
    Serial.println("...");
    delay(1000);
  }

If the ESP8266 is not connected to even one of the registered WiFi networks, you need to wait till ESP8266 connects with one of them before doing any useful work on the internet:

else
{
    Serial.print("WiFi Disconnected!!!");
    Serial.print("Establishing a connection with a nearby Wi-Fi...");
    while(wifi_multi.run(connectTimeOutPerAP)!=WL_CONNECTED)
    {
      Serial.print(".");
      delay(1000);
    }
    Serial.println();
    Serial.print("Connected to ");
    Serial.println(WiFi.SSID());
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
  }
}

ESP8266 MultiWiFi Configuration in Station (STA) Mode

Programming the ESP8266 Access Point Mode (AP)

If you are done connecting the ESP8266 with a WiFi network and feeling proud of yourself, I am sorry to tell you this but you have done something which is too mainstream. You have been doing this for the last two decades with your mobile phone or PC.

Let’s do something interesting i.e., configure the ESP8266 in Access Point Mode and advertise a WiFi network with which we can connect other electronic devices i.e., smartphones, laptops, etc.

To do this, upload the following sketch in your ESP8266 and you will see a WiFi advertised by the name of “ESP8266”. You can connect with this WiFi using a secure password “embedded-robotics”. Of course, you can change the ssid and password of the advertised WiFi, so let’s check it out:

/*
 * This Code will configure ESP8266 in SoftAP mode and allow different devices (Laptop, Mobile, PCs) connect to it
 */
#include <ESP8266WiFi.h> 

const char* ap_ssid = "ESP8266"; //Access Point SSID
const char* ap_password= "embedded-robotics"; //Access Point Password
uint8_t max_connections=8;//Maximum Connection Limit for AP
int current_stations=0, new_stations=0;

void setup()
{
  //Start the serial communication channel
  Serial.begin(115200);
  Serial.println();
  
  //Setting the AP Mode with SSID, Password, and Max Connection Limit
  if(WiFi.softAP(ap_ssid,ap_password,1,false,max_connections)==true)
  {
    Serial.print("Access Point is Creadted with SSID: ");
    Serial.println(ap_ssid);
    Serial.print("Max Connections Allowed: ");
    Serial.println(max_connections);
    Serial.print("Access Point IP: ");
    Serial.println(WiFi.softAPIP());
  }
  else
  {
    Serial.println("Unable to Create Access Point");
  }
}

void loop()
{
  //Continuously check how many stations are connected to Soft AP and notify whenever a new station is connected or disconnected

  new_stations=WiFi.softAPgetStationNum();
  
  if(current_stations<new_stations)//Device is Connected
  {
    current_stations=new_stations;
    Serial.print("New Device Connected to SoftAP... Total Connections: ");
    Serial.println(current_stations);
  }
  
  if(current_stations>new_stations)//Device is Disconnected
  {
    current_stations=new_stations;
    Serial.print("Device disconnected from SoftAP... Total Connections: ");
    Serial.println(current_stations);
  }
  
}

Now I will go through the code so that you can understand it and can make customized changes.

Firstly, include the ESP8266WiFi.h library and then specify the SSID and Password of the WiFi network you wish to advertise. You also need to define the max_connections to limit the number of devices which can connect to this network:

#include <ESP8266WiFi.h> 
const char* ap_ssid = "ESP8266"; //Access Point SSID
const char* ap_password= "embedded-robotics"; //Access Point Password
uint8_t max_connections=8;//Maximum Connection Limit for AP
int current_stations=0, new_stations=0;

In the setup() function, set the parameters for serial communication and configure ESP8266 in SoftAP Mode to advertise a WiFi network with ssid = ap_ssid, password = ap_password, and max_connections = 8:

void setup()
{
  //Start the serial communication channel
  Serial.begin(115200);
  Serial.println();
  //Setting the AP Mode with SSID, Password, and Max Connection Limit
  if(WiFi.softAP(ap_ssid,ap_password,1,false,max_connections)==true)
  {
    Serial.print("Access Point is Creadted with SSID: ");
    Serial.println(ap_ssid);
    Serial.print("Max Connections Allowed: ");
    Serial.println(max_connections);
    Serial.print("Access Point IP: ");
    Serial.println(WiFi.softAPIP());
  }
  else
  {
    Serial.println("Unable to Create Access Point");
  }
}

In the loop() function, continuously check how many devices are connected to the advertised WiFi network and notify whenever a new station is connected or disconnected via Serial Monitor:

void loop()
{
  new_stations=WiFi.softAPgetStationNum(); 
  if(current_stations<new_stations)//Device is Connected
  {
    current_stations=new_stations;
    Serial.print("New Device Connected to SoftAP... Total Connections: ");
    Serial.println(current_stations);
  }
  if(current_stations>new_stations)//Device is Disconnected
  {
    current_stations=new_stations;
    Serial.print("Device disconnected from SoftAP... Total Connections: ");
    Serial.println(current_stations);
  }
}

I have connected my mobile and laptop with the Soft AP, and here is the output from the Serial Terminal:

ESP8266 WiFi Configuration in Access Point (AP) Mode

You can also ping the ESP8266 to check whether your device is connected successfully or not. Let’s do this via laptop against the IP assigned to ESP8266 (visible in the serial monitor):

Laptop Connection with ESP8266 WiFi Network in Access Point (PA) Mode

Conclusion

ESP8266 WiFi module can connect to the WiFi network advertised by your router and let you access the web pages on the internet. Not only that, but you can also configure ESP8266 with Multi WiFi operation and it will connect with the most stable WiFi network among the multiple networks advertised in a local area. To connect the smart devices directly with the ESP8266 module, you can configure the ESP8266 to advertise its WiFi network and establish a remote connection with the devices.

This article illustrated how you can implement the WiFi services provided by the ESP8266 WiFi Module using simple sketches in Arduino IDE. Establishing a WiFi connection with the ES8266 module is just a starting point in exploring the power of the internet in terms of IoT and Automation.

Sharing is Caring!

Subscribe for Latest Articles

Don't miss new updates on your email!

Leave a Comment

Your email address will not be published. Required fields are marked *

Exit mobile version