ESP8266 Remote Controlled Sockets

In this project your’re going to build a web server with an ESP8266 that can control remotely any sockets (safely).

Before continue reading this project, please complete the following tutorials:

If you like the ESP and you want to do more projects you can read my eBook Home Automation using ESP8266 here.

Let’s get started!

First, watch the step-by-step video tutorial below

Parts List

Here’s the hardware that you need to complete this project:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Remote Controlled Sockets (433MHz)

You can buy remote controlled sockets in any store or your can buy them on eBay. Keep in mind that they need to communicate via RF at 433MHz. Here’s my setup:

  • Remote control – channel I
  • Socket 1 – channel I and mode 1
  • Socket 2 – channel I and mode 3

remote controlled

RC Switch Library Download

Here’s the Arduino library you need for this project:

  1. Download the RC Switch library
  2. Unzip the RC Switch library
  3. Remove the “-” from the folder name, otherwise your Arduino IDE won’t recognize your library
  4. Install the RC Switch library in your Arduino IDE
  5. Restart your Arduino IDE

The RC Switch library is great and it works with almost all remote controlled sockets in the market.

Receiver Circuit

433mhz receiver circuit esp8266 - Copy

Follow the circuit above for your receiver. Then upload the code below or you can go to File > Examples > RC Switch > ReceiveDemo_Advanced.

/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on inerrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    output(mySwitch.getReceivedValue(), mySwitch.getReceivedBitlength(), mySwitch.getReceivedDelay(), mySwitch.getReceivedRawdata(),mySwitch.getReceivedProtocol());
    mySwitch.resetAvailable();
  }
}

View raw code

Save the TriState Values

Open your Arduino serial monitor at a baud rate of 9600 and start pressing the buttons of your remote. Save the TriState values (highlighted in red) of each key in a notepad. tristatevalues

Schematics (3.3V FTDI Programmer)

The schematics to upload code to your ESP8266 are very straight forward. You only need to establish a serial communication between your FTDI programmer and your ESP8266 to upload some code. Flashing Firmware - FTDI Programmer

Uploading your ESP8266 code

Having the ESP8266 add-on for the Arduino IDE installed (How to Install the ESP8266 Board in Arduino IDE). Go to Tools and select “Generic ESP8266 Module”. Arduino IDE select esp8266 Copy the sketch below to your Arduino IDE. Replace the SSID and password with your own credentials. You also need to change the TriState values. After modifying my sketch upload it to your ESP8266.

/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();
MDNSResponder mdns;

// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

ESP8266WebServer server(80);

// Replace with your remote TriState values
char* socket1TriStateOn = "0FFF0FFFFFFF";
char* socket1TriStateOff = "0FFF0FFFFFF0";
char* socket2TriStateOn = "0FFFFF0FFFFF";
char* socket2TriStateOff = "0FFFFF0FFFF0";

String webPage = "";
 
