Advice Needed: How to Control a Sliding Gate Opener?


(Angelos) #21

Hi @gopi_ar,

Nice!

I am configuring now my Wemos D1 mini (ESP8266) to connect to my MQTT Broker (Mosquitto) to publish and subscribe to messages. In this way, I will use MQTT to integrate it to OpenHab2.

You wrote: “2 pairs” = 4 wires. Did you mean 2 wires (1 pair) from the Cat6 cable?

In my system, I need to close the circuit between 2 pins [pins 9 (Common = 24V AC) & 12 (Step-Step)] in the Robo 500 gate opener. In my case, I will use only 2 wires between the relay and the NICE 500.

Maybe the NICE 400 has another type of motherboard with different (seperate) functions for Open / Close.


(Tommy Sharp) #22

Hey guys, sorry for the slow response… This is my arduino scrip below that I have loaded on a Wemos D1 Mini which has the relay shield that they also sell.

This uses the “Homie” firmware which you can find by searching these forums. It takes care of the wifi and MQTT stuff nicely.

My gate has 2 terminals for a push button switch to be used, I’ve connected these up to my relay. I have also mounted a magnetic reed switch to the gate and loaded it up as a contact so that I can tell if the gate is open or closed.

I needed to use the debouncer because the magnetic reed switch flicks between open/close a few times in the split second that it registers as opened or closed.

#include <Homie.h>

const int PIN_RELAY = D1;
const int PIN_DOOR = D2;

Bounce debouncer = Bounce(); // Bounce is built into Homie, so you can use it without including it first
int lastDoorValue = -1;

HomieNode GateSensorNode("gatesensor", "sensor");
HomieNode GateRelayNode("gaterelay", "switch");


bool doorOnHandler(String value) {
  if (value == "true") {
digitalWrite(PIN_RELAY, HIGH);
Homie.setNodeProperty(GateRelayNode, "on", "true"); // Update the state of the relay
Serial.println("Gate relay is on");
delay(100);                  // waits for half a second and then switches relay off again, my gate just needs to the circuit to be closed for a short time
digitalWrite(PIN_RELAY, LOW);
Homie.setNodeProperty(GateRelayNode, "on", "false");
Serial.println("Gate relay set back to off");
  } else if (value == "false") {
digitalWrite(PIN_RELAY, LOW);
Homie.setNodeProperty(GateRelayNode, "on", "false");
Serial.println("Gate relay is off");
  } else {
return false;
  }
  return true;
}

void loopHandler() {
  int doorValue = debouncer.read();

  if (doorValue != lastDoorValue) {
 Serial.print("Door is now: ");
 Serial.println(doorValue ? "open" : "close");

 if (Homie.setNodeProperty(GateSensorNode, "open", doorValue ? "true" : "false", true)) {
   lastDoorValue = doorValue;
 } else {
   Serial.println("Sending failed");
 }
  }
}

void setup() {
  pinMode(PIN_DOOR, INPUT_PULLUP);
  pinMode(PIN_RELAY, OUTPUT);
  digitalWrite(PIN_DOOR, HIGH);
  digitalWrite(PIN_RELAY, LOW); // turn off relay with voltage LOW
  debouncer.attach(PIN_DOOR);
  debouncer.interval(500);

  Homie.setFirmware("homie-gatesensor", "1.0.1");
  GateRelayNode.subscribe("on", doorOnHandler);
  Homie.registerNode(GateSensorNode);
  Homie.registerNode(GateRelayNode);
  Homie.setLoopFunction(loopHandler);
  Homie.setup();
}

void loop() {
  Homie.loop();
  debouncer.update();
}

This is what my items in Openhab 1.8 look like.

Contact Gate01Contact "Front Gate" <slidinggate> (GroupOutdoors) {mqtt="<[mosquitto:homie/0fc787e0/gatesensor/open:command:OPEN:true],	<[mosquitto:homie/0fc787e0/gatesensor/open:command:CLOSED:false]"}
Switch Gate01Button {mqtt="<[mosquitto:homie/0fc787e0/gaterelay/on:state:ON:true],<[mosquitto:homie/0fc787e0/gaterelay/on:state:OFF:false],>[mosquitto:homie/0fc787e0/gaterelay/on/set:command:ON:true],>[mosquitto:homie/0fc787e0/gaterelay/on/set:command:OFF:false]"}

And as you can see from the up time below, it’s pretty reliable for a $15 setup.


(Angelos) #23

Thanx alot @TommySharp !
I got some ideas from your sketch and I created mine (beta version):
The sketch is not clean yet… I am still trying things out.
I added OTA also to be able to play with the sketch Over The Air :slight_smile:

