Introduction
The ESP8266 NodeMCU is one of the most popular Wi-Fi microcontrollers ever made. In this tutorial, we build a web server hosted on the NodeMCU to control an LED from any smartphone or browser.
Components Needed
- ESP8266 NodeMCU
- LED and 330-ohm resistor
- Breadboard and jumper wires
Wiring
Connect LED anode through 330-ohm resistor to GPIO 2 (D4). Cathode to GND.
The Code
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
ESP8266WebServer server(80);
#define LED 2
bool ledOn = false;
String getPage() {
return "<html><head><meta name='viewport' content='width=device-width,initial-scale=1'></head><body>"
"<h1>LED Control</h1><p>Status: <b>" + String(ledOn?"ON":"OFF") + "</b></p>"
"<a href='/on'><button>Turn ON</button></a> <a href='/off'><button>Turn OFF</button></a></body></html>";
}
void setup() {
Serial.begin(115200); pinMode(LED, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(500);
Serial.println("IP: " + WiFi.localIP().toString());
server.on("/", []() { server.send(200, "text/html", getPage()); });
server.on("/on", []() { ledOn=true; digitalWrite(LED,HIGH); server.sendHeader("Location","/"); server.send(302); });
server.on("/off", []() { ledOn=false; digitalWrite(LED,LOW); server.sendHeader("Location","/"); server.send(302); });
server.begin();
}
void loop() { server.handleClient(); }
How to Use
- Upload the code and open Serial Monitor at 115200 baud.
- Note the IP address (e.g. 192.168.1.105).
- Open that IP in any browser on the same Wi-Fi network.
- Click ON/OFF to control the LED!
Conclusion
You have built your first IoT web server. This same pattern extends to relays, servo motors, and multi-device control systems!