ESP8266 NodeMCU MQTT – Publish DS18B20 Temperature Readings (Arduino IDE)

Learn how to publish DS18B20 temperature readings via MQTT with the ESP8266 (NodeMCU) 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 ESP8266 will be programmed using Arduino IDE.

ESP8266 NodeMCU MQTT - Publish DS18B20 Temperature Readings (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.

ESP8266 NodeMCU MQTT Publish DS18B20 Temperature Readings How it works and project overview
  • The ESP8266 requests temperature readings from the DS18B20 sensor. The readings are published in the esp/ds18b20/temperature topic;
  • Node-RED is subscribed to the esp/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 ESP8266 using Arduino IDE, so make sure you have the ESP8266 add-on installed.

MQTT Broker

Installing Mosquitto MQTT broker Raspberry Pi

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 ESP8266 we’ll use the Async MQTT Client Library.

Installing the Async MQTT Client Library

  1. Click here to download the Async MQTT client library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get async-mqtt-client-master folder
  3. Rename your folder from async-mqtt-client-master to async_mqtt_client
  4. Move the async_mqtt_client folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Alternatively, you can go to Sketch > Include Library > Add . ZIP library and select the library you’ve just downloaded.

Installing the ESPAsync TCP Library

To use MQTT with the ESP, you also need the ESPAsync TCP library.

  1. Click here to download the ESPAsync TCP client library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get ESPAsyncTCP-master folder
  3. Rename your folder from ESPAsyncTCP-master to ESPAsyncTCP
  4. Move the ESPAsyncTCP folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Alternatively, you can go to Sketch > Include Library > Add . ZIP library and select the library you’ve just downloaded.

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.

1. Open your Arduino IDE and go to Sketch Include Library > Manage Libraries. The Library Manager should open.

2. Type “onewire” in the search box and install OneWire library by Paul Stoffregen.

Install OneWire library by Paul Stoffregen in Arduino IDE

3. Then, search for “Dallas” and install DallasTemperature library by Miles Burton.

Install DallasTemperature library by Miles Burton in Arduino IDE

After installing the libraries, restart your Arduino IDE.

To learn more about the DS18B20 temperature sensor, read our guide: ESP8266 DS18B20 Temperature Sensor with Arduino IDE (Single, Multiple, Web Server)

Parts Required

For this tutorial you need the following parts:

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 ESP8266 as shown in the following schematic diagram with the DS18B20 data pin connected to GPIO 4 (D2).

ESP8266 NodeMCU DS18B20 Temperature sensor connected GPIO 4 schematic circuit diagram

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.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp8266-nodemcu-mqtt-publish-ds18b20-arduino/
  
  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 <OneWire.h>
#include <DallasTemperature.h>
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <AsyncMqttClient.h>

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

// Raspberri 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 Topics
#define MQTT_PUB_TEMP "esp/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;
Ticker mqttReconnectTimer;

WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
Ticker 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 onWifiConnect(const WiFiEventStationModeGotIP& event) {
  Serial.println("Connected to Wi-Fi.");
  connectToMqtt();
}

void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
  Serial.println("Disconnected from Wi-Fi.");
  mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
  wifiReconnectTimer.once(2, connectToWifi);
}

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

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()) {
    mqttReconnectTimer.once(2, connectToMqtt);
  }
}

/*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.print("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void setup() {
  sensors.begin();
  Serial.begin(115200);
  Serial.println();
  
  wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
  wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);

  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 degrees
    temp = sensors.getTempCByIndex(0);
    // Temperature in Fahrenheit degrees
    //temp = sensors.getTempFByIndex(0);
    
    // Publish an MQTT message on topic esp/ds18b20/temperature
    uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());                            
    Serial.printf("Publishing on topic %s at QoS 1, packetId: %i ", MQTT_PUB_TEMP, packetIdPub1);
    Serial.printf("Message: %.2f \n", temp);
  }
}

View raw code

How the Code Works

The following section imports all the required libraries.

#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <AsyncMqttClient.h>

Include your network credentials on the following lines.

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

Insert the Raspberry Pi IP address, so that the ESP8266 connects to your broker.

#define MQTT_HOST IPAddress(192, 168, 1, 106)

If you’re using a cloud MQTT broker, insert the broker domain name, for example:

#define MQTT_HOST "example.com"

Define the MQTT port.

#define MQTT_PORT 1883

We’ll publish the temperature on the esp/ds18b20/temperature topic. If you want to change the topic, change it on the following line.

#define MQTT_PUB_TEMP "esp/ds18b20/temperature"

You can create more topics if you want.

Setup your DS18B20 on the following lines. In our case, it is connected to GPIO 4. You can connect it to any other GPIO.

// 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);

The temp variable will hold the temperature value from the DS18B20 temperature sensor.

float temp;

Create an AsyncMqttClient object called mqttClient to handle the MQTT client and timers to reconnect to your MQTT broker and router when it disconnects.

AsyncMqttClient mqttClient;
Ticker mqttReconnectTimer;

WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
Ticker wifiReconnectTimer;

Then, create some auxiliary timer variables to publish the readings every 10 seconds. You can change the delay time on the interval variable.

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

MQTT functions: connect to Wi-Fi, connect to MQTT, and Wi-Fi events

We haven’t added any comments to the functions defined in the next code section. Those functions come with the Async Mqtt Client library. The function’s names are pretty self-explanatory.

For example, the connectToWifi() connects your ESP8266 to your router:

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

The connectToMqtt() connects your ESP8266 to your MQTT broker:

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

The onMqttConnect() function runs after starting a session with the broker.

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

MQTT functions: disconnect and publish

If the ESP8266 loses connection with the MQTT broker, calls the onMqttDisconnect function that prints that message in the serial monitor.

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");

  if (WiFi.isConnected()) {
    mqttReconnectTimer.once(2, connectToMqtt);
  }
}

When you publish a message to an MQTT topic, the onMqttPublish() function is called. It prints the packet id in the Serial Monitor.

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

Basically, all these functions that we’ve just mentioned are callback functions. So, they are executed asynchronously.

setup()

Now, let’s proceed to the setup(). Initialize the DS18B20 sensor and start the serial communication.

sensors.begin();
Serial.begin(115200);

The next two lines create handlers that will allow both the MQTT broker and Wi-Fi connection to reconnect, in case the connection is lost.

wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);

Finally, assign all the callbacks functions. This means that these functions will be executed automatically when needed. For example, when the ESP8266 connects to the broker, it automatically calls the onMqttConnect() function, and so on.

mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
//mqttClient.onSubscribe(onMqttSubscribe);
//mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);

Broker Authentication

If your broker requires authentication, uncomment the following line and insert your credentials (username and password).

mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");

Finally, connect to Wi-Fi.

connectToWifi();

loop()

In the loop(), you create a timer that will allow you to publish new temperature readings in the esp/d18b20/temperature topic every 10 seconds.

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 degrees
  temp = sensors.getTempCByIndex(0);

If you prefer the temperature in Fahrenheit, uncomment the following line:

//temp = sensors.getTempFByIndex(0);

Learn more about the DS18B20 temperature sensor: ESP8266 DS18B20 Temperature Sensor with Arduino IDE (Single, Multiple, Web Server).

Publishing to topics

To publish a message on an MQTT topic, use the next line:

uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());

If you would like to publish more readings on different topics, you can duplicate this previous line the loop().

Basically, use the publish() method on the mqttClient object to publish data on a topic. The publish() method accepts the following arguments, in order:

  • MQTT topic (const char*)
  • QoS (uint8_t): quality of service – it can be 0, 1 or 2
  • retain flag (bool): retain flag
  • payload (const char*)

The QoS (quality of service) is a way to guarantee that the message is delivered. It can be one of the following levels:

  • 0: the message will be delivered once or not at all. The message is not acknowledged. There is no possibility of duplicated messages;
  • 1: the message will be delivered at least once, but may be delivered more than once;
  • 2: the message is always delivered exactly once;
  • Learn about MQTT QoS.

Uploading the code

With your Raspberry Pi powered on and running the Mosquitto MQTT broker, upload the code to your ESP8266.

Open the Serial Monitor at a baud rate of 115200 and you’ll see that the ESP8266 starts publishing messages.

ESP8266 NodeMCU Arduino IDE Serial Monitor MQTT Publish sensor readings debugging demonstration

Preparing Node-RED Dashboard

The ESP8266 is publishing temperature readings every 10 seconds on the esp/ds18b20/temperature topic. Now, you can use any dashboard that supports MQTT or any other device that supports MQTT to subscribe to that topic and receive the readings.

As an example, we’ll create a simple flow using Node-RED to subscribe to that topic and display the readings on a gauge or chart.

If you don’t have Node-RED installed, follow the next tutorials:

Having Node-RED running on your Raspberry Pi, go to your Raspberry Pi IP address followed by :1880.

http://raspberry-pi-ip-address:1880

The Node-RED interface should open. Drag an MQTT in node, a chart node and a gauge node to the flow.

Node-RED Drag Nodes MQTT In Chart Gauge

Click the MQTT node and edit its properties as follows:

MQTT In node ESP8266 Publish Temperature Node-RED Flow

The Server field refers to the MQTT broker. In our case, the MQTT broker is the Raspberry Pi, so it is set to localhost:1883. If you’re using a Cloud MQTT broker, you should change that field. Insert the topic you want to be subscribed to and the QoS.

Set the following properties for the gauge node.

Gauge Node ESP32 Publish Temperature Node-RED Flow

Edit the chart node as follows:

Chart Node ESP32 Publish Temperature Node-RED Flow

Wire your nodes as shown below:

ESP8266 NodeMCU MQTT Publish Temperature Node-RED Flow

Finally, deploy your flow (press the button on the upper right corner).

Alternatively, you can go to Menu > Import and copy the following to your Clipboard to create your Node-RED flow.

[{"id":"3eb4b485.bb948c","type":"mqtt in","z":"b01416d3.f69f38","name":"","topic":"esp/ds18b20/temperature","qos":"1","datatype":"auto","broker":"8db3fac0.99dd48","x":930,"y":120,"wires":[["706fecd4.6f91a4","47ed6377.491d6c"]]},{"id":"706fecd4.6f91a4","type":"ui_gauge","z":"b01416d3.f69f38","name":"","group":"37de8fe8.46846","order":2,"width":0,"height":0,"gtype":"gage","title":"Temperature","label":"ºC","format":"{{value}}","min":0,"max":"40","colors":["#00b500","#f7df09","#ca3838"],"seg1":"","seg2":"","x":1190,"y":100,"wires":[]},{"id":"47ed6377.491d6c","type":"ui_chart","z":"b01416d3.f69f38","name":"","group":"2b7ac01b.fc984","order":4,"width":0,"height":0,"label":"Temperature","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"outputs":1,"x":1190,"y":160,"wires":[[]]},{"id":"8db3fac0.99dd48","type":"mqtt-broker","z":"","name":"","broker":"localhost","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"37de8fe8.46846","type":"ui_group","z":"","name":"DS18B20","tab":"53b8c8f9.cfbe48","order":1,"disp":true,"width":"6","collapse":false},{"id":"2b7ac01b.fc984","type":"ui_group","z":"","name":"SENSORS","tab":"99ab8dc5.f435c","disp":true,"width":"6","collapse":false},{"id":"53b8c8f9.cfbe48","type":"ui_tab","z":"","name":"Home","icon":"dashboard","order":2,"disabled":false,"hidden":false},{"id":"99ab8dc5.f435c","type":"ui_tab","z":"","name":"HTTP","icon":"dashboard","order":1,"disabled":false,"hidden":false}]

View raw code

Demonstration

Go to your Raspberry Pi IP address followed by :1880/ui.

http://raspberry-pi-ip-address:1880/ui

You should get access to the current sensor readings on the Dashboard (gauge and chart).

ESP32 MQTT Publish Temperature Node-RED Dashboard Gauge Chart

That’s it! You have your ESP8266 board publishing sensor readings to Node-RED via MQTT.

Wrapping Up

MQTT is a great communication protocol to exchange small amounts of data between devices. In this tutorial you’ve learned how to publish DS18B20 temperature readings with the ESP8266 on an MQTT topic. Then, you can use any device or home automation platform to subscribe to that topic and receive the readings.

Instead of a DS18B20, you can use any a different sensor:

We hope you’ve found this tutorial useful. If you want to learn more about the ESP8266, take a look at our resources:

Thanks for reading.


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

Leave a Comment

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.