Remote Control LED with NodeMCU via WiFi

Remote Control LED with NodeMCU via WiFi

NodeMCU Series Tutorial:

  1. ESP8266 and the IoT Marvel NodeMCU

  2. Light Up LED: How to Program NodeMCU with Arduino IDE

  3. Three Network Modes of NodeMCU: How to Turn it into a WiFi Hotspot

Remote Control LED with NodeMCU via WiFi

In the previous tutorial, we introduced the three network modes of NodeMCU/ESP8266 and practiced how to turn NodeMCU into a WiFi hotspot using AP mode, where you can customize the hotspot name and password. In today’s tutorial, we will practice the STA network mode, which allows NodeMCU to join an existing local area network and establish a remote control webpage to control an LED’s on and off.

Remote Control LED with NodeMCU via WiFi

Arduino + WiFi Module to Achieve Remote Control of LED

Implementation Idea

Lighting up an LED is a textbook case for learning any microcontroller, and remotely lighting up an LED via WiFi is a must-learn case for any IoT microcontroller platform. The above image shows the example of using Arduino with the ESP8266 WiFi module to achieve remote control of an LED in the “Arduino Starter Learning Kit”. As we mentioned earlier, NodeMCU can be simply understood as an Arduino integrated with a WiFi module, greatly simplifying hardware circuit connections. What we need to do in the program:

  1. In STA mode, connect NodeMCU to an existing hotspot. This hotspot can be our school’s or home router’s wireless network or a temporary hotspot created by a mobile phone.

  2. Create an HTTP web service on NodeMCU. This may involve some web programming knowledge, such as how to create button controls using HTML and how to determine button click events using JS. In this tutorial, we will only touch on this without overly pursuing complex CSS styles and complicated JS frameworks, using only the most basic JS and simplest HTML structure for hardware interaction. Of course, if you understand web development, you can expand on your own.

  3. The mobile phone accesses NodeMCU’s HTTP web service to achieve remote control of the LED, so it does not involve programming for a mobile app.

Hardware Connection

The hardware setup is very simple; we need:

  1. One NodeMCU

  2. One LED

  3. One breadboard

  4. Several connecting wires

Remote Control LED with NodeMCU via WiFi

As shown in the diagram, the LED is connected to the D7 pin of NodeMCU, which is GPIO13. We can refer to the following diagram for the specific pin connections of NodeMCU:

Remote Control LED with NodeMCU via WiFi

How to Connect NodeMCU to Other WiFi Hotspots

Once the circuit is connected, we can connect NodeMCU to the computer and open Arduino IDE to start programming (of course, the premise is that you have already installed the ESP8266 core for Arduino). First, let’s understand how to make NodeMCU join other WiFi hotspots, which is the STA network mode.

Remote Control LED with NodeMCU via WiFi

Enter the following code in Arduino IDE:

#include <ESP8266WiFi.h>

const char* ssid = “test”; // WiFi name to join

const char* password = “12345678”; // WiFi password to join

void setup(void){

Serial.begin(115200);

WiFi.mode(WIFI_STA); // Set to STA mode

WiFi.begin(ssid, password); // Connect to target WiFi

Serial.println(“”);

// Wait for connection

while (WiFi.status() != WL_CONNECTED) {

delay(500);

Serial.print(“.”);

}

Serial.println(“”);

Serial.print(“Connected to “);

Serial.println(ssid);

Serial.print(“IP address: “);

Serial.println(WiFi.localIP()); // Output the obtained IP address

}

void loop(void){

}

Change the ssid and password to your target hotspot information, compile and upload to NodeMCU, then open the serial monitor. If NodeMCU joins the hotspot, we will see the obtained IP address. It’s that simple. This is the typical code for NodeMCU to join a WiFi hotspot. Here, it is important to note that you must first set NodeMCU to STA mode using WiFi.mode(WIFI_STA), and the ssid and password must be entered correctly. Also, the ssid name does not support Chinese characters, and NodeMCU/ESP8266 only supports 2.4G hotspots, not 5G.

Establishing a Web Service

After joining the WiFi hotspot, we need to establish a web service. When the mobile phone or computer accesses the IP of NodeMCU, the browser will display the control buttons for the LED. Pressing different buttons, NodeMCU will control the LED’s on and off.

#include <ESP8266WiFi.h>

#include <WiFiClient.h>

#include <ESP8266WebServer.h>

const char* ssid = “test”; // WiFi name to join

const char* password = “12345678”; // WiFi password to join

int ledPin = 13; // LED pin GPIO13

// Create Web Server

ESP8266WebServer server(80);

// Root directory as control interface

const char* serverIndex = “<html><head><meta charset=’utf-8′><meta name=’viewport’ content=’user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1,width=device-width’><title>Remote Control LED</title></head><body><h1>Mobile Remote Control LED</h1><button id=’ledon’>Light Up LED</button><button id=’ledoff’>Turn Off LED</button><script>function createXMLHttpRequest(){var xmlHttp;if(window.XMLHttpRequest){xmlHttp=new XMLHttpRequest();if(xmlHttp.overrideMimeType)xmlHttp.overrideMimeType(‘text/xml’)}else if(window.ActiveXObject){try{xmlHttp=new ActiveXObject(‘Msxml2.XMLHTTP’)}catch(e){try{xmlHttp=new ActiveXObject(‘Microsoft.XMLHTTP’)}catch(e){}}}return xmlHttp;};document.getElementById(‘ledon’).onclick=function(){led(‘on’)};document.getElementById(‘ledoff’).onclick=function(){led(‘off’)};function led(s){xmlHttp=createXMLHttpRequest();var url=’/’+s;xmlHttp.open(‘GET’, url, true);xmlHttp.onreadystatechange=function(){if(xmlHttp.readyState==4){if(xmlHttp.status==200){console.log(‘ok’)}}};xmlHttp.setRequestHeader(‘Content-Type’,’application/x-www-form-urlencoded’);xmlHttp.send();}</script></body></html>”;

