Esp8266 Relay without delay Issues/pulling my hair out

First off, I am very new to openhab. I have more experience with arduino and basic IOT. This community is amazing, I am learning so much by following other peoples topics and the openhab beginner instructions. Having a lot of fun until this :/…

I am trying to get openhab2 to operate a standard relay (on/off). I followed this other topic ([OH2] Control ESP8266 Relay using MQTT Eventbus) and was able to get everything working just fine. MQTT was setup and tested. The relay would come on and the turn off as configured. However, I don’t want the delay. I simply want the on/off function. I removed the delay commands from the arudino code but no luck. I have a feeling OpenHab needs to know the state of the relay so I am most likely missing some commands. Any help would be amazing! Listed below is Dim’s code that I edited.

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

/************************* WiFi Access Point *********************************/

/************************* MQTT Broker Setup *********************************/
#define mqtt_server “10.0.0.XX”
#define mqtt_serverport 1883 // use 8883 for SSL
//#define mqtt_username “<mqtt_username>” not used for now…
//#define mqtt_password “<mqtt_password>” not used for now…

/************************* 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);

// Setup subscription ‘Workbench light’ for monitoring topic for changes.
Adafruit_MQTT_Subscribe Desklight = Adafruit_MQTT_Subscribe(&mqtt, “openhab/out/Desklight/command”);

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

void setup() {
Serial.println(""); Serial.println(F(“Booting… v0.2”));
pinMode(relayPin, OUTPUT);
// Connect to WiFi access point.
Serial.print("Connecting to "); Serial.println(WLAN_SSID);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println(“Connection Failed! Rebooting in 5 secs…”);

// Setup MQTT subscription for DeskLight feed.

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

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.println(“Ready & WiFi connected”);
Serial.print("IP address: "); Serial.println(WiFi.localIP());

void loop() {
// 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.

// 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 == &DeskLight) {
Serial.print(F("Got: ")); Serial.println((char *)DeskLight.lastread);
// toggle the relay for 10 ms
Serial.println(“Toggle Relay On for 10 ms & then Off”);
digitalWrite(relayPin, HIGH);
digitalWrite(relayPin, LOW);

// ping the server to keep the mqtt connection alive
// NOT required if you are publishing once every KEEPALIVE seconds
// if(! {
// 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()) {

Serial.print("Connecting to MQTT… ");

uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(“Retrying MQTT connection in 5 seconds…”);
delay(5000); // wait 5 seconds
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
Serial.println(“MQTT Connected!”);

OpenHab2 config:

Please use code fences to preserve the formatting of your code

// Your code goes here

I’m no expert on Arduino code but in the original the on/off delay was to simulate a button press (e.g. like pressing a door bell button or garage door opener button).

You can’t just eliminate the delay because changing the state of a reality that quickly can burn it out in no time, not to mention the fact that the really won’t stay on long enough for what ever is receiving the simulate button press to register the signal change.

If what you are really after is to just go high on one receipt of an mqtt message and go low on the next you will need to keep track of the current state of the relay on the Arduino and toggle the state instead of flipping it high and immediately low immediately which, if you are simulating a button press is probably too fast to be picked up and if you are controlling something like a light would keep the light on for so little time as to be inperceptable.

1 Like

It will be much easier to use a framework for the ESP8266.
Check out:

  1. GitHub - homieiot/homie-esp8266: 💡 ESP8266 framework for Homie, a lightweight MQTT convention for the IoT
  2. Releases · homieiot/homie-esp8266 · GitHub

and of course: