IoT/ESP32 B.Tech/Diploma Beginner

ESP32 MQTT – Publish DS18B20 Temperature Readings (Arduino IDE)

Learn how to publish DS18B20 temperature readings via MQTT with the ESP32 to any platform that supports MQTT client. We'll publish sensor readings to Node-RED.

  • Suitable forB.Tech/Diploma IoT/ESP32 students
  • Build time1-2 weeks
  • LevelBeginner
  • Available atAjvika Labs, Kakinada

About this project

Learn how to publish DS18B20 temperature readings via MQTT with the ESP32 to any platform that supports MQTT or any other MQTT client. As an example, we’ll publish sensor readings to Node-RED Dashboard and the ESP32 will be programmed using Arduino IDE.
Recommended reading:
What is MQTT and How It Works
Project Overview
The following diagram shows a high-level overview of the project we’ll build.
The ESP32 request temperature readings from the DS18B20 sensor. The readings are published in the
esp32/ds18b20/temperature
topic;
Node-RED is subscribed to the
esp32/ds18b20/temperature
topic. So, it receives the DS18B20 temperature readings and displays the readings in a gauge/chart;
You can receive the readings in any other platform that supports MQTT and handle the readings as you want.
Prerequisites
Before proceeding with this tutorial, make sure you check the following prerequisites.
Arduino IDE
We’ll program the ESP32 using Arduino IDE, so make sure you have the ESP32 add-on installed.
Installing the ESP32 Board in Arduino IDE (Windows, Mac OS X, Linux)
MQTT Broker
To use MQTT, you need a broker. We’ll be using
Mosquitto broker
installed on a Raspberry Pi. Read
How to Install Mosquitto Broker on Raspberry Pi
You can use any other MQTT broker, including a cloud MQTT broker. We’ll show you how to do that in the code later on.
If you’re not familiar with MQTT make sure you read our introductory tutorial:
What is MQTT and How It Works
MQTT Libraries
To use MQTT with the ESP32, we’ll use a forked version of the
Async MQTT Client Library
Installing the Async MQTT Client Library
Go to
Sketch
>
Include Library
>
Add . ZIP
library and select the library you’ve just downloaded.
Click here to download the Async MQTT client library (our forked version)
. You should have a .zip folder in your
Downloads
folder.
Installing the Async TCP Library
To use MQTT with the ESP32, you also need the
Async TCP library
Open the
Arduino Library Manager
by clicking the Library icon in the left sidebar.
AsyncTCP
and install the
AsyncTCP library by ESP32Async
DS18B20 Temperature Sensor Libraries
To interface with the DS18B20 temperature sensor, you need to install the
One Wire library by Paul Stoffregen
and the
Dallas Temperature library
. Follow the next steps to install those libraries.
Open the
Arduino Library Manager
by clicking the Library icon in the left sidebar.
Type “onewire” in the search box and install the
OneWire
library by Paul Stoffregen.
Then, search for “
Dallas
” and install the
DallasTemperature
library by Miles Burton.
To learn more about the DS18B20 temperature sensor, read our guide:
ESP32 DS18B20 Temperature Sensor with Arduino IDE (Single, Multiple, Web Server)
Parts Required
For this tutorial you need the following parts:
ESP32
(read
Best ESP32 development boards
)
DS18B20 Temperature Sensor
–
DS18B20 with ESP32 Guide
4.7k Ohm resistor
Raspberry Pi board
(read
Best Raspberry Pi Starter Kits
)
MicroSD Card – 16GB Class10
Raspberry Pi Power Supply (5V 2.5A)
Jumper wires
Breadboard
You can use the preceding links or go directly to
MakerAdvisor.com/tools
to find all the parts for your projects at the best price!
Schematic Diagram
Wire the DS18B20 to the ESP32 as shown in the following schematic diagram with the DS18B20 data pin connected to
GPIO 4
Code
Copy the following code to your Arduino IDE. To make it work for you, you need to insert your network credentials as well as the MQTT broker details.
/*
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
#include `WiFi.h`
extern \"C\" {
#include \"freertos/FreeRTOS.h\"
#include \"freertos/timers.h\"
}
#include `AsyncMqttClient.h`
#include `OneWire.h`
#include `DallasTemperature.h`

#define WIFI_SSID \"REPLACE_WITH_YOUR_SSID\"
#define WIFI_PASSWORD \"REPLACE_WITH_YOUR_PASSWORD\"

// Raspberry Pi Mosquitto MQTT Broker
#define MQTT_HOST IPAddress(192, 168, 1, XXX)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST \"example.com\"
#define MQTT_PORT 1883

// Temperature MQTT Topic
#define MQTT_PUB_TEMP \"esp32/ds18b20/temperature\"

// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
// Temperature value
float temp;

AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;

unsigned long previousMillis = 0; // Stores last time temperature was published
const long interval = 10000; // Interval at which to publish sensor readings

void connectToWifi() {
Serial.println(\"Connecting to Wi-Fi...\");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

void connectToMqtt() {
Serial.println(\"Connecting to MQTT...\");
mqttClient.connect();
}

void WiFiEvent(WiFiEvent_t event) {
Serial.printf(\"[WiFi-event] event: %d\
\", event);
switch(event) {
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.println(\"WiFi connected\");
Serial.println(\"IP address: \");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println(\"WiFi lost connection\");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
}
}

void onMqttConnect(bool sessionPresent) {
Serial.println(\"Connected to MQTT.\");
Serial.print(\"Session present: \");
Serial.println(sessionPresent);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println(\"Disconnected from MQTT.\");
if (WiFi.isConnected()) {
xTimerStart(mqttReconnectTimer, 0);
}
}

/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
Serial.println(\"Subscribe acknowledged.\");
Serial.print(\" packetId: \");
Serial.println(packetId);
Serial.print(\" qos: \");
Serial.println(qos);
}
void onMqttUnsubscribe(uint16_t packetId) {
Serial.println(\"Unsubscribe acknowledged.\");
Serial.print(\" packetId: \");
Serial.println(packetId);
}*/

