Learn how to program the ESP32 or ESP8266 boards with MicroPython to publish DS18B20 temperature readings via MQTT to any platform that supports MQTT or any MQTT client. As an example, we’ll publish sensor readings to Node-RED Dashboard.
Recommended reading: What is MQTT and How It Works
Note: this tutorial is compatible with both the ESP32 and ESP8266 development boards.
Project Overview
The following diagram shows a high-level overview of the project we’ll build.
- The ESP requests temperature readings from the DS18B20 temperature sensor;
- Temperature readings are published in the esp/ds18b20/temperature topic;
- Node-RED is subscribed to that topic;
- Node-RED receives the temperature readings and displays them on a gauge/chart;
- You can receive the readings in any other platform that supports MQTT and handle the readings as you want.
Prerequisites
Before continuing with this tutorial, make sure you complete the following prerequisites:
To follow this tutorial you need MicroPython firmware installed in your ESP32 or ESP8266 boards. You also need an IDE to write and upload the code to your board. We suggest using Thonny IDE or uPyCraft IDE:
- Thonny IDE:
- uPyCraft IDE:
- Getting Started with uPyCraft IDE
- Install uPyCraft IDE (Windows, Mac OS X, Linux)
- Flash/Upload MicroPython Firmware to ESP32 and ESP8266
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
Parts Required
For this tutorial you need the following parts:
- ESP32 (read Best ESP32 development boards) or ESP8266
- 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!
umqtttsimple Library
To use MQTT with the ESP32/ESP8266 and MicroPython, we’ll use the umqttsimple.py library. Follow the next set of instructions for the IDE you’re using:
- A. Upload umqttsimple library with uPyCraft IDE
- B. Upload umqttsimple library with Thonny IDE
try:
import usocket as socket
except:
import socket
import ustruct as struct
from ubinascii import hexlify
class MQTTException(Exception):
pass
class MQTTClient:
def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0,
ssl=False, ssl_params={}):
if port == 0:
port = 8883 if ssl else 1883
self.client_id = client_id
self.sock = None
self.server = server
self.port = port
self.ssl = ssl
self.ssl_params = ssl_params
self.pid = 0
self.cb = None
self.user = user
self.pswd = password
self.keepalive = keepalive
self.lw_topic = None
self.lw_msg = None
self.lw_qos = 0
self.lw_retain = False
def _send_str(self, s):
self.sock.write(struct.pack("!H", len(s)))
self.sock.write(s)
def _recv_len(self):
n = 0
sh = 0
while 1:
b = self.sock.read(1)[0]
n |= (b & 0x7f) << sh
if not b & 0x80:
return n
sh += 7
def set_callback(self, f):
self.cb = f
def set_last_will(self, topic, msg, retain=False, qos=0):
assert 0 <= qos <= 2
assert topic
self.lw_topic = topic
self.lw_msg = msg
self.lw_qos = qos
self.lw_retain = retain
def connect(self, clean_session=True):
self.sock = socket.socket()
addr = socket.getaddrinfo(self.server, self.port)[0][-1]
self.sock.connect(addr)
if self.ssl:
import ussl
self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
premsg = bytearray(b"\x10\0\0\0\0\0")
msg = bytearray(b"\x04MQTT\x04\x02\0\0")
sz = 10 + 2 + len(self.client_id)
msg[6] = clean_session << 1
if self.user is not None:
sz += 2 + len(self.user) + 2 + len(self.pswd)
msg[6] |= 0xC0
if self.keepalive:
assert self.keepalive < 65536
msg[7] |= self.keepalive >> 8
msg[8] |= self.keepalive & 0x00FF
if self.lw_topic:
sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
msg[6] |= self.lw_retain << 5
i = 1
while sz > 0x7f:
premsg[i] = (sz & 0x7f) | 0x80
sz >>= 7
i += 1
premsg[i] = sz
self.sock.write(premsg, i + 2)
self.sock.write(msg)
#print(hex(len(msg)), hexlify(msg, ":"))
self._send_str(self.client_id)
if self.lw_topic:
self._send_str(self.lw_topic)
self._send_str(self.lw_msg)
if self.user is not None:
self._send_str(self.user)
self._send_str(self.pswd)
resp = self.sock.read(4)
assert resp[0] == 0x20 and resp[1] == 0x02
if resp[3] != 0:
raise MQTTException(resp[3])
return resp[2] & 1
def disconnect(self):
self.sock.write(b"\xe0\0")
self.sock.close()
def ping(self):
self.sock.write(b"\xc0\0")
def publish(self, topic, msg, retain=False, qos=0):
pkt = bytearray(b"\x30\0\0\0")
pkt[0] |= qos << 1 | retain
sz = 2 + len(topic) + len(msg)
if qos > 0:
sz += 2
assert sz < 2097152
i = 1
while sz > 0x7f:
pkt[i] = (sz & 0x7f) | 0x80
sz >>= 7
i += 1
pkt[i] = sz
#print(hex(len(pkt)), hexlify(pkt, ":"))
self.sock.write(pkt, i + 1)
self._send_str(topic)
if qos > 0:
self.pid += 1
pid = self.pid
struct.pack_into("!H", pkt, 0, pid)
self.sock.write(pkt, 2)
self.sock.write(msg)
if qos == 1:
while 1:
op = self.wait_msg()
if op == 0x40:
sz = self.sock.read(1)
assert sz == b"\x02"
rcv_pid = self.sock.read(2)
rcv_pid = rcv_pid[0] << 8 | rcv_pid[1]
if pid == rcv_pid:
return
elif qos == 2:
assert 0
def subscribe(self, topic, qos=0):
assert self.cb is not None, "Subscribe callback is not set"
pkt = bytearray(b"\x82\0\0\0")
self.pid += 1
struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
#print(hex(len(pkt)), hexlify(pkt, ":"))
self.sock.write(pkt)
self._send_str(topic)
self.sock.write(qos.to_bytes(1, "little"))
while 1:
op = self.wait_msg()
if op == 0x90:
resp = self.sock.read(4)
#print(resp)
assert resp[1] == pkt[2] and resp[2] == pkt[3]
if resp[3] == 0x80:
raise MQTTException(resp[3])
return
# Wait for a single incoming MQTT message and process it.
# Subscribed messages are delivered to a callback previously
# set by .set_callback() method. Other (internal) MQTT
# messages processed internally.
def wait_msg(self):
res = self.sock.read(1)
self.sock.setblocking(True)
if res is None:
return None
if res == b"":
raise OSError(-1)
if res == b"\xd0": # PINGRESP
sz = self.sock.read(1)[0]
assert sz == 0
return None
op = res[0]
if op & 0xf0 != 0x30:
return op
sz = self._recv_len()
topic_len = self.sock.read(2)
topic_len = (topic_len[0] << 8) | topic_len[1]
topic = self.sock.read(topic_len)
sz -= topic_len + 2
if op & 6:
pid = self.sock.read(2)
pid = pid[0] << 8 | pid[1]
sz -= 2
msg = self.sock.read(sz)
self.cb(topic, msg)
if op & 6 == 2:
pkt = bytearray(b"\x40\x02\0\0")
struct.pack_into("!H", pkt, 2, pid)
self.sock.write(pkt)
elif op & 6 == 4:
assert 0
# Checks whether a pending message from server is available.
# If not, returns immediately with None. Otherwise, does
# the same processing as wait_msg.
def check_msg(self):
self.sock.setblocking(False)
return self.wait_msg()
A. Upload umqttsimple library with uPyCraft IDE
1. Create a new file by pressing the New File button.
2. Copy the umqttsimple library code into it. You can access the umqttsimple library code in the following link:
3. Save the file by pressing the Save button.
4. Call this new file “umqttsimple.py” and press ok.
5. Click the Download and Run button.
6. The file should be saved on the device folder with the name “umqttsimple.py” as highlighted in the figure below.
Now, you can use the library functionalities in your code by importing the library.
B. Upload umqttsimple library with Thonny IDE
1. Copy the library code to a new file. The umqttsimple library code can be found here.
2. Go to File > Save as…
3. Select save to “MicroPython device“:
4. Name your file as umqttsimple.py and press the OK button:
And that’s it. The library was uploaded to your board. To make sure that it was uploaded successfully, go to File > Save as… and select the MicroPython device. Your file should be listed there:
After uploading the library to your board, you can use the library functionalities in your code by importing the library.
Schematic: ESP32 with DS18B20
Wire the DS18B20 temperature sensor to the ESP32 development board as shown in the following schematic diagram.
Learn how to use the ESP32 GPIOs with our guide: ESP32 Pinout Reference: Which GPIO pins should you use?
Schematic: ESP8266 NodeMCU with DS18B20
If you’re using an ESP8266 NodeMCU, follow the next diagram instead.
Learn how to use the ESP8266 GPIOs with our guide: ESP8266 Pinout Reference: Which GPIO pins should you use?
Code
After uploading the library to the ESP32 or ESP8266, copy the following code to the main.py file. It publishes the temperature readings on the esp/ds18b20/temperature topic every 5 seconds.
# Complete project details at https://RandomNerdTutorials.com/micropython-mqtt-publish-ds18b10-esp32-esp8266/
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
from machine import Pin
import onewire
import ds18x20
esp.osdebug(None)
import gc
gc.collect()
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
mqtt_server = '192.168.1.XXX'
#EXAMPLE IP ADDRESS
#mqtt_server = '192.168.1.106'
client_id = ubinascii.hexlify(machine.unique_id())
topic_pub_temp = b'esp/ds18b20/temperature'
last_message = 0
message_interval = 5
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
ds_pin = machine.Pin(4)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
def connect_mqtt():
global client_id, mqtt_server
client = MQTTClient(client_id, mqtt_server)
#client = MQTTClient(client_id, mqtt_server, user=your_username, password=your_password)
client.connect()
print('Connected to %s MQTT broker' % (mqtt_server))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
def read_sensor():
try:
roms = ds_sensor.scan()
ds_sensor.convert_temp()
time.sleep_ms(750)
for rom in roms:
temp = ds_sensor.read_temp(rom)
# uncomment for Fahrenheit
temp = temp * (9/5) + 32.0
if (isinstance(temp, float) or (isinstance(temp, int))):
temp = (b'{0:3.1f},'.format(temp))
return temp
else:
return('Invalid sensor readings.')
except OSError as e:
return('Failed to read sensor.')
try:
client = connect_mqtt()
except OSError as e:
restart_and_reconnect()
while True:
try:
if (time.time() - last_message) > message_interval:
temp = read_sensor()
print(temp)
client.publish(topic_pub_temp, temp)
last_message = time.time()
except OSError as e:
restart_and_reconnect()
How the Code Works
Import the following libraries:
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
from machine import Pin
import onewire
import ds18x20
In the following variables, you need to enter your network credentials and your broker IP address.
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'
For example, our broker IP address is: 192.168.1.106.
mqtt_server = '192.168.1.106'
Note: read this tutorial to see how to get your broker IP address.
To create an MQTT client, we need to get the ESP unique ID. That’s what we do in the following line (it is saved on the client_id variable).
client_id = ubinascii.hexlify(machine.unique_id())
Next, create the topic you want your ESP to be publishing in. In our example, it will publish temperature on the esp/ds18b20/temperature topic.
topic_pub_temp = b'esp/ds18b20/temperature'
Then, create the following variables:
last_message = 0
message_interval = 5
The last_message variable will hold the last time a message was sent. The message_interval is the time between each message sent. Here, we’re setting it to 5 seconds (this means a new message will be sent every 5 seconds). You can change it, if you want.
After that, connect the ESP to your local network.
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
Create an instance for the DS18B20 temperature sensor on GPIO 4.
ds_pin = machine.Pin(4)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
Connect to MQTT Broker
The connect_mqtt() function creates an MQTT Client and connects to your broker.
def connect_mqtt():
global client_id, mqtt_server
client = MQTTClient(client_id, mqtt_server)
#client = MQTTClient(client_id, mqtt_server, user=your_username, password=your_password)
client.connect()
print('Connected to %s MQTT broker' % (mqtt_server))
return client
If your MQTT broker requires username and password, you should use the following line to pass your broker username and password as arguments.
client = MQTTClient(client_id, mqtt_server, user=your_username, password=your_password)
Restart and Reconnect
The restart_and_reconnect() function resets the ESP32/ESP8266 board. This function will be called if we’re not able to publish the readings via MQTT in case the broker disconnects.
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
Read DS18B20 Sensor
We created a function called read_sensor() that returns the current temperature from the DS18B20 sensor and handles any exceptions, in case we’re not able to get readings from the sensor.
def read_sensor():
try:
roms = ds_sensor.scan()
ds_sensor.convert_temp()
time.sleep_ms(750)
for rom in roms:
temp = ds_sensor.read_temp(rom)
# uncomment for Fahrenheit
temp = temp * (9/5) + 32.0
if (isinstance(temp, float) or (isinstance(temp, int))):
temp = (b'{0:3.1f},'.format(temp))
return temp
else:
return('Invalid sensor readings.')
except OSError as e:
return('Failed to read sensor.')
Learn more about getting readings from the DS18B20 temperature sensor: MicroPython: DS18B20 Temperature Sensor with ESP32 and ESP8266
Publishing MQTT Messages
In the while loop, we publish new temperature readings every 5 seconds.
First, check if it’s time to get new readings:
if (time.time() - last_message) > message_interval:
If it is, request a new temperature reading from the DS18B20 sensor by calling the read_sensor() function. The temperature is saved on the temp variable.
temp = read_sensor()
Finally, publish the temperature by using the publish() method on the client object. The publish() method accepts as arguments the topic and the message, as follows:
client.publish(topic_pub_temp, temp)
Finally, update the time when the last message was sent:
last_message = time.time()
In case the ESP32 or ESP8266 disconnects from the broker, and we’re not able to publish the readings, call the restart_and_reconnect() function to reset the ESP board and try to reconnect to the broker.
except OSError as e:
restart_and_reconnect()
After uploading the code, you should get new sensor readings on the shell every 5 seconds.
Now, go to the next section to prepare Node-RED to receive the readings the ESP is publishing.
Preparing Node-RED Dashboard
The ESP32 or 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 those topics and display the readings on gauges.
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 one MQTT in nodes, a gauge node and a chart node to the flow.
Click the MQTT node and edit its properties.
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. This previous MQTT node is subscribed to the esp/ds18b20/temperature topic.
Click on the gauge node and edit its properties.
Then, edit the chart node:
Wire your nodes as shown below:
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}]
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).
That’s it! You have your ESP32 or ESP8266 boards publishing DS18B20 temperature readings to Node-RED via MQTT using MicroPython.
Wrapping Up
MQTT is a great communication protocol to exchange small amounts of data between IoT devices. In this tutorial you’ve learned how to publish readings from a DS18B20 tempreature sensor with the ESP32 and ESP8266 using MicroPython to an MQTT topic. Then, you can use any device or home automation platform to subscribe to those topics and receive the readings.
Instead of a DS18B20 temperature sensor, you can use any other sensor like DHT11 or DHT22 sensor or BME280 sensor.
Learn more about MicroPython with our eBook: MicroPython Programming using ESP32/ESP8266.
Great article.
Are you sure your title is correct? I do not think there is a DS18B20