Introduction: WiFi / Internet Controlled Relays Using ESP8266 - Quick, 30 Minutes IoT Project

ESP8266 is a very popular device for IoT these days. ESP8266 is easily available as a module. Its a small and dirt cheap device which has a inbuilt controller running at 80Mhz and with optional firmware it can be used as a stand alone device without a microcontroller like arduino.

Video of working project and overview of making process -

This project is very simple and uses an ESP8266 module ESP-01. It has pinout headers which provides very easy connectivity with other devices. A 5V 2A AC power supply, a voltage regulator and optoisolated 2 relays board is used. A CP2102 USB-UART is used to program and configure the ESP module. The module is loaded with NodeMCU firmware which support Arduino like functions for GPIO and lua scripting support.

Part List

ESP8266 module ESP-01

Opto-isolated 2 Channel 5V Relay Board

SMPS Supply 5V 2A

LM2596 DC to DC 3A Step Down Module with Voltage Display - or any other step down voltage regulator to convert 5V to 3.3V for ESP module. Even a cheap IC like LM317 or LM1117 will do.

CP2102 USB UART module - or any other 3.3V compatible USB-TTL UART adaptor

Jumper wires

Step 1: Prepare and Test the Power Supply

  1. Take a red and black jumper wire. Cut it in half. Strip the ends.
  2. Take power adaptor and cut the connector end. Strip the ends and connect them to red(to positive) and black(to negative) jumper wires in correct polarity. Use a multimeter to check positive and negative ends. Solder the open ends.
  3. Twist and tin the ends of other 2 jumper wires.
  4. Connect the power adaptor to input screw terminals of regulator in correct polarity.
  5. Connect other 2 red and black jumper wires to output screw terminals. Red to positive and black to negative.
  6. Power on the adaptor after double checking the connections and set the output voltage to 3.3 by changing the potentiometer.
  7. If you are using any other type of voltage regulator, use your knowledge to give input and take output from it.


Connect the relay board and test for working on the power supply

Connections

  • +5V (Red wire at input terminal) - VCC of relay board
  • GND (Black wire at input terminal) - GND of relay board

Relay board is now powered up. For testing the working, connect black wire(GND) at 3.3V output screw terminal to IN1 and IN2 pins on relay board. It should trigger relay and glow corresponding LEDs. If it doesn't check your connections. You may remove the connections for now if you want.

Connect and check ESP-01 for power

Once you verify that relay board is working and 3.3 V output is set, turn the power off and connect VCC and GND of ESP-01 to Red and Black jumper wires in proper polarity. Verify the connection and turn on the power. The power LED on module should glow. Remove the connections for now.

Now the power supply is set and tested with devices.

Step 2: Prepare & Program the ESP01 Module

By default ESP module comes with AT commands firmware which is good but normally it requires another microcontroller like Arduino to control it using AT commands on serial. For this project we are not using any microcontroller so we need use the ESP as everything. For this we need to update the firmware. We will be using NodeMCU firmware for the same.

All information on NodeMCU is here : https://github.com/nodemcu/nodemcu-firmware

Download softwares and other files - these instructions are for Windows.

http://esp8266.ru/esplorer-latest/?f=ESPlorer.zip (Needs Java Runtime)

https://github.com/nodemcu/nodemcu-flasher (Download from release folder for 32 or 64 bit OS)

http://robokits.co.in/download/init.zip - Firmware for wifi module. Download, unzip and edit with editor like Notepad++ or Sublime. Change the IP address and your WiFi SSID and Password for your router. See comments in file.

For programming we need a USB-TTL UART converter module such as CP2012 or FTDI (3.3V).

Connections

ESP VCC - ESP CH_PD to 3.3V +ve (Output from Regulator)

ESP RX - UART TX

ESP TX - UART RX

ESP GND - ESP_GPIO0 to system GND

UART GND to system GND

