NodeMCU LED Control

Controlling LEDs with NodeMCU via Wi-Fi

Introduction

This experiment shows how to use the NodeMCU (ESP8266) to control LEDs remotely via Wi-Fi, using a simple web server.

NodeMCU with LED

Components Needed

Circuit Setup

  1. Connect the long leg (anode) of the LED to the D2 pin of the NodeMCU.
  2. Connect the short leg (cathode) of the LED to the GND pin through a 220-ohm resistor.

Ensure the LED is properly connected for it to turn on or off via the web interface.

NodeMCU Circuit Setup

Code for NodeMCU LED Control

Upload the following code to your NodeMCU to control the LED via Wi-Fi:


#include 

const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";

WiFiServer server(80);
int ledPin = D2;

void setup() {
  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  server.begin();
}

void loop() {
  WiFiClient client = server.available();
  if (client) {
    String request = client.readStringUntil('\r');
    client.flush();
    
    if (request.indexOf("/LED=ON") != -1) {
      digitalWrite(ledPin, HIGH); 
    } else if (request.indexOf("/LED=OFF") != -1) {
      digitalWrite(ledPin, LOW);
    }

    client.print("HTTP/1.1 200 OK\nContent-Type: text/html\n\n");
    client.print("

LED Control

Turn On

Turn Off

"); delay(1); } }

Explanation

The code sets up a web server on the NodeMCU. You can control the LED by visiting the server's IP address in a web browser and clicking the links to turn the LED on or off.

Troubleshooting