Same-day dispatch before 2 PM · Free delivery over ₹999 · GST invoices Get the appPrices incl. GST
Geekobot
Snap & SendNEWGeeko AIWhere's myOrder
Log in
Products
  • Projects
    • Component guidesHow parts work, with code you can run
    • Learning pathsFrom your first LED to your first robot
    • Workshops & eventsOnline sessions for makers and classes
    • ElectrolarkFree guided builds, simulator and certificates
    • Students & teachersStudent discount and classroom help
    • CommunityShare builds and ask other makers
    • CalculatorsOhm's law, LED resistor, 555 and 100+ more
    • Circuit builderWire parts and run the circuit, powered by Electrolark
    • Geeko AIAsk what to buy or how to wire it
    • Snap & SendPhotograph a part or list, we find it
    • Part finderAnswer a few questions, get the right part
    • Compatibility checkWill these two parts work together?
    • Compare partsSpecs side by side
    • Business & bulk ordersGST invoices, credit and volume prices
    • Request a quotationSend your list, get a quote
    • Classroom kitsPer-student kits and lab bundles
    • Gift cardsFor students, teams and events
  • Atal Tinkering Lab
BOM to cart
Geekobot

Components, kits and know-how for makers, students, engineers, labs and businesses across India.

Ask Geeko AIOrders, parts and projects, any timeEmail supportReply within 1 working dayGet the Geekobot appAdd it to your home screen, free

Follow us

Shop

  • Boards & SBCs
  • Sensors & Modules
  • IoT & Wireless
  • Drone & FPV
  • 3D Printing
  • Filaments & Resins
  • Motors & Drivers
  • Power & Batteries
  • Semiconductors
  • Passive
  • Displays & LEDs
  • Switches & Relays
  • Wires & Cables
  • Prototyping
  • Tools & Test
  • Robotics
  • STEM Kits
  • Atal Tinkering Lab
  • Mechanical Parts
  • Audio

Orders

  • Track your order
  • Help & support
  • Shipping and delivery
  • Refunds and cancellation
  • Contact us

Learn

  • Projects
  • Geeko AI project assistant
  • Learning paths
  • Guides
  • Calculators
  • Electrolark: free guided builds

Part tools

  • Part finder
  • Compare parts
  • Will it work with my board?

Institutions

  • Classroom kits
  • Atal Tinkering Lab
  • Students & teachers
  • Workshops & Events

Business

  • Business & education
  • Request a quotation
  • BOM bulk upload
  • Quick order by SKU

Company

  • About Geekobot
  • Community
  • Gift cards
  • Terms & conditions
  • Privacy policy
  • Product directory
  • Sitemap

© 2026 Geekobot, a trade name of OLatus Systems Private Limited. All rights reserved.

20, 1st Floor, Neeladri Complex, 10th Cross, Sampige Rd, 2nd Main, Malleshwaram, Bengaluru, Karnataka 560003 · GSTIN 29AACCO0462F1ZM

+91 91810 15607 · connect@geekobot.in · Monday to Saturday, 10 AM to 2 PM IST

UPI · CARDS · NETBANKING · GST INVOICES

ShopProjectsGeeko AIGuides
Compare 0 parts →
Log in

Shop by category

Shop all components
  • Boards & SBCs1,910 products
    • Alternative Single Board Computers
    • Arduino Ecosystem
    • FPGA & Logic Boards
    • Microcontroller & Wireless Boards
    View all
  • Sensors & Modules4,701 products
    • Biomedical & Heart Rate
    • Current, Voltage & Power
    • Force, Weight & Pressure
    • Gas, Weather & Environmental
    View all
  • IoT & Wireless2,314 products
    • RF Modules
    • RFID & NFC
    • Antennas & RF Accessories
    • Cameras & Smart Vision
    View all
  • Drone & FPV3,558 products
    • Flight Control & Navigation
    • FPV Video & Optics
    • Frames & Structural Parts
    • Motors & Propulsion
    View all
  • 3D Printing2,204 products
    • 3D Printers
    • 3D Scanners & Digitizers
    • Laser Engravers & Cutters
    • Material Management & Upgrades
    View all
  • Filaments & Resins1,472 products
    • Filaments
    • Photopolymer Resins
    View all
  • Motors & Drivers463 products
    • BLDC Motor Drivers
    • DC & Geared Motors
    • DC Motor Drivers
    • Linear Actuators & Solenoids
    View all
  • Power & Batteries557 products
    • Battery Holders & Connectors
    • Breadboard Power
    • Chargers & BMS
    • DC-DC Converters
    View all
  • Semiconductors295 products
    • Diodes & Rectifiers
    • Interface & RF Encoder ICs
    • Logic ICs (74xx)
    • Logic ICs (CD4000)
    View all
  • Passive67 products
    • Capacitors
    • Circuit Protection
    • Crystals & Oscillators
    • Inductors
    View all
  • Displays & LEDs572 products
    • 7-Segment & Dot Matrix
    • Addressable LEDs
    • Character LCDs
    • Graphic LCDs
    View all
  • Switches & Relays184 products
    • Keypads & Touch
    • Push Buttons & Tactile
    • Relay Modules
    • Relays
    View all
  • Wires & Cables233 products
    • Board-to-Wire Connectors
    • Crimp & Splice
    • Headers & Dupont
    • Heat Shrink & Sleeving
    View all
  • Prototyping101 products
    • Breadboards
    • Interface Modules
    • PCBs & Perfboards
    View all
  • Tools & Test717 products
    • Bench Power Supplies
    • Hand Tools
    • Measuring Tools
    • Meters & Testers
    View all
  • Robotics180 products
    • Humanoid & Legged Robots
    • Robot Chassis & Platforms
    • Robotic Arms & Grippers
    • Wheels & Casters
    View all
  • STEM Kits268 products
    • Arduino Learning Kits
    • Coding & IoT Kits
    • Early Coding (Ages 3-8)
    • Invention Kits
    View all
  • Atal Tinkering Lab196 products
    • Package 1: Electronics, Robotics, IoT and Sensors
    • Package 2: Rapid Prototyping Tools
    • Package 3: Mechanical, Electrical and Measurement Tools
    • Package 4: Power Supply, Accessories and Safety Equipment
    View all
  • Mechanical Parts212 products
    • Bearings
    • Brackets & Mounts
    • Couplers
    • Fasteners & Standoffs
    View all
  • Audio109 products
    • Amplifier Modules
    • Buzzers & Sirens
    • Speakers
    View all
  1. Home
  2. ›Guides
  3. ›IoT & Wireless
  4. ›MQTT and Home Assistant for ESP32
Step 8 of 16 in ESP32 and IoTPart of a learning path.
Next

Concept explainer · Intermediate · 3 min read

MQTT and Home Assistant for ESP32

Send Sensor Data and Control Relays

By Geekobot Learning Team · Updated 24 Oct 2026

On this page
Short answerMQTT in five ideasSetting up Home Assistant and MosquittoESP32 code: publish temperature, control a relayMake entities appear automatically: MQTT discoveryMQTT or ESPHome?Common mistakesFAQsParts and next steps
Short answer

MQTT is a lightweight messaging system: devices publish messages to named topics on a broker, and anything subscribed to that topic receives them. For a smart home, run the Mosquitto broker on Home Assistant, have your ESP32 publish sensor readings (for example home/livingroom/temperature) and subscribe to a command topic to switch a relay. MQTT discovery messages make the entities appear in Home Assistant automatically. ESPHome is a no-code alternative.

Key specs at a glance

Pattern
Publish / subscribe through a broker
Broker
Mosquitto (Home Assistant add-on or any Linux box)
Port
1883 (plain), 8883 (TLS)
QoS
0 at most once, 1 at least once, 2 exactly once
Library
PubSubClient or AsyncMqttClient on ESP32
Alternative
ESPHome with its native Home Assistant API
01