Note - any GND will work anywhere as all of them are common (Shorted internally).


  • Connect the USB-UART to USB port of PC/Laptop
  • It will generate a virtual COM port. Note the port number
  • Open NodeMCU Flasher, select com port and hit Flash.
  • Wait till flashing finishes. It will take about 50 to 90 seconds. If flashing doesn't start make sure connections are proper and module is powered up using external supply. It will not work properly on USB supply.
  • If flashing stops inbetween, restart the power to ESP module and flash again till it completes properly.
  • After flashing is finished successfully remove power and USB. Remove the short between ESP GND pin and GPIO0 pin.
  • Open ESPlorer software (it needs Java, download and install if not already installed). Connect on the same COM Port as Flasher at 9600 baud rate. Don't worry for firmware detection errors if any.
  • Upload the init.lua file after modifying your required IP address, WiFi SSID and Password (Key). You may use Notepad++ or Sublime Text Editor for the same. It may not open properly in normal notepad. Upload button is on the bottom left part of ESPloarer software.
  • Reset controller using reset button on bottom center part of software.
  • If you have set setting properly in lua file you should get connected IP address. Edit init.lua file if there is any error or you are not getting connected to wifi.
  • Now you may open the IP address you set in browser to check if the server is working properly or not. If you get a page with 4 on/off buttons its working fine. Turn the module off and remove UART connections.

Step 3: Connect Everything Together and Test

Now keeping the power off make/check following connections.

  • ESP VCC - +3.3V (Keep VCC and CH_PD shorted for ever)
  • ESP GND -GND
  • ESP GPIO0 - Relay Board IN1
  • ESP GPIO2 - Relay Board IN2
  • Relay Board VCC - +5V
  • Relay Board GND - GND
  • Adaptor +5V to Regulator +ve Input
  • Adaptor - to Regulatore -ve Input
  • Adaptor +ve output - 3.3V
  • Adaptor -Ve output - GND

Once this is done, power on the adaptor and open the set IP address in your browser. Turn relays on/off and see that the realys on relay board will work accordingly. Now you can control these relays from any device connected to your network like phone or tab with browser.

You can also control this device thorugh internet by using any DNS service like duckdns or no-ip.com. Many routers support No-IP and other DNS services which will keep your dynamic IP address updated. You may use other ports than port 80 (in init.lua file to create server) in order to control multiple devices on same public (internet) IP.

Comments

author
speedytex (author)2017-06-15

Could I use this to trigger a dc switch that opens and closes my driveway gate opener via internet with my iphone or can you recommend another solution

author
panttal (author)speedytex2017-07-03

yes, you can all you need to setup server and internet access via your own domain or using sub domain from some ddns domain service provider like, noip.com, dyndns.org etc.

author
EdyW (author)2017-06-12

I updated init.lua thru ESPlorer because a IP change. It seams to upload ok (upload successful), but when I reset the module, it shows old IP numbers..

any help, please?

author
NitinS37 (author)2017-05-13

I can upload the program to my esp but cant access its IP address, it shows junk values in my serial monitor.... can any one help me here ?

author
abhinnkp (author)2017-03-14

Hi,

Can you do another Instructable showing the controlling of relay modules over the internet. I'm very much interested in it.

author
SelvaK3 (author)2017-02-28

Instead of using web server, can I use an another esp8266 to send the control signal to the esp8266 connected with relay.

author
budhaditya.biswas.7 (author)2017-01-11

why not this code is running in init.lua file?? please help

<html><body>

<h1 style="font-size:500%; text-align:center; color:red"><b>IOT based Relay Switching</b></h1>

<table align="center" style="border:2px solid red; width:50%; height:120"><tr><td align="center" style="border-style:solid; border-width:2px"><b><font face=Verdana; size=5; color=black>Relay 1</font></b></td>

<td align="center" style="border-style:solid; border-width:2px"><b><font face=Verdana; size=5; color=black>Relay 2</font></b></td></tr><tr>

<td align="center" style="border-style: solid; border-width:1px"><a href=\"?pin=ON1\"><button><font face="Verdana" size=5 color=green><b>ON</button></b></font></a></td><td align="center" style="border-style: solid; border-width:1px" ><a href=\"?pin=ON2\"><button><font face="Verdana" size=5 color=green><b>ON</button></b></font></a></td></tr>

<tr><td align="center" style="border-style:solid; border-width: 1px"><a href=\"?pin=OFF1\"><button><font face="Verdana" size=5 color=red><b>OFF</button></b></font></a></td><td align="center" style="border-style:solid; border-width: 1px"><a href=\"?pin=OFF2\"><button><font face="Verdana" size=5 color=red><b>OFF</button></b></font></a></td></tr></table>

