Simple Esp8266 MQTT Sensor with Home Assistant

Quick Introduction to MQTT

MQTT is an OASIS standard messaging protocol for the Internet of Things (IoT). It is designed as an extremely lightweight publish/subscribe messaging transport that is ideal for connecting remote devices with a small code footprint and minimal network bandwidth

mqtt.org

Many Home Assistant users are used to speak about MQTT (or Zigbee2Mqtt) protocol, commonly used to interface devices (sensors, actuators…) to the Hub, these devices are called MQTT clients.

To implement this communication Home Assistant is often “paired” with the Add-on “Mosquitto“, that act as an MQTT broker.

So, in a simple scenario like the one we’ll see in this article, the sensor (MQTT client) will exchange information with the server (MQTT broker) using the MQTT protocol: The Client will publish a topic while the Broker will subscribe this same topic.

Before start, we assume you have already the Mosquitto broker up and running on your Home Assistant instance. (link)

This is just a simple demonstration project for the MQTT communication, next step I’m planning to extend it with battery management and espnow protocol.

BOM

In this first example for a MQTT sensor I’ve used a generic Wemos D1 ESP8266 module and a TMP36GT9Z temperature sensor.

Wiring

Code

Using the Arduino IDE (link):

  • Copy and paste following code
#include <ESP8266WiFi.h>
#include <Wire.h>
#include <PubSubClient.h>


//****************** CONFIGURATION ******************
#define wifi_ssid "your_router_id"
#define wifi_password "your_router_psw"

#define mqtt_server "your_mosquitto_ip" // your HA IP, example 192.XX.XXX.XX
#define mqtt_user "your_mosquitto_user"
#define mqtt_password "your_mosquitto_psw"


#define temperature_topic "sensor/temperature"
//****************** CONFIGURATION ******************

WiFiClient espClient;
PubSubClient client(espClient);

long lastMsg = 0;
float temp = 0.0;

int sensorPin = 0;


void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

void setup_wifi() {
  delay(10);
  // Connect to a WiFi network
  Serial.println();
  Serial.print("Connecting Wi-Fi...");
  Serial.println(wifi_ssid);

  WiFi.begin(wifi_ssid, wifi_password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("Connected:");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Connecting MQTT...");
    // Attempt to connect

    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}


void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 5000) { // publish frequency
     lastMsg = now;

      int reading = analogRead(sensorPin); 
      float voltage = reading * 3.3;  //3.3 if power at 3.3V
      voltage /= 1024.0; 

      float Temp = (voltage - 0.5) * 100; //conversion from voltage to temperature, the resolution of the sensor is 10 mV per degree, plus offset of 500 mV


      Serial.print("Temperature:");
      Serial.println(String(Temp).c_str());
      client.publish(temperature_topic, String(Temp).c_str(), true);
  }
}
  • Add necessary libraries to you Arduino Project
  • Set your own Wi-Fi and MQTT broker parameters in the “Configuration” section of the code.
  • MQTT User and Password can be retrieved from the Mosquitto Integration – Configuration page.
  • Now Compile and Upload your firmware to the ESP8266 and start your Serial Monitor. You should see the temperature readings, each 5 seconds

Test the MQTT communication

As explained at the beginning, the Wemos is acting as a MQTT client publishing a topic to the Mosquitto broker. The topic that is publishing is that one:

#define temperature_topic "sensor/temperature"

To test if the MQTT broker (Mosquitto Addon) is receiving this topic we can simply subscribe the topic from Mosquitto configuration page:

  • Copy and paste the topic into Topic to subscribe
  • Click START LISTENING

If everything is working properly you should start to read the messages from the client, with the temperature value.

So, the project is working!

Create a new Home Assistant entity

The final step is to include this sensor in Home Assistant Dashboard as a Temperature entity:

  • Open your configuration.yaml
  • Copy and paste following code
  • Restart HA
mqtt:
  sensor:
   - name: "MQTT Temperature Sensor"
     state_topic: "sensor/temperature"
     unit_of_measurement: "c"
     device_class: "temperature"
  • Go to Edit your dashboard and click ADD CARD
  • Search for the new entity “MQTT Temperature Sensor” and click ADD TO DASHBOARD