Arduino RELAY switches over WiFi, controlled via HASS / MQTT, comes with OTA Support

I would like to pilot a remote control with a relay, so it must stay excited for some time! What should I add to your sketch?

Hi Daniel,

My apologies, I have not checked my account for quite some time.
My setup is a toggle switch - it will stay ON (or OFF) unless you intentionally change its state.

The Sketch basically hooks in with the MQTT and listen for a state update on the TOPIC it is subscribed to, confirms it back to the server to acknowledge the change. In a nut shell - the relay will simply follow the state “described” by MQTT server.

You can create your automation logic on the HA side controlling the state of the MQTT TOPIC.
(In my recent project, I created a sprinkler timer controlling the TOPIC state) so I do not over water my garden.

cheers
Erick

I was looking for something like this, and fits perfectly for my project.
I don’t know much about programming, so I’m asking for help:
Can someone add push buttons to sketch, so relay’s can be operated with wall switches (I mean push button) which will report state to mqtt broker.
that would be great, so no matter which button is pushed the light’s will power off, and mqtt broker will know the state of.

I was looking for this, but haven’t found working solution.
The buttons in above sketch doesn’t switch relay on and off.

thanks for help.

Thanks for this!
I was able to get everything up, however the buttons don’t trip the relays… I can see in Home assistant the values are changing from 0 to 1 when I press the button, but it doesn’t affect the relay…
I did not get my LED to work either, but that’s ok since the LED on the nodemcu does clicks on when a button is pressed.
Edit: got my led to turn off when I press the button.

Thoughts?

Thanks in advance!

That would need to be set up with an automation

So I’m going to connect this to my pool, which has some momentary push buttons ran to the spa. I can figure out how to tie the momentary on state to an automation to toggle my spa jets, BUT I do not know how to rewrite the ino file for push button action.

Could anyone here help?

1 Like

Thanks for confirming that!
I managed to trip the switch with automations, but I am hoping to find an arduino based trigger as a failsafe in case the system is down - I have a sonoff 4ch pro but i’m trying to create a generic version to learn, and customize.
Any help is appreciated,
Thanks!

Sorry it was late last night when i posted that…

You could also just change the buttonTopic to match the swtichTopic
ie:

char const* buttonTopic1 = "/test/button1/";
char const* buttonTopic2 = "/test/button2/";
char const* buttonTopic3 = "/test/button3/";
char const* buttonTopic4 = "/test/button4/";

to

char const* buttonTopic1 = "/test/switch1/";
char const* buttonTopic2 = "/test/switch2/";
char const* buttonTopic3 = "/test/switch3/";
char const* buttonTopic4 = "/test/switch4/";

in this case you would then remove the button sensors from your config, the HA switch and the ESP button will preform the same task

Unfortunately this only keeps the switch ON only if the button is pressed…
I’ll keep trying to figure this out.
Thanks!

Yeah thats the way the sketch is written, High triggers off and low triggers on, I was also looking for low/low or high/high to toggle state

Hi Folks!

I just wanted to say a quick - but heartfelt - Thank You! to @erickjoaquin, @olegunnar, and @koen01

Your work made it so easy for me to set up my Makerfocus D1 Mini together with the JBtek 4 Channel DC 5V Relay Module in my HomeAssistant seup so I’ll be able to control my sprinkler from my desk rather than having to crawl around under the house for every change. Plus I will get notified when the water actually gets turned on and off.

Great Community - Great Stuff!
-Chairstacker

https://www.amazon.com/gp/product/B01N3P763C

https://www.amazon.com/gp/product/B00KTEN3TM

Hello Erick et al.: Thanks very much for the leadership in getting me started using Arduino with a Wemos D1 R2 and a 4 switch relay. I got everything working but have one question for you experts:

I want to use the relay as a garage button (quick on/off signal, maybe half a second or less) as opposed to the on/off switch your code offers. To make this work I simply inserted
after this line:
client.publish("/house/switchConfirm3/", “1”);

these lines

delay(300);
digitalWrite(switchPin3, HIGH);
client.publish("/house/switchConfirm3/", “0”);

