Begin typing your search above and press return to search. Press Esc to cancel.

control Electrical Devices From user web browser using esp8266 Nodemcu


Hi, in this tutorial we will see how to control electrical devices like fan, light, etc., to turn on and off using esp8266 from a web browser. if you are bored with a dedicated device controller like an app or an remote which will be available for only one particular device but using this method all the device which support web browsing will be act as a  controller for us.

Make sure all the devices are connected to the same router, this example doesn't include a port forwarding function which will not allow us to control the device from outside the home network. 

Components that you need for completing this project are very simple, you need to have an esp8266 wifi module and a relay, make sure you buying a 5v relay which very easy to use with esp chips doesn't require external supply too. we can make use of the Vin pin of the nodemcu or if you are using a generic chip, you need to supply an external 5v to the relay.


For this example project I have used only 2 relay circuit, but the actual program wrote for connecting four relay module. 


You can check the above video on how this thing works and how to connect your browser to the ip address returned from esp and all the details are included in this video.





Copy the below arduino code and paste into your Arduino IDE and upload the program to your nodemcu or any other esp devices that you are using, make sure to choose the correct port and device name from the board. also don't forget to change the SSID and password to your Wi-fi settings.

This program for the esp8266 wrote to return the status of the device , which will in turn notify us with the device state in the browser which will also make the user to know which device has currently turned on or off. 

----------------------------------------------------------------------------------------------------------------------------



#include <ESP8266WiFi.h>
 
const char* ssid = "Magesh";
const char* password = "jayakumar";
 
; // 
WiFiServer server(80);
 
void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(0, OUTPUT);
  pinMode(13, OUTPUT);
  digitalWrite(5, LOW);
  digitalWrite(4, LOW);
  digitalWrite(0, LOW);
  digitalWrite(13, LOW);
 
  // Connect to WiFi network
  Serial.println();
  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");
 
  // Start the server
  server.begin();
  Serial.println("Server started");
 
  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
 
}
 
void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
 
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
 
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
 
  // Match the request
 
 
  if (request.indexOf("/light1on") > 0)  {
    digitalWrite(5, HIGH);
   
  }
  if (request.indexOf("/light1off") >0)  {
    digitalWrite(5, LOW);
   
  }

   if (request.indexOf("/light2on") > 0)  {
    digitalWrite(4, HIGH);
   
  }
  if (request.indexOf("/light2off") >0)  {
    digitalWrite(4, LOW);
   
  }
    if (request.indexOf("/light3on") >0)  {
    digitalWrite(0, HIGH);
   
  }
  if (request.indexOf("/light3off") > 0)  {
    digitalWrite(0, LOW);
   
  }
   if (request.indexOf("/light4on") > 0)  {
    digitalWrite(13, HIGH);
   
  }
  if (request.indexOf("/light4off") > 0)  {
    digitalWrite(13, LOW);
   
  }
// Set ledPin according to the request
//digitalWrite(ledPin, value);
 
  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.println("<head>");
  client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
  client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
 client.println("</head>");
  client.println("<body bgcolor = \"#f7e6ec\">"); 
  client.println("<hr/><hr>");
  client.println("<h4><center> Esp8266 Electrical Device Control </center></h4>");
  client.println("<hr/><hr>");
  client.println("<br><br>");
  client.println("<br><br>");
  client.println("<center>");
  client.println("Device 1");
  client.println("<a href=\"/light1on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/light1off\"\"><button>Turn Off </button></a><br />");  
  client.println("</center>");   
  client.println("<br><br>");
   client.println("<center>");
   client.println("Device 2");
  client.println("<a href=\"/light2on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/light2off\"\"><button>Turn Off </button></a><br />");  
client.println("</center>"); 
  client.println("<br><br>");
    client.println("<center>");
   client.println("Device 3");
  client.println("<a href=\"/light3on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/light3off\"\"><button>Turn Off </button></a><br />");  
client.println("</center>"); 
  client.println("<br><br>");
   client.println("<center>");
   client.println("Device 4");
  client.println("<a href=\"/light4on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/light4off\"\"><button>Turn Off </button></a><br />");  
client.println("</center>"); 
  client.println("<br><br>");
  client.println("<center>");
  client.println("<table border=\"5\">");
 client.println("<tr>");
  if (digitalRead(5))
         { 
           client.print("<td>Light 1 is ON</td>");
        
         }
          else
          {
            client.print("<td>Light 1 is OFF</td>");
      
        }
     
        client.println("<br />");
             
         if (digitalRead(4))
          { 
           client.print("<td>Light 2 is ON</td>");

         }
          else
          {

            client.print("<td>Light 2 is OFF</td>");

          }
          client.println("</tr>");


          client.println("<tr>");

          if (digitalRead(0))

          { 
           client.print("<td>Light 3 is ON</td>");

          }

          else

          {
            client.print("<td>Light 3 is OFF</td>");
          }


          if (digitalRead(13))


          { 


           client.print("<td>Light 4 is ON</td>");

          }


          else


          {


            client.print("<td>Light 4 is OFF</td>");


          }

          client.println("</tr>");


          client.println("</table>");

          client.println("</center>");
  client.println("</html>"); 
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
 
}
---------------------------------------------------------------------------------------------





Copy the above code and complete the process. Share and let others know about this tiny chip which can do dozens of magic.


if you like the above tutorial and if you want try out with cool projects you can also check this link here , that's the amazon book link where you can use that book to make IoT with Esp8266 or Nodemcu, that books gives you basic coverage on how to do simple things and get yourself started with arduino and goes on developing projects like sending data to webserver and creating a webserver, uploading and controlling data from a webpage, how to interface TFT LCD and I2C devices and many more things can find on the link.

36 comments:

  1. which is the best place to get one of these wifi board

    ReplyDelete
    Replies
    1. it depends on where you are from? better you can get it from ebay, or aliexpress or amazon many option are there :)

      Delete
  2. How can I connect the relays to my ESP8266 ( My model is different from yours )

    http://www.amazon.in/ESP8266-Serial-Wireless-Transceiver-Module/dp/B00O34AGSU/ref=sr_1_fkmr0_2?ie=UTF8&qid=1452943507&sr=8-2-fkmr0&keywords=iot+espp8266

    ReplyDelete
  3. What is the difference between your
    NodeMCU http://www.amazon.in/ESP8266-NodeMcu-WiFi-Development-Board/dp/B00UY8C3N0/ref=sr_1_4?ie=UTF8&qid=1452944042&sr=8-4&keywords=esp+8266

    and
    the one I am using ? I am confused - as both say 'ESPP' , but yours is a development board ?
    ( Sorry , about asking all dumb questions - but I am new to all this )

    ReplyDelete
  4. This is a risky setup. Since the relay is intended to get a 5V trigger signal and the esp and node deliver 3.3v from the pins I strongly recommend to add logic level shifter to feed the relay with 5V wich it is supposed to operate with.

    ReplyDelete
    Replies
    1. Yep. Agree. Didn't work at my project caused by the 3.3v/5v issue.

      Delete
  5. I copied the code and the Arduino Uno workbench reports ESP8266wifi.h is not there !

    I think I have to download and integrate into the workbench somehow. Please help.

    ReplyDelete
  6. from where we can find out esp8266 library because git hub esp8266 library is not working .

    ReplyDelete
  7. My NodeMCU is not being connected to wifi. Whta's the problem?

    ReplyDelete
  8. Hi, my relay dont turn on the light, but the led that have the relay works when i turn on in the web, but dont open the Fan circuit. All the program works so good. I connected the circuit same than you but I don't know why not work. I test the relay in a arduino mega and works correctly.
    Regards

    ReplyDelete
  9. Great post with great information. One of the very best. I will back agin in future for something new.
    Plastic Gauge Isolator

    ReplyDelete
  10. thanks alot >> but how can i control it over any internet access >> not local wifi ?

    ReplyDelete
  11. where is the server language php or .net code m looking for that ?
    anyone can help tthis out

    ReplyDelete
  12. compilation terminated.





    hai i am new for iot when i run this above code i am getting this below error
    exit status 1
    Error compiling for board Arduino/Genuino Uno.

    ReplyDelete
  13. Thanks a lot for sharing this amazing and nice post,.
    hydroponics

    ReplyDelete

  14. This is gigantic thus exact here. Much obliged to you for posting them.The Industrial Internet of things (IIoT) is disrupting businesses across the globe and will also change the way we live and work.It will not only redefine how machines and humans interact but also improve operational efficiency and increase levels of productivity.

    If you are looking for the Internet of Thing Solutions and services then very big companies available in the market.Thease companies provide the best solutions by integrating the best of our and industry components

    ReplyDelete
  15. Thanks for sharing such good information. It is really nice and informative.
    Keep it up!!!
    Get best tool for Browser hijacker removal.

    ReplyDelete
  16. Wide World of Sports breaking news headlines, live scores and match results..Wide World of Sports

    ReplyDelete
  17. In Today’s very fast world people wish to access any information the internet at their fingertips. So, to stay connected with people all over the world, you require a broadband service that offers you seamless internet connectivity. So, contact us right away to avail the services of Airtel broadband connection in chandigarh

    ReplyDelete
  18. Great post. Needed to write simple word that Thanks for suggestions. Keep it up! best sap simple finance online training institute in hyderabad

    ReplyDelete
  19. gracias funciona muy bien lo mismo en la pc que en el movil ahora solo nwcesito fijar las IP para que no cambien cuando se queda sin energia el modem o lo reinicia el proveedor de internet

    ReplyDelete
  20. This is one of the best malware removal blog I found till date. Found everything I wanted to know at one place. Thanks!Remove Google Chrome Critical ERROR Scam Pop-up

    ReplyDelete
  21. how to do that anywhere over internet not in Local Area Network

    ReplyDelete
  22. Who would've thought IoT would find application even in fields like that. If you're interested into learning more about this fascinating project, just visit this website, it'll give you all the necessary information. Cheers!

    ReplyDelete
  23. Hey! Someone in my Myspace group shared this website with us so I came to check it out. I'm definitely loving the information. I'm book-marking and will be tweeting this to my followers! Outstanding blog and brilliant design. property maintenance software

    ReplyDelete
  24. Nice blog.
    We offer comprehensive placement assistance to students through live practical training, Assignments, and Internships which will prove to be highly beneficial for job seekers.
    courses in digital marketing in bangalore

    ReplyDelete
  25. An amazing web journal I visit this blog, it's unbelievably wonderful. Oddly, in this blog's content made without a doubt and reasonable. The substance of data is informative.
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  26. Sebagai pemain anda jelas mengtahui, bagaimana syarat dan ketenuan dalam permainan dominoqq online
    asikqq
    dewaqq
    sumoqq
    interqq
    pionpoker
    bandar ceme terpercaya
    hobiqq
    paito warna terlengkap
    bocoran sgp

    ReplyDelete
  27. Admiring the time and energy you put into your blog and in depth information you present. It's nice to come across a blog every once in a while that isn't the same out of date rehashed material. Fantastic read! I've bookmarked your site and I'm adding your RSS feeds to my Google account.
    automated welding edmonton

    ReplyDelete
  28. Excellent information I liked it. It will useful and helpful

    Sanjary Academy is the best Piping Design institute in Hyderabad, Telangana. It is the best Piping design Course in India and we have offer professional Engineering Courses like Piping design Course, QA/QC Course, document controller course, Pressure Vessel Design Course, Welding Inspector Course, Quality Management Course and Safety Officer Course.
    Piping Design Course

    ReplyDelete
  29. Thanks for providing the updated information

    Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course,Welding Inspector Course, Quality Management Course, #Safety officer course.
    Welding Inspector Course
    Safety officer course
    Quality Management Course
    Quality Management Course in India

    ReplyDelete