WiFi Web Server (ESP8266/NodeMCU)

Z2M Part: EMC-00003-A

Creates a WiFi web server to control an LED and display LDR sensor data. Access the web page from any device on the same network.

Circuit Diagram
Circuit diagram for WiFi Web Server (ESP8266/NodeMCU)
Wire Connections & Pin Configuration

Wire Color Connections:

Yellow → NodeMCU A0 to LDR–resistor junction
Red → 3.3V to LDR
Black → GND to 10kΩ resistor

Pin Configuration:

NodeMCU D4 (GPIO2) → Built-in LED (onboard, no external connection)
NodeMCU A0 → LDR + 10kΩ junction (voltage divider)
NodeMCU 3.3V → LDR (one leg)
NodeMCU GND → 10kΩ resistor (voltage divider)
Arduino Code
Edit
// WiFi Web Server - Control LED & Display LDR
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

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

#define LED_PIN 2    // D4 - built-in LED (or use D1/D2 for external)
#define LDR_PIN A0   // LDR on A0

ESP8266WebServer server(80);

void handleRoot() {
  int ldr = analogRead(LDR_PIN);
  String html = "<html><body><h1>NodeMCU Web Server</h1>";
  html += "<p>LDR Value: " + String(ldr) + "</p>";
  html += "<p><a href=\"/on\">LED ON</a> | <a href=\"/off\">LED OFF</a></p>";
  html += "</body></html>";
  server.send(200, "text/html", html);
}

void handleOn() {
  digitalWrite(LED_PIN, LOW);  // Built-in LED active LOW
  server.sendHeader("Location", "/");
  server.send(303);
}

void handleOff() {
  digitalWrite(LED_PIN, HIGH);
  server.sendHeader("Location", "/");
  server.send(303);
}

void setup() {
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);

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

  server.on("/", handleRoot);
  server.on("/on", handleOn);
  server.on("/off", handleOff);
  server.begin();
}

void loop() {
  server.handleClient();
}

Instruction Details

Wiring: Connect LDR one leg to 3.3V, other to 10kΩ to GND. Connect junction to NodeMCU A0. Built-in LED uses D4 (GPIO2).
Library: Not required (ESP8266 core).
Upload Code: Tools → Board → NodeMCU 1.0. Tools → Port → select COM port. Set WiFi SSID and password in code. Click Upload button.
View Output: Open Serial Monitor at 9600 baud to get IP. Open IP in browser to control LED and view LDR value.

How to Use

  1. Connect the required components as per the Pin Configuration above
  2. Open Arduino IDE and create a new sketch
  3. Copy and paste the code above
  4. Select your Arduino board and COM port from Tools menu
  5. Click the Upload button to upload the code to your Arduino
  6. Open Serial Monitor (if applicable) to see the output

Components Required

  • NodeMCU/ESP8266
  • LDR (Light Dependent Resistor)
  • 10kΩ Resistor
  • Micro USB Cable
  • Breadboard
  • Jumper Wires

Category: IoT Projects