Introduction: Using an Esp8266 Arduino to Control a Relay Using Home-assistant

This Instructable shows how to connect a relay module to an esp8266, something that should be straight forward but needs a few extra components to make the relay work correctly if you're using the small esp device in the pictures.

This board was from ebay and has an AMS1117 voltage regulator built onto the board so that you can connect it straight to a USB type power source.

The board also comes with a little daughter board which has a CH340G chip on it which allows you to plug the esp board into it and program it, and once programmed the esp can then be removed and used in a project.

There are upsides and downsides to this form factor which are that once the esp is programmed if you need to change some of your code you need to take it out of your project and plug it back into the programmer. An upside would be that the esp device is smaller than a NodeMCU Devkit, so if you're tight for space this might be a good trade off.

The circuit on the veroboard in these pictures is doing more than just the relay control. More on that in another Instructable later.


Step 1: Things You'll Need

  1. ESP8266
  2. Arduino relay module

  3. Veroboard

  4. BC547B transistor

  5. 1Kohm resistor

  6. 1N4001 diode

  7. Some wire, soldering iron, solder etc to actually build the circuit

Step 2: The Circuit

The circuit I used to control the relay with the esp8266 uses a BC547B transistor, a 1K resistor and a 1N4001 diode.

I connected the control wire from GPIO16 on the esp but any of the GPIO pins could be used.

  • The emitter of the transistor is connected to Ground along with the GND pin of the relay.
  • The base of the transistor is connected to the control pin from the ESP via the 1K resistor.
  • The collector of the transistor is connected to the control pin on the relay which is also connected to VCC via the diode.

Its a very simple circuit which switches the control pin of the relay to ground when the GPIO pin goes high.

Step 3: Home-assistant Setup

You can use home-assistant (https://home-assistant.io) to control the relay via the MQTT server and ESP8266. The switch config for home-assistant below will switch on and off the relay using the topic 'ha/switch1'

switch:

platform:

mqtt name: "Switch1"

state_topic: "ha/switch1"

command_topic: "ha/switch1"

qos: 0

payload_on: "ON"

payload_off: "OFF"

optimistic:

false retain: true

Step 4: ESP8266 Sketch

The sketch I've written for the esp8266 also has code for reading the temperature from a DS18b20 and also detecting if the LED is on or off on the control box for my boiler, but I've removed this code for this Instructable and will include it in separate Instructables.

#include <ESP8266WiFi.h>

#include <PubSubClient.h>

// Update these with values suitable for your network. const char* ssid = ""; const char* password = ""; const char* mqtt_server = "";

WiFiClient espClient; PubSubClient client(espClient); int HeatingPin = 16; String switch1; String strTopic; String strPayload;

void setup_wifi() {

delay(10); // We start by connecting to a WiFi network 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"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); }

void callback(char* topic, byte* payload, unsigned int length) { payload[length] = '\0'; strTopic = String((char*)topic); if(strTopic == "ha/switch1") { switch1 = String((char*)payload); if(switch1 == "ON") { Serial.println("ON"); digitalWrite(HeatingPin, HIGH); } else { Serial.println("OFF"); digitalWrite(HeatingPin, LOW); } } } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("arduinoClient")) { Serial.println("connected"); // Once connected, publish an announcement... client.subscribe("ha/#"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void setup() { Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback);

pinMode(HeatingPin, OUTPUT); digitalWrite(HeatingPin, HIGH); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); }

This sketch will switch the relay on and off when ever the MQTT broker receives a message of 'ON' and 'OFF' to the topic of 'ha/switch1'.

You can change this how ever you want in the sketch, as long as you also change the home-assistant switch config too in Step 3.

Comments

author
JuanP228 (author)2017-07-29

Hi looking for some help. I modified your sketch to manipulate a remote; however, it's jamming the HA switch. It seems to be connecting but not working.

Could you perhaps take a look at the rev sketch?

author
JuanP228 (author)2017-07-29

1

author
JuanP228 (author)2017-07-29

Hi, I modified your sketch to operate a remote control; however, it appears to be connecting to the server, but when it does it seems to confuse it and the HA switch only stays in one position. In fact it disrupts all other operating switches.

Could you perhaps take a look?

#include <ESP8266WiFi.h>

#include <PubSubClient.h>

#define OFF D1

#define ON D2

// Update these with values suitable for your network.

const char* ssid = "XX";

const char* password = "XX";

const char* mqtt_server = "XX";