void onMqttPublish(uint16_t packetId) {
Serial.println(\"Publish acknowledged.\");
Serial.print(\" packetId: \");
Serial.println(packetId);
}

void setup() {
// Start the DS18B20 sensor
sensors.begin();

Serial.begin(115200);
Serial.println();
Serial.println();

mqttReconnectTimer = xTimerCreate(\"mqttTimer\", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate(\"wifiTimer\", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

WiFi.onEvent(WiFiEvent);

mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
//mqttClient.onSubscribe(onMqttSubscribe);
//mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
// If your broker requires authentication (username and password), set them below
//mqttClient.setCredentials(\"REPlACE_WITH_YOUR_USER\", \"REPLACE_WITH_YOUR_PASSWORD\");
connectToWifi();
}

void loop() {
unsigned long currentMillis = millis();
// Every X number of seconds (interval = 10 seconds)
// it publishes a new MQTT message
if (currentMillis - previousMillis >= interval) {
// Save the last time a new reading was published
previousMillis = currentMillis;
// New temperature readings
sensors.requestTemperatures();
// Temperature in Celsius

Technologies used

ESP32ArduinoRaspberry PiMQTTWiFiDS18B20Arduino IDE

Hardware components

  • ESP32
  • Arduino
  • Raspberry Pi
  • DS18B20
  • SD Card

Software & tools

  • Arduino IDE
  • Node-RED
  • MQTT

What you get

  • Working project / hardware kit, tested before delivery
  • Complete source code with explanation
  • Project demo and guidance for your viva
  • Project report, PPT and IEEE paper support (on request)
Delivery & Payment
Delivery takes a minimum of two weeks from the date your inquiry is confirmed. Payment is in two parts: • 50% advance to start the project • Remaining 50% before delivery Note: • Documentation and PPT are not included by default • If you need documentation/PPT, it can be arranged for extra time and cost We'll confirm the exact timeline and cost with you after reviewing your requirements.