All examples

ESP32 MQTT connection test (the simplest example)

Published:

This example is for people trying MakerHex for the first time. It has one goal: to see with your own eyes that your board is connected to MakerHex. You do not even need a sensor.

The board will do two things:

  1. Send data (publish): It sends three values in turn: a counter, the Wi-Fi signal strength and how many seconds the board has been running. Each value goes on its own, with a single command.
  2. Receive data (subscribe): When you send 1 from the dashboard, the LED on the board turns on; 0 turns it off.

It takes about 15 minutes.

A few words first

Word Meaning
MQTT The language (protocol) devices use to exchange short messages over the internet.
Server (broker) The switchboard that receives messages and passes them on. MakerHex's is at mqtt.makerhex.com.
Topic The address a message is sent to. Written like a folder path: school/test1/counter
Topic prefix The start of your device's own address. The dashboard gives it to you (for example school/test1). Your device can only write under it.
Publish Send a message to a topic.
Subscribe Listen to a topic and get notified when a message arrives on it.

What you need

  • An ESP32 development board (ESP32 DevKit or similar) and a USB cable
  • Arduino IDE 2.x
  • A 2.4 GHz Wi-Fi network (the ESP32 cannot join 5 GHz networks)
  • A MakerHex account (create your free account)

Nothing else. Most ESP32 boards have a small LED connected to pin 2; we will use that.

1. Create the device in the dashboard

  1. In the dashboard go to Devices → Add a device.
  2. Device name: Test 1, Tag: test1, Device type: Other.
  3. MQTT identity: Generate automatically (recommended).
  4. Under Variables, use Add variable to add four variables:
Variable name MQTT Topic Writable?
Counter counter No
Signal strength signal No
Uptime uptime No
LED led Yes
  1. Click Create device. The dialog shows the user name, password and Topic prefix. Note them down; they go into the code.

The MQTT Topic column matters: it must match the topic names in the code letter for letter.

2. Prepare the Arduino IDE

  1. In Tools → Board → Boards Manager, install the esp32 package (Espressif Systems).
  2. In Tools → Manage Libraries, install PubSubClient (Nick O'Leary).

What is a library? A ready-made code package that someone else wrote and shared. PubSubClient sends and receives MQTT messages for us. WiFi and WiFiClientSecure come with the ESP32 package; you do not install them separately.

3. The code

Paste the code into a new sketch. Only change the five lines in section 2 to your own details.

// =================================================================
// MakerHex - Device and connection test (ESP32)
// No sensor needed. The board sends three values to MakerHex in turn
// and switches its LED on and off when a command arrives.
// MakerHex must not be used to control life-critical or
// safety-critical systems.
// =================================================================

// ----- 1) Libraries: ready-made code packages we use -----
#include <WiFi.h>              // connect to a Wi-Fi network
#include <WiFiClientSecure.h>  // make an encrypted (secure) connection
#include <PubSubClient.h>      // send and receive MQTT messages
#include <time.h>              // get the time from the internet

// ----- 2) 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_test1_xxxxxx";           // "user name" from the dashboard
const char* MQTT_PASSWORD = "PASSWORD_FROM_DASHBOARD";  // "password" from the dashboard
const char* PREFIX        = "your-workspace/test1";     // "Topic prefix" from the dashboard

// ----- 3) Fixed settings: no need to change these -----
const char* SERVER = "mqtt.makerhex.com";  // MakerHex MQTT server
const int PORT = 8883;                     // port number for encrypted connections
const int LED_PIN = 2;                     // pin of the LED on the board
const unsigned long WAIT = 30000;          // time between sends: 30000 ms = 30 seconds

// Certificate that proves the server really is MakerHex.
// It is not secret and is the same for everyone. Copy it as is; do not change a single character.
const char* CERTIFICATE = R"PEM(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/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Bo1BfASdW
tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1
/q4AaOeMSQ+2b1tbFfLn
-----END CERTIFICATE-----
)PEM";

// ----- 4) Objects and variables used throughout the program -----
WiFiClientSecure secureConnection;    // encrypted internet connection
PubSubClient mqtt(secureConnection);  // object that speaks MQTT over this connection

unsigned long lastSend = 0;  // when we last sent something (milliseconds)
int counter = 0;             // a number that goes up by 1 on every send
int turn = 0;                // which value to send this time: 0, 1 or 2

