WiFi controlled LED using ESP8266

In this IoT(Internet of Things) application tutorial, we show how to create WiFi controlled LED using ESP8266 with HTML web page. In this example we will use ESP12E WiFi module which uses the ESP8266 chip to create asynchronous web server using ESPAsyncWebServer and ESPAsyncTCP libraries. Arduino IDE is used to build and upload code into the ESP12E module. The ESP8266 WiFi LED controller can be accessed using browser on PC or smartphone. LED control using smartphone can be easily extended to control switches and other electronics sensors to create IoT devices. 

WiFi controlled LED using ESP8266

In this example, we have connected a LED to GPIO pin 5. When user visits the web server the user can select to turn on or off the LED.

Prerequisites:

1. If you do not know how to program ESP8266 using Arduino IDE, setup ESP8266 board on Arduino see the tutorial LED Blink using ESP8266 & Arduino IDE with Video and Pictures.

2. For displaying simple message using HTML see Simple ESP8266 Asynchronous Web Server Example with Code.

Video demo:

The following video demonstrates how the WiFi controlled LED works using ESP8266 based web server. 


What is ESPAsyncWebServer library?

ESPAsyncWebServer library is a web server library that connects client to the server asynchronously. By serving clients asynchronously multiple clients can be served simultaneously without having congestion problem with service demand. This means that load on the server when there are many clients is reduced. This is because in asynchronous connection, resources used by one client is freed when the connection is closed. So using ESPAsyncWebServer(HTTP) library which runs on top of ESPAsynchTCP libary(TCP) more than one client connection can be handled. The library uses the concept of events and handlers. Handlers are routines that are executed based on events. If any event occurs, requests are triggered, and handlers executes the routine requested. Since handlers are used that checks for event triggers, we do not need to write anything in the loop() function. The library uses template engine to render the final web HTML. The template processing engine combines the content(html, css etc) and variables using template placeholders in the client request parameters to render the final HTML web page.

The ESPAsyncWebServer can be downloaded and installed from the following URL:

https://github.com/me-no-dev/ESPAsyncWebServer

Since we are using ESP12E wifi module, we need the ESPAsynchTCP libary which can be downloaded and installed from the following URL:


  https://github.com/me-no-dev/ESPAsyncTCP 
  
If you are using the ESP32 wifi module, then you need to download and install the following AyncTCP library instead of ESPAsynchTCP libary:

https://github.com/me-no-dev/AsyncTCP

The following shows ESP12E WiFi module with LED on breadboard used in this example project.

 ESP8266 LED control Asynchronous Web Server Code

The following is the code that turns LED on and off via ESP8266 based WiFi web server

#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

#define LED 5

const char ssid[]="SSID";
const char password[]="PASSWORD";

const char LEDcontrolwebpage[] PROGMEM = R"=====(
<html>
  <head>
    <title>ESP12E LED Control Web Page</title>
  </head>
  <body>
    <p>Select LED State</p>
    <a href="/on"><button>ON</button></a>
    <a href="/off"><button>OFF</button></a>
  </body>
</html>
)=====";

AsyncWebServer server(80);

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(115200);

  Serial.printf("Connecting to %s....\n", ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if(WiFi.waitForConnectResult() != WL_CONNECTED){
    Serial.printf("WiFi connection failed!Rebooting ...\n");
    delay(1000);
    ESP.restart();
    }
  Serial.printf("Connected to %s\n", ssid);
  Serial.printf("IP address: %s\n", WiFi.localIP().toString().c_str());

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", LEDcontrolwebpage);
    }
    );

  server.on("/on", HTTP_GET, [](AsyncWebServerRequest *request){     
    digitalWrite(LED,HIGH); 
    printf("LED On\n"); 
    request->redirect("/");
    }
    );

  server.on("/off", HTTP_GET,
  [](AsyncWebServerRequest *request){    
    digitalWrite(LED, LOW);
    printf("LED Off\n");
    request->redirect("/");
    }
    );

  server.begin();
}

void loop() {

}

1. In the above code, we have included the ESPAsyncWebServer and ESPAsynchTCP libraries to build the asynchronous web server. 

#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

2. Then we have setup the WiFi network credentials. This should be replaced with your own WiFi SSID and PASSWORD credentials.

 const char ssid[]="SSID";
const char password[]="PASSWORD";

3. We have stored our HTML code inside the character array called LEDcontrolwebpage in the program memory space as string literal. The HTML code contains basically two buttons for turning the LED ON and OFF. When ON or OFF button is pressed, the hyperlink is called which is linked to directory /on and /off respectively.

const char LEDcontrolwebpage[] PROGMEM = R"=====(
<html>
  <head>
    <title>ESP12E LED Control Web Page</title>
  </head>
  <body>
    <p>Select LED State</p>
    <a href="/on"><button>ON</button></a>
    <a href="/off"><button>OFF</button></a>
  </body>
</html>
)=====";

4. Using AsyncWebServer server(80) we have create server object with port number 80.

5. In the setup() function, we have set up the LED pin to output and set the baud rate of 115200 for serial communication with the ESP12E wifi module. We then print message to the user "connecting to... " ssid provided to inform progress of connection behind the scene which users can see on the Arduino IDE serial monitor. Using WiFi.mode() we have setup the ESP8266mod into Station mode.  Using if(WiFi.waitForConnectResult() ) statement we check for wifi connection to Access Point(AP). If the connection fails then we print message "WiFi connection failed!Rebooting ...\n" to inform users that connection has failed and after 1 second delay restart the module. If the connection is successful, we print out message "Connected to " ssid and also print out the IP address to inform the user at which IP address it is connected to. 

Using the on method of object server, server.on() , we create a handler that handles the HTTP request from incoming clients. Whenever there is request, we send the content of the LEDcontrolwebpage  stored in the program code in 3 description above.

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", LEDcontrolwebpage);
    }
    );

 When the client presses the ON button, the /on is provoked because of the hyperlink in the html code. This event provokes the following handler server.on(). When this handler is executed the digitalWrite(LED, HIGH) function is used to turn ON the LED. We also send "LED On" to the serial monitor to inform the user. Finally a redirect to the main page is done.

server.on("/on", HTTP_GET, [](AsyncWebServerRequest *request){
    //printf("%s/on\n", WiFi.localIP().toString().c_str());
    digitalWrite(LED,HIGH);
    printf("LED On\n");
    request->redirect("/");
    }
    );

 When the client presses the OFF button, the /off is provoked because of the hyperlink in the html code. This event provokes the following handler server.off(). When this handler is executed the digitalWrite(LED, LOW) function is used to turn OFF the LED. We also send "LED Off" to the serial monitor to inform the user. Finally a redirect to the main page is done.

server.on("/on", HTTP_GET, [](AsyncWebServerRequest *request){
    //printf("%s/on\n", WiFi.localIP().toString().c_str());
    digitalWrite(LED,HIGH);
    printf("LED On\n");
    request->redirect("/");
    }
    );

6. Finally the server.begin() is used to start the asynchronous web server.

Post a Comment

Previous Post Next Post