Relay on/off with esp8266 and openHAB

Hi,
I am new to openHAB and esp8266. I want to build my self a smart light switch which consists of a two channel relay board and esp8266-01. I want to control the relay with MQTT from the openHAB app on my phone. But i need help with the code for the esp8266. I did some research in google but i haven`t found anything related to my problem. I am aware of sonoff and the other already made devices i want to make my own device as a project for my home.
THANKS in advance!

Use the homie-framework.

I found an example in Homie called lightonoff but can it interact with openhab via MQTT i cant see where can i enter my wi-fi creadentials or both device can discover each other without that?

Send me a PM
I have some code

It’s for a sonoff but it will work on any ESP8266 board
Just make sure you use the right pins

1 Like

I cant seem to find how to PM you. Maybe cause i`m a new member. Can you PM me?

Click on the avatar and then on “Message”

1 Like

Could you send me the code too, please ?

Can you please share me code.

Hi Could you please send me code.

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

const char* ssid = "SSID"; //SSID WIFI Access Point
const char* password = "password"; //Access Point Password
const char* mqtt_server = "XXX.XXX.XXX.XXX"; //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() {

  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) {
    extButton();
    for(int i = 0; i<500; i++){
      extButton();
      delay(1);
    }
    Serial.print(".");
  }
  digitalWrite(13, LOW);
  delay(500);
  digitalWrite(13, HIGH);
  delay(500);
  digitalWrite(13, LOW);
  delay(500);
  digitalWrite(13, HIGH);
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

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

  // 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", "MQTTUsername", "MQTTPassword")) {
      Serial.println("connected");
      // 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
      client.subscribe(inTopic);
      
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      for(int i = 0; i<5000; i++){
        extButton();
        delay(1);
      }
    }
  }
}

void extButton() {
  debouncer.update();
   // 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;
     digitalWrite(relay_pin,relayState);
     if (relayState == 1){
      client.publish(switchTopic, "ON", false);
      digitalWrite(13, LOW);
     }
     else if (relayState == 0){
      client.publish(switchTopic, "OFF", false);
      digitalWrite(13, HIGH);
     }
   }
}

void updatecall()  {
    unsigned long currentMillis = millis();
      if (currentMillis - previousMillis >= interval) {
        // save the last time status was send
        previousMillis = currentMillis;
          if (relayState == 1){
          }
          else if (relayState == 0){
          }
       }
}

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
  debouncer2.attach(switch_pin);
  debouncer2.interval(50);
  
  digitalWrite(13, LOW);          // Blink to indicate setup
  delay(50);
  digitalWrite(13, HIGH);
  delay(50);
  
  Serial.begin(115200);
  setup_wifi();                   // Connect to wifi

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

  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

}

void loop() {
  
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  extButton();
}