WiFi-controlled Power Switches Based on ESP8266-ESP01 and Managed Via WebThings

by imageguy in Circuits > Microcontrollers

1583 Views, 11 Favorites, 0 Comments

WiFi-controlled Power Switches Based on ESP8266-ESP01 and Managed Via WebThings

Four relay ESP8266-ESP01 example
2020-11-04_16-13-39.jpg

A couple of winters ago I moved to a house that had roof heaters to combat a persistent ice dam problem. “They just turn the panel breakers on when the first snow falls and leave them on for the winter,” said the selling real estate agent.

This plan lasted only until the first eye-watering power bill. A better solution was needed. There was no way to add a central switching panel for all the zones without extensive wiring work. But a WiFi controlled switches placed in the outlet boxes would do the trick.

My main design parameter was that the switches fit into standard 1 or 2 gang electrical boxes, so I could just replace the current outlets. Space was tight, so the only solution was to use Espressif ESP8266-ESP01 as a controller that provides WiFi connectivity and can drive up to four circuits in a tiny package.

Each controller contains a 110V power supply. The actual switching is done by G5LE relays. The whole system is managed using WebThings, controlled by a Raspberry Pi 3B+ or directly via command line.

Warning: These circuits mix low voltage DC circuits with 110V AC circuits. You can get electrocuted if you are not careful! If you plan to hardwire the switches into your house wiring, be aware of the rules in your jurisdiction – you might need to hire a certified electrician to install the controllers to make it legal. It might also be a really good idea to hire a professional it you haven’t done wiring work before. Be safe!

The controllers with one or two switches will fit into a standard 1-gang wall box. Controllers with three switches can be made in two configurations. One splits the controller over two 16x24 PCBs (meaning that the board has 16 rows by 24 columns of holes at 0.1” spacing). This configuration will fit into a high volume 1-gang box. Second configuration uses a single 24x32 PCB and will fit into a 2-gang box. Controllers with four switches will need the two 16x24 configuration.

I built all controller versions except the 1 switch. My two board three switch controller has four control circuits, but the relay board has only three relays, since I didn’t need four switches on any of my roof controllers. This can be seen on the video, with the fourth switch wired separately.

ESP8266 Arduino sketch uses WebThings library and Over The Air (OTA) updates, so the code can be modified without disassembling the switches.

Supplies

The list below shows where I purchased most of the parts I used.

WebThings controller: Raspberry Pi 3B+: https://www.amazon.com/gp/product/B085DPFR3N $10.99 for 40

headers : https://www.amazon.com/gp/product/B07VNXL5BD $8.69 for 40 pcs each 40x1 male and female headers

2N5401: https://www.amazon.com/New-2N5401-General-Purpose-Transistor/dp/B07SD299R8 $4.99 for 100

2N4401: https://www.amazon.com/CHANZON-BJT-Transistors-2N4401-TO-92-100/dp/B083TRT8JH $4.99 for 100

resistors: https://www.amazon.com/BOJACK-Resistor-Ohm-5-6M-Resistors-Assortment/dp/B07P3MFG5D, $12.99 for 1350 piece assortment kit

PCBs: https://www.amazon.com/gp/product/B07LF7N5K9 $9.99 for 34 piece assortment

ESP8266-ESP-01: https://www.amazon.com/gp/product/B07H3G81TW $11.99 for 4 pieces

Mean Well IRM-03-12: https://www.digikey.com/en/products/detail/mean-well-usa-inc/IRM-03-12/7704636, $6.62 plus 10% tariff for US customers

CUI Inc VXO7803-1000, 6V-36V to 3.3V, 1A: https://www.digikey.com/en/products/detail/cui-inc... $2.80 plus 10% tariff for US customers

Omron G5LE-1A-E DC12: https://www.digikey.com/en/products/detail/omron-... $2.36

small 2 pole wire terminal: https://www.amazon.com/gp/product/B014GMRBH2 $9.09 for 40.

large 2 pole wire terminal: htps://www.amazon.com/gp/product/B07D148GG9 $10.99 for 40

For each controller board, you will need:

1 IRM-03-12 ($7.28)

1 VXO7803-1000 ($3.08)

1 ESP8266-ESP01 ($3)

2x4 female headers

1 220 ohm resistor

1 10K ohm resistor

1 large 2 pole wire terminal

PCB:

1 or 2 switches: 1 16x24 PCB

3 switches:

1 24x32 PCBs

or

2 16x24 PCBs

2 1x4 male headers, with wires to connect them

1 small 2 pole wire terminal (note: small terminal goes onto the control PCB, large goes onto the relay PCB)

4 switches:

2 16x24 PCBs

2 1x5 (4 male headers, with wires to connect them

1 small 2 pole wire terminal (note: small terminal goes onto the control PCB, large goes onto the relay PCB)

Rough cost $15 + sales tax and shipping per switch

For each switch:

1 2N5401 PNP transistor

1 2N4401 NPN transistor

1 G5LE-1A-E DC12 relay ($2.36)

small 2 pole wire terminal

Rough cost: $3+ per circuit

Circuit Design

2020-11-04_16-14-00.jpg
2020-11-04_16-14-11.jpg

Each controller circuit has three parts. The logic part runs at 3.3V. The switching part runs at 12V. The power part is at 110V. A MeanWell IRM-03-12 3W board mounted power supply generates 12V, which is then fed to a CUI VXO7803-1000 to generate 3.3V.

The whole system can easily be modified to use 5V instead of 12V by using something like LT1117FD instead of VXO7803 (but note that LT1117FD has different pinout). I chose to use 12V since it fit better with components I had on hand from other projects.

DC Power requirements:

Each G5LE relay requires 0.4W for switching coil. ESP8266 uses some 70mA in idle state and may need over 400mA at startup. Since LT1117FD is often used to drive ESP8266 and produces 700mA, it is safe to assume that ESP8266 won’t need more than 700mA no matter what it does.

Four switches require 1.6W, leaving 1.4W for the ESP8266 and ancillary logic. Even though VXO7803-1000 may draw up to 3.3W, it will never do so in this context. MeanWell IRM-03-12 thus has enough power for a four circuit switch.

There is a 1W output MeanWell 12V power supply, but it might not produce enough power for ESP8266 at startup. It should be enough for regular operation, with enough to spare to drive a single relay.

AC Power requirements:

G5LE relays are rated at 16A. US electrical code limits regular house circuits to 20A and each individual device to 15A, so these relays should be ample. We assume that 12-gauge wire is used to connect each switch to the 110V power. Output terminals will also accept 12-gauge wire.

Note that the PCB 110V traces must be able to take 20A – a wire can be soldered onto each trace if need be.

Current Flow:

Relays switch the Line, while Neutral is not interrupted. While each output terminal provides connections for both Line and Neutral, the Neutral wires could also be wired directly to the source, bypassing the switch.

On the DC side, 12V + is fed directly to the relays from the power supply. The logic switches the ground on and off (i.e., the ground coil terminal of each relay is connected to the logic driven by ESP8266).

The ESP8266-ESP01 package provides access to four GPIO pins. They should not be pulled down on startup, so we treat HIGH as “off” and LOW as “on”. Each GPIO pin is connected to a 2N5401 PNP transistor base pin. Emitter is connected to 3.3V + and collector is connected to the base pin of the 2N4401 NPN transistor. NPN collector pin is connected to the relay, while the emitter pin is connected to ground.

A MOSFET could be used instead two transistors, but it would require a bit more vertical space (transistors can fit below ESP8266) and G5LE needs little enough current that a MOSFET is not needed. You do need two transistors – if you just try to use 2N5401 to switch the 12V ground, it won’t work.

PCB Design

labeled-2.jpg
labeled-3.jpg
switch_1.png
switch_2.png
switch_3.png
switch_3_one.png
switch_4.png

I used Fritzing to design the PCBs. There are sketches for all five of the possible configurations.

The sketch uses some private parts that I either couldn't find in default bins or online or didn't quite like the way they looked. They can all be found in my Fritzing parts repository: https://github.com/imageguy/Fritzing_parts

The VXO7803 is soldered into the PCB, since it sticks out above the power supply if it’s plugged into a header. ESP8266 is plugged into a header, which leaves enough space below it to fit in transistors to drive two relays. This is crucial, since space is at premium.

The GPIO wires on the ESP01 package are in somewhat random order. GPIO1 (TX) is on one header, while the the other three ports are on the other header in order GPIO2, GPIO0, GPIO3 (RX). To simplify the wiring, we use the ports in this order: 2-0-3-1 (i.e., device 0 uses GPIO2). In two board configuration, the output pins are ordered from the 12V line on the control board and the output terminals are numbered from left to right if looking from above, with the terminals on top. In the single board configuration, the output terminals are numbered from the input terminal. See labels on pictures.

Let me reiterate that the 110V traces that connect the relays must be able to carry 20A current. I've soldered on wires on mine.

If you decide to make actual PCBs, you will need two sided boards.

Installing the Switches

2020-11-03_13-52-24.jpg
2020-11-06_12-04-19.jpg

You can package a controller into a some sort of standalone box that functions as an extension cord. I needed to install them into wall boxes. They are very tight fit, especially if your box has both incoming and outgoing wire. One of my three-switch controllers using two PCB configuration was placed in a 2-gang box together with an unswitched outlet. It was a very tight fit.

If you want to put a controller in a wall to drive outlets in the same box, you will need either a custom very deep box, or a box with no bottom. Even a two switch controller will not fit into the same box as an outlet.

Depending on what other wires you have in the outlet, put a piece of insulator on the bottom side of the controller PCB so you nothing shorts out. For a two-PCB configuration, I found it useful to mount them one over the other, with the logic PCB on top and the relay PCB on the bottom, with a thin screw with nuts used to fix the PCBs in each corner.

Be careful attaching wires to the terminals. A solid 12 gauge wire is stiff enough that it will lever the soldered wire terminal out of the PCB. If your wiring skills are poor, like mine, it helps to use stranded wire to connect controllers to the house wiring.

In a two board configuration, I found it easiest to connect the input 110V lines to the 12V power supply to the relay board input wire terminals.

Pictures show before and after for one of my two-switch locations. Electrical tape is to prevent bugs from crawling into the box alongside the wiring.

Over-the-AIR (OTA) Update

Once your switch controller is installed, pulling out the 8266 so you can connect it to a serial line and reprogram may be hard or impossible. We use Android ability to be updated over the WiFi.

There are two constraints. First, the OTA process copies the new compiled sketch to the target system, then reboots and runs the new code. This means that only half the program memory is available. Given than ESP01 has a little less than 1MB, this is a serious constraint. The switch sketch (see the next step) fits with plenty of room to spare.

OTA can be done in several different ways, but I always update from the Arduino IDE. The second constraint is that your target system must be on the same subnet as the IDE.

To learn about the OTA, visit https://arduino-esp8266.readthedocs.io/en/latest/ota_updates/readme.html but here is a simple example, also attached as .ino file:

/* Minimal Over-the-air (OTA) example. Does nothing except allowing the update. 
   Update requires a password.
*/ 
#include <ESP8266WiFi.h>
#include <ArduinoOTA.h> 

const char* ssid = "your network ssid"; 
const char* sspassword = "your network password"; 
const char* myname = "your controller hostname"; 
const char* esp_passwd = "OTA update password" ; 


void setup() { 

  // WiFi setup
  WiFi.hostname( myname ) ; 
  WiFi.mode( WIFI_STA ) ;
  WiFi.begin( ssid, sspassword ) ; 
  while ( WiFi.status() != WL_CONNECTED ) {   
    delay( 500 ) ; 
  } 
  
  // OTA setup
  ArduinoOTA.setHostname( myname ) ; 
  ArduinoOTA.setPassword( esp_passwd ) ; 
  ArduinoOTA.begin();
} 

void loop() { 

  ArduinoOTA.handle();

}

The sketch requires a password for OTA update. You should consider carefully before commenting this out. Your controller can make changes to the actual physical world, so any hostile intrusion may have serious consequences. The security of the whole system depends on the security of your WiFi network. Requiring a password to update is just a smidgeon of extra security so nobody can upload some carefully crafted piece of malice. Sure, I have no doubt that your WiFi is fully secured, but the world is littered with victims who were sure that their security is bombproof. Don’t become another one.

Once you upload the sketch over the serial line and wait for a minute or so to reboot and reconnect to WiFi, you will see your new system on the list of ports. Select it, instead of USB0, or whatever is your wired serial port, to do updates over the WiFi.

In addition to the ESP8266WiFi library, OTA uses the ArduinoOTA library which should already part of your Arduino IDE and, if not, can be installed via the library manager.

Note that there is no logging over the serial connection. My Arduino IDE (1.8.13) does not support serial monitor over a WiFi port. You could use a telnet connection instead, but the Arduino IDE already tells you what is going on.

Since the WiFi authentication is via SSID and password, you can replace your router, as long as you keep those the same. If you need to change SSID and/or the password for your network, propagate the changes to your controllers before making them on the router.

Downloads

Arduino Sketch

I run all the controllers from a single source file. Each controller is defined via its CONTROLLER_ID and has a corresponding #if stanza that defines the number of switches (1-4), the hostname and the name of each device controlled by that controller.

In the WebThings terminology, each controller is an adapter and that has one or more devices. The sketch keeps writing LOW or HIGH to active output pins but, unless the device was just turned on or off, the value written to the pin is the same that the pin already has.

webthing-arduino library should already be installed in your arduino IDE. If not, it's available in the Library Manager.

As in the OTA example code, there is no serial line output.

Downloads

WebThings

floorplan.png

Until the end of 2020, WebThings were part of Mozilla. They have now transitioned to a community supported system. Visit https://webthings.io/gateway/

I run my gateway on a Raspberry Pi 3B+. You can set your gateway to be accessible through the webthings.io, where it’ll get its own subdomain you can log in. Or you can keep it accessible just through your local network.

Since each controller runs a web server, you can just send a well-crafted curl command:

curl -X PUT http:///things//properties/on -H 'Content-Type: application/json' \
-d '{"on":true}'

This turns the device on. '{"on":false}' turns it off.

If you use the gateway, there is a place you can upload the floorplan and position your devices on it. I find it much more convenient than looking at the device list. I thought that a floorplan drawn in inkscape with black background and white foreground looked really nice.

Final Thoughts

Security of this system leaves much to be desired. One obvious hole is using the tunneling so your gateway can be accessed through the webthings.io domain. This can be avoided if you set your gateway up locally.

The other obvious hole is that controller accepts commands without authentication, so anyone gaining access to your local network can turn your devices off and on at will. This is potentially a dreadful risk. Reading the samples in the WebThings online documentation, I believe there is a mechanism to add authentication. It’s certainly something I plan to investigate soon.

I’ve used these switches for several months now. They work fine even if the controller ambient temperature is below freezing. The ability to turn off each heater separately saves enough money to more than pay for the cost of parts in a couple of winter months. Building this was fun, installing was a pain, but the result was well worth time, money and trouble.