Building Your Own Smart Thermostat Using ESP32 and MQTT
11.12.2024 - Engine: Gemini

Building a Smart Thermostat with ESP32 and MQTT
Components:
- ESP32 Microcontroller
- Temperature Sensor (e.g. DHT22)
- Relay (for switching the heating/cooling device)
- MQTT Broker
Setup:
-
Hardware Connection:
- Connect the temperature sensor to the ESP32.
- Connect the relay to the ESP32 and the heating/cooling device.
-
Software Installation:
- Install Arduino IDE.
- Install ESP32 libraries.
- Install MQTT library.
Code:
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// MQTT Broker details
const char* mqttServer = "broker.mqtt-dashboard.com";
uint16_t mqttPort = 1883;
// Temperature sensor details
#define DHTPIN 5
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// Relay details
const int relayPin = 2;
// Global variables
bool heating = false;
float desiredTemp = 20.0;
// MQTT client
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// Connect to WiFi
WiFi.begin("Network Name", "Password");
while (WiFi.status() != WL_CONNECTED) { delay(500); }
// Connect to MQTT client
client.setServer(mqttServer, mqttPort);
while (!client.connected()) { client.connect("Thermostat"); }
// Initialize temperature sensor
dht.begin();
// Set relay pin as output
pinMode(relayPin, OUTPUT);
}
void loop() {
// Keep client alive
client.loop();
// Read temperature
float temp = dht.readTemperature();
// Publish temperature over MQTT
client.publish("thermostat/temp", String(temp).c_str());
// Compare temperature with desired temperature
if (temp < desiredTemp - 0.5) {
// Heat
digitalWrite(relayPin, HIGH);
heating = true;
} else if (temp > desiredTemp + 0.5) {
// Cool
digitalWrite(relayPin, LOW);
heating = false;
}
// Publish heating status over MQTT
client.publish("thermostat/heating", heating ? "true" : "false");
}
How it Works:
- The ESP32 connects to the WiFi and MQTT broker.
- The temperature sensor reads the room temperature and publishes it over MQTT.
- The ESP32 compares the sensed temperature with the desired temperature.
- If the temperature is below the desired temperature, the heating device is turned on.
- If the temperature is above the desired temperature, the heating device is turned off.
- The heating status is published over MQTT.