ESP32 MQTT - Send data

To be able to receive data from an ESP32, I have prepared an MQTT broker as a Docker container. The container can be integrated into Home-Assistant and thus forward the data from the ESP32 to Home-Assistant via MQTT. On the part of ESP32, I tested sending with the following sketch and later integrated the relevant parts into another sketch.

MQTT - ESP32 - WiFi


const char* ssid = "home";
const char* password = "???";
const char* mqttServer = "";
const int mqttPort = 1883;
const char* mqttUser = "mqtt";
const char* mqttPassword = "???";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Connecting to WiFi..");
  Serial.println("Connected to the WiFi network");
  client.setServer(mqttServer, mqttPort);
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
    if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
    } else {
      Serial.print("failed with state ");
  client.publish("esp32/test", "Hello from ESP32");

void loop() {


When using the Eclipse-Mosquitto MQTT Docker image, the connection setup can be examined in the logs, see: MQTT Viewing Connections: Logs

positive Bewertung({{pro_count}})
Rate Post:
{{percentage}} % positive
negative Bewertung({{con_count}})

THANK YOU for your review!

Publication: 2022-11-04 from Bernhard 🔔

Top articles in this section

ESP32 Flowmeter - RS485 Modbus
As described in the first article of this series, my first goal was to read out a TUF-2000M Ultrasonic Flow Meter via an ESP32. For this purpose I found an example for an ESP8266 on the internet: Reading a TUF-2000M Ultrasonic Flow Meter with an Arduino or ESP8266 and I described the setup of the TUF-2000M in the following article: Field Report: Ultrasonic Flow Meter TUF-2000M. To be able to read the TUF-2000M via RS485, it must first be c...

ESP32 WiFi example
In preparation for uploading sketches to a microcontroller, I installed the ESP32 board infromations and a USB to UART Bridge driver, see: Preparations for Programming an ESP32.

DS18B20 Temperature Sensors ESP32, MQTT and WiFi - HowTo
In addition to connecting a flow meter via RS485, I plugged 5-piece DS18B20 temperature sensors to the ESP32 so that their values are also transmitted to HomeAssistant via MQTT.

Questions / Comments