Connecting ESP32 with DS18B20 Sensor and Publishing Data using MQTT Protocol

  ·   3 min read

The Internet of Things (IoT) has revolutionized the way we interact with devices and gather data. One of the most popular microcontrollers for IoT projects is the ESP32, thanks to its built-in Wi-Fi and Bluetooth capabilities. In this article, we’ll explore how to connect an ESP32 to a DS18B20 temperature sensor and publish the temperature data using the MQTT protocol.

Components Required

  1. ESP32 Development Board: A powerful microcontroller with Wi-Fi and Bluetooth capabilities.
  2. DS18B20 Temperature Sensor: A digital temperature sensor that provides accurate temperature readings.
  3. 4.7k Ohm Resistor: Used as a pull-up resistor for the DS18B20 data line.
  4. Breadboard and Jumper Wires: For making connections between components.
  5. MQTT Broker: A server that receives and forwards messages to clients. Mosquitto is a popular open-source option.

Setting Up the Hardware

  1. Connect the DS18B20 Sensor:
    • Connect the VDD pin of the DS18B20 to the 3.3V pin on the ESP32.
    • Connect the GND pin of the DS18B20 to a GND pin on the ESP32.
    • Connect the DATA pin of the DS18B20 to a digital GPIO pin on the ESP32 (e.g., GPIO 4).
    • Place a 4.7k Ohm resistor between the DATA pin and the VDD pin of the DS18B20.

Programming the ESP32

To program the ESP32, we’ll use the Arduino IDE. Ensure you have the ESP32 board package installed in your Arduino IDE.

Libraries Required

  • OneWire: For communication with the DS18B20 sensor.
  • DallasTemperature: To easily interface with the DS18B20 sensor.
  • PubSubClient: For MQTT communication.

Code

#include <WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

// MQTT Broker
const char* mqtt_server = "broker.hivemq.com"; // You can use a public broker or set up your own

WiFiClient espClient;
PubSubClient client(espClient);

// Data wire is plugged into GPIO 4 on the ESP32
#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup() {
  Serial.begin(115200);
  
  // Connect to Wi-Fi
  setup_wifi();
  
  // Connect to MQTT Broker
  client.setServer(mqtt_server, 1883);
  
  // Start the DS18B20 sensor
  sensors.begin();
}

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);

  Serial.print("Temperature: ");
  Serial.println(temperatureC);

  // Publish temperature data to MQTT topic
  client.publish("esp32/temperature", String(temperatureC).c_str());

  delay(2000); // Adjust the delay as needed
}

Setting Up the MQTT Broker

For testing purposes, you can use a public MQTT broker like HiveMQ. However, for production environments, it’s recommended to set up your own broker using Mosquitto or similar software.

Installing Mosquitto

On a Linux system, you can install Mosquitto using the following commands:

sudo apt update
sudo apt install mosquitto mosquitto-clients

Start the Mosquitto service:

sudo systemctl start mosquitto
sudo systemctl enable mosquitto

Conclusion

By following the steps outlined in this article, you can successfully connect an ESP32 to a DS18B20 temperature sensor and publish the data using the MQTT protocol. This setup can be extended to include multiple sensors and more complex data processing, making it ideal for home automation and IoT projects.

References

This project demonstrates the power and flexibility of the ESP32 in IoT applications, providing a foundation for further exploration and development.