Set Up ESP32 MQTT Client for Sensor Data with LWIP and PubSubClient

Introduction

This tutorial will guide you through setting up an ESP32 as an MQTT client to transmit sensor data using the LWIP stack and the PubSubClient library. You will learn how to configure the ESP32, connect it to Wi-Fi, and publish sensor data to an MQTT broker.

Prerequisites

  • Basic understanding of electronics and programming
  • ESP32 development board
  • Arduino IDE installed
  • MQTT broker (e.g., Mosquitto or a cloud-based broker)
  • Sensors (e.g., DHT11 for temperature and humidity)
  • USB cable for connecting ESP32 to your computer

Parts/Tools

  • ESP32 Development Board
  • DHT11 or DHT22 Sensor
  • Jumper wires
  • Breadboard (optional)
  • Arduino IDE with ESP32 board support
  • PubSubClient library

Steps

  1. Install the ESP32 Board in Arduino IDE
    1. Open Arduino IDE, go to File > Preferences.
    2. In the Additional Board Manager URLs, add:
    3. https://dl.espressif.com/dl/package_esp32_index.json
    4. Go to Tools > Board > Board Manager.
    5. Search for “ESP32” and install the package.
  2. Install the PubSubClient Library
    1. Go to Sketch > Include Library > Manage Libraries.
    2. Search for “PubSubClient” and install it.
  3. Connect the Sensor to ESP32
    1. Connect the DHT11 sensor:
      • VCC to 3.3V
      • GND to GND
      • Data pin to GPIO 23 (or any other GPIO)
  4. Write the Code

    Open a new sketch in Arduino IDE and enter the following code:

    
    #include <WiFi.h>
    #include <PubSubClient.h>
    #include <DHT.h>
    
    #define DHTPIN 23
    #define DHTTYPE DHT11
    
    DHT dht(DHTPIN, DHTTYPE);
    const char* ssid = "YOUR_SSID";
    const char* password = "YOUR_PASSWORD";
    const char* mqtt_server = "YOUR_MQTT_BROKER";
    
    WiFiClient espClient;
    PubSubClient client(espClient);
    
    void setup() {
        Serial.begin(115200);
        dht.begin();
        setup_wifi();
        client.setServer(mqtt_server, 1883);
    }
    
    void setup_wifi() {
        delay(10);
        Serial.print("Connecting to ");
        Serial.println(ssid);
        
        WiFi.begin(ssid, password);
        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
        }
        Serial.println(" connected");
    }
    
    void loop() {
        if (!client.connected()) {
            reconnect();
        }
        client.loop();
    
        float h = dht.readHumidity();
        float t = dht.readTemperature();
    
        if (isnan(h) || isnan(t)) {
            Serial.println("Failed to read from DHT sensor!");
            return;
        }
    
        String payload = "Temperature: " + String(t) + "°C, Humidity: " + String(h) + "%";
        client.publish("sensor/data", payload.c_str());
        delay(2000);
    }
    
    void reconnect() {
        while (!client.connected()) {
            Serial.print("Attempting MQTT connection...");
            if (client.connect("ESP32Client")) {
                Serial.println("connected");
            } else {
                Serial.print("failed, rc=");
                Serial.print(client.state());
                delay(2000);
            }
        }
    }
            
  5. Upload the Code
    1. Select your ESP32 board under Tools > Board.
    2. Select the correct port under Tools > Port.
    3. Click on the upload button and wait for the code to compile and upload.

Troubleshooting

  • Wi-Fi Connection Issues: Ensure SSID and password are correct. Check the Wi-Fi signal strength.
  • MQTT Connection Problems: Verify the broker address and port. Ensure the broker is running and accessible.
  • Sensor Reading Errors: Check the wiring of the DHT sensor. Ensure the correct DHT library is installed.
  • Debugging: Use Serial.println() statements to print debug information to the Serial Monitor.

Conclusion

You have successfully set up your ESP32 as an MQTT client to transmit sensor data. You can expand this project by adding more sensors or integrating with a home automation system. Enjoy exploring the capabilities of IoT with your ESP32!

Leave a Comment

Your email address will not be published. Required fields are marked *