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.
Article Contents
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.
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.
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:
- const char* ssid = “your_wifi_ssid”
- 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:
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());
}
}
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:
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):
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.
He is the owner and founder of Embedded Robotics and a health based start-up called Nema Loss. He is very enthusiastic and passionate about Business Development, Fitness, and Technology. Read more about his struggles, and how he went from being called a Weak Electrical Engineer to founder of Embedded Robotics.
Bonjour j’ai un code d’ESP8266 fonctionnant en PB ( temps que l’on reste appuyé sur le BP de l’écran tactile la led est allumée) , mais le code est en web server (STA)
j’aimerais l’avoir en ACCESS POINT (AP) j’ai essayé de modifier le code avec quelques exemple en AP mais je n’y arrive pas .
Je vous laisse le code .
Merci de votre aide .
#ifdef ESP32
#include
#include
#else
#include
#include
#endif
#include
const char* ssid = “xxxxxxxxx” ;
const char* password = “xxxxxxxxx” ;
const int output = D0 ;
// page web HTML :
const char index_html [ ] PROGMEM = R”rawliteral(
commande led avec bouton poussoir
body { font-family: Arial; text-align: center; margin:
0px auto; padding-top: 30px;}
.button {
padding: 20px 20px;
font-size: 24px;
text-align: center;
outline: none;
color: #fff;
background-color: #2f4468;
border: none;
border-radius: 20px;
box-shadow: 0 6px #999;
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
.button:hover {background-color: #1f2e45}
.button:active {
background-color: #1f2e45;
box-shadow: 0 4px #666;
transform: translateY(2px);
}
commande led avec bouton poussoir
BOUTON POUSSOIR
function toggleCheckbox ( x ) {
var xhr = new XMLHttpRequest ( ) ;
xhr . open ( “GET”, “/” + x , true ) ;
xhr . send ( ) ;
}
)rawliteral”;
void notFound ( AsyncWebServerRequest *request )
{
request->send ( 404 , “text/plain” , “Not found” ) ;
}
AsyncWebServer server( 80 ) ;
void setup ( )
{
Serial.begin ( 115200 ) ;
WiFi . mode ( WIFI_STA ) ;
WiFi . begin ( ssid , password ) ;
if ( WiFi . waitForConnectResult ( ) != WL_CONNECTED )
{
Serial . println ( “WiFi Failed!” ) ;
return ;
}
Serial . println ( ) ;
Serial . print ( “addresse IP ESP8266: http://” ) ;
Serial . println ( WiFi . localIP ( ) ) ;
pinMode ( output , OUTPUT ) ;
digitalWrite ( output , LOW ) ;
// Send web page to client
server.on(“/”,HTTP_GET,[](AsyncWebServerRequest*request)
{
request->send_P ( 200 , “text/html” , index_html ) ;
} ) ;
// Receive an HTTP GET request
server.on(“/on”,HTTP_GET,[](AsyncWebServerRequest*request)
{
digitalWrite ( output , HIGH ) ;
request->send ( 200 , “text/plain” , “ok” ) ;
} ) ;
// Receive an HTTP GET request
server.on(“/off”,HTTP_GET,[](AsyncWebServerRequest*request)
{
digitalWrite ( output , LOW ) ;
request->send ( 200 , “text/plain” , “ok” ) ;
} ) ;
server . onNotFound ( notFound ) ;
server . begin ( ) ;
}
void loop ( ) { }
Hi Nicolas,
I could not understand the language, but it seems like that you need a little bit of help with the code. If you can describe what you need help with in English, I maybe able to help you.
Hii Awais , I have a question … can we make a Wi-Fi repeater out of it …
like only using arduino ide to code into nodemcu and then use it as an wifi range extender .
Hi Samyak,
Thanks for reaching out. ESP8266 employs a Wi-Fi chip that can be used in AP Mode or STA Mode. To use it as a WiFi repeater, you will have to make some custom configurations. You can check out the following tutorials for this:
https://www.reichelt.com/magazin/en/projects/how-you-build-your-own-wifi-repeater
https://circuitdigest.com/microcontroller-projects/nodemcu-esp8266-wifi-repeater-or-range-extender
I like ap mode. But i have to changemy phone s connection each time. Is there a more convenient way? Dual connect? Pass thru ap?
I think such a setting may be made in the phone settings in which your phone should switch between two preferred WiFi Access Points i.e., between ESP8266 AP and your Home Router WiFi AP.
Hello
Before I ask my question, I have to thank you for your good tutorials.
And the question!
How to limit the lifetime of ip assigned to a client connected to esp8266 which is in AP mode.
I mean to release the ip assigned to the client after disconnecting it and assign the same ip to the new client that connects.
Hi Jafar,
Thanks for your comment. To limit the lifetime of an IP assigned to a device, you can implement the timer in ESP8266 after which you can disconnect all the devices in a periodic loop. I have not come across any such library which can do the task for you but you can surely write it yourself with not much effort. Just explore the API for ESP8266 AP Mode and you will be able to use the functions to manipulate the connected devices. For further information, please explore the following link: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/soft-access-point-class.html
How to hotspot with mobile wifi connect to control esp8266 configuration. Some other load application. Like ex: lamp,fan,etc…
Please answer to send Email me.