Switch relay with a NodeMCU (ESP8266) and Openhabian (Raspberry Pi)

Hello guys,

I use openhab 2.4 and the MQTT binding 2.4. however, i don’t use the PaperUI for configuring the broker, I use the openhab2 folders on my Raspberry Pi instead and it works fine.

I want to switch a relay with a NodeMCU (ESP8266) and openhab2. I programmed it with the Arduino IDE. in the picture below you can see the serial monitor of the nodeMCU, MQTT.fx and my openhab site of the switch.

Here is my problem. Only when I have pressed the switch 30 times I hear a click from my relay. As you can see on the serial monitor the message “Z1ON” or “Z1OFF” doesn’t always reach my ESP and I’m helpless. Do any of you know why?

My arduino Code for the NodeMCU:

#include <PubSubClient.h>
#include <ESP8266WiFi.h>     
#include <WiFiManager.h> 

#define wifi_ssid "SSID" //enter your WIFI SSID
#define wifi_password "MY PASSWORD" //enter your WIFI Password
#define mqtt_server "MY IP ADRESS" // Enter your MQTT server address or IP.
#define mqtt_device "SmartMCU" //MQTT device for broker and OTA name
#define mqtt_user "openhabian" //enter your MQTT username
#define mqtt_password "openhabian" //enter your password

//#define channel1 D0
//#define channel1pub "MCU/channel1"

int channel1 = 16;
const char* channel1pub = "MCU/channel1";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
char message_buff[100];

void callback(char* topic, byte* payload, unsigned int length) 
{
  
    int i = 0;

  Serial.println("Message arrived:  topic: " + String(topic));
  Serial.println("Length: " + String(length,DEC));
  
  // create character buffer with ending null terminator (string)
  for(i=0; i<length; i++) {
    message_buff[i] = payload[i];
  }
  message_buff[i] = '\0';
  
  String msgString = String(message_buff);
  
  Serial.println("Payload: " + msgString);
  int state = digitalRead(channel1);  // get the current state of GPIO1 pin
 
  if (msgString == "Z1ON"){    // if there is a "1" published to any topic (#) on the broker then:
    digitalWrite(channel1, HIGH);     // set pin to the opposite state 
    Serial.println("Switching Z1 ON"); 
    client.publish(channel1pub, "Z1ON");
  }
  else if(msgString == "Z1OFF")
  {
    digitalWrite(channel1, LOW );     // set pin to the opposite state 
    Serial.println("Switching Z1 OFF");
    client.publish(channel1pub, "Z1OFF");
  }
}

void reconnect() 
{
  // Loop until we're reconnected
  while (!client.connected()) 
  {
    //Serial.print("Attempting MQTT connection...");
      // Attempt to connect
    if (client.connect(mqtt_device, mqtt_user, mqtt_password)) {
     // Serial.println("connected");
      // Once connected, publish an announcement...
      //client.publish(channel1pub, "hello world");
      // ... and resubscribe
      client.subscribe(channel1pub);
    }
    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()
{
  pinMode(channel1, OUTPUT);
  digitalWrite(channel1, LOW);
  //pinMode(channel1, OUTPUT);
  //digitalWrite(channel1,HIGH);
  Serial.begin(9600);
  delay(10);
  WiFiManager wifiManager;
  //1wifiManager.resetSettings(); 
  wifiManager.autoConnect("SmartMCU");
  Serial.println("Connected to network!!!");
  Serial.println();
  Serial.println();  
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}
void loop() 
{
  if (!client.connected()) 
  {
    reconnect();
  }
  client.loop();
  long now = millis();
  if (now - lastMsg > 2000) 
  {
    lastMsg = now;
    ++value;
    //snprintf (msg, 75, "Hey!! I'm alive #%ld", value);
    //Serial.print("Publish message: ");
    //Serial.println(msg);
    //client.publish("<OUT TOPIC>", msg);
  }
}

Since this isn’t an Arduino programming forum you on might have better luck passing to an Arduino forum where there will be more people with the expertise to help.

The majority of ESP users on this forum use Tasmota or ESP Easy for a job like this. With Tasmota with the HA mode enabled, the MQTT 2.5 M1 binding can even automatically discover the device and create the Thing automatically.

So you would say that my openhab configuration is right ? Because I wasn’t sure if there was a problem with the configuration of openhab or if it was the ESP Arduino code.

I assume as well that something in your Arduino code is wrong, but I cannot spot the issue. If you click 30 times the button and 30 times mqtt.fx sees the message, then Arduino should see the message as well. as a next step I would try to remove as much filter logic as possible. for example, subscribe to topic # to receive ALL incoming messages

Well, I’m on my phone but even on a computer screen shots tend to be almost illegible. So I can’t really say. But as Stefan says, if the messages are being published from OH to the broker the problem has to be in the Arduino. OH is doing what it’s supposed to do.

1 Like