Trying to creat an MQTT button with wemos and button shield

I would like to use a simple Wemos D1 with a button shield to send a transition to Hassio when the button is pressed. I would have thought this example code would have been everywhere. My goal is to have an all lights on/off toggle button.

Can anyone point me to code they have used for this?

I have found the following code, but the posting is not formatted correctly and i am not good enough at Arduino to properly format it and start working with it…
https://circuits.io/circuits/2446254-esp8266-mqtt-switch

As you can see the first half is a mess!

#include "Arduino.h" #include "ESP8266WiFi.h" #include "PubSubClient.h" #include "Bounce2.h"

#define wifiSsid "yourssid" #define wifiPassword "yourpass"

//-- MQTT #define mqttServerIp "yourserver" #define mqttUser "youruser" #define mqttPassword "yourpass"

//-- MQTT char stateTopic[] = "outdoor/highlight"; char cmdTopic[] = "outdoor/highlight/set"; char topicValue[] = "OFF";

//-- GPIO #define relayPin 2 //BUILTIN_LED //5 #define buttonPin 0

//-- SETTINGS const int mqttTimeReconect = 5000; const int buttonPressHoldTime = 500; const int showWifiReconnectionTime = 1000;

int x = 1;

WiFiClient wifiClient; PubSubClient client(wifiClient); Bounce bouncer = Bounce();

bool showWiFiStatus = false; long lastMsg = 0; long lastMqttReconnect = 0; long lastWiFiReconnect = 0; String topicMsg; int prevButtonState = LOW;

void setupGpio() { pinMode(relayPin, OUTPUT); digitalWrite(relayPin, HIGH);

pinMode(buttonPin, INPUT); bouncer.attach(buttonPin); bouncer.interval(5); }

//--- WiFi void setupWifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(wifiSsid);

WiFi.begin(wifiSsid, wifiPassword); }

void reconnectWiFi() { long now = millis(); if (WiFi.status() != WL_CONNECTED) { if (now - lastWiFiReconnect > showWifiReconnectionTime) { //show reconnect status lastWiFiReconnect = now; Serial.println("Failed connect to WiFi..."); showWiFiStatus = false; } } else { if(!showWiFiStatus) { showWiFiStatus = true; Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); Serial.print("RSSI: "); Serial.println(WiFi.RSSI()); } } } //-- MQTT

void setRelayState(uint8_t state) { //state should be inverted in according with the circuit digitalWrite(relayPin, state); }

char messageBuff[100]; void mqttCallback(char* topic, byte* payload, unsigned int length) { int i = 0; for(i=0; i<length; i++) { messageBuff[i] = payload[i]; } messageBuff[i] = '\0';

String topicPayload = String(messageBuff);

Serial.print("Recived for topic: "); Serial.print(topic); Serial.println(" data: " + topicPayload); setRelayState((topicPayload == "ON") ? HIGH : LOW); }

void setupMqtt() { client.setServer(mqttServerIp, 1883); client.setCallback(mqttCallback); }

String macToStr(const uint8_t* mac) { String result; for (int i = 0; i < 6; ++i) { result += String(mac[i], 16); if (i < 5) result += ':'; } return result; }

void reconnectMqtt() { long now = millis(); // Loop until we're reconnected if (!client.connected() && (now - lastMqttReconnect > mqttTimeReconect)) { lastMqttReconnect = now; Serial.print("Attempting MQTT connection..."); // Attempt to connect // If you do not want to use a username and password, change next line to // if (client.connect("ESP8266Client")) { if (client.connect("esp8266HiglightOutdoor", mqttUser, mqttPassword)) { Serial.println("connected"); if(client.subscribe(cmdTopic)) { Serial.print("Subscribed on topic: "); Serial.println(cmdTopic); } } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying } } }

void setup() { Serial.begin(115200); setupGpio(); setupWifi(); setupMqtt(); } // This will store the last known state of the button int oldButtonState = HIGH;

void loop() { bouncer.update(); int newButtonState = bouncer.read(); long now = millis();

reconnectWiFi();

if (!client.loop()) { reconnectMqtt(); } // Button Coding ( this needs to be reviewed for push button vs switch)

if (now - lastMsg > buttonPressHoldTime) { //you should press the button more than lastMsg = now;

// Has the button gone high since we last read it? if (newButtonState == LOW && oldButtonState == HIGH) {

if (x == 0) {
  // Toggle on
  topicMsg = "ON";
  setRelayState(HIGH);
  x = 1;


} else {
  // Toggle off
  topicMsg = "OFF";
  setRelayState(LOW);
  x = 0;

  }

  if(client.publish(stateTopic, topicMsg.c_str())) {
    Serial.print("Topic: ");
    Serial.print(stateTopic);
    Serial.print(" ");
    Serial.println(topicMsg +"; Published Ok"); //it sends ON by default on nodemcu
  } else {
    Serial.print("Topic: ");
    Serial.print(stateTopic);
    Serial.print(" ");
    Serial.println(topicMsg +"; Published failed");
  }
}

Gonna throw this out there. Look at flashing it with ESPEasy. Then it’s a simple as looking at when the button state changes and it will publish a message. It’s easier in the log run because if something changes, wifi password, mqtt topic, or whatever you can just log into the device to change it and not worry about having to pull the device to reload code through the arduino ide.

Ok, loaded it and can talk to it. But there is no listing for Home Assistant in the controllers section?

use the openhab mqtt ( i think) . I’m at work and don’t have anything to look at. Then it’s a matter of adding in your mqtt server address and credentials.

I seem to have it working… Can this be used for SHT30 nodes to report temp/humidity? I assume it is much more complex to do so…

maybe? I have one working with a dht22 and looking at the hardware page SHT1X devices are supported.

Thought it was working… had it sitting plugged in and after about 15 minutes it just triggered with out a button press…

Yes! It works. I also have an SHT30 and Wemos working with it as well! The SHT30 takes a dev load of 2.0.

Use The Deep sleep capability to send a mqtt message then go into deep sleep then but the button over the reset pin and in home assistant use a automation for when it receives a change in that MQTT topic it does something

I was thinking that exact thing. Then I could battery power it as well. I need a good little box for it. So far I have tried one 3D printed box I found, but not sure if our library drops quality on prints or if it was a crappy design. Parts did not fit together well.

I cant help you at all on 3D printing, never learned how to