Project tutorial

Control LED from web app using ESP8266 Serial WIFI module © GPL3+

Controlling LED using web application over WiFi using ESP8266 module and Arduino board.

  • 51,295 views
  • 13 comments
  • 11 respects

Components and supplies

About this project

Hello everyone, I am going to tell you about controlling LED using web application over WiFi using ESP8266 module and Arduino board. So let’s start,

Required Components: 1. Arduino Board 2. LEDs 3. Breadboard 4. some male and female connecting wires 5. Of course your laptop

§ Setting up Arduino IDE for project:

• Install the ESP8266 Board Package:

For this, you need Arduino 1.6.4 or higher. Open the Arduino IDE and go to File -> Preferences (in Windows shortcut is Ctrl+comma) or Arduino -> Preferences(in Mac shortcut is ⌘+comma). In Preferences, enter the given line to “Additional Board Manager’s URL” towards the bottom: http://arduino.esp8266.com/package_esp8266com_index.json

After adding it click OK.

After doing this step restart Arduino IDE. Now go to Tools -> Board -> Boards Manager… In Boards Manager, search by  esp. You will get something like ‘esp8266 by ESP8266 Community‘, click on it and click on Install button. After installation Close it and restart Arduino IDE.

Now go to Tools -> Board -> Generic ESP8266 Module (this is the new added module). Now follow the given things for few other settings in Tools menu:

  • Flash Mode: DIO
  • Flash Frequency: 40 MHz
  • Upload Using: Serial
  • CPU Frequency: 80 MHz
  • Flash Size: 4M (1M SPIFFS)
  • Upload Speed: 115200
  • Port: my USB port (this shows up once you plugged Arduino board to your laptop )
  • Programmer: AVRISP mkll

Leave other settings as default.

• Install the ArduinoJSON library:

In our HTML app we are going to deal with JSON data. So we need to add ArduinoJson library to our Arduino IDE. ArduinoJson is available in Arduino’s Library Manager. You can automatically install it from there. To open Library Manager go to Sketch -> Include Library -> Manage Libraries… and search by ‘json‘. You will get something like ‘ArduinoJSON by Benolt Blanchon‘  click on it and click on Install button. If you are getting some kind of problem in installing the library then follow the given link installing ArduinoJson library. After setting up this, now you can include this library with #include <ArduinoJson.h> in the sketch.

Navigating to Library Manager

Library Manager

§ Setting up HTML app:

After doing all these setting in your Arduino IDE you are ready to write the sketch. But wait before doing that, let’s create our HTML application which I created in PHP. You can check out my HTML app here Controlling LED using ESP8266 HTML app and unzip it(if you downloaded .zip file). Make sure that you should have Apache and PHP installed in your laptop. You can do it easily with the help of Google. After setting up Apache and PHP, For mac users open your Terminal go to /Library/WebServer/Documents and paste the unzipped folder here. For Linux users, open your Terminal go to /var/www/ and paste the unzipped folder here. For Windows users, follow the link deploy php app in apache windows.Start your Apache server and test it. Open your web browser and type http://localhost/your-HTML-app-folder-name to the URL. For me it’s http://localhost/wifiarduino. You will get your running html application.In our HTML app there are two things one is index.php and another one is light.json file. The light.json file is simple. It either reads {“light”:”on”} or {“light”:”off”}. That’s it. Remember that, it needs to be set to permission 777 or 666 so the PHP file can write to it.The index.php file is the public file that writes {“light”:”on”} or {“light”:”off”} to light.json. There are two links that links you to the current page with a url parameter ?light=on or ?light=off. Based on the url parameter, the PHP writes the appropriate instructions to the JSON file, like http://localhost/wifiarduino/?light=on

This slideshow requires JavaScript.

§ Wiring up everything:

Now you are ready to wire up everything. Here we are not using FTDI to USB cable that’s why we are going to use our Arduino board behave like FTDI for that we have removed the ATmega chip. Be careful while removing the chip don’t damage it while removing. For help you can see this video here remove atmega chip from arduino. Connect the ESP8266 as given below in the diagram. So it is like that:

 ESP8266        Arduino

  • VCC                3.3 V
  • GND              GND
  • CH_PD          3.3 V
  • TX                  TX
  • RX                  RX
  • GPIO2           3.3 V
  • GPIO0          GND

