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.

59 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. Nice blog thanks for sharing details http://elweigh.com

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

    ReplyDelete
  18. 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
  19. Great post. Needed to write simple word that Thanks for suggestions. Keep it up! best sap simple finance online training institute in hyderabad

    ReplyDelete
  20. 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
  21. 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
  22. how to do that anywhere over internet not in Local Area Network

    ReplyDelete
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. Great post!!
    Thanks for Sharing a useful content about Internet of things (IoT), Definitely IOT will be the Game Changer of all technology
    IoT Training courses | IoT training

    ReplyDelete
  32. Thank you a lot for giving everyone an exceptionally splendid possiblity to discover important secrets from here. It can be so useful and also packed with a great time for me and my office fellow workers to search the blog at least three times in 7 days to read through the new issues you have. And of course, I am at all times motivated with your great tips and hints you serve. Selected two points in this article are honestly the most effective we have ever had.
    electrical engineering edmonton

    ReplyDelete
  33. Thanks for sharing is so amazing and helpful to us.
    Buy Hydrocodone online

    ReplyDelete

  34. Best Article buy Pain Pills online Excellent post. I appreciate this site. Stick with it! Because the admin of this web page is working, no doubt very quickly it will be well-known, due to its quality contents.This website was how do you say it? Relevant!! Finally, I’ve found something that helped me.
    Best Article buy Roxicodone online Excellent post
    buy Xanax online
    buy Oxycodone online

    Best Article buy Pain Medications online Excellent post. I appreciate this site. Stick with it! Because the admin of this web page is working, no doubt very quickly it will be well-known, due to its quality contents.This website was how do you say it? Relevant!! Finally, I’ve found something that helped me.

    buy Research Chemicals online

    buy Roxicodone online

    buy Cbd Isolate online

    ReplyDelete
  35. Nice post. It is really interesting. Thanks for sharing the post!
    Buy AC Online | Smart LED TV
    Laptops for Sale | Best Inverter AC

    ReplyDelete
  36. Thanks for sharing 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."
    Piping Design Course
    Piping Design Course in India­
    Piping Design Course in Hyderabad
    Welding Inspector Course
    Quality Management Course
    Quality Management Course in india
    Safety officer course

    ReplyDelete
  37. Thanks for sharing 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."
    Piping Design Course
    Piping Design Course in India­
    Piping Design Course in Hyderabad
    Welding Inspector Course
    Quality Management Course
    Quality Management Course in india
    Safety officer course

    ReplyDelete
  38. Internet - The internet is a global wide area network that connects your computer to the world. High-bandwidth data lines are the backbone of the internet. The data-line is connected to the webserver and internet service providers. The internet service provider or ISP serve as intermediaries between your computer and the internet. The internet provides a range of services online. Some of them include the web is a mammoth collection of web pages that can be viewed on browsers, email which allows us to send and receive messages online, social media can be viewed on websites or apps, online gaming allows players to play against each other or collaborate and software updates for your operating system or applications. For more information visit: computermobile.info

    ReplyDelete
  39. Really fine and interesting informative post. I used to be looking for this kind of post and i enjoyed looking over this one. Thank you for sharing.
    Learn PMP Training in Hyderabad 360DigiTMG

    ReplyDelete
  40. Ontdek onze Contactgrill! - Kookstore.nl - De grootste collectie keukenapparatuur, kookartikelen en keukenaccessoires online! - Contactgrill kopen Wist je dat je verschillende voedingsproducten kunt grillen? Je kunt hierbij denken aan groenten, aan vis, aan vlees en zelfs aan tosti’s. Het enige wat je hiervoor nodig hebt, is een contactgrill. Een contactgrill is een ontzettend handig en innovatief apparaat. Met dit apparaat heb je namelijk géén…

    ReplyDelete
  41. We are offering high quality social media marketing services. Like Facebook, Yahoo, Hotmail, Outlook, Gmail, Google Voice etc. buy outlook pva accounts

    ReplyDelete
  42. Happy to visit your blog, I am by all accounts forward to more solid articles and I figure we as a whole wish to thank such huge numbers of good articles, blog to impart to us.
    360DigiTMG internet of things course

    ReplyDelete
  43. Hi, I am complete begginer with this kind of IOT stuff. I found NodeMCU with ESP8266, I tried to copy the code to arduino IDE, it succesfully flashed the device, but after reset I dont see any wifi network created by the NodeMCU...whatever project I tried, all works (LED blinking etc) but I dont see any newly created Wifi AP...can anybody help what I am doing wrong with the Wifi?...I tried replacing the device to new one, I tried to flash its firmware wit some standard, and custom build, etc...but no luck.Thanks.

    ReplyDelete
  44. In my opinion, email marketing is a campaign that needs to be used by companies that are serious about increasing their business sales.buy twitter accounts
    Email marketing is an online advertisement strategy which uses electronic means to communicate with prospects and customers. Email marketing is one of the most effective internet advertising tools because it helps you in creating a brand image. It is one of the most cost effective ways to generate leads for your business. It is important that your business does not just survive but also thrives on a daily basis through an efficient email marketing campaign. There are so many benefits associated with email marketing and below are some of them:

    ReplyDelete
  45. Really its very easy ot see after coding from this blog post..Buy Facebook accounts

    ReplyDelete
  46. Are you interested to learn the many important things Buy Gmail accounts that can be done using a Forex blog? If yes, then please do read the following brief article which is all about "Learn The Forex From An Expert". In this article I am not only going to discuss "Learn The Forex From An Expert" but I will also tell you about how to start using a Forex blog to earn some money as well. So, just check out the contents of this article below and you would surely be able to earn some money using a Forex blog!

    ReplyDelete
  47. This article discusses the importance of this blog Buy Youtube accountsfor business promotion. Promoting a blog is just like promoting any other website and can be difficult to do if you are not sure what needs to be done, but with the right tips and tricks, this doesn't have to be. Hopefully, you find this article on this blog helpful and decide to visit the site below to see just what they are talking about.

    ReplyDelete
  48. This obviously makes every readers to thank the blogger and hope the similar creative content in future too.
    Buy Gmail Accounts

    ReplyDelete