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

73K36348

Intro: 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.

44 Comments

Hi,
I don't get a point for D1.
If the relay module is a chineese piece of kind I know, it is advisable (but not necessary) to pull up an input (relay board connector 3) to VCC. It can be done by a resistor (whatever value but not to exceed transistor's max collector current when it is open, let's say 10k). This resistor should replace D1. In this diagram D1 is pointless.
Does it matter if the relay is a 40DA SSR 40amp relay? I want to control an electrical smoker using this code...

This is the first howto I read that simply works!

mosquitto_pub -t 'ha/switch1' -m "OFF"

One can replace int HeatingPin = 16; with int HeatingPin = D0;

int HeatingPin = 5; with int HeatingPin = D1; etc

MQTT login with username and password:

if (client.connect("arduinoClient",MQTT_USERNAME,MQTT_PASSWORD))

instead of:

if (client.connect("arduinoClient"))

Anyway, thanks for this instructable!

why the heatspreader on the esp?

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

Good job @padeth I had been looking all over for someone who knew how to do this (slightly different esp and relay). BTW @sandipanc4 and @jackyj6 you should probably stick with leggos.

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?

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

}

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

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

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

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

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.

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.

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.

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

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.

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

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
More Comments