WiFiClient espClient;

PubSubClient client(espClient);

// int HeatingPin = 16;

String switch1;

String strTopic;

String strPayload;

void setup_wifi() {

delay(10);

// We start by
connecting to a WiFi network

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");


Serial.println("IP address: ");


Serial.println(WiFi.localIP());

}

void callback(char* topic, byte* payload, unsigned int
length) {

payload[length] =
'\0';

strTopic =
String((char*)topic);

if(strTopic ==
"ha/switch1")

{

switch1 =
String((char*)payload);

if(switch1 ==
"ON")

{


Serial.println("ON");


digitalWrite(ON, LOW);

delay(250);

digitalWrite(ON, HIGH);

}

else

{


Serial.println("OFF");


digitalWrite(OFF, LOW);

delay(250);


digitalWrite(OFF, HIGH);;

}

}

}

void reconnect() {

// Loop until we're
reconnected

while (!client.connected())
{


Serial.print("Attempting MQTT connection...");

// Attempt to
connect

if
(client.connect("XX", "XX", "XX")) {


Serial.println("connected");

// Once
connected, publish an announcement...


client.subscribe("ha/#");

} else {


Serial.print("failed, rc=");


Serial.print(client.state());


Serial.println(" try again in 5 seconds");

// Wait 5
seconds before retrying

delay(5000);

}

}

}

void setup()

{

Serial.begin(115200);

setup_wifi();


client.setServer(mqtt_server, 1883);


client.setCallback(callback);

pinMode(OFF,
OUTPUT);

pinMode(ON, OUTPUT);

digitalWrite(OFF,
HIGH);

digitalWrite(ON,
HIGH);

}

void loop()

{

if
(!client.connected()) {

reconnect();

}

client.loop();

}

author
jturner27uk (author)2017-07-09

all worked a treat. Thank you for the detailed instructions.

author
REGATTE (author)2017-02-20

you could use blynk or mydevice cayenne it'll be more easier and wherever something goes wrong its more easier to rectify

author
Quentin70 (author)2017-02-08

I have problems with the Home Assistant set-up side. I copied and pasted the above code, but I received always the MQTT invalid config. Could you please share the code to configure correctly the MQTT and the related switch in the configuration.yaml? thanks

author
SerghJ (author)2017-02-07

Working from the start. Thanks. Using ESP-12E. Programmed with Arduino UNO as Generic ESP8266.

author
Ashf6 (author)2017-02-07

how can i add 4 channel relay and 4 push button to manually turn it on and off? someone please help me I want it to control room lights.

author
SandipanC4 (author)2017-01-16

What the hell is heating pin? What Happens when someone is using NodeMCU Board I dont think there is something or anything anywhere like heeating pin.

author
BrendanM82 (author)SandipanC42017-01-18

HeatingPin is defined 5 lines above setup_wifi() as: "int HeatingPin = 16;"

That is the output pin that is connected to this relay he is using. IN this case rather than use the int '16' he used a variable named HeatingPin to store the pin number.

author
SandipanC4 (author)BrendanM822017-01-18

Ya I didnt read it that time but anyways both the code and cofig is non working.

author
Will_P (author)SandipanC42017-01-31

The project doesn't work for me either, a bit more detail on the Home Assistant set-up side of things from the author would help.

author
SandipanC4 (author)Will_P2017-01-31

Everything works on homeassistant and nodemcu the problem is a nodemcu cant power the realy because the output is only of 3.3v

author
Will_P (author)SandipanC42017-02-01

Use the Vin pin, that will supply 5V depending on your board, I'm using
tinxi® NodeMCU Lua WIFI Internet Development Board Based on ESP8266 ESP-12E CP2102 https://www.amazon.co.uk/dp/B01GCK3J40/ref=cm_sw_r_cp_api_iyzKybMK3KQGS

author
SandipanC4 (author)Will_P2017-02-01

Using the same board and that not gonna work tried that already.

author
Will_P (author)SandipanC42017-02-01

That's strange, my relay is connected to 3v and GPIO 14 (D5) and works a treat when tested via http, the stated trigger voltage for my relay is between 2 and 5v.