/*
 * Dim - Relay Shield Toggle v0.2
 * Turns on the relay for 10 ms, then off based on OH2 event
 * Relay Shield transistor closes relay when D1 is HIGH
/*

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <Adafruit_MQTT.h>
#include <Adafruit_MQTT_Client.h>

/************************* WiFi Access Point *********************************/
#define WLAN_SSID       "<ssid>"
#define WLAN_PASS       "<pass>"

/************************* MQTT Broker Setup *********************************/
#define mqtt_server      "<mqtt_broker>"
#define mqtt_serverport  1883                   // use 8883 for SSL
#define mqtt_username    "<mqtt_username>"
#define mqtt_password    "<mqtt_password>"

/************************* Constants, Variables, Integers, etc *********************************/
const int relayPin = D1;
const long togDelay = 10;  // pause for 10 milliseconds before toggling to Open
const long postDelay = 20;  // pause for 20 milliseconds after toggling to Open
int value = 0;
int relayState = LOW;

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, mqtt_server, mqtt_serverport, mqtt_username, mqtt_password);

// Setup subscription 'Robo500' for monitoring topic for changes.
Adafruit_MQTT_Subscribe Robo500 = Adafruit_MQTT_Subscribe(&mqtt, "openhab/out/Robo500/command");

/*************************** Sketch Code ************************************/
void MQTT_connect();

void setup() {
  Serial.begin(115200);
  Serial.println(""); Serial.println(F("Booting... v0.2"));
  pinMode(relayPin, OUTPUT);
  // Connect to WiFi access point.
  Serial.print("Connecting to "); Serial.println(WLAN_SSID);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
  Serial.println("Connection Failed! Rebooting in 5 secs...");
  delay(5000);
  ESP.restart();
  }

  // Setup MQTT subscription for Robo500 feed.
  mqtt.subscribe(&Robo500);

  // Begin OTA
  ArduinoOTA.setPort(8266); // Port defaults to 8266
  ArduinoOTA.setHostname("robo500");   // Hostname defaults to esp8266-[ChipID]
  ArduinoOTA.setPassword((const char *)"<pass>");   // No authentication by default

  ArduinoOTA.onStart([]() {
    Serial.println("Start");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  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");
  });
  ArduinoOTA.begin();
  Serial.println("");
  Serial.println("Ready & WiFi connected");
  Serial.print("IP address: "); Serial.println(WiFi.localIP());
}

void loop() {
  ArduinoOTA.handle();
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();
  
  // this is our 'wait for incoming subscription packets' busy subloop
  // try to spend your time here

  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    if (subscription == &Robo500) {
      Serial.print(F("Got: ")); Serial.println((char *)Robo500.lastread);
      // toggle the relay for 10 ms
      Serial.println("Toggle Relay On for 10 ms & then Off");
      digitalWrite(relayPin, HIGH);
      delay(togDelay);
      digitalWrite(relayPin, LOW);
      delay(postDelay);
    }
  }

  // ping the server to keep the mqtt connection alive
  // NOT required if you are publishing once every KEEPALIVE seconds
//   if(! mqtt.ping()) {
//    mqtt.disconnect();
//  }
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }
  
  Serial.print("Connecting to MQTT... ");
  
  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
}


(Angelos) #24

100% success today! :wink:
The solution (ESP8266 + MQTT + OH2) works better than I expected
More news soon with full documentation and pictures of the implementation…


(Angelos) #25

Updated here:


(Angelos) #26

just a small update on this project:

It’s unbelievable how well this system works even at -14 degrees Celsius temperatures… :slight_smile: :slight_smile: :slight_smile:


(matt dorsey) #27

I have this working! However, I am trying to do away with the delay. I just want to simply turn the relay on/off. I deleted the " delay(togDelay);" and " delay(postDelay);" but no luck… Can anyone help?


(matt dorsey) #28

anyone???


(Angelos) #29

:slight_smile:

Let’s do the following:
Open up a new thread with your scenario, post your current ESP sketch and let’s see what can be done


(The Squid) #30

Use the expire binding, that’s what I used and it’s working perfectly.

Take a look at my example


(Angelos) #31

Another update since it has been now 1 year+ since this system went operational:
Zero (0) hiccups, Zero (0) faults, instant reaction to openHAB commands… super happy :slight_smile:


==> events.log <==
2018-02-19 09:32:03.689 [ome.event.ItemCommandEvent] - Item 'Robo500' received command ON


(Angelos) #32

2 years mark: Zero maintenance done :slight_smile:

Snow will not stop the ESP… going strong