void handleRoot() {

server.send(200, “text/html”, serverIndex);

}

// 404 Page Handling

void handleNotFound(){

String message = “File Not Found\n\n”;

message += “URI: “;

message += server.uri();

message += “\nMethod: “;

message += (server.method() == HTTP_GET)?”GET”:”POST”;

message += “\nArguments: “;

message += server.args();

message += “\n”;

for (uint8_t i=0; i<server.args(); i++){

message += ” ” + server.argName(i) + “: ” + server.arg(i) + “\n”;

}

server.send(404, “text/plain”, message);

}

// Turn on LED operation

void turnLedOn(){

Serial.println(“LED ON”);

digitalWrite(ledPin, HIGH);

}

// Turn off LED operation

void turnLedOff(){

Serial.println(“LED OFF”);

digitalWrite(ledPin, LOW);

}

void setup(void){

Serial.begin(115200);

pinMode(ledPin, OUTPUT);

digitalWrite(ledPin, LOW);

WiFi.mode(WIFI_STA); // Set to STA mode

WiFi.begin(ssid, password); // Connect to target WiFi

Serial.println(“”);

// Wait for connection

while (WiFi.status() != WL_CONNECTED) {

delay(500);

Serial.print(“.”);

}

Serial.println(“”);

Serial.print(“Connected to “);

Serial.println(ssid);

Serial.print(“IP address: “);

Serial.println(WiFi.localIP()); // Output the obtained IP address

// HTTP Routes

server.on(“/”, handleRoot);

server.on(“/on”,turnLedOn);

server.on(“/off”,turnLedOff);

server.onNotFound(handleNotFound);

server.begin();

}

void loop(void){

server.handleClient();

}

This web page content is directly written into the Arduino code as a string:

<html>

<head>

<meta charset=’utf-8′>

<meta name=’viewport’ content=’user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1,width=device-width’>

<title>Remote Control LED</title>

</head>

<body>

<h1>Mobile Remote Control LED</h1>

<button id=’ledon’>Light Up LED</button>

<button id=’ledoff’>Turn Off LED</button>

<script>

function createXMLHttpRequest(){

var xmlHttp;

if(window.XMLHttpRequest){

xmlHttp=new XMLHttpRequest();

if(xmlHttp.overrideMimeType)

xmlHttp.overrideMimeType(‘text/xml’)

}else if(window.ActiveXObject){

try{

xmlHttp=new ActiveXObject(‘Msxml2.XMLHTTP’)

}catch(e){

try{

xmlHttp=new ActiveXObject(‘Microsoft.XMLHTTP’)

}catch(e){}

}

}

return xmlHttp;

};

document.getElementById(‘ledon’).onclick=function(){led(‘on’)};

document.getElementById(‘ledoff’).onclick=function(){led(‘off’)};

function led(s){

xmlHttp=createXMLHttpRequest();

var url=’/’+s;

xmlHttp.open(‘GET’, url, true);

xmlHttp.onreadystatechange=function(){

if(xmlHttp.readyState==4){

if(xmlHttp.status==200){console.log(‘ok’)}

}

};

xmlHttp.setRequestHeader(‘Content-Type’,’application/x-www-form-urlencoded’);

xmlHttp.send();

}

</script>

</body>

</html>

This HTML code creates two buttons, “Light Up LED” and “Turn Off LED” in the web UI. When the button is clicked, JS will generate an HTTP request accordingly, for example, “Light Up LED” will request

http://nodemcu’s IP address/on

Conversely, it will be

http://nodemcu’s IP address/off

In the HTTP routing, we define:

server.on(“/on”,turnLedOn);

server.on(“/off”,turnLedOff);

When /on is accessed, the turnLedOn function will be executed, and when /off is accessed, the turnLedOff function will be executed, allowing us to control the LED’s on and off. If you understand web programming, this is a typical RESTful architecture. Of course, you can also achieve the same functionality through parameters or different protocols such as WebSocket, MQTT, etc., but we won’t elaborate on that here.

Compile and upload the above code to NodeMCU, then open the serial monitor to obtain NodeMCU’s IP address, and access this IP with a mobile browser to see the following interface:

Remote Control LED with NodeMCU via WiFi

By clicking the “Light Up LED” and “Turn Off LED” buttons, can you remotely control the LED?

Purchase NodeMCU

https://item.taobao.com/item.htm?id=580998229338

How to Obtain Arduino E-books and Video Tutorials

Do you also want a copy of the Arduino e-book and various video tutorials included with our kit?

Scan the QR code below to follow us, and reply “Benefits

Remote Control LED with NodeMCU via WiFi

Remote Control LED with NodeMCU via WiFi

Click to read the original text and purchase the Arduino starter learning kit

Leave a Comment

Your email address will not be published. Required fields are marked *