</body>

</html>

author
immortalsantee (author)2016-11-07

Can you tell me the reason of reset in esp8266 v1 module while connected to relay with 220v. I have tried esp8266 with relay with 3.3v and 5v, and it works perfectly. But when i connect 220v to relay and control relay with esp8266 the result is unpredictable. It works for a while (220V connected case). But after certain attempt, esp8266 stops responding. Can you help me what might be the problem? For easiness I have made image of what I have done till now. Please have a look.
http://santoshm.com.np/wp-content/uploads/2016/11/diagram.jpg
Thanks.

author

I put a capacitor on the line from the relay in to the esp8266 gpio and that fixed the problem for me. Hope that helps at all

author

I have the same problem as you. The relay/esp both work fine until I connect the relay to mains voltage... Did you ever get an answer to your question or figure out a solution?

Thanks

author
RasmusS1 (author)2015-11-06

Hi,

Thank you for guidance, it works!
I have a question for the firmware.
I want the first relay to turn on for 20 seconds and then turn off,
and the other one must turn on and off instantly.
Is there an easy way to get it to work?

author
Robokits (author)RasmusS12016-01-25

You can do it with simple scripts. Now you can also use arduino ide for programming in arduino compatible C.

author
RasmusS1 (author)Robokits2016-09-27

do you mind pointene me in the right direction?

author
darshan_syntrons (author)2016-08-26

Hello,

I have used AT Command which is sequence given below:

AT

AT+CWMODE=2

AT+CWSAP="IndiaAP","1234test",5,3

AT+RST

AT+CIPMUX=1

AT+CIPSTART=1,"UDP","192.168.4.100",80

AT+CIPSERVER=1,80

AT+CIPSTO=3600

AT+CIPSEND=1,5

12345

Use 300ms Delay for avoid busy -------

AT+CIPSEND=1,5

12345

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

My problem is that how to reduce 300ms delay between send two data packets.

Please anyone can help me...

author
SpinCOR8 (author)2016-08-18

Hello - Thanks for the Project! It's exactly what I need to save some coin over using a more expensive alternative. Your Instructable rocks! Unfortunately I'm getting: "ERROR: Communication with MCU not yet established" in the ESPlorer v0.2.0-rc3 IDE. I was able to flash the NodeMCU firmware at a 9600bps on the first try! And I believe my power config at 3.3V to ESP-01 with only a shared GND to CP210x is good. CP210x is powered by PC. My LM2595 step-down is powered by a AC/DC wall plug at 5.5vdc/500ma.

I've pulled the GND to GPIO0 jumper. COM3 port says it's opened and I've mirrored the baud rate in my Win7 OS. My CP210x has latest driver. My port setting are: 9600bps, 8db, No: Pairty, 1sb, No: Flow Ctrl.

I cycled through each baud rate option hoping for a miracle to no avail. Finally, I did try two different ESP-01s in hopes the one antenna may have been defective and still can't get any communication. Please help? Thanks again!

author
Robokits (author)SpinCOR82016-08-19

If you have flashed the nodemcu firmware successfully, you need to disconnect GND and GPIO0 otherwise the module will stay in bootloader mode and you will not be able to use it normally. You can only flash in this mode. Other things should be fine. You should at least get a startup message from nodemcu when the module starts.

author
SpinCOR8 (author)Robokits2016-08-20

Thanks for the quick reply! It turns out I had a bad jumper wire connection or two that was either effecting the TX/RX and/or power stability. A complete rework of my benchtop configuration solved the enigma. Thanks again for the quick reply and the project!

author
SpinCOR8 (author)SpinCOR82016-08-20

Hello thanks again for your willingness to share your expertise. My next problem is I can't get the webpage to start. The only changes I've made to the init.lua file is as you instructable (e.g. IP, SSID, p/w). I'm working in the same room as the WiFi router (2.4 ghz, 802 1.1, WPA/WPA2 PSK). I even reformatted/reloaded .lua on the ESP01. Any suggestions?

author
smocksam (author)2016-08-04

So my switches are opposite of what they should be. I ought to be able to figure that part out on my own.

However there is no indicator to tell if you turned things on or what state they are in when you load the page. Would there be a way to put an indicator that shows whether it's off or on?

thanks

author
Jose LuisG35 (author)2016-07-29

Hello,thanks for project.For me everything is ok,except,that only one relay works.I can see de buttons on web page,but only relay one work.When i push button 2 on,nothing happen.I have pull-up resistors for rst,chpd,gpio0 and gpio2.Without resistors,nothing works.I have check de conections,power supply,esp module,etc, and everything seems fine.Also i have no problem to access the web page from my destok pc,but i cannot,from my phone,ipod,or my tablet.All my devices are in the same network.Can you help me with this?.

Thank you in advance,and sorry for my english.

author
Robokits (author)Jose LuisG352016-07-29

Can you check if your relay works -> give VCC to relay input pin.

Secondly check if your esp module gives output. Check the pin with reference to GND.

author
Jose LuisG35 made it! (author)Robokits2016-07-31

Now,both relays working.I think the problem was de ESP-01 module and i will check well later.I have notice that when i press relay 2 button,the blue comunication led on ESP-12-E module goes on.Is this normal?.

As i said before to Vaidyasp,i need four relays for my project,and also i need access outside of my wifi network.I do not know nothing about programming,so please,can you help me with this?.I will appreciate it.

Thank you so much.

IMG_20160731_2232435_rewind.jpgIMG_20160731_2224104_rewind.jpg
author
Jose LuisG35 (author)Robokits2016-07-30

Hi again.I have changed the wires for relay 1 and 2,and both relays works fine.If i check gpio0 when i push button 1,gpio0 goes down 0v and activate relay,but when i push button 2,gpio2 remain high,and relay is not activated.I have re-checked,conections in esp module,breadboard,power supply,and all seems ok.I had thought ,the problem was the pull-up resistor,but gpio0 have another one,and wors fine.I realy do not where the problem can be.Init.lua?.

Thanks a lot.

author
vaidyasp (author)Jose LuisG352016-07-30

The file is fine and working, It may be problem of programming. Try re-uploading the code using upload button in esplorer. You may also check your module's io pin working with some other code.

author
Jose LuisG35 (author)vaidyasp2016-07-31

Thanks for reply.At this moment i am trying with another module,a ESP-12-E.

For my project ,i need four relays,and the ESP-01,has only two gpios.If this module works,i will need help with the lua script and the access outside my wifi network.I am electronic technician,but i am rookie in programming,no matter what languaje.

Thank you very much.

author
KrauserS (author)2016-07-03

guys please I'm just newbie here. Where do I find the code for this? Thank you

author
Robokits (author)KrauserS2016-07-29

Its already in description.

http://robokits.co.in/download/init.zip

author
zelic (author)2016-06-30

Awesome project! I made it but i have one little problem when I go to webpage it shows only header "Robokits IOT Server" i dont have buttons but i know that this thing works when i type http://192.168.0.87/?pin=ON1....What I have done wrong? Sorry for my English...

author
zelic (author)zelic2016-06-30

Hope this helps...

esp.png
author
Robokits (author)zelic2016-07-29

Upload the file directly. When you uplaod through esplorere editor it sends the file line by line and tries to execute it on ESP8266. Some long lines or some lines with complex html may not work. Upload the complete file using upload button in left bottom row.

author
JohnW166 (author)2016-01-30

Mine works great however after 2 days it no longer serves up the webpage. I have to recycle the power to the esp8266 and it all good.
My power supply is rock solid and my wifi router is never turned off or ever needs rebooting.
Do you know why this happens? I have checked in my router setup for anything about expiring ip leases etc but nothing was there to help.
Only way to fix it seems to be adding something to cycle the power every day or so.

author
Robokits (author)JohnW1662016-06-23

No idea why this can happen. Keep the serial link connected and debug for the reason why its rebooting. In worst case keep a timer which will reboot module in few hours.

author
TsunamiS1 (author)2016-02-11

Hey, followed the tutorial precisley, the website show up at my desired ip the voltages are correct. But when i try to switch the relays on or off nothing seem to happen? any suggestions on this? firmware is flashed and the init.lua is on the esp8266

Greetings Tibor

author
Robokits (author)TsunamiS12016-06-23

Check the voltages on ESP pins. If you get the voltage check the electronics and connections, if you don't change esp module and check.

author
James-Willetts (author)2016-02-20

Tried for seven hours to get this working without success. I managed to get the ESP8266 to connect as per the video but no web page. I have two devices and programmed both the same one connected to network the other did not. If I change station to station AP on the one that does not connect it creats a hot spot but still no web page. I have used Notpad++ to edit can anyone help

author
Robokits (author)James-Willetts2016-06-23

Try this and check.

wifi.setmode(wifi.STATIONAP)

It will be in both node and router at the same time.

author
asantos5 (author)2016-03-13

Hello My Friend, It's a great tutorial, i searched many times but I don't figured out how to replace that second relay by a push button, my intention is to when the button is pressed, the relay is turned (if ON, turn OFF and if OFF turn ON) and on the web page show state and turn the relay too or by mqtt...

author
Robokits (author)asantos52016-06-23

Try this

local x=0;

if(_GET.pin == "ON1")then

if(x == 1)then

gpio.write(Relay1, gpio.LOW);

x=0;

else

gpio.write(Relay1, gpio.HIGH);

x=1;

end

end

Its not tested but something around this should work.

author
FrancescoG28 (author)2016-03-28

I can't set my esp8266 on station mode I don't know why... I followed step by step this tutorial :( can you help me?
tnx

author
Robokits (author)FrancescoG282016-06-23

You may remove or comment these lines and check.

cfg = {

ip="192.168.2.87",

netmask="255.255.255.0",

gateway="192.168.2.15"

}

wifi.sta.setip(cfg)

author
Robokits (author)FrancescoG282016-06-23

You may remove or comment these lines and check.

cfg = {

ip="192.168.2.87",

netmask="255.255.255.0",

gateway="192.168.2.15"

}

wifi.sta.setip(cfg)

author
Robokits (author)FrancescoG282016-06-23

You need to specify the network ssid and password correctly. You can choose to have a static ip or get an IP assigned through DHCP.

author
t0bi (author)2016-06-08

Hi Robokits!

Nice easy work, good understanable, I made it, works well.

Pls give an answer: why does not work it with iPhone?

Does it need a meta Tag?

author
Robokits (author)t0bi2016-06-23

It should if you iphone connects to the network created by ESP8266. Basically its just pushing data when requested by web browser.

author
chimeranzl. (author)2016-06-23

Should this circuit not have a transistor with resistors doing the switching? Eg: the recommended way? Similar to the Arduino to drive a DC relay: http://playground.arduino.cc/uploads/Learning/relays.pdf

author
Robokits (author)chimeranzl.2016-06-23

Well you are right when you want to drive a relay but if you see the relay board we are using here it contains the circuit to turn on the relay which contains an optoisolator. With optoisolator driven relay circuit the ESP has to just turn on an LED to turn on the relay.

author
mastermetal08 (author)2016-04-12

If anyone interested, iPhone superusers could combine SIRI with assistant+,activator and simple curl command to voice control ESP-01. Or, Simple springboard icon flicks triggering curl commands (e.g. curl -X POST 192.168.x.x/?pin=ON2 >/dev/null )

author
GopalaK5 (author)2016-02-03

after updating firmware its not responding at commands. what i want to do now please tell me.

author
piotruuch. (author)2016-01-25

Hello!

I have a problem. Wants to relay 1 after turning work 30sec and shutdown. Will it be good:

if(_GET.pin == "ON1")then

gpio.write(Relay1, gpio.HIGH);

wait(30);

gpio.write(Relay1, gpio.LOW);

elseif(_GET.pin == "OFF1")then

gpio.write(Relay1, gpio.LOW);

author
85rocco (author)2016-01-23

Very nice. I'm looking to do something rather similar, my hardware would be exactly the same as yours however but with a different user interface. Instead of an On button and an Off button, I want just a single button (per relay) which activates the relay only when the button is pushed and turns off the relay when the button is released. Any thoughts that might get me pointed in the right direction?

About This Instructable

184,124views

1,058favorites

License:

Bio: We are group of makers who love and create different products related to hobby electronics, automation and OEM consumer and industrial products.
More by Robokits:Control Nema Stepper Motor With Arduino And Micro stepping Drive Getting Started with Arduino and Visual Basic 2008WiFi / Internet Controlled Relays using ESP8266 - Quick, 30 minutes IoT project
Add instructable to: