Remote Temperature Monitoring Using MQTT and ESP8266 Modules




Introduction: Remote Temperature Monitoring Using MQTT and ESP8266 Modules

If you want to monitor some remote temperatures this Instructable will show you can do this by using some ESP8266 modules, MQTT (with a broker), LCD screen (for local monitoring), home-assistant (for local and remote monitoring), and of cause some temperature sensors (I use DS18b20 as they are pretty good and cheap enough)

I will divide this Instructable into several little projects as there is quite a bit to do to get it all working. These will be:

  1. Build a temperature sensor using an ESP8266 and DS18b20 - output to serial
  2. Setup MQTT broker on a ubuntu server
  3. Modify the sketch on the ESP8266 to publish temperature to the MQTT broker
  4. Connect LCD screen to another ESP8266 for local monitoring (Instructable
  5. Install and configure home-assistant on a ubuntu server (for local and remote monitoring)

Step 1: Build a Temperature Sensor Using an ESP8266 and DS18b20 - Output to Serial

Connecting the DS18b20 to the ESP8266 is very simple. The picture above along with the BreadBoard Fritzing should help.

You simply connect the left hand pin to Ground, the centre pin to the GPIO that you want to use (I use D1 which is GPIO5), and the right had ping to 5v.

Once this is all connected up you can use the Simple DallasTemperature example to get the temperature from the sensor which is sent to the serial output.

I added sensors.setResolution(12) which sets the resolution of the device to 12 bits so that I get a more precise temperature reading. You can see from the values below what you can expect from each of the bit resolutions:

Mode Resol Conversion time

9 bits 0.5°C 93.75 ms

10 bits 0.25°C 187.5 ms

11 bits 0.125°C 375 ms

12 bits 0.0625°C 750 ms

You can get the library for the DS18b20 from the Arduino Library manager, so no need to download it from github separately.

Step 2: Setup MQTT Broker on a Ubuntu Server

This part of the Instructable assumes you know how to install and update ubuntu. Once you have got this far you'll need to install mosquitto.

root@ubuntu:~# apt-get install mosquitto
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
The following NEW packages will be installed
  libwebsockets3 mosquitto
0 to upgrade, 2 to newly install, 0 to remove and 3 not to upgrade.
Need to get 0 B/163 kB of archives.
After this operation, 490 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Selecting previously unselected package libwebsockets3:amd64.
(Reading database ... 64521 files and directories currently installed.)
Preparing to unpack .../libwebsockets3_1.2.2-1_amd64.deb ...
Unpacking libwebsockets3:amd64 (1.2.2-1) ...
Selecting previously unselected package mosquitto.
Preparing to unpack .../mosquitto_1.4.8-0mosquitto1_amd64.deb ...
Unpacking mosquitto (1.4.8-0mosquitto1) ...
Processing triggers for ureadahead (0.100.0-16) ...
Processing triggers for man-db ( ...
Setting up libwebsockets3:amd64 (1.2.2-1) ...
Setting up mosquitto (1.4.8-0mosquitto1) ...
mosquitto start/running, process 12955
Processing triggers for libc-bin (2.19-0ubuntu6.7) ...

Once mosquitto is installed it should be running, check it by running a ps:

root@ubuntu:~# ps aux |grep mosquitto
mosquit+ 12955  0.1  0.0  37236  2420 ?        Ss   16:45   0:01 /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf
root     13307  0.0  0.0  11744   948 pts/0    S+   16:58   0:00 grep --color=auto mosquitto

Now if you run the following command to subscribe to the broker you should see nothing, but mosquitto_sub will sit and wait for something to be published to the broker.

root@ubuntu:~# mosquitto_sub -h localhost -v -t "#"

This will subscribe to all topics (as you've used the # for the topic) so anything that is sent to the broker will be displayed.

Then in another ssh window send a message to the broker as follows :

rot@ubuntu:~# mosquitto_pub -h localhost -t "ha/test" -m "Hello"

Then back in the other window that is running the mosquitto_sub you should see the following :

root@ubuntu:~# mosquitto_sub -h localhost -v -t "#"
ha/test Hello

This shows that the broker is working and is ready for receiving data from the ESP8266 nodes and sending it onto home-assistant.

Step 3: Modify the Sketch on the ESP8266 to Publish Temperature to the MQTT Broker

Now that the MQTT broker is running on your ubuntu server you can now update the sketch on your ESP8266 to start sending temperatures to it.

The follow sketch will need a little modifying to include your own wifi SSID and the IP address of your ubuntu server that has mosquitto running on it.

You will need the following libraries which you can get from github:

#include <ESP8266WiFi.h>

#include <PubSubClient.h>

#include <OneWire.h>

#include <DallasTemperature.h>

// Data wire is plugged into pin 2 on the Arduino #define ONE_WIRE_BUS 5

// Setup a oneWire instance to communicate with any OneWire devices // (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

// Update these with values suitable for your network. const char* ssid = ""; const char* password = ""; const char* mqtt_server = "";

WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; float temp = 0; int inPin = 5;

void setup_wifi() { delay(10); // We start by connecting to a WiFi network 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("arduinoClient_temperature_sensor")) { 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 setup() { Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); pinMode(inPin, INPUT); sensors.begin(); }

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

long now = millis(); if (now - lastMsg > 60000) { lastMsg = now; sensors.setResolution(12); sensors.requestTemperatures(); // Send the command to get temperatures temp = sensors.getTempCByIndex(0); Serial.println(temp); if((temp > -20) && (temp <60)) { client.publish("ha/_temperature1", String(temp).c_str(),TRUE); } } }


Step 4: Install and Configure Home-assistant on a Ubuntu Server (for Local and Remote Monitoring)

For full instructions to install and configure home-assistant you can pop over to But here are some pointers to get things working.

You will need to have python3-pip installed first of all:

root@ubuntu:~# apt-get install python3-pip

Once pip is installed you can install home-assistant:

pip3 install homeassistant

You then just run hass as follows:

root@ubuntu:~# hass

This will run hass and will create a basic configuration file which we will now edit to add the sensor for the temperature.

Your home-assistant configuration file should be in your /home/USERID/.homeassistant dir, called configuration.yaml. Open this and you'll need to add a section for the MQTT server and add a new sensor to it as follows:

  port: 1883
  keepalive: 1000
  protocol: 3.1
  client_id: home-assistant-1

   platform: mqtt
   state_topic: "ha/_temperature1"
   name: "Back garden"
   unit_of_measurement: "°C"
   qos: 1

As you can see the state_topic is the same as what you have set in the sketch on the ESP8266. Once you have saved the config file, restart hass, by just pressing ctrl-c to stop it then run it again by typing hass again.

If you then browse to the IP address of your ubuntu server on port 8123 (default port for home-assistant) you should see something like the pic above.

If you want to add the temperature to a 'card' on the webpage, which does look much nicer, then you can just add a group for the temperatures (in this case just the one temperature for now) as follows:

group:  temperatures:
    name: Temperatures
       - sensor.back_garden

Be the First to Share


    • Block Code Contest

      Block Code Contest
    • Cold Challenge

      Cold Challenge
    • Game Design: Student Design Challenge

      Game Design: Student Design Challenge



    4 years ago

    Is there any
    reason to communicate only the temp within the range of -20 to 60 °,
    since the ds18b20 can read temperatures up to 125 °?


    5 years ago

    how do i add another temp sensor to the esp8266? and can i send the other sensor on another topic?


    6 years ago

    Great post.
    This is a request for guidance.
    My ESP8266 module connects to “” and subscribes to a topic say “b1”. What ever is published to “b1”, it can read it immediately.
    Problem happens when my second ESP8266 module subscribes to “” to “b1”. It continuously returns :

    WiFi connected
    IP address:
    Attempting MQTT connection…connected
    Message arrived [b1] 0
    Attempting MQTT connection…connected
    Message arrived [b1] 0
    Attempting MQTT connection…connected
    Message arrived [b1] 0
    Attempting MQTT connection…connected

    Could you kindly suggest what might be going wrong. I look forward to your advice.


    Reply 6 years ago

    Its not well documented, but in the call to client.connect, clientID should be unique. This tripped me up as well. You can use the MAC address as the clientID, it will be unique to the network.

    char myClientID[18];

    WiFi.macAddress( ).toCharArray( myClientID, sizeof( myClientID ));

    if (client.connect( myClientID )) {



    The Arduino IDE really should be able to generate a unique UUID at compile time. It would save a lot of headaches.


    6 years ago

    Thanks for the super good and inspiring article on Remote Temperature Monitoring Using MQTT and ESP8266.

    Currently I have a mosquitto Broker running on a Raspberry Pi, and a ESP8266 with your sample code. It works fine, and I can see the temperature in a terminal window on my RPI.

    Now, I try with another ESP8266 with the same code, but then it goes wrong.

    On the other ESP8266 I can see in the terminal window that it loses the connection to mosquitto Broker, and constantly trying to reconnect. There are 8 meters between the two ESP8266 so that they should not disturb each other.

    Via an android WiFi analyzes App, I can see that the two ESP8266 emits a WiFI signal called DoitWiFi, on the same channel as my WiFi Access Point / Router. It is perhaps the reason for the bad connection, but how do I turn this WiFi signal off ?.

    It is as if ESP8266 acting as an independent Access Point. Can it be changed?

    The applied ESP8266 is a GreekCreit.NodeMcu-Lua-ESP8266-ESP12E. See link below.

    WiFi Analyser.JPGMQTT connection.JPG

    Reply 6 years ago

    It turns out that ESP8266 by default run in Mixed Mode and that this can be changed by inserting the following sentence in the Void Setup_wifi ()

    void setup_wifi () {

    WiFi.mode (WIFI_STA); // Sets the unit in Station Mode, and not by default Mixed Mode.

    This disappears this extra WiFi signal.

    Unfortunately, it has not changed that when two devices connected while you lose the current connection to MQTT broker? ? ?

    Is it something to be used different user account, or else ii compared to MQTT broker?

    MQTT connection2.JPG

    6 years ago

    Is this concept using internet? or local wifi only?


    6 years ago

    Did you try any measurements on the power consumption for ESP8266 configuration? I think about some sensors in my garden and having them on battery sounds not so promising at a first glance. Sending temperature every 15 minutes is ok, but I am not sure how much the batteries will last, 1 month will be ideal :D


    Reply 6 years ago

    I've not done any measurements of power usage for any of my ESP8266 projects (yet) mainly because they are all indoors and connected to a mains power adapter of some kind.

    You can put the ESP8266 into sleep mode and only wake up (switch wifi on again) every 15mins if that is how often you would like to send the data, this would reduce the power usage. Also you could include a solar cell to keep the battery (if you're using rechargeable) topped up.


    Reply 6 years ago

    Thanks, I'll let you know my findings when I'm done, your project is a good start for what I want to do :)


    6 years ago

    Thanks for this, love the focus om MQTT!


    6 years ago

    Thanks for the follow-up Instructable to your other Instructable. Look forward to trying it out.