You thought about it, do IT !

MQTT – Publish your own arduino / ESP sensor data

MQTT – Publish your own arduino / ESP sensor data

Today we will learn how to publish the data of our home made sensor to Home Assistant MQTT broker.

To send data to a broker using arduino IDE you need to follow this steps :

Download required library and include it to the top of your program

#include <PubSubClient.h>

Add required variables and initialize :

#define MQTT_HOSTNAME "Your_Device_Name"
#define MQTT_BROKER_IP "Your_Broker_IP"
#define MQTT_USERNAME "Your_Broker_User"
#define MQTT_PASSWORD "Your_Broker_Password"

const char* mqtt_server = MQTT_BROKER_IP;
#define MSG_BUFFER_SIZE  (50)
char msg[MSG_BUFFER_SIZE];
WiFiClient client;
PubSubClient MQTTclient(client);

Define the function that will publish data :

//Fonction qui publie les données sur le broker MQTT
void MQTT_Publish(){
  
  //Debug
  Serial.println("MQTT - Publishing");

 
  //Connects if needed
  if (!MQTTclient.connected()) {
    Serial.println("MQTT - Attempting connection...");
    MQTTclient.connect(MQTT_HOSTNAME,MQTT_USERNAME, MQTT_PASSWORD);
  }
  
  //If connected, publish
  if (MQTTclient.connected()) {
    Serial.println("MQTT - Connected");
    
    MQTTclient.publish("TEST/Your_Sensor",String(Your_Sensor_Value).c_str(),true);
    
    //Delay needed if deepsleep after publishing
    delay(50);

  } else {
    Serial.print("MQTT - Error, rc=");
    Serial.print(MQTTclient.state());
  }

}

Now you can publish data on your program using MQTT_Publish() function.

do-it.dev Avatar
if you liked it, please contribute !

Leave a Reply

Your email address will not be published. Required fields are marked *

Aurélien Bordinat

I am a french computer engineer, adept of DIY, home automation and new technologies. When i’m not busy trail running, i spend some time prototyping.