void setup(void){
  webPage += "<h1>ESP8266 Web Server</h1><p>Socket #1 <a href=\"socket1On\"><button>ON</button></a>&nbsp;<a href=\"socket1Off\"><button>OFF</button></a></p>";
  webPage += "<p>Socket #2 <a href=\"socket2On\"><button>ON</button></a>&nbsp;<a href=\"socket2Off\"><button>OFF</button></a></p>";
  mySwitch.enableTransmit(2);
  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  if (mdns.begin("esp8266", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }
  
  server.on("/", [](){
    server.send(200, "text/html", webPage);
  });
  server.on("/socket1On", [](){
    server.send(200, "text/html", webPage);
    mySwitch.sendTriState(socket1TriStateOn);
    delay(1000);
  });
  server.on("/socket1Off", [](){
    server.send(200, "text/html", webPage);
    mySwitch.sendTriState(socket1TriStateOff);
    delay(1000); 
  });
  server.on("/socket2On", [](){
    server.send(200, "text/html", webPage);
    mySwitch.sendTriState(socket2TriStateOn);
    delay(1000);
  });
  server.on("/socket2Off", [](){
    server.send(200, "text/html", webPage);
    mySwitch.sendTriState(socket2TriStateOff);
    delay(1000); 
  });
  server.begin();
  Serial.println("HTTP server started");
}
 
void loop(void){
  server.handleClient();
} 

View raw code

ESP8266 IP Address

Open the Arduino serial monitor at a baud rate of 115200. Connect GPIO 0 of your ESP8266 to VCC and reset your board.

After a few seconds your IP address should appear. In my case it’s 192.168.1.70.

esp ip address

Final Circuit

This is the final circuit for your ESP8266 that hosts a web server and transmits RF signals to control your sockets.

esp with 433Mhz - Copy

Demonstration

For the final demonstration open any browser from a device that is connected to the same router that your ESP is. Then type the IP address and click Enter!

Screenshot_2015-09-15-18-31-33

Now when you press the buttons in your web server you can control both sockets (watch the video at the beginning of this project for a live demo).

on and off sockets

Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog and my Facebook Page.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

47 thoughts on “ESP8266 Remote Controlled Sockets”

      • Thanks for sharing this wonderful project.I from Malaysia , Esp8266 can talk to each other. I wonder it possible for the esp8266 can talk to all the esp8266 with the same firmware all in one.For example every esp8266 can talk to each other.Let say we have 10 esp install in the same area 10 meter apart within the wifi area . all the esp have a input pir motion detector and output led.If possible one of the esp detection a motion and post the command to the other 9 esp to for the led to go high using their own wifi network. Thanks You

        Reply
          • Thanks Rui Santos I have try you recommended how to make two ESP talk . I found that the server can connect to many clients .But one clients can only connect to one server.
            I wants one client so that many server connect to this client I mean that one client sent a signal that many server can receive Thanks again Have a nice day

  1. Hi Rui!
    Once again i have a doubt and would trouble you..so please bear!

    Whenever i connect my esp to my home wifi, it gets an ip and everything runs well, even after rebooting the ESP with wifi unbooted. But once the wifi modem reboots, the ESP is no longer available at the same ip that i got last time.

    As a product, this will be a huge fault since the user will have to reprogram it again and again for everytime there is a powercut or modem reboot.

    Please tell me how to resolve this.

    Thanks for the past time you replied and for this time also.

    Reply
    • Hi,
      My router doesn’t do that to my ESP. Everytime I restart it has the same IP address.
      This should help you with what you’re looking for: github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en#wifiapsetip
      go to the “wifi.ap.setip()” section

      Reply
  2. Hi. Could you tell me how reliable you have found the connection. I found in the past the esp8266 seem to lock up at some point.

    Have you had your boards running for anyone period of time without issue?

    Thanks

    Trev

    Reply
    • Hi Trev,
      Which power supply are you using? How many clients you connected to your ESP at once?
      If your ESP peaks a high level of current and your power supply can’t supply it. it will shutdown your web server instantly.
      If the ESP-01 doesn’t work for you, try the ESP-12 board. Usually it works better.
      I didn’t try to run this sketch in an ESP for too long. But programming the ESP with Lua using NodeMCU firmware ha proven to me to create more reliable web servers that can run for a few days straight without any problems.

      Reply
      • Hi again.

        I had a bit of a play with them a while back using the arduino ide. I also read quite a bit and it sounded like they were very unreliable back then. I certainly found them to be.

        If you have had a server running for a few days it sounds like they are getting better.

        Trev

        Reply
  3. Hi Rui – Great stuff as usual, thanks! Can i somehow create a “network” of these remote controlled sockets in various rooms, all controlled by one arduino through a web server? I assume there would need to be a RF unit connected to a wifi unit, to control outlets in its proximity? Any guideposts would be greatly appreciated!

    Reply
    • Hi Karazi,
      I would install Raspbian in a Raspberry Pi and I would program a Python web server in your RPi. The RPi would be the main hub and it would receive all the requests within your network.
      Then I would have multiple ESPs acting as clients sending data to your raspberry pi with http post requests!

      Reply
      • Thank you for your response! I have a new version Pi hanging around and have already purchased the esp / ftdi / 433 transmitter/receivers – can I still use these with the Pi implementation in the circuits you diagramed? Sorry to waste your time but would you mind commenting on why you prefer Pi to Arduino for this application? I am still kind of new! Thx!!

        Reply
  4. Hello!

    I’m trying to compile your code on arduino IDE with ESP8266 board, But I’m getting the error:

    Build options changed, rebuilding all
    C:\Users\abc\Desktop\sketch_dec14a\sketch_dec14a\sketch_dec14a\sketch_dec14a.ino:22:27: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    char* socket1TriStateOn = “0FFF0FFFFFFF”;

    ^

    C:\Users\abc\Desktop\sketch_dec14a\sketch_dec14a\sketch_dec14a\sketch_dec14a.ino:23:28: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    char* socket1TriStateOff = “0FFF0FFFFFF0”;

    ^

    C:\Users\abc\Desktop\sketch_dec14a\sketch_dec14a\sketch_dec14a\sketch_dec14a.ino:24:27: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    char* socket2TriStateOn = “0FFFFF0FFFFF”;

    ^

    C:\Users\abc\Desktop\sketch_dec14a\sketch_dec14a\sketch_dec14a\sketch_dec14a.ino:25:28: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    char* socket2TriStateOff = “0FFFFF0FFFF0”;

    ^

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:33:42: warning: converting to non-pointer type ‘long unsigned int’ from NULL [-Wconversion-null]

    unsigned long RCSwitch::nReceivedValue = NULL;

    ^

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp: In constructor ‘RCSwitch::RCSwitch()’:

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:49:28: warning: converting to non-pointer type ‘long unsigned int’ from NULL [-Wconversion-null]

    RCSwitch::nReceivedValue = NULL;

    ^

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp: In member function ‘void RCSwitch::switchOn(char*, int)’:

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:189:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    char* code[6] = { “00000”, “10000”, “01000”, “00100”, “00010”, “00001” };

    ^

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:189:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:189:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:189:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:189:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:189:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp: In member function ‘void RCSwitch::switchOff(char*, int)’:

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:201:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    char* code[6] = { “00000”, “10000”, “01000”, “00100”, “00010”, “00001” };

    ^

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:201:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:201:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:201:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:201:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:201:74: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp: In member function ‘char* RCSwitch::getCodeWordB(int, int, boolean)’:

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:245:61: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    char* code[5] = { “FFFF”, “0FFF”, “F0FF”, “FF0F”, “FFF0” };

    ^

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:245:61: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:245:61: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:245:61: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:245:61: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp: In member function ‘void RCSwitch::enableReceive()’:

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:597:30: warning: converting to non-pointer type ‘long unsigned int’ from NULL [-Wconversion-null]

    RCSwitch::nReceivedValue = NULL;

    ^

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:598:34: warning: converting to non-pointer type ‘unsigned int’ from NULL [-Wconversion-null]

    RCSwitch::nReceivedBitlength = NULL;

    ^

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp: In member function ‘bool RCSwitch::available()’:

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:612:38: warning: NULL used in arithmetic [-Wpointer-arith]

    return RCSwitch::nReceivedValue != NULL;

    ^

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp: In member function ‘void RCSwitch::resetAvailable()’:

    C:\Users\abc\Documents\Arduino\libraries\rcswitch\RCSwitch.cpp:616:28: warning: converting to non-pointer type ‘long unsigned int’ from NULL [-Wconversion-null]

    RCSwitch::nReceivedValue = NULL;

    ^

    It semms like ESP8266 doesn’t support RCSwitch library, Could you please response me how can I fix this issues?

    Thank you!

    Reply
  5. Hi Rui ,Thanks for sharing this project.
    I want to decode RF 433MHz Receiver Module with esp8266.
    I’ve tried to use the RemoteSwitch library with the ShowReceivedCode example, but I did not succeed.
    can you hellp me?
    thanks a lot!!!

    Reply
  6. Hi Rui,
    by adding the following line of code after the mySwitch.enableTransmit(2);
    Users will be able to set the pulse length which i have found varies between RC Outlets.

    Simply add then adjust the timing in microseconds to suit your needs 🙂

    mySwitch.setPulseLength(204); // 204 is my timing adjust to suit

    Reply
  7. ESP8266 Remote Controlled Sockets
    How to connect GPIO 0 of your ESP8266 to VCC and reset your board.
    I tested,does not work, I can see the IP address on the Serial Monitor

    Reply
  8. hei i want to ask, i have use esp8266 with my arduino IDE, i have been succed but, after my esp8266 unpower the program disappear, what should i do ?

    Reply
  9. can anybody help me on using a ESP8266 i have loaded the code which uploaded ok using arduino IDE when i go into serial monitor all i get is dots i have changed baud rate then i get garbge so my baud rate must be ok
    I cannot even type AT command it seams the ESP8266 is talking one way but not back again

    any ideas please

    Reply
    • Hi Nigel,
      I’ve just answered your question in the Random Nerd Tutorials private Facebook group.

      “Hi Nigel Holland, after you upload some code with your ESP8266 it flashes a custom firmware and erases the old AT firmware, so you won’t be able to send more AT commands until you re-flash your ESP with the AT firmware.

      To answer your question, you might now be seeing your IP address, because of a couple of things. Can you double check if you have entered your SSID and Password in your Arduino code? Can you verify that your Arduino IDE serial monitor is on 115200?
      If you can’t see the error try to scan your network for devices using this section “Finding the ESP8266 IP Address” on this guide https://randomnerdtutorials.com/esp8266-troubleshooting-guide/:

      Thanks,
      Rui

      Reply
  10. Bro i had read your tutorial and i raised a doubt about how the data is sent from the Website to the ESP8266 module in background. Could you please help me ………thank you in advance

    Reply
  11. do’nt forget to register the mac adress, ip,hostname of esp8266 in your router to keep the same ip after router reboot.
    on a pc , just type hostname in the adress of browser (not working on android ; why ?)
    and you can do port forwarding with a Free Dynamic DNS to access your device from anywhere in the world.

    Reply
  12. What if I change the password and user name? Do I have to change them through entering the program if arduino and enter the password and user name?

    Reply
  13. Hi, thanks for great tut. I want to ask… Do you know about some lib like rc-switch but for python/micropython? I was searching through internet, but I didn’t find anything… Thank you for perfect work what are you doing…

    Jan

    Reply
  14. Hello Rui and Sara,
    Have you had any attempts at adding Fauxmo, or ESPAlexa to make it so that one could control these outlets with Alexa? If so, What would that code look like?

    Reply
  15. hi great work around.

    for some reason it is not possible to get the tri-state codes, is it also possible to use the binary code in this sketch?

    Reply
  16. Hello Rui Santos

    Tutorial works fine by me. Have now integrated my RF-Remote in Home-Assistant too.

    But i wont add a another RF Remote but i get no Tristate value.
    only that

    Decimal: 10296496 (24Bit) Binary: 100111010001110010110000 Tri-State: not applicable PulseLength: 104 microseconds Protocol: 3
    Raw data: 7398,949,611,435,1128,438,1129,957,616,953,610,943,621,426,1150,936,622,423,1153,415,1142,426,1137,944,621,944,632,937,627,418,1154,410,1152,938,630,414,1132,963,618,943,630,415,1152,415,1167,396,1149,422,1126,

    it is possible to add Binary as Value (change Code)? Any Idea?

    Reply
    • Sven,

      Take a look at the documentation for different types of data can be used. I changed mine to use myswitch.send(“decimalcode”, 24) as the suggestion from this page:
      https://web.archive.org/web/20151007014308/https://code.google.com/p/rc-switch/wiki/HowTo_Send

      Quote from that page:
      Transmission methods
      There are three methods to send raw codes:

      Binary string
      send(string binaryCode)

      Sends the binary string.

      #include <RCSwitch.h>

      RCSwitch mySwitch = RCSwitch();

      void setup() {
      mySwitch.enableTransmit(10); // Using Pin #10
      }

      void loop() {
      mySwitch.send(“000000000001010100010001”);
      delay(1000);
      }
      Decimal value
      send(int decimalCode, int bitLength)

      Same as the first one but using the decimal value. The bit length is needed to zero-fill the binary code.

      #include <RCSwitch.h>

      RCSwitch mySwitch = RCSwitch();

      void setup() {
      mySwitch.enableTransmit(10); // Using Pin #10
      }

      void loop() {
      mySwitch.send(5393, 24);
      delay(1000);
      }
      Tri-state string
      sendTriState(string triStateCode)

      Tri-state codes are according to the data sheets of some encoding chips. Take a look at this blogpost if you are interested in details.

      #include <RCSwitch.h>

      RCSwitch mySwitch = RCSwitch();

      void setup() {
      mySwitch.enableTransmit(10); // Using Pin #10
      }

      void loop() {
      mySwitch.sendTriState(“00000FFF0F0F”);
      delay(1000);
      }

      Reply
  17. Hello, I always follow your publications, I really like the teaching, always very well explained, with diagrams, etc.
    I’m from Brazil and we speak “almost” the same language
    When I was in Lisbon I almost had to use the “translator” lol
    then
    I would like to assemble the receiver using an ESP-01, due to its practicality and possibility of using that board that already has the regulator, relay, terminals, etc.
    I will only use it to monitor the 433mhz RF sensors of my alarm and close the relay (of the siren) if there is a violation of any of the sensors
    but I didn’t find any instructions on how to use the IRQ on this board.
    thanks

    Reply

Leave a Reply to gdaelen Cancel reply

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.