Get Started-nodemcu-5-connecting-wifi
|

Connecting NodeMCU to Wi-Fi: NodeMCU Beginners’ Guide

In this lesson, we will learn how to use NodeMCU’s Wi-Fi capabilities to connect it to a network and communicate over HTTP. This is an essential part of IoT (Internet of Things), where devices send and receive data via the internet.

Understanding Wi-Fi Capabilities of NodeMCU

NodeMCU is equipped with the ESP8266 Wi-Fi module, which supports:

  • Station Mode (STA): Connecting NodeMCU to an existing Wi-Fi network.
  • Access Point Mode (AP): Creating its own Wi-Fi network.
  • Station + AP Mode: Both modes are active simultaneously.

For most applications, we will use the Station Mode (STA).

Connecting to a Wi-Fi Network

To connect NodeMCU to a Wi-Fi network, we use the ESP8266WiFi library, which comes pre-installed with the Arduino IDE.

Code Example:

#include <ESP8266WiFi.h>

const char* ssid = "Your_SSID";  // Replace with your network SSID
const char* password = "Your_PASSWORD";  // Replace with your network password

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.print("Connecting to Wi-Fi");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nWi-Fi connected!");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  // Nothing to do here
}

Explanation of Code

  1. WiFi.begin(ssid, password); – Initiates a connection to the Wi-Fi network.
  2. WiFi.status() – Checks the connection status.
  3. WiFi.localIP() – Retrieves the IP address assigned to NodeMCU.
  4. The IP address is printed to the Serial Monitor when the connection is successful.

Sending and Receiving Data via HTTP

Once connected to a network, we can send data to or receive data from web servers using HTTP requests.

Example: Sending a simple HTTP GET request to a server.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

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

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nConnected to WiFi");
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    WiFiClient client;  // Create WiFi client
    HTTPClient http;

    http.begin(client, "https://jsonplaceholder.typicode.com/posts/1");
  // Replace with your server URL
    int httpCode = http.GET();

    if (httpCode > 0) {
      String payload = http.getString();
      Serial.println(httpCode);
      Serial.println(payload);
    } else {
      Serial.println("Error in HTTP request");
    }
    http.end();
  }
  delay(10000);  // Send request every 10 seconds
}

Explanation of Code

  1. HTTPClient http; – Creates an HTTP client object.
  2. http.begin() – Specifies the URL to connect to.
  3. http.GET() – Sends an HTTP GET request.
  4. http.getString() – Retrieves the response from the server.
  5. The server URL in the code depends on where you want to send your HTTP request. For testing, use a free API like https://jsonplaceholder.typicode.com/posts/1. If you have a web server, use its IP (http://192.168.1.100/data) or domain (http://yourwebsite.com/data). For IoT cloud logging, services like ThingSpeak (http://api.thingspeak.com/update?api_key=YOUR_API_KEY&field1=123) or Firebase (https://your-project.firebaseio.com/sensorData.json) can be used. We will discuss ThingSpeak and Firebase in an upcoming lesson. You can choose the appropriate URL based on your needs.

Simple Project: Displaying Sensor Data on a Web Page

Let’s create a simple web server on NodeMCU to display sensor data.

Components Required:

  • NodeMCU
  • Potentiometer or any sensor that gives analog outputs(for analog input demonstration)

Circuit Setup:

  • Connect the middle pin of the potentiometer(or the sensor’s analog output pin) to A0 (Analog Input).
  • Connect one of the side pins to 3.3V and the other to GND.

Code Example:

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

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

ESP8266WebServer server(80);  // Create a web server object on port 80

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to WiFi");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);  // Associate URL with handler function
  server.begin();  // Start the server
}

void handleRoot() {
  int sensorValue = analogRead(A0);
  String html = "<html><body><h1>Sensor Value: " + String(sensorValue) + "</h1></body></html>";
  server.send(200, "text/html", html);
}

void loop() {
  server.handleClient();  // Handle incoming requests
}

Explanation of Code

  1. ESP8266WebServer server(80); – Creates a web server object listening on port 80.
  2. server.on("/", handleRoot); – Defines what happens when the root URL is accessed.
  3. server.handleClient(); – Listens for incoming client requests.

You can access the web page by typing the IP address of your NodeMCU (printed in the Serial Monitor) in your browser. It will display the current sensor value in a simple HTML page.

serial-monitor-nodemcu-connected-to -wifi
Nodemcu-web-server

In the next lesson, we will build a complete IoT project where data is sent to a cloud service and visualized. Stay tuned!

Similar Posts

Leave a Reply

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