// ----- 5) Runs by itself when a message arrives from the dashboard -----
// topic: address of the message, data: its content, length: how many characters
void messageArrived(char* topic, byte* data, unsigned int length) {
  // The message arrives character by character. Join them into one piece of text (String).
  String value = "";
  for (unsigned int i = 0; i < length; i++) {
    value += (char)data[i];
  }

  Serial.print("Message from dashboard: ");
  Serial.print(topic);
  Serial.print(" = ");
  Serial.println(value);

  // If the value is "1" (or "true") turn the LED on, otherwise turn it off.
  if (value == "1" || value == "true") {
    digitalWrite(LED_PIN, HIGH);
    Serial.println("LED on");
  } else {
    digitalWrite(LED_PIN, LOW);
    Serial.println("LED off");
  }
}

// ----- 6) Function that connects to Wi-Fi -----
void connectWiFi() {
  Serial.print("Connecting to WiFi");
  WiFi.begin(WIFI_NAME, WIFI_PASSWORD);    // start connecting
  while (WiFi.status() != WL_CONNECTED) {  // wait until connected
    delay(500);                            // wait half a second
    Serial.print(".");                     // print a dot while waiting
  }
  Serial.println(" done");
}

// ----- 7) Function that connects to MakerHex (the MQTT server) -----
void connectMakerHex() {
  while (!mqtt.connected()) {  // keep trying while not connected
    Serial.print("Connecting to MakerHex...");

    // connect(client ID, user name, password). We use the user name as the client ID.
    if (mqtt.connect(MQTT_USER, MQTT_USER, MQTT_PASSWORD)) {
      Serial.println(" done");

      // Subscribe to the topic LED commands arrive on, e.g. "your-workspace/test1/set/led"
      String ledTopic = String(PREFIX) + "/set/led";
      mqtt.subscribe(ledTopic.c_str());
      Serial.println("Listening on: " + ledTopic);
    } else {
      Serial.print(" failed, error code: ");
      Serial.println(mqtt.state());  // a number that tells why it failed
      delay(5000);                   // wait 5 seconds, then try again
    }
  }
}

// ----- 8) setup(): runs ONCE when the board starts -----
void setup() {
  Serial.begin(115200);      // start talking to the Serial Monitor on the computer
  pinMode(LED_PIN, OUTPUT);  // make the LED pin an "output" (so it can supply power)

  connectWiFi();

  // The board's clock must be right so the certificate dates can be checked.
  // We get the time from a time server on the internet.
  Serial.print("Getting the time");
  configTime(0, 0, "pool.ntp.org");
  while (time(nullptr) < 1700000000) {  // wait until the time arrives
    delay(500);
    Serial.print(".");
  }
  Serial.println(" done");

  secureConnection.setCACert(CERTIFICATE);  // use this certificate for the encrypted connection
  mqtt.setServer(SERVER, PORT);             // tell it which server to connect to
  mqtt.setCallback(messageArrived);         // run "messageArrived" when a message comes in

  connectMakerHex();
}

// ----- 9) loop(): runs OVER AND OVER after setup -----
void loop() {
  // Reconnect if the connection dropped
  if (WiFi.status() != WL_CONNECTED) connectWiFi();
  if (!mqtt.connected()) connectMakerHex();

  // Checks for incoming messages and keeps the connection alive. Call it on every pass.
  mqtt.loop();

  // If 30 seconds have not passed since the last send, skip the rest of loop.
  // (We don't use delay; during a delay the board cannot hear messages from the dashboard.)
  if (millis() - lastSend < WAIT) return;
  lastSend = millis();  // remember now as the "last send" time

  // We send ONE value per turn: counter, then signal, then uptime.
  if (turn == 0) {
    counter = counter + 1;
    String topic = String(PREFIX) + "/counter";  // e.g. your-workspace/test1/counter
    String value = String(counter);              // turn the number into text: 5 -> "5"
    mqtt.publish(topic.c_str(), value.c_str());  // send it
    Serial.println("Sent: counter = " + value);
  } else if (turn == 1) {
    String topic = String(PREFIX) + "/signal";
    String value = String(WiFi.RSSI());          // Wi-Fi signal strength, e.g. -55
    mqtt.publish(topic.c_str(), value.c_str());
    Serial.println("Sent: signal = " + value);
  } else {
    String topic = String(PREFIX) + "/uptime";
    String value = String(millis() / 1000);      // seconds since the board started
    mqtt.publish(topic.c_str(), value.c_str());
    Serial.println("Sent: uptime = " + value);
  }

  // Next time, send the next value: 0 -> 1 -> 2 -> back to 0
  turn = turn + 1;
  if (turn > 2) turn = 0;
}