Power up ESP8266: Remember ESP8266 module works on low voltage(3.3V DC). Connect VCC and CH_PD of the ESP8266 to 3.3V of Arduino board. Put 1KΩ resistor between GPIO2 and 3.3V power supply.Connecting TX/RX pins: The TX/RX pins are used to program the module and for Serial I/O, commonly used for debugging. Connect ESP9266’s TX -> TX and RX->RX  from Arduino board.Putting ESP8266 in FLASH mode: Here when GPIO0 (the Violet coloured wire in above diagram) is connected to ground at boot, this tells the ESP8266 to start up in bootloader mode(or programming mode). This is when you can flash the ESP8266, meaning transfer the Arduino code to the ESP8266. After the Arduino code is loaded, you’ll see a “Done Uploading” message at the bottom of the ArduinoIDE. Then the code will start running. After uploading the program, remove the Violet wire. If you want to flash another program, then restart the Arduino by unplug/replug the USB or press Reset button on Arduino board or you can reset the Arduino by disconnecting the CH_PD (Chip PowerDown) pin. If you don’t want to put ESP8266 in FLASH mode(bootloader or programming mode), simply remove the Violet wire.

§ Writing Arduino Code(Sketch):

We already installed essential libraries to work with ESP8266. Now this is the most interesting part. Here we are going to use <ESP8266WiFi.h> and <ArduinoJson.h> header files.<ArduinoJson.h> library, basically tells the ESP to ping our light.json file. If the latest value for the key light is on, then turn on the LED and iff the value for the key light is off, then turn off the LED. Here, light.json outputs its value using JSON. So we need a parser. So I used ArduinoJson. So this is my code:

#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
const char* ssid     = "mywifi"; 
const char* password = "mywifipassword";
const char* host     = "192.168.1.10"; // Your domain  
String path          = "/wifiarduino/light.json";
const int pin        = 2;
void setup() {
    pinMode(pin, OUTPUT);
    pinMode(pin, HIGH);
    Serial.begin(115200);
  delay(10);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  int wifi_ctr = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
    Serial.println("IP address: " + WiFi.localIP());
}
void loop() {
    Serial.print("connecting to ");
  Serial.println(host);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  client.print(String("GET ") + path + " HTTP/1.1\r\n" +               "Host: " + host + "\r\n" +                "Connection: keep-alive\r\n\r\n");
  delay(500); // wait for server to respond
  // read response  
String section="header";
  while(client.available()){
    String line = client.readStringUntil('\r');
    // Serial.print(line);    // we’ll parse the HTML body here
    if (section=="header") { // headers..
      Serial.print(".");
      if (line=="\n") { // skips the empty space at the beginning
         section="json";
      }
    }
    else if (section=="json") {  // print the good stuff
      section="ignore";
      String result = line.substring(1);      // Parse JSON
      int size = result.length() + 1;
      char json[size];
      result.toCharArray(json, size);
      StaticJsonBuffer<200> jsonBuffer;
      JsonObject& json_parsed = jsonBuffer.parseObject(json);
      if (!json_parsed.success())
      {
        Serial.println("parseObject() failed");
        return;
      }
      // Make the decision to turn off or on the LED
      if (strcmp(json_parsed["light"], "on") == 0) {
        digitalWrite(pin, HIGH);
         Serial.println("LED ON");
      }
      else {
        digitalWrite(pin, LOW);
        Serial.println("led off");
      }
    }
  }
  Serial.print("closing connection. ");
}

void setup(): Here we are setting a few basic configurations set to our specific values like:

a.) Wifi name and password (the ssid & password variables)

b.) light.json URL (the host & path variable)

c.) Output pin (we use GPIO2, so const int pin=2) We begin a Serial Connection using Serial.begin(115200). Here we set baud rate to 115200. Set the same Baud Rate on Serial Monitor of Arduino IDE to see the response output from ESP8266. Last we start connecting to the internet using

Wifi.begin(ssid, password);

While the ESP is still connecting, I have it delay and then print a dot. If you are watching the Serial Terminal, you’ll see dots appear until you log in. It’s just a way to see that the little ESP is trying to connect. void loop(): Now we run the loop() function.Here, we will connect to light.json and print the HTTP response (the info you get from the URL).The stuff used in client.print(…) is called an HTTP request. Here. it contains a very simple request header. The last while loop is to see the HTTP response body in the serial, wait a little bit, see it close and re-open the connection, then see the HTTP response body again. Rinse and repeat. We can see the log of the response in your Serial Terminal. The response will something like this:HTTP/1.1 200 OKAccess-Control-Allow-Origin: *Access-Control-Allow-Headers: X-Requested-WithContent-Type: application/jsonTransfer-Encoding: chunkedContent-Disposition: attachment;Date: Sun, 12 Jul 2015 18:49:27 GMTCache-control: private{"light":"off"}The first section is the HTTP Response header. It tells us what kind of data we’re getting using

application/json

, that the webpage is up and running using 200 OK. We only care about the last line (

{"light":"off"}

), which tells the ESP8266 what to do with the LED. I have introduced a variable name

section

. Using this, I keep track of what section of the HTTP response I’m reading.The program then reads the HTTP response line by line. Each line is represented by the variable

line

in the while loop. The default value is

section = "header"

since the HTTP Response begins with header.It then doesn’t change until it reaches an empty line. When it reach an empty line

if (line=="\n")

then the program sets

section="json"

since the next line will be the JSON line we care about.We parse the next JSON line and store the JSON into a

json_parsed

variable. You can read this in the section after the comments

// Parse JSON

.After this, we turn the LED on or off depending on the result. We use the

strcmp

function (short for string comparison).

strcmp(json_parsed["light"], "on") == 0)

, meaning if the  key

light

is set to

on

, then we turn on the LED. We do this using

digitalWrite(pin, HIGH)

line where the variable

pin

is the GPIO number we set in the beginning of the file.

§ Final things to do:

As I already mentioned remove the Violet coloured wire after uploading the code. Now go on Arduino IDE and go to Tools > Serial Monitor. Change the baud rate to 115200 baud from right bottom in Serial Monitor . It will tell you whether you are connected to your WiFi or not. If you can see red light turn on permanently and blue light flashes, it means your module is ready to use.Finally, just remove RX and TX pins. And power  tFinally, just remove RX and TX pins. And power up ESP8266 with external power source like 3.3V rechargeable Li-ion battery or something other with same DC voltage. So this is my final circuit diagram after completion. Thanks for reading. Happy programming.

Code

Code snippet #1Plain text
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>

const char* ssid     = "mywifi";  
const char* password = "mywifipassword";

const char* host     = "192.168.1.10"; // Your domain  
String path          = "/wifiarduino/light.json";  
const int pin        = 2;

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

  delay(10);
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  int wifi_ctr = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("WiFi connected");  
  Serial.println("IP address: " + WiFi.localIP());
}

void loop() {  
  Serial.print("connecting to ");
  Serial.println(host);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  client.print(String("GET ") + path + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: keep-alive\r\n\r\n");

  delay(500); // wait for server to respond

  // read response
  String section="header";
  while(client.available()){
    String line = client.readStringUntil('\r');
    // Serial.print(line);
    // we’ll parse the HTML body here
    if (section=="header") { // headers..
      Serial.print(".");
      if (line=="\n") { // skips the empty space at the beginning 
        section="json";
      }
    }
    else if (section=="json") {  // print the good stuff
      section="ignore";
      String result = line.substring(1);

      // Parse JSON
      int size = result.length() + 1;
      char json[size];
      result.toCharArray(json, size);
      StaticJsonBuffer<200> jsonBuffer;
      JsonObject& json_parsed = jsonBuffer.parseObject(json);
      if (!json_parsed.success())
      {
        Serial.println("parseObject() failed");
        return;
      }

      // Make the decision to turn off or on the LED
      if (strcmp(json_parsed["light"], "on") == 0) {
        digitalWrite(pin, HIGH); 
        Serial.println("LED ON");
      }
      else {
        digitalWrite(pin, LOW);
        Serial.println("led off");
      }
    }
  }
  Serial.print("closing connection. ");
}
Code snippet #2Plain text
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With
Content-Type: application/json
Transfer-Encoding: chunked
Content-Disposition: attachment;
Date: Sun, 12 Jul 2015 18:49:27 GMT
Cache-control: private
{"light":"off"}
Github
https://github.com/bblanchon/ArduinoJson
Github
https://github.com/Arduino-Projects/Controlling-LED-using-ESP8266-UI

Comments

Similar projects you might like

Hacking My Toaster

Project tutorial by javier muñoz sáez

  • 306 views
  • 5 comments
  • 9 respects

Rickroll Box

Project showcase by slagestee

  • 1,117 views
  • 0 comments
  • 4 respects

START: A STandalone ARduino Terminal

Project tutorial by Alessio Villa

  • 769 views
  • 0 comments
  • 4 respects

Music Reactive LED Strip

Project showcase by buzzandy

  • 334 views
  • 2 comments
  • 10 respects

Pavlov's Cat

Project tutorial by Arduino

  • 631 views
  • 0 comments
  • 2 respects

Infrared Controlled Logic Puzzle -- Lights On!

Project tutorial by FIELDING

  • 192 views
  • 0 comments
  • 5 respects
Add projectSign up / Login