Skip to content

MQTT User Password example

Rotzbua edited this page Mar 12, 2024 · 2 revisions

This is an example code which was tested on an ESP32, which connects to a MQTT-Broker with user and password.

#include <WiFi.h>
#include <MQTT.h>

WiFiClient net;
MQTTClient client;

unsigned long lastMillis = 0;


//Wifi config
const char ssid[] = "SSID";
const char pass[] = "password"; //The SSID and password of your Wifi network

//MQTT-Broker config
const char mqttClientId[] = "arduino"; //The MQTT Client ID
const char mqttUsername[] = "user";
const char mqttPassword[] = "password"; //Username and password for your MQTT-Broker



void connect() { //Cobnn
  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect(mqttClientId, mqttUsername, mqttPassword)) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");

  client.subscribe("for/example"); //subscribe to a topic

}

void messageReceived(String &topic, String &payload) {
//react on MQTT commands with acording functions
 
Serial.println("incoming: " + topic + " - " + payload);

}
  
void setup() {
  // put your setup code here, to run once:

  WiFi.begin(ssid, pass);

  client.begin("0.0.0.0", net); //put the IP-Adress of your broker here
  client.onMessage(messageReceived);

  connect();
  delay(5000);
}

void loop() {
  client.loop();
  if (!client.connected()) {
    connect();
  }
  client.publish("topic/to/publish/to", "payload"); //topic an payload to publish
}