Select the board (Tools → Board), the port (Tools → Port) and click Upload. When it finishes, open Tools → Serial Monitor and choose 115200 baud at the bottom right. You should see lines like:

Connecting to WiFi..... done
Getting the time.. done
Connecting to MakerHex... done
Listening on: your-workspace/test1/set/led
Sent: counter = 1
Sent: signal = -58
Sent: uptime = 64

4. Check in the dashboard

  • In the dashboard open Devices → Test 1. Counter, Signal strength and Uptime update in turn, every 30 seconds.
  • In Writable variables, type 1 for LED and send it: the board's LED turns on and the Serial Monitor shows Message from dashboard. Send 0 to turn it off.

If you see this, your board is talking to MakerHex in both directions. Well done!

What do the commands in the code do?

Command What it does
#include <...> Adds a library to the code so we can use its commands.
const char* NAME = "..."; Defines a piece of text that will not change (a constant). We keep the Wi-Fi name, password and so on like this.
Serial.begin(115200) Starts talking to the computer over USB. 115200 is the speed; choose the same in the Serial Monitor.
Serial.print() / Serial.println() Writes text to the Serial Monitor. println moves to a new line afterwards.
pinMode(pin, OUTPUT) Makes a pin an output so it can power something like an LED.
digitalWrite(pin, HIGH / LOW) Turns power on an output pin on (HIGH) or off (LOW).
delay(ms) Makes the board wait for the given milliseconds. While waiting it cannot do anything else.
millis() Time since the board started, in milliseconds. We use it to measure time without waiting.
WiFi.begin(name, password) Starts connecting to a Wi-Fi network.
WiFi.status() Tells whether we are connected to Wi-Fi. It is WL_CONNECTED when connected.
WiFi.RSSI() Wi-Fi signal strength. -50 is very good, -70 is fair, -85 is weak.
configTime(...) / time(nullptr) Gets the time from the internet / returns the current time.
setCACert(certificate) Uses the certificate to check that the server really is MakerHex.
mqtt.setServer(address, port) Sets which MQTT server to connect to.
mqtt.setCallback(function) Sets which function runs when a message arrives. Ours is messageArrived.
mqtt.connect(id, user, password) Connects to MakerHex. Returns true on success.
mqtt.connected() Tells whether we are connected right now.
mqtt.state() If the connection failed, tells why with a number (see the table below).
mqtt.subscribe(topic) Subscribes to a topic; messages on it go to messageArrived.
mqtt.publish(topic, value) Sends a message to a topic. The value must be text; we turn numbers into text with String(...).
mqtt.loop() Checks incoming messages and keeps the connection alive. Call it on every pass of loop().
String(...) / .c_str() Turns a number into text / turns text into the form the MQTT commands expect.

Why only one value per turn?

Every publish is one message, and every MakerHex plan has a message limit: on the Free plan, 1 message every 30 seconds per device. If we sent all three values at once we would be at three times the limit and most messages would be rejected. So every 30 seconds we send just the next value.

If your plan allows faster sending (Maker 5 s, Trial / Pro / Ultimate 1 s), you can lower WAIT. Details: Message rate and size limits.

The way to send several values in one message is JSON; we explain it in Connect your existing project to MakerHex.

Troubleshooting

Symptom Likely cause and fix
Connecting to WiFi...... never ends Wrong Wi-Fi name or password, or the network is 5 GHz. The ESP32 only joins 2.4 GHz networks.
Getting the time...... never ends The network may not reach the internet. Try your phone's hotspot.
error code: -2 The server could not be reached or the certificate could not be verified. Check that the certificate block was copied completely.
error code: 4 or 5 Wrong user name or password. Check the MQTT connection details card on the device page; regenerate the password if needed.
Connected but no values in the dashboard PREFIX or the MQTT Topic names in the dashboard do not match the code (counter, signal, uptime).
The LED command arrives but the LED stays off Your board's LED may be on another pin. Change LED_PIN, or connect an LED with a 220 Ω resistor to pin 2.

What's next?

MakerHex must not be used to control life-critical or safety-critical systems. This example is for learning.

Related examples

Try it with your own device: start free, 14 days of Pro features included, no credit card.

Start free