My problem is, I cannot get the relay to trigger from Home Assistant using mqtt. :(

author
SandipanC4 (author)Will_P2017-02-02

I am using the 8 way relay and when I turn it on from mqtt just the light in the relay turns on but nothing happens.

author
SandipanC4 (author)2017-01-09

What if the MQTT Server is password protected? The whole thing is incomplete.

author
Will_P (author)SandipanC42017-01-31

If the MQTT server is password protected, edit this line (should be line 64)

if (client.connect("arduinoClient")) {

with the client ID, username and password, like this

if (client.connect("clientID", "username", "password")) {

replacing "clientID", "username", "password" with your server login details. :)

author
SandipanC4 (author)Will_P2017-01-31

I know that I just said that the code is incomplete.

author
JackyJ6 (author)2016-09-28

A lot of nice pictures end videos but nothing about home-assistant and MQTT..

author
JackyJ6 (author)JackyJ62016-09-28

... maybe a video of your project working ?

author
JackyJ6 (author)2016-09-28

A lot of
useless text and pictures and almost nothing about this obscure stuff as home
assistance and MQTT ! Are you serious ?

author
KayT13 (author)2016-04-21

i feel really stupid, but what does this do?

author
Millies (author)KayT132016-04-30

Briefly, the esp8266 is a wifi radio and the relay is basically a switch. You can switch something on or off remotely with this.

Quite impressive, really.

author
laith mohamed (author)2016-04-16

I like your work with arduino .

author
RichH3 (author)2016-04-14

You can use the opto-isolated relay boards like these and save yourself a lot of work and make it smaller too by eliminating all of the extra parts and connect a IO pin directly to the relay board. I have a few 8 channel controllers using an Pro-Mini with a HC06 bluetooth for the interface and the 8 channel versions of this single channel board.

http://www.ebay.com/itm/like/151526058542?lpid=82&...

author
padeath (author)RichH32016-04-14

The relay module I'm using is like the one you linked to, and in fact did just work without any extra circuitry on a NodeMCU Devkit ESP8266, but when I connected it to this little ESP8266 it didn't switch off when I set the pin to LOW. But adding the extra bits made it work. :)

author
Cgiff (author)2016-04-14

thanks for this post, I've been using Arduino Uno Sainsmart Clones, am very interested in some 8266 devices around the house for energy control. Ontario's Hydro costs are getting expensive in the peak time periods 18c /KWH. BTW nice heat sink :)

author
padeath (author)Cgiff2016-04-14

Thanks for the comment :) Yeah I love these little esp8266 devices, I've got them in various types packaging, this little one is good, but I do prefer the NodeMCU Devkit though :)

author
Romninja (author)2016-04-14

Why is there a heatsink on your esp8266? i haven't heard of them getting hot.

author
padeath (author)Romninja2016-04-14

haha yeah, you're the second person to ask about that. My friend bought a bunch of them and put one on the esp8266 for a bit of fun. They dont get hot nope, but why not put one on if your mate has got them and he wanted to put one on it :)

Yes Jay I'm talking about you bro :)

author
Akin Yildiz (author)2016-04-08

can you please share the direct link to the esp and the usb board used.!!
.
it looks like it has an onboard light sensor and RGB led.?

author
padeath (author)Akin Yildiz2016-04-08

Oh yeah and yes it a LDR and tri-colour LED.

I found that these can cause funny things when reading the digital and analog pins that they are connected to. I'm not 100% if it is doing this though.

The LED isn't a neopixel as such, as in each of the 3 LEDs in it are actually connected to a GPIO.

There is actually also a push button on the ESP board.

These are connected to the follow GPIO pins:

LDR = A0;
RED = 15;
GREEN = 12;
BLUE = 13;
BUTTON = 4;

author
padeath (author)Akin Yildiz2016-04-08

You can get them from ebay and gearbest. I got mine from ebay from a UK seller (as I'm in the UK).

gearbest url : http://www.gearbest.com/boards-shields/pp_315640.h...

ebay url : http://www.ebay.co.uk/itm/ESP8266-WIFI-Wireless-Se...

I hope this helps.

author
instructablessy (author)2016-04-08

really cool

author
instructablessy (author)2016-04-08

really cool

author
arno.eras (author)2016-04-06

nice lol. cool project

author
arno.eras (author)2016-04-06

why the heatspreader on the esp?

author
padeath (author)arno.eras2016-04-06

haha I knew someone might ask this. My friend bought 30+ of them and stuck one on it to keep it cool ;)

About This Instructable

35,256views

349favorites

License:

More by padeath:ESP8266 + Confused.com Brian Toy RobotMagic 8 Ball Using Esp8266 and I2c LCD ScreenDS18b20 Temperature Sensor As a Thermostat
Add instructable to: