ESP8266 wifi light switch

This IoT project will guide making ESP8266 wifi light switch on wall, which uses relay 5VDC to control lamp remotely.
The lamp can be turned on/off by phone (via wifi) or by local switch. In case no phone, we still control it by phone. In case of ...lazy, we can control lamp via local wifi network.
Result video:



Hardware need:
(1) ESP8266
(2) Power module 220V to 5VDC
(3) Power module 5VDC to 3.3VDC
(4) Electronics: relay 5VDC, transistor, resistor
1. ESP8266
3. Power module 5VDC to 3.3V
2. Power module 220V to 5VDC



Software need:
(1) Arduino IDE
(2) Firmware for ESP8266

Step 1. Make circuit





Step 2. Programming ESP8266
Using Arduino IDE to program firmware for ESP. To know pramming by Arduino IDE, please see our article link here
After first download, ESP8266 will be downloaded by OTA (over the air), instruction to do it link here
Download OTA helps us update firmware ESP8266 without touching the board. It's easy for next modify when the board is already installed to the wall.

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
//------------------------------for local web
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

MDNSResponder mdns;
ESP8266WebServer server(80);
String webPage;
//----------------------------for local web

const char* ssid = "NguyenTuong";
const char* password = "064897435";
int pinout=14;  //for relay
int pinsw=12;  //for switch
boolean light_change;
boolean sw_status;

void setup() {
  pinMode(pinout, OUTPUT);
  pinMode(pinsw, INPUT);
  Serial.begin(74880);
  Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  // No authentication by default
  ArduinoOTA.setPassword((const char *)"123");

  ArduinoOTA.onStart([]() {
    Serial.println("Start");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  //-----------------------------------------add your code here
  webPage += "<center><font size='27'>ESP8266 Web Server<p>Light #1 ";
  webPage += "<a href=\"light1_change_status\"><mark>TOGGLE it";
  webPage += "</mark></a></p></font></center>";

  if (mdns.begin("esp8266", WiFi.localIP())) 
    Serial.println("MDNS responder started");
 
  server.on("/", [](){
    server.send(200, "text/html", webPage);
  });
  server.on("/light1_change_status", [](){
    server.send(200, "text/html", webPage);
    // Change status
    light_change = true;
    delay(100);
  });

  server.begin();
  //-------------------------------------------add your code here
}


void loop() {
  ArduinoOTA.handle();
  //-------------------------------------------add your code here
  server.handleClient();
  if(light_change)
  {
    light_change = false;
    if(digitalRead(pinout)) digitalWrite(pinout,LOW);
    else digitalWrite(pinout,HIGH);
  }

  if(sw_status != digitalRead(pinsw))
  {
    sw_status = digitalRead(pinsw);
    light_change = true;
  }
  delay(200);
  
}

Step 3. Test it
Here is our real model, looks small:

Overall connection:




This module has IP address 192.168.1.30
After power on, ESP will connect to local wifi network. Type IP address into web browser, a local web server will show, relay can be controlled from here









38 comments:

  1. Very nice project. Good documentation. You should be teaching thus stuff.

    ReplyDelete
    Replies
    1. i am not able to control the relay from the browser. i have done all the above mentioned steps but still no success instead the relay is closing and opening in a loop. please help.

      Delete
    2. Check if GPIO14 can be ON/OFF. If yes, check transistor, or power supply for transistor not enough for relay operation.

      Delete
  2. Near the lamp, on the relay, should be 5v instead of 3.3v, right?

    ReplyDelete
    Replies
    1. yes, you're right. If you use 5VDC relay, it should be 5V.

      Delete
    2. I do not know how to you feeback ?

      Delete
  3. useful project. Thanks

    ReplyDelete
  4. hi.i was wondering if i can connect a esp8266 12E directly to an arduino uno and program them so i could give order to esp8266(for example turn GPIO14 high) over wifi and then arduino read the esp 14 pins that is connected to on of its digital pins(8) as input and alter one of another digital pins(like 10 or 11). is this possible?

    ReplyDelete
    Replies
    1. Hi, i think it is possible. Please search on Google or Youtube about the way program ESP12E by UNO.
      ESP12E is also possible connecting with other Arduino board (UNO, Pro Mini) to control GPIO -> You can use UART, or SPI communication between ESP12 and other Arduino board.

      Delete
    2. I am using the same code on nodemcu to control switch directly from GPIO pins,I think using transistor you can get more reliable results , maybe !! :P

      @engineer2you Thankyou , found exactly what i was looking for :)....

      Delete
  5. Exclusive post. Thanks for sharing with us.
    Smart Plug

    ReplyDelete
  6. Good little project. Some ideas for improvement in the circuit. GPIO pins could control opto-isolation LED, and on the other side, power the Relay with a different voltage source. That way, relay back EMF won't enter ESP8266 circuit. Also, a discussion about HomeAssistant integration would be fantastic.

    ReplyDelete
  7. One way to test if your relay will glitch your ESP8266 is to click the relay off and on with a high duty-cycle -- say 80Hz.

    ReplyDelete
  8. Fantastic and useful we blog thanks for publishing this.it's useful and informative.keep up the great.
    2 Way 2gang Wireless Light Touch Switch

    ReplyDelete
  9. hi nice project.
    can u pls tell me if i have to use "two way" switch or ordinary switch?

    ReplyDelete
    Replies
    1. use "two way" if you need control light remotely

      Delete
  10. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me. Unique wifi names

    ReplyDelete
  11. This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post.! lemigliorivpn

    ReplyDelete
  12. Hi, ground wire means 0V of power supply 0V-5V. Sorry about this confusion. I should write 0V instead of GND

    ReplyDelete
  13. Thanks for such an awesome project.
    Can you please modify the code for Nodemcu working in AP mode for multiple channel relays with manual switches option.
    This will eliminate the need for a local wifi network & IP assigning issues as the system will work on fixed AP mode IP. Awaiting your earliest positive response.

    ReplyDelete
    Replies
    1. Hi, thanks for visit my site.
      You're right, making AP mode will no need local wifi network & IP assigning. I will make this kind project in another post. It's also not difficult, i guess you can make it by yourself. I'm quite busy these days :)

      Delete
  14. Good project this ESP8266 wifi light switch
    but sir i require when lamp on/off through switch its indicate in web page

    ReplyDelete
    Replies
    1. Hi, if you need indicate, you should use input of ESP8266 to detect status of light to show on web page

      Delete
  15. When I'm connect esp8266 module with same SSID and password as set on program, but it not working when control different network operate on PC or mobile.

    ReplyDelete
    Replies
    1. basically, it works in same network. Example, ESP8266 IP is 192.168.1.30, so it will work in network 192.168.1.xxx, it can't work in network 192.168.xxx.xxx

      Delete
    2. Thank you sir
      But I can how to control from anywhere my led.

      Delete
    3. Hi, if you want so, you should search for "ESP8266 control via internet" where you will need to open the port.

      Delete
  16. wow, great, I was wondering how to cure acne naturally. and found your site by google, learned a lot, now i’m a bit clear. I’ve bookmark your site and also add rss. keep us updated. KRM Light+

    ReplyDelete
  17. I think that thanks for the valuabe information and insights you have so provided here. track light fixtures

    ReplyDelete
  18. This article is an appealing wealth of useful informative that is interesting and well-written. I commend your hard work on this and thank you for this information. I know it very well that if anyone visits your blog, then he/she will surely revisit it again. https://enisxytissimatoswifi.eu/

    ReplyDelete
  19. Acknowledges for paper such a beneficial composition, I stumbled beside your blog besides decipher a limited announce. I want your technique of inscription. touch switches India

    ReplyDelete
  20. Very good written article. It will be supportive to anyone who utilizes it, including me. Keep doing what you are doing – can’r wait to read more posts.Poker Online

    ReplyDelete
  21. You can also extend the coverage of the router with the use of repeaters or extenders - these are available from many stores. internet router

    ReplyDelete