Nodemcu MQTT Switch example

I was wondering if someone might be able to share a code example of an MQTT switch written for NodeMCU or other Arduino-like platform?

I need to turn a servo arm 13 degrees. Just enough to press the button on my coffee maker. Here’s what I have so far.

#include <ESP8266WiFi.h>
#include <ESP8266WiFiAP.h>
#include <ESP8266WiFiGeneric.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WiFiScan.h>
#include <ESP8266WiFiSTA.h>
#include <ESP8266WiFiType.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>

#include <PubSubClient.h>

#define wifi_ssid ""
#define wifi_password ""

#define mqtt_server ""
#define mqtt_user ""
#define mqtt_password ""
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(D4);  // attaches the servo on pin 9 to the servo object
  for (pos = 0; pos <= 13; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
    //while(1);
  }
  for (pos = 13; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
    //while (1);
  }
}

void loop() {}

I can’t give you an example for your case, but I can give you an mqtt example for a garagedoor which includes a switch.

The callback Method is called every time something is send to the command-Topic.

Greets

Thanks for the post. My MQTT has password with the setup on home assistant. I can see the Node MCU ESP8266 connect to my network, but MQTT cant connect. Any help would be appreciated.
Thanks

Hi stayblack,

just add

const char* mqtt_server = "HASS-SERVER";
const char* mqtt_username = "homeassistant";
const char* mqtt_password = "YOUR-PASSWORD";

-Dennis