Switching on and off a relay as a beginner with mqtt

Hello guys,i am new with this whole thing and the fact that i am french may not help.(video tutorials were you guys would explain how you did the DEMO would help a lot as well as provinding the codes … well maybe it exists and i just don’t know ).

Here is the thing i don’t really know how to use mqtt with openhab. I have the esp 8286, a raspberry pi 3 with openhabian, installed mosquitto, i have a mqtt client that’s connected to the raspberry (through port 1883).
I just want to undestand the basics : How do i know for example the path to write in the Items file ?

I know it may seem a lot , but i would like someone to take my hand (not litterally) and explain things to me. (I am completely lost over things that seem so easy)

I just want to switch on and off a relay with pin D0 of my esp8286 (gpio16). I did it with adafruit’s mqtt service . I want to do it with openhab.

1)First of all i am not quite sure how to make my esp 8286 communicate with my raspberry.
2)I created a switch item but i don’t know the mqtt path.
Do i still have to write a rules while even if it’s just a switch (On and Off) ?
I have so many questions

Thanks to those that will help.

It’s not called a path but a topic:
You create it yourself eg: House/LivingRoom/Switch


thank you very much . now i suscribed to a topic and i can see the results when i switch. Just gotta connect my esp 8266 now to see the magic

You’ve done the hardest. You can download the pubsubclient library for arduino. It comes with examples.

Bonne chance

Try Tasmota it works with any ESP8266

hello,i want to deeply thank you for the help.

