ESP8266 switch pin via MQTT

This is a simple code template to switch a pin of an ESP8266 microcontroller using MQTT.

The example turns PIN D7 on if "1" was received at the "candle" MQTT topic. All other messages turn the pin off.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <MQTT.h>
#include <stdint.h>

// Configuration
#define WIFI_SSID "xxx"
#define WIFI_PASSWORD "yyy"

#define MQTT_BROKER "192.168.1.70"
#define MQTT_CLIENT_ID "candle"
#define MQTT_USERNAME ""
#define MQTT_PASSWORD ""
#define MQTT_TOPIC "candle"


WiFiClient net;
MQTTClient client;

void connect_mqtt() {
  // Make sure wifi is connected
  while (WiFi.status() != WL_CONNECTED) delay(500);
  // Connect client
  client.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD);

  // Subscribe to all led topics
  client.subscribe(MQTT_TOPIC);

  // Publish ready message
  client.publish(MQTT_TOPIC, "Connected.");
}

static inline void reconnect_if_required() {
  if (!client.connected()) connect_mqtt();
}

void messageReceived(String &topic, String &payload) {
  int value = payload.toInt();

  if (value == 1)
    digitalWrite(D7, 1);
  else
    digitalWrite(D7, 0);
}

void setup() {
  // Connect WIFI
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  // Connect MQTT
  client.begin(MQTT_BROKER, net);
  client.onMessage(messageReceived);

  // First connection
  connect_mqtt();

  // Initialize pin
  pinMode(D7, OUTPUT);
  digitalWrite(D7, 0);
}

void loop() {
  client.loop();
}

Show Comments