Contents
Introduction
If we are performing any internet related projects then our first task is to connect node mcu to wifi. For the connection we need to follow various procedure which we will be discussing in this section.
Component Required
- NodeMCU
- usb cable
Coding
#include <ESP8266WiFi.h>
const char *ssid = "Your wifi Network name";
const char *pass = "Network password";
void setup()
{
Serial.begin(9600);
delay(10);
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
}
void loop()
{
}
Important commands for wifi connection
#include<ESP8266wifi.h>
This is esp8266 library file. We must include this library in all the project where we need a wifi connection.
WiFi.begin(ssid, pass);
If we want to get connected to any wifi or any local host then we must know the SSID and PASSWORD of that network. We must use that SSID and PASSWORD in the programming section. we can directly write the name of your network SSID in the place of ssid and network PASSWORD in the place of pass. If we want to do this task in more organized way the we can use the following command in the beginning also
const char *ssid = “Your wifi Network name”;
const char *pass = “Network password”;
if we do in this way then it will be easy for us when the password or ssid of the network get change we should not search for wifi.begin function we can directly change it in the beginning.
WiFi.status()
This function provides the status of the wifi. when we call this function it will return certain value which helps us to know weather NodeMCU is connected to wifi , disconnected to wifi , or waiting for connection.
- WL_CONNECTED: assigned when connected to a WiFi network;
- WL_NO_SHIELD: assigned when no WiFi shield is present;
- WL_IDLE_STATUS: it is a temporary status assigned when WiFi.begin() is called and remains active until the number of attempts expires (resulting in WL_CONNECT_FAILED) or a connection is established (resulting in WL_CONNECTED);
- WL_NO_SSID_AVAIL: assigned when no SSID are available;
- WL_SCAN_COMPLETED: assigned when the scan networks is completed;
- WL_CONNECT_FAILED: assigned when the connection fails for all the attempts;
- WL_CONNECTION_LOST: assigned when the connection is lost;
- WL_DISCONNECTED: assigned when disconnected from a network;
WiFi.localIP()
This function will Send the IP address of the ESP8266 to the computer.