Like i said the mqtt is connected and i can see it thanks to the mqtt client (i use mqtt fx) . But still haven’t been able to connect my node mcu . I have problems uploading codes with references to the node mcu . Don’t you have a simple program already working that i could modify a little bit? something like
if ((char)payload[0] == ‘o’ && (char)payload[1]== ‘n’) { // comparing if ON command is coming from server.

digitalWrite(16, HIGH);  //gpio16

} else {
digitalWrite(16, LOW); // else turn off led



And why are all tutorials about sonoff ?


I am using also the Pubsubclient.
My callback function looks like this:

void callback(char* topic, byte* payload, unsigned int length) {
  String selector;
  Serial.print("Message arrived [");
  Serial.print("] ");
  String mqtt_data = "";
  for (int i = 0; i < length; i++) {
    mqtt_data += (char)payload[i];
  selector= String (topic);
  if (selector == String("/SONOFF01/REL")) {                             //hier Topic anpassen ######
     Serial.println("inTopic/REL received");
    // tu irgendwas mit dem text....
    if (mqtt_data == "ON") {
      RelState= HIGH;
      Serial.println("set RelState HIGH");
    if (mqtt_data == "OFF") {
      RelState= LOW;
      Serial.println("set RelState LOW");
    client.publish("/SONOFF01/RELSTATE", mqtt_REL);                    // sofort den Status zurück melden! ############

later in the Main Loop I am switching the relay:

  digitalWrite (RELPIN1, RelState);

Why Sonoff? Because these are cheap and handy switches, including power supply and housing. But you can do the same with a naked ESP8266 board.


1 Like

can i have the whole code please .?? you can erase your wifi ssid and wifi password and any other personnal stuff.(just tell me "this line is for ssid " for example) Please it’s been 3 days that i have been trying to do this . Been modifying tons of codes.

ps: i don’t undestand german if it’s german .
thanks for answearing

Yes, I will send you the complete code this evening via PN, I currently don’t have access to it.
And yes, the comments are in German, but you can use the Google translator for it.


Here is my code:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Bounce2.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

const char* ssid = "XXXXXXX"; //SSID WIFI Access Point
const char* password = "XXXXXXXXX"; //Access Point Password
const char* mqtt_server = "XXXXXXXXX"; //IP address MQTT server

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

const char* inTopic = "House/LivingRoom/AquariumPump"; // MQTT Topic this switch subscribes ("listens" to
const char* switchTopic = "House/LivingRoom/AquariumPumpStatus"; //MQTT Topic wall switch publish

int relay_pin = 12; //Pin for Relay
int button_pin = 0; //Pin for button
int switch_pin = 14; //Pin for ext switch
bool relayState = HIGH;

// Instantiate a Bounce object - used for built in button to toggle relay on/off:
Bounce debouncer = Bounce(); 
Bounce debouncer2 = Bounce();

unsigned long previousMillis = 0;  // will store last time STATUS was send to MQTT
const long interval = 60000; //one minute for status refresh

void setup_wifi() {

  // We start by connecting to a WiFi network
  Serial.print("Connecting to ");

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    for(int i = 0; i<500; i++){
  digitalWrite(13, LOW);
  digitalWrite(13, HIGH);
  digitalWrite(13, LOW);
  digitalWrite(13, HIGH);
  Serial.println("WiFi connected");
  Serial.println("IP address: ");

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print("] ");
  for (int i = 0; i < length; i++) {

  // Switch on the RELAY if an "1" was received as first character or OFF if first character was a "0" or toggle relay when received a "2"
  if ((char)payload[1] == 'F') {
    digitalWrite(13, HIGH); // Turn LED OFF
    digitalWrite(relay_pin, LOW);   // Turn the RELAY OFF
    relayState = LOW;
  } else if ((char)payload[1] == 'N') {
    digitalWrite(13, LOW); // Turn LED OFF
    digitalWrite(relay_pin, HIGH);  // Turn the RELAY ON by making the voltage HIGH
    relayState = HIGH;

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("SonoffAquariumPump", "openhab", "Spirou@01")) {
      // Once connected, publish an announcement to $State...
//      client.publish($State, "I am ON", true);
      //Send WIFI Signal Strength
      long rssi = WiFi.RSSI();
      char sig[50];
      sprintf(sig, "%d.%02d", (int)rssi, (int)(rssi*100)%100);
//      client.publish($Signal, sig, true);
      //Send IP address of node
      char buf[16];
      sprintf(buf, "%d.%d.%d.%d", WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3] );
//      client.publish($IP, buf, true);
      //Subscribe to incoming commands
    } else {
      Serial.print("failed, rc=");
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      for(int i = 0; i<5000; i++){

void extButton() {
   // Call code if Bounce fell / onboard button pushed (Toggle from HIGH to LOW) :
   if ( debouncer.fell() ) {
     Serial.println("Debouncer fell");
     // Toggle relay state :
     relayState = !relayState;
     if (relayState == 1){
//      client.publish($State, "I am ON", true);
      client.publish(switchTopic, "ON", false);
      digitalWrite(13, LOW);
     else if (relayState == 0){
//      client.publish($State, "I am OFF", true);
      client.publish(switchTopic, "OFF", false);
      digitalWrite(13, HIGH);

void extSwitch() {
  if (debouncer2.fell()) {
    client.publish(switchTopic, "ON", false);
  if (debouncer2.rose()) {
    client.publish(switchTopic, "OFF", false);

void updatecall()  {
    unsigned long currentMillis = millis();
      if (currentMillis - previousMillis >= interval) {
        // save the last time status was send
        previousMillis = currentMillis;
          if (relayState == 1){
//            client.publish($State, "I am ON", true);
          else if (relayState == 0){
//            client.publish($State, "I am OFF", true);

void setup() {
  String line = "";
  pinMode(relay_pin, OUTPUT);     // Initialize the relay pin as an output
  pinMode(button_pin, INPUT);     // Initialize the relay pin as an input
  pinMode(switch_pin, INPUT_PULLUP);
  pinMode(13, OUTPUT);            // Initialize the onboard LED as output

  debouncer.attach(button_pin);   // Use the bounce2 library to debounce the built in button
  debouncer.interval(50);         // Input must be low for 50 ms
  digitalWrite(13, LOW);          // Blink to indicate setup
  digitalWrite(13, HIGH);
  setup_wifi();                   // Connect to wifi

  client.setServer(mqtt_server, 1883); //connect to MQTT

  // Port defaults to 8266: ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID] - change to your own hostname with ArduinoOTA.setHostname("YOURNODEHOSTNAME");
  // No authentication by default - set your password with ArduinoOTA.setPassword((const char *)"YOURPASSWORD");
  //ArduinoOTA.setPassword((const char *)"123456");

  ArduinoOTA.onStart([]() {
  ArduinoOTA.onEnd([]() {
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  Serial.print("IP address: ");


void loop() {
  if (!client.connected()) {
  // updatecall();

I too am a noobie. My first project is a Garage Door Sensor and Opener. I have a Raspberry Pi 3 with OpenHAB and MQTT Broker installed, a Sonnoff RF Bridge and a door sensor. I’ve ordered a USB to TTL adapter and an ESP8266 WiFi relay. When they arrive I will install Tasmota on both so that I can use MQTT. In the meantime I can view Garage Door state via Ewelink and I’ve been reading as much as I can in preparation and this thread is very helpful. Thank you to the contributors.