What You Will Build
By the end of this project your NodeMCU ESP8266 will be hosting its own small web page. Open it on your phone or laptop, tap a button, and an LED on your breadboard switches on or off. There is no app to install, no cloud account and no extra hardware: everything runs on your home network, served directly by a chip that costs a couple of dollars.
This is the "hello world" of IoT, and it teaches the pattern behind almost every connected gadget. A microcontroller joins Wi-Fi, listens for HTTP requests, and turns each request into a physical action. Replace the LED with a relay module and the same sketch becomes a smart switch. Replace it with a motor driver and it becomes a remote-controlled robot.
Along the way you will meet the three things that trip up nearly every NodeMCU beginner: the mismatch between the printed D-labels and real GPIO numbers, the active-LOW onboard LED, and the boot-strapping pins that can stop a board from starting if you wire to them carelessly.
Meet the NodeMCU ESP8266
Before the ESP32 arrived, the ESP8266 was the chip that put Wi-Fi on a two-dollar module and changed what hobbyists could build. The NodeMCU v3 (sold under the LoLin name, with near-identical Amica versions) mounts an ESP-12E or ESP-12F module on a breadboard-friendly board and adds everything needed to start coding over USB: a CH340G USB-to-serial chip, a micro-USB port, a 3.3 V regulator and an auto-reset circuit, so you never have to hold a BOOT button to upload.
The specifications that matter for this project:
- CPU: 32-bit Tensilica L106 at 80 MHz, switchable to 160 MHz in software
- Flash: 4 MB on the board
- RAM: roughly 80 KB of data RAM, of which around 40 to 50 KB is left free once the Wi-Fi stack is running
- Wi-Fi: 802.11 b/g/n on 2.4 GHz only. It will not see a 5 GHz network at all
- GPIO: 11 usable pins out of the chip's 17, because several are committed to the flash chip
- Analog input: one 10-bit ADC pin (A0)
- Logic level: 3.3 V on every pin, and the pins are not 5 V tolerant
Today an ESP32 costs only slightly more and is far more capable, with two cores, Bluetooth and many more pins. The NodeMCU ESP8266 still earns its place because millions of tutorials target it, the CH340 driver situation is well understood, and it is a forgiving board to learn on. If you already own one, this is a perfectly good way to start.
One practical note on size: the LoLin v3 is noticeably wider than the Amica board. On a half-size breadboard it can cover every free hole on one side, leaving nowhere to plug in a component. Use a full-size breadboard, or run jumper wires from the header pins as we do below.
The GPIO Numbering Problem: D0 vs GPIO Numbers
The silkscreen on the board prints labels such as D0, D1, D2 ... D8, but the ESP8266 hardware knows its pins by GPIO numbers, and the two do not match. The Arduino functions pinMode() and digitalWrite() expect the GPIO number unless you use the Dx macros that the ESP8266 board package defines for you.
| Silkscreen | GPIO | Notes |
|---|---|---|
| D0 | GPIO16 | No PWM, no interrupts, no I2C. Used to wake the chip from deep sleep |
| D1 | GPIO5 | Default I2C SCL |
| D2 | GPIO4 | Default I2C SDA |
| D3 | GPIO0 | Boot-mode pin. Held LOW at reset puts the chip in flash mode |
| D4 | GPIO2 | Onboard LED (active LOW). Must be HIGH at boot |
| D5 | GPIO14 | SPI clock |
| D6 | GPIO12 | SPI MISO |
| D7 | GPIO13 | SPI MOSI |
| D8 | GPIO15 | SPI chip select. Must be LOW at boot |
In code you can write the raw number (pinMode(14, OUTPUT)) or the macro (pinMode(D5, OUTPUT)). Both compile to exactly the same thing, but the macro matches the label printed on your board, so it is far easier to read and to debug.
For an external LED, pick a pin with no boot-time duties. D1, D2, D5, D6 and D7 are all safe choices. Avoid D3, D4 and D8 for anything that can pull the line the wrong way during reset, because the chip reads those three pins at startup to decide how to boot. This project uses D5 (GPIO14).
⚠️ Warning
The onboard LED (D4 / GPIO2) is active LOW: digitalWrite(D4, LOW) turns it ON and HIGH turns it OFF, the opposite of most Arduino examples. It also shares a boot-strapping pin, so you will see it flicker during every upload. That is normal.
A Note on the Analog Pin
The ESP8266's own ADC accepts only 0 to 1.0 V. NodeMCU boards add a small resistor divider (typically 220 kΩ and 100 kΩ) in front of A0, which stretches the usable range to roughly 0 to 3.3 V at the header pin. We do not use the ADC in this project, but remember it if you later connect a sensor and the readings look wrong. On a bare ESP-12F module without that divider, anything above 1 V can damage the input.
Installing the ESP8266 Board Package
The ESP8266 uses a different board package from the ESP32, so it needs its own URL:
- Open File → Preferences in the Arduino IDE.
- In Additional boards manager URLs, add
https://arduino.esp8266.com/stable/package_esp8266com_index.json - Open Tools → Board → Boards Manager, search for esp8266, and install esp8266 by ESP8266 Community.
- Select Tools → Board → ESP8266 Boards → NodeMCU 1.0 (ESP-12E Module).
- Set Tools → Upload Speed to 115200 for the most reliable uploads.
If no COM port appears when you plug the board in, you probably need the CH340 driver, or you are using a charge-only USB cable. Many cheap cables carry power but no data lines, and this is by far the most common cause of a "dead" board.
Components
6 itemsNeed these parts? Get this build sheet by email
Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.
Wiring the External LED
The circuit has only two connections:
- LED anode (the longer leg) → 330 Ω resistor → D5 on the NodeMCU
- LED cathode (the shorter leg, flat side of the case) → GND on the NodeMCU
The resistor can sit on either side of the LED, since it only needs to be somewhere in the series path. The 3.3 V output on the pin, minus the LED's forward voltage of about 2 V for a red LED, leaves roughly 1.3 V across the resistor. Ohm's law gives 1.3 V ÷ 330 Ω ≈ 4 mA, which glows clearly and is far below the ESP8266's recommended pin current limit of about 12 mA. A 150 Ω resistor gives about 9 mA and a brighter LED while staying inside that limit. Never connect an LED without a resistor, because it will draw excessive current and can damage both the LED and the pin.
Step 1: Prove the Hardware With a Blink Test
Never add Wi-Fi to a circuit you have not tested. This sketch blinks the onboard LED and the external LED in a pattern that makes any wiring or polarity mistake obvious. It uses the Dx macros so the pin names match the board.
// NodeMCU ESP8266 v3 - dual LED blink (hardware check)
// Onboard LED: D4 / GPIO2, active LOW
// External LED: D5 / GPIO14, active HIGH
#define ONBOARD_LED D4
#define EXT_LED D5
void setup() {
Serial.begin(115200);
delay(100);
pinMode(ONBOARD_LED, OUTPUT);
pinMode(EXT_LED, OUTPUT);
digitalWrite(ONBOARD_LED, HIGH); // HIGH = off for an active-LOW LED
digitalWrite(EXT_LED, LOW); // LOW = off
Serial.println();
Serial.println("NodeMCU ESP8266 - dual LED blink");
Serial.printf("CPU: %u MHz | Free heap: %u bytes\n",
(unsigned)ESP.getCpuFreqMHz(), (unsigned)ESP.getFreeHeap());
}
void loop() {
digitalWrite(ONBOARD_LED, LOW); // onboard ON
digitalWrite(EXT_LED, LOW); // external OFF
Serial.println("Onboard ON / External OFF");
delay(500);
digitalWrite(ONBOARD_LED, HIGH); // onboard OFF
digitalWrite(EXT_LED, HIGH); // external ON
Serial.println("Onboard OFF / External ON");
delay(500);
digitalWrite(ONBOARD_LED, LOW); // both ON
digitalWrite(EXT_LED, HIGH);
Serial.println("Both ON");
delay(200);
}Upload it and open the Serial Monitor at 115200 baud. The two LEDs should alternate, and the onboard LED should appear to behave "backwards" relative to the HIGH and LOW comments, which is the active-LOW behaviour in action. If the external LED never lights, flip it around, because reversed polarity is the usual culprit.
If you ever see garbled characters right after pressing reset, that is not a fault. The ESP8266's boot ROM prints its startup message at 74880 baud, so it looks like noise at 115200. Your own Serial.println output after that point is fine.
Step 2: Add Wi-Fi and a Web Server
With the hardware proven, the next step is to make the board reachable over the network. Three ideas are involved:
Station mode. The ESP8266 can join your router like a phone does (station mode) or create its own network (access point mode). We use station mode, so the board gets an IP address from your router and every device on the same network can reach it.
An HTTP server. The ESP8266WebServer library listens on port 80, the standard web port. When a browser requests a path such as / or /led, the library calls a function you registered for that path.
Routes that map to actions. Our sketch exposes three routes:
| Route | What it does |
|---|---|
/ | Serves the control page (HTML, CSS and a little JavaScript) |
/led?state=on, off or toggle | Changes the LED and replies with its new state as JSON |
/status | Replies with the current LED state as JSON |
The page itself is stored in flash with PROGMEM instead of RAM, which matters on a chip with only a few dozen kilobytes free. The JavaScript in the page calls /led using fetch(), so the page updates in place without a reload, and it polls /status every few seconds so a second phone or browser tab stays in sync.
Replace YOUR_SSID and YOUR_PASSWORD with your own network details before uploading.
// NodeMCU ESP8266 - Wi-Fi LED controller with a built-in web page
// Control the LED on D5 from any browser on your network.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* WIFI_SSID = "YOUR_SSID";
const char* WIFI_PASS = "YOUR_PASSWORD";
#define ONBOARD_LED D4 // active LOW - mirrors the external LED
#define EXT_LED D5 // active HIGH
ESP8266WebServer server(80);
bool ledOn = false;
const char PAGE[] PROGMEM = R"rawliteral(
<!DOCTYPE html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>NodeMCU LED Control</title>
<style>
body{font-family:system-ui,sans-serif;background:#0f1923;color:#e8eef5;
text-align:center;margin:0;padding:2rem}
.card{max-width:340px;margin:0 auto;background:#16222e;border-radius:14px;padding:1.5rem}
.dot{width:70px;height:70px;border-radius:50%;margin:1rem auto;
background:#334155;transition:.2s}
.dot.on{background:#22c55e;box-shadow:0 0 28px #22c55e}
button{width:100%;padding:.9rem;margin-top:.6rem;font-size:1rem;border:0;
border-radius:8px;background:#6366f1;color:#fff;cursor:pointer}
</style></head><body><div class="card">
<h2>NodeMCU LED</h2>
<div id="dot" class="dot"></div>
<p id="label">Loading...</p>
<button onclick="send('on')">Turn ON</button>
<button onclick="send('off')">Turn OFF</button>
<button onclick="send('toggle')">Toggle</button>
</div>
<script>
function render(s){
document.getElementById('dot').className = 'dot' + (s.led ? ' on' : '');
document.getElementById('label').textContent = 'LED is ' + (s.led ? 'ON' : 'OFF');
}
function send(a){ fetch('/led?state=' + a).then(r => r.json()).then(render); }
function poll(){ fetch('/status').then(r => r.json()).then(render); }
poll();
setInterval(poll, 3000);
</script></body></html>
)rawliteral";
void setLed(bool on) {
ledOn = on;
digitalWrite(EXT_LED, on ? HIGH : LOW);
digitalWrite(ONBOARD_LED, on ? LOW : HIGH); // active LOW
}
void sendStatus() {
String json = String("{\"led\":") + (ledOn ? "true" : "false") + "}";
server.send(200, "application/json", json);
}
void handleRoot() {
server.send_P(200, "text/html", PAGE);
}
void handleLed() {
String state = server.arg("state");
if (state == "on") setLed(true);
else if (state == "off") setLed(false);
else if (state == "toggle") setLed(!ledOn);
else {
server.send(400, "application/json",
"{\"error\":\"use state=on, off or toggle\"}");
return;
}
Serial.printf("LED -> %s\n", ledOn ? "ON" : "OFF");
sendStatus();
}
void connectWiFi() {
WiFi.persistent(false); // do not wear out flash saving credentials
WiFi.mode(WIFI_STA);
WiFi.setAutoReconnect(true);
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("Connecting to ");
Serial.print(WIFI_SSID);
uint32_t start = millis();
while (WiFi.status() != WL_CONNECTED) {
if (millis() - start > 20000) {
Serial.println("\nWi-Fi timeout - restarting");
ESP.restart();
}
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected. Open http://");
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
delay(100);
pinMode(ONBOARD_LED, OUTPUT);
pinMode(EXT_LED, OUTPUT);
setLed(false);
connectWiFi();
if (MDNS.begin("nodemcu-led")) {
MDNS.addService("http", "tcp", 80);
Serial.println("Also reachable at http://nodemcu-led.local");
}
server.on("/", HTTP_GET, handleRoot);
server.on("/led", HTTP_GET, handleLed);
server.on("/status", HTTP_GET, sendStatus);
server.onNotFound([]() { server.send(404, "text/plain", "Not found"); });
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
MDNS.update();
}How the Sketch Works
setLed() is the single place that touches the pins. Every route calls it, so the LED state, the pin levels and the status reported to the browser can never disagree. The onboard LED mirrors the external one, with its inverted logic handled in this one function so nothing else needs to remember it.
connectWiFi() has a timeout. A sketch that loops forever on a wrong password looks identical to a crashed board. After 20 seconds it restarts and tries again, and it prints dots so you can see it working. WiFi.persistent(false) stops the library rewriting your credentials to flash on every boot, which saves wear on the chip.
loop() stays free of delay(). server.handleClient() must run frequently to answer requests, and a long delay() makes the page feel frozen. Anything you add later should use millis() timing instead.
Input is validated. An unknown value for state returns a 400 error instead of silently doing nothing. Habits like that make a project far easier to extend.
mDNS gives the board a friendly name. After connecting you can often browse to http://nodemcu-led.local instead of remembering an IP address. Windows 10 and later, macOS, iOS and Linux (with Avahi) usually resolve it. Some Android versions do not, so keep the IP address handy as a fallback.
Finding the Address and Testing
Upload the sketch, open the Serial Monitor at 115200 baud and wait for the line that starts with Connected. Open http://, followed by an address such as 192.168.1.42. Type that address into any browser on the same network, using http, not https, and the control page appears.
You can also test without the page at all. From a terminal, these two commands switch the LED and read back its state:
curl "http://192.168.1.42/led?state=on"
curl "http://192.168.1.42/status"Testing the endpoints directly like this is a useful habit. If the curl commands work but the page does not, the problem is in the HTML or JavaScript. If neither works, it is the network or the sketch.
Your router normally hands out a different IP address after a restart. To keep the address stable, either reserve it for the board's MAC address in the router's DHCP settings, which is the cleanest method, or set a static address in code with WiFi.config(ip, gateway, subnet) before calling WiFi.begin().
Steps
- 1Add the ESP8266 board manager URL in Preferences and install the esp8266 package
- 2Select NodeMCU 1.0 (ESP-12E Module) and set the upload speed to 115200
- 3Install the CH340 driver if no COM port appears, and use a data-capable USB cable
- 4Wire the LED anode through 330 Ω to D5 and the cathode to GND
- 5Upload the blink test and confirm both LEDs alternate, remembering the onboard LED is inverted
- 6Enter your Wi-Fi name and password in the web server sketch, then upload it
- 7Read the IP address from the Serial Monitor and open it in a browser on the same network
- 8Tap Turn ON, Turn OFF and Toggle, and confirm the LED and the page stay in sync
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| No COM port appears | Charge-only cable or missing CH340 driver | Try a different data cable and install the driver |
| Upload fails with "espcomm_open failed" | Wrong port or board selected | Re-select the port, choose NodeMCU 1.0, and try 115200 upload speed |
| External LED never lights | Reversed polarity, wrong pin or missing connection | Flip the LED, confirm the wire is on D5, and re-run the blink test |
| Onboard LED appears inverted | It is active LOW | Expected behaviour. LOW turns it on |
| Serial Monitor shows only dots | Wrong password, or a 5 GHz-only network | Check spelling and case, and use a 2.4 GHz network |
| Page will not load | Different network, guest Wi-Fi with client isolation, or https typed | Join the same network and use the http:// address |
| Garbage text at reset | Boot ROM message at 74880 baud | Ignore it. Your own output at 115200 is fine |
| Board resets or will not boot | Something is pulling D3, D4 or D8 the wrong way at startup | Disconnect wires from those pins and use D5 to D7 or D1 and D2 |
| Address changes after a restart | Router assigns a new DHCP lease | Reserve the address in the router, or set a static IP |
Security and Where to Go Next
This sketch has no password, and anyone on your Wi-Fi network can switch the LED. That is fine for a bench demo. Do not forward port 80 on your router to the internet, because that would expose the board to everyone. For anything you plan to leave running or connect to real equipment, add authentication or move to MQTT with a broker on your own network.
Once this works, there are natural directions to take it:
- Dimming: use
analogWrite(EXT_LED, value). On the ESP8266 the PWM range is 0 to 1023 and the default frequency is 1 kHz. Add a slider to the page. - A relay: swap the LED for a relay module to switch a lamp or fan. If you do, use a properly isolated relay module and treat mains wiring with real care.
- Wireless updates: read ESP8266 OTA Updates so you can reflash the board without a cable.
- MQTT control: follow NodeMCU ESP8266 MQTT LED Control to control the LED from Home Assistant or Node-RED.
- Phone app control: see NodeMCU ESP8266 with Blynk for a no-code dashboard approach.
You now have the complete loop that every connected device uses: join the network, listen for a request, validate it, act on the hardware, and report the result back. Everything more advanced is a variation on those steps.
