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.
Wire Color Connections:
Pin Configuration:
// 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();
}