Home Assistant is the most popular open-source home automation platform — running on a Raspberry Pi or any Linux box, it becomes the hub for every sensor, switch, and actuator in your home. MQTT is the glue that connects your ESP32 devices to it, with zero cloud dependency.

// What you'll build: ESP32 reads a DHT22 and publishes temperature + humidity to a local Mosquitto MQTT broker every 30 seconds. Home Assistant auto-discovers the device via MQTT Discovery and shows live sensor cards on its dashboard.
ESP32 DHT22 sensor PubSubClient PUBLISH home/esp32/state MOSQUITTO MQTT Broker port 1883 SUBSCRIBE wildcard # HOME ASSISTANT Auto-discovery DASH BOARD
// AD SLOT — IN-CONTENT RESPONSIVE

Step 1 — Install Mosquitto on Home Assistant

In Home Assistant go to Settings → Add-ons → Add-on Store and search for Mosquitto broker. Install it, enable Start on boot, and start it. Note your HA host IP — you'll need it for the ESP32 sketch.

Create an MQTT user: Settings → People → Add user (e.g. username mqtt_user).

Step 2 — ESP32 Sketch

// ha_mqtt_sensor.ino
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <DHT.h>

const char* SSID       = "YOUR_SSID";
const char* PASSWORD   = "YOUR_PASSWORD";
const char* MQTT_HOST  = "192.168.1.10";  // Home Assistant IP
const int   MQTT_PORT  = 1883;
const char* MQTT_USER  = "mqtt_user";
const char* MQTT_PASS  = "mqtt_password";

const char* DEVICE_ID        = "esp32_living_room";
const char* STATE_TOPIC      = "home/esp32_living_room/state";
const char* DISCOVERY_PREFIX = "homeassistant";

#define DHT_PIN  4
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);

WiFiClient   wifiClient;
PubSubClient mqtt(wifiClient);

// Publish MQTT Discovery configs so HA auto-discovers sensors
void publishDiscovery() {
  StaticJsonDocument<512> doc;

  // Temperature sensor
  doc["name"]        = "Living Room Temperature";
  doc["unique_id"]   = "esp32_lr_temp";
  doc["state_topic"] = STATE_TOPIC;
  doc["value_template"] = "{{ value_json.temperature }}";
  doc["unit_of_measurement"] = "°C";
  doc["device_class"] = "temperature";
  doc["device"]["identifiers"][0] = DEVICE_ID;
  doc["device"]["name"] = "ESP32 Living Room";
  doc["device"]["model"] = "ESP32 + DHT22";
  doc["device"]["manufacturer"] = "ESPSTACK";
  String payload; serializeJson(doc, payload);
  mqtt.publish((String(DISCOVERY_PREFIX) + "/sensor/" + DEVICE_ID + "/temp/config").c_str(),
               payload.c_str(), true);

  // Humidity sensor
  doc.clear();
  doc["name"]        = "Living Room Humidity";
  doc["unique_id"]   = "esp32_lr_hum";
  doc["state_topic"] = STATE_TOPIC;
  doc["value_template"] = "{{ value_json.humidity }}";
  doc["unit_of_measurement"] = "%";
  doc["device_class"] = "humidity";
  doc["device"]["identifiers"][0] = DEVICE_ID;
  serializeJson(doc, payload);
  mqtt.publish((String(DISCOVERY_PREFIX) + "/sensor/" + DEVICE_ID + "/hum/config").c_str(),
               payload.c_str(), true);
}

void connectMQTT() {
  while (!mqtt.connected()) {
    Serial.print("Connecting MQTT...");
    if (mqtt.connect(DEVICE_ID, MQTT_USER, MQTT_PASS)) {
      Serial.println("connected.");
      publishDiscovery();
    } else {
      Serial.printf("failed rc=%d, retry in 5s\n", mqtt.state());
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  dht.begin();
  WiFi.begin(SSID, PASSWORD);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  mqtt.setServer(MQTT_HOST, MQTT_PORT);
}

unsigned long lastPublish = 0;
void loop() {
  if (!mqtt.connected()) connectMQTT();
  mqtt.loop();

  if (millis() - lastPublish >= 30000) {
    lastPublish = millis();
    float t = dht.readTemperature();
    float h = dht.readHumidity();
    StaticJsonDocument<64> doc;
    doc["temperature"] = round(t * 10) / 10.0;
    doc["humidity"]    = round(h * 10) / 10.0;
    String payload; serializeJson(doc, payload);
    mqtt.publish(STATE_TOPIC, payload.c_str());
    Serial.printf("Published: %s\n", payload.c_str());
  }
}

Step 3 — Home Assistant Dashboard

After flashing and powering the ESP32:

  1. Go to Settings → Devices & Services → MQTT
  2. Your device ESP32 Living Room will appear automatically via Discovery
  3. Add the sensors to a dashboard card: Overview → Add card → Entities → select your temperature and humidity sensors

Bonus — HA Automation: Alert when too hot

// configuration.yaml (Home Assistant)
automation:
  - alias: "High Temperature Alert"
    trigger:
      platform: numeric_state
      entity_id: sensor.living_room_temperature
      above: 30
    action:
      service: notify.mobile_app_your_phone
      data:
        message: "Living room is {{ states('sensor.living_room_temperature') }}°C!"

Tips & Troubleshooting

IssueCauseFix
Device not appearing in HAMQTT Integration not configuredSettings → Integrations → Add → MQTT
rc=-2 (connect fails)Wrong broker IP or port blockedPing broker; check firewall; verify port 1883 open
Duplicate entitiesunique_id already usedChange unique_id in discovery payload
Stale values after rebootRetained messagesPublish empty payload to config topic to clear
A
Engr. Aamir Aziz Butt
PhD Researcher · IoT Engineer · Founder ESPSTACK

PhD candidate at Muslim Youth University, Islamabad. MS Computer Engineering from COMSATS. 10+ years of IoT development experience across ESP32, Jetson Nano, and cloud platforms.