Difficulty Level: Intermediate
This project will demonstrate how to control an LED over Wi-Fi using an ESP8266 microcontroller and a web interface. You can use the same approach to control other devices connected to your ESP8266.
The ESP8266 will host a web server that you can access from any browser. The web interface will provide controls to toggle the LED on and off.
Follow these steps to wire your circuit:
Below is the Arduino code to set up the ESP8266 as a Wi-Fi server and control the LED through the web interface:
#include <ESP8266WiFi.h>
const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";
WiFiServer server(80);
const int ledPin = 2; // GPIO2 is D4 on NodeMCU
void setup() {
pinMode(ledPin, OUTPUT); // Set LED pin as output
digitalWrite(ledPin, LOW); // Initially turn off LED
Serial.begin(115200);
delay(10);
// Connect to WiFi
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
server.begin(); // Start the server
Serial.println("Server started");
}
void loop() {
WiFiClient client = server.available(); // Listen for incoming clients
if (!client) {
return;
}
// Wait for data from client
while (!client.available()) {
delay(1);
}
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Control LED based on request
if (request.indexOf("/LED=ON") != -1) {
digitalWrite(ledPin, HIGH);
}
if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(ledPin, LOW);
}
// Respond to client with basic HTML
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("");
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<h1>ESP8266 LED Control</h1>");
client.println("<p>LED is " + (String)(digitalRead(ledPin) ? "ON" : "OFF") + "</p>");
client.println("<p><a href=\"/LED=ON\">Turn On</a></p>");
client.println("<p><a href=\"/LED=OFF\">Turn Off</a></p>");
client.println("</html>");
}
WiFi.begin(ssid, password);
: Connects the ESP8266 to the specified Wi-Fi network.server.begin();
: Starts the web server to listen for incoming requests.digitalWrite(ledPin, HIGH);
: Turns the LED on when the URL contains /LED=ON
.client.readStringUntil('\r');
: Reads the HTTP request from the web browser.client.println()
: Sends an HTML response back to the client, updating the web page with LED control links.You've built a Wi-Fi enabled LED controller! You can expand this project by controlling multiple LEDs or other devices like relays and motors, or even integrating sensors for more advanced automation projects.