MQTT in five ideas

  1. 1
    Broker: a server that receives every message and passes it on. Devices never talk directly.
  2. 2
    Topics: text paths such as home/garden/soil or home/pump/set. Use + for one level and # for all levels when subscribing.
  3. 3
    Publish: send a message to a topic.
  4. 4
    Subscribe: ask the broker for every message on a topic.
  5. 5
    Retained messages and last will: a retained message is kept for new subscribers (good for the last known state); a last-will message is published by the broker if a device drops off (good for 'offline' status).
02

Setting up Home Assistant and Mosquitto

  1. 1
    In Home Assistant, install the Mosquitto broker add-on (Settings, Add-ons) and start it.
  2. 2
    Create a Home Assistant user for your devices (for example mqtt_esp) and use its username and password in the ESP32 code.
  3. 3
    Add the MQTT integration (Settings, Devices and services); it usually finds the broker automatically.
  4. 4
    Use MQTT Explorer or the integration's 'Listen to a topic' tool to watch messages while testing.

Home Assistant itself can run on a Raspberry Pi, a mini PC or a virtual machine.

03

ESP32 code: publish temperature, control a relay

Install PubSubClient by Nick O'Leary. The example publishes a value every 30 seconds and switches a relay on GPIO 26 when Home Assistant sends ON or OFF.

ESP32 MQTT sensor and relay · Arduino C++Verify & upload in Electrolark
#include <WiFi.h>
#include <PubSubClient.h>

const char* WIFI_SSID = "your-wifi";
const char* WIFI_PASS = "your-password";
const char* MQTT_HOST = "192.168.1.10";   // Home Assistant IP
const char* MQTT_USER = "mqtt_esp";
const char* MQTT_PASS = "secret";
const int RELAY = 26;

WiFiClient net;
PubSubClient mqtt(net);
unsigned long lastSend = 0;

void onMessage(char* topic, byte* payload, unsigned int len) {
  String msg;
  for (unsigned int i = 0; i < len; i++) msg += (char)payload[i];
  if (String(topic) == "home/pump/set") {
    digitalWrite(RELAY, msg == "ON" ? HIGH : LOW);
    mqtt.publish("home/pump/state", msg.c_str(), true);   // retained state
  }
}

void connectMqtt() {
  while (!mqtt.connected()) {
    if (mqtt.connect("esp32-pump", MQTT_USER, MQTT_PASS,
                     "home/pump/status", 0, true, "offline")) {
      mqtt.publish("home/pump/status", "online", true);
      mqtt.subscribe("home/pump/set");
    } else {
      delay(2000);
    }
  }
}

void setup() {
  pinMode(RELAY, OUTPUT);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  mqtt.setServer(MQTT_HOST, 1883);
  mqtt.setCallback(onMessage);
}

void loop() {
  if (!mqtt.connected()) connectMqtt();
  mqtt.loop();
  if (millis() - lastSend > 30000) {
    lastSend = millis();
    float temp = 27.4;   // replace with your sensor reading
    mqtt.publish("home/pump/temperature", String(temp, 1).c_str());
  }
}
04

Make entities appear automatically: MQTT discovery

Home Assistant listens on homeassistant/<component>/<object_id>/config. Publish a retained JSON config once at start-up and the entity appears with no YAML. For the temperature above, publish to homeassistant/sensor/esp32pump_temp/config:

{"name":"Pump temperature","state_topic":"home/pump/temperature","unit_of_measurement":"°C","device_class":"temperature","unique_id":"esp32pump_temp"}

For the relay, use the switch component with command_topic home/pump/set and state_topic home/pump/state. PubSubClient's default packet size is 256 bytes, so call mqtt.setBufferSize(512) before sending long config messages.

05

MQTT or ESPHome?

ESPHome lets you describe sensors and relays in a short YAML file, builds the firmware for you, and connects to Home Assistant through its own native API (MQTT optional). It is faster for standard sensors and supports over-the-air updates. Write your own MQTT code when you need custom logic, non-Home Assistant brokers, or devices that also talk to other systems such as Node-RED or a cloud service.

06

