Connect your first IoT device with an ESP32 and DHT11
Published: Updated:
In this example an ESP32 board reads temperature and humidity from a DHT11 or DHT22 sensor and sends them to MakerHex every 30 seconds. A command from the dashboard switches the board's LED on and off. It takes about 20 minutes.
Trying MakerHex for the first time? Start with Device and connection test: no sensor needed and every line is explained.
Video walkthrough (in Turkish): we build this example step by step in a two-part video. The latest code is on this page.
What you need
- An ESP32 development board (ESP32 DevKit or similar)
- A DHT11 or DHT22 temperature and humidity sensor (no sensor? see "No sensor?" below)
- DHT11 (blue): the most common and cheapest; 0–50 °C, ±2 °C, whole-number readings.
- DHT22 (white): more accurate; −40–80 °C, ±0.5 °C, decimal readings.
- Arduino IDE 2.x
- A MakerHex account (create your free account)
Wiring: Sensor data pin (DATA or S) → GPIO 4, VCC (+) → 3.3V, GND (−) → GND. 3-pin modules already have the required resistor on the board; with a bare 4-pin sensor, add a 10 kΩ resistor between data and VCC. For the LED we use the built-in LED found on most ESP32 boards (GPIO 2).
1. Create the device in the dashboard
- In the dashboard go to Devices → Add a device.
- Device name:
Greenhouse 1, Tag:greenhouse1, Device type:Other. - MQTT identity:
Generate automatically (recommended). - Under Variables, use Add variable to add three variables:
| Variable name | MQTT Topic | Writable? |
|---|---|---|
| Temperature | temperature |
No |
| Humidity | humidity |
No |
| LED | led |
Yes |
- Click Create device. The dialog shows the user name, password and Topic prefix (for example
your-workspace/greenhouse1). Note them down.
You can see these details later on the device page in the MQTT connection details card.
2. Prepare the Arduino IDE
- In the Boards Manager, install the
esp32package (Espressif Systems). - In the Library Manager, install:
PubSubClient(Nick O'Leary)DHT sensor library(Adafruit), together withAdafruit Unified Sensorwhen asked
3. The code
Paste the code below into a new sketch. Only change the seven lines at the top. If you use a DHT22, change DHT11 to DHT22 on the DHT_TYPE line.
// MakerHex must not be used to control life-critical or safety-critical systems.
// Libraries: ready-made code packages we use
#include <WiFi.h> // connect to a Wi-Fi network
#include <WiFiClientSecure.h> // encrypted (TLS) connection
#include <PubSubClient.h> // send and receive MQTT messages
#include <DHT.h> // read the DHT11 / DHT22 sensor
#include <time.h> // get the time from the internet
// ---- Change these ----
const char* WIFI_SSID = "YOUR_WIFI"; // Wi-Fi network name
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD"; // Wi-Fi password
const char* MQTT_USER = "d_greenhouse1_xxxxxx"; // user name from the dashboard
const char* MQTT_PASS = "PASSWORD_FROM_DASHBOARD"; // password from the dashboard
const char* TOPIC_PREFIX = "your-workspace/greenhouse1"; // Topic prefix from the dashboard
const unsigned long SEND_EVERY_MS = 30000; // send every 30 seconds (Free plan limit)
#define DHT_TYPE DHT11 // using a DHT22? change to DHT22
// ----------------------
const char* MQTT_HOST = "mqtt.makerhex.com"; // MakerHex MQTT server
const uint16_t MQTT_PORT = 8883; // encrypted connection port
// Let's Encrypt root certificates (ISRG Root X1 and X2).
// Not secret; used to verify the identity of the MakerHex server.
const char* ROOT_CA = R"PEM(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIR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// pin the sensor's data leg is connected to
#define LED_PIN 2 // pin of the board's built-in LED
DHT dht(DHT_PIN, DHT_TYPE); // sensor object: which pin, which model
WiFiClientSecure net; // encrypted internet connection
PubSubClient mqtt(net); // object that speaks MQTT over this connection
String dataTopic; // {prefix}/data → readings as JSON
String ledSetTopic; // {prefix}/set/led → command from the dashboard
String ledStateTopic; // {prefix}/led → current LED state
unsigned long lastSend = 0; // when we last sent (milliseconds)
// Runs by itself when a message arrives from the dashboard.
void onMessage(char* topic, byte* payload, unsigned int length) {
// The message arrives byte by byte; join the bytes into one piece of text.
String value;
for (unsigned int i = 0; i < length; i++) value += (char)payload[i];
value.trim(); // remove spaces at the start and end
if (ledSetTopic == topic) { // is this an LED command?
// "1", "true" or "on" means the LED should turn on
bool on = value == "1" || value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on");
digitalWrite(LED_PIN, on ? HIGH : LOW); // switch the LED on or off
mqtt.publish(ledStateTopic.c_str(), on ? "1" : "0"); // report the new state to the dashboard
Serial.printf("LED %s\n", on ? "on" : "off");
}
}
// Connects to Wi-Fi; does nothing if already connected.
void connectWiFi() {
if (WiFi.status() == WL_CONNECTED) return;
Serial.print("Connecting to WiFi");
WiFi.mode(WIFI_STA); // act as a device that joins a Wi-Fi network
WiFi.begin(WIFI_SSID, WIFI_PASS); // start connecting
while (WiFi.status() != WL_CONNECTED) { // wait until connected
delay(500);
Serial.print(".");
}
Serial.println(" done");
}
// Get the time from the internet so the certificate dates can be checked.
void syncClock() {
configTime(0, 0, "pool.ntp.org", "time.google.com");
for (int i = 0; i < 20 && time(nullptr) < 1700000000; i++) delay(500); // wait up to 10 s
}
// Connects to MakerHex; if it fails, retries every 5 seconds.
void connectMqtt() {
while (!mqtt.connected()) {
connectWiFi();
Serial.print("Connecting to MakerHex...");
// A client ID unique to this board: user name + chip serial number
String clientId = String(MQTT_USER) + "-" + String((uint32_t)ESP.getEfuseMac(), HEX);
if (mqtt.connect(clientId.c_str(), MQTT_USER, MQTT_PASS)) {
Serial.println(" done");
mqtt.subscribe(ledSetTopic.c_str()); // start listening for LED commands
} else {
Serial.printf(" failed (code %d), retrying in 5 s\n", mqtt.state());
delay(5000);
}
}
}
// Runs ONCE when the board starts.
void setup() {
Serial.begin(115200); // start talking to the Serial Monitor
pinMode(LED_PIN, OUTPUT); // make the LED pin an output
dht.begin(); // start the sensor
// Build the topic addresses from the prefix, e.g. "your-workspace/greenhouse1/data"
dataTopic = String(TOPIC_PREFIX) + "/data";
ledSetTopic = String(TOPIC_PREFIX) + "/set/led";
ledStateTopic = String(TOPIC_PREFIX) + "/led";
connectWiFi();
syncClock();
net.setCACert(ROOT_CA); // verify the server with this certificate
mqtt.setServer(MQTT_HOST, MQTT_PORT); // which server to connect to
mqtt.setCallback(onMessage); // run onMessage when a message arrives
connectMqtt();
}
// Runs OVER AND OVER after setup.
void loop() {
if (!mqtt.connected()) connectMqtt(); // reconnect if the connection dropped
mqtt.loop(); // read incoming messages, keep the connection alive (every pass)
// Not enough time since the last send? Skip the rest of loop for now.
if (millis() - lastSend < SEND_EVERY_MS) return;
lastSend = millis();
float t = dht.readTemperature(); // read temperature (°C)
float h = dht.readHumidity(); // read humidity (%)
if (isnan(t) || isnan(h)) { // could not read (NaN)? don't send
Serial.println("Sensor read failed");
return;
}
// Send both values in one message: {"temperature":24.6,"humidity":61.0}
char json[64];
snprintf(json, sizeof(json), "{\"temperature\":%.1f,\"humidity\":%.1f}", t, h);
mqtt.publish(dataTopic.c_str(), json);
Serial.println(json);
}
Select your board, upload, and open the Serial Monitor at 115200 baud. You should see lines like:
Connecting to WiFi.... done
Connecting to MakerHex... done
{"temperature":24.6,"humidity":61.0}
4. Watch and control from the dashboard
- Open the device in the dashboard: Temperature and Humidity update every 30 seconds. If your plan allows it, you can lower
SEND_EVERY_MS(Maker: 5000, Trial / Pro / Ultimate: 1000). - In Writable variables, send
1to LED: the LED turns on. Send0to turn it off. - Add a gauge, chart or button widget to a dashboard and pick these variables to build your own screen.
How it works
- The device sends all readings in one JSON message to
{prefix}/data. Each JSON key (temperature,humidity) matches the MQTT Topic of a variable in the dashboard. - You can also send a single value to its own topic:
24.6to{prefix}/temperature. - Commands from the dashboard arrive on
{prefix}/set/{variable}as a plain value (1,0,true,falseor a number). - Every device has its own user name and password, and can only access topics under its own prefix.
Functions used in the code
| Function | What it does |
|---|---|
Serial.begin(115200) / Serial.println() |
Starts talking to the computer over USB / writes text to the Serial Monitor. |
pinMode() / digitalWrite() |
Makes a pin an output / switches power on that output on (HIGH) or off (LOW). |
dht.begin() / dht.readTemperature() / dht.readHumidity() |
Starts the sensor / reads temperature / reads humidity. Returns NaN if the reading fails; isnan() checks for that. |
WiFi.begin() / WiFi.status() |
Starts connecting to Wi-Fi / tells whether we are connected. |
configTime() / time() |
Gets the time from the internet / returns the current time. Needed for the certificate check. |
net.setCACert() |
Uses the certificate to verify that the server really is MakerHex. |
mqtt.setServer() / mqtt.setCallback() |
Sets the server to connect to / the function to run when a message arrives. |
mqtt.connect() / mqtt.connected() / mqtt.state() |
Connects to MakerHex / tells whether we are connected / gives a number explaining why a connection failed. |
mqtt.subscribe(topic) |
Subscribes to a topic; messages on it go to onMessage. |
mqtt.publish(topic, message) |
Sends a message to a topic. |
mqtt.loop() |
Reads incoming messages and keeps the connection alive. Call it on every pass of loop(). |
millis() |
Milliseconds since the board started. Lets you measure time without delay(). |
snprintf() |
Puts numbers into a text template; here it builds the JSON message. %.1f means "a number with 1 decimal place". |
For a slower, line-by-line walkthrough, see Device and connection test.
Troubleshooting
| Symptom | Likely cause |
|---|---|
failed (code -2) |
Network or certificate problem. Make sure the clock was synced and the ROOT_CA block was copied completely. |
failed (code 4) or failed (code 5) |
Wrong user name or password. Check the MQTT connection details card in the dashboard; regenerate the password if needed. |
| Connects but no values arrive | The Topic prefix or JSON keys do not match the dashboard. Variables that are not defined in the dashboard are silently ignored. |
Sensor read failed |
Check the sensor wiring, the pin number, and that the DHT_TYPE line matches your sensor. |
No sensor? Replace the dht.readTemperature() and dht.readHumidity() lines with float t = 20 + random(0, 100) / 10.0; and float h = 50 + random(0, 200) / 10.0; to send test data.
Adapt it to your own project with AI
If you want to use this example with other sensors or another board, you can have an AI assistant (ChatGPT, Claude, Gemini, Cursor) write the code. First describe your project in your own words, then paste the MakerHex system information text from Write MakerHex code with AI below it. The AI writes the code and tells you which device and variables to create in the dashboard.
If you have already created your device in the dashboard, the Generate code with AI button on the device page fills this text in for you with your device's name, topics and variables.
For this example, the project description could be:
I have an ESP32 DevKit V1 and a DHT22 (or DHT11) temperature and humidity sensor; the sensor's data pin is on GPIO 4.
I use the Arduino IDE. I want to send temperature and humidity to MakerHex every 30 seconds
and switch the board's built-in LED (GPIO 2) on and off from the dashboard. My plan is Free.
Do not give your password to the AI; enter it yourself after you get the code.
MakerHex must not be used to control life-critical or safety-critical systems. This example is for learning and monitoring.
Related examples
- ESP32 MQTT connection test (the simplest example)No sensor needed. Send values one by one from an ESP32 to MakerHex over MQTT and switch an LED from the dashboard. Every line explained for first-timers.
- Connect your existing project to MakerHexAlready have a working ESP32 project? Connect it to MakerHex with one library, a ready-made block and two lines. Send values or JSON, receive commands.
- Write ESP32 and Arduino code with AIDescribe your project to ChatGPT, Claude or Gemini and add the MakerHex system text. The AI writes the code and tells you what to set up in the dashboard.
Try it with your own device: start free, 14 days of Pro features included, no credit card.
Start free