This works great but leaves me with one challenge: When I plug the board in, it boots up, connects to the Wifi, all good. Then, the Wemos appears to “go once through the entire ‘switch with delay’ routine” for all 4 switches. As an example: If I make long delays for demonstration purposes for the for the first 3 switches, say 4, 3, and 2 seconds, then the board will execute the 4 “pushed buttons” once (with its 4,3,2 second delays) before being ready to await Home assistant input.

Usually, this would not be a problem, but if the energy supply in the house is interrupted, the board boots up again and fires a LOW signal for the delay time specified during boot up to each relay, thereby opening the garage door.

Can I avoid the board doing the “startup firing all switches once as specified in my delay Arduino code”? Do I need to change the Arduino code or set payloads to zero?

Many thanks for your help!

By the way, I do not believe that what I observe is the HIGH/LOW states that have been described for certain Pins at bootup, see https://forum.wemos.cc/topic/66/wifi-relay-gpio-pin-1-behavior-at-boot/5. Rather, my code (better: Erick’s code) is executed once at startup and opens the garage door after boot without intention.

I just signed up to answer in this thread. Great work! I was looking for a complete tutorial and this was exactly what I needed! Works like a charm :slight_smile:

Had to switch High and low as I have an active low module. And I activate more than 1 channel per topic, but this was easily added.

I only have to figure out why some pins lose power during boot up (some channels switch shortly). But the device shouldn’t reboot at all after initial setup, so…

Hello all,

hope eric or someone here can help me.

I use linked code and made some corrections, extend to 8 channel relay mqtt support., but it Works only first 4 channel. I add four more const int outputs and switchtopics, define and so on… Here is the code for better understanding:

const int kuhinja = 0;
const int dnevna = 2;
const int spalnica = 4;
const int hodnik = 5;
const int nik = 12;
const int otroska = 13;
const int kopalnica = 14;
const int wc = 16;

char const* switchTopic1 = “/house/kuhinja/”;
char const* switchTopic2 = “/house/dnevna/”;
char const* switchTopic3 = “/house/spalnica/”;
char const* switchTopic4 = “/house/hodnik/”;
char const* switchTopic5 = “/house/nik/”;
char const* switchTopic6 = “/house/otroska/”;
char const* switchTopic7 = “/house/kopalnica/”;
char const* switchTopic8 = “/house/wc/”;
void setup() {
//initialize the switch as an output and set to LOW (off)
pinMode(kuhinja, OUTPUT); // Relay Switch 1
digitalWrite(kuhinja, HIGH);

pinMode(dnevna, OUTPUT); // Relay Switch 2
digitalWrite(dnevna, HIGH);

  pinMode(spalnica, OUTPUT); // Relay Switch 3
     digitalWrite(spalnica, HIGH);

     pinMode(hodnik, OUTPUT); // Relay Switch 4
         digitalWrite(hodnik, HIGH);

            pinMode(nik, OUTPUT); // Relay Switch 5
                digitalWrite(nik, HIGH);

                     pinMode(otroska, OUTPUT); // Relay Switch 6
                         digitalWrite(otroska, HIGH);

                            pinMode(kopalnica, OUTPUT); // Relay Switch 7
                                 digitalWrite(kopalnica, HIGH);

                                       pinMode(wc, OUTPUT); // Relay Switch 8
                                            digitalWrite(wc, HIGH);

if (topicStr == “/house/kuhinja/”)
{

 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(kuhinja, LOW);
   client.publish("/house/switchConfirm1/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(kuhinja, HIGH);
   client.publish("/house/switchConfirm1/", "0");
   }
 }


 // EJ: copy and paste this whole else-if block, should you need to control more switches
 else if (topicStr == "/house/dnevna/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(dnevna, LOW);
   client.publish("/house/switchConfirm2/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(dnevna, HIGH);
   client.publish("/house/switchConfirm2/", "0");
   }
 }

 
 else if (topicStr == "/house/spalnica/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(spalnica, LOW);
   client.publish("/house/switchConfirm3/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(spalnica, HIGH);
   client.publish("/house/switchConfirm3/", "0");
   }
 }

 
 else if (topicStr == "/house/hodnik/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(hodnik, LOW);
   client.publish("/house/switchConfirm4/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(hodnik, HIGH);
   client.publish("/house/switchConfirm4/", "0");
   }
 }

 else if (topicStr == "/house/nik/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(nik, LOW);
   client.publish("/house/switchConfirm5/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(nik, HIGH);
   client.publish("/house/switchConfirm5/", "0");
   }
 }

  else if (topicStr == "/house/otroska/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(otroska, LOW);
   client.publish("/house/switchConfirm6/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(otroska, HIGH);
   client.publish("/house/switchConfirm6/", "0");
   }
 }

  else if (topicStr == "/house/kopalnica/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(kopalnica, LOW);
   client.publish("/house/switchConfirm7/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(kopalnica, HIGH);
   client.publish("/house/switchConfirm7/", "0");
   }
 }

  else if (topicStr == "/house/wc/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(wc, LOW);
   client.publish("/house/switchConfirm8/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(wc, HIGH);
   client.publish("/house/switchConfirm8/", "0");
   }
 }

if (client.connect((char*) clientName.c_str())) { //EJ: Update accordingly with your MQTT account
Serial.print("\tMQTT Connected");
client.subscribe(switchTopic1);
client.subscribe(switchTopic2);
client.subscribe(switchTopic3);
client.subscribe(switchTopic4);
client.subscribe(switchTopic5);
client.subscribe(switchTopic6);
client.subscribe(switchTopic7);
client.subscribe(switchTopic8);

What can be wrong ?

Thanks for help
Sam

1 Like

Hi All, @Esp8266 (Sam),

I took a quick glance on your code, I am assuming you have also extended the “Topics” in HASS MQTT/Switch YAML setting complementing your added relay codes/topics right?

Hence, you will need to define in additional switch profile in switch yaml following the “format” below:

switch 5:
  - platform: mqtt
    name: "MQTT Switch 5"
    state_topic: "/house/switchConfirm5/"
    command_topic: "/house/switch5/"
    payload_on: "1"
    payload_off: "0"
    qos: 0
    retain: true


adjust the topic name according to your convention, add switches 7 to 8 following the format.

Cheers
Erick
ps.  my apologies to all if my response is always coming in very late, need to look after the family first :-)

Hi @econzune,

I hope I understood your issue correctly. it is the case wherein, the Arduino sketch always do an “initialise” routine as per “defined static default setting” on reset (or power interruption), then eventually get its topic update from the MQTT server completing the whole boot up process.

I would suggest changing the initialise routine to fetch the last state topic from the MQTT server (talking aloud / half thinking :slight_smile:

cheers
Erick

Hello Eric,

thanks for your replay,

i use node red to control relays. I made all eight nodes and working only four.
When i check with serial monitor it only read from 1 to 4 switches (kuhinja, dnevna, spalnica, hodnik). It is possible to attached some print screens here?

Thanks
Regards
Sam

@Esp8266 (Hi Sam) ,

Try monitoring the topic - pub/sub behaviour in MQTT.

The way I will do this, I will access the Pi HASS using putty (or any ssh client) and execute the following command

core-ssh:~# mosquitto_sub -h <your mqtt ip address> -v -t "#"

using # - will show you all the topics MQTT is interacting with.
Start with this to check if your wemos (or any arduino/arduino clone) is:
(1) HASS is publishing to the MQTT Server when ever a switch is activated
(2) WEMOS is Publishing back to MQTT when it receives the topic update it is subscribed to from MQTT as per step 1.

My MQTT server response look like this

/house/switch1/ 0
/house/switchConfirm1/ 0
/house/switch1/ 1
/house/switchConfirm1/ 1

The first pair of “0” is switching OFF switch 1 - command/confirm

This will help you ensure the topic in your node red work flow is aligned with your sketch topics.

Good luck!
Erick

Friend, congratulations for the project, I was very useful so that I could understand the operation of everything and consequently concluded the project.

Congratulations!

im looking for something like this to control my 16relay board using node red as i had a nightmare trying to get has to work how easy is it to adapt the arduino code to work are there any sections that are not needed etc that are only for has im thinlking the mqtt should work fine etc

many thanks