Common mistakes to avoid

  • !Hard-coding a blocking reconnect loop that stops the rest of the code forever.
  • !Forgetting mqtt.loop(), so incoming messages never arrive.
  • !Publishing state without the retain flag, so Home Assistant shows 'unknown' after a restart.
  • !Using the same client ID on two devices; they keep kicking each other off.
  • !Leaving the broker open with no username and password.
07

Frequently asked questions

What is MQTT used for?

Sending small messages between devices through a central broker. It is the standard way for DIY sensors and switches to talk to Home Assistant, Node-RED and many IoT platforms.

Do I need a broker for MQTT?

Yes. Devices only talk to the broker. Mosquitto is the usual choice and runs as a Home Assistant add-on.

What port does MQTT use?

1883 for plain connections and 8883 for TLS-encrypted connections.

Is ESPHome better than writing MQTT code?

For standard sensors and relays with Home Assistant, ESPHome is quicker. Custom MQTT code gives more control and works with any broker or platform.

What is MQTT QoS?

Quality of service: 0 sends once with no confirmation, 1 guarantees delivery at least once, 2 exactly once. QoS 0 or 1 suits most home sensors.

Parts for this guide

  • 5V Relay Module with Optocoupler
    ₹74View
Shop ESP32 & Wireless BoardsShop Relay Modules

Terms in this guide

MQTTMessage Queuing Telemetry Transport: a lightweight publish/subscribe messaging protocol where devices send and receive messages on named topics through a broker.Deep sleepA low-power mode where most of a microcontroller is switched off, cutting current to microamps between tasks.RelayAn electrically operated switch: a coil moves contacts that switch a separate circuit.GPIOGeneral-purpose input/output: a microcontroller pin that your code can read or drive.

Projects that use it

Put this into practice: 249 step-by-step builds in our project library use parts from this guide.

Beginner · 1–2 hoursWi-Fi weather station dashboardView projectIntermediate · 1–2 hoursWi-Fi plant monitor with pump controlView projectBeginner · 1–2 hoursWi-Fi room occupancy sensorView project
Browse all 249 projects

Keep learning

Component guideBeginnerESP32 GuideThe ESP32 is a low-cost 3.3 V microcontroller from Espressif with built-in Wi-Fi and Bluetooth, used for IoT devices, smart-home controllers and web dashboards.5 min read · Boards & MicrocontrollersComponent guideBeginnerRelay ModulesA relay module is an electrically controlled switch that lets a microcontroller turn a separate circuit on or off, such as a 12 V pump or a mains lamp.4 min read · Switches, Relays & InputComparisonBeginnerDHT11 vs DHT22DHT11 vs DHT22 compared: accuracy, range and sampling rate, plus wiring, pull-up, Arduino/ESP32 code and when to pick a BME280 or SHT31.3 min read · SensorsComparisonBeginnerWi-Fi vs Bluetooth vs LoRa vs ZigbeeCompare Wi-Fi, BLE, Bluetooth Classic, ESP-NOW, nRF24L01, 433 MHz, LoRa, Zigbee and 4G for projects by range, data rate, power and typical hardware.4 min read · IoT & Wireless

Sources

  • OASIS MQTT 3.1.1 and 5.0 specifications
  • Home Assistant MQTT integration and discovery documentation
  • PubSubClient library documentation
  • ESPHome documentation

Written by the Geekobot team from manufacturer datasheets. Always check the datasheet for the exact part and variant you buy.

On this page
Short answerMQTT in five ideasSetting up Home Assistant and MosquittoESP32 code: publish temperature, control a relayMake entities appear automatically: MQTT discoveryMQTT or ESPHome?Common mistakesFAQsParts and next steps
Need a hand?Ask Geeko AI which part fits your project, or talk to the Geekobot team.Ask Geeko AIHelp & support

Parts for this guide1 item · ₹74

5V Relay Module with Optocoupler

Run itChange the inputs and watch the output

This sketch prints nothing, so the panel shows the MQTT messages it sends and receives.

Relay (GPIO 26) OFF
Serial monitor115200 baud
publish home/pump/status = online (retained)
subscribe home/pump/set

A simulation of the sketch above, so you know what to expect. Real readings vary with your parts and wiring.

Ask the Community

Ask a question