Wi-Fi Enabled LED Controller with ESP8266

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.

Components Required

System Overview

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.

Wiring the Components

Follow these steps to wire your circuit:

Arduino Code

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>");
}
            

Code Explanation

Upload and Test

  1. Upload the code to your ESP8266 using the Arduino IDE.
  2. Open the Serial Monitor to find the IP address assigned to the ESP8266 by your Wi-Fi network.
  3. Enter the IP address in your web browser, and you will see a simple webpage with buttons to turn the LED on and off.
  4. Click the links to toggle the LED state.

Conclusion

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.