Connect your existing project to MakerHex
Published:
You already have a working ESP32 project: you read a sensor and print the value to the Serial Monitor. In this guide we connect it to MakerHex without rewriting it. You will:
- Create the device in the dashboard.
- Install one library.
- Paste the ready-made MakerHex block at the top of your code.
- Add one line to
setup()and one line toloop(). - Send the values you want with one line.
If you have never tried MakerHex, we suggest starting with Device and connection test; everything there is explained line by line.
This guide is for the ESP32. For the ESP8266, Raspberry Pi or other boards, use Write MakerHex code with AI.
Example project: before
We use this simple project throughout the guide. It reads temperature and humidity from a DHT22 sensor and prints them:
#include <DHT.h>
DHT dht(4, DHT22); // sensor on pin 4
void setup() {
Serial.begin(115200);
dht.begin();
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
Serial.println(temperature);
Serial.println(humidity);
delay(2000);
}
Your project may be different; the steps are the same.
1. Create the device in the dashboard
- Devices → Add a device. Give it a name and tag (for example
Room,room1), Device type:Other, MQTT identity:Generate automatically (recommended). - Add a variable for every value you want to send. Keep the MQTT Topic short, lowercase and without spaces:
| Variable name | MQTT Topic | Writable? |
|---|---|---|
| Temperature | temperature |
No |
| Humidity | humidity |
No |
- After Create device, note the user name, password and Topic prefix shown in the dialog.
2. Install the library
In the Arduino IDE, open Tools → Manage Libraries and install PubSubClient (Nick O'Leary). Nothing else is needed; the Wi-Fi and encrypted-connection libraries come with the ESP32 package.
3. Paste the MakerHex block at the top
Paste the whole block below at the top of your code, under your own #include lines. Only change the five lines under "Your details". You do not need to touch the rest.
// ================= MakerHex block: START =================
// MakerHex must not be used to control life-critical or safety-critical systems.
#include <WiFi.h> // connect to a Wi-Fi network
#include <WiFiClientSecure.h> // encrypted connection
#include <PubSubClient.h> // send and receive MQTT messages
#include <time.h> // get the time from the internet
// ----- Your details: change only these five lines -----
const char* WIFI_NAME = "YOUR_WIFI"; // Wi-Fi network name
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD"; // Wi-Fi password
const char* MQTT_USER = "d_room1_xxxxxx"; // "user name" from the dashboard
const char* MQTT_PASSWORD = "PASSWORD_FROM_DASHBOARD"; // "password" from the dashboard
const char* PREFIX = "your-workspace/room1"; // "Topic prefix" from the dashboard
// Public certificate that verifies the MakerHex server. Not secret; copy it as is.
const char* MAKERHEX_CERTIFICATE = R"PEM(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn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DAzBPMQsw
CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg
R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00
MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT
ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw
EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW
+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9
ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T
AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI
zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW
tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1
/q4AaOeMSQ+2b1tbFfLn
-----END CERTIFICATE-----
)PEM";
WiFiClientSecure makerhexConnection; // encrypted internet connection
PubSubClient mqtt(makerhexConnection); // object that speaks MQTT over this connection
// Runs when a command arrives from the dashboard (defined at the end of the block).
void makerhexCommand(String name, String value);
// Reads the raw message from the dashboard and passes it to makerhexCommand.
void makerhexMessageArrived(char* topic, byte* data, unsigned int length) {
String value = "";
for (unsigned int i = 0; i < length; i++) value += (char)data[i]; // join the characters
String name = String(topic);
name = name.substring(name.lastIndexOf('/') + 1); // "your-workspace/room1/set/led" -> "led"
makerhexCommand(name, value);
}
// Connects to Wi-Fi and MakerHex; retries every 5 seconds until connected.
void makerhexConnect() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting to WiFi");
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
Serial.println(" done");
}
while (!mqtt.connected()) {
Serial.print("Connecting to MakerHex...");
if (mqtt.connect(MQTT_USER, MQTT_USER, MQTT_PASSWORD)) {
Serial.println(" done");
mqtt.subscribe((String(PREFIX) + "/set/#").c_str()); // listen for all commands from the dashboard
} else {
Serial.print(" failed, error code: ");
Serial.println(mqtt.state());
delay(5000);
}
}
}
// Call ONCE in setup(): sets up the connection and connects.
void makerhexSetup() {
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) delay(500);
configTime(0, 0, "pool.ntp.org"); // get the time for the certificate check
while (time(nullptr) < 1700000000) delay(500);
makerhexConnection.setCACert(MAKERHEX_CERTIFICATE); // verify the server with this certificate
mqtt.setServer("mqtt.makerhex.com", 8883); // MakerHex server, encrypted port
mqtt.setBufferSize(512); // enough room for JSON messages
mqtt.setCallback(makerhexMessageArrived); // run this function when a message arrives
makerhexConnect();
}
// Call on EVERY PASS of loop(): keeps the connection alive and reads incoming commands.
void makerhexLoop() {
if (WiFi.status() != WL_CONNECTED || !mqtt.connected()) makerhexConnect();
mqtt.loop();
}
// Sends a single value to its own topic. Example: makerhexSend("temperature", 24.6);
void makerhexSend(const char* name, float value) {
String topic = String(PREFIX) + "/" + name;
mqtt.publish(topic.c_str(), String(value).c_str());
}
// Sends several values in one message (JSON). Example: makerhexSendJson("{\"temperature\":24.6,\"humidity\":61}");
void makerhexSendJson(String json) {
String topic = String(PREFIX) + "/data";
mqtt.publish(topic.c_str(), json.c_str());
}
// Write here what should happen when a command arrives. Leave it empty if you don't receive commands.
// name: the variable's MQTT Topic (e.g. "led"), value: the value that arrived (e.g. "1")
void makerhexCommand(String name, String value) {
Serial.println("Command: " + name + " = " + value);
}
// ================= MakerHex block: END =================
4. Add one line each to setup() and loop()
At the end of setup(), add:
makerhexSetup(); // connect to Wi-Fi and MakerHex
At the very start of loop(), add:
makerhexLoop(); // keep the connection alive, read incoming commands
5. Remove delay(), use a timer
Many projects end loop() with a wait like delay(2000). A long delay() is a problem when connected to MakerHex: while the board waits it cannot keep the connection alive or hear commands from the dashboard. Every plan also has a message limit (on the Free plan, 1 message every 30 seconds per device).
So instead of delay() we use millis() to ask "have 30 seconds passed?":
const unsigned long WAIT = 30000; // 30 seconds (Maker: 5000, Trial / Pro / Ultimate: 1000)
unsigned long lastSend = 0; // when we last sent
void loop() {
makerhexLoop();
if (millis() - lastSend >= WAIT) { // 30 s since the last send?
lastSend = millis();
// ... read the sensor and send (below) ...
}
}
millis() returns the milliseconds since the board started. Subtracting the last send time from now tells us how much time has passed.
6. Send your data
There are two ways. Whichever you choose, the name you send must match the MQTT Topic in the dashboard.
Way A: one value
The easiest. One line for each value you want to send:
makerhexSend("temperature", temperature);
This sends a plain value such as 24.6 to the your-workspace/room1/temperature topic. Every line is a separate message. If you only send one value, this is all you need.
Way B: several values with JSON (recommended)
If you send two or more values, send them all in one message so you stay within the message limit. JSON is a way of writing values side by side:
{"temperature":24.6,"humidity":61.0}
- It starts and ends with curly braces.
- Each value's name is in double quotes, followed by a colon and the value.
- Values are separated by commas. Numbers are written without quotes.
In the code we build this text piece by piece. \" puts a double quote inside the code; String(temperature, 1) turns the number into text with 1 decimal place:
String json = "{\"temperature\":" + String(temperature, 1) + ",\"humidity\":" + String(humidity, 1) + "}";
makerhexSendJson(json);
This sends one message to the your-workspace/room1/data topic. MakerHex matches each name in the JSON with the variables in the dashboard and ignores names that are not defined there.
Example project: after
All together. Paste the whole block from step 3 where it says // ... MakerHex block ...:
#include <DHT.h>
// ... MakerHex block goes here ...
DHT dht(4, DHT22);
const unsigned long WAIT = 30000; // send every 30 seconds
unsigned long lastSend = 0;
void setup() {
Serial.begin(115200);
dht.begin();
makerhexSetup(); // NEW: connect to MakerHex
}
void loop() {
makerhexLoop(); // NEW: keep the connection alive
if (millis() - lastSend >= WAIT) {
lastSend = millis();
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) { // sensor could not be read? don't send
Serial.println("Sensor read failed");
return;
}
// NEW: send both values in one message
String json = "{\"temperature\":" + String(temperature, 1) + ",\"humidity\":" + String(humidity, 1) + "}";
makerhexSendJson(json);
Serial.println("Sent: " + json);
}
}
Receiving commands from the dashboard (optional)
To control an LED, relay or fan from the dashboard:
- Add a Writable variable to the device in the dashboard, for example LED with MQTT Topic
led. - Fill in the
makerhexCommandfunction at the end of the block:
void makerhexCommand(String name, String value) {
Serial.println("Command: " + name + " = " + value);
if (name == "led") { // is this command for the LED?
digitalWrite(2, value == "1" ? HIGH : LOW); // "1" turns it on, anything else off
}
}
- Add
pinMode(2, OUTPUT);tosetup().
When you send 1 to LED in the dashboard, the command arrives on your-workspace/room1/set/led; the block passes it to your function as name = "led", value = "1".
What do the block's functions do?
| Function | Where is it called? | What does it do? |
|---|---|---|
makerhexSetup() |
End of setup(), once |
Connects to Wi-Fi, gets the time, sets up the certificate and server, connects to MakerHex. |
makerhexLoop() |
Start of loop(), every pass |
Reconnects if the connection dropped; reads incoming commands with mqtt.loop() and keeps the connection alive. |
makerhexSend(name, value) |
Wherever you want to send | Sends one value to the {prefix}/{name} topic. |
makerhexSendJson(json) |
Wherever you want to send | Sends several values in one message to the {prefix}/data topic. |
makerhexCommand(name, value) |
By itself, when a command arrives | You fill it in: what should happen for which command. |
makerhexConnect() |
Called by the block | Retries every 5 seconds until connected; once connected it subscribes to {prefix}/set/# (# means "everything below"). |
makerhexMessageArrived(...) |
Called by the block | Turns the incoming message into text and takes the last part of the topic (led) as the name. |
Commands used inside the block, such as WiFi.begin, mqtt.connect, mqtt.subscribe, mqtt.publish and mqtt.loop, are explained one by one in the "What do the commands in the code do?" table on the Device and connection test page.
Common mistakes
- Leaving a long
delay()inloop(). Commands are delayed and the connection may drop. Use amillis()timer. - Sending too often. Messages sent more often than your plan allows are rejected; if this keeps happening the device's MQTT access is turned off. See Message rate and size limits.
- Sending every value separately. Sending three values with
makerhexSendis three messages. Use JSON for two or more values. - Name mismatch. The name in the code (
"temperature") must match the MQTT Topic in the dashboard.tempandtemperatureare different names; use lowercase letters, no spaces or accented letters. - Sending a failed reading. If the sensor cannot be read, check with
isnan(...)and skip that turn.
MakerHex must not be used to control life-critical or safety-critical systems.
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.
- 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.
- Message rate and size limitsHow often can your device send data, what happens over the limit, and how do you turn MQTT access back on? Limits per plan and how to code for them.
Try it with your own device: start free, 14 days of Pro features included, no credit card.
Start free