HA – communication between MQTT and Arduino


MQTT stands for Message Queuing Telemetry Transport.
It’s a lightweight protocol where a small code footprint is needed, and the connection uses a small bandwidth. It is mainly used for “machine-to-machine” communication or IOT (Internet-Of-Things).
It’s an ideal solution to exchange data between Home Assistant and Arduino (ESP32) projects.

We need the following components:

  • An MQTT Broker (Mosquitto broker within HA, works fine ! https://mosquitto.org/ )
    This can be installed/managed from within HA itself.
  • MQTT explorer (a free tool for windows/linux/mac http://mqtt-explorer.com/ )
    To create/modify/view MQTT topics, we will use MQTT Explorer.
  • an Arduino board with network/WiFi (ESP32 is ideal)
    Besides the ESP32 board definition, we also need to install the PubSubClient library.
    (this will be the library we use to communicate with MQTT)

Create an MQTT topic “ESP32/TEST” and “publish” it via MQTT Explorer.
Next, add this topic into your configuration.yaml and reboot HA afterwards.

mqtt:  
  sensor:
    - name: "ESP32_MQTT_TEST"
      state_topic: "esp32/test"
      value_template: "{{ value }}"
      qos: 1

After rebooting HA, you will find a new sensor “ESP32_MQTT_TEST”. (as defined in “name” above)
You can publish data from within HA, to this MQTT topic. (usable within automations …)
(or send data from ESP32 to HA, as you will see a bit further down this article)

service: mqtt.publish
data:
  topic: esp32/test
  payload: The text to publish, of course you can also use other sensor values

The following arduino code is used as an example in the ESP32:
(publishing and subscribing !)

#include <WiFi.h>
#include <PubSubClient.h>

// WiFi
const char *ssid = "XXX"; // Enter your WiFi name
const char *password = "XXX";  // Enter WiFi password

// MQTT Broker
const char *mqtt_broker = "192.168.123.88";
const char *topic = "esp32/test";
const char *mqtt_username = "XXX";
const char *mqtt_password = "XXX";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
 // Set software serial baud to 115200;
 Serial.begin(115200);
 // connecting to a WiFi network
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
     delay(500);
     Serial.println("Connecting to WiFi..");
 }
 Serial.println("Connected to the WiFi network");
 //connecting to a mqtt broker
 client.setServer(mqtt_broker, mqtt_port);
 client.setCallback(callback);
 while (!client.connected()) {
     String client_id = "esp32-test-";
     client_id += String(WiFi.macAddress());
     Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
     if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
         Serial.println("HA mqtt broker connected");
     } else {
         Serial.print("failed with state ");
         Serial.print(client.state());
         delay(2000);
     }
 }
 // publish and subscribe
 client.publish(topic, "Bericht vanuit Arduino naar de MQTT broker");
 client.subscribe(topic);
}

void callback(char *topic, byte *payload, unsigned int length) {
 Serial.print("Message arrived in topic: ");
 Serial.println(topic);
 Serial.print("Message:");
 for (int i = 0; i < length; i++) {
     Serial.print((char) payload[i]);
 }
 Serial.println();
 Serial.println("-----------------------");
}

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

– SSID & password, are your WiFi SSID & according password.
– mqtt_broker, is the IP address (or DNS name), of your broker. (mostly, identical to HA IP address)
– topic, the MQTT topic.
– mqtt_username & mqtt_password, username & password to authenticate with MQTT broker.
– mqtt_port (default = 1883)
client.setserver, you initialise a connection with the MQTT broker.
client.publish, you send a message to the corresponding MQTT topic / broker.
client.subscribe, a subscription for notification to the MQTT topic / broker is made.
client.setcallback, subroutine to be called when receiving an mqtt message. (see “void callback(…)” for arguments)


This entry was posted in Blog, Home Assistant, Tutorials. Bookmark the permalink.

2 Responses to HA – communication between MQTT and Arduino

  1. Allan Keith Williams says:

    “(or send data from ESP32 to HA, as you will see a bit further down this article)”

    Where is that bit?
    I can receive data from my ESP32, but cant seem to send commands back. I can see (via mqtt explorer) that HA has sent the command, but it doesnt seem to get to the ESP32.

    • Kris says:

      Hi Allan Keith,

      Sorry for the late reply, I’m currently on holidays, so I don’t read my mails every day.

      The last code-part in red, contains everything to send/receive data from/to MQTT.
      – make sure your settings are correct in the “//MQTT Broker” part (you will get a “HA mqtt broker connected” on your serial terminal, when everything is fine)
      – make sure you have a call to client.setCallBack (to be sure, move this line of code after the check for the MQTT connection. (just before the line “//publish and subscribe”)
      the value between the brackets () after client.setCallBack, must correspond with a void with the same name,, to be able to receive the message. (in my code, this is “callback”.
      – make sure you are “subscribing’ to the correct topic, this is case-sensitive, no spaces, and no slash at the end of the topic !
      – make sure you have a line “client.loop();” in your main loop, otherwise the topic does not get catched. Also make sure that this loop is not containing to much code, that may slow-down (or even skip) to retrieval of your message.
      (to send something from ESP32 to MQTT, you can call client.publish(…) whenever you like.

      I case this still does not work, you can send your code and topic name()s and MQTT config to me 🙂 (kris at digitalplayground dot be)

      Best regards and good luck,
      Kris

Leave a Reply

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