> For the complete documentation index, see [llms.txt](https://docs.heisenware.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.heisenware.com/tutorials/integration-guides/connect-from-arduino-via-mqtt.md).

# Connect from Arduino via MQTT

Use this code snippet to send data from an Arduino (ESP32) device to your Heisenware account.

{% hint style="info" %}

#### Create integration credentials first

Because an external device must publish data directly to the Heisenware broker, you must generate client credentials first. Add an MQTT integration in the **App Manager** (see [Integrations (inbound)](/app-manager/inbound-integrations.md#connecting-mqtt-and-vrpc-clients)).
{% endhint %}

Replace the capitalized placeholder variables in the code below with your specific configuration details. For an account named `acme` with no custom workspaces, the `ACCOUNT` value is `acme` and the `DOMAIN` value is `acme.default`.

```cpp
// Use <ESP8266WiFi.h> for ESP8266

#include <WiFi.h> 
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h> // <-- ADDED for JSON

// 1. WiFi Configuration
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

// 2. MQTT Configuration
const char* mqtt_server = "ACCOUNT.heisenware.cloud";
const int mqtt_port = 8884;
const char* mqtt_user = "YOUR_HW_MQTT_USERNAME";
const char* mqtt_pass = "YOUR_HW_MQTT_PASSWORD";
const char* mqtt_topic = "DOMAIN/arduino";

// 3. Timer for publishing
unsigned long lastMsgTime = 0;
const long msgInterval = 5000; // Publish every 5 seconds (5000 ms)

// 4. Instantiate clients
WiFiClientSecure espClient;
PubSubClient client(espClient);

// Callback function for subscribed topics
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void setup() {
  Serial.begin(115200);
  delay(10);

  // Seed the random number generator
  randomSeed(analogRead(A0)); 

  // Connect to WiFi
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  
  // 5. CRITICAL: Disable certificate validation (INSECURE)
  Serial.println("WARNING: Disabling SSL certificate validation!");
  espClient.setInsecure(); 
  
  // 6. Set the MQTT server, custom port, and callback
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    
    const char* clientID = "MyESP32-JSONPublisher";

    // 7. Connect using username and password
    if (client.connect(clientID, mqtt_user, mqtt_pass)) {
      Serial.println("connected");
      
      // Subscribe to your topic
      client.subscribe(mqtt_topic);
      Serial.print("Subscribed to: ");
      Serial.println(mqtt_topic);
      
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000); 
    }
  }
}

// 8. Function to publish the JSON message
void publishRandomValue() {
  // Generate a random integer
  int randomValue = random(0, 100); // Random number between 0 and 99

  // Create a JSON document.
  // Size 64 is small but sufficient for {"value": 100}
  StaticJsonDocument<64> doc;
  doc["value"] = randomValue;

  // Serialize JSON to a char buffer
  char buffer[64];
  size_t n = serializeJson(doc, buffer);

  // Publish the message
  Serial.print("Publishing JSON: ");
  Serial.println(buffer);
  
  if (client.publish(mqtt_topic, buffer, n)) {
    Serial.println("Publish OK");
  } else {
    Serial.println("Publish failed");
  }
}

void loop() {
  // 1. Ensure connection is active
  if (!client.connected()) {
    reconnect();
  }
  // 2. Allow the MQTT client to process messages
  client.loop();

  // 3. Handle non-blocking publishing
  unsigned long now = millis();
  if (now - lastMsgTime > msgInterval) {
    lastMsgTime = now;
    
    // Call the function to build and send the message
    publishRandomValue();
  }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.heisenware.com/tutorials/integration-guides/connect-from-arduino